Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ccaf67076e | ||
|
|
8f7dd82e40 | ||
|
|
9989aa4de5 | ||
|
|
f983533d59 | ||
|
|
2182759d47 | ||
|
|
4d1851ddd2 | ||
|
|
0d82eca735 | ||
|
|
cfb6b271ee | ||
|
|
0b97964457 | ||
|
|
edfbfcf5db | ||
|
|
e5172432df | ||
|
|
741b04f120 | ||
|
|
83f2cc1344 | ||
|
|
152556d582 | ||
|
|
67fc31a008 | ||
|
|
23eace8350 | ||
|
|
93817e4840 | ||
|
|
bb97d982e4 | ||
|
|
700f58015d | ||
|
|
872ce3a825 | ||
|
|
385b31e7bb | ||
|
|
3d66a616ff | ||
|
|
b7e18a1214 | ||
|
|
3b0bae9c70 | ||
|
|
8b9343a320 | ||
|
|
8618c75459 | ||
|
|
711d2077e2 | ||
|
|
b25646b033 | ||
|
|
02bf7784b1 | ||
|
|
c164d60643 | ||
|
|
1bd4cfe73c | ||
|
|
f4e1eeb21c | ||
|
|
4b5fe62014 | ||
|
|
36c2be61ae | ||
|
|
e9206a9448 | ||
|
|
0bf28879c4 | ||
|
|
7c936712b9 | ||
|
|
e32a19fe3b | ||
|
|
c6382c6221 | ||
|
|
02280fbed9 | ||
|
|
d897eb205d | ||
|
|
b1f290ea32 | ||
|
|
0e36b6b7a0 | ||
|
|
d92f121cf4 | ||
|
|
0a73ba0f12 | ||
|
|
9e4e0efbab | ||
|
|
524dff07d2 | ||
|
|
8b3e5c08f7 | ||
|
|
c17444f5d6 | ||
|
|
df85ecdfff | ||
|
|
b8824141d6 | ||
|
|
aedd2ec3db | ||
|
|
5abad21082 | ||
|
|
1ae41c7ae5 | ||
|
|
e41671dbf9 | ||
|
|
eaeb9092e4 | ||
|
|
2f3ca0a006 | ||
|
|
1b65351be4 | ||
|
|
0422f6d51e | ||
|
|
8d050d4040 | ||
|
|
82b3a4b384 | ||
|
|
d2f391a881 | ||
|
|
9e778487d9 | ||
|
|
7938d71f2f | ||
|
|
422a6fed30 | ||
|
|
c6ea0454b3 | ||
|
|
467767a6c5 | ||
|
|
cf795c512a | ||
|
|
18b499030d | ||
|
|
d800d6f3ce | ||
|
|
185f706107 | ||
|
|
5a4661cdad | ||
|
|
7abdd94a0e | ||
|
|
22f0684ab0 | ||
|
|
80b2c63693 | ||
|
|
4b2a553bda | ||
|
|
ad30e73b10 | ||
|
|
15b62e302d | ||
|
|
9d5ec20f20 | ||
|
|
c878425fd0 | ||
|
|
90e80dda64 | ||
|
|
1db5bfeab5 | ||
|
|
b2b3fcd4a3 | ||
|
|
9cf97375c7 | ||
|
|
7839b6affb | ||
|
|
597064a07d | ||
|
|
0ea57d14c9 | ||
|
|
afd736d615 | ||
|
|
ce9b8c376f | ||
|
|
79776e6752 | ||
|
|
a2432022a1 | ||
|
|
ea5ee96bdc | ||
|
|
fe954092a4 | ||
|
|
5e148fec92 | ||
|
|
5daa2a9548 | ||
|
|
f1913f7b18 | ||
|
|
65a453553e | ||
|
|
29da8f24da | ||
|
|
3443ad9968 | ||
|
|
838dc93eff | ||
|
|
07ef68ec1f | ||
|
|
3cb7f86086 | ||
|
|
fc9565c157 | ||
|
|
557f6022f3 | ||
|
|
d0a56169e3 | ||
|
|
f7d6e2b4ed | ||
|
|
df82ee42fd | ||
|
|
a29d761483 | ||
|
|
713a86b9d6 | ||
|
|
d6250f16b0 | ||
|
|
1c5d5c3788 | ||
|
|
699e9d9ff1 | ||
|
|
fad0cb931a | ||
|
|
5d7ff55869 | ||
|
|
642ccb5b82 | ||
|
|
51a7ce0827 | ||
|
|
157a54b11d | ||
|
|
be083d81fc | ||
|
|
f6c869ad47 | ||
|
|
bef5b26509 | ||
|
|
59cfe24178 | ||
|
|
87d0d58ae8 | ||
|
|
de8b6c972d | ||
|
|
0ac4839e94 | ||
|
|
565bce6d8b | ||
|
|
b278b028cf | ||
|
|
33abd9369e | ||
|
|
e6b2f7f271 | ||
|
|
0bd1e9cf59 | ||
|
|
693625bf2c | ||
|
|
3a6c587569 | ||
|
|
bd85eaf0a0 | ||
|
|
29aa0f416e | ||
|
|
5b32607911 | ||
|
|
76e5359752 | ||
|
|
5ec4efbb6e | ||
|
|
f8bb7b421a | ||
|
|
887c169aa8 | ||
|
|
8c10dcc6c2 | ||
|
|
671da6b5fa | ||
|
|
7fdb2f4ea8 | ||
|
|
67388b31f5 | ||
|
|
2379cca765 | ||
|
|
34be6651e5 | ||
|
|
10f8e3e8ef | ||
|
|
0c6ea8eb5c | ||
|
|
6e69b06e61 | ||
|
|
98ba383a68 | ||
|
|
4e6d81a9bf | ||
|
|
0e2c206023 | ||
|
|
285f06d1e7 | ||
|
|
6aead03f3e | ||
|
|
7eb9e06452 | ||
|
|
fab06d5005 | ||
|
|
16860f93ad | ||
|
|
6ba45d5bc3 |
@@ -1,16 +0,0 @@
|
||||
# http://editorconfig.org
|
||||
root = true
|
||||
|
||||
[*]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
end_of_line = lf
|
||||
charset = utf-8
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
||||
|
||||
[*.md]
|
||||
trim_trailing_whitespace = false
|
||||
|
||||
[Makefile]
|
||||
indent_style = tab
|
||||
@@ -1,7 +1,10 @@
|
||||
src/**/*-test.js
|
||||
src/public
|
||||
src/routes/chart/ECharts/theme
|
||||
src/routes/chart/highCharts/mapdata
|
||||
src/locales/_build/
|
||||
src/locales/**/*.js
|
||||
docs/**/*.js
|
||||
node_modules
|
||||
dist
|
||||
.umi
|
||||
build
|
||||
public
|
||||
coverage
|
||||
*.config.js
|
||||
|
||||
# ignore umi generated files under src
|
||||
src/.umi
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"extends": "react-app",
|
||||
"rules": {
|
||||
"jsx-a11y/href-no-hash": "off",
|
||||
"no-console": "warn",
|
||||
"valid-jsdoc": "warn"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
module.exports = {
|
||||
root: true,
|
||||
parser: '@typescript-eslint/parser',
|
||||
parserOptions: {
|
||||
ecmaVersion: 2020,
|
||||
sourceType: 'module',
|
||||
ecmaFeatures: { jsx: true },
|
||||
},
|
||||
plugins: [
|
||||
'@typescript-eslint',
|
||||
'react',
|
||||
'react-hooks',
|
||||
'unused-imports',
|
||||
'prettier',
|
||||
'import',
|
||||
'jsx-a11y',
|
||||
],
|
||||
extends: [
|
||||
'eslint:recommended',
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
'plugin:react/recommended',
|
||||
'plugin:react-hooks/recommended',
|
||||
'plugin:prettier/recommended',
|
||||
],
|
||||
settings: {
|
||||
react: { version: 'detect' },
|
||||
'import/resolver': {
|
||||
typescript: {},
|
||||
},
|
||||
},
|
||||
env: {
|
||||
browser: true,
|
||||
node: true,
|
||||
es6: true,
|
||||
},
|
||||
rules: {
|
||||
'prettier/prettier': 'error',
|
||||
'react/react-in-jsx-scope': 'off',
|
||||
'@typescript-eslint/no-unused-vars': [
|
||||
'warn',
|
||||
{ argsIgnorePattern: '^_', varsIgnorePattern: '^_' },
|
||||
],
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
'unused-imports/no-unused-imports': 'warn',
|
||||
'no-console': [
|
||||
'warn',
|
||||
{
|
||||
allow: ['warn', 'error', 'info'],
|
||||
},
|
||||
],
|
||||
'import/order': 'off',
|
||||
},
|
||||
overrides: [
|
||||
{
|
||||
files: ['*.ts', '*.tsx'],
|
||||
rules: {
|
||||
'@typescript-eslint/explicit-module-boundary-types': 'off',
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -1,8 +0,0 @@
|
||||
> 请酌情提供细节,并保持issue精简便于查阅
|
||||
> 1. 功能需求 => 详细说明
|
||||
> 2. Bug反馈
|
||||
> 2.1 简单描述下报错
|
||||
> 2.2 你期望什么结果
|
||||
> 2.3 如何操作导致的
|
||||
> 2.4 可提供运行环境信息
|
||||
> 3. 代码求助 => 可以提,未必及时答复
|
||||
@@ -0,0 +1,76 @@
|
||||
++ name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [master]
|
||||
pull_request:
|
||||
branches: [master]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [18, 20]
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Enable corepack (pnpm)
|
||||
run: |
|
||||
corepack enable
|
||||
corepack prepare pnpm@latest --activate
|
||||
|
||||
- name: Cache pnpm store
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.pnpm-store
|
||||
~/.cache/pnpm
|
||||
key: ${{ runner.os }}-pnpm-${{ hashFiles('**/pnpm-lock.yaml') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-pnpm-
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Test (if present)
|
||||
run: pnpm test --if-present
|
||||
|
||||
- name: Lint
|
||||
run: pnpm run lint
|
||||
|
||||
- name: Build
|
||||
run: pnpm run build
|
||||
|
||||
- name: Upload build (artifact)
|
||||
if: success()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: dist
|
||||
path: ./dist
|
||||
|
||||
publish:
|
||||
name: Publish to GitHub Pages
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/master'
|
||||
steps:
|
||||
- name: Download artifact
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: dist
|
||||
|
||||
- name: Deploy to GitHub Pages
|
||||
uses: peaceiris/actions-gh-pages@v3
|
||||
with:
|
||||
publish_dir: ./dist
|
||||
publish_branch: gh-pages
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -1,23 +1,14 @@
|
||||
coverage
|
||||
dist
|
||||
node_modules
|
||||
npm-debug.log
|
||||
yarn-error.log
|
||||
/node_modules
|
||||
/.env.local
|
||||
/.umirc.local.ts
|
||||
/config/config.local.ts
|
||||
/src/.umi
|
||||
/src/.umi-production
|
||||
/src/.umi-test
|
||||
/dist
|
||||
.swc
|
||||
.turbopack
|
||||
|
||||
pnpm-lock.yaml
|
||||
yarn.lock
|
||||
package-lock.json
|
||||
|
||||
# ide
|
||||
.idea
|
||||
|
||||
# Mac General
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
|
||||
# umi
|
||||
.umi
|
||||
.umi-production
|
||||
|
||||
# jslingui
|
||||
src/locales/_build
|
||||
src/locales/**/*.js
|
||||
npm-lock.json
|
||||
@@ -1,6 +1,9 @@
|
||||
*.svg
|
||||
*.ejs
|
||||
.DS_Store
|
||||
node_modules
|
||||
dist
|
||||
.umi
|
||||
build
|
||||
coverage
|
||||
public
|
||||
node_modules
|
||||
.umi
|
||||
.umi-production
|
||||
src/locales/**/*.json
|
||||
@@ -1,5 +1,8 @@
|
||||
{
|
||||
"semi": false,
|
||||
"printWidth": 80,
|
||||
"singleQuote": true,
|
||||
"trailingComma": "es5"
|
||||
"trailingComma": "all",
|
||||
"proseWrap": "never",
|
||||
"overrides": [{ "files": ".prettierrc", "options": { "parser": "json" } }],
|
||||
"plugins": ["prettier-plugin-organize-imports", "prettier-plugin-packagejson"]
|
||||
}
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
{
|
||||
"extends": ["stylelint-config-standard", "stylelint-config-prettier"],
|
||||
"rules": {
|
||||
"declaration-empty-line-before": null,
|
||||
"no-descending-specificity": null,
|
||||
"selector-pseudo-class-no-unknown": null,
|
||||
"selector-pseudo-element-colon-notation": null
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
language: node_js
|
||||
node_js:
|
||||
- node
|
||||
script:
|
||||
- npm run build
|
||||
before_install:
|
||||
- |
|
||||
if [ "$TRAVIS_BRANCH" = "develop" ]; then
|
||||
for prefixed_envvar in ${!DEV_*}; do
|
||||
eval export ${prefixed_envvar#DEV_}="${!prefixed_envvar}"
|
||||
done
|
||||
elif [ "$TRAVIS_BRANCH" = "master" ]; then
|
||||
for prefixed_envvar in ${!PROD_*}; do
|
||||
eval export ${prefixed_envvar#PROD_}="${!prefixed_envvar}"
|
||||
done
|
||||
fi
|
||||
- openssl aes-256-cbc -K $encrypted_18b2305b78c9_key -iv $encrypted_18b2305b78c9_iv -in config/id_rsa.enc -out ~/.ssh/id_rsa -d
|
||||
- chmod 600 ~/.ssh/id_rsa
|
||||
- echo -e "Host $HOST\n\tStrictHostKeyChecking no\n" >> ~/.ssh/config
|
||||
- yarn global add now
|
||||
after_script:
|
||||
- scp -o stricthostkeychecking=no -r ./dist root@$HOST:$BUILD_DIR
|
||||
- cd ./docs && now -A $DOC_NOW_CONFIG -t $NOW_TOKEN && now alias -A $DOC_NOW_CONFIG -t $NOW_TOKEN
|
||||
@@ -1,102 +0,0 @@
|
||||
// https://umijs.org/config/
|
||||
import { resolve } from 'path'
|
||||
import { i18n } from './src/utils/config'
|
||||
|
||||
export default {
|
||||
ignoreMomentLocale: true,
|
||||
targets: { ie: 9 },
|
||||
plugins: [
|
||||
[
|
||||
// https://umijs.org/plugin/umi-plugin-react.html
|
||||
'umi-plugin-react',
|
||||
{
|
||||
dva: { immer: true },
|
||||
antd: true,
|
||||
dynamicImport: {
|
||||
webpackChunkName: true,
|
||||
loadingComponent: './components/Loader/Loader',
|
||||
},
|
||||
routes: {
|
||||
exclude: [
|
||||
/model\.(j|t)sx?$/,
|
||||
/service\.(j|t)sx?$/,
|
||||
/models\//,
|
||||
/components\//,
|
||||
/services\//,
|
||||
/chart\/Container\.js$/,
|
||||
/chart\/ECharts\/.+Component\.js$/,
|
||||
/chart\/ECharts\/.+ComPonent\.js$/,
|
||||
/chart\/ECharts\/theme\/.+\.js$/,
|
||||
/chart\/highCharts\/.+Component\.js$/,
|
||||
/chart\/highCharts\/mapdata\/.+\.js$/,
|
||||
/chart\/Recharts\/.+Component\.js$/,
|
||||
/chart\/Recharts\/Container\.js$/,
|
||||
],
|
||||
update: routes => {
|
||||
if (!i18n) return routes
|
||||
|
||||
const newRoutes = []
|
||||
for (const item of routes[0].routes) {
|
||||
newRoutes.push(item)
|
||||
if (item.path) {
|
||||
newRoutes.push(
|
||||
Object.assign({}, item, {
|
||||
path:
|
||||
`/:lang(${i18n.languages
|
||||
.map(item => item.key)
|
||||
.join('|')})` + item.path,
|
||||
})
|
||||
)
|
||||
}
|
||||
}
|
||||
routes[0].routes = newRoutes
|
||||
|
||||
return routes
|
||||
},
|
||||
},
|
||||
dll: {
|
||||
include: ['dva', 'dva/router', 'dva/saga', 'dva/fetch', 'antd/es'],
|
||||
},
|
||||
hardSource: /* isMac */ process.platform === 'darwin',
|
||||
pwa: {
|
||||
manifestOptions: {
|
||||
srcPath: 'manifest.json'
|
||||
},
|
||||
}
|
||||
},
|
||||
],
|
||||
],
|
||||
// Theme for antd
|
||||
// https://ant.design/docs/react/customize-theme
|
||||
theme: './config/theme.config.js',
|
||||
// Webpack Configuration
|
||||
proxy: {
|
||||
'/api/v1/weather': {
|
||||
target: 'https://api.seniverse.com/',
|
||||
changeOrigin: true,
|
||||
pathRewrite: { '^/api/v1/weather': '/v3/weather' },
|
||||
},
|
||||
},
|
||||
alias: {
|
||||
api: resolve(__dirname, './src/services/'),
|
||||
components: resolve(__dirname, './src/components'),
|
||||
config: resolve(__dirname, './src/utils/config'),
|
||||
models: resolve(__dirname, './src/models'),
|
||||
routes: resolve(__dirname, './src/routes'),
|
||||
services: resolve(__dirname, './src/services'),
|
||||
themes: resolve(__dirname, './src/themes'),
|
||||
utils: resolve(__dirname, './src/utils'),
|
||||
},
|
||||
extraBabelPresets: ['@lingui/babel-preset-react'],
|
||||
extraBabelPlugins: [
|
||||
[
|
||||
'import',
|
||||
{
|
||||
libraryName: 'lodash',
|
||||
libraryDirectory: '',
|
||||
camel2DashComponentName: false,
|
||||
},
|
||||
'lodash',
|
||||
],
|
||||
],
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { defineConfig } from 'umi';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: ['@umijs/plugins/dist/antd', '@umijs/plugins/dist/locale'],
|
||||
esbuildMinifyIIFE: true,
|
||||
locale: {
|
||||
antd: true,
|
||||
default: 'zh-CN',
|
||||
baseNavigator: true,
|
||||
useLocalStorage: true,
|
||||
baseSeparator: '-',
|
||||
title: true,
|
||||
},
|
||||
npmClient: 'pnpm',
|
||||
});
|
||||
@@ -1,87 +1,109 @@
|
||||
|
||||
<p align="center">
|
||||
<a href="http://github.com/zuiidea/antd-admin">
|
||||
<img alt="antd-admin" height="64" src="./docs/_media/logo.svg">
|
||||
</a>
|
||||
<a href="http://github.com/zuiidea/antd-admin" target="_blank">
|
||||
<img alt="antd-admin-logo" height="80" src="./public/logo.svg">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<h1 align="center">AntD Admin</h1>
|
||||
|
||||
<div align="center">
|
||||
|
||||
一套优秀的中后台前端解决方案
|
||||
|
||||
[](https://github.com/ant-design/ant-design)
|
||||
[](https://github.com/umijs/umi)
|
||||
[](https://github.com/zuiidea/antd-admin/issues)
|
||||
[](http://opensource.org/licenses/MIT)
|
||||

|
||||
[](https://github.com/zuiidea/antd-admin/pulls)
|
||||
[](https://gitter.im/antd-admin/antd-admin)
|
||||
基于 Ant Design 6、Umi 4 与 TypeScript 构建的企业级前端解决方案。
|
||||
|
||||
</div>
|
||||
|
||||
- 在线演示 - [https://antd-admin.zuiidea.com](https://antd-admin.zuiidea.com)
|
||||
- 使用文档 - [https://doc.antd-admin.zuiidea.com/#/zh-cn/](https://doc.antd-admin.zuiidea.com/#/zh-cn/)
|
||||
- 常见问题 - [https://doc.antd-admin.zuiidea.com/#/zh-cn/faq](https://doc.antd-admin.zuiidea.com/#/zh-cn/faq)
|
||||
- 更新日志 - [https://doc.antd-admin.zuiidea.com/#/zh-cn/change-log](https://doc.antd-admin.zuiidea.com/#/zh-cn/change-log)
|
||||
---
|
||||
|
||||
[English](./README.md) | 简体中文
|
||||
## 📖 项目简介
|
||||
|
||||
## 特性
|
||||
**AntD Admin** 是一个轻量、高性能的管理后台模板,旨在为构建企业级应用提供干净、可扩展的起点。项目使用 **Ant Design 6**、**Umi 4** 与 **TypeScript** 的最新特性,减轻样板代码,提升开发体验。
|
||||
|
||||
- 国际化,源码中抽离翻译字段,按需加载语言包
|
||||
- 动态权限,不同权限对应不同菜单
|
||||
- 优雅美观,Ant Design 设计体系
|
||||
- Mock 数据,本地数据调试
|
||||
无论您要构建仪表盘、管理系统,还是集成 AI 功能的工具,本项目都能提供必要的基础。
|
||||
|
||||
## ✨ 主要特性
|
||||
|
||||
## 使用
|
||||
- 🚀 **现代栈**:基于 **Ant Design 6** + **Umi 4** + **TypeScript**。
|
||||
- 🎨 **清晰架构**:使用 `zustand` 进行轻量状态管理。
|
||||
- 🛠 **良好的开发体验**:内置本地 mock 服务器(`mock/index.js`),无需后端即可开发前端功能。
|
||||
- 📦 **丰富示例页面**:包含可直接使用的页面示例:
|
||||
- 📊 **仪表盘**:数据可视化概览。
|
||||
- 👥 **用户管理**:CRUD 操作示例。
|
||||
- 🧩 **菜单管理**:动态路由配置示例。
|
||||
- 🤖 **AI 聊天示例**:大模型(LLM)接口集成示例。
|
||||
- ✅ **CI/CD 支持**:预配置的 GitHub Actions 工作流,用于 lint 和构建。
|
||||
|
||||
1. 下载项目代码。
|
||||
## 🚀 快速开始
|
||||
|
||||
建议使用 **pnpm** 进行包管理。
|
||||
|
||||
```bash
|
||||
git clone https://github.com/zuiidea/antd-admin.git my-project
|
||||
cd my-project
|
||||
# 1. 克隆仓库
|
||||
git clone https://github.com/zuiidea/antd-admin.git -b master --depth=1
|
||||
cd antd-admin
|
||||
|
||||
# 2. 安装依赖
|
||||
pnpm install
|
||||
|
||||
# 3. 启动本地开发(含 mock 数据)
|
||||
npm run dev
|
||||
|
||||
# 4. 构建生产包
|
||||
npm run build
|
||||
|
||||
# 5. 代码质量检查
|
||||
npm run lint
|
||||
npm run format
|
||||
```
|
||||
|
||||
2. 进入目录安装依赖,国内用户推荐使用 [cnpm](https://cnpmjs.org) 进行加速。
|
||||
🔌 开发说明
|
||||
|
||||
```bash
|
||||
yarn install
|
||||
```
|
||||
#### Mock 服务
|
||||
|
||||
或者
|
||||
项目包含位于 `mock/index.js` 的内置 mock 服务,方便在没有后端的情况下独立开发前端功能。
|
||||
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
如需关闭 mock 或切换到真实 API,请修改项目的代理配置(例如 Umi 项目可能的配置文件 `config/proxy.ts`、`.umirc.ts` 或 `config/config.ts`),以匹配您的实际项目结构。
|
||||
|
||||
3. 启动本地服务器。
|
||||
#### 常用路由
|
||||
|
||||
```bash
|
||||
npm run start
|
||||
```
|
||||
| 路由 | 说明 |
|
||||
| --- | --- |
|
||||
| `/` 或 `/dashboard` | 主仪表盘 |
|
||||
| `/users` | 用户列表与管理 |
|
||||
| `/sys/menu` | 系统菜单配置 |
|
||||
| `/ai/chat` | AI 聊天示例界面 |
|
||||
|
||||
4. 启动完成后打开浏览器访问 [http://localhost:7000](http://localhost:7000),如果需要更改启动端口,可在 `.env` 文件中配置。
|
||||
#### 定制化
|
||||
|
||||
- **API 集成:** 在 `src/services` 中更新 API 接口以对接真实后端。
|
||||
- **组件扩展:** 在 `src/components` 中复用或扩展现有组件(例如 `DropOption`、`StandardTable`)。
|
||||
- **主题:** 在主题配置中自定义 Ant Design 变量以匹配品牌视觉。
|
||||
|
||||
> 更多信息请参考 [使用文档](https://doc.antd-admin.zuiidea.com/#/zh-cn/)。
|
||||
#### GitHub Actions(CI)
|
||||
|
||||
仓库包含预配置的 GitHub Actions 工作流(见 `.github/workflows/ci.yml`),用于保证代码质量:
|
||||
|
||||
## 支持环境
|
||||
- 使用 `pnpm` 安装依赖。
|
||||
- 运行 lint 检查。
|
||||
- 构建生产包。
|
||||
|
||||
现代浏览器及 IE9。
|
||||
- **工作流位置:** `.github/workflows/ci.yml`
|
||||
- **提示:** 若要在 CI 中加入自动化测试,请在 `package.json` 中添加测试脚本并更新 workflow YAML。
|
||||
|
||||
| [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/edge/edge_48x48.png" alt="IE / Edge" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>IE / Edge | [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/firefox/firefox_48x48.png" alt="Firefox" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>Firefox | [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/chrome/chrome_48x48.png" alt="Chrome" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>Chrome | [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/safari/safari_48x48.png" alt="Safari" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>Safari | [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/opera/opera_48x48.png" alt="Opera" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>Opera |
|
||||
| --------- | --------- | --------- | --------- | --------- |
|
||||
| IE9, IE10, IE11, Edge| last 2 versions| last 2 versions| last 2 versions| last 2 versions
|
||||
## 🤝 贡献
|
||||
|
||||
## 参与贡献
|
||||
欢迎各类贡献:修复 bug、添加新示例页面或组件、完善类型定义与 lint 规则、改进国际化等。
|
||||
|
||||
我们非常欢迎你的贡献,你可以通过以下方式和我们一起共建 :smiley:
|
||||
- 在你的公司或个人项目中使用 AntD Admin。
|
||||
- 通过 [Issue](http://github.com/zuiidea/antd-admin/issues) 报告 bug 或进行咨询。
|
||||
- 提交 [Pull Request](http://github.com/zuiidea/antd-admin/pulls) 改进代码。
|
||||
常见贡献流程:
|
||||
|
||||
1. Fork 仓库。
|
||||
2. 新建分支:`git checkout -b feature/AmazingFeature`。
|
||||
3. 提交变更:`git commit -m 'Add some AmazingFeature'`。
|
||||
4. 推送分支:`git push origin feature/AmazingFeature`。
|
||||
5. 提交 Pull Request。
|
||||
|
||||
## 📄 许可证
|
||||
|
||||
本项目采用 MIT 许可证。
|
||||
|
||||
由 zuiidea 与贡献者共同维护,Made with ❤️。
|
||||
|
||||
> 强烈推荐阅读 [《提问的智慧》](https://github.com/ryanhanwu/How-To-Ask-Questions-The-Smart-Way)、[《如何向开源社区提问题》](https://github.com/seajs/seajs/issues/545) 和 [《如何有效地报告 Bug》](http://www.chiark.greenend.org.uk/%7Esgtatham/bugs-cn.html)、[《如何向开源项目提交无法解答的问题》](https://zhuanlan.zhihu.com/p/25795393),更好的问题更容易获得帮助。
|
||||
@@ -1,7 +1,6 @@
|
||||
|
||||
<p align="center">
|
||||
<a href="http://github.com/zuiidea/antd-admin">
|
||||
<img alt="antd-admin" height="64" src="./docs/_media/logo.svg">
|
||||
<a href="http://github.com/zuiidea/antd-admin" target="_blank">
|
||||
<img alt="antd-admin-logo" height="80" src="./public/logo.svg">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
@@ -9,78 +8,107 @@
|
||||
|
||||
<div align="center">
|
||||
|
||||
A excellent front-end solution for enterprise applications.
|
||||
An excellent enterprise-grade front-end solution built with Ant Design 6, Umi 4, and TypeScript.
|
||||
|
||||
[](https://github.com/ant-design/ant-design)
|
||||
[](https://github.com/umijs/umi)
|
||||
[](https://github.com/zuiidea/antd-admin/issues)
|
||||
[](http://opensource.org/licenses/MIT)
|
||||

|
||||
[](https://github.com/zuiidea/antd-admin/pulls)
|
||||
[](https://gitter.im/antd-admin/antd-admin)
|
||||
[](https://github.com/ant-design/ant-design)
|
||||
[](https://github.com/umijs/umi)
|
||||
[](https://www.typescriptlang.org/)
|
||||
[](https://github.com/zuiidea/antd-admin/issues)
|
||||
[](https://github.com/zuiidea/antd-admin/stargazers)
|
||||
[](http://opensource.org/licenses/MIT)
|
||||
[](https://github.com/zuiidea/antd-admin/pulls)
|
||||
|
||||
</div>
|
||||
|
||||
- Preview - [https://antd-admin.zuiidea.com](https://antd-admin.zuiidea.com)
|
||||
- Documentation - [https://doc.antd-admin.zuiidea.com](https://doc.antd-admin.zuiidea.com)
|
||||
- FAQ - [https://doc.antd-admin.zuiidea.com/#/faq](https://doc.antd-admin.zuiidea.com/#/faq)
|
||||
- ChangeLog - [https://doc.antd-admin.zuiidea.com/#/change-log](https://doc.antd-admin.zuiidea.com/#/change-log)
|
||||
---
|
||||
|
||||
English | [简体中文](./README-zh_CN.md)
|
||||
## 📖 Introduction
|
||||
|
||||
## Features
|
||||
**AntD Admin** is a lightweight, high-performance admin template designed to provide a clean and extensible starting point for building enterprise applications. It leverages the latest features of **Ant Design 6**, **Umi 4**, and **TypeScript**, offering a modern development experience with minimal boilerplate.
|
||||
|
||||
- Internationalization, extracting translation fields from source code, loading language packs on demand
|
||||
- Dynamic permissions, different permissions for different menus
|
||||
- Elegant and beautiful, Ant Design system
|
||||
- Mock data, local data debugging
|
||||
Whether you are building a dashboard, a management system, or an AI-powered tool, this project provides the essential foundation you need.
|
||||
|
||||
## ✨ Key Features
|
||||
|
||||
## Usage
|
||||
- 🚀 **Modern Stack**: Built on **Ant Design 6** + **Umi 4** + **TypeScript**.
|
||||
- 🎨 **Clean Architecture**: Lightweight state management using `zustand`.
|
||||
- 🛠 **Dev Experience**: Integrated local mock server (`mock/index.js`) for seamless frontend development without backend dependency.
|
||||
- 📦 **Rich Examples**: Includes ready-to-use pages:
|
||||
- 📊 **Dashboard**: Data visualization overview.
|
||||
- 👥 **User Management**: CRUD operations example.
|
||||
- 🧩 **Menu Management**: Dynamic routing configuration.
|
||||
- 🤖 **AI Chat Demo**: Integration example for LLM interfaces.
|
||||
- ✅ **CI/CD Ready**: Pre-configured GitHub Actions for linting and building.
|
||||
|
||||
1. Clone project code.
|
||||
## 🚀 Quick Start
|
||||
|
||||
We recommend using **pnpm** for package management.
|
||||
|
||||
```bash
|
||||
git clone https://github.com/zuiidea/antd-admin.git my-project
|
||||
cd my-project
|
||||
# 1. Clone the repository
|
||||
git clone https://github.com/zuiidea/antd-admin.git -b master --depth=1
|
||||
cd antd-admin
|
||||
|
||||
# 2. Install dependencies
|
||||
pnpm install
|
||||
|
||||
# 3. Start local development server (with mock data)
|
||||
npm run dev
|
||||
|
||||
# 4. Build for production
|
||||
npm run build
|
||||
|
||||
# 5. Code quality checks
|
||||
npm run lint
|
||||
npm run format
|
||||
```
|
||||
|
||||
2. Installation dependence.
|
||||
🔌 **Development Notes**
|
||||
|
||||
```bash
|
||||
yarn install
|
||||
```
|
||||
#### Mock Server
|
||||
|
||||
Or
|
||||
The project includes a built-in mock server defined in `mock/index.js`. This allows you to develop frontend features independently of the backend.
|
||||
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
To disable mocks or switch to a real API, modify the proxy settings in your configuration file (for example, `config/proxy.ts` or `.umirc.ts`).
|
||||
|
||||
3. Start local server.
|
||||
#### Common Routes
|
||||
|
||||
```bash
|
||||
npm run start
|
||||
```
|
||||
| Route | Description |
|
||||
| --- | --- |
|
||||
| `/` or `/dashboard` | Main Dashboard |
|
||||
| `/users` | User List & Management |
|
||||
| `/sys/menu` | System Menu Configuration |
|
||||
| `/ai/chat` | AI Chat Interface Demo |
|
||||
|
||||
4. After the startup is complete, open a browser and visit [http://localhost:7000](http://localhost:7000), If you need to change the startup port, you can configure it in the `.env` file.
|
||||
#### Customization
|
||||
|
||||
- **API Integration:** Update API endpoints in `src/services` to connect to your real backend.
|
||||
- **Component Extension:** Reuse or extend existing components in `src/components` (for example, `DropOption`, `StandardTable`).
|
||||
- **Theme:** Customize Ant Design tokens in the theme configuration to match your brand identity.
|
||||
|
||||
> More instructions at [documentation](https://doc.antd-admin.zuiidea.com)。
|
||||
#### GitHub Actions CI
|
||||
|
||||
This repository includes a pre-configured GitHub Actions workflow to ensure code quality:
|
||||
|
||||
## Browsers support
|
||||
- Installs dependencies using `pnpm`.
|
||||
- Runs linting checks.
|
||||
- Builds the project for production.
|
||||
|
||||
Modern browsers and IE9.
|
||||
|
||||
| [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/edge/edge_48x48.png" alt="IE / Edge" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>IE / Edge | [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/firefox/firefox_48x48.png" alt="Firefox" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>Firefox | [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/chrome/chrome_48x48.png" alt="Chrome" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>Chrome | [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/safari/safari_48x48.png" alt="Safari" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>Safari | [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/opera/opera_48x48.png" alt="Opera" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>Opera |
|
||||
| --------- | --------- | --------- | --------- | --------- |
|
||||
| IE9, IE10, IE11, Edge| last 2 versions| last 2 versions| last 2 versions| last 2 versions
|
||||
|
||||
## Contributing
|
||||
|
||||
We very much welcome your contribution, you can build together with us in the following ways :smiley:
|
||||
|
||||
- Use Ant Design Pro in your daily work.
|
||||
- Submit [GitHub issues](http://github.com/zuiidea/antd-admin/issues)s to report bugs or ask questions.
|
||||
- Propose [Pull Request](http://github.com/zuiidea/antd-admin/pulls) to improve our code.
|
||||
- **Workflow location:** `.github/workflows/ci.yml`
|
||||
- **Tip:** To add automated tests to the CI pipeline, add a test script to `package.json` and update the workflow YAML accordingly.
|
||||
🤝 Contributing
|
||||
Contributions are always welcome! Whether it's fixing a bug, adding a new feature, or improving documentation, please feel free to submit an Issue or a Pull Request.
|
||||
Typical contributions include:
|
||||
🐛 Bug fixes
|
||||
🧩 New example pages or components
|
||||
📝 Type definitions and linting improvements
|
||||
🌍 Internationalization (i18n) updates
|
||||
How to contribute:
|
||||
Fork the repository.
|
||||
Create your feature branch (git checkout -b feature/AmazingFeature).
|
||||
Commit your changes (git commit -m 'Add some AmazingFeature').
|
||||
Push to the branch (git push origin feature/AmazingFeature).
|
||||
Open a Pull Request.
|
||||
📄 License
|
||||
This project is licensed under the MIT License.
|
||||
Made with ❤️ by zuiidea and contributors.
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
### 开发环境
|
||||
|
||||
- OS:Windows
|
||||
- 编辑器:Atom
|
||||
- cmd:Cmder
|
||||
|
||||
### Atom 插件
|
||||
|
||||
- [atom-beautify](https://atom.io/packages/atom-beautify)
|
||||
|
||||
#### Less
|
||||
|
||||
- [x] Beautify On Save
|
||||
|
||||
#### Javascript
|
||||
|
||||
- [ ] Disable Beautifying Language
|
||||
|
||||
#### Markdown
|
||||
|
||||
- [x] Beautify On Save
|
||||
- [x] Default Beautifier:Remark
|
||||
|
||||
#### HTML
|
||||
|
||||
- [x] Beautify On Save
|
||||
|
||||
- [linter](https://atom.io/packages/linter)
|
||||
- [ ] Lint on Change
|
||||
- [linter-eslint](https://atom.io/packages/linter-eslint)
|
||||
- [x] Fix errors on save
|
||||
|
||||
### Cmder 主题
|
||||
|
||||
- [Panda-Theme-Cmder](https://github.com/HamidFaraji/Panda-Theme-Cmder)
|
||||
@@ -1,8 +0,0 @@
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
const lessToJs = require('less-vars-to-js')
|
||||
|
||||
module.exports = () => {
|
||||
const themePath = path.join(__dirname, '../src/themes/default.less')
|
||||
return lessToJs(fs.readFileSync(themePath, 'utf8'))
|
||||
}
|
||||
@@ -1,86 +1,36 @@
|
||||
# API configuration
|
||||
|
||||
## Why
|
||||
This project uses explicit per-feature service modules (TypeScript) under `src/services/` that call a shared HTTP helper `src/utils/request.ts` (exported as the default `api` function).
|
||||
|
||||
In the use of `redux` or `dva` projects, we often write functions like the following `service` layer to make the code structure clearer, but it is easy to see that we will write a lot of similar code in `antd -admin@5.0`, using the more concise configuration method to achieve the same function.
|
||||
Why this pattern?
|
||||
- Clear function boundaries per domain (users, admin, menu, dashboard).
|
||||
- Type-safe signatures in TypeScript for inputs/outputs (`src/types`).
|
||||
- Centralized request handling (query params, JSON body, auth header, unified response format) in `src/utils/request.ts`.
|
||||
|
||||
```javascript
|
||||
Export async function login(data) {
|
||||
Return request({
|
||||
Url: '/api/v1/user/login',
|
||||
Method: 'post',
|
||||
Data,
|
||||
})
|
||||
Example service (from `src/services/user.ts`):
|
||||
|
||||
```ts
|
||||
import type { PagedResponse, User } from '@/types/user';
|
||||
import api from '../utils/request';
|
||||
|
||||
export async function listUsers(
|
||||
params?: Record<string, string | number | boolean>,
|
||||
): Promise<PagedResponse<User>> {
|
||||
return api<PagedResponse<User>>('/users', { method: 'GET', params });
|
||||
}
|
||||
|
||||
export async function createUser(values: Record<string, unknown>): Promise<User> {
|
||||
return api('/user', { method: 'POST', body: values });
|
||||
}
|
||||
```
|
||||
|
||||
## Configuration and use
|
||||
Usage:
|
||||
- Import named functions from the service module: `import { listUsers } from '@/services/user'`.
|
||||
- The helper `api(path, options)` returns the parsed `data` payload from responses that follow the `{ success, message, data }` convention.
|
||||
|
||||
In the `src/services/api.js` file, you will see the following configuration object, the object's key is used to call the function name, the object's value is the requested `url`, the default request method is `GET`, The format of the value of the other request mode object is `'method url'`.
|
||||
Notes about `src/utils/request.ts`:
|
||||
- Combines `config.apiPrefix` with the provided `path`.
|
||||
- Supports `params` (query), `body` (JSON or FormData), and sets `Authorization` header from local storage when available.
|
||||
- Throws errors and shows UI messages for non-success responses.
|
||||
|
||||
```javascript
|
||||
Export default {
|
||||
...
|
||||
queryUser: '/user/:id',
|
||||
queryUserList: '/users',
|
||||
updateUser: 'Patch /user/:id',
|
||||
createUser: 'POST /user/:id',
|
||||
removeUser: 'DELETE /user/:id',
|
||||
removeUserList: 'POST /users/delete',
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
Used in other files
|
||||
|
||||
```javascript
|
||||
Import { queryUser } from 'api'
|
||||
|
||||
// in the general file
|
||||
...
|
||||
queryUser(option).then(data => console.log(data))
|
||||
...
|
||||
|
||||
/ / Model file
|
||||
...
|
||||
Yield call(queryUser, option)
|
||||
...
|
||||
```
|
||||
|
||||
## Method to realize
|
||||
|
||||
Refer to the `src/services/index.js` file to traverse the api configuration. Each property returns the corresponding encapsulated request function.
|
||||
|
||||
```javascript
|
||||
Import request from 'utils/request'
|
||||
Import { apiPrefix } from 'utils/config'
|
||||
|
||||
Import api from './api'
|
||||
|
||||
Const gen = params => {
|
||||
Let url = apiPrefix + params
|
||||
Let method = 'GET'
|
||||
|
||||
Const paramsArray = params.split(' ')
|
||||
If (paramsArray.length === 2) {
|
||||
Method = paramsArray[0]
|
||||
Url = apiPrefix + paramsArray[1]
|
||||
}
|
||||
|
||||
Return function(data) {
|
||||
Return request({
|
||||
Url,
|
||||
Data,
|
||||
Method,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Const APIFunction = {}
|
||||
For (const key in api) {
|
||||
APIFunction[key] = gen(api[key])
|
||||
}
|
||||
|
||||
Module.exports = APIFunction
|
||||
|
||||
```
|
||||
If you are migrating older code that used an API mapping, prefer creating small service modules with clear function names and types as shown above.
|
||||
@@ -8,76 +8,50 @@
|
||||
|
||||
<div align="center">
|
||||
|
||||
A excellent front-end solution for enterprise applications.
|
||||
An enterprise-grade front-end starter built with Ant Design 6, Umi 4 and TypeScript.
|
||||
|
||||
[](https://github.com/ant-design/ant-design)
|
||||
[](https://github.com/umijs/umi)
|
||||
[](https://github.com/zuiidea/antd-admin/issues)
|
||||
[](http://opensource.org/licenses/MIT)
|
||||

|
||||
[](https://github.com/zuiidea/antd-admin/pulls)
|
||||
[](https://gitter.im/antd-admin/antd-admin)
|
||||
[](https://github.com/ant-design/ant-design)
|
||||
[](https://github.com/umijs/umi)
|
||||
[](https://www.typescriptlang.org/)
|
||||
[](http://opensource.org/licenses/MIT)
|
||||
[](https://github.com/zuiidea/antd-admin/pulls)
|
||||
|
||||
</div>
|
||||
|
||||
- Preview - [https://antd-admin.zuiidea.com](https://antd-admin.zuiidea.com)
|
||||
- Documentation - [https://doc.antd-admin.zuiidea.com](https://doc.antd-admin.zuiidea.com)
|
||||
- FAQ - [https://doc.antd-admin.zuiidea.com/#/faq](https://doc.antd-admin.zuiidea.com/#/faq)
|
||||
- ChangeLog - [https://doc.antd-admin.zuiidea.com/#/change-log](https://doc.antd-admin.zuiidea.com/#/change-log)
|
||||
- Documentation source for this project is under `docs/`.
|
||||
|
||||
## Features
|
||||
## Quick start
|
||||
|
||||
- Internationalization, extracting translation fields from source code, loading language packs on demand
|
||||
- Dynamic permissions, different permissions for different menus
|
||||
- Elegant and beautiful, Ant Design system
|
||||
- Mock data, local data debugging
|
||||
|
||||
|
||||
## Usage
|
||||
|
||||
1. Clone project code.
|
||||
This repository uses `pnpm` in examples and CI; `npm` or `yarn` also work but `pnpm` is recommended.
|
||||
|
||||
```bash
|
||||
git clone https://github.com/zuiidea/antd-admin.git my-project
|
||||
cd my-project
|
||||
# clone
|
||||
git clone https://github.com/zuiidea/antd-admin.git
|
||||
cd antd-admin
|
||||
|
||||
# install
|
||||
pnpm install
|
||||
|
||||
# start dev server (includes local mock server)
|
||||
npm run dev
|
||||
|
||||
# build
|
||||
npm run build
|
||||
|
||||
# lint & format
|
||||
npm run lint
|
||||
npm run format
|
||||
```
|
||||
|
||||
2. Installation dependence.
|
||||
Notes:
|
||||
|
||||
```bash
|
||||
yarn install
|
||||
```
|
||||
- Mock data live in `mock/index.js` and the project can run without a backend during development.
|
||||
- CI workflow is available at `.github/workflows/ci.yml` (uses pnpm, lint, build).
|
||||
- Update API endpoints under `src/services` to integrate a real backend.
|
||||
|
||||
Or
|
||||
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
3. Start local server.
|
||||
|
||||
```bash
|
||||
npm run start
|
||||
```
|
||||
|
||||
4. After the startup is complete, open a browser and visit [http://localhost:7000](http://localhost:7000), If you need to change the startup port, you can configure it in the `.env` file.
|
||||
|
||||
|
||||
> More instructions at [documentation](https://doc.antd-admin.zuiidea.com)。
|
||||
|
||||
|
||||
## Browsers support
|
||||
|
||||
Modern browsers and IE9.
|
||||
|
||||
| [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/edge/edge_48x48.png" alt="IE / Edge" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>IE / Edge | [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/firefox/firefox_48x48.png" alt="Firefox" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>Firefox | [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/chrome/chrome_48x48.png" alt="Chrome" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>Chrome | [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/safari/safari_48x48.png" alt="Safari" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>Safari | [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/opera/opera_48x48.png" alt="Opera" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>Opera |
|
||||
| --------- | --------- | --------- | --------- | --------- |
|
||||
| IE9, IE10, IE11, Edge| last 2 versions| last 2 versions| last 2 versions| last 2 versions
|
||||
For detailed documentation see the other pages in this `docs/` folder.
|
||||
|
||||
## Contributing
|
||||
|
||||
We very much welcome your contribution, you can build together with us in the following ways :smiley:
|
||||
Contributions welcome — file issues or open a PR as usual on GitHub.
|
||||
|
||||
- Use Ant Design Pro in your daily work.
|
||||
- Submit [GitHub issues](http://github.com/zuiidea/antd-admin/issues)s to report bugs or ask questions.
|
||||
- Propose [Pull Request](http://github.com/zuiidea/antd-admin/pulls) to improve our code.
|
||||
|
||||
@@ -9,3 +9,4 @@
|
||||
- Guide
|
||||
- [Deploy](deploy.md)
|
||||
- [Change Log](change-log.md)
|
||||
- [FAQ](faq.md)
|
||||
|
||||
@@ -1,50 +1,26 @@
|
||||
## 5.0.0
|
||||
## 6.0.0
|
||||
|
||||
#### Optimization
|
||||
This project was modernized and migrated to a modern front-end stack. Key highlights of the current version:
|
||||
|
||||
- Try to use decorators to simplify code writing and improve code readability.
|
||||
### Modern stack
|
||||
- Upgraded to Ant Design 6, Umi 4 and TypeScript 5.
|
||||
- React has been updated to the current major line used in the repo (see `package.json`).
|
||||
|
||||
- API configurization to simplify the way data is obtained.
|
||||
### Architecture & DX
|
||||
- Services are implemented as TypeScript modules under `src/services/` and use a centralized HTTP helper `src/utils/request.ts`.
|
||||
- Lightweight local state management using `zustand` replacing older `dva` patterns.
|
||||
- Local mock server using `mock/index.js` with `mockjs` for frontend development without backend dependency.
|
||||
|
||||
- The files in `utils` are split and each has its own role.
|
||||
### Tooling & CI
|
||||
- Dev workflows use `pnpm` by default; scripts are defined in `package.json` (e.g. `pnpm run dev`, `pnpm run build`).
|
||||
- Tests use `jest` and related tooling; CI is implemented with GitHub Actions (`.github/workflows/ci.yml`) which installs via `pnpm`, lints and builds the project.
|
||||
|
||||
- Simplify the `utils/request` file without special handling.
|
||||
### Quality and types
|
||||
- TypeScript types are added/expanded under `src/types/` for safer APIs and components.
|
||||
- Prettier / ESLint configuration added to enforce code style.
|
||||
|
||||
#### Specification
|
||||
### Other
|
||||
- Documentation is maintained under `docs/` (this site) and updated to reflect the new stack and commands.
|
||||
- Removed old custom components that duplicate Ant Design functionality and simplified the codebase accordingly.
|
||||
|
||||
- Functions add comments, parameters, return values, etc., ambiguous code adds comments, canonical reference [Google JavaScript Style Guide](https://google.github.io/styleguide/jsguide.html#appendices-jsdoc-tag-reference).
|
||||
|
||||
- Semantic version number, specification participation [semantic version 2.0.0](https://semver.org/lang/zh-CN/).
|
||||
|
||||
- Static code checking, unified code style, will use `prettier`, `stylelint`, `eslint` specification code before code submission.
|
||||
|
||||
- Git submits information normalization, [git-commit-emoji-cn](https://github.com/liuchengxu/git-commit-emoji-cn).
|
||||
|
||||
- Based on the pre-defined routing of `Umi`, there is no need to write a routing configuration file.
|
||||
|
||||
- Use `React 16` new features such as `Fragment`, `Context`, `PureComponent`, etc.
|
||||
|
||||
#### Features
|
||||
|
||||
- Support internationalization, extract source fields from source code, load language packs on demand, and automatically translate online.
|
||||
|
||||
- Support for the introduction of `ant-design-pro` components, `lodash` functions on demand.
|
||||
|
||||
- Support multiple layouts, which rules can be used according to the rules.
|
||||
|
||||
- Support Antd Admin to automatically compile and deploy on Travis.
|
||||
|
||||
- Generate a documentation website using `Docsify`.
|
||||
|
||||
|
||||
#### Style
|
||||
|
||||
- Added Antd Admin standalone Logo.
|
||||
|
||||
- Rewrite the overall layout component, optimize the menu, automatic breadcrumb navigation, menu auto-expansion and other logic.
|
||||
|
||||
- The mobile menu is changed to drawer.
|
||||
|
||||
#### Other
|
||||
|
||||
- Discard components such as `IconFont`, `Search`, `DataTable` because they are well supported and replaceable in `Antd`.
|
||||
If you want a more detailed, commit-level changelog for each migration step, I can generate one from git history or help draft a migration guide.
|
||||
@@ -30,73 +30,4 @@ You can do some custom configuration in `/src/utils/config.js`:
|
||||
|
||||
- Type: `String`
|
||||
|
||||
Under the `Primary` layout, whether the top of the page is fixed when scrolling。
|
||||
|
||||
## layouts
|
||||
|
||||
- Type: `Array`
|
||||
|
||||
Configuration? Which routes use which layout, unspecified route uses the default layout `Public`, the project currently has `Primary` and `Public` layouts,
|
||||
The default configuration is as follows:
|
||||
|
||||
```javascript
|
||||
layouts: [
|
||||
{
|
||||
name: 'primary',
|
||||
include: [/.*/],
|
||||
exclude: [/(\/(en|zh))*\/login/],
|
||||
},
|
||||
],
|
||||
```
|
||||
|
||||
The object properties for each layout are as follows:
|
||||
|
||||
- `name` - The name of the layout;
|
||||
|
||||
- `include` - Specifies a list of routing rules that use this layout, which can be a regular expression or a string;
|
||||
|
||||
- `exclude` - Specifies a list of routing rules that do not use this layout, which can be a regular expression or a string.
|
||||
|
||||
> Note: `exclude` takes precedence over `include`, and the layout previous it has a higher priority than the behind layout. The development process may need to be combined with the layout in the `src/layouts` directory. For details, see [Using Layout](./layout.md).
|
||||
|
||||
## i18n
|
||||
|
||||
- Type: `Object`
|
||||
|
||||
Configure internationalization, the default configuration is as follows:
|
||||
|
||||
```javascript
|
||||
i18n: {
|
||||
languages: [
|
||||
{
|
||||
key: 'en',
|
||||
title: 'English',
|
||||
flag: '/america.svg',
|
||||
},
|
||||
{
|
||||
key: 'zh',
|
||||
title: '中文',
|
||||
flag: '/china.svg',
|
||||
},
|
||||
],
|
||||
defaultLanguage: 'en',
|
||||
}
|
||||
```
|
||||
|
||||
### i18n.languages
|
||||
|
||||
- Type: `Array`
|
||||
|
||||
Specify which languages the app supports, and the object properties for each language are as follows:
|
||||
|
||||
- `key` - The `key` of the language is applied to the page url to distinguish the language, and also corresponds to the language package folder name in the `src/locales` directory;
|
||||
|
||||
- `title` - The name of the language, at the bottom of the login page, at the top of the `Primary` layout, the language switch is displayed;
|
||||
|
||||
- `flag` - The path of the flag icon of the language, the language switching display at the top of the `Primary` layout.
|
||||
|
||||
### i18n.defaultLanguage
|
||||
|
||||
- Type: `String`
|
||||
|
||||
Configure the default language.
|
||||
Under the `Primary` layout, whether the top of the page is fixed when scrolling。
|
||||
@@ -0,0 +1,9 @@
|
||||
# FAQ
|
||||
|
||||
Most asked
|
||||
|
||||
## create new page
|
||||
|
||||
1. just copy a page in /src/pages (route here auto generated by [umi](https://umijs.org/guide/router.html#basic-routing))
|
||||
2. modify namespace/pathToRegexp in model.js
|
||||
3. modify mock route.js to add a route
|
||||
@@ -1,6 +1,6 @@
|
||||
# Quick Start
|
||||
|
||||
> Before delving into Ant Design React, a good knowledge base of [React](http://facebook.github.io/react/) 、 [ES2015+](http://es6.ruanyifeng.com/) 、 [Antd Design](https://ant.design/docs/react/introduce-cn) . Learn about [UmiJS](https://umijs.org/) , [Dva](http://github.com/dvajs/dva) . And properly installed and configured [Node.js](https://nodejs.org/) v8 or above, [Git](https://git-scm.com/). It would be helpful if you have pre-existing knowledge on those.
|
||||
> Before delving into Ant Design React, a good knowledge base of [React](http://facebook.github.io/react/) 、 [ES2015+](http://es6.ruanyifeng.com/) 、 [Antd Design](https://ant.design/docs/react/introduce-cn). Learn about [UmiJS](https://umijs.org/). Ensure you have [Node.js](https://nodejs.org/) (v18+ recommended) and [Git](https://git-scm.com/) installed.
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -52,22 +52,24 @@ The project layout is as follows:
|
||||
|
||||
## Development
|
||||
|
||||
1. Install Dependencies.
|
||||
1. Install dependencies (recommended: `pnpm`).
|
||||
|
||||
```bash
|
||||
yarn install
|
||||
pnpm install
|
||||
```
|
||||
|
||||
Or
|
||||
Or with other package managers:
|
||||
|
||||
```bash
|
||||
npm install
|
||||
# or
|
||||
yarn install
|
||||
```
|
||||
|
||||
2. Start local server.
|
||||
2. Start local development server.
|
||||
|
||||
```bash
|
||||
npm run start
|
||||
npm run dev
|
||||
```
|
||||
|
||||
3. After the startup is complete, open a browser and visit [http://localhost:7000](http://localhost:7000), If you need to change the startup port, you can configure it in the `.env` file.
|
||||
3. After startup, open the app in a browser (see dev server output for the actual URL/port).
|
||||
|
||||
@@ -1,75 +1,121 @@
|
||||
# globalization
|
||||
# Internationalization (i18n) Guide
|
||||
|
||||
## Add language
|
||||
This project uses Umi's `plugin-locale` (based on `react-intl`) to manage localization. Translation resources live in `src/locales` (for example `en-US.json`, `zh-CN.json`). Below are instructions for: adding a language, adding a translation entry, switching languages, and disabling i18n. Examples use Japanese `ja-JP`.
|
||||
|
||||
Take Japanese as an example.
|
||||
## 1. Add a new language (persistent)
|
||||
|
||||

|
||||
1. Create a new translation file under `src/locales/` with the language id as the file name, for example: `src/locales/ja-JP.json`.
|
||||
|
||||
1. Add a language pack local file, `ja` is the Japanese language code, and a list of languages that support translation [有道智云](http://ai.youdao.com/docs/doc-trans-api.s#p05), the `src/locales/ja/messages.json` file will be generated after running the following command.
|
||||
2. The file should contain a JSON object of translation keys and values (nesting allowed):
|
||||
|
||||
```bash
|
||||
npm run add-locale ja
|
||||
```
|
||||
```json
|
||||
{
|
||||
"welcome": "ようこそ",
|
||||
"login": {
|
||||
"username": "ユーザー名",
|
||||
"password": "パスワード",
|
||||
"submit": "ログイン"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
2. Extract the fields in the code that need to be translated, ie `<Trans>?message</Trans>`, `` i18n.t`message `` in the `message` field, run the following command after `src/locales/ja /messages.json` will appear after the extracted field configuration.
|
||||
3. If you want Ant Design components to use the same locale (dates, component text), add the AntD locale import and mapping in `src/app.tsx`'s `pick` function, e.g.:
|
||||
|
||||
```bash
|
||||
npm run extract
|
||||
```
|
||||
```ts
|
||||
import jaJP from 'antd/locale/ja_JP';
|
||||
// ...
|
||||
if (l === 'ja-JP') return jaJP;
|
||||
```
|
||||
|
||||
You will see the following information:
|
||||
4. Add the language to the language selector (for example in `src/components/TopbarControls.tsx`):
|
||||
|
||||
```bash
|
||||
Catalog statistics:
|
||||
┌─────────────┬─────────────┬─────────┐
|
||||
│ Language │ Total count │ Missing │
|
||||
├─────────────┼─────────────┼─────────┤
|
||||
│ en (source) │ 52 │ - │
|
||||
│ ja │ 52 │ 52 │
|
||||
│ zh │ 52 │ 0 │
|
||||
└─────────────┴─────────────┴─────────┘
|
||||
```
|
||||
```ts
|
||||
{ key: 'ja-JP', label: '日本語' }
|
||||
```
|
||||
|
||||
3. At the same time, we have added the relevant configuration in `src/utils/config.js`.
|
||||
5. Restart the dev server:
|
||||
|
||||
```javascript
|
||||
{
|
||||
...
|
||||
i18n: {
|
||||
languages: [
|
||||
...
|
||||
{
|
||||
key:'ja',
|
||||
title: '日本語',
|
||||
flag: '/japanese.svg',
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
```
|
||||
```bash
|
||||
pnpm run dev
|
||||
```
|
||||
|
||||
> Routing related effects, after the configuration `npm run start` takes effect after restart.
|
||||
Umi collects files in `src/locales` into `localeInfo` at build/dev time so the new language becomes available. If you prefer not to restart, see the runtime registration option below.
|
||||
|
||||
4. Use the built-in commands for automatic translation. You will see the translated configuration in `src/locales/ja/messages.json`.
|
||||
## 2. Add a translation entry
|
||||
|
||||
```bash
|
||||
npm run trans:only
|
||||
```
|
||||
1. Add the same key to each language JSON (keep `en-US.json` and `zh-CN.json` up to date alongside the new language):
|
||||
|
||||
You will see the following information:
|
||||
`src/locales/en-US.json`
|
||||
|
||||
```bash
|
||||
start: en -> ja
|
||||
...
|
||||
youdao: en -> ja: Unpublished -> 未発表
|
||||
youdao: en -> ja: Update -> 更新
|
||||
youdao: en -> ja: Update User -> ユーザーの更新
|
||||
youdao: en -> ja: Username -> 名
|
||||
...
|
||||
All translations have been completed.
|
||||
```
|
||||
```json
|
||||
"my.feature.greeting": "Hello from feature"
|
||||
```
|
||||
|
||||
> `npm run trans` will execute `npm run extract` and `npm run trans:only` in order.
|
||||
`src/locales/zh-CN.json`
|
||||
|
||||
5. Finally, you can adjust the inaccurate fields in `src/locales/ja/messages.json`. Start the development mode `npm run start`, open [http://localhost:7000/ja/login](http://localhost:7000/ja/login) and you will see the Japanese version of the app.
|
||||
```json
|
||||
"my.feature.greeting": "来自功能的问候"
|
||||
```
|
||||
|
||||
2. In a component use `useIntl()` and `formatMessage`:
|
||||
|
||||
```ts
|
||||
import { useIntl } from 'umi';
|
||||
const intl = useIntl();
|
||||
const text = intl.formatMessage({ id: 'my.feature.greeting', defaultMessage: 'Hello' });
|
||||
```
|
||||
|
||||
Use `useIntl()` (or `injectIntl`) so the component updates automatically when the locale changes.
|
||||
|
||||
## 3. Runtime switching and registering
|
||||
|
||||
- Switch locale (writes `umi_locale` to localStorage and either reloads or triggers an update):
|
||||
|
||||
```ts
|
||||
import { setLocale } from 'umi';
|
||||
// switch and reload
|
||||
setLocale('ja-JP', true);
|
||||
// switch without reload (emit update event)
|
||||
setLocale('zh-CN', false);
|
||||
```
|
||||
|
||||
- Register a locale at runtime (no server restart required):
|
||||
|
||||
```ts
|
||||
import { addLocale, setLocale } from 'umi';
|
||||
import jaMessages from '@/locales/ja-JP.json';
|
||||
import jaAntd from 'antd/locale/ja_JP';
|
||||
|
||||
addLocale('ja-JP', jaMessages, { antd: jaAntd, momentLocale: 'ja' });
|
||||
setLocale('ja-JP', false);
|
||||
```
|
||||
|
||||
`addLocale` merges messages into the internal `localeInfo`. You can pass extra data (like AntD locale and moment locale) so components using AntD/moment behave correctly.
|
||||
|
||||
## 4. Disable i18n (turn off multi-language)
|
||||
|
||||
To permanently disable multi-language support:
|
||||
|
||||
1. In `src/app.tsx`'s `LocaleWrapper`, return a fixed AntD locale (ignore `localStorage` `umi_locale`):
|
||||
|
||||
```ts
|
||||
const pick = (l: string | null) => {
|
||||
return zhCN; // force Chinese
|
||||
};
|
||||
```
|
||||
|
||||
2. Remove or hide the language switcher (for example, remove language menu items in `src/components/TopbarControls.tsx`).
|
||||
|
||||
3. Optionally remove other JSON files in `src/locales` except the single target language to reduce build size.
|
||||
|
||||
If you only want to temporarily prevent user switching, hide the switcher (step 2) and keep files intact for easy re-enable.
|
||||
|
||||
## 5. Debugging & common issues
|
||||
|
||||
- New language not appearing: restart dev server or use `addLocale`; ensure AntD locale mapping exists in `app.tsx`.
|
||||
- Missing translations: check all `src/locales/*.json` contain the key, and the `formatMessage` id is correct.
|
||||
- Want automated extraction of message ids: this repo does not include extraction scripts; consider integrating `lingui`, `babel-plugin-react-intl`, or other tooling and adding scripts to `package.json`.
|
||||
|
||||
If you want, I can:
|
||||
- create an initial `src/locales/ja-JP.json` and update `TopbarControls`/`app.tsx` mappings; or
|
||||
- add a small example component that demonstrates runtime registration using `addLocale`. Tell me which one you prefer.
|
||||
|
||||
@@ -2,59 +2,59 @@
|
||||
|
||||
## Add a new layout
|
||||
|
||||
Take a new layout named `secondary` as an example to make the route starting with `seconday` use this layout.
|
||||
Take a new layout named `secondary` as an example to make the route starting with `secondary` use this layout.
|
||||
|
||||
1. Add related configuration in `src/utils/config.js`. For details, please refer to [layouts](/configuration?id=layouts).
|
||||
|
||||
```javascript
|
||||
```javascript
|
||||
layouts: [
|
||||
{
|
||||
name: 'primary',
|
||||
include: [/.*/],
|
||||
exlude: [/(\/(en|zh))*\/login/, /(\/(en|zh))*\/seconday\/(.*)/],
|
||||
exclude: [/(\/(en|zh))*\/login/, /(\/(en|zh))*\/secondary\/(.*)/],
|
||||
},
|
||||
{
|
||||
name: 'secondary',
|
||||
include: [/(\/(en|zh))*\/seconday\/(.*)/],
|
||||
include: [/(\/(en|zh))*\/secondary\/(.*)/],
|
||||
},
|
||||
],
|
||||
```
|
||||
```
|
||||
|
||||
2. Add the `secondary` layout component to the `src/layouts/BaseLayout.js` file.
|
||||
|
||||
```javascript
|
||||
```javascript
|
||||
import SecondaryLayout from './SecondaryLayout'
|
||||
|
||||
const LayoutMap = {
|
||||
Primary: PrimaryLayout,
|
||||
Public: PublicLayout,
|
||||
Secondary: SecondaryLayout,
|
||||
primary: PrimaryLayout,
|
||||
public: PublicLayout,
|
||||
secondary: SecondaryLayout,
|
||||
}
|
||||
```
|
||||
```
|
||||
|
||||
3. Add the `SecondaryLayout.js` file to the `src/layouts/` directory.
|
||||
|
||||
```javascript
|
||||
```javascript
|
||||
import React from 'react'
|
||||
|
||||
export default ({ children }) => {
|
||||
Return (
|
||||
return (
|
||||
<div>
|
||||
<h1>Seconday</h1>
|
||||
<h1>Secondary</h1>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
```
|
||||
|
||||
4. Add a `seconday/index.js` file to the `src/pages/` directory.
|
||||
4. Add a `secondary/index.js` file to the `src/pages/` directory.
|
||||
|
||||
```javascript
|
||||
```javascript
|
||||
import React from 'react'
|
||||
|
||||
export default ({ children }) => {
|
||||
Return <div>Seconday page Content</div>
|
||||
Return <div>Secondary page Content</div>
|
||||
}
|
||||
```
|
||||
```
|
||||
|
||||
5. Finally, start the development mode `npm run start`, open [http://localhost:7000/seconday/](http://localhost:7000/seconday/) and you will see the page for the `seconday` layout.
|
||||
5. Finally, start the development mode with `npm run dev`, then open the layout page in your browser (see dev server output for the actual URL), e.g. `/secondary/`.
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"name": "antd-admin-devdoc",
|
||||
"alias": ["devdoc-antd-admin.now.sh", "devdoc.antd-admin.zuiidea.com"],
|
||||
"type": "static",
|
||||
"public": true
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"name": "antd-admin-doc",
|
||||
"alias": ["doc-antd-admin.now.sh", "doc.antd-admin.zuiidea.com"],
|
||||
"type": "static",
|
||||
"public": true
|
||||
}
|
||||
@@ -1,22 +1,33 @@
|
||||
# HTTP request
|
||||
# HTTP requests
|
||||
|
||||
this project use axios for http service, file located in src/utils/request.js
|
||||
This project uses a small fetch-based HTTP helper implemented at `src/utils/request.ts` (export default `api`). The helper centralizes:
|
||||
|
||||
## Custom Header
|
||||
- Prefixing paths with `config.apiPrefix`.
|
||||
- Handling `params` (query string) and `body` (JSON or FormData).
|
||||
- Injecting an `Authorization` header from local storage when available.
|
||||
- Unified response parsing and error handling (expects backend responses in the form `{ success, message, data }`).
|
||||
|
||||
As for privilege access or modify cookie, you could add header param by yourself
|
||||
Key behaviors
|
||||
|
||||
```
|
||||
axios.defaults.headers.common['Authorization'] = 'token'
|
||||
- `api(path, options)` merges `config.apiPrefix` + `path` to build the URL.
|
||||
- If `options.params` is provided it's serialized and appended as query string.
|
||||
- `options.body` handling:
|
||||
- FormData is sent as-is (do not set Content-Type manually).
|
||||
- Strings and Blobs are sent directly.
|
||||
- Plain objects are JSON.stringified and Content-Type defaults to `application/json`.
|
||||
- If a token exists in local storage (key `app-auth-token`), the helper injects an `Authorization: Bearer <token>` header unless one is already provided.
|
||||
- Responses are expected to be JSON with `{ success: boolean, message?: string, data: T }`. Non-success responses throw an Error and show a UI message (uses `antd`'s `message`).
|
||||
|
||||
Usage (TypeScript-friendly):
|
||||
|
||||
```ts
|
||||
import api from '@/utils/request';
|
||||
|
||||
// GET with query params
|
||||
const page = await api('/users', { method: 'GET', params: { page: 1, pageSize: 10 } });
|
||||
|
||||
// POST with JSON body
|
||||
const created = await api('/user', { method: 'POST', body: { name: 'Alice' } });
|
||||
```
|
||||
|
||||
Or
|
||||
|
||||
```
|
||||
axios.interceptors.request.use(function (config) {
|
||||
config.headers.token = window.localStorage.getItem('token');
|
||||
return config;
|
||||
}, function (error) {
|
||||
return Promise.reject(error);
|
||||
});
|
||||
```
|
||||
The helper returns the `data` field from successful responses. Check `src/utils/request.ts` for exact typings and behavior.
|
||||
@@ -1,86 +1,35 @@
|
||||
# 接口配置
|
||||
|
||||
## 为什么
|
||||
本项目使用基于 TypeScript 的按功能分割服务模块,位于 `src/services/`,所有服务通过共享的 HTTP 封装 `src/utils/request.ts`(默认导出为 `api` 函数)发起请求。
|
||||
|
||||
在使用了`redux`或者`dva`项目中,我们经常会写类似下面的`service`层的函数,使代码结构更清晰,但是很容易看出,我们会写很多相似的代码,在`antd-admin@5.0`中,使用了更加简洁的配置方式实现了相同的功能。
|
||||
为什么采用此模式?
|
||||
- 每个领域(user/admin/menu/dashboard)有独立函数,职责清晰。
|
||||
- 使用 TypeScript 提供输入/输出类型定义,便于维护(参见 `src/types`)。
|
||||
- 请求处理集中化(查询参数、JSON body、鉴权 header、统一响应格式等)在 `src/utils/request.ts`。
|
||||
|
||||
```javascript
|
||||
export async function login(data) {
|
||||
return request({
|
||||
url: '/api/v1/user/login',
|
||||
method: 'post',
|
||||
data,
|
||||
})
|
||||
示例(来自 `src/services/user.ts`):
|
||||
|
||||
```ts
|
||||
import type { PagedResponse, User } from '@/types/user';
|
||||
import api from '../utils/request';
|
||||
|
||||
export async function listUsers(
|
||||
params?: Record<string, string | number | boolean>,
|
||||
): Promise<PagedResponse<User>> {
|
||||
return api<PagedResponse<User>>('/users', { method: 'GET', params });
|
||||
}
|
||||
|
||||
export async function createUser(values: Record<string, unknown>): Promise<User> {
|
||||
return api('/user', { method: 'POST', body: values });
|
||||
}
|
||||
```
|
||||
|
||||
## 配置和使用
|
||||
使用方式:
|
||||
- 通过 `import { listUsers } from '@/services/user'` 导入命名函数。
|
||||
- `api(path, options)` 返回后端约定格式 `{ success, message, data }` 中的 `data` 字段。
|
||||
|
||||
在`src/services/api.js`文件中,你会看到如下配置对象,对象的键用于调用时的函数名称,对象的值为请求的`url`,默认请求方式为`GET`,如果是其他请求方式对象的值的格式则为`'method url'`。
|
||||
关于 `src/utils/request.ts`:
|
||||
- 会将 `config.apiPrefix` 与 `path` 拼接;支持 `params`(查询)、`body`(JSON 或 FormData);若存在本地 token 则自动注入 `Authorization`。
|
||||
- 对非成功响应会抛出异常并在界面上显示消息(使用 `antd` 的 `message`)。
|
||||
|
||||
```javascript
|
||||
export default {
|
||||
...
|
||||
queryUser: '/user/:id',
|
||||
queryUserList: '/users',
|
||||
updateUser: 'Patch /user/:id',
|
||||
createUser: 'POST /user/:id',
|
||||
removeUser: 'DELETE /user/:id',
|
||||
removeUserList: 'POST /users/delete',
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
在其他文件中使用
|
||||
|
||||
```javascript
|
||||
import { queryUser } from 'api'
|
||||
|
||||
// 一般文件中
|
||||
...
|
||||
queryUser(option).then(data => console.log(data))
|
||||
...
|
||||
|
||||
// model文件中
|
||||
...
|
||||
yield call(queryUser, option)
|
||||
...
|
||||
```
|
||||
|
||||
## 实现方式
|
||||
|
||||
参考`src/services/index.js`文件,对api配置进行遍历,每个属性都返回对应的封装后的request函数。
|
||||
|
||||
```javascript
|
||||
import request from 'utils/request'
|
||||
import { apiPrefix } from 'utils/config'
|
||||
|
||||
import api from './api'
|
||||
|
||||
const gen = params => {
|
||||
let url = apiPrefix + params
|
||||
let method = 'GET'
|
||||
|
||||
const paramsArray = params.split(' ')
|
||||
if (paramsArray.length === 2) {
|
||||
method = paramsArray[0]
|
||||
url = apiPrefix + paramsArray[1]
|
||||
}
|
||||
|
||||
return function(data) {
|
||||
return request({
|
||||
url,
|
||||
data,
|
||||
method,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const APIFunction = {}
|
||||
for (const key in api) {
|
||||
APIFunction[key] = gen(api[key])
|
||||
}
|
||||
|
||||
module.exports = APIFunction
|
||||
|
||||
```
|
||||
如果你在迁移旧的 API 映射实现,建议按当前结构将功能拆分为小型服务模块并补充类型定义。
|
||||
@@ -8,77 +8,46 @@
|
||||
|
||||
<div align="center">
|
||||
|
||||
一套优秀的中后台前端解决方案
|
||||
基于 Ant Design 6、Umi 4 与 TypeScript 的企业级前端起手模版。
|
||||
|
||||
[](https://github.com/ant-design/ant-design)
|
||||
[](https://github.com/umijs/umi)
|
||||
[](https://github.com/zuiidea/antd-admin/issues)
|
||||
[](http://opensource.org/licenses/MIT)
|
||||

|
||||
[](https://github.com/zuiidea/antd-admin/pulls)
|
||||
[](https://gitter.im/antd-admin/antd-admin)
|
||||
[](https://github.com/ant-design/ant-design)
|
||||
[](https://github.com/umijs/umi)
|
||||
|
||||
</div>
|
||||
|
||||
- 在线演示 - [https://antd-admin.zuiidea.com](https://antd-admin.zuiidea.com)
|
||||
- 使用文档 - [https://doc.antd-admin.zuiidea.com/#/zh-cn/](https://doc.antd-admin.zuiidea.com/#/zh-cn/)
|
||||
- 常见问题 - [https://doc.antd-admin.zuiidea.com/#/zh-cn/faq](https://doc.antd-admin.zuiidea.com/#/zh-cn/faq)
|
||||
- 更新日志 - [https://doc.antd-admin.zuiidea.com/#/zh-cn/change-log](https://doc.antd-admin.zuiidea.com/#/zh-cn/change-log)
|
||||
- 文档源文件位于 `docs/` 目录。
|
||||
|
||||
## 特性
|
||||
## 快速开始
|
||||
|
||||
- 国际化,源码中抽离翻译字段,按需加载语言包
|
||||
- 动态权限,不同权限对应不同菜单
|
||||
- 优雅美观,Ant Design 设计体系
|
||||
- Mock 数据,本地数据调试
|
||||
|
||||
|
||||
## 使用
|
||||
|
||||
1. 下载项目代码。
|
||||
本仓库示例与 CI 使用 `pnpm`,你也可以使用 `npm` 或 `yarn`,但推荐 `pnpm`。
|
||||
|
||||
```bash
|
||||
git clone https://github.com/zuiidea/antd-admin.git my-project
|
||||
cd my-project
|
||||
# 克隆
|
||||
git clone https://github.com/zuiidea/antd-admin.git
|
||||
cd antd-admin
|
||||
|
||||
# 安装依赖
|
||||
pnpm install
|
||||
|
||||
# 启动开发(含本地 mock)
|
||||
npm run dev
|
||||
|
||||
# 构建
|
||||
npm run build
|
||||
|
||||
# lint 与格式化
|
||||
npm run lint
|
||||
npm run format
|
||||
```
|
||||
|
||||
2. 进入目录安装依赖,国内用户推荐使用 [cnpm](https://cnpmjs.org) 进行加速。
|
||||
说明:
|
||||
|
||||
```bash
|
||||
yarn install
|
||||
```
|
||||
- 本地 mock 实现在 `mock/index.js`,便于在无后端时开发。
|
||||
- CI 工作流位于 `.github/workflows/ci.yml`(使用 pnpm、lint、build)。
|
||||
- 若需对接真实后端,请修改 `src/services` 下的 API。
|
||||
|
||||
或者
|
||||
更多详细文档请查看 `docs/` 目录下的其他页面。
|
||||
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
## 参与贡献
|
||||
|
||||
3. 启动本地服务器。
|
||||
|
||||
```bash
|
||||
npm run start
|
||||
```
|
||||
|
||||
4. 启动完成后打开浏览器访问 [http://localhost:7000](http://localhost:7000),如果需要更改启动端口,可在 `.env` 文件中配置。
|
||||
|
||||
|
||||
> 更多信息请参考 [使用文档](https://doc.antd-admin.zuiidea.com/#/zh-cn/)。
|
||||
|
||||
|
||||
## 支持环境
|
||||
|
||||
现代浏览器及 IE9。
|
||||
|
||||
| [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/edge/edge_48x48.png" alt="IE / Edge" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>IE / Edge | [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/firefox/firefox_48x48.png" alt="Firefox" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>Firefox | [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/chrome/chrome_48x48.png" alt="Chrome" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>Chrome | [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/safari/safari_48x48.png" alt="Safari" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>Safari | [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/opera/opera_48x48.png" alt="Opera" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>Opera |
|
||||
| --------- | --------- | --------- | --------- | --------- |
|
||||
| IE9, IE10, IE11, Edge| last 2 versions| last 2 versions| last 2 versions| last 2 versions
|
||||
|
||||
## 参与贡献
|
||||
|
||||
我们非常欢迎你的贡献,你可以通过以下方式和我们一起共建 :smiley:
|
||||
- 在你的公司或个人项目中使用 AntD Admin。
|
||||
- 通过 [Issue](http://github.com/zuiidea/antd-admin/issues) 报告 bug 或进行咨询。
|
||||
- 提交 [Pull Request](http://github.com/zuiidea/antd-admin/pulls) 改进代码。
|
||||
|
||||
> 强烈推荐阅读 [《提问的智慧》](https://github.com/ryanhanwu/How-To-Ask-Questions-The-Smart-Way)、[《如何向开源社区提问题》](https://github.com/seajs/seajs/issues/545) 和 [《如何有效地报告 Bug》](http://www.chiark.greenend.org.uk/%7Esgtatham/bugs-cn.html)、[《如何向开源项目提交无法解答的问题》](https://zhuanlan.zhihu.com/p/25795393),更好的问题更容易获得帮助。
|
||||
欢迎提交 Issue 或 PR 改进项目文档或代码。
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
|
||||
- 支持国际化,源码中抽离翻译字段,按需加载语言包,自动在线翻译。
|
||||
|
||||
- 支持按需引入 `ant-design-pro` 组件、`lodash` 函数。
|
||||
- 支持按需引入 `lodash` 函数。
|
||||
|
||||
- 支持多布局,可根据规则规定哪些路由使用哪种布局。
|
||||
|
||||
|
||||
@@ -30,73 +30,4 @@
|
||||
|
||||
- 类型: `String`
|
||||
|
||||
在`Primary`布局下,页面滚动时是否固定顶部。
|
||||
|
||||
## layouts
|
||||
|
||||
- 类型: `Array`
|
||||
|
||||
配置哪些路由使用哪种布局,未指定路由使用默认布局 `Public`,项目中目前有 `Primary` 和 `Public` 两种布局,
|
||||
默认配置如下:
|
||||
|
||||
```javascript
|
||||
layouts: [
|
||||
{
|
||||
name: 'primary',
|
||||
include: [/.*/],
|
||||
exlude: [/(\/(en|zh))*\/login/],
|
||||
},
|
||||
],
|
||||
```
|
||||
|
||||
每种布局的对象属性如下:
|
||||
|
||||
- `name` - 布局的名称;
|
||||
|
||||
- `include` - 指定使用该布局的路由规则列表,规则可为正则表达式或者字符串;
|
||||
|
||||
- `exlude` - 指定不使用该布局的路由规则列表,规则可为正则表达式或者字符串。
|
||||
|
||||
> 注意:`exlude` 优先级高于 `include`,前面的布局优先级高于后面的布局。开发过程中可能需要结合`src/layouts`目录下的布局使用,具体方法可查看 [使用布局](./layout.md)。
|
||||
|
||||
## i18n
|
||||
|
||||
- 类型: `Object`
|
||||
|
||||
配置国际化,默认配置如下:
|
||||
|
||||
```javascript
|
||||
i18n: {
|
||||
languages: [
|
||||
{
|
||||
key: 'en',
|
||||
title: 'English',
|
||||
flag: '/america.svg',
|
||||
},
|
||||
{
|
||||
key: 'zh',
|
||||
title: '中文',
|
||||
flag: '/china.svg',
|
||||
},
|
||||
],
|
||||
defaultLanguage: 'en',
|
||||
}
|
||||
```
|
||||
|
||||
### i18n.languages
|
||||
|
||||
- 类型: `Array`
|
||||
|
||||
指定应用支持哪些语言,每种语言的对象属性如下:
|
||||
|
||||
- `key` - 语言的`key`,应用到页面 url 上以区分语言,也对应 `src/locales` 目录下的语言包文件夹名;
|
||||
|
||||
- `title` - 语言名称,在登录页底部、`Primay` 布局顶部语言切换显示;
|
||||
|
||||
- `flag` - 语言的国旗图标的路径,在 `Primay` 布局顶部语言切换显示。
|
||||
|
||||
### i18n.defaultLanguage
|
||||
|
||||
- 类型: `String`
|
||||
|
||||
配置默认语言。
|
||||
在`Primary`布局下,页面滚动时是否固定顶部。
|
||||
@@ -36,7 +36,7 @@ File sizes after gzip:
|
||||
|
||||
`build` 命令会打包所有的资源,包含 JavaScript, CSS, web fonts, images, html 等。你可以在 `dist/` 目录下找到这些文件。
|
||||
|
||||
> 如果 有使用 HashHistory 、 部署 html 到非根目录、静态化等需求,请查看[Umi 部署](https://umijs.org/zh/guide/deploy.html)。
|
||||
> 如果有使用 HashHistory 、 部署 html 到非根目录、静态化等需求,请查看[Umi 部署](https://umijs.org/zh/guide/deploy.html)。
|
||||
|
||||
## 本地验证
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# 问题集锦
|
||||
|
||||
## 新建页面
|
||||
|
||||
1. 直接从/src/pages复制一个page (会自动创建路由[umi](https://umijs.org/zh/guide/router.html#%E7%BA%A6%E5%AE%9A%E5%BC%8F%E8%B7%AF%E7%94%B1))
|
||||
2. 修改 namespace/pathToRegexp 在 model.js
|
||||
3. 修改 mock中route.js增加一条route
|
||||
@@ -9,32 +9,29 @@ git clone https://github.com/zuiidea/antd-admin.git my-project
|
||||
cd my-project
|
||||
```
|
||||
|
||||
## 目录结构
|
||||
|
||||
应用的目录结构如下
|
||||
1. 克隆项目并安装依赖(推荐使用 `pnpm`)。
|
||||
|
||||
```bash
|
||||
├── dist/ # 默认build输出目录
|
||||
├── mock/ # Mock文件目录
|
||||
├── public/ # 静态资源文件目录
|
||||
├── src/ # 源码目录
|
||||
│ ├── components/ # 组件目录
|
||||
│ ├── e2e/ # e2e目录
|
||||
│ ├── layouts/ # 布局目录
|
||||
│ ├── locales/ # 国际化文件目录
|
||||
│ ├── models/ # 数据模型目录
|
||||
│ ├── pages/ # 页面组件目录
|
||||
│ ├── services/ # 数据接口目录
|
||||
│ │ ├── api.js # 接口配置
|
||||
│ │ └── index.js # 接口输出
|
||||
│ ├── themes/ # 项目样式目录
|
||||
│ │ ├── default.less # 样式变量
|
||||
│ │ ├── index.less # 全局样式
|
||||
│ │ ├── mixin.less # 样式函数
|
||||
│ │ └── vars.less # 样式变量及函数
|
||||
│ ├── utils/ # 工具函数目录
|
||||
│ │ ├── config.js # 项目配置
|
||||
│ │ ├── constant.js # 静态常量
|
||||
git clone https://github.com/zuiidea/antd-admin.git my-project
|
||||
cd my-project
|
||||
pnpm install
|
||||
```
|
||||
|
||||
或使用其它包管理器:
|
||||
|
||||
```bash
|
||||
npm install
|
||||
# 或
|
||||
yarn install
|
||||
```
|
||||
|
||||
2. 启动开发模式:
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
3. 启动完成后在浏览器打开项目(查看开发服务器输出以获取实际 URL/端口)。
|
||||
│ │ ├── index.js # 工具函数
|
||||
│ │ ├── request.js # 异步请求函数(axios)
|
||||
│ │ └── theme.js # 项目需要在js中使用到样式变量
|
||||
@@ -52,22 +49,21 @@ cd my-project
|
||||
|
||||
## 本地开发
|
||||
|
||||
1. 进入目录安装依赖,国内用户推荐使用 [cnpm](https://cnpmjs.org) 进行加速
|
||||
项目推荐使用 `pnpm` 进行依赖管理:
|
||||
|
||||
```bash
|
||||
yarn install
|
||||
pnpm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
或者
|
||||
也可以使用 `npm` 或 `yarn`:
|
||||
|
||||
```bash
|
||||
npm install
|
||||
# 或
|
||||
yarn install
|
||||
# 然后使用对应的启动命令,例如 `npm run dev` 或 `yarn dev`(若 package.json 中配置了),
|
||||
# 本仓库默认开发脚本为 `npm run dev`。
|
||||
```
|
||||
|
||||
2. 启动本地服务器
|
||||
|
||||
```bash
|
||||
npm run start
|
||||
```
|
||||
|
||||
3. 启动完成后打开浏览器访问 [http://localhost:7000](http://localhost:7000),如果需要更改启动端口,可在 `.env` 文件中配置。
|
||||
启动后在浏览器打开项目(查看开发服务器输出以获取实际 URL/端口)。
|
||||
|
||||
@@ -1,75 +1,123 @@
|
||||
# 国际化
|
||||
# 国际化(i18n)使用说明
|
||||
|
||||
## 新增应用语言
|
||||
本项目通过 Umi 的 `plugin-locale`(基于 `react-intl`)管理多语言,翻译资源位于 `src/locales`(例如 `en-US.json`、`zh-CN.json`)。下面说明如何:新增语言、增加翻译条目、切换语言与关闭多语言。示例以新增日语 `ja-JP` 为例。
|
||||
|
||||
以新增日语为例。
|
||||
## 1. 新增一种语言(长期支持)
|
||||
|
||||

|
||||
1. 在 `src/locales/` 下创建新的翻译文件,文件名为语言标识,例如:`src/locales/ja-JP.json`。
|
||||
|
||||
1. 添加语言包本地文件,`ja` 为日语的语言代码,支持翻译的语言列表参考 [有道智云](http://ai.youdao.com/docs/doc-trans-api.s#p05),运行下面命令后会生成 `src/locales/ja/messages.json` 文件。
|
||||
2. 文件内容为 JSON 格式的翻译对象(可嵌套):
|
||||
|
||||
```bash
|
||||
npm run add-locale ja
|
||||
```
|
||||
```json
|
||||
{
|
||||
"welcome": "ようこそ",
|
||||
"login": {
|
||||
"username": "ユーザー名",
|
||||
"password": "パスワード",
|
||||
"submit": "ログイン"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
2. 提取代码中需要翻译的字段,即 `<Trans>message</Trans>`、`` i18n.t`message `` 中 `message` 字段,运行下面命令后 `src/locales/ja/messages.json` 将会出现提取后的字段配置。
|
||||
3. 若希望 Ant Design 组件也使用对应的本地化(日期/组件文案),在 `src/app.tsx` 的 `pick` 函数中添加对应的 AntD locale 引入与映射,例如:
|
||||
|
||||
```bash
|
||||
npm run extract
|
||||
```
|
||||
```ts
|
||||
import jaJP from 'antd/locale/ja_JP';
|
||||
// ...
|
||||
if (l === 'ja-JP') return jaJP;
|
||||
```
|
||||
|
||||
你将看到如下信息:
|
||||
4. 在语言选择列表(例如 `src/components/TopbarControls.tsx` 的 `localeMenuItems`)中加入新语言项:
|
||||
|
||||
```bash
|
||||
Catalog statistics:
|
||||
┌─────────────┬─────────────┬─────────┐
|
||||
│ Language │ Total count │ Missing │
|
||||
├─────────────┼─────────────┼─────────┤
|
||||
│ en (source) │ 52 │ - │
|
||||
│ ja │ 52 │ 52 │
|
||||
│ zh │ 52 │ 0 │
|
||||
└─────────────┴─────────────┴─────────┘
|
||||
```
|
||||
```ts
|
||||
{ key: 'ja-JP', label: '日本語' }
|
||||
```
|
||||
|
||||
3. 与此同时,我们在 `src/utils/config.js` 新增相关配置。
|
||||
5. 重启开发服务器:
|
||||
|
||||
```javascript
|
||||
{
|
||||
...
|
||||
i18n: {
|
||||
languages: [
|
||||
...
|
||||
{
|
||||
key:'ja',
|
||||
title: '日本語',
|
||||
flag: '/japanese.svg',
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
```
|
||||
```bash
|
||||
pnpm run dev
|
||||
```
|
||||
|
||||
> 路由相关效果,配置后 `npm run start` 重启后生效。
|
||||
Umi 会在构建时将 `src/locales` 下的文件编入 `localeInfo`,页面即可使用新语言。
|
||||
|
||||
4. 使用内置的命令进行自动翻译,在 `src/locales/ja/messages.json` 中将会看到翻译后的配置。
|
||||
提示:如不想重启或想动态注册翻译,可使用运行时 API `addLocale(name, messages, extraLocales)`(见下一节)。
|
||||
|
||||
```bash
|
||||
npm run trans:only
|
||||
```
|
||||
## 2. 增加一条多语言文本(翻译条目)
|
||||
|
||||
你将看到如下信息:
|
||||
1. 在所有语言的 JSON 文件中添加相同的 id(推荐同时维护 `en-US.json` 与 `zh-CN.json`,新语言也应添加):
|
||||
|
||||
```bash
|
||||
start: en -> ja
|
||||
...
|
||||
youdao: en -> ja: Unpublished -> 未発表
|
||||
youdao: en -> ja: Update -> 更新
|
||||
youdao: en -> ja: Update User -> ユーザーの更新
|
||||
youdao: en -> ja: Username -> 名
|
||||
...
|
||||
All translations have been completed.
|
||||
```
|
||||
`src/locales/en-US.json`
|
||||
|
||||
> `npm run trans` 将会依次执行 `npm run extract` 和 `npm run trans:only`
|
||||
```json
|
||||
"my.feature.greeting": "Hello from feature"
|
||||
```
|
||||
|
||||
5. 最后,可以在 `src/locales/ja/messages.json` 中对翻译不准确的的字段进行调整。启动开发模式 `npm run start`,打开 [http://localhost:7000/ja/login](http://localhost:7000/ja/login),你将看到日语版本的应用。
|
||||
`src/locales/zh-CN.json`
|
||||
|
||||
```json
|
||||
"my.feature.greeting": "来自功能的问候"
|
||||
```
|
||||
|
||||
2. 在组件中使用 `useIntl()` 获取 `intl`,并调用 `formatMessage`:
|
||||
|
||||
```ts
|
||||
import { useIntl } from 'umi';
|
||||
const intl = useIntl();
|
||||
const text = intl.formatMessage({ id: 'my.feature.greeting', defaultMessage: 'Hello' });
|
||||
```
|
||||
|
||||
建议使用 `useIntl()`(或 `injectIntl`)以保证语言切换时组件可自动刷新并显示新文本。
|
||||
|
||||
## 3. 运行时切换或注册语言
|
||||
|
||||
- 切换语言(会写入 `localStorage` 并触发刷新或事件):
|
||||
|
||||
```ts
|
||||
import { setLocale } from 'umi';
|
||||
// 切换并刷新页面
|
||||
setLocale('ja-JP', true);
|
||||
// 切换但不刷新(触发事件更新)
|
||||
setLocale('zh-CN', false);
|
||||
```
|
||||
|
||||
- 运行时注册(无需重启):
|
||||
|
||||
```ts
|
||||
import { addLocale, setLocale } from 'umi';
|
||||
import jaMessages from '@/locales/ja-JP.json';
|
||||
import jaAntd from 'antd/locale/ja_JP';
|
||||
|
||||
addLocale('ja-JP', jaMessages, { antd: jaAntd, momentLocale: 'ja' });
|
||||
setLocale('ja-JP', false);
|
||||
```
|
||||
|
||||
`addLocale` 会把翻译合并到内部 `localeInfo`,并可同时提供 AntD 与(可选的)moment 本地化配置。
|
||||
|
||||
## 4. 关闭多语言(禁用 i18n)
|
||||
|
||||
若想永久关闭多语言功能:
|
||||
|
||||
1. 在 `src/app.tsx` 的 `LocaleWrapper` 中,直接返回固定的 AntD locale(忽略 `localStorage` 中的 `umi_locale`):
|
||||
|
||||
```ts
|
||||
const pick = (l: string | null) => {
|
||||
return zhCN; // 强制使用中文
|
||||
};
|
||||
```
|
||||
|
||||
2. 移除或隐藏语言切换控件(例如删除 `src/components/TopbarControls.tsx` 中的语言菜单项或 Dropdown)。
|
||||
|
||||
3. 可选:删除 `src/locales` 中其它语言文件,仅保留目标语言文件以减少构建体积。
|
||||
|
||||
如果只是临时禁止用户切换,建议仅执行第 2 步(隐藏切换),以便未来快速恢复多语言支持。
|
||||
|
||||
## 5. 调试与常见问题
|
||||
|
||||
- 新增语言后无显示:确认已重启 dev server(或使用 `addLocale` 动态注册),并在 `app.tsx` 中为该语言提供 AntD locale。
|
||||
- 翻译未生效或缺失:检查 `src/locales/*.json` 是否包含对应 id,且 `formatMessage` 中的 id 拼写正确。
|
||||
- 想自动抽取翻译 id:仓库未内置抽取脚本,建议按需集成 `lingui`、`babel-plugin-react-intl` 或其他工具并在 `package.json` 中添加相应脚本。
|
||||
|
||||
如果你需要,我可以:
|
||||
- 为你创建一个 `src/locales/ja-JP.json` 的初始翻译并更新 `TopbarControls` 与 `app.tsx` 映射;或
|
||||
- 添加一个示例组件,演示如何在运行时通过 `addLocale` 注册新语言。请告诉我你更希望我执行哪项。
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## 新增布局
|
||||
|
||||
以新增名为 `secondary` 的布局为例,使以 `seconday` 开头的路由都使用该布局。
|
||||
以新增名为 `secondary` 的布局为例,使以 `secondary` 开头的路由都使用该布局。
|
||||
|
||||
1. 在 `src/utils/config.js` 新增相关配置,参数详细请查看 [layouts](/zh-cn/configuration?id=layouts)。
|
||||
|
||||
@@ -11,11 +11,11 @@
|
||||
{
|
||||
name: 'primary',
|
||||
include: [/.*/],
|
||||
exlude: [/(\/(en|zh))*\/login/, /(\/(en|zh))*\/seconday\/(.*)/],
|
||||
exclude: [/(\/(en|zh))*\/login/, /(\/(en|zh))*\/secondary\/(.*)/],
|
||||
},
|
||||
{
|
||||
name: 'secondary',
|
||||
include: [/(\/(en|zh))*\/seconday\/(.*)/],
|
||||
include: [/(\/(en|zh))*\/secondary\/(.*)/],
|
||||
},
|
||||
],
|
||||
```
|
||||
@@ -40,21 +40,21 @@
|
||||
export default ({ children }) => {
|
||||
return (
|
||||
<div>
|
||||
<h1>Seconday</h1>
|
||||
<h1>Secondary</h1>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
4. 在`src/pages/` 目录中新增 `seconday/index.js` 文件。
|
||||
4. 在`src/pages/` 目录中新增 `secondary/index.js` 文件。
|
||||
|
||||
```javascript
|
||||
import React from 'react'
|
||||
|
||||
export default ({ children }) => {
|
||||
return <div>Seconday page Content</div>
|
||||
return <div>Secondary page Content</div>
|
||||
}
|
||||
```
|
||||
|
||||
5. 最后,启动开发模式 `npm run start`,打开 [http://localhost:7000/seconday/](http://localhost:7000/seconday/),你将看到 `seconday` 布局的页面。
|
||||
5. 最后,使用 `npm run dev` 启动开发模式,然后在浏览器中打开该布局页面(查看开发服务器输出以获取实际 URL),例如 `/secondary/`。
|
||||
|
||||
@@ -1,24 +1,33 @@
|
||||
# HTTP请求
|
||||
# HTTP 请求
|
||||
|
||||
本项目使用了axios提供http请求服务,文件在src/utils/request.js
|
||||
本项目使用位于 `src/utils/request.ts` 的轻量封装(基于 `fetch`),默认导出为 `api`。该封装负责:
|
||||
|
||||
## 自定义Header
|
||||
- 将 `config.apiPrefix` 与请求 `path` 拼接为最终 URL。
|
||||
- 处理 `params`(查询字符串)与 `body`(JSON 或 FormData)。
|
||||
- 在本地有 token 时自动注入 `Authorization` 头(本项目使用 localStorage 键 `app-auth-token`)。
|
||||
- 统一解析后端返回(后端需遵循 `{ success, message, data }` 约定)并在非成功时抛出错误并显示 UI 提示(使用 `antd` 的 `message`)。
|
||||
|
||||
为了提供鉴权、修改cookie等服务,可以手动修改Header
|
||||
主要行为说明
|
||||
|
||||
```
|
||||
axios.defaults.headers.common['Authorization'] = 'token'
|
||||
- `api(path, options)` 会把 `config.apiPrefix` 与 `path` 拼接。
|
||||
- 当传入 `options.params` 时,会序列化为查询字符串并追加到 URL。
|
||||
- `options.body` 的处理策略:
|
||||
- 若为 FormData,直接发送(不要手动设置 Content-Type)。
|
||||
- 若为字符串或 Blob,直接发送。
|
||||
- 其余对象会被 `JSON.stringify`,默认设置 `Content-Type: application/json`(除非已在 headers 中指定)。
|
||||
- 若 localStorage 中有 token 且未在 headers 中显式提供 Authorization,将自动设置 `Authorization: Bearer <token>`。
|
||||
- 成功响应返回后端 `data` 字段;响应格式不符合约定或后端返回失败时会抛出异常。
|
||||
|
||||
使用示例(TypeScript):
|
||||
|
||||
```ts
|
||||
import api from '@/utils/request';
|
||||
|
||||
// 带查询参数的 GET
|
||||
const page = await api('/users', { method: 'GET', params: { page: 1, pageSize: 10 } });
|
||||
|
||||
// 发送 JSON 请求体的 POST
|
||||
const created = await api('/user', { method: 'POST', body: { name: 'Alice' } });
|
||||
```
|
||||
|
||||
或者
|
||||
|
||||
```
|
||||
// 添加请求拦截器
|
||||
axios.interceptors.request.use(function (config) {
|
||||
// 在发送请求之前做些什么
|
||||
config.headers.token = window.localStorage.getItem('token');
|
||||
return config;
|
||||
}, function (error) {
|
||||
return Promise.reject(error);
|
||||
});
|
||||
```
|
||||
详细实现请参阅 `src/utils/request.ts`,文档中仅列出使用建议与约定。
|
||||
@@ -1,3 +0,0 @@
|
||||
module.exports = {
|
||||
testURL: 'http://localhost:8000',
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { Config, configUmiAlias, createConfig } from 'umi/test';
|
||||
|
||||
export default async () => {
|
||||
return (
|
||||
(await configUmiAlias({
|
||||
...createConfig({
|
||||
target: 'browser',
|
||||
jsTransformer: 'esbuild',
|
||||
jsTransformerOpts: { jsx: 'automatic' },
|
||||
}),
|
||||
// you can override umi default jest config here
|
||||
setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts'],
|
||||
})) as Config.InitialOptions
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,53 @@
|
||||
import * as adminSvc from '../../src/services/admin';
|
||||
|
||||
/**
|
||||
* Skill 元数据与封装 — Admin
|
||||
* 目的:为自动化代理或 LLM 提供明确的能力描述与可直接调用的包装函数。
|
||||
*/
|
||||
export const meta = {
|
||||
id: 'admin:manage',
|
||||
name: 'Admin Management',
|
||||
description: '登录/登出、获取当前管理员、管理管理员列表(增删改查)',
|
||||
inputs: {
|
||||
login: { adminname: 'string', password: 'string' },
|
||||
getAdmin: { id: 'string' },
|
||||
createAdmin: { values: 'object' },
|
||||
updateAdmin: { id: 'string', values: 'object' },
|
||||
deleteAdmin: { id: 'string' },
|
||||
deleteAdmins: { ids: 'string[]' },
|
||||
listAdmins: { params: 'object | undefined' },
|
||||
},
|
||||
outputs: 'JSON (see src/types/admin.ts for schema)',
|
||||
};
|
||||
|
||||
export const actions = {
|
||||
async login(payload: { adminname: string; password: string }) {
|
||||
return adminSvc.login(payload);
|
||||
},
|
||||
async logout() {
|
||||
return adminSvc.logout();
|
||||
},
|
||||
async currentAdmin() {
|
||||
return adminSvc.currentAdmin();
|
||||
},
|
||||
async listAdmins(params?: Record<string, string | number | boolean>) {
|
||||
return adminSvc.listAdmins(params as any);
|
||||
},
|
||||
async createAdmin(values: Record<string, unknown>) {
|
||||
return adminSvc.createAdmin(values);
|
||||
},
|
||||
async getAdmin(id: string) {
|
||||
return adminSvc.getAdmin(id);
|
||||
},
|
||||
async updateAdmin(id: string, values: Record<string, unknown>) {
|
||||
return adminSvc.updateAdmin(id, values);
|
||||
},
|
||||
async deleteAdmin(id: string) {
|
||||
return adminSvc.deleteAdmin(id);
|
||||
},
|
||||
async deleteAdmins(ids: string[]) {
|
||||
return adminSvc.deleteAdmins(ids);
|
||||
},
|
||||
};
|
||||
|
||||
export default { meta, actions };
|
||||
@@ -0,0 +1,17 @@
|
||||
import * as dashSvc from '../../src/services/dashboard';
|
||||
|
||||
export const meta = {
|
||||
id: 'dashboard:view',
|
||||
name: 'Dashboard View',
|
||||
description: '获取仪表盘汇总数据',
|
||||
inputs: {},
|
||||
outputs: 'JSON summary data from /dashboard',
|
||||
};
|
||||
|
||||
export const actions = {
|
||||
async getDashboard() {
|
||||
return dashSvc.getDashboard();
|
||||
},
|
||||
};
|
||||
|
||||
export default { meta, actions };
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* Skills registry
|
||||
*
|
||||
* 目的:集中导出 llm/skills 下的 skill 模块,便于运行时自动发现或静态引入。
|
||||
* 导出:
|
||||
* - `skills`:按短名映射的 skill 模块集合。
|
||||
* - `listSkills()`:返回所有 skill 的 meta 数组,便于展示或自动选择。
|
||||
* - `getSkillById(id)`:基于 meta.id 查找对应 skill 模块。
|
||||
*/
|
||||
import admin from './admin.skill';
|
||||
import dashboard from './dashboard.skill';
|
||||
import menu from './menu.skill';
|
||||
import user from './user.skill';
|
||||
|
||||
const skills: Record<string, any> = {
|
||||
admin,
|
||||
menu,
|
||||
user,
|
||||
dashboard,
|
||||
};
|
||||
|
||||
export function listSkills() {
|
||||
return Object.values(skills).map((s) => s.meta);
|
||||
}
|
||||
|
||||
export function getSkillById(id: string) {
|
||||
return Object.values(skills).find((s) => s.meta && s.meta.id === id);
|
||||
}
|
||||
|
||||
export { skills };
|
||||
|
||||
export default skills;
|
||||
@@ -0,0 +1,35 @@
|
||||
import * as menuSvc from '../../src/services/menu';
|
||||
|
||||
export const meta = {
|
||||
id: 'menu:manage',
|
||||
name: 'Menu Management',
|
||||
description: '列出、创建、更新、删除与排序菜单项',
|
||||
inputs: {
|
||||
listMenus: {},
|
||||
createMenu: { values: 'MenuFormValues' },
|
||||
updateMenu: { id: 'number | string', values: 'Partial<MenuFormValues>' },
|
||||
deleteMenu: { id: 'number | string' },
|
||||
sortMenus: { order: 'Array<number | string>' },
|
||||
},
|
||||
outputs: 'JSON (see src/types/menu.ts for schema)',
|
||||
};
|
||||
|
||||
export const actions = {
|
||||
async listMenus() {
|
||||
return menuSvc.listMenus();
|
||||
},
|
||||
async createMenu(values: any) {
|
||||
return menuSvc.createMenu(values);
|
||||
},
|
||||
async updateMenu(id: number | string, values: any) {
|
||||
return menuSvc.updateMenu(id, values);
|
||||
},
|
||||
async deleteMenu(id: number | string) {
|
||||
return menuSvc.deleteMenu(id);
|
||||
},
|
||||
async sortMenus(order: Array<number | string>) {
|
||||
return menuSvc.sortMenus(order);
|
||||
},
|
||||
};
|
||||
|
||||
export default { meta, actions };
|
||||
@@ -0,0 +1,39 @@
|
||||
import * as userSvc from '../../src/services/user';
|
||||
|
||||
export const meta = {
|
||||
id: 'user:manage',
|
||||
name: 'User Management',
|
||||
description: '用户列表/分页、创建、获取、更新、删除与批量删除',
|
||||
inputs: {
|
||||
listUsers: { params: 'object | undefined' },
|
||||
createUser: { values: 'object' },
|
||||
getUser: { id: 'string' },
|
||||
updateUser: { id: 'string', values: 'object' },
|
||||
deleteUser: { id: 'string' },
|
||||
deleteUsers: { ids: 'string[]' },
|
||||
},
|
||||
outputs: 'JSON (see src/types/user.ts for schema)',
|
||||
};
|
||||
|
||||
export const actions = {
|
||||
async listUsers(params?: Record<string, string | number | boolean>) {
|
||||
return userSvc.listUsers(params as any);
|
||||
},
|
||||
async createUser(values: Record<string, unknown>) {
|
||||
return userSvc.createUser(values);
|
||||
},
|
||||
async getUser(id: string) {
|
||||
return userSvc.getUser(id);
|
||||
},
|
||||
async updateUser(id: string, values: Record<string, unknown>) {
|
||||
return userSvc.updateUser(id, values);
|
||||
},
|
||||
async deleteUser(id: string) {
|
||||
return userSvc.deleteUser(id);
|
||||
},
|
||||
async deleteUsers(ids: string[]) {
|
||||
return userSvc.deleteUsers(ids);
|
||||
},
|
||||
};
|
||||
|
||||
export default { meta, actions };
|
||||
@@ -0,0 +1,36 @@
|
||||
项目:antd-admin_next
|
||||
|
||||
目标:将仓库中的关键信息写成对大模型(LLM)友好的简短说明,便于自动化理解、代码导航和提示生成。
|
||||
|
||||
概览:
|
||||
- 技术栈:React + Ant Design + TypeScript(前端单页/多页面结构),源码位于 `src/`。
|
||||
- 路由/页面:页面文件放在 `src/pages/` 目录;布局在 `src/layouts/`;组件在 `src/components/`。
|
||||
- 重要工具:`src/utils/request.ts` 为 HTTP 请求封装,使用 `fetch`,默认 API 前缀由 `src/utils/config.ts` 提供。
|
||||
|
||||
API 与约定:
|
||||
- 全局 API 前缀:`/api/v1`(见 `src/utils/config.ts`)。
|
||||
- 请求函数 `api(path, options)`:
|
||||
- 自动把 `options.params` 转为查询字符串。
|
||||
- 对对象 body 自动 JSON 序列化并设置 `Content-Type: application/json`(FormData 会被保留)。
|
||||
- 当响应状态为 `204` 返回空对象;当 `res.ok` 为 false 时抛出 Error,错误信息优先使用响应体中的 `message` 字段。
|
||||
|
||||
如何使用(对模型说明):
|
||||
- 若要调用后端资源,请调用 `api('/resource', { method: 'GET' | 'POST', params, body })`。
|
||||
- 成功响应应为 JSON,失败会抛出 Error。处理调用时应捕获异常并展示 `error.message`。
|
||||
|
||||
本文件用途:
|
||||
- 作为 LLM 的快速上下文:当模型在代码中自动生成、补全或审阅代码时,可引用此文件以获得仓库结构、关键约定和请求行为的摘要。
|
||||
|
||||
快速运行(可能依赖 package manager):
|
||||
- 常用:`npm run dev` 或 `pnpm dev` 启动开发服务器。
|
||||
|
||||
如需更详细的接口契约或后端响应示例,请查看对应的 `src/services/` 目录下的 API 封装文件。
|
||||
|
||||
Agent Skills:
|
||||
- 为方便自动化代理(Agent/LLM)调用,项目在 `llm/skills/` 下提供了若干能力描述与包装:
|
||||
- `llm/skills/admin.skill.ts`:管理员管理相关操作(login、logout、list/create/update/delete)
|
||||
- `llm/skills/menu.skill.ts`:菜单管理操作(list/create/update/delete/sort)
|
||||
- `llm/skills/user.skill.ts`:用户管理操作(list/create/get/update/delete/batch)
|
||||
- `llm/skills/dashboard.skill.ts`:获取仪表盘数据的读取操作
|
||||
|
||||
这些 skill 文件导出 `meta`(能力描述)和 `actions`(可直接调用的异步函数),便于代理在运行时发现并调用对应后端逻辑。
|
||||
@@ -4,10 +4,33 @@
|
||||
"display": "standalone",
|
||||
"background_color": "#fff",
|
||||
"description": "A front-end solution for enterprise applications built upon Ant Design and UmiJS",
|
||||
"icons": [
|
||||
"icons": [{
|
||||
"src": "logo/logo@96.png",
|
||||
"sizes": "72x72"
|
||||
},
|
||||
{
|
||||
"src": "logo.svg",
|
||||
"sizes": "72x72 96x96 128x128 144x144 152x152 192x192 384x384 512x512"
|
||||
"src": "logo/logo@128.png",
|
||||
"sizes": "128x128"
|
||||
},
|
||||
{
|
||||
"src": "logo/logo@144.png",
|
||||
"sizes": "144x144"
|
||||
},
|
||||
{
|
||||
"src": "logo/logo@152.png",
|
||||
"sizes": "152x152"
|
||||
},
|
||||
{
|
||||
"src": "logo/logo@192.png",
|
||||
"sizes": "192x192"
|
||||
},
|
||||
{
|
||||
"src": "logo/logo@384.png",
|
||||
"sizes": "384x384"
|
||||
},
|
||||
{
|
||||
"src": "logo/logo@512.png",
|
||||
"sizes": "512x512"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
/**
|
||||
* Query objects that specify keys and values in an array where all values are objects.
|
||||
* @param {array} array An array where all values are objects, like [{key:1},{key:2}].
|
||||
* @param {string} key The key of the object that needs to be queried.
|
||||
* @param {string} value The value of the object that needs to be queried.
|
||||
* @return {object|undefined} Return frist object when query success.
|
||||
*/
|
||||
export function queryArray(array, key, value) {
|
||||
if (!Array.isArray(array)) {
|
||||
return
|
||||
}
|
||||
return array.filter(_ => _[key] === value)
|
||||
}
|
||||
|
||||
export function randomNumber(min, max) {
|
||||
return Math.floor(Math.random() * (max - min) + min)
|
||||
}
|
||||
|
||||
export function randomAvatar() {
|
||||
// https://uifaces.co
|
||||
const avatarList = [
|
||||
'https://randomuser.me/api/portraits/men/32.jpg',
|
||||
'https://images.pexels.com/photos/415829/pexels-photo-415829.jpeg?h=350&auto=compress&cs=tinysrgb',
|
||||
'https://d3iw72m71ie81c.cloudfront.net/female-17.jpg',
|
||||
'https://randomuser.me/api/portraits/men/35.jpg',
|
||||
'https://pbs.twimg.com/profile_images/835224725815246848/jdMBCxHS.jpg',
|
||||
'https://pbs.twimg.com/profile_images/584098247641300992/N25WgvW_.png',
|
||||
'https://d3iw72m71ie81c.cloudfront.net/male-5.jpg',
|
||||
'https://images.pexels.com/photos/413723/pexels-photo-413723.jpeg?h=350&auto=compress&cs=tinysrgb',
|
||||
'https://randomuser.me/api/portraits/women/44.jpg',
|
||||
'https://randomuser.me/api/portraits/women/68.jpg',
|
||||
'https://randomuser.me/api/portraits/women/65.jpg',
|
||||
'https://randomuser.me/api/portraits/men/43.jpg',
|
||||
'https://tinyfac.es/data/avatars/475605E3-69C5-4D2B-8727-61B7BB8C4699-500w.jpeg',
|
||||
'https://pbs.twimg.com/profile_images/943227488292962306/teiNNAiy.jpg',
|
||||
'https://randomuser.me/api/portraits/men/46.jpg'
|
||||
]
|
||||
return avatarList[randomNumber(0, avatarList.length - 1)]
|
||||
}
|
||||
|
||||
export const Constant = {
|
||||
ApiPrefix: '/api/v1',
|
||||
NotFound: {
|
||||
message: 'Not Found',
|
||||
documentation_url: '',
|
||||
},
|
||||
Color: {
|
||||
green: '#64ea91',
|
||||
blue: '#8fc9fb',
|
||||
purple: '#d897eb',
|
||||
red: '#f69899',
|
||||
yellow: '#f8c82e',
|
||||
peach: '#f797d6',
|
||||
borderBase: '#e5e5e5',
|
||||
borderSplit: '#f4f4f4',
|
||||
grass: '#d6fbb5',
|
||||
sky: '#c1e0fc',
|
||||
},
|
||||
}
|
||||
|
||||
export Mock from 'mockjs'
|
||||
export qs from 'qs'
|
||||
@@ -1,142 +0,0 @@
|
||||
import { Mock, Constant } from './_utils'
|
||||
|
||||
const { ApiPrefix, Color } = Constant
|
||||
|
||||
const Dashboard = Mock.mock({
|
||||
'sales|8': [
|
||||
{
|
||||
'name|+1': 2008,
|
||||
'Clothes|200-500': 1,
|
||||
'Food|180-400': 1,
|
||||
'Electronics|300-550': 1,
|
||||
},
|
||||
],
|
||||
cpu: {
|
||||
'usage|50-600': 1,
|
||||
space: 825,
|
||||
'cpu|40-90': 1,
|
||||
'data|20': [
|
||||
{
|
||||
'cpu|20-80': 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
browser: [
|
||||
{
|
||||
name: 'Google Chrome',
|
||||
percent: 43.3,
|
||||
status: 1,
|
||||
},
|
||||
{
|
||||
name: 'Mozilla Firefox',
|
||||
percent: 33.4,
|
||||
status: 2,
|
||||
},
|
||||
{
|
||||
name: 'Apple Safari',
|
||||
percent: 34.6,
|
||||
status: 3,
|
||||
},
|
||||
{
|
||||
name: 'Internet Explorer',
|
||||
percent: 12.3,
|
||||
status: 4,
|
||||
},
|
||||
{
|
||||
name: 'Opera Mini',
|
||||
percent: 3.3,
|
||||
status: 1,
|
||||
},
|
||||
{
|
||||
name: 'Chromium',
|
||||
percent: 2.53,
|
||||
status: 1,
|
||||
},
|
||||
],
|
||||
user: {
|
||||
name: 'github',
|
||||
sales: 3241,
|
||||
sold: 3556,
|
||||
},
|
||||
'completed|12': [
|
||||
{
|
||||
'name|+1': 2008,
|
||||
'Task complete|200-1000': 1,
|
||||
'Cards Complete|200-1000': 1,
|
||||
},
|
||||
],
|
||||
'comments|5': [
|
||||
{
|
||||
name: '@last',
|
||||
'status|1-3': 1,
|
||||
content: '@sentence',
|
||||
avatar() {
|
||||
return Mock.Random.image(
|
||||
'48x48',
|
||||
Mock.Random.color(),
|
||||
'#757575',
|
||||
'png',
|
||||
this.name.substr(0, 1)
|
||||
)
|
||||
},
|
||||
date() {
|
||||
return `2016-${Mock.Random.date('MM-dd')} ${Mock.Random.time(
|
||||
'HH:mm:ss'
|
||||
)}`
|
||||
},
|
||||
},
|
||||
],
|
||||
'recentSales|36': [
|
||||
{
|
||||
'id|+1': 1,
|
||||
name: '@last',
|
||||
'status|1-4': 1,
|
||||
date() {
|
||||
return `${Mock.Random.integer(2015, 2016)}-${Mock.Random.date(
|
||||
'MM-dd'
|
||||
)} ${Mock.Random.time('HH:mm:ss')}`
|
||||
},
|
||||
'price|10-200.1-2': 1,
|
||||
},
|
||||
],
|
||||
quote: {
|
||||
name: 'Joho Doe',
|
||||
title: 'Graphic Designer',
|
||||
content:
|
||||
"I'm selfish, impatient and a little insecure. I make mistakes, I am out of control and at times hard to handle. But if you can't handle me at my worst, then you sure as hell don't deserve me at my best.",
|
||||
avatar:
|
||||
'http://img.hb.aicdn.com/bc442cf0cc6f7940dcc567e465048d1a8d634493198c4-sPx5BR_fw236',
|
||||
},
|
||||
numbers: [
|
||||
{
|
||||
icon: 'pay-circle-o',
|
||||
color: Color.green,
|
||||
title: 'Online Review',
|
||||
number: 2781,
|
||||
},
|
||||
{
|
||||
icon: 'team',
|
||||
color: Color.blue,
|
||||
title: 'New Customers',
|
||||
number: 3241,
|
||||
},
|
||||
{
|
||||
icon: 'message',
|
||||
color: Color.purple,
|
||||
title: 'Active Projects',
|
||||
number: 253,
|
||||
},
|
||||
{
|
||||
icon: 'shopping-cart',
|
||||
color: Color.red,
|
||||
title: 'Referrals',
|
||||
number: 4324,
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
module.exports = {
|
||||
[`GET ${ApiPrefix}/dashboard`](req, res) {
|
||||
res.json(Dashboard)
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
// Consolidated mock server for development (simplified)
|
||||
const Mock = require('mockjs');
|
||||
const qs = require('qs');
|
||||
|
||||
const ApiPrefix = '/api/v1';
|
||||
|
||||
// simple in-memory admin users with richer mock fields
|
||||
const adminList = [
|
||||
{
|
||||
id: 1,
|
||||
username: 'admin',
|
||||
password: 'admin',
|
||||
real_name: '李四',
|
||||
nick_name: '超级管理员',
|
||||
mobile: '13800000000',
|
||||
avatar: Mock.Random.image('100x100', '#4096ff', '#fff', 'png', 'A'),
|
||||
role: '管理员',
|
||||
department: '运维部',
|
||||
permissions: '*',
|
||||
status: 1,
|
||||
remark: '拥有所有权限',
|
||||
lastLogin: Mock.Random.datetime(),
|
||||
createdBy: 'system',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
username: 'guest',
|
||||
password: 'guest',
|
||||
real_name: '访客',
|
||||
nick_name: '访客',
|
||||
mobile: '15100000000',
|
||||
avatar: Mock.Random.image('100x100', '#ff7f50', '#fff', 'png', 'G'),
|
||||
role: '访客',
|
||||
department: '外部',
|
||||
permissions: '/dashboard,/users,/users/list',
|
||||
status: 1,
|
||||
remark: '',
|
||||
lastLogin: Mock.Random.datetime(),
|
||||
createdBy: 'system',
|
||||
},
|
||||
];
|
||||
|
||||
// users list
|
||||
let users = Mock.mock({
|
||||
'data|20-30': [
|
||||
{
|
||||
id: '@id',
|
||||
name: '@name',
|
||||
nickName: '@last',
|
||||
phone: /^1[34578]\d{9}$/,
|
||||
'age|18-60': 1,
|
||||
address: '@county(true)',
|
||||
isMale: '@boolean',
|
||||
email: '@email',
|
||||
createTime: '@datetime',
|
||||
avatar() {
|
||||
return Mock.Random.image(
|
||||
'100x100',
|
||||
'#4096ff',
|
||||
'#757575',
|
||||
'png',
|
||||
this.nickName ? this.nickName.substr(0, 1) : '',
|
||||
);
|
||||
},
|
||||
},
|
||||
],
|
||||
}).data;
|
||||
|
||||
// routes database (source of truth)
|
||||
const ROUTES_DB = [
|
||||
{ id: '1', name: '仪表盘', icon: 'home', route: '/dashboard' },
|
||||
{ id: '2', name: 'Ai会话', icon: 'robot', route: '/ai/chat' },
|
||||
{ id: '3', name: '用户管理', icon: 'user', route: '/users' },
|
||||
{
|
||||
id: '4',
|
||||
breadcrumbParentId: '3',
|
||||
name: '用户列表',
|
||||
icon: 'team',
|
||||
route: '/users/list',
|
||||
},
|
||||
{
|
||||
id: '5',
|
||||
menuParentId: '-1',
|
||||
breadcrumbParentId: '4',
|
||||
name: '用户详情',
|
||||
route: '/users/:id',
|
||||
},
|
||||
{ id: '6', name: '系统设置', icon: 'settings', route: '/sys' },
|
||||
{
|
||||
id: '7',
|
||||
breadcrumbParentId: '6',
|
||||
name: '成员列表',
|
||||
icon: 'team',
|
||||
route: '/admin/list',
|
||||
},
|
||||
{
|
||||
id: '8',
|
||||
menuParentId: '-1',
|
||||
breadcrumbParentId: '6',
|
||||
name: '成员详情',
|
||||
icon: 'user',
|
||||
route: '/admin/:id',
|
||||
},
|
||||
{
|
||||
id: '9',
|
||||
breadcrumbParentId: '6',
|
||||
name: '菜单设置',
|
||||
icon: 'tool',
|
||||
route: '/sys/menu',
|
||||
},
|
||||
{ id: '10', name: '项目介绍', icon: 'info-c', route: '/guide' },
|
||||
];
|
||||
|
||||
// convert routes DB into menus tree used by UI
|
||||
function buildMenusFromRoutes(db) {
|
||||
const items = db
|
||||
// exclude routes that should not appear in menu (explicit menuParentId === '-1')
|
||||
.filter((r) => !(r.menuParentId === '-1' || r.menuParentId === -1))
|
||||
.map((r, idx) => {
|
||||
const id = Number(r.id) || r.id;
|
||||
// prefer explicit menuParentId, fall back to breadcrumbParentId
|
||||
const parentIdRaw = r.breadcrumbParentId ?? null;
|
||||
const parentId =
|
||||
parentIdRaw === undefined || parentIdRaw === null
|
||||
? null
|
||||
: parentIdRaw === '-1'
|
||||
? null
|
||||
: Number(parentIdRaw);
|
||||
return {
|
||||
id,
|
||||
title: r.name,
|
||||
icon: r.icon,
|
||||
route: r.route,
|
||||
parentId,
|
||||
status: 1,
|
||||
sort: idx + 1,
|
||||
children: [],
|
||||
};
|
||||
});
|
||||
|
||||
const map = new Map();
|
||||
items.forEach((it) => map.set(it.id, it));
|
||||
const roots = [];
|
||||
items.forEach((it) => {
|
||||
if (it.parentId == null || !map.has(it.parentId)) {
|
||||
roots.push(it);
|
||||
} else {
|
||||
map.get(it.parentId).children.push(it);
|
||||
}
|
||||
});
|
||||
|
||||
// sort recursively by sort
|
||||
const sortRec = (arr) => {
|
||||
arr.sort((a, b) => (a.sort || 0) - (b.sort || 0));
|
||||
arr.forEach((c) => {
|
||||
if (c.children && c.children.length) sortRec(c.children);
|
||||
});
|
||||
};
|
||||
sortRec(roots);
|
||||
return roots;
|
||||
}
|
||||
|
||||
const menus = buildMenusFromRoutes(ROUTES_DB);
|
||||
|
||||
// dashboard
|
||||
const Dashboard = Mock.mock({
|
||||
'sales|6': [
|
||||
{
|
||||
'name|+1': 2008,
|
||||
'Clothes|200-500': 1,
|
||||
'Food|180-400': 1,
|
||||
'Electronics|300-550': 1,
|
||||
},
|
||||
],
|
||||
cpu: { 'usage|50-600': 1, space: 825, 'cpu|40-90': 1 },
|
||||
browser: [
|
||||
{ name: 'Google Chrome', percent: 43.3, status: 1 },
|
||||
{ name: 'Mozilla Firefox', percent: 33.4, status: 2 },
|
||||
],
|
||||
});
|
||||
|
||||
// simple helper to read cookie token
|
||||
function parseTokenFromCookie(headers) {
|
||||
const cookie = headers.cookie || '';
|
||||
const cookies = qs.parse(cookie.replace(/\s/g, ''), { delimiter: ';' });
|
||||
if (!cookies.token) return null;
|
||||
try {
|
||||
return JSON.parse(cookies.token);
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
[`GET ${ApiPrefix}/dashboard`](req, res) {
|
||||
res.json({ success: true, data: Dashboard });
|
||||
},
|
||||
|
||||
[`GET ${ApiPrefix}/menus`](req, res) {
|
||||
res.json({ success: true, data: menus });
|
||||
},
|
||||
|
||||
[`POST ${ApiPrefix}/admin/login`](req, res) {
|
||||
const { username, password } = req.body || {};
|
||||
const admin = adminList.find(
|
||||
(u) => u.username === username && u.password === password,
|
||||
);
|
||||
|
||||
if (admin) {
|
||||
const now = new Date();
|
||||
now.setDate(now.getDate() + 1);
|
||||
res.cookie(
|
||||
'token',
|
||||
JSON.stringify({ id: admin.id, deadline: now.getTime() }),
|
||||
{ maxAge: 24 * 3600 * 1000, httpOnly: true },
|
||||
);
|
||||
res.json({ success: true, message: 'Ok', data: null });
|
||||
} else {
|
||||
res
|
||||
.status(400)
|
||||
.json({ success: false, message: 'Invalid credentials', data: null });
|
||||
}
|
||||
},
|
||||
|
||||
[`GET ${ApiPrefix}/admin/logout`](req, res) {
|
||||
res.clearCookie('token');
|
||||
res.json({ success: true, data: null });
|
||||
},
|
||||
|
||||
[`GET ${ApiPrefix}/admin`](req, res) {
|
||||
const token = parseTokenFromCookie(req.headers);
|
||||
const response = {};
|
||||
let admin = {};
|
||||
if (!token) {
|
||||
res
|
||||
.status(200)
|
||||
.json({ success: false, message: 'Not Login', data: null });
|
||||
return;
|
||||
}
|
||||
response.success = token.deadline > new Date().getTime();
|
||||
if (response.success) {
|
||||
const adminItem = adminList.find((u) => u.id === token.id);
|
||||
if (adminItem) {
|
||||
const { password, ...other } = adminItem;
|
||||
admin = other;
|
||||
}
|
||||
}
|
||||
res.json({ success: response.success, data: admin || null });
|
||||
},
|
||||
|
||||
[`GET ${ApiPrefix}/users`](req, res) {
|
||||
const { query } = req;
|
||||
let { pageSize, page, ...other } = query || {};
|
||||
pageSize = Number(pageSize) || 10;
|
||||
page = Number(page) || 1;
|
||||
let newData = users.slice();
|
||||
for (const key in other) {
|
||||
if (Object.prototype.hasOwnProperty.call(other, key)) {
|
||||
newData = newData.filter(
|
||||
(item) => String(item[key]).indexOf(String(other[key])) > -1,
|
||||
);
|
||||
}
|
||||
}
|
||||
res.status(200).json({
|
||||
success: true,
|
||||
data: {
|
||||
data: newData.slice((page - 1) * pageSize, page * pageSize),
|
||||
total: newData.length,
|
||||
},
|
||||
});
|
||||
},
|
||||
|
||||
[`GET ${ApiPrefix}/user/:id`](req, res) {
|
||||
const { id } = req.params || {};
|
||||
let item = users.find((u) => String(u.id) === String(id));
|
||||
// 如果找不到用户,则生成一个带有相同 id 的 mock 用户,避免 404
|
||||
if (!item) {
|
||||
item = Mock.mock({
|
||||
id: String(id),
|
||||
name: '@name',
|
||||
nickName: '@last',
|
||||
phone: /^1[34578]\d{9}$/,
|
||||
'age|18-60': 1,
|
||||
address: '@county(true)',
|
||||
isMale: '@boolean',
|
||||
email: '@email',
|
||||
createTime: '@datetime',
|
||||
avatar() {
|
||||
return Mock.Random.image(
|
||||
'100x100',
|
||||
'#4096ff',
|
||||
'#757575',
|
||||
'png',
|
||||
this.nickName ? this.nickName.substr(0, 1) : '',
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
// enrich with some additional mock fields: phone model and browsing history
|
||||
const enriched = {
|
||||
...item,
|
||||
// ensure lastLogin exists for user detail view (used by UI)
|
||||
lastLogin: item.lastLogin || Mock.Random.datetime(),
|
||||
phoneModel: Mock.Random.pick([
|
||||
'iPhone 13',
|
||||
'iPhone 14 Pro',
|
||||
'Samsung S22',
|
||||
'Huawei P50',
|
||||
'Xiaomi 12',
|
||||
]),
|
||||
browsingHistory: Mock.mock({
|
||||
'data|3-6': [
|
||||
{
|
||||
url: '@url',
|
||||
title: '@title',
|
||||
time: '@datetime',
|
||||
},
|
||||
],
|
||||
}).data,
|
||||
};
|
||||
const { ...other } = enriched;
|
||||
res.status(200).json({ success: true, data: other });
|
||||
},
|
||||
|
||||
[`GET ${ApiPrefix}/routes`](req, res) {
|
||||
res.status(200).json({ success: true, data: ROUTES_DB });
|
||||
},
|
||||
|
||||
// admin accounts CRUD
|
||||
[`GET ${ApiPrefix}/admins`](req, res) {
|
||||
res.status(200).json({
|
||||
success: true,
|
||||
data: { data: adminList, total: adminList.length },
|
||||
});
|
||||
},
|
||||
|
||||
[`GET ${ApiPrefix}/admin/:id`](req, res) {
|
||||
const { id } = req.params || {};
|
||||
const item = adminList.find((u) => String(u.id) === String(id));
|
||||
if (!item)
|
||||
return res
|
||||
.status(404)
|
||||
.json({ success: false, message: 'Not found', data: null });
|
||||
const { password, ...other } = item;
|
||||
res.status(200).json({ success: true, data: other });
|
||||
},
|
||||
|
||||
[`POST ${ApiPrefix}/admin`](req, res) {
|
||||
const body = req.body || {};
|
||||
const id = adminList.length
|
||||
? Math.max(...adminList.map((u) => u.id)) + 1
|
||||
: 1;
|
||||
|
||||
const next = { id, ...body };
|
||||
adminList.push(next);
|
||||
const { password, ...other } = next;
|
||||
res.status(200).json({ success: true, data: other });
|
||||
},
|
||||
|
||||
[`PATCH ${ApiPrefix}/admin/:id`](req, res) {
|
||||
const { id } = req.params || {};
|
||||
const body = req.body || {};
|
||||
const idx = adminList.findIndex((u) => String(u.id) === String(id));
|
||||
if (idx === -1)
|
||||
return res
|
||||
.status(404)
|
||||
.json({ success: false, message: 'Not found', data: null });
|
||||
|
||||
adminList[idx] = { ...adminList[idx], ...body };
|
||||
const { password, ...other } = adminList[idx];
|
||||
res.status(200).json({ success: true, data: other });
|
||||
},
|
||||
};
|
||||
@@ -1,67 +0,0 @@
|
||||
import { Mock, Constant } from './_utils'
|
||||
|
||||
const { ApiPrefix } = Constant
|
||||
|
||||
let postId = 0
|
||||
const database = Mock.mock({
|
||||
'data|100': [
|
||||
{
|
||||
id() {
|
||||
postId += 1
|
||||
return postId + 10000
|
||||
},
|
||||
'status|1-2': 1,
|
||||
title: '@title',
|
||||
author: '@last',
|
||||
categories: '@word',
|
||||
tags: '@word',
|
||||
'views|10-200': 1,
|
||||
'comments|10-200': 1,
|
||||
visibility: () => {
|
||||
return Mock.mock(
|
||||
'@pick(["Public",' + '"Password protected", ' + '"Private"])'
|
||||
)
|
||||
},
|
||||
date: '@dateTime',
|
||||
image() {
|
||||
return Mock.Random.image(
|
||||
'100x100',
|
||||
Mock.Random.color(),
|
||||
'#757575',
|
||||
'png',
|
||||
this.author.substr(0, 1)
|
||||
)
|
||||
},
|
||||
},
|
||||
],
|
||||
}).data
|
||||
|
||||
module.exports = {
|
||||
[`GET ${ApiPrefix}/posts`](req, res) {
|
||||
const { query } = req
|
||||
let { pageSize, page, ...other } = query
|
||||
pageSize = pageSize || 10
|
||||
page = page || 1
|
||||
|
||||
let newData = database
|
||||
for (let key in other) {
|
||||
if ({}.hasOwnProperty.call(other, key)) {
|
||||
newData = newData.filter(item => {
|
||||
if ({}.hasOwnProperty.call(item, key)) {
|
||||
return (
|
||||
String(item[key])
|
||||
.trim()
|
||||
.indexOf(decodeURI(other[key]).trim()) > -1
|
||||
)
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
res.status(200).json({
|
||||
data: newData.slice((page - 1) * pageSize, page * pageSize),
|
||||
total: newData.length,
|
||||
})
|
||||
},
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
import { Constant } from './_utils'
|
||||
const { ApiPrefix } = Constant
|
||||
|
||||
const database = [
|
||||
{
|
||||
id: '1',
|
||||
icon: 'dashboard',
|
||||
name: 'Dashboard',
|
||||
zhName: '仪表盘',
|
||||
route: '/dashboard',
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
breadcrumbParentId: '1',
|
||||
name: 'Users',
|
||||
zhName: '用户管理',
|
||||
icon: 'user',
|
||||
route: '/user',
|
||||
},
|
||||
{
|
||||
id: '7',
|
||||
breadcrumbParentId: '1',
|
||||
name: 'Posts',
|
||||
zhName: '文章管理',
|
||||
icon: 'shopping-cart',
|
||||
route: '/post',
|
||||
},
|
||||
{
|
||||
id: '21',
|
||||
menuParentId: '-1',
|
||||
breadcrumbParentId: '2',
|
||||
name: 'User Detail',
|
||||
zhName: '用户详情',
|
||||
route: '/user/:id',
|
||||
},
|
||||
{
|
||||
id: '3',
|
||||
breadcrumbParentId: '1',
|
||||
name: 'Request',
|
||||
zhName: 'Request',
|
||||
icon: 'api',
|
||||
route: '/request',
|
||||
},
|
||||
{
|
||||
id: '4',
|
||||
breadcrumbParentId: '1',
|
||||
name: 'UI Element',
|
||||
zhName: 'UI组件',
|
||||
icon: 'camera-o',
|
||||
},
|
||||
{
|
||||
id: '45',
|
||||
breadcrumbParentId: '4',
|
||||
menuParentId: '4',
|
||||
name: 'Editor',
|
||||
zhName: 'Editor',
|
||||
icon: 'edit',
|
||||
route: '/UIElement/editor',
|
||||
},
|
||||
{
|
||||
id: '5',
|
||||
breadcrumbParentId: '1',
|
||||
name: 'Charts',
|
||||
zhName: 'Charts',
|
||||
icon: 'code-o',
|
||||
},
|
||||
{
|
||||
id: '51',
|
||||
breadcrumbParentId: '5',
|
||||
menuParentId: '5',
|
||||
name: 'ECharts',
|
||||
zhName: 'ECharts',
|
||||
icon: 'line-chart',
|
||||
route: '/chart/ECharts',
|
||||
},
|
||||
{
|
||||
id: '52',
|
||||
breadcrumbParentId: '5',
|
||||
menuParentId: '5',
|
||||
name: 'HighCharts',
|
||||
zhName: 'HighCharts',
|
||||
icon: 'bar-chart',
|
||||
route: '/chart/highCharts',
|
||||
},
|
||||
{
|
||||
id: '53',
|
||||
breadcrumbParentId: '5',
|
||||
menuParentId: '5',
|
||||
name: 'Rechartst',
|
||||
zhName: 'Rechartst',
|
||||
icon: 'area-chart',
|
||||
route: '/chart/Recharts',
|
||||
},
|
||||
]
|
||||
|
||||
module.exports = {
|
||||
[`GET ${ApiPrefix}/routes`](req, res) {
|
||||
res.status(200).json(database)
|
||||
},
|
||||
}
|
||||
@@ -1,249 +0,0 @@
|
||||
import { Mock, Constant, qs, randomAvatar } from './_utils'
|
||||
|
||||
const { ApiPrefix } = Constant
|
||||
|
||||
let usersListData = Mock.mock({
|
||||
'data|80-100': [
|
||||
{
|
||||
id: '@id',
|
||||
name: '@name',
|
||||
nickName: '@last',
|
||||
phone: /^1[34578]\d{9}$/,
|
||||
'age|11-99': 1,
|
||||
address: '@county(true)',
|
||||
isMale: '@boolean',
|
||||
email: '@email',
|
||||
createTime: '@datetime',
|
||||
avatar() {
|
||||
return randomAvatar()
|
||||
},
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
let database = usersListData.data
|
||||
|
||||
const EnumRoleType = {
|
||||
ADMIN: 'admin',
|
||||
DEFAULT: 'guest',
|
||||
DEVELOPER: 'developer',
|
||||
}
|
||||
|
||||
const userPermission = {
|
||||
DEFAULT: {
|
||||
visit: ['1', '2', '21', '7', '5', '51', '52', '53'],
|
||||
role: EnumRoleType.DEFAULT,
|
||||
},
|
||||
ADMIN: {
|
||||
role: EnumRoleType.ADMIN,
|
||||
},
|
||||
DEVELOPER: {
|
||||
role: EnumRoleType.DEVELOPER,
|
||||
},
|
||||
}
|
||||
|
||||
const adminUsers = [
|
||||
{
|
||||
id: 0,
|
||||
username: 'admin',
|
||||
password: 'admin',
|
||||
permissions: userPermission.ADMIN,
|
||||
avatar: randomAvatar(),
|
||||
},
|
||||
{
|
||||
id: 1,
|
||||
username: 'guest',
|
||||
password: 'guest',
|
||||
permissions: userPermission.DEFAULT,
|
||||
avatar: randomAvatar(),
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
username: '吴彦祖',
|
||||
password: '123456',
|
||||
permissions: userPermission.DEVELOPER,
|
||||
avatar: randomAvatar(),
|
||||
},
|
||||
]
|
||||
|
||||
const queryArray = (array, key, keyAlias = 'key') => {
|
||||
if (!(array instanceof Array)) {
|
||||
return null
|
||||
}
|
||||
let data
|
||||
|
||||
for (let item of array) {
|
||||
if (item[keyAlias] === key) {
|
||||
data = item
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (data) {
|
||||
return data
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const NOTFOUND = {
|
||||
message: 'Not Found',
|
||||
documentation_url: 'http://localhost:8000/request',
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
[`POST ${ApiPrefix}/user/login`](req, res) {
|
||||
const { username, password } = req.body
|
||||
const user = adminUsers.filter(item => item.username === username)
|
||||
|
||||
if (user.length > 0 && user[0].password === password) {
|
||||
const now = new Date()
|
||||
now.setDate(now.getDate() + 1)
|
||||
res.cookie(
|
||||
'token',
|
||||
JSON.stringify({ id: user[0].id, deadline: now.getTime() }),
|
||||
{
|
||||
maxAge: 900000,
|
||||
httpOnly: true,
|
||||
}
|
||||
)
|
||||
res.json({ success: true, message: 'Ok' })
|
||||
} else {
|
||||
res.status(400).end()
|
||||
}
|
||||
},
|
||||
|
||||
[`GET ${ApiPrefix}/user/logout`](req, res) {
|
||||
res.clearCookie('token')
|
||||
res.status(200).end()
|
||||
},
|
||||
|
||||
[`GET ${ApiPrefix}/user`](req, res) {
|
||||
const cookie = req.headers.cookie || ''
|
||||
const cookies = qs.parse(cookie.replace(/\s/g, ''), { delimiter: ';' })
|
||||
const response = {}
|
||||
let user = {}
|
||||
if (!cookies.token) {
|
||||
res.status(200).send({ message: 'Not Login' })
|
||||
return
|
||||
}
|
||||
const token = JSON.parse(cookies.token)
|
||||
if (token) {
|
||||
response.success = token.deadline > new Date().getTime()
|
||||
}
|
||||
if (response.success) {
|
||||
const userItem = adminUsers.find(_ => _.id === token.id)
|
||||
if (userItem) {
|
||||
const { password, ...other } = userItem
|
||||
user = other
|
||||
}
|
||||
}
|
||||
response.user = user
|
||||
res.json(response)
|
||||
},
|
||||
|
||||
[`GET ${ApiPrefix}/users`](req, res) {
|
||||
const { query } = req
|
||||
let { pageSize, page, ...other } = query
|
||||
pageSize = pageSize || 10
|
||||
page = page || 1
|
||||
|
||||
let newData = database
|
||||
for (let key in other) {
|
||||
if ({}.hasOwnProperty.call(other, key)) {
|
||||
newData = newData.filter(item => {
|
||||
if ({}.hasOwnProperty.call(item, key)) {
|
||||
if (key === 'address') {
|
||||
return other[key].every(iitem => item[key].indexOf(iitem) > -1)
|
||||
} else if (key === 'createTime') {
|
||||
const start = new Date(other[key][0]).getTime()
|
||||
const end = new Date(other[key][1]).getTime()
|
||||
const now = new Date(item[key]).getTime()
|
||||
|
||||
if (start && end) {
|
||||
return now >= start && now <= end
|
||||
}
|
||||
return true
|
||||
}
|
||||
return (
|
||||
String(item[key])
|
||||
.trim()
|
||||
.indexOf(decodeURI(other[key]).trim()) > -1
|
||||
)
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
res.status(200).json({
|
||||
data: newData.slice((page - 1) * pageSize, page * pageSize),
|
||||
total: newData.length,
|
||||
})
|
||||
},
|
||||
|
||||
[`POST ${ApiPrefix}/users/delete`](req, res) {
|
||||
const { ids=[] } = req.body
|
||||
database = database.filter(item => !ids.some(_ => _ === item.id))
|
||||
res.status(204).end()
|
||||
},
|
||||
|
||||
[`POST ${ApiPrefix}/user`](req, res) {
|
||||
const newData = req.body
|
||||
newData.createTime = Mock.mock('@now')
|
||||
newData.avatar =
|
||||
newData.avatar ||
|
||||
Mock.Random.image(
|
||||
'100x100',
|
||||
Mock.Random.color(),
|
||||
'#757575',
|
||||
'png',
|
||||
newData.nickName.substr(0, 1)
|
||||
)
|
||||
newData.id = Mock.mock('@id')
|
||||
|
||||
database.unshift(newData)
|
||||
|
||||
res.status(200).end()
|
||||
},
|
||||
|
||||
[`GET ${ApiPrefix}/user/:id`](req, res) {
|
||||
const { id } = req.params
|
||||
const data = queryArray(database, id, 'id')
|
||||
if (data) {
|
||||
res.status(200).json(data)
|
||||
} else {
|
||||
res.status(200).json(NOTFOUND)
|
||||
}
|
||||
},
|
||||
|
||||
[`DELETE ${ApiPrefix}/user/:id`](req, res) {
|
||||
const { id } = req.params
|
||||
const data = queryArray(database, id, 'id')
|
||||
if (data) {
|
||||
database = database.filter(item => item.id !== id)
|
||||
res.status(204).end()
|
||||
} else {
|
||||
res.status(200).json(NOTFOUND)
|
||||
}
|
||||
},
|
||||
|
||||
[`PATCH ${ApiPrefix}/user/:id`](req, res) {
|
||||
const { id } = req.params
|
||||
const editItem = req.body
|
||||
let isExist = false
|
||||
|
||||
database = database.map(item => {
|
||||
if (item.id === id) {
|
||||
isExist = true
|
||||
return Object.assign({}, item, editItem)
|
||||
}
|
||||
return item
|
||||
})
|
||||
|
||||
if (isExist) {
|
||||
res.status(201).end()
|
||||
} else {
|
||||
res.status(200).json(NOTFOUND)
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -1,115 +1,56 @@
|
||||
{
|
||||
"name": "antd-admin",
|
||||
"version": "5.0.1",
|
||||
"private": true,
|
||||
"version": "6.0.0",
|
||||
"description": "An admin dashboard application demo built upon Ant Design and UmiJS",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"build": "umi build",
|
||||
"dev": "umi dev",
|
||||
"test": "jest",
|
||||
"test:watch": "jest --watch",
|
||||
"format": "prettier --write .",
|
||||
"lint": "eslint --ext .ts,.tsx src",
|
||||
"lint:fix": "eslint --ext .ts,.tsx src --fix",
|
||||
"start": "npm run dev"
|
||||
},
|
||||
"dependencies": {
|
||||
"@lingui/react": "^2.7.1",
|
||||
"ant-design-pro": "^2.1.1",
|
||||
"antd": "^3.10.7",
|
||||
"axios": "^0.18.0",
|
||||
"babel-core": "7.0.0-bridge.0",
|
||||
"classnames": "^2.2.6",
|
||||
"d3-shape": "^1.2.2",
|
||||
"draftjs-to-html": "^0.8.4",
|
||||
"draftjs-to-markdown": "^0.5.1",
|
||||
"dva-model-extend": "^0.1.2",
|
||||
"echarts": "^4.2.0-rc.2",
|
||||
"echarts-for-react": "^2.0.15-beta.0",
|
||||
"echarts-gl": "^1.1.1",
|
||||
"echarts-liquidfill": "^2.0.2",
|
||||
"enquire-js": "^0.2.1",
|
||||
"highcharts-exporting": "^0.1.7",
|
||||
"highcharts-more": "^0.1.7",
|
||||
"json-format": "^1.0.1",
|
||||
"lodash": "^4.17.11",
|
||||
"md5": "^2.2.1",
|
||||
"nprogress": "^0.2.0",
|
||||
"path-to-regexp": "^2.4.0",
|
||||
"prop-types": "^15.6.2",
|
||||
"qs": "^6.5.2",
|
||||
"rc-tween-one": "^2.2.17",
|
||||
"react-adsense": "^0.0.6",
|
||||
"react-countup": "^4.0.0-alpha.6",
|
||||
"react-draft-wysiwyg": "^1.12.13",
|
||||
"react-helmet": "^5.2.0",
|
||||
"react-highcharts": "^16.0.2",
|
||||
"react-perfect-scrollbar": "^1.4.2",
|
||||
"recharts": "^1.3.6",
|
||||
"store": "^2.0.12"
|
||||
"@ant-design/icons": "^6.1.0",
|
||||
"@ant-design/x": "^2.3.0",
|
||||
"@ant-design/x-sdk": "^2.3.0",
|
||||
"@umijs/plugins": "^4.6.32",
|
||||
"antd": "^6.3.2",
|
||||
"react": "^19.2.4",
|
||||
"react-dom": "^19.2.4",
|
||||
"umi": "^4.6.32",
|
||||
"zustand": "^5.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@lingui/babel-preset-react": "^2.7.1",
|
||||
"@lingui/cli": "^2.7.1",
|
||||
"@lingui/loader": "^2.7.1",
|
||||
"babel-eslint": "^10.0.1",
|
||||
"babel-plugin-dev-expression": "^0.2.1",
|
||||
"babel-plugin-import": "^1.10.0",
|
||||
"babel-plugin-macros": "^2.4.2",
|
||||
"babel-plugin-module-resolver": "^3.1.1",
|
||||
"cross-env": "^5.2.0",
|
||||
"eslint": "^5.9.0",
|
||||
"eslint-config-react-app": "^3.0.5",
|
||||
"eslint-plugin-flowtype": "^3.0.0",
|
||||
"eslint-plugin-import": "^2.6.0",
|
||||
"eslint-plugin-jsx-a11y": "^6.1.1",
|
||||
"eslint-plugin-react": "^7.1.0",
|
||||
"husky": "^1.1.4",
|
||||
"less-vars-to-js": "^1.3.0",
|
||||
"lint-staged": "^8.0.4",
|
||||
"mockjs": "^1.0.1-beta3",
|
||||
"module": "^1.2.5",
|
||||
"prettier": "^1.15.2",
|
||||
"stylelint": "^9.8.0",
|
||||
"stylelint-config-prettier": "^4.0.0",
|
||||
"stylelint-config-standard": "^18.2.0",
|
||||
"umi": "^2.2.8",
|
||||
"umi-plugin-react": "^1.2.3"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"puppeteer": "^1.10.0"
|
||||
},
|
||||
"lint-staged": {
|
||||
"src/**/*.js": [
|
||||
"eslint --ext .js --fix",
|
||||
"npm run prettier",
|
||||
"git add"
|
||||
],
|
||||
"**/*.less": [
|
||||
"stylelint --syntax less",
|
||||
"npm run prettier",
|
||||
"git add"
|
||||
]
|
||||
},
|
||||
"lingui": {
|
||||
"fallbackLocale": "en",
|
||||
"sourceLocale": "en",
|
||||
"localeDir": "src/locales",
|
||||
"srcPathDirs": [
|
||||
"src/pages",
|
||||
"src/layouts",
|
||||
"src/components",
|
||||
"src/layouts"
|
||||
],
|
||||
"format": "minimal",
|
||||
"extractBabelOptions": {
|
||||
"presets": [
|
||||
"umi/babel"
|
||||
]
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"analyze": "cross-env ANALYZE=1 umi build",
|
||||
"build": "umi build",
|
||||
"lint:js": "eslint --ext .js src",
|
||||
"lint:style": "stylelint \"src/**/*.less\" --syntax less",
|
||||
"start": "umi dev",
|
||||
"test": "cross-env BABELRC=none umi test",
|
||||
"prettier": "prettier --write 'src/**/*.(js|less)'",
|
||||
"precommit": "lint-staged",
|
||||
"add-locale": "lingui add-locale",
|
||||
"extract": "lingui extract",
|
||||
"trans": "lingui extract --clean && node ./scripts/translate.js",
|
||||
"doc": "docsify serve docs"
|
||||
"@testing-library/jest-dom": "^6.1.1",
|
||||
"@testing-library/react": "^14.0.0",
|
||||
"@types/jest": "^29.5.3",
|
||||
"@types/react": "19.2.14",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@typescript-eslint/eslint-plugin": "^6.9.0",
|
||||
"@typescript-eslint/parser": "^6.9.0",
|
||||
"@umijs/test": "^4.6.32",
|
||||
"eslint": "^8.47.0",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"eslint-import-resolver-typescript": "^4.4.4",
|
||||
"eslint-plugin-import": "^2.29.1",
|
||||
"eslint-plugin-jsx-a11y": "^6.7.1",
|
||||
"eslint-plugin-prettier": "^5.1.0",
|
||||
"eslint-plugin-react": "^7.33.2",
|
||||
"eslint-plugin-react-hooks": "^4.6.0",
|
||||
"eslint-plugin-unused-imports": "^2.0.0",
|
||||
"jest": "^29.6.1",
|
||||
"mockjs": "^1.1.0",
|
||||
"prettier": "^2.8.8",
|
||||
"prettier-plugin-organize-imports": "^3.2.2",
|
||||
"prettier-plugin-packagejson": "^2.4.3",
|
||||
"ts-jest": "^29.1.0",
|
||||
"ts-node": "^10.9.2",
|
||||
"typescript": "^5.9.3",
|
||||
"jest-environment-jsdom": "^29.6.1",
|
||||
"jsdom": "^21.1.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
<?xml version="1.0" encoding="iso-8859-1"?>
|
||||
<!-- Generator: Adobe Illustrator 19.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
|
||||
<svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
|
||||
viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve">
|
||||
<rect style="fill:#F0F0F0;" width="512" height="512"/>
|
||||
<g>
|
||||
<rect y="64" style="fill:#D80027;" width="512" height="64"/>
|
||||
<rect y="192" style="fill:#D80027;" width="512" height="64"/>
|
||||
<rect y="320" style="fill:#D80027;" width="512" height="64"/>
|
||||
<rect y="448" style="fill:#D80027;" width="512" height="64"/>
|
||||
</g>
|
||||
<rect style="fill:#2E52B2;" width="256" height="275.69"/>
|
||||
<g>
|
||||
<polygon style="fill:#F0F0F0;" points="51.518,115.318 45.924,132.529 27.826,132.529 42.469,143.163 36.875,160.375
|
||||
51.518,149.741 66.155,160.375 60.56,143.163 75.203,132.529 57.106,132.529 "/>
|
||||
<polygon style="fill:#F0F0F0;" points="57.106,194.645 51.518,177.434 45.924,194.645 27.826,194.645 42.469,205.279
|
||||
36.875,222.49 51.518,211.857 66.155,222.49 60.56,205.279 75.203,194.645 "/>
|
||||
<polygon style="fill:#F0F0F0;" points="51.518,53.202 45.924,70.414 27.826,70.414 42.469,81.047 36.875,98.259 51.518,87.625
|
||||
66.155,98.259 60.56,81.047 75.203,70.414 57.106,70.414 "/>
|
||||
<polygon style="fill:#F0F0F0;" points="128.003,115.318 122.409,132.529 104.311,132.529 118.954,143.163 113.36,160.375
|
||||
128.003,149.741 142.64,160.375 137.045,143.163 151.689,132.529 133.591,132.529 "/>
|
||||
<polygon style="fill:#F0F0F0;" points="133.591,194.645 128.003,177.434 122.409,194.645 104.311,194.645 118.954,205.279
|
||||
113.36,222.49 128.003,211.857 142.64,222.49 137.045,205.279 151.689,194.645 "/>
|
||||
<polygon style="fill:#F0F0F0;" points="210.076,194.645 204.489,177.434 198.894,194.645 180.797,194.645 195.44,205.279
|
||||
189.845,222.49 204.489,211.857 219.125,222.49 213.531,205.279 228.174,194.645 "/>
|
||||
<polygon style="fill:#F0F0F0;" points="204.489,115.318 198.894,132.529 180.797,132.529 195.44,143.163 189.845,160.375
|
||||
204.489,149.741 219.125,160.375 213.531,143.163 228.174,132.529 210.076,132.529 "/>
|
||||
<polygon style="fill:#F0F0F0;" points="128.003,53.202 122.409,70.414 104.311,70.414 118.954,81.047 113.36,98.259
|
||||
128.003,87.625 142.64,98.259 137.045,81.047 151.689,70.414 133.591,70.414 "/>
|
||||
<polygon style="fill:#F0F0F0;" points="204.489,53.202 198.894,70.414 180.797,70.414 195.44,81.047 189.845,98.259
|
||||
204.489,87.625 219.125,98.259 213.531,81.047 228.174,70.414 210.076,70.414 "/>
|
||||
</g>
|
||||
<g>
|
||||
</g>
|
||||
<g>
|
||||
</g>
|
||||
<g>
|
||||
</g>
|
||||
<g>
|
||||
</g>
|
||||
<g>
|
||||
</g>
|
||||
<g>
|
||||
</g>
|
||||
<g>
|
||||
</g>
|
||||
<g>
|
||||
</g>
|
||||
<g>
|
||||
</g>
|
||||
<g>
|
||||
</g>
|
||||
<g>
|
||||
</g>
|
||||
<g>
|
||||
</g>
|
||||
<g>
|
||||
</g>
|
||||
<g>
|
||||
</g>
|
||||
<g>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 2.7 KiB |
@@ -1,23 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generator: Adobe Illustrator 19.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
|
||||
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
|
||||
viewBox="-49 141 512 512" style="enable-background:new -49 141 512 512;" xml:space="preserve">
|
||||
<style type="text/css">
|
||||
.st0{fill:#D80027;}
|
||||
.st1{fill:#FFDA44;}
|
||||
</style>
|
||||
<rect x="-49" y="141" class="st0" width="512" height="512"/>
|
||||
|
||||
<g>
|
||||
<polygon class="st1" points="91.1,296.8 113.2,364.8 184.7,364.8 126.9,406.9 149,474.9 91.1,432.9 33.2,474.9 55.4,406.9
|
||||
-2.5,364.8 69,364.8 "/>
|
||||
<polygon class="st1" points="254.5,537.5 237.6,516.7 212.6,526.4 227.1,503.9 210.2,483 236.1,489.9 250.7,467.4 252.1,494.2
|
||||
278.1,501.1 253,510.7 "/>
|
||||
<polygon class="st1" points="288.1,476.5 296.1,450.9 274.2,435.4 301,435 308.9,409.4 317.6,434.8 344.4,434.5 322.9,450.5
|
||||
331.5,475.9 309.6,460.4 "/>
|
||||
<polygon class="st1" points="333.4,328.9 321.6,353 340.8,371.7 314.3,367.9 302.5,391.9 297.9,365.5 271.3,361.7 295.1,349.2
|
||||
290.5,322.7 309.7,341.4 "/>
|
||||
<polygon class="st1" points="255.2,255.9 253.2,282.6 278.1,292.7 252,299.1 250.1,325.9 236,303.1 209.9,309.5 227.2,289
|
||||
213,266.3 237.9,276.4 "/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 1.3 KiB |
|
After Width: | Height: | Size: 3.1 KiB |
|
After Width: | Height: | Size: 3.5 KiB |
|
After Width: | Height: | Size: 3.9 KiB |
|
After Width: | Height: | Size: 4.7 KiB |
|
After Width: | Height: | Size: 9.7 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 2.4 KiB |
@@ -1,114 +0,0 @@
|
||||
/**
|
||||
* Youdao Translate, My private account is for testing purposes only.
|
||||
* Please go to the official account to apply for an account. Thank you for your cooperation.
|
||||
* APP ID:055c2d71f9a05214
|
||||
* Secret key:ZcpuQxQW3NkQeKVkqrXIKQYXH57g2KuN
|
||||
*/
|
||||
|
||||
/* eslint-disable */
|
||||
const md5 = require('md5')
|
||||
const qs = require('qs')
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
const axios = require('axios')
|
||||
const jsonFormat = require('json-format')
|
||||
const { i18n } = require('../src/utils/config')
|
||||
const { languages, defaultLanguage } = i18n
|
||||
|
||||
const locales = {}
|
||||
|
||||
languages.forEach(item => {
|
||||
locales[item.key] = require(`../src/locales/${item.key}/messages.json`)
|
||||
})
|
||||
|
||||
const youdao = ({ q, from, to }) =>
|
||||
new Promise((resolve, reject) => {
|
||||
{
|
||||
const appid = '055c2d71f9a05214'
|
||||
const appse = 'ZcpuQxQW3NkQeKVkqrXIKQYXH57g2KuN'
|
||||
const salt = Date.now()
|
||||
|
||||
const sign = md5(appid + q + salt + appse)
|
||||
const query = qs.stringify({
|
||||
q,
|
||||
from,
|
||||
to,
|
||||
appKey: appid,
|
||||
salt,
|
||||
sign,
|
||||
})
|
||||
|
||||
axios.get(`http://openapi.youdao.com/api?${query}`).then(({ data }) => {
|
||||
if (data.query && data.translation[0]) {
|
||||
resolve(data.translation[0])
|
||||
} else {
|
||||
resolve(q)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
const transform = async ({ from, to, locales, outputPath }) => {
|
||||
for (const key in locales[from]) {
|
||||
if (locales[to][key]) {
|
||||
console.log(`add to skip: ${key}`)
|
||||
} else {
|
||||
let res = key
|
||||
let way = 'youdao'
|
||||
if (key.indexOf('/') !== 0) {
|
||||
const reg = '{([^{}]*)}'
|
||||
const tasks = key
|
||||
.match(new RegExp(`${reg}|((?<=(${reg}|^)).*?(?=(${reg}|$)))`, 'g'))
|
||||
.map(item => {
|
||||
if (new RegExp(reg).test(item)) {
|
||||
return Promise.resolve(item)
|
||||
}
|
||||
return youdao({
|
||||
q: item,
|
||||
from,
|
||||
to,
|
||||
})
|
||||
})
|
||||
|
||||
res = (await Promise.all(tasks)).join('')
|
||||
} else {
|
||||
res = `/${to + key}`
|
||||
way = 'link'
|
||||
}
|
||||
if (res !== key) {
|
||||
locales[to][key] = res
|
||||
console.log(`${way}: ${from} -> ${to}: ${key} -> ${res}`)
|
||||
} else {
|
||||
console.log(`same: ${from} -> ${to}: ${key}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
await fs.writeFileSync(
|
||||
path.resolve(__dirname, outputPath),
|
||||
jsonFormat(locales[to], {
|
||||
type: 'space',
|
||||
size: 2,
|
||||
})
|
||||
)
|
||||
}
|
||||
;(async () => {
|
||||
const tasks = languages
|
||||
.map(item => ({
|
||||
from: defaultLanguage,
|
||||
to: item.key,
|
||||
}))
|
||||
.filter(item => item.from !== item.to)
|
||||
|
||||
for (const item of tasks) {
|
||||
console.log(`start: ${item.from} -> ${item.to}`)
|
||||
await transform({
|
||||
from: item.from,
|
||||
to: item.to,
|
||||
locales,
|
||||
outputPath: `../src/locales/${item.to}/messages.json`,
|
||||
})
|
||||
console.log(`completed: ${item.from} -> ${item.to}`)
|
||||
}
|
||||
|
||||
console.log('All translations have been completed.')
|
||||
})()
|
||||
@@ -0,0 +1,82 @@
|
||||
import { ConfigProvider } from 'antd';
|
||||
import 'antd/dist/reset.css';
|
||||
import enUS from 'antd/locale/en_US';
|
||||
import zhCN from 'antd/locale/zh_CN';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
|
||||
import AuthGate from './components/AuthGate';
|
||||
|
||||
function LocaleWrapper({ children }: { children: React.ReactElement }) {
|
||||
// read initial locale synchronously so Antd has correct locale on first render
|
||||
const pick = (l: string | null) => {
|
||||
if (l === 'zh-CN') return zhCN;
|
||||
return enUS;
|
||||
};
|
||||
let initial: typeof zhCN | typeof enUS | undefined = undefined;
|
||||
const stored = window.localStorage.getItem('umi_locale') || null;
|
||||
initial = pick(stored);
|
||||
|
||||
const [locale, setLocale] = useState<typeof zhCN | typeof enUS | undefined>(
|
||||
initial,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const read = () => {
|
||||
let l: string | null = null;
|
||||
try {
|
||||
l = window.localStorage.getItem('umi_locale') || null;
|
||||
} catch (e) {
|
||||
l = null;
|
||||
}
|
||||
setLocale(pick(l));
|
||||
};
|
||||
|
||||
const onStorage = (ev: StorageEvent) => {
|
||||
if (ev.key === 'umi_locale') read();
|
||||
};
|
||||
|
||||
const onLocaleChange = (ev: Event) => {
|
||||
// CustomEvent used by TopbarControls with detail = locale string
|
||||
const possible = ev as CustomEvent | Event;
|
||||
if (possible && typeof (possible as CustomEvent).detail !== 'undefined') {
|
||||
const d = (possible as CustomEvent).detail;
|
||||
if (d) setLocale(pick(String(d)));
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('storage', onStorage);
|
||||
window.addEventListener('localechange', onLocaleChange as EventListener);
|
||||
return () => {
|
||||
window.removeEventListener('storage', onStorage);
|
||||
window.removeEventListener(
|
||||
'localechange',
|
||||
onLocaleChange as EventListener,
|
||||
);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return <ConfigProvider locale={locale}>{children}</ConfigProvider>;
|
||||
}
|
||||
|
||||
export function rootContainer(container: React.ReactElement) {
|
||||
return (
|
||||
<LocaleWrapper>
|
||||
<AuthGate>{container}</AuthGate>
|
||||
</LocaleWrapper>
|
||||
);
|
||||
}
|
||||
|
||||
// ensure mobile viewport meta exists (adds meta tag if not present)
|
||||
try {
|
||||
if (typeof window !== 'undefined') {
|
||||
const hasVp = document.querySelector('meta[name="viewport"]');
|
||||
if (!hasVp) {
|
||||
const m = document.createElement('meta');
|
||||
m.name = 'viewport';
|
||||
m.content = 'width=device-width,initial-scale=1,maximum-scale=1';
|
||||
document.head.appendChild(m);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// ignore in non-DOM environments
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { Spin } from 'antd';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { history } from 'umi';
|
||||
|
||||
import useGlobalSync from '@/hooks/useGlobalSync';
|
||||
import useIsMounted from '@/hooks/useIsMounted';
|
||||
import adminService from '../services/admin';
|
||||
|
||||
import useGlobalStore from '../store/useGlobalStore';
|
||||
|
||||
export default function AuthGate({ children }: { children: React.ReactNode }) {
|
||||
const isLoggedIn = useGlobalSync((s) => s.isLoggedIn);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const isMounted = useIsMounted();
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
try {
|
||||
const admin = (await adminService.currentAdmin()) as
|
||||
| import('@/types/admin').Admin
|
||||
| undefined;
|
||||
if (!isMounted()) return;
|
||||
if (admin) {
|
||||
useGlobalStore.getState().login();
|
||||
useGlobalStore.getState().setCurrentUser(admin);
|
||||
} else {
|
||||
useGlobalStore.getState().logout();
|
||||
}
|
||||
} catch (e) {
|
||||
useGlobalStore.getState().logout();
|
||||
} finally {
|
||||
if (isMounted()) setLoading(false);
|
||||
}
|
||||
})();
|
||||
}, [isMounted]);
|
||||
|
||||
useEffect(() => {
|
||||
const path = history.location.pathname;
|
||||
if (!isLoggedIn && path !== '/login') {
|
||||
history.replace('/login');
|
||||
}
|
||||
if (isLoggedIn && path === '/login') {
|
||||
history.replace('/');
|
||||
}
|
||||
}, [isLoggedIn]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
minHeight: '100vh',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
>
|
||||
<Spin size="large" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import React from 'react';
|
||||
import DropOption from './DropOption';
|
||||
|
||||
// Mock antd Dropdown to expose menu items for testing
|
||||
jest.mock('antd', () => {
|
||||
return {
|
||||
Dropdown: ({ menu, children }: any) =>
|
||||
React.createElement(
|
||||
'div',
|
||||
null,
|
||||
React.createElement('div', { 'data-testid': 'trigger' }, children),
|
||||
React.createElement(
|
||||
'div',
|
||||
{ 'data-testid': 'menu' },
|
||||
menu?.items?.map((it: any) =>
|
||||
React.createElement(
|
||||
'button',
|
||||
{
|
||||
key: it.key,
|
||||
'data-key': it.key,
|
||||
onClick: () => menu.onClick?.({ key: it.key }),
|
||||
},
|
||||
typeof it.label === 'string'
|
||||
? it.label
|
||||
: React.createElement('span', null, it.label),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
};
|
||||
});
|
||||
|
||||
jest.mock('@ant-design/icons', () => ({
|
||||
BarsOutlined: () => React.createElement('span', null, 'Bars'),
|
||||
DownOutlined: () => React.createElement('span', null, 'Down'),
|
||||
}));
|
||||
|
||||
test('renders default trigger when no children provided', () => {
|
||||
render(<DropOption menuOptions={[]} />);
|
||||
const trigger = screen.getByTestId('trigger');
|
||||
// default trigger in component is an <a>
|
||||
expect(trigger.querySelector('a')).toBeTruthy();
|
||||
});
|
||||
|
||||
test('wraps plain text children in a span', () => {
|
||||
render(<DropOption menuOptions={[]}>PlainChild</DropOption>);
|
||||
const trigger = screen.getByTestId('trigger');
|
||||
expect(screen.getByText('PlainChild')).toBeTruthy();
|
||||
expect(trigger.firstElementChild?.tagName.toLowerCase()).toBe('span');
|
||||
});
|
||||
|
||||
test('clicking menu item calls onMenuClick with key', () => {
|
||||
const onMenuClick = jest.fn();
|
||||
render(
|
||||
<DropOption
|
||||
menuOptions={[{ key: 'one', label: 'One' }]}
|
||||
onMenuClick={onMenuClick}
|
||||
/>,
|
||||
);
|
||||
const item = screen.getByText('One');
|
||||
fireEvent.click(item);
|
||||
expect(onMenuClick).toHaveBeenCalledWith('one');
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import { BarsOutlined, DownOutlined } from '@ant-design/icons';
|
||||
import { Dropdown } from 'antd';
|
||||
import React from 'react';
|
||||
|
||||
type Option = { key: string; label: React.ReactNode };
|
||||
|
||||
interface DropOptionProps {
|
||||
menuOptions: Option[];
|
||||
onMenuClick?: (key: string) => void;
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
const DropOption: React.FC<DropOptionProps> = ({
|
||||
menuOptions,
|
||||
onMenuClick,
|
||||
children,
|
||||
}) => {
|
||||
const items = menuOptions.map((o) => ({ key: o.key, label: o.label }));
|
||||
|
||||
const menu = {
|
||||
items,
|
||||
onClick: ({ key }: { key: string }) => onMenuClick?.(key),
|
||||
};
|
||||
|
||||
// ensure Dropdown receives a single React element as child
|
||||
let triggerNode: React.ReactElement;
|
||||
if (React.Children.count(children) === 1 && React.isValidElement(children)) {
|
||||
triggerNode = children as React.ReactElement;
|
||||
} else if (children) {
|
||||
// wrap non-element children (like plain text) in a span
|
||||
triggerNode = <span>{children}</span>;
|
||||
} else {
|
||||
triggerNode = (
|
||||
<a onClick={(e) => e.preventDefault()}>
|
||||
<BarsOutlined style={{ marginRight: 2 }} />
|
||||
<DownOutlined />
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Dropdown menu={menu} trigger={['click']}>
|
||||
{triggerNode}
|
||||
</Dropdown>
|
||||
);
|
||||
};
|
||||
|
||||
export default DropOption;
|
||||
@@ -1,34 +0,0 @@
|
||||
import React from 'react'
|
||||
import PropTypes from 'prop-types'
|
||||
import { Dropdown, Button, Icon, Menu } from 'antd'
|
||||
|
||||
const DropOption = ({
|
||||
onMenuClick,
|
||||
menuOptions = [],
|
||||
buttonStyle,
|
||||
dropdownProps,
|
||||
}) => {
|
||||
const menu = menuOptions.map(item => (
|
||||
<Menu.Item key={item.key}>{item.name}</Menu.Item>
|
||||
))
|
||||
return (
|
||||
<Dropdown
|
||||
overlay={<Menu onClick={onMenuClick}>{menu}</Menu>}
|
||||
{...dropdownProps}
|
||||
>
|
||||
<Button style={{ border: 'none', ...buttonStyle }}>
|
||||
<Icon style={{ marginRight: 2 }} type="bars" />
|
||||
<Icon type="down" />
|
||||
</Button>
|
||||
</Dropdown>
|
||||
)
|
||||
}
|
||||
|
||||
DropOption.propTypes = {
|
||||
onMenuClick: PropTypes.func,
|
||||
menuOptions: PropTypes.array.isRequired,
|
||||
buttonStyle: PropTypes.object,
|
||||
dropdownProps: PropTypes.object,
|
||||
}
|
||||
|
||||
export default DropOption
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"name": "DropOption",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"main": "./DropOption.js"
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
import React from 'react'
|
||||
import { Editor } from 'react-draft-wysiwyg'
|
||||
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css'
|
||||
import styles from './Editor.less'
|
||||
|
||||
const DraftEditor = props => {
|
||||
return (
|
||||
<Editor
|
||||
toolbarClassName={styles.toolbar}
|
||||
wrapperClassName={styles.wrapper}
|
||||
editorClassName={styles.editor}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default DraftEditor
|
||||
@@ -1,106 +0,0 @@
|
||||
.wrapper {
|
||||
height: 500px;
|
||||
|
||||
:global {
|
||||
.rdw-dropdownoption-default {
|
||||
padding: 6px;
|
||||
}
|
||||
|
||||
.rdw-dropdown-optionwrapper {
|
||||
box-sizing: content-box;
|
||||
width: 100%;
|
||||
border-radius: 0 0 2px 2px;
|
||||
&:hover {
|
||||
box-shadow: none;
|
||||
}
|
||||
}
|
||||
|
||||
.rdw-inline-wrapper {
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 0;
|
||||
|
||||
.rdw-option-wrapper {
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
}
|
||||
|
||||
.rdw-option-active {
|
||||
box-shadow: 1px 1px 0 #e8e8e8 inset;
|
||||
}
|
||||
|
||||
.rdw-colorpicker-option {
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.rdw-colorpicker-modal,
|
||||
.rdw-embedded-modal,
|
||||
.rdw-emoji-modal,
|
||||
.rdw-image-modal,
|
||||
.rdw-link-modal {
|
||||
box-shadow: 4px 4px 40px rgba(0, 0, 0, 0.05);
|
||||
}
|
||||
|
||||
.rdw-colorpicker-modal,
|
||||
.rdw-embedded-modal,
|
||||
.rdw-link-modal {
|
||||
height: auto;
|
||||
}
|
||||
|
||||
.rdw-emoji-modal {
|
||||
width: 214px;
|
||||
}
|
||||
|
||||
.rdw-colorpicker-modal {
|
||||
width: auto;
|
||||
}
|
||||
|
||||
.rdw-embedded-modal-btn,
|
||||
.rdw-image-modal-btn,
|
||||
.rdw-link-modal-btn {
|
||||
height: 32px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.rdw-embedded-modal-input,
|
||||
.rdw-embedded-modal-size-input,
|
||||
.rdw-link-modal-input {
|
||||
padding: 2px 6px;
|
||||
height: 32px;
|
||||
}
|
||||
|
||||
.rdw-dropdown-selectedtext {
|
||||
color: #000;
|
||||
}
|
||||
|
||||
.rdw-dropdown-wrapper,
|
||||
.rdw-option-wrapper {
|
||||
min-width: 36px;
|
||||
transition: all 0.2s ease;
|
||||
height: 30px;
|
||||
|
||||
&:active {
|
||||
box-shadow: 1px 1px 0 #e8e8e8 inset;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
box-shadow: 1px 1px 0 #e8e8e8;
|
||||
}
|
||||
}
|
||||
|
||||
.rdw-dropdown-wrapper {
|
||||
min-width: 60px;
|
||||
}
|
||||
|
||||
.rdw-editor-main {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
}
|
||||
|
||||
.editor {
|
||||
border: 1px solid #f1f1f1;
|
||||
padding: 5px;
|
||||
border-radius: 2px;
|
||||
height: auto;
|
||||
min-height: 200px;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"name": "Editor",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"main": "./Editor.js"
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
import React from 'react'
|
||||
import PropTypes from 'prop-types'
|
||||
import styles from './FilterItem.less'
|
||||
|
||||
const FilterItem = ({ label = '', children }) => {
|
||||
const labelArray = label.split('')
|
||||
return (
|
||||
<div className={styles.filterItem}>
|
||||
{labelArray.length > 0 ? (
|
||||
<div className={styles.labelWrap}>
|
||||
{labelArray.map((item, index) => (
|
||||
<span className="labelText" key={index}>
|
||||
{item}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
''
|
||||
)}
|
||||
<div className={styles.item}>{children}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
FilterItem.propTypes = {
|
||||
label: PropTypes.string,
|
||||
children: PropTypes.element.isRequired,
|
||||
}
|
||||
|
||||
export default FilterItem
|
||||
@@ -1,17 +0,0 @@
|
||||
.filterItem {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
|
||||
.labelWrap {
|
||||
width: 64px;
|
||||
line-height: 28px;
|
||||
margin-right: 12px;
|
||||
justify-content: space-between;
|
||||
display: flex;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.item {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"name": "FilterItem",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"main": "./FilterItem.js"
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import React from 'react';
|
||||
|
||||
interface LinkItem {
|
||||
title: string;
|
||||
href: string;
|
||||
}
|
||||
|
||||
interface GlobalFooterProps {
|
||||
links?: LinkItem[];
|
||||
copyright?: React.ReactNode;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const GlobalFooter: React.FC<GlobalFooterProps> = ({
|
||||
links = [],
|
||||
copyright,
|
||||
}) => {
|
||||
return (
|
||||
<footer style={{ textAlign: 'center', padding: '24px 0', color: '#666' }}>
|
||||
{links.length > 0 && (
|
||||
<div style={{ marginBottom: 8 }}>
|
||||
{links.map((l, i) => (
|
||||
<a key={i} href={l.href} style={{ margin: '0 8px' }}>
|
||||
{l.title}
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div>{copyright ?? `© ${new Date().getFullYear()}`}</div>
|
||||
</footer>
|
||||
);
|
||||
};
|
||||
|
||||
export default GlobalFooter;
|
||||
@@ -0,0 +1,33 @@
|
||||
import {
|
||||
AppstoreOutlined,
|
||||
HomeOutlined,
|
||||
InfoCircleOutlined,
|
||||
ProfileOutlined,
|
||||
RobotOutlined,
|
||||
SettingOutlined,
|
||||
TeamOutlined,
|
||||
ToolOutlined,
|
||||
UserAddOutlined,
|
||||
UserOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import React from 'react';
|
||||
|
||||
export const ICON_MAP: Record<string, React.ReactNode> = {
|
||||
home: <HomeOutlined />,
|
||||
'info-c': <InfoCircleOutlined />,
|
||||
user: <UserOutlined />,
|
||||
team: <TeamOutlined />,
|
||||
profile: <ProfileOutlined />,
|
||||
'user-add': <UserAddOutlined />,
|
||||
settings: <SettingOutlined />,
|
||||
tool: <ToolOutlined />,
|
||||
robot: <RobotOutlined />,
|
||||
'app-store': <AppstoreOutlined />,
|
||||
};
|
||||
|
||||
export function Icon({ name }: { name?: string }) {
|
||||
if (!name) return null;
|
||||
return ICON_MAP[name] || null;
|
||||
}
|
||||
|
||||
export default Icon;
|
||||
@@ -1,66 +0,0 @@
|
||||
import React, { PureComponent, Fragment } from 'react'
|
||||
import PropTypes from 'prop-types'
|
||||
import { Breadcrumb, Icon } from 'antd'
|
||||
import Link from 'umi/navlink'
|
||||
import withRouter from 'umi/withRouter'
|
||||
import { withI18n } from '@lingui/react'
|
||||
import { pathMatchRegexp, queryAncestors } from 'utils'
|
||||
import styles from './Bread.less'
|
||||
|
||||
@withI18n()
|
||||
@withRouter
|
||||
class Bread extends PureComponent {
|
||||
generateBreadcrumbs = paths => {
|
||||
return paths.map((item, key) => {
|
||||
const content = (
|
||||
<Fragment>
|
||||
{item.icon ? (
|
||||
<Icon type={item.icon} style={{ marginRight: 4 }} />
|
||||
) : null}
|
||||
{item.name}
|
||||
</Fragment>
|
||||
)
|
||||
|
||||
return (
|
||||
<Breadcrumb.Item key={key}>
|
||||
{paths.length - 1 !== key ? (
|
||||
<Link to={item.route || '#'}>{content}</Link>
|
||||
) : (
|
||||
content
|
||||
)}
|
||||
</Breadcrumb.Item>
|
||||
)
|
||||
})
|
||||
}
|
||||
render() {
|
||||
const { routeList, location, i18n } = this.props
|
||||
|
||||
// Find a route that matches the pathname.
|
||||
const currentRoute = routeList.find(
|
||||
_ => _.route && pathMatchRegexp(_.route, location.pathname)
|
||||
)
|
||||
|
||||
// Find the breadcrumb navigation of the current route match and all its ancestors.
|
||||
const paths = currentRoute
|
||||
? queryAncestors(routeList, currentRoute, 'breadcrumbParentId').reverse()
|
||||
: [
|
||||
routeList[0],
|
||||
{
|
||||
id: 404,
|
||||
name: i18n.t`Not Found`,
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<Breadcrumb className={styles.bread}>
|
||||
{this.generateBreadcrumbs(paths)}
|
||||
</Breadcrumb>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Bread.propTypes = {
|
||||
routeList: PropTypes.array,
|
||||
}
|
||||
|
||||
export default Bread
|
||||
@@ -1,16 +0,0 @@
|
||||
.bread {
|
||||
margin-bottom: 24px;
|
||||
|
||||
:global {
|
||||
.ant-breadcrumb {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
.bread {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
}
|
||||
@@ -1,174 +0,0 @@
|
||||
import React, { PureComponent, Fragment } from 'react'
|
||||
import PropTypes from 'prop-types'
|
||||
import { Menu, Icon, Layout, Avatar, Popover, Badge, List } from 'antd'
|
||||
import { Ellipsis } from 'ant-design-pro'
|
||||
import { Trans, withI18n } from '@lingui/react'
|
||||
import { setLocale } from 'utils'
|
||||
import moment from 'moment'
|
||||
import classnames from 'classnames'
|
||||
import config from 'config'
|
||||
import styles from './Header.less'
|
||||
|
||||
const { SubMenu } = Menu
|
||||
|
||||
@withI18n()
|
||||
class Header extends PureComponent {
|
||||
handleClickMenu = e => {
|
||||
e.key === 'SignOut' && this.props.onSignOut()
|
||||
}
|
||||
render() {
|
||||
const {
|
||||
i18n,
|
||||
fixed,
|
||||
avatar,
|
||||
username,
|
||||
collapsed,
|
||||
notifications,
|
||||
onCollapseChange,
|
||||
onAllNotificationsRead,
|
||||
} = this.props
|
||||
|
||||
const rightContent = [
|
||||
<Menu key="user" mode="horizontal" onClick={this.handleClickMenu}>
|
||||
<SubMenu
|
||||
title={
|
||||
<Fragment>
|
||||
<span style={{ color: '#999', marginRight: 4 }}>
|
||||
<Trans>Hi,</Trans>
|
||||
</span>
|
||||
<span>{username}</span>
|
||||
<Avatar style={{ marginLeft: 8 }} src={avatar} />
|
||||
</Fragment>
|
||||
}
|
||||
>
|
||||
<Menu.Item key="SignOut">
|
||||
<Trans>Sign out</Trans>
|
||||
</Menu.Item>
|
||||
</SubMenu>
|
||||
</Menu>,
|
||||
]
|
||||
|
||||
if (config.i18n) {
|
||||
const { languages } = config.i18n
|
||||
const currentLanguage = languages.find(
|
||||
item => item.key === i18n._language
|
||||
)
|
||||
|
||||
rightContent.unshift(
|
||||
<Menu
|
||||
key="language"
|
||||
selectedKeys={[currentLanguage.key]}
|
||||
onClick={data => {
|
||||
setLocale(data.key)
|
||||
}}
|
||||
mode="horizontal"
|
||||
>
|
||||
<SubMenu title={<Avatar size="small" src={currentLanguage.flag} />}>
|
||||
{languages.map(item => (
|
||||
<Menu.Item key={item.key}>
|
||||
<Avatar
|
||||
size="small"
|
||||
style={{ marginRight: 8 }}
|
||||
src={item.flag}
|
||||
/>
|
||||
{item.title}
|
||||
</Menu.Item>
|
||||
))}
|
||||
</SubMenu>
|
||||
</Menu>
|
||||
)
|
||||
}
|
||||
|
||||
rightContent.unshift(
|
||||
<Popover
|
||||
placement="bottomRight"
|
||||
trigger="click"
|
||||
key="notifications"
|
||||
overlayClassName={styles.notificationPopover}
|
||||
getPopupContainer={() => document.querySelector('#layoutHeader')}
|
||||
content={
|
||||
<div className={styles.notification}>
|
||||
<List
|
||||
itemLayout="horizontal"
|
||||
dataSource={notifications}
|
||||
locale={{
|
||||
emptyText: <Trans>You have viewed all notifications.</Trans>,
|
||||
}}
|
||||
renderItem={item => (
|
||||
<List.Item className={styles.notificationItem}>
|
||||
<List.Item.Meta
|
||||
title={
|
||||
<Ellipsis tooltip lines={1}>
|
||||
{item.title}
|
||||
</Ellipsis>
|
||||
}
|
||||
description={moment(item.date).fromNow()}
|
||||
/>
|
||||
<Icon
|
||||
style={{ fontSize: 10, color: '#ccc' }}
|
||||
type="right"
|
||||
theme="outlined"
|
||||
/>
|
||||
</List.Item>
|
||||
)}
|
||||
/>
|
||||
{notifications.length ? (
|
||||
<div
|
||||
onClick={onAllNotificationsRead}
|
||||
className={styles.clearButton}
|
||||
>
|
||||
<Trans>Clear notifications</Trans>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<Badge
|
||||
count={notifications.length}
|
||||
dot
|
||||
offset={[-10, 10]}
|
||||
className={styles.iconButton}
|
||||
>
|
||||
<Icon className={styles.iconFont} type="bell" />
|
||||
</Badge>
|
||||
</Popover>
|
||||
)
|
||||
|
||||
return (
|
||||
<Layout.Header
|
||||
className={classnames(styles.header, {
|
||||
[styles.fixed]: fixed,
|
||||
[styles.collapsed]: collapsed,
|
||||
})}
|
||||
id="layoutHeader"
|
||||
>
|
||||
<div
|
||||
className={styles.button}
|
||||
onClick={onCollapseChange.bind(this, !collapsed)}
|
||||
>
|
||||
<Icon
|
||||
type={classnames({
|
||||
'menu-unfold': collapsed,
|
||||
'menu-fold': !collapsed,
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.rightContainer}>{rightContent}</div>
|
||||
</Layout.Header>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Header.propTypes = {
|
||||
fixed: PropTypes.bool,
|
||||
user: PropTypes.object,
|
||||
menus: PropTypes.array,
|
||||
collapsed: PropTypes.bool,
|
||||
onSignOut: PropTypes.func,
|
||||
notifications: PropTypes.array,
|
||||
onCollapseChange: PropTypes.func,
|
||||
onAllNotificationsRead: PropTypes.func,
|
||||
}
|
||||
|
||||
export default Header
|
||||
@@ -1,154 +0,0 @@
|
||||
@import '~themes/vars.less';
|
||||
|
||||
.header {
|
||||
padding: 0;
|
||||
box-shadow: @shadow-2;
|
||||
position: relative;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
height: 72px;
|
||||
z-index: 9;
|
||||
align-items: center;
|
||||
background-color: #fff;
|
||||
|
||||
&.fixed {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
right: 0;
|
||||
width: ~'calc(100% - 256px)';
|
||||
z-index: 9;
|
||||
transition: width 0.2s;
|
||||
|
||||
&.collapsed {
|
||||
width: ~'calc(100% - 80px)';
|
||||
}
|
||||
}
|
||||
|
||||
:global {
|
||||
.ant-menu-submenu-title {
|
||||
height: 72px;
|
||||
}
|
||||
|
||||
.ant-menu-horizontal {
|
||||
line-height: 72px;
|
||||
|
||||
& > .ant-menu-submenu:hover {
|
||||
color: @primary-color;
|
||||
background-color: @hover-color;
|
||||
}
|
||||
}
|
||||
|
||||
.ant-menu {
|
||||
border-bottom: none;
|
||||
height: 72px;
|
||||
}
|
||||
|
||||
.ant-menu-horizontal > .ant-menu-submenu {
|
||||
top: 0;
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.ant-menu-horizontal > .ant-menu-item,
|
||||
.ant-menu-horizontal > .ant-menu-submenu {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.ant-menu-horizontal > .ant-menu-item-active,
|
||||
.ant-menu-horizontal > .ant-menu-item-open,
|
||||
.ant-menu-horizontal > .ant-menu-item-selected,
|
||||
.ant-menu-horizontal > .ant-menu-item:hover,
|
||||
.ant-menu-horizontal > .ant-menu-submenu-active,
|
||||
.ant-menu-horizontal > .ant-menu-submenu-open,
|
||||
.ant-menu-horizontal > .ant-menu-submenu-selected,
|
||||
.ant-menu-horizontal > .ant-menu-submenu:hover {
|
||||
border-bottom: none;
|
||||
}
|
||||
}
|
||||
|
||||
.rightContainer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.button {
|
||||
width: 72px;
|
||||
height: 72px;
|
||||
line-height: 72px;
|
||||
text-align: center;
|
||||
font-size: 18px;
|
||||
cursor: pointer;
|
||||
transition: @transition-ease-in;
|
||||
|
||||
&:hover {
|
||||
color: @primary-color;
|
||||
background-color: @hover-color;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.iconButton {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
border-radius: 24px;
|
||||
cursor: pointer;
|
||||
.background-hover();
|
||||
|
||||
&:hover {
|
||||
.iconFont {
|
||||
color: @primary-color;
|
||||
}
|
||||
}
|
||||
|
||||
& + .iconButton {
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
.iconFont {
|
||||
color: #b2b0c7;
|
||||
font-size: 24px;
|
||||
}
|
||||
}
|
||||
|
||||
.notification {
|
||||
padding: 24px 0;
|
||||
width: 320px;
|
||||
.notificationItem {
|
||||
transition: all 0.3s;
|
||||
padding: 12px 24px;
|
||||
cursor: pointer;
|
||||
&:hover {
|
||||
background-color: @hover-color;
|
||||
}
|
||||
}
|
||||
.clearButton {
|
||||
text-align: center;
|
||||
height: 48px;
|
||||
line-height: 48px;
|
||||
cursor: pointer;
|
||||
.background-hover();
|
||||
}
|
||||
}
|
||||
|
||||
.notificationPopover {
|
||||
:global {
|
||||
.ant-popover-inner-content {
|
||||
padding: 0;
|
||||
}
|
||||
.ant-popover-arrow {
|
||||
display: none;
|
||||
}
|
||||
.ant-list-item-content {
|
||||
flex: 0;
|
||||
margin-left: 16px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
.header {
|
||||
width: 100% !important;
|
||||
}
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
import React, { PureComponent, Fragment } from 'react'
|
||||
import PropTypes from 'prop-types'
|
||||
import { Menu, Icon } from 'antd'
|
||||
import Navlink from 'umi/navlink'
|
||||
import withRouter from 'umi/withRouter'
|
||||
import {
|
||||
arrayToTree,
|
||||
queryAncestors,
|
||||
pathMatchRegexp,
|
||||
addLangPrefix,
|
||||
} from 'utils'
|
||||
import store from 'store'
|
||||
|
||||
const { SubMenu } = Menu
|
||||
|
||||
@withRouter
|
||||
class SiderMenu extends PureComponent {
|
||||
state = {
|
||||
openKeys: store.get('openKeys') || [],
|
||||
}
|
||||
|
||||
onOpenChange = openKeys => {
|
||||
const { menus } = this.props
|
||||
const rootSubmenuKeys = menus.filter(_ => !_.menuParentId).map(_ => _.id)
|
||||
|
||||
const latestOpenKey = openKeys.find(
|
||||
key => this.state.openKeys.indexOf(key) === -1
|
||||
)
|
||||
|
||||
let newOpenKeys = openKeys
|
||||
if (rootSubmenuKeys.indexOf(latestOpenKey) !== -1) {
|
||||
newOpenKeys = latestOpenKey ? [latestOpenKey] : []
|
||||
}
|
||||
|
||||
this.setState({
|
||||
openKeys: newOpenKeys,
|
||||
})
|
||||
store.set('openKeys', newOpenKeys)
|
||||
}
|
||||
|
||||
generateMenus = data => {
|
||||
return data.map(item => {
|
||||
if (item.children) {
|
||||
return (
|
||||
<SubMenu
|
||||
key={item.id}
|
||||
title={
|
||||
<Fragment>
|
||||
{item.icon && <Icon type={item.icon} />}
|
||||
<span>{item.name}</span>
|
||||
</Fragment>
|
||||
}
|
||||
>
|
||||
{this.generateMenus(item.children)}
|
||||
</SubMenu>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<Menu.Item key={item.id}>
|
||||
<Navlink to={addLangPrefix(item.route) || '#'}>
|
||||
{item.icon && <Icon type={item.icon} />}
|
||||
<span>{item.name}</span>
|
||||
</Navlink>
|
||||
</Menu.Item>
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
collapsed,
|
||||
theme,
|
||||
menus,
|
||||
location,
|
||||
isMobile,
|
||||
onCollapseChange,
|
||||
} = this.props
|
||||
|
||||
// Generating tree-structured data for menu content.
|
||||
const menuTree = arrayToTree(menus, 'id', 'menuParentId')
|
||||
|
||||
// Find a menu that matches the pathname.
|
||||
const currentMenu = menus.find(
|
||||
_ => _.route && pathMatchRegexp(_.route, location.pathname)
|
||||
)
|
||||
|
||||
// Find the key that should be selected according to the current menu.
|
||||
const selectedKeys = currentMenu
|
||||
? queryAncestors(menus, currentMenu, 'menuParentId').map(_ => _.id)
|
||||
: []
|
||||
|
||||
return (
|
||||
<Menu
|
||||
mode="inline"
|
||||
theme={theme}
|
||||
onOpenChange={this.onOpenChange}
|
||||
openKeys={this.state.openKeys}
|
||||
inlineCollapsed={collapsed}
|
||||
selectedKeys={selectedKeys}
|
||||
onClick={
|
||||
isMobile
|
||||
? () => {
|
||||
onCollapseChange(true)
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{this.generateMenus(menuTree)}
|
||||
</Menu>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
SiderMenu.propTypes = {
|
||||
menus: PropTypes.array,
|
||||
theme: PropTypes.string,
|
||||
isMobile: PropTypes.bool,
|
||||
collapsed: PropTypes.bool,
|
||||
onCollapseChange: PropTypes.func,
|
||||
}
|
||||
|
||||
export default SiderMenu
|
||||
@@ -1,88 +0,0 @@
|
||||
import React, { PureComponent } from 'react'
|
||||
import PropTypes from 'prop-types'
|
||||
import { Icon, Switch, Layout } from 'antd'
|
||||
import { withI18n, Trans } from '@lingui/react'
|
||||
import ScrollBar from '../ScrollBar'
|
||||
import { config } from 'utils'
|
||||
import SiderMenu from './Menu'
|
||||
import styles from './Sider.less'
|
||||
|
||||
@withI18n()
|
||||
class Sider extends PureComponent {
|
||||
render() {
|
||||
const {
|
||||
i18n,
|
||||
menus,
|
||||
theme,
|
||||
isMobile,
|
||||
collapsed,
|
||||
onThemeChange,
|
||||
onCollapseChange,
|
||||
} = this.props
|
||||
|
||||
return (
|
||||
<Layout.Sider
|
||||
width={256}
|
||||
theme={theme}
|
||||
breakpoint="lg"
|
||||
trigger={null}
|
||||
collapsible
|
||||
collapsed={collapsed}
|
||||
onBreakpoint={isMobile ? null : onCollapseChange}
|
||||
className={styles.sider}
|
||||
>
|
||||
<div className={styles.brand}>
|
||||
<div className={styles.logo}>
|
||||
<img alt="logo" src={config.logoPath} />
|
||||
{collapsed ? null : <h1>{config.siteName}</h1>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={styles.menuContainer}>
|
||||
<ScrollBar
|
||||
option={{
|
||||
// Disabled horizontal scrolling, https://github.com/utatti/perfect-scrollbar#options
|
||||
suppressScrollX: true,
|
||||
}}
|
||||
>
|
||||
<SiderMenu
|
||||
menus={menus}
|
||||
theme={theme}
|
||||
isMobile={isMobile}
|
||||
collapsed={collapsed}
|
||||
onCollapseChange={onCollapseChange}
|
||||
/>
|
||||
</ScrollBar>
|
||||
</div>
|
||||
{collapsed ? null : (
|
||||
<div className={styles.switchTheme}>
|
||||
<span>
|
||||
<Icon type="bulb" />
|
||||
<Trans>Switch Theme</Trans>
|
||||
</span>
|
||||
<Switch
|
||||
onChange={onThemeChange.bind(
|
||||
this,
|
||||
theme === 'dark' ? 'light' : 'dark'
|
||||
)}
|
||||
defaultChecked={theme === 'dark'}
|
||||
checkedChildren={i18n.t`Dark`}
|
||||
unCheckedChildren={i18n.t`Light`}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</Layout.Sider>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Sider.propTypes = {
|
||||
menus: PropTypes.array,
|
||||
theme: PropTypes.string,
|
||||
isMobile: PropTypes.bool,
|
||||
collapsed: PropTypes.bool,
|
||||
onThemeChange: PropTypes.func,
|
||||
onCollapseChange: PropTypes.func,
|
||||
}
|
||||
|
||||
export default Sider
|
||||
@@ -1,110 +0,0 @@
|
||||
@import '~themes/vars.less';
|
||||
|
||||
.sider {
|
||||
box-shadow: fade(@primary-color, 10%) 0 0 28px 0;
|
||||
z-index: 10;
|
||||
:global {
|
||||
.ant-layout-sider-children {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: space-between;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.brand {
|
||||
z-index: 1;
|
||||
height: 72px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0 24px;
|
||||
box-shadow: 0 1px 9px -3px rgba(0, 0, 0, 0.2);
|
||||
.logo {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
img {
|
||||
width: 36px;
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
h1 {
|
||||
vertical-align: text-bottom;
|
||||
font-size: 16px;
|
||||
text-transform: uppercase;
|
||||
display: inline-block;
|
||||
font-weight: 700;
|
||||
color: @primary-color;
|
||||
white-space: nowrap;
|
||||
margin-bottom: 0;
|
||||
.text-gradient();
|
||||
|
||||
:local {
|
||||
animation: fadeRightIn 300ms @ease-in-out;
|
||||
animation-fill-mode: both;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.menuContainer {
|
||||
height: ~'calc(100vh - 120px)';
|
||||
overflow-x: hidden;
|
||||
flex: 1;
|
||||
padding: 24px 0;
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background-color: rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
}
|
||||
|
||||
:global {
|
||||
.ant-menu-inline {
|
||||
border-right: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.switchTheme {
|
||||
width: 100%;
|
||||
height: 48px;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 0 16px;
|
||||
overflow: hidden;
|
||||
transition: all 0.3s;
|
||||
|
||||
span {
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
:global {
|
||||
.anticon {
|
||||
min-width: 14px;
|
||||
margin-right: 4px;
|
||||
font-size: 14px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes fadeLeftIn {
|
||||
0% {
|
||||
transform: translateX(5px);
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
100% {
|
||||
transform: translateX(0);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
import Header from './Header'
|
||||
import Menu from './Menu'
|
||||
import Bread from './Bread'
|
||||
import Sider from './Sider'
|
||||
|
||||
export { Header, Menu, Bread, Sider }
|
||||
@@ -1,27 +0,0 @@
|
||||
import React from 'react'
|
||||
import PropTypes from 'prop-types'
|
||||
import classNames from 'classnames'
|
||||
import styles from './Loader.less'
|
||||
|
||||
const Loader = ({ spinning = true, fullScreen }) => {
|
||||
return (
|
||||
<div
|
||||
className={classNames(styles.loader, {
|
||||
[styles.hidden]: !spinning,
|
||||
[styles.fullScreen]: fullScreen,
|
||||
})}
|
||||
>
|
||||
<div className={styles.warpper}>
|
||||
<div className={styles.inner} />
|
||||
<div className={styles.text}>LOADING</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
Loader.propTypes = {
|
||||
spinning: PropTypes.bool,
|
||||
fullScreen: PropTypes.bool,
|
||||
}
|
||||
|
||||
export default Loader
|
||||
@@ -1,67 +0,0 @@
|
||||
.loader {
|
||||
background-color: #fff;
|
||||
width: 100%;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
z-index: 100000;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
opacity: 1;
|
||||
text-align: center;
|
||||
|
||||
&.fullScreen {
|
||||
position: fixed;
|
||||
}
|
||||
|
||||
.warpper {
|
||||
width: 100px;
|
||||
height: 100px;
|
||||
display: inline-flex;
|
||||
flex-direction: column;
|
||||
justify-content: space-around;
|
||||
}
|
||||
|
||||
.inner {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
margin: 0 auto;
|
||||
text-indent: -12345px;
|
||||
border-top: 1px solid rgba(0, 0, 0, 0.08);
|
||||
border-right: 1px solid rgba(0, 0, 0, 0.08);
|
||||
border-bottom: 1px solid rgba(0, 0, 0, 0.08);
|
||||
border-left: 1px solid rgba(0, 0, 0, 0.7);
|
||||
border-radius: 50%;
|
||||
z-index: 100001;
|
||||
|
||||
:local {
|
||||
animation: spinner 600ms infinite linear;
|
||||
}
|
||||
}
|
||||
|
||||
.text {
|
||||
width: 100px;
|
||||
height: 20px;
|
||||
text-align: center;
|
||||
font-size: 12px;
|
||||
letter-spacing: 4px;
|
||||
color: #000;
|
||||
}
|
||||
|
||||
&.hidden {
|
||||
z-index: -1;
|
||||
opacity: 0;
|
||||
transition: opacity 1s ease 0.5s, z-index 0.1s ease 1.5s;
|
||||
}
|
||||
}
|
||||
@keyframes spinner {
|
||||
0% {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
|
||||
100% {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"name": "Loader",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"main": "./Loader.js"
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
import React, { Component } from 'react'
|
||||
import PropTypes from 'prop-types'
|
||||
import classnames from 'classnames'
|
||||
import Loader from '../Loader'
|
||||
import styles from './Page.less'
|
||||
|
||||
export default class Page extends Component {
|
||||
render() {
|
||||
const { className, children, loading = false, inner = false } = this.props
|
||||
const loadingStyle = {
|
||||
height: 'calc(100vh - 184px)',
|
||||
overflow: 'hidden',
|
||||
}
|
||||
return (
|
||||
<div
|
||||
className={classnames(className, {
|
||||
[styles.contentInner]: inner,
|
||||
})}
|
||||
style={loading ? loadingStyle : null}
|
||||
>
|
||||
{loading ? <Loader spinning /> : ''}
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Page.propTypes = {
|
||||
className: PropTypes.string,
|
||||
children: PropTypes.node,
|
||||
loading: PropTypes.bool,
|
||||
inner: PropTypes.bool,
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
@import '~themes/vars.less';
|
||||
|
||||
.contentInner {
|
||||
background: #fff;
|
||||
padding: 24px;
|
||||
box-shadow: @shadow-1;
|
||||
min-height: ~'calc(100vh - 230px)';
|
||||
position: relative;
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
.contentInner {
|
||||
padding: 12px;
|
||||
min-height: ~'calc(100vh - 160px)';
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"name": "Page",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"main": "./Page.js"
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import ScrollBar from 'react-perfect-scrollbar'
|
||||
import 'react-perfect-scrollbar/dist/css/styles.css'
|
||||
import './index.less'
|
||||
|
||||
export default ScrollBar
|
||||
@@ -1,31 +0,0 @@
|
||||
:global {
|
||||
.ps--active-x > .ps__rail-x,
|
||||
.ps--active-y > .ps__rail-y {
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
.ps__rail-x:hover > .ps__thumb-x,
|
||||
.ps__rail-x:focus > .ps__thumb-x {
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
.ps__rail-y:hover > .ps__thumb-y,
|
||||
.ps__rail-y:focus > .ps__thumb-y {
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
.ps__rail-y,
|
||||
.ps__rail-x {
|
||||
z-index: 9;
|
||||
}
|
||||
|
||||
.ps__thumb-y {
|
||||
width: 4px;
|
||||
right: 4px;
|
||||
}
|
||||
|
||||
.ps__thumb-x {
|
||||
height: 4px;
|
||||
bottom: 4px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import useGlobalSync from '@/hooks/useGlobalSync';
|
||||
import {
|
||||
BulbOutlined,
|
||||
FullscreenExitOutlined,
|
||||
FullscreenOutlined,
|
||||
GlobalOutlined,
|
||||
UserOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import { Avatar, Button, Dropdown, Tooltip, type MenuProps } from 'antd';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { setLocale as setUmiLocale } from 'umi';
|
||||
|
||||
type Props = {
|
||||
goProfile?: () => void;
|
||||
onLogout?: () => void;
|
||||
};
|
||||
|
||||
export default function TopbarControls({ goProfile, onLogout }: Props) {
|
||||
const [isFullscreen, setIsFullscreen] = useState(false);
|
||||
const [darkMode, setDarkMode] = useState(false);
|
||||
const currentAdmin = useGlobalSync((s) => s.currentAdmin);
|
||||
const isLoggedIn = useGlobalSync((s) => s.isLoggedIn);
|
||||
|
||||
useEffect(() => {
|
||||
const dm = localStorage.getItem('app-dark-mode');
|
||||
if (dm === 'true') {
|
||||
setDarkMode(true);
|
||||
document.documentElement.classList.add('dark-mode');
|
||||
}
|
||||
const onFs = () => setIsFullscreen(!!document.fullscreenElement);
|
||||
document.addEventListener('fullscreenchange', onFs);
|
||||
return () => document.removeEventListener('fullscreenchange', onFs);
|
||||
}, []);
|
||||
|
||||
const toggleFullscreen = async () => {
|
||||
try {
|
||||
if (!document.fullscreenElement)
|
||||
await document.documentElement.requestFullscreen();
|
||||
else await document.exitFullscreen();
|
||||
} catch (e) {
|
||||
void 0;
|
||||
}
|
||||
};
|
||||
|
||||
const toggleDarkMode = () => {
|
||||
const next = !darkMode;
|
||||
setDarkMode(next);
|
||||
if (next) document.documentElement.classList.add('dark-mode');
|
||||
else document.documentElement.classList.remove('dark-mode');
|
||||
|
||||
localStorage.setItem('app-dark-mode', String(next));
|
||||
};
|
||||
|
||||
const changeLocale = (l: string) => {
|
||||
try {
|
||||
// ensure umi locale stored, then notify app to update Antd locale immediately
|
||||
setUmiLocale(l, true);
|
||||
localStorage.setItem('umi_locale', l);
|
||||
window.dispatchEvent(new CustomEvent('localechange', { detail: l }));
|
||||
} catch (e) {
|
||||
window.location.reload();
|
||||
}
|
||||
};
|
||||
|
||||
const localeMenuItems: MenuProps['items'] = [
|
||||
{ key: 'en-US', label: 'English' },
|
||||
{ key: 'zh-CN', label: '中文' },
|
||||
];
|
||||
|
||||
const profileMenuItems: MenuProps['items'] = [
|
||||
{ key: 'profile', label: '个人信息' },
|
||||
{ key: 'logout', label: '注销' },
|
||||
];
|
||||
|
||||
const handleProfileClick = (key: string) => {
|
||||
if (key === 'profile') {
|
||||
goProfile && goProfile();
|
||||
} else if (key === 'logout') {
|
||||
onLogout && onLogout();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
|
||||
<Tooltip title={isFullscreen ? '退出全屏' : '全屏'}>
|
||||
<Button
|
||||
type="text"
|
||||
onClick={toggleFullscreen}
|
||||
icon={
|
||||
isFullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />
|
||||
}
|
||||
/>
|
||||
</Tooltip>
|
||||
|
||||
<Tooltip title={darkMode ? '浅色模式' : '暗黑模式'}>
|
||||
<Button type="text" onClick={toggleDarkMode} icon={<BulbOutlined />} />
|
||||
</Tooltip>
|
||||
|
||||
<Dropdown
|
||||
menu={{
|
||||
items: localeMenuItems,
|
||||
onClick: ({ key }) => changeLocale(String(key)),
|
||||
}}
|
||||
placement="bottomRight"
|
||||
>
|
||||
<Button type="text" icon={<GlobalOutlined />} />
|
||||
</Dropdown>
|
||||
|
||||
{isLoggedIn && currentAdmin ? (
|
||||
<Dropdown
|
||||
menu={{
|
||||
items: profileMenuItems,
|
||||
onClick: ({ key }) => handleProfileClick(String(key)),
|
||||
}}
|
||||
placement="bottomRight"
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 8,
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
>
|
||||
<Avatar
|
||||
size={20}
|
||||
src={currentAdmin.avatar}
|
||||
icon={!currentAdmin.avatar ? <UserOutlined /> : undefined}
|
||||
/>
|
||||
<span style={{ color: 'inherit' }}>
|
||||
{currentAdmin.real_name || currentAdmin.username}
|
||||
</span>
|
||||
</div>
|
||||
</Dropdown>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||