添加字典功能及初始化数据
This commit is contained in:
@@ -1,2 +1,2 @@
|
||||
# 开发环境配置
|
||||
VITE_API_BASE_URL=http://localhost:8080
|
||||
VITE_API_BASE_URL=http://localhost:19089/api
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
life-script 部署脚本
|
||||
功能:项目构建、文件传输、原子切换、历史版本管理、回滚支持
|
||||
使用系统自带的ssh/scp命令,无需额外依赖
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import subprocess
|
||||
import shutil
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
# 服务器配置
|
||||
SERVER_IP = "101.200.208.45"
|
||||
USERNAME = "root"
|
||||
|
||||
# 部署配置
|
||||
APP_NAME = "life-script"
|
||||
DEPLOY_BASE = "/data/www/course-web-deploy"
|
||||
RELEASES_DIR = f"{DEPLOY_BASE}/releases"
|
||||
LINK_PATH = "/data/www/course-of-life"
|
||||
MAX_RELEASES = 5
|
||||
|
||||
# 本地路径
|
||||
SCRIPT_DIR = Path(__file__).parent.absolute()
|
||||
DIST_DIR = SCRIPT_DIR / "dist"
|
||||
|
||||
|
||||
class Colors:
|
||||
"""终端颜色"""
|
||||
GREEN = '\033[32m'
|
||||
RED = '\033[31m'
|
||||
YELLOW = '\033[33m'
|
||||
RESET = '\033[0m'
|
||||
|
||||
|
||||
def log_info(msg):
|
||||
"""打印信息日志"""
|
||||
print(f"{Colors.GREEN}[INFO]{Colors.RESET} {msg}")
|
||||
|
||||
|
||||
def log_error(msg):
|
||||
"""打印错误日志"""
|
||||
print(f"{Colors.RED}[ERROR]{Colors.RESET} {msg}")
|
||||
|
||||
|
||||
def log_warn(msg):
|
||||
"""打印警告日志"""
|
||||
print(f"{Colors.YELLOW}[WARN]{Colors.RESET} {msg}")
|
||||
|
||||
|
||||
def run_command(cmd, cwd=None, shell=True, capture=True):
|
||||
"""执行本地命令"""
|
||||
try:
|
||||
if capture:
|
||||
result = subprocess.run(
|
||||
cmd,
|
||||
cwd=cwd,
|
||||
shell=shell,
|
||||
capture_output=True,
|
||||
text=True
|
||||
)
|
||||
return result.returncode == 0, result.stdout, result.stderr
|
||||
else:
|
||||
result = subprocess.run(cmd, cwd=cwd, shell=shell)
|
||||
return result.returncode == 0, "", ""
|
||||
except Exception as e:
|
||||
return False, "", str(e)
|
||||
|
||||
|
||||
def exec_ssh_cmd(cmd):
|
||||
"""通过SSH执行远程命令"""
|
||||
ssh_cmd = f'ssh {USERNAME}@{SERVER_IP} "{cmd}"'
|
||||
return run_command(ssh_cmd)
|
||||
|
||||
|
||||
def scp_upload(local_path, remote_path, recursive=False):
|
||||
"""通过SCP上传文件或目录"""
|
||||
r_flag = "-r" if recursive else ""
|
||||
scp_cmd = f'scp {r_flag} "{local_path}" {USERNAME}@{SERVER_IP}:{remote_path}'
|
||||
success, stdout, stderr = run_command(scp_cmd)
|
||||
if not success:
|
||||
log_error(f"SCP上传失败: {stderr}")
|
||||
return success
|
||||
|
||||
|
||||
def check_env():
|
||||
"""检查本地环境"""
|
||||
log_info("检查本地环境...")
|
||||
|
||||
# 检查npm
|
||||
success, _, _ = run_command("npm --version")
|
||||
if not success:
|
||||
log_error("未找到npm命令,请先安装Node.js")
|
||||
sys.exit(1)
|
||||
|
||||
log_info("环境检查通过")
|
||||
|
||||
|
||||
def build_project():
|
||||
"""构建项目"""
|
||||
log_info("开始构建项目...")
|
||||
|
||||
# 切换到项目目录
|
||||
os.chdir(SCRIPT_DIR)
|
||||
|
||||
# 清理旧构建
|
||||
if DIST_DIR.exists():
|
||||
shutil.rmtree(DIST_DIR)
|
||||
log_info("已清理旧的dist目录")
|
||||
|
||||
# 执行构建(不捕获输出,直接显示)
|
||||
log_info("执行: npm run build")
|
||||
success, _, _ = run_command("npm run build", capture=False)
|
||||
if not success:
|
||||
log_error("项目构建失败")
|
||||
sys.exit(1)
|
||||
|
||||
log_info("项目构建成功")
|
||||
|
||||
# 检查dist目录
|
||||
if not DIST_DIR.exists():
|
||||
log_error("dist目录不存在")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def deploy():
|
||||
"""部署到服务器"""
|
||||
timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
|
||||
release_path = f"{RELEASES_DIR}/{timestamp}"
|
||||
|
||||
log_info(f"准备部署版本: {timestamp}")
|
||||
|
||||
# 1. 创建远程目录
|
||||
log_info("创建远程目录...")
|
||||
exec_ssh_cmd(f"mkdir -p {release_path}")
|
||||
|
||||
# 2. 上传文件
|
||||
log_info("上传文件到服务器...")
|
||||
for item in DIST_DIR.iterdir():
|
||||
if item.is_file():
|
||||
if not scp_upload(item, f"{release_path}/"):
|
||||
log_error("文件上传失败")
|
||||
sys.exit(1)
|
||||
else:
|
||||
if not scp_upload(item, f"{release_path}/", recursive=True):
|
||||
log_error("目录上传失败")
|
||||
sys.exit(1)
|
||||
log_info("文件上传成功")
|
||||
|
||||
# 3. 设置权限
|
||||
log_info("设置文件权限...")
|
||||
exec_ssh_cmd(f"chmod -R 755 {release_path}")
|
||||
|
||||
# 4. 原子切换软链接
|
||||
log_info("切换服务版本...")
|
||||
# 检查目标路径是否为普通目录
|
||||
exec_ssh_cmd(f"if [ -d '{LINK_PATH}' ] && [ ! -L '{LINK_PATH}' ]; then mv '{LINK_PATH}' '{LINK_PATH}_backup_$(date +%s)'; fi")
|
||||
# 创建软链接
|
||||
exec_ssh_cmd(f"ln -snf '{release_path}' '{LINK_PATH}'")
|
||||
|
||||
log_info(f"部署完成!当前版本指向: {release_path}")
|
||||
|
||||
# 5. 清理旧版本
|
||||
clean_old_releases()
|
||||
|
||||
|
||||
def clean_old_releases():
|
||||
"""清理旧版本,只保留最近的N个"""
|
||||
log_info(f"清理旧版本(保留最近{MAX_RELEASES}个)...")
|
||||
clean_cmd = f"cd {RELEASES_DIR} && ls -t | tail -n +{MAX_RELEASES + 1} | xargs -I {{}} rm -rf {{}}"
|
||||
exec_ssh_cmd(clean_cmd)
|
||||
|
||||
|
||||
def rollback():
|
||||
"""回滚到上一个版本"""
|
||||
log_info("开始回滚操作...")
|
||||
|
||||
# 获取当前指向的版本
|
||||
success, current_link, _ = exec_ssh_cmd(f"readlink {LINK_PATH}")
|
||||
log_info(f"当前版本: {current_link}")
|
||||
|
||||
# 获取上一个版本目录
|
||||
success, prev_version, _ = exec_ssh_cmd(
|
||||
f"ls -dt {RELEASES_DIR}/* | grep -v '{current_link}' | head -n 1"
|
||||
)
|
||||
|
||||
if not prev_version:
|
||||
log_error("没有找到可回滚的历史版本")
|
||||
sys.exit(1)
|
||||
|
||||
log_info(f"回滚目标版本: {prev_version}")
|
||||
exec_ssh_cmd(f"ln -snf {prev_version} {LINK_PATH}")
|
||||
log_info("回滚成功!")
|
||||
|
||||
|
||||
def print_usage():
|
||||
"""打印使用说明"""
|
||||
print("""
|
||||
用法: python deploy.py [命令]
|
||||
|
||||
命令:
|
||||
deploy - 构建并部署到服务器(默认)
|
||||
rollback - 回滚到上一个版本
|
||||
|
||||
示例:
|
||||
python deploy.py # 部署
|
||||
python deploy.py rollback # 回滚
|
||||
""")
|
||||
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
command = sys.argv[1] if len(sys.argv) > 1 else "deploy"
|
||||
|
||||
if command == "rollback":
|
||||
rollback()
|
||||
elif command == "deploy":
|
||||
check_env()
|
||||
build_project()
|
||||
deploy()
|
||||
else:
|
||||
print_usage()
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,133 @@
|
||||
#!/bin/bash
|
||||
# course-web 部署脚本
|
||||
# 功能:项目构建、文件传输、原子切换、历史版本管理、回滚支持
|
||||
|
||||
SERVER_IP="101.200.208.45"
|
||||
USERNAME="root"
|
||||
APP_NAME="course-web"
|
||||
DEPLOY_BASE="/data/www/course-web-deploy"
|
||||
RELEASES_DIR="${DEPLOY_BASE}/releases"
|
||||
LINK_PATH="/data/www/course-of-life"
|
||||
MAX_RELEASES=5
|
||||
|
||||
# 打印带颜色的信息
|
||||
function log_info() {
|
||||
echo -e "\033[32m[INFO] $1\033[0m"
|
||||
}
|
||||
|
||||
function log_error() {
|
||||
echo -e "\033[31m[ERROR] $1\033[0m"
|
||||
}
|
||||
|
||||
# 检查环境
|
||||
function check_env() {
|
||||
log_info "检查本地环境..."
|
||||
if ! command -v npm &> /dev/null; then
|
||||
log_error "未找到npm命令,请先安装Node.js"
|
||||
exit 1
|
||||
fi
|
||||
if ! command -v scp &> /dev/null; then
|
||||
log_error "未找到scp命令"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
# 构建项目
|
||||
function build_project() {
|
||||
log_info "开始构建项目..."
|
||||
# 清理旧构建
|
||||
rm -rf dist
|
||||
|
||||
# 安装依赖并构建
|
||||
# npm install # 视情况开启,为了速度暂时注释,假设依赖已安装
|
||||
if npm run build; then
|
||||
log_info "项目构建成功"
|
||||
else
|
||||
log_error "项目构建失败"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ ! -d "dist" ]; then
|
||||
log_error "dist目录不存在"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
# 部署到服务器
|
||||
function deploy() {
|
||||
TIMESTAMP=$(date +%Y%m%d%H%M%S)
|
||||
RELEASE_PATH="${RELEASES_DIR}/${TIMESTAMP}"
|
||||
|
||||
log_info "准备部署版本: ${TIMESTAMP}"
|
||||
|
||||
# 1. 创建远程目录结构
|
||||
ssh "${USERNAME}@${SERVER_IP}" "mkdir -p ${RELEASE_PATH}"
|
||||
|
||||
# 2. 上传文件
|
||||
log_info "上传文件到服务器..."
|
||||
if scp -r dist/* "${USERNAME}@${SERVER_IP}:${RELEASE_PATH}/"; then
|
||||
log_info "文件上传成功"
|
||||
else
|
||||
log_error "文件上传失败"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 3. 设置权限
|
||||
ssh "${USERNAME}@${SERVER_IP}" "chmod -R 755 ${RELEASE_PATH}"
|
||||
|
||||
# 4. 原子切换软链接
|
||||
log_info "切换服务版本..."
|
||||
# 检查目标路径是否为普通目录(非软链接),如果是则备份并移除,防止ln失败
|
||||
ssh "${USERNAME}@${SERVER_IP}" "
|
||||
if [ -d '${LINK_PATH}' ] && [ ! -L '${LINK_PATH}' ]; then
|
||||
echo '检测到目标路径为普通目录,进行备份...'
|
||||
mv '${LINK_PATH}' '${LINK_PATH}_backup_$(date +%s)'
|
||||
fi
|
||||
ln -snf '${RELEASE_PATH}' '${LINK_PATH}'
|
||||
"
|
||||
|
||||
log_info "部署完成!当前版本指向: ${RELEASE_PATH}"
|
||||
|
||||
# 5. 清理旧版本
|
||||
clean_old_releases
|
||||
}
|
||||
|
||||
# 清理旧版本,只保留最近的N个
|
||||
function clean_old_releases() {
|
||||
log_info "清理旧版本(保留最近${MAX_RELEASES}个)..."
|
||||
ssh "${USERNAME}@${SERVER_IP}" "
|
||||
cd ${RELEASES_DIR} && ls -t | tail -n +$((${MAX_RELEASES} + 1)) | xargs -I {} rm -rf {}
|
||||
"
|
||||
}
|
||||
|
||||
# 回滚到上一个版本
|
||||
function rollback() {
|
||||
log_info "开始回滚操作..."
|
||||
# 获取当前指向的版本
|
||||
CURRENT_LINK=$(ssh "${USERNAME}@${SERVER_IP}" "readlink ${LINK_PATH}")
|
||||
log_info "当前版本: ${CURRENT_LINK}"
|
||||
|
||||
# 获取上一个版本目录
|
||||
PREV_VERSION=$(ssh "${USERNAME}@${SERVER_IP}" "ls -dt ${RELEASES_DIR}/* | grep -v '${CURRENT_LINK}' | head -n 1")
|
||||
|
||||
if [ -z "$PREV_VERSION" ]; then
|
||||
log_error "没有找到可回滚的历史版本"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
log_info "回滚目标版本: ${PREV_VERSION}"
|
||||
ssh "${USERNAME}@${SERVER_IP}" "ln -snf ${PREV_VERSION} ${LINK_PATH}"
|
||||
log_info "回滚成功!"
|
||||
}
|
||||
|
||||
# 主流程
|
||||
case "$1" in
|
||||
"rollback")
|
||||
rollback
|
||||
;;
|
||||
*)
|
||||
check_env
|
||||
build_project
|
||||
deploy
|
||||
;;
|
||||
esac
|
||||
@@ -124,8 +124,11 @@ const AnimatedRoutes = () => {
|
||||
* App 主组件
|
||||
*/
|
||||
function App() {
|
||||
// 生产环境使用 /course-of-life 作为基础路径
|
||||
const basename = import.meta.env.PROD ? '/course-of-life' : '';
|
||||
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<BrowserRouter basename={basename}>
|
||||
{/* 动态背景 */}
|
||||
<Background />
|
||||
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { ArrowRight, Check } from 'lucide-react';
|
||||
import { GlassCard, GlassInput, GlassTextarea, GlassButton } from '../components/ui';
|
||||
import { GlassCard, GlassInput, GlassTextarea, GlassButton, GlassSelect } from '../components/ui';
|
||||
import { PromptTagGroup } from '../components/PromptTag';
|
||||
import useStore from '../store/useStore';
|
||||
import { inspirationClusters } from '../utils/constants';
|
||||
import * as dictionaryService from '../services/dictionary';
|
||||
|
||||
/**
|
||||
* OnboardingPage 组件
|
||||
@@ -24,11 +25,39 @@ const OnboardingPage = () => {
|
||||
|
||||
const [formData, setFormData] = useState(registrationData);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
|
||||
// 字典数据状态
|
||||
const [zodiacOptions, setZodiacOptions] = useState([]);
|
||||
const [mbtiOptions, setMbtiOptions] = useState([]);
|
||||
const [genderOptions, setGenderOptions] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
setFormData(registrationData);
|
||||
}, [registrationData]);
|
||||
|
||||
// 加载字典数据
|
||||
useEffect(() => {
|
||||
const loadDictionaries = async () => {
|
||||
try {
|
||||
const [zodiacList, mbtiList, genderList] = await Promise.all([
|
||||
dictionaryService.getZodiacList(),
|
||||
dictionaryService.getMbtiList(),
|
||||
dictionaryService.getGenderList()
|
||||
]);
|
||||
setZodiacOptions([{ value: '', label: '请选择星座' }, ...dictionaryService.transformToOptions(zodiacList)]);
|
||||
setMbtiOptions([{ value: '', label: '请选择MBTI' }, ...dictionaryService.transformToOptions(mbtiList)]);
|
||||
setGenderOptions([{ value: '', label: '请选择性别' }, ...dictionaryService.transformToOptions(genderList)]);
|
||||
} catch (error) {
|
||||
console.error('加载字典数据失败:', error);
|
||||
// 使用默认选项
|
||||
setZodiacOptions([{ value: '', label: '请选择星座' }]);
|
||||
setMbtiOptions([{ value: '', label: '请选择MBTI' }]);
|
||||
setGenderOptions([{ value: '', label: '请选择性别' }]);
|
||||
}
|
||||
};
|
||||
loadDictionaries();
|
||||
}, []);
|
||||
|
||||
const updateField = (field, value) => {
|
||||
setFormData(prev => ({ ...prev, [field]: value }));
|
||||
};
|
||||
@@ -46,7 +75,12 @@ const OnboardingPage = () => {
|
||||
};
|
||||
|
||||
const saveStepData = () => {
|
||||
updateRegistration(formData);
|
||||
// 保存时将兴趣爱好字符串转换为数组
|
||||
const dataToSave = { ...formData };
|
||||
if (typeof dataToSave.hobbies === 'string') {
|
||||
dataToSave.hobbies = dataToSave.hobbies.split(/[,,]/).map(s => s.trim()).filter(s => s);
|
||||
}
|
||||
updateRegistration(dataToSave);
|
||||
};
|
||||
|
||||
const handleNext = async () => {
|
||||
@@ -82,15 +116,15 @@ const OnboardingPage = () => {
|
||||
</div>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-2">
|
||||
<GlassInput label="称呼" placeholder="例如:林中鹿" value={formData.nickname} onChange={(v) => updateField('nickname', v)} />
|
||||
<GlassInput label="性别" placeholder="自由填写" value={formData.gender} onChange={(v) => updateField('gender', v)} />
|
||||
<GlassInput label="MBTI" placeholder="如:INFJ" value={formData.mbti} onChange={(v) => updateField('mbti', v)} />
|
||||
<GlassInput label="星座" placeholder="星辰指引" value={formData.zodiac} onChange={(v) => updateField('zodiac', v)} />
|
||||
<GlassSelect label="性别" options={genderOptions} value={formData.gender} onChange={(v) => updateField('gender', v)} />
|
||||
<GlassSelect label="MBTI" options={mbtiOptions} value={formData.mbti} onChange={(v) => updateField('mbti', v)} />
|
||||
<GlassSelect label="星座" options={zodiacOptions} value={formData.zodiac} onChange={(v) => updateField('zodiac', v)} />
|
||||
</div>
|
||||
<GlassInput
|
||||
label="兴趣爱好"
|
||||
placeholder="用逗号分隔你的热爱"
|
||||
value={Array.isArray(formData.hobbies) ? formData.hobbies.join(',') : formData.hobbies}
|
||||
onChange={(v) => updateField('hobbies', v.split(',').map(s => s.trim()).filter(s => s))}
|
||||
placeholder="用逗号分隔你的热爱,如:阅读,旅行,摄影"
|
||||
value={Array.isArray(formData.hobbies) ? formData.hobbies.join(',') : (formData.hobbies || '')}
|
||||
onChange={(v) => updateField('hobbies', v)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import api from './api';
|
||||
|
||||
/**
|
||||
* 字典服务
|
||||
* 处理字典数据的获取
|
||||
*/
|
||||
|
||||
/**
|
||||
* 根据字典类型获取启用的字典列表
|
||||
* @param {string} dictType - 字典类型
|
||||
* @returns {Promise<Array>} 字典列表
|
||||
*/
|
||||
export const getEnabledDictionariesByType = async (dictType) => {
|
||||
const response = await api.get('/dictionary/enabledByType', {
|
||||
params: { dictType }
|
||||
});
|
||||
return response.data || [];
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取星座字典
|
||||
* @returns {Promise<Array>} 星座列表
|
||||
*/
|
||||
export const getZodiacList = async () => {
|
||||
return getEnabledDictionariesByType('constellation');
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取MBTI字典
|
||||
* @returns {Promise<Array>} MBTI列表
|
||||
*/
|
||||
export const getMbtiList = async () => {
|
||||
return getEnabledDictionariesByType('mbti');
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取性别字典
|
||||
* @returns {Promise<Array>} 性别列表
|
||||
*/
|
||||
export const getGenderList = async () => {
|
||||
return getEnabledDictionariesByType('gender');
|
||||
};
|
||||
|
||||
/**
|
||||
* 将字典数据转换为下拉选项格式
|
||||
* @param {Array} dictList - 字典列表
|
||||
* @returns {Array<{value: string, label: string}>} 选项列表
|
||||
*/
|
||||
export const transformToOptions = (dictList) => {
|
||||
if (!Array.isArray(dictList)) return [];
|
||||
return dictList.map(item => ({
|
||||
value: item.dictValue || item.dictCode || '',
|
||||
label: item.dictName || item.dictValue || ''
|
||||
}));
|
||||
};
|
||||
|
||||
export default {
|
||||
getEnabledDictionariesByType,
|
||||
getZodiacList,
|
||||
getMbtiList,
|
||||
getGenderList,
|
||||
transformToOptions
|
||||
};
|
||||
@@ -72,6 +72,7 @@ const transformToBackendFormat = (frontendData) => {
|
||||
nickname,
|
||||
gender,
|
||||
zodiac,
|
||||
profession,
|
||||
mbti,
|
||||
hobbies,
|
||||
childhood,
|
||||
@@ -85,6 +86,7 @@ const transformToBackendFormat = (frontendData) => {
|
||||
nickname,
|
||||
gender,
|
||||
zodiac,
|
||||
profession,
|
||||
mbti,
|
||||
// 兴趣爱好转为 JSON 字符串
|
||||
hobbies: Array.isArray(hobbies) ? JSON.stringify(hobbies) : hobbies,
|
||||
@@ -118,6 +120,7 @@ export const transformToFrontendFormat = (backendData) => {
|
||||
nickname,
|
||||
gender,
|
||||
zodiac,
|
||||
profession,
|
||||
mbti,
|
||||
hobbies,
|
||||
childhoodDate,
|
||||
@@ -136,6 +139,7 @@ export const transformToFrontendFormat = (backendData) => {
|
||||
nickname: nickname || '',
|
||||
gender: gender || '',
|
||||
zodiac: zodiac || '',
|
||||
profession: profession || '',
|
||||
mbti: mbti || '',
|
||||
// 兴趣爱好从 JSON 字符串解析
|
||||
hobbies: hobbies ? (typeof hobbies === 'string' ? JSON.parse(hobbies) : hobbies) : [],
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Settings, Settings2 } from 'lucide-react';
|
||||
import Modal from '../components/Modal';
|
||||
import { GlassButton, GlassInput } from '../components/ui';
|
||||
import { GlassButton, GlassInput, GlassSelect } from '../components/ui';
|
||||
import useStore from '../store/useStore';
|
||||
import * as dictionaryService from '../services/dictionary';
|
||||
|
||||
/**
|
||||
* ProfileModal 组件
|
||||
@@ -18,13 +19,19 @@ const ProfileModal = ({ isOpen, onClose }) => {
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
|
||||
// 字典数据状态
|
||||
const [zodiacOptions, setZodiacOptions] = useState([]);
|
||||
const [mbtiOptions, setMbtiOptions] = useState([]);
|
||||
const [genderOptions, setGenderOptions] = useState([]);
|
||||
|
||||
// 编辑表单状态
|
||||
const [editForm, setEditForm] = useState({
|
||||
nickname: registrationData.nickname,
|
||||
profession: registrationData.profession || '',
|
||||
gender: registrationData.gender || '',
|
||||
mbti: registrationData.mbti,
|
||||
zodiac: registrationData.zodiac,
|
||||
hobbies: registrationData.hobbies?.join(', ') || ''
|
||||
hobbies: registrationData.hobbies?.join(',') || ''
|
||||
});
|
||||
|
||||
// 同步 registrationData 到 editForm
|
||||
@@ -32,12 +39,37 @@ const ProfileModal = ({ isOpen, onClose }) => {
|
||||
setEditForm({
|
||||
nickname: registrationData.nickname,
|
||||
profession: registrationData.profession || '',
|
||||
gender: registrationData.gender || '',
|
||||
mbti: registrationData.mbti,
|
||||
zodiac: registrationData.zodiac,
|
||||
hobbies: registrationData.hobbies?.join(', ') || ''
|
||||
hobbies: registrationData.hobbies?.join(',') || ''
|
||||
});
|
||||
}, [registrationData]);
|
||||
|
||||
// 加载字典数据
|
||||
useEffect(() => {
|
||||
const loadDictionaries = async () => {
|
||||
try {
|
||||
const [zodiacList, mbtiList, genderList] = await Promise.all([
|
||||
dictionaryService.getZodiacList(),
|
||||
dictionaryService.getMbtiList(),
|
||||
dictionaryService.getGenderList()
|
||||
]);
|
||||
setZodiacOptions([{ value: '', label: '请选择星座' }, ...dictionaryService.transformToOptions(zodiacList)]);
|
||||
setMbtiOptions([{ value: '', label: '请选择MBTI' }, ...dictionaryService.transformToOptions(mbtiList)]);
|
||||
setGenderOptions([{ value: '', label: '请选择性别' }, ...dictionaryService.transformToOptions(genderList)]);
|
||||
} catch (error) {
|
||||
console.error('加载字典数据失败:', error);
|
||||
setZodiacOptions([{ value: '', label: '请选择星座' }]);
|
||||
setMbtiOptions([{ value: '', label: '请选择MBTI' }]);
|
||||
setGenderOptions([{ value: '', label: '请选择性别' }]);
|
||||
}
|
||||
};
|
||||
if (isOpen) {
|
||||
loadDictionaries();
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
/**
|
||||
* 处理保存
|
||||
*/
|
||||
@@ -47,9 +79,10 @@ const ProfileModal = ({ isOpen, onClose }) => {
|
||||
updateRegistration({
|
||||
nickname: editForm.nickname,
|
||||
profession: editForm.profession,
|
||||
gender: editForm.gender,
|
||||
mbti: editForm.mbti,
|
||||
zodiac: editForm.zodiac,
|
||||
hobbies: editForm.hobbies.split(',').map(s => s.trim()).filter(s => s)
|
||||
hobbies: editForm.hobbies.split(/[,,]/).map(s => s.trim()).filter(s => s)
|
||||
});
|
||||
await saveUserProfile();
|
||||
setIsEditing(false);
|
||||
@@ -69,9 +102,10 @@ const ProfileModal = ({ isOpen, onClose }) => {
|
||||
setEditForm({
|
||||
nickname: registrationData.nickname,
|
||||
profession: registrationData.profession || '',
|
||||
gender: registrationData.gender || '',
|
||||
mbti: registrationData.mbti,
|
||||
zodiac: registrationData.zodiac,
|
||||
hobbies: registrationData.hobbies?.join(', ') || ''
|
||||
hobbies: registrationData.hobbies?.join(',') || ''
|
||||
});
|
||||
setIsEditing(false);
|
||||
};
|
||||
@@ -165,22 +199,28 @@ const ProfileModal = ({ isOpen, onClose }) => {
|
||||
value={editForm.profession}
|
||||
onChange={(v) => setEditForm(prev => ({ ...prev, profession: v }))}
|
||||
/>
|
||||
<GlassInput
|
||||
<GlassSelect
|
||||
label="性别"
|
||||
options={genderOptions}
|
||||
value={editForm.gender}
|
||||
onChange={(v) => setEditForm(prev => ({ ...prev, gender: v }))}
|
||||
/>
|
||||
<GlassSelect
|
||||
label="MBTI"
|
||||
placeholder="性格色彩"
|
||||
options={mbtiOptions}
|
||||
value={editForm.mbti}
|
||||
onChange={(v) => setEditForm(prev => ({ ...prev, mbti: v }))}
|
||||
/>
|
||||
<GlassInput
|
||||
<GlassSelect
|
||||
label="星座"
|
||||
placeholder="星辰指引"
|
||||
options={zodiacOptions}
|
||||
value={editForm.zodiac}
|
||||
onChange={(v) => setEditForm(prev => ({ ...prev, zodiac: v }))}
|
||||
/>
|
||||
</div>
|
||||
<GlassInput
|
||||
label="兴趣爱好"
|
||||
placeholder="让灵魂起舞的事物"
|
||||
placeholder="让灵魂起舞的事物,用逗号分隔"
|
||||
value={editForm.hobbies}
|
||||
onChange={(v) => setEditForm(prev => ({ ...prev, hobbies: v }))}
|
||||
/>
|
||||
|
||||
@@ -5,6 +5,8 @@ import tailwindcss from '@tailwindcss/vite'
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss()],
|
||||
// 生产环境使用 /course-of-life/ 路径
|
||||
base: '/course-of-life/',
|
||||
server: {
|
||||
port: 3000
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user