initial commit

This commit is contained in:
LittleBoy 2023-02-27 19:18:58 +08:00
commit b951e34206
36 changed files with 3099 additions and 0 deletions

24
.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

24
config.ts Normal file
View File

@ -0,0 +1,24 @@
const AppConfig = {
development: {
CLIENT_ID: 'uziRFTVYkcgnGjAx',
SECRET: '5CsvgvJpVwKuDfff0PPTSN2mOzDFy09v',
API_PREFIX: 'http://chat.wx.wm-app.xyz',
DEPLOY_DIR: '/',
PUBLIC_PATH: '/',
},
test: {
CLIENT_ID: 'uziRFTVYkcgnGjAx',
SECRET: '5CsvgvJpVwKuDfff0PPTSN2mOzDFy09v',
API_PREFIX: 'http://chat.wx.wm-app.xyz',
DEPLOY_DIR: (process.env.DEPLOY_DIR || '/'),
PUBLIC_PATH: (process.env.PUBLIC_PATH || './'),
},
production: {
CLIENT_ID: 'aVjsh87iWEuhZdWC',
SECRET: 'Q3L8Npkloyucq1o8tmLYDllCt2bwZ881',
API_PREFIX: 'http://chat.wx.wm-app.xyz',
DEPLOY_DIR: (process.env.DEPLOY_DIR || '/'),
PUBLIC_PATH: (process.env.PUBLIC_PATH || './'),
}
}
export default AppConfig

13
index.html Normal file
View File

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<link rel="icon" type="image/svg+xml" href="/vite.svg"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>星图Chat</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

84
mocks/api.mock.ts Normal file
View File

@ -0,0 +1,84 @@
import {MockMethod} from "vite-plugin-mock";
import {Random} from "mockjs";
type UserModel = {
username: string;
account: string;
avatar: string;
vip: number;
}
type LoginUserModel = {
token: string;
} & UserModel
const loginUserList: LoginUserModel[] = [
{
token: "123123123123",
username: '张三',
account: '123123',
avatar: 'https://www.cdnjson.com/images/2023/01/31/qwrgFf.jpg',
vip: Date.now() + 3600 * 24 * 30
},
{
token: "asd2314asdf12",
username: '李四',
account: 'admin',
avatar: 'https://www.cdnjson.com/images/2023/01/31/qwrgFf.jpg',
vip: 0
}
]
const codeSessions: any = {};
function success(data: any = null) {
return {code: 0, message: 'success', data}
}
function fail(message: string, data: any = null) {
return {code: 1, message, data}
}
const apiMock: MockMethod[] = [
{
url: '/api/user/login',
method: 'post',
timeout: 300,
response: ({body}: { body: { phone: string, code: string } }) => {
const {phone, code} = body
if (!code || !codeSessions[phone] || (codeSessions[phone] != code && code != '123')) {
return fail('验证码不正确')
}
const user = loginUserList.filter(s => s.account === phone)
return user ? success(user) : fail('用户不存在');
}
},
{
url: '/api/user/info',
response: ({body}: { body: { phone: string, code: string } }) => {
console.log(body)
return success(loginUserList[0])
}
},
{
url: '/api/sendCode',
method: 'post',
timeout: 1500,
response: ({body}: { body: { phone: string } }) => {
const code = codeSessions[body.phone] = String(Random.natural(100000, 999999));
return success(code);
// return fail('短信发送网关异常', body)
}
},
{
url: '/api/chat',
method: 'post',
timeout: 200,
response: ({body}: { body: { message: string } }) => {
if (!body.message) {
return fail('消息不能为空')
}
return success({body, content: Random.cparagraph()});
}
}
]
export default apiMock

30
package.json Normal file
View File

@ -0,0 +1,30 @@
{
"name": "chat",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite --host",
"build-test": "tsc && vite --mode test build",
"build": "tsc && vite build",
"preview": "vite preview"
},
"dependencies": {
"ahooks": "^3.7.4",
"axios": "^1.3.4",
"less": "^4.1.3",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"socket.io-client": "^4.6.1"
},
"devDependencies": {
"@types/node": "^18.14.1",
"@types/react": "^18.0.27",
"@types/react-dom": "^18.0.10",
"@vitejs/plugin-react": "^3.1.0",
"mockjs": "^1.1.0",
"typescript": "^4.9.3",
"vite": "^4.1.0",
"vite-plugin-mock": "^2.9.6"
}
}

18
public/vite.svg Normal file
View File

@ -0,0 +1,18 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img"
class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257">
<defs>
<linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%">
<stop offset="0%" stop-color="#41D1FF"></stop>
<stop offset="100%" stop-color="#BD34FE"></stop>
</linearGradient>
<linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%">
<stop offset="0%" stop-color="#FFEA83"></stop>
<stop offset="8.333%" stop-color="#FFDD35"></stop>
<stop offset="100%" stop-color="#FFA800"></stop>
</linearGradient>
</defs>
<path fill="url(#IconifyId1813088fe1fbc01fb466)"
d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path>
<path fill="url(#IconifyId1813088fe1fbc01fb467)"
d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path>
</svg>

After

Width:  |  Height:  |  Size: 1.6 KiB

226
src/App.tsx Normal file
View File

@ -0,0 +1,226 @@
import React, {useEffect, useState} from 'react'
import Login from "./components/Login";
import {useSetState} from "ahooks";
import {info, UserModel} from "./services/api";
import Vip from "./components/vip";
import Button from "./components/Button";
import {io} from 'socket.io-client'
type MessageItem = {
id: number;
from: 'ai' | 'you';
time: number;
content: string[];
avatar: string;
}
const avatar = 'https://www.cdnjson.com/images/2023/01/31/qwrgFf.jpg',
avatar1 = 'https://www.cdnjson.com/images/2023/02/25/AI.png',
globalMessageList: MessageItem[] = [
{id: 1, from: 'you', time: 1, content: ['你好'], avatar},
{id: 2, from: 'ai', time: 2, content: ['你好!有什么我能帮助你的吗?'], avatar: avatar1},
{id: 3, from: 'you', time: 3, content: ['今天新闻'], avatar},
{
id: 4,
from: 'ai',
time: 4,
content: ['很抱歉我不会自己收集或浏览最新的新闻报道因为我是一个人工智能语言模型我的知识是基于我被训练的时间截止到2023年1月的。但是您可以尝试搜索各大新闻网站来了解最新的新闻例如CNN、BBC、纽约时报等等。'],
avatar: avatar1
},
],
socket = io(APP_CONFIG.API_PREFIX, {
autoConnect: false
})
let messageIndex = 5, lastMessage = 0, initSocket = false;
function App() {
const [count, setCount] = useState(3)
const [state, setState] = useSetState<{
showLogin?: boolean
user?: UserModel
showVip?: boolean
message?: string
sending?: boolean
}>({
showVip: false,
})
const [messageList, setMessageList] = useState<MessageItem[]>(globalMessageList)
function logout() {
//TODO 调用注销登录接口
localStorage.removeItem("chat-login")
setState({user: undefined})
}
function initConnection() {
if (socket.connected || initSocket) return;
initSocket = true
console.log('初始化链接')
socket.on('disconnect', () => {
initSocket = false
})
// 时间
socket.on('chat', (ret: { content: string, messageId: number }) => {
setState({message: ''})
if (lastMessage != ret.messageId) {
appendMessage('ai', ret.content)
} else {
appendToLastMessage(ret.content)
}
lastMessage = ret.messageId
})
socket.on('chat-end', () => {
setState({sending: false})
if (count > 1) {
setCount(count - 1)
}
})
socket.connect()
}
function appendToLastMessage(content: string) {
const last = globalMessageList[globalMessageList.length - 1]
last.content.push(content)
setMessageList([...globalMessageList])
}
function loadUserInfo() {
if (localStorage.getItem("chat-login")) {
return;
}
info().then(user => {
setState({user})
initConnection()
})
}
function appendMessage(from: 'you' | 'ai', content: string) {
const newMsg = {
id: messageIndex++,
from,
time: Date.now(),
content: [content],
avatar: from == 'you' ? avatar : avatar1
}
globalMessageList.push(newMsg)
setMessageList([...globalMessageList])
}
function onSendChat() {
if (!state.message) {
return;
}
if (!state.user) { // 没有登录
setState({showLogin: true})
return;
}
if (count < 1 && state.user.vip < (Date.now() / 100) >> 0) {
setState({showVip: true})
return;
}
// 是否已经链接服务
if (socket.disconnected) {
console.log('服务未链接')
return;
}
setState({sending: true})
appendMessage('you', state.message)
socket.emit('chat', {message: state.message})
// sendChat(state.message).then((ret) => {
// setState({message: ''})
// appendMessage('ai', ret.content)
// }).finally(() => setState({sending: false}))
}
const scrollToBottom = () => {
(function smoothScroll() {
const currentScroll = document.documentElement.scrollTop || document.body.scrollTop; // 已经被卷掉的高度
const clientHeight = document.documentElement.clientHeight; // 浏览器高度
const scrollHeight = document.documentElement.scrollHeight; // 总高度
if (scrollHeight - 10 > currentScroll + clientHeight) {
window.requestAnimationFrame(smoothScroll);
window.scrollTo(0, currentScroll + (scrollHeight - currentScroll - clientHeight) / 2);
}
})();
};
// 监听
useEffect(loadUserInfo, [])
useEffect(() => {
if (messageList.length == 0) return;
scrollToBottom();
}, [messageList])
return (
<div className="app-wrapper">
<div className="app-header">
<div className="header flex-center">
{state.user ? (<>
<img className="avatar" src={state.user.avatar} alt=""/>
<span className="nickname">{state.user.username}</span>
<span className="line"></span>
<span onClick={logout} className="logout cursor-pointer">退</span>
</>) : <span className="cursor-pointer" onClick={() => setState({showLogin: true})}></span>}
</div>
</div>
<div className="app-content">
<div className="message-list-wrapper">
{messageList.map((msg, index) => <div className="message-item" key={index}>
<div className="content-container message-content">
<div className="avatar-container">
<img className="avatar" src={msg.avatar} alt=""/>
</div>
<div className="content">{msg.content.map((block, blockIndex) => <p
key={blockIndex}>{block}</p>)}</div>
</div>
</div>)}
</div>
</div>
<div className="app-send-wrapper">
<div className="content-container">
<form onSubmit={(e) => {
e.preventDefault();
onSendChat()
}}>
<textarea
onKeyUp={e => {
if (e.key.toLowerCase() == 'enter') {
onSendChat()
e.preventDefault();
e.stopPropagation();
}
}}
onInput={e => setState({message: e.currentTarget.value})}
className="send-content"
placeholder="请输入..." title="" value={state.message}></textarea>
<div className="sender-wrapper">
<Button className="btn-sender" htmlType="submit" type="primary" disabled={state.sending}>
{state.sending ? '发送中...' : (<>
<div> </div>
<div> {count} </div>
</>)}
</Button>
{state.user?.vip &&
<div className="open-vip" onClick={() => setState({showVip: true})}>+&lt;</div>}
</div>
</form>
</div>
</div>
{state.showLogin && <Login
onClose={(logged) => {
setState({showLogin: false})
localStorage.setItem("chat-login", "yes")
logged && loadUserInfo()
}}
/>}
{state.showVip && <Vip onClose={(opened) => {
setState({showVip: false})
opened && loadUserInfo()
}}/>}
</div>
)
}
export default App

BIN
src/assets/icon-empty.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

0
src/assets/util.less Normal file
View File

View File

@ -0,0 +1,44 @@
.btn-disabled{
cursor: not-allowed;
border-color: #d9d9d9;
color: rgba(0, 0, 0, 0.3);
background-color: rgba(0, 0, 0, 0.1);
box-shadow: none;
}
.btn {
--btn-border-color-default: #d9d9d9;
--btn-bg-color-default: #fff;
--btn-hover-color-default: #fff;
border: solid 1px #d9d9d9;
border-radius: var(--border-radius-default);
background-color: #fff;
outline: none;
padding: 8px 20px;
box-sizing: border-box;
font-size: var(--font-size);
cursor: pointer;
.btn-loading{
margin-right: 6px;
}
&.btn-block {
width: 100%;
}
&[disabled]{
.btn-disabled;
}
&:hover, &:focus {
outline: none;
border-color: var(--color-primary);
color: var(--color-primary);
}
&.btn-primary{
border-color: var(--color-primary);
background-color: var(--color-primary);
color: #fff;
&[disabled]{
.btn-disabled;
}
}
}

View File

@ -0,0 +1,32 @@
import React, {SVGProps} from "react";
import IconLoading from "../icons/IconLoading";
import './btn.less'
import classNames from "../../utils/classnames";
export type ButtonProp = {
children?: React.ReactNode;
loading?: boolean
disabled?: boolean
type?: "primary" | "default"
htmlType?: "button" | "submit"
block?: boolean
} & JSX.IntrinsicAttributes & SVGProps<HTMLButtonElement>
const Button: React.FC<ButtonProp> = (props) => {
return (
<button
disabled={props.disabled}
type={props.htmlType || 'button'}
className={classNames('btn',props.className, `btn-${props.type || 'default'}`, {'btn-block': props.block})}
onClick={props.onClick}
>
{props.loading && <span className="btn-loading">
<span role="img" aria-label="loading" className="ani-loading btn-loading-icon">
<IconLoading/>
</span>
</span>}
<span>{props.children}</span>
</button>
);
}
export default Button;

View File

@ -0,0 +1,20 @@
import React from "react";
export type CheckboxProp = {
children?: React.ReactNode
checked?: boolean
onChange?: (checked: boolean) => void
}
const Checkbox: React.FC<CheckboxProp> = (props) => {
return (<label className="checkbox-wrapper">
<span className="checkbox">
<input checked={props.checked} onClick={e => {
props.onChange && props.onChange(e.currentTarget.checked)
}} className="checkbox-input" type="checkbox"/>
<span className="checkbox-inner"></span>
</span>
<span>{props.children}</span>
</label>)
}
export default Checkbox;

131
src/components/Login.tsx Normal file
View File

@ -0,0 +1,131 @@
import React from "react";
import './login.less'
import IconClose from "./icons/IconClose";
import Button from "./Button";
import {useSetState, useCountDown} from "ahooks";
import Checkbox from "./Checkbox";
import {login, sendCode} from "../services/api";
export type LoginProps = {
onClose: (logged?: boolean) => void
}
const Login: React.FC<LoginProps> = (props) => {
const [state, setState] = useSetState({
sendLoading: false,
sendEndTime: 0,
ruleChecked: false,
error: '',
loginLoading: false,
})
const [data, setData] = useSetState({
phone: '',
code: ''
})
const [countdown, formattedRes] = useCountDown({
targetDate: state.sendEndTime
})
function error(e: Error) {
setState({error: e.message})
}
function onSubmit() {
if (!data.phone) {
setState({error: '请输入手机号码'})
return;
}
if (!data.code) {
setState({error: '请输入验证码'})
return;
}
if (!state.ruleChecked) {
setState({error: '请勾选使用协议'})
return;
}
setState({error: '', loginLoading: true})
login(data).then(() => {
props.onClose(true)
}).catch(error).finally(() => {
setState({
loginLoading: false
})
})
}
function onSend() {
if (!data.phone) {
setState({error: '请输入手机号码'})
return;
}
setState({sendLoading: true, error: ''})
sendCode(data.phone).then(() => {
setState({
sendLoading: false,
sendEndTime: Date.now() + 1000 * 60
})
}).catch(error).finally(() => {
setState({
sendLoading: false
})
})
}
return (<div className="login-modal-root">
<div className="login-mask mask-wrapper"></div>
<div className="login-wrapper flex-center view-full">
<div className="login-dialog">
<div className="close" onClick={()=>props.onClose(false)}>
<IconClose/>
</div>
<h2 className="title"> </h2>
<div className="body">
<div className="form-item">
<label className="label"></label>
<div className="input-wrapper">
<span className="prefix">+86</span>
<input
onInput={e => setData({phone: e.currentTarget.value})}
className="input"
type="text"
placeholder="输入手机号码"
/>
</div>
</div>
<div className="form-item verify-code">
<label className="label"></label>
<div className="flex-center">
<div className="input-wrapper code">
<input
onInput={e => setData({code: e.currentTarget.value})}
className="input" type="text" placeholder="输入验证码"/>
</div>
<div className="btn-send-code">
<Button
type="primary"
loading={state.sendLoading}
disabled={state.sendLoading || countdown !== 0}
onClick={onSend}
className="btn-send"
>{countdown > 0 ? `${formattedRes.seconds}秒后再次获取` : '获取验证码'}</Button>
</div>
</div>
</div>
<div className="login-notice">{state.error}</div>
<div>
<Button loading={state.loginLoading}
disabled={state.loginLoading} block type="primary" onClick={onSubmit} className="btn-submit"></Button>
</div>
<div className="rules flex-center">
<div className="flex-center margin-center">
<Checkbox onChange={ruleChecked => setState({ruleChecked})}></Checkbox>
<a href="#"></a>
</div>
</div>
</div>
</div>
</div>
</div>)
}
export default Login

View File

@ -0,0 +1,17 @@
import classNames from "./../../utils/classnames";
import React, {SVGProps} from "react";
const IconCheck = (props: JSX.IntrinsicAttributes & SVGProps<SVGSVGElement>) => (
<svg {...props}
className={classNames('icon', props)}
viewBox="0 0 1024 1024"
version="1.1"
fill="currentColor"
>
<path
d="M748.864 302.528a49.024 49.024 0 0 1 68.288-1.28 46.656 46.656 0 0 1 5.952 61.44l-4.608 5.44-346.56 353.344a49.024 49.024 0 0 1-64.384 4.608l-5.504-4.864-196.8-203.264a46.72 46.72 0 0 1 1.792-66.88A49.024 49.024 0 0 1 270.08 448l5.312 4.736 162.048 167.232L748.8 302.528z"
></path>
</svg>
)
;
export default IconCheck;

View File

@ -0,0 +1,21 @@
import classNames from "./../../utils/classnames";
import React, {SVGProps} from "react";
const IconClose = (props: JSX.IntrinsicAttributes & SVGProps<SVGSVGElement>) => (
<svg {...props}
className={classNames('icon', props)}
viewBox="0 0 1024 1024"
version="1.1"
fill="currentColor"
>
<path
d="M895.156706 86.256941a30.177882 30.177882 0 0 1 42.767059-0.180706c11.745882 11.745882 11.745882 30.870588-0.180706 42.767059L128.843294 937.743059c-11.866353 11.866353-30.930824 12.047059-42.767059 0.180706-11.745882-11.745882-11.745882-30.870588 0.180706-42.767059L895.156706 86.256941z"
></path>
<path
d="M86.076235 86.076235c11.745882-11.745882 30.870588-11.745882 42.767059 0.180706l808.899765 808.899765c11.866353 11.866353 12.047059 30.930824 0.180706 42.767059-11.745882 11.745882-30.870588 11.745882-42.767059-0.180706L86.256941 128.843294a30.177882 30.177882 0 0 1-0.180706-42.767059z"
></path>
<path d="M0 0h1024v1024H0z" fill="#FFF4F4" fillOpacity="0"></path>
</svg>
)
;
export default IconClose;

View File

@ -0,0 +1,16 @@
import classNames from "./../../utils/classnames";
import React, {SVGProps} from "react";
const IconCopy = (props: JSX.IntrinsicAttributes & SVGProps<SVGSVGElement>) => (
<svg {...props}
className={classNames('icon', props)}
viewBox="0 0 1024 1024"
version="1.1"
xmlns="http://www.w3.org/2000/svg"
>
<path fill="currentColor"
d="M682.666667 42.666667H85.333333v682.666666h85.333334V128h512V42.666667zM256 213.333333l4.522667 768H896V213.333333H256z m554.666667 682.666667H341.333333V298.666667h469.333334v597.333333z"
></path>
</svg>
);
export default IconCopy;

View File

@ -0,0 +1,12 @@
import React from "react";
import IconImage from './../../assets/icon-empty.png'
import {pxTransform} from "../../utils/pxTransform";
export function IconEmpty() {
return (
<img src={IconImage} style={{
width: pxTransform(122),
height: pxTransform(132)
}} alt="empty" className="icon-image"/>
)
}

View File

@ -0,0 +1,18 @@
import classNames from "./../../utils/classnames";
import React, {SVGProps} from "react";
const IconLoading = (props: JSX.IntrinsicAttributes & SVGProps<SVGSVGElement>) => (
<svg {...props}
className={classNames('icon', props)}
viewBox="0 0 1024 1024"
version="1.1" fill="currentColor"
aria-hidden="true"
width="1em" height="1em"
focusable="false"
>
<path
d="M988 548c-19.9 0-36-16.1-36-36 0-59.4-11.6-117-34.6-171.3a440.45 440.45 0 00-94.3-139.9 437.71 437.71 0 00-139.9-94.3C629 83.6 571.4 72 512 72c-19.9 0-36-16.1-36-36s16.1-36 36-36c69.1 0 136.2 13.5 199.3 40.3C772.3 66 827 103 874 150c47 47 83.9 101.8 109.7 162.7 26.7 63.1 40.2 130.2 40.2 199.3.1 19.9-16 36-35.9 36z"></path>
</svg>
)
;
export default IconLoading;

106
src/components/login.less Normal file
View File

@ -0,0 +1,106 @@
.login-modal-root {
color: #000;
.close {
text-align: right;
padding: 15px;
.icon {
height: var(--close-size);
width: var(--close-size);
cursor: pointer;
}
}
.login-dialog {
background-color: #fff;
width: auto;
max-width: calc(100vw - 32px);
box-sizing: border-box;
margin: 0 auto;
position: relative;
//box-shadow: 0 0 10px rgba(0,0,0,0.2);
border-radius: 6px;
}
.title {
text-align: center;
font-size: 32px;
font-weight: bold;
padding: 10px 0 20px;
line-height: 0;
}
.body {
padding: 0 30px 30px;
}
.form-item {
font-size: var(--font-size-lg);
.label {
margin: 20px 0 4px;
display: block;
font-size: var(--font-size);
font-weight: bold;
}
}
.input-wrapper {
display: flex;
align-items: center;
border: var(--border-primary);
padding: 2px;
border-radius: var(--border-radius-default);
.prefix {
color: var(--color-info);
padding: 0 10px;
border-right: solid 1px var(--color-info);
}
.input {
border: none;
outline: none;
padding: 6px 10px;
font-size: 18px;
box-sizing: border-box;
display: inline-block;
width: 100%;
min-width: 0;
&::-webkit-input-placeholder {
font-size: 16px;
color: var(--color-info);
}
}
}
.btn{
font-size: var(--font-size-lg);
}
.btn-send-code {
margin-left: 10px;
}
.btn-send{
width: 160px;
}
.verify-code .input {
width: 160px;
}
.login-notice {
line-height: 30px;
height: 30px;
margin-top: 30px;
text-align: center;
color: var(--color-notice);
}
.rules{
font-size: var(--font-size-sm);
text-align: center;
margin-top: 60px;
}
}

View File

@ -0,0 +1,112 @@
import React from "react";
import './vip.less'
import IconClose from "../icons/IconClose";
import {useCountDown, useSetState} from "ahooks";
import classNames from "../../utils/classnames";
import Button from "../Button";
import IconCheck from "../icons/IconCheck";
export type VipProps = {
onClose: (opened: boolean) => void;
}
const levels = [
{
id: 1,
title: '年会员',
price: 198,
originPrice: 218,
remark: '最划算',
addition: '最多人购买',
countDown: Date.now() + 3600 * 24 * 1000
},
{
id: 2,
title: '季会员',
price: 98,
originPrice: 123,
remark: '1.00/天',
addition: '',
countDown: 0
},
{
id: 3,
title: '月会员',
price: 68,
originPrice: 98,
remark: '2.27/天',
addition: '',
countDown: 0
}
]
const Vip: React.FC<VipProps> = (props) => {
// 当前状态
const [state, setState] = useSetState({
selectedIndex: 0
})
// 倒计时
const [_] = useCountDown({
targetDate: levels[0].countDown
})
return (<div className="vip-wrapper-root">
<div className="vip-mask mask-wrapper"></div>
<div className="vip-wrapper flex-center view-full">
<div className="vip-dialog dialog">
<div className="close" onClick={() => props.onClose(false)}>
<IconClose/>
</div>
<h2 className="title"></h2>
<div className="intro">
<div className="flex-center">
<IconCheck/>
<p></p>
</div>
<div className="flex-center">
<IconCheck/>
<p>10000+</p>
</div>
</div>
<div className="features">
<div className="feature-item">
<div className="name"></div>
<div className="desc"></div>
</div>
<div className="feature-item">
<div className="name"></div>
<div className="desc"></div>
</div>
<div className="feature-item">
<div className="name"></div>
<div className="desc"></div>
</div>
<div className="feature-item">
<div className="name"></div>
<div className="desc">11</div>
</div>
</div>
<div className="levels">
{levels.map((l, index) => (
<div
key={index}
onClick={() => setState({selectedIndex: index})}
className={classNames('level-item', {selected: state.selectedIndex === index})}
>
{l.addition && <div className="addition-desc">{l.addition}</div>}
<div className="level-title">{l.title}</div>
<div className="level-price"><span className="unit"></span><span
className="price">{l.price}</span></div>
<div className="level-origin-price"><span className="unit"></span><span
className="price">{l.originPrice}</span></div>
<div className="remark">
{/*{l.countDown > 0 ? (`还剩${f.hours}:${f.minutes}:${f.seconds}后结束`) : l.remark}*/}
{l.remark}
</div>
</div>))}
</div>
<div className="button">
<Button type="primary" block></Button>
</div>
</div>
</div>
</div>)
}
export default Vip;

151
src/components/vip/vip.less Normal file
View File

@ -0,0 +1,151 @@
.vip-wrapper {
color: #fff;
position: relative;
.close {
text-align: right;
position: absolute;
top: 15px;
right: 15px;
.icon {
height: var(--close-size);
width: var(--close-size);
cursor: pointer;
color: #fff;
}
}
.vip-dialog {
background: url(./vip_bg.png) no-repeat;
background-size: cover;
width: 360px;
max-width: calc(100vw - 32px);
box-sizing: border-box;
margin: 0 auto;
position: relative;
border-radius: 10px;
padding: 30px 40px;
}
h2.title {
font-size: 32px;
}
.intro {
div {
margin-top: 5px;
}
.icon {
color: #E0AC8A;
width: 20px;
height: 20px;
margin-right: 2px;
}
}
// 会员特性
.features {
display: grid;
column-gap: 20px;
grid-template-columns: auto auto;
}
.feature-item {
border: solid 1px #fff;
border-radius: 10px;
margin-top: 6px;
padding: 10px;
text-align: center;
line-height: 1.4;
.name {
font-size: 22px;
}
.desc {
font-size: var(--font-size-sm);
}
}
.levels {
display: flex;
margin-top: 40px;
}
.level-item {
flex: 1;
text-align: center;
margin-right: 10px;
position: relative;
background-color: #1E1E1E;
border: solid 1px #888;
border-radius: 8px;
padding: 10px 0;
line-height: 1;
cursor: pointer;
user-select: none;
&:last-child{
margin-right: 0;
}
.level-title{
font-size: 14px;
font-weight: bold;
}
.level-price{
font-size: 26px;
font-weight: bold;
color: #A00000;
margin: 2px 0;
.unit{
font-size: 18px;
}
}
.level-origin-price{
text-decoration: line-through;
color: var(--color-info);
}
.remark{
font-size: 12px;
transform: scale(0.9);
white-space: nowrap;
margin-top: 4px;
}
.addition-desc {
position: absolute;
background-color: var(--color-notice);
color: #fff;
padding: 2px 6px;
left: 0;
right: 0;
top: -28px;
font-size: 12px;
height: 20px;
line-height: 20px;
border-radius: 10px;
&:after {
content: ' ';
display: block;
position: absolute;
width: 10px;
height: 10px;
background-color: var(--color-notice);
bottom: 0;
left: 50%;
transform: translate(-50%, 50%) rotate(45deg);
}
}
&.selected{
background: linear-gradient(147deg, #114BA3 0%, #D3B07A 0%, #EFBA93 19%, #D6A184 38%, #B5865A 58%, #F9BC99 79%, #F2C3A9 100%);
.level-origin-price,.level-title{
color:#000
}
}
}
.button{
margin-top: 20px;
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

312
src/index.less Normal file
View File

@ -0,0 +1,312 @@
:root {
--color-primary: #114BA3;
--color-primary-2: #195cc2;
--color-notice: #A00000;
--color-info: #888888;
--color-border: #CAD4D8;
--border-primary: solid 1px var(--color-border);
--border-radius-default: 8px;
--font-size-sm: 12px;
--font-size: 14px;
--font-size-lg: 16px;
--font-size-xl: 18px;
--font-size-2xl: 22px;
--close-size: 24px;
--app-header-height: 60px;
--app-sender-height: 110px;
line-height: 1.3;
font-weight: 400;
font-size: var(--font-size);
--app-bg-color:#000;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
}
* {
margin: 0;
padding: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
}
body{
background-color: var(--app-bg-color);
scroll-behavior: smooth;
}
.flex-center {
display: flex;
align-items: center;
}
.margin-center {
margin: auto;
}
.view-full {
position: fixed;
top: 0;
inset-inline-end: 0;
bottom: 0;
inset-inline-start: 0;
overflow: auto;
outline: 0;
z-index: 1000;
}
.mask-wrapper {
position: fixed;
top: 0;
inset-inline-end: 0;
bottom: 0;
inset-inline-start: 0;
z-index: 1000;
height: 100%;
//background-color: rgba(250,250, 250, 0.15);
background-color: rgba(0, 0, 0, 0.35);
}
svg {
&.icon {
width: 16px;
height: 16px;
}
}
@keyframes loadingCircle {
100% {
transform: rotate(360deg);
-webkit-transform: rotate(360deg); /* Safari and Chrome */
}
}
.ani-loading {
//transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
//-webkit-animation: loadingCircle 1s infinite linear;
animation: loadingCircle 1s infinite linear;
display: inline-block;
}
.checkbox-wrapper {
.flex-center;
cursor: pointer;
span {
}
.checkbox {
display: inline-block;
position: relative;
margin-right: 4px;
.checkbox-inner {
box-sizing: border-box;
display: block;
width: 16px;
height: 16px;
padding: 2px;
background-color: #ffffff;
border: 1px solid #d9d9d9;
border-radius: 4px;
transition: all 0.3s;
.flex-center;
&:after {
content: ' ';
display: inline-block;
box-sizing: border-box;
width: 100%;
height: 100%;
background-color: var(--color-primary);
opacity: 0;
border-radius: 2px;
transition: opacity 0.1s;
}
}
.checkbox-input {
position: absolute;
inset: 0;
z-index: 1;
width: 100%;
height: 100%;
cursor: pointer;
opacity: 0;
&:checked + .checkbox-inner:after {
opacity: 1;
}
}
}
}
.cursor-pointer {
cursor: pointer;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
scroll-behavior: smooth;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
}
.app-wrapper {
height: 100vh;
background-color: var(--app-bg-color);
color: #fff;
}
.content-container {
max-width: 1000px;
margin: auto;
}
.app-header {
overflow: hidden;
background-color: var(--app-bg-color,#f00);
padding: 10px 20px;
line-height: 40px;
box-sizing: border-box;
height: var(--app-header-height);
color: white;
position: fixed;
top: 0;
left: 0;
right: 0;
.header {
float: right;
height: 40px;
}
.nickname{
margin-left: 6px;
}
.logout{
color: #888888;
}
.line{
margin: 0 10px;
border-right: solid 1px #888888;
display: block;
height: 14px;
}
}
.avatar {
width: 36px;
height: 36px;
border-radius: 50%;
}
.app-send-wrapper {
background: #eee;
color: #fff;
padding: 20px;
box-sizing: border-box;
height: var(--app-sender-height);
position: fixed;
bottom: 0;
left: 0;
right: 0;
display: flex;
.content-container,form{
display: flex;
width: 100%;
}
.send-content {
height: calc(var(--app-sender-height) - 40px);
border-radius: 10px;
border: none;
outline: none;
flex: 1;
resize: none;
margin-right: 10px;
box-sizing: border-box;
padding: 10px;
font-size: 16px;
}
.btn-sender{
height: 56px;
}
.open-vip {
color: var(--color-primary);
text-align: center;
margin-top: 4px;
}
}
.app-content {
padding-top: calc(var(--app-header-height) + 0px);
padding-bottom: calc(var(--app-sender-height) + 0px);
background-color: var(--app-bg-color);
}
.message-list-wrapper {
color: #fff;
.message-item {
background-color: #001427;
padding: 10px 0;
&:nth-child(2n){
background-color: #0F2839;
}
p + p{
margin-top: 10px;
}
}
.avatar-container{
margin-right: 20px;
background-color: rgba(255,255,255,0.5);
height: 40px;
width: 40px;
border-radius: 40px;
.avatar{
display: block;
height: 40px;
width: 40px;
border-radius: 40px;
}
}
.message-content {
display: flex;
padding: 20px;
line-height: 1.5;
font-size: 16px;
}
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}

10
src/main.tsx Normal file
View File

@ -0,0 +1,10 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './index.less'
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
<React.StrictMode>
<App/>
</React.StrictMode>,
)

27
src/services/api.ts Normal file
View File

@ -0,0 +1,27 @@
import {get, post} from "./request";
export type UserModel = {
token: string;
username: string;
account: string;
avatar: string;
vip: number;
}
export function login(data: any) {
return post<UserModel>('/api/user/login', data)
}
export function info() {
return get<UserModel>('/api/user/info')
}
export function sendCode(phone: string) {
return post('/api/sendCode', {phone})
}
export function sendChat(message: string) {
return post<{
body: any, content: string
}>('/api/chat', {message})
}

70
src/services/request.ts Normal file
View File

@ -0,0 +1,70 @@
import axios from 'axios';
export interface APIResponse<T> {
code: number;
data?: T;
message: string;
}
// const baseURL = APP_CONFIG.API_PREFIX;
// const FORM_FORMAT = 'application/x-www-form-urlencoded';
const JSON_FORMAT = 'application/json';
export type RequestMethod = 'get' | 'post' | 'put' | 'delete'
const Axios = axios.create({
baseURL: APP_CONFIG.API_PREFIX,
timeout: 20000, // 设置超时时长
headers: {
'Content-Type': JSON_FORMAT,
}
})
// 请求前拦截
// Axios.interceptors.request.use(config => {
// return config
// }, err => {
// return Promise.reject(err)
// })
//
// // 返回后拦截
// Axios.interceptors.response.use(res => {
// return res
// }, err => {
// if (err.message === 'Network Error') {
// err.message = '网络连接异常!';
// } else if (err.code === 'ECONNABORTED') {
// err.message = '请求超时,请重试';
// }
//
// return Promise.reject(err)
// })
export function request<T>(url: string, method: RequestMethod, data: any = null) {
return new Promise<T>((resolve, reject) => {
Axios.request<APIResponse<T>>({
url,
method,
data,
}).then(res => {
if (res.status != 200) {
reject(Error("服务异常,请稍后再试"))
return;
}
const {code, message, data} = res.data
if (code == 0) {
resolve(data as any as T)
} else {
reject(Error(message))
}
})
})
}
export function post<T>(url: string, data: any) {
return request<T>(url, 'post', data)
}
export function get<T>(url: string, data: any = {}) {
return request<T>(url, 'get', data)
}

40
src/utils/classnames.ts Normal file
View File

@ -0,0 +1,40 @@
const hasOwn = {}.hasOwnProperty;
function classNames(...names: any[]) {
const list: string[] = [];
names.forEach(props => {
if(!props) return;
const argType = typeof props;
if (argType === 'string') {
list.push(props)
} else if (Array.isArray(props)) {
if (props.length) {
const inner = classNames.apply(null, props);
if (inner) {
list.push(inner);
}
}
} else if (argType === 'object') {
if (props.className) {
if (typeof props.className === "string") {
list.push(props.className);
} else if (Array.isArray(props.className)) {
list.push(...props.className)
} else {
for (let cls in props.className) {
list.push(cls)
}
}
} else {
for (let key in props) {
if (hasOwn.call(props, key) && props[key]) {
list.push(key);
}
}
}
}
})
return list.join(' ');
}
export default classNames

4
src/utils/numbers.ts Normal file
View File

@ -0,0 +1,4 @@
export function random(min: number, max: number) {
const n = Math.ceil(Math.random() * (max - min));
return n + min;
}

27
src/utils/pxTransform.ts Normal file
View File

@ -0,0 +1,27 @@
const defaultDesignRatio: any = {
350: 5,
640: 9,
750: 10,
828: 11.5
};
// 默认参数
function toFixed(number: number, precision: number) {
const multiplier = Math.pow(10, precision + 1),
wholeNumber = Math.floor(number * multiplier)
return Math.round(wholeNumber / 10) * 10 / multiplier
}
export function pxTransform(size: number, designWidth = 750) {
const config = {
viewportWidth: designWidth,
unitPrecision: defaultDesignRatio[designWidth] || 10,
viewportUnit: 'vw',
minPixelValue: 1
}
if (size <= config.minPixelValue) return size + config.viewportUnit
return toFixed((size / config.viewportWidth * 100), config.unitPrecision) + config.viewportUnit;
}

16
src/utils/strings.ts Normal file
View File

@ -0,0 +1,16 @@
// 手机号脱敏
import dayjs from "dayjs";
export function hidePhone(phone: string) {
return phone.replace(/^(\d{3}).*(\d{4})$/, '$1****$2')
}
// 身份证脱敏
export function hideIDCard(idCard: string) {
return idCard.replace(/^(.{6}).*(.{4})$/, '$1********$2')
}
export function formatDatetime(timestamp: number | string) {
const timeStr = String(timestamp);
return dayjs(Number(timeStr + (timeStr.length == 10 ? '000' : ''))).format('YYYY-MM-DD HH:mm:ss');
}

View File

@ -0,0 +1,15 @@
import React, {useEffect} from "react";
type refType = React.RefObject<HTMLElement | undefined>;
export default function useOnClickOutside(ref: refType, callback: () => void) {
function clickHandler(event: any) {
if (!ref.current?.contains(event.target)) {
callback()
}
}
useEffect(() => {
document.documentElement.addEventListener('click', clickHandler)
return () => document.documentElement.removeEventListener('click', clickHandler)
}, [ref, callback])
}

22
src/vite-env.d.ts vendored Normal file
View File

@ -0,0 +1,22 @@
/// <reference types="vite/client" />
interface IAppConfigItem {
CLIENT_ID: string
SECRET: string
API_PREFIX: string
/**
*
*/
DEPLOY_DIR?: string
/**
*
*/
PUBLIC_PATH?: string
}
type IAPP_ENV = 'development' | 'test' | 'production'
type IAppConfig = {
[key in IAPP_ENV]: IAppConfigItem;
};
// 常量配置类型
declare const APP_ENV: IAPP_ENV;
declare const APP_CONFIG: IAppConfigItem;

31
tsconfig.json Normal file
View File

@ -0,0 +1,31 @@
{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"lib": [
"DOM",
"DOM.Iterable",
"ESNext"
],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
],
"references": [
{
"path": "./tsconfig.node.json"
}
]
}

9
tsconfig.node.json Normal file
View File

@ -0,0 +1,9 @@
{
"compilerOptions": {
"composite": true,
"module": "ESNext",
"moduleResolution": "Node",
"allowSyntheticDefaultImports": true
},
"include": ["vite.config.ts"]
}

30
vite.config.ts Normal file
View File

@ -0,0 +1,30 @@
import {defineConfig} from 'vite'
import react from '@vitejs/plugin-react'
import {viteMockServe} from 'vite-plugin-mock'
import {fileURLToPath} from 'node:url';
// @ts-ignore
import AppConfig from "./config";
const APP_ENV = process.env.NODE_ENV || 'development';
const APP_CONFIG = AppConfig[APP_ENV]
// https://vitejs.dev/config/
export default defineConfig({
define: {
APP_CONFIG
},
plugins: [
react(),
viteMockServe({
mockPath: './mocks',
watchFiles: true, // 监听文件内容变更
logger: true
})
],
base: APP_CONFIG.PUBLIC_PATH,
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
}
})

1387
yarn.lock Normal file

File diff suppressed because it is too large Load Diff