聊天进行到私聊进度备份

This commit is contained in:
heiye111
2026-05-19 21:35:25 +08:00
commit 205b492be9
37 changed files with 16686 additions and 0 deletions

8
.editorconfig Normal file
View File

@@ -0,0 +1,8 @@
[*.{js,jsx,mjs,cjs,ts,tsx,mts,cts,vue,css,scss,sass,less,styl}]
charset = utf-8
indent_size = 2
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
end_of_line = lf
max_line_length = 100

1
.gitattributes vendored Normal file
View File

@@ -0,0 +1 @@
* text=auto eol=lf

42
.gitignore vendored Normal file
View File

@@ -0,0 +1,42 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
.DS_Store
dist
dist-ssr
coverage
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
*.tsbuildinfo
.eslintcache
# Cypress
/cypress/videos/
/cypress/screenshots/
# Vitest
__screenshots__/
# Vite
*.timestamp-*-*.mjs
test-results/
playwright-report/

5
.oxfmtrc.json Normal file
View File

@@ -0,0 +1,5 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"semi": false,
"singleQuote": true
}

10
.oxlintrc.json Normal file
View File

@@ -0,0 +1,10 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["eslint", "unicorn", "oxc", "vue", "vitest"],
"env": {
"browser": true
},
"categories": {
"correctness": "error"
}
}

10
.vscode/extensions.json vendored Normal file
View File

@@ -0,0 +1,10 @@
{
"recommendations": [
"Vue.volar",
"vitest.explorer",
"ms-playwright.playwright",
"dbaeumer.vscode-eslint",
"EditorConfig.EditorConfig",
"oxc.oxc-vscode"
]
}

69
README.md Normal file
View File

@@ -0,0 +1,69 @@
# webappvue1
This template should help get you started developing with Vue 3 in Vite.
## Recommended IDE Setup
[VS Code](https://code.visualstudio.com/) + [Vue (Official)](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur).
## Recommended Browser Setup
- Chromium-based browsers (Chrome, Edge, Brave, etc.):
- [Vue.js devtools](https://chromewebstore.google.com/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd)
- [Turn on Custom Object Formatter in Chrome DevTools](http://bit.ly/object-formatters)
- Firefox:
- [Vue.js devtools](https://addons.mozilla.org/en-US/firefox/addon/vue-js-devtools/)
- [Turn on Custom Object Formatter in Firefox DevTools](https://fxdx.dev/firefox-devtools-custom-object-formatters/)
## Customize configuration
See [Vite Configuration Reference](https://vite.dev/config/).
## Project Setup
```sh
npm install
```
### Compile and Hot-Reload for Development
```sh
npm run dev
```
### Compile and Minify for Production
```sh
npm run build
```
### Run Unit Tests with [Vitest](https://vitest.dev/)
```sh
npm run test:unit
```
### Run End-to-End Tests with [Playwright](https://playwright.dev)
```sh
# Install browsers for the first run
npx playwright install
# When testing on CI, must build the project first
npm run build
# Runs the end-to-end tests
npm run test:e2e
# Runs the tests only on Chromium
npm run test:e2e -- --project=chromium
# Runs the tests of a specific file
npm run test:e2e -- tests/example.spec.ts
# Runs the tests in debug mode
npm run test:e2e -- --debug
```
### Lint with [ESLint](https://eslint.org/)
```sh
npm run lint
```

8
e2e/vue.spec.js Normal file
View File

@@ -0,0 +1,8 @@
import { test, expect } from '@playwright/test'
// See here how to get started:
// https://playwright.dev/docs/intro
test('visits the app root url', async ({ page }) => {
await page.goto('/')
await expect(page.locator('h1')).toHaveText('You did it!')
})

42
eslint.config.js Normal file
View File

@@ -0,0 +1,42 @@
import { defineConfig, globalIgnores } from 'eslint/config'
import globals from 'globals'
import js from '@eslint/js'
import pluginVue from 'eslint-plugin-vue'
import pluginPlaywright from 'eslint-plugin-playwright'
import pluginVitest from '@vitest/eslint-plugin'
import pluginOxlint from 'eslint-plugin-oxlint'
import skipFormatting from 'eslint-config-prettier/flat'
export default defineConfig([
{
name: 'app/files-to-lint',
files: ['**/*.{vue,js,mjs,jsx}'],
},
globalIgnores(['**/dist/**', '**/dist-ssr/**', '**/coverage/**']),
{
languageOptions: {
globals: {
...globals.browser,
},
},
},
js.configs.recommended,
...pluginVue.configs['flat/essential'],
{
...pluginPlaywright.configs['flat/recommended'],
files: ['e2e/**/*.{test,spec}.{js,ts,jsx,tsx}'],
},
{
...pluginVitest.configs.recommended,
files: ['src/**/__tests__/*'],
},
...pluginOxlint.buildFromOxlintConfigFile('.oxlintrc.json'),
skipFormatting,
])

13
index.html Normal file
View File

@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="UTF-8">
<link rel="icon" href="/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vite App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>

8
jsconfig.json Normal file
View File

@@ -0,0 +1,8 @@
{
"compilerOptions": {
"paths": {
"@/*": ["./src/*"]
}
},
"exclude": ["node_modules", "dist"]
}

15225
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

66
package.json Normal file
View File

@@ -0,0 +1,66 @@
{
"name": "webappvue1",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"test:unit": "vitest",
"test:e2e": "playwright test",
"lint": "run-s lint:*",
"lint:oxlint": "oxlint . --fix",
"lint:eslint": "eslint . --fix --cache",
"format": "oxfmt src/"
},
"dependencies": {
"@microsoft/signalr": "^10.0.0",
"@microsoft/signalr-protocol-msgpack": "^10.0.0",
"mitt": "^3.0.1",
"pinia": "^3.0.4",
"update": "^0.7.4",
"vant": "^4.9.24",
"vue": "beta",
"vue-router": "^5.0.4"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@playwright/test": "^1.59.1",
"@vitejs/plugin-vue": "^6.0.6",
"@vitejs/plugin-vue-jsx": "^5.1.5",
"@vitest/eslint-plugin": "^1.6.16",
"@vue/test-utils": "^2.4.6",
"eslint": "^10.2.1",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-oxlint": "~1.60.0",
"eslint-plugin-playwright": "^2.10.1",
"eslint-plugin-vue": "~10.8.0",
"globals": "^17.5.0",
"jsdom": "^29.0.2",
"npm-run-all2": "^8.0.4",
"oxfmt": "^0.45.0",
"oxlint": "~1.60.0",
"vite": "^8.0.8",
"vite-plugin-vue-devtools": "^8.1.1",
"vitest": "^4.1.4"
},
"engines": {
"node": "^20.19.0 || >=22.12.0"
},
"overrides": {
"vue": "beta",
"@vue/compiler-core": "beta",
"@vue/compiler-dom": "beta",
"@vue/compiler-sfc": "beta",
"@vue/compiler-ssr": "beta",
"@vue/compiler-vapor": "beta",
"@vue/reactivity": "beta",
"@vue/runtime-core": "beta",
"@vue/runtime-dom": "beta",
"@vue/runtime-vapor": "beta",
"@vue/server-renderer": "beta",
"@vue/shared": "beta",
"@vue/compat": "beta"
}
}

110
playwright.config.js Normal file
View File

@@ -0,0 +1,110 @@
import process from 'node:process'
import { defineConfig, devices } from '@playwright/test'
/**
* Read environment variables from file.
* https://github.com/motdotla/dotenv
*/
// require('dotenv').config();
/**
* See https://playwright.dev/docs/test-configuration.
*/
export default defineConfig({
testDir: './e2e',
/* Maximum time one test can run for. */
timeout: 30 * 1000,
expect: {
/**
* Maximum time expect() should wait for the condition to be met.
* For example in `await expect(locator).toHaveText();`
*/
timeout: 5000,
},
/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: !!process.env.CI,
/* Retry on CI only */
retries: process.env.CI ? 2 : 0,
/* Opt out of parallel tests on CI. */
workers: process.env.CI ? 1 : undefined,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: 'html',
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
/* Maximum time each action such as `click()` can take. Defaults to 0 (no limit). */
actionTimeout: 0,
/* Base URL to use in actions like `await page.goto('/')`. */
baseURL: process.env.CI ? 'http://localhost:4173' : 'http://localhost:5173',
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: 'on-first-retry',
/* Only on CI systems run the tests headless */
headless: !!process.env.CI,
},
/* Configure projects for major browsers */
projects: [
{
name: 'chromium',
use: {
...devices['Desktop Chrome'],
},
},
{
name: 'firefox',
use: {
...devices['Desktop Firefox'],
},
},
{
name: 'webkit',
use: {
...devices['Desktop Safari'],
},
},
/* Test against mobile viewports. */
// {
// name: 'Mobile Chrome',
// use: {
// ...devices['Pixel 5'],
// },
// },
// {
// name: 'Mobile Safari',
// use: {
// ...devices['iPhone 12'],
// },
// },
/* Test against branded browsers. */
// {
// name: 'Microsoft Edge',
// use: {
// channel: 'msedge',
// },
// },
// {
// name: 'Google Chrome',
// use: {
// channel: 'chrome',
// },
// },
],
/* Folder for test artifacts such as screenshots, videos, traces, etc. */
// outputDir: 'test-results/',
/* Run your local dev server before starting the tests */
webServer: {
/**
* Use the dev server by default for faster feedback loop.
* Use the preview server on CI for more realistic testing.
* Playwright will re-use the local server if there is already a dev-server running.
*/
command: process.env.CI ? 'npm run preview' : 'npm run dev',
port: process.env.CI ? 4173 : 5173,
reuseExistingServer: !process.env.CI,
},
})

BIN
public/0A16339584.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 116 KiB

BIN
public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

11
src/App.vue Normal file
View File

@@ -0,0 +1,11 @@
<template>
<div id="app">
<router-view /> <!-- 这里会根据路由显示不同页面 -->
</div>
</template>

86
src/assets/base.css Normal file
View File

@@ -0,0 +1,86 @@
/* color palette from <https://github.com/vuejs/theme> */
:root {
--vt-c-white: #ffffff;
--vt-c-white-soft: #f8f8f8;
--vt-c-white-mute: #f2f2f2;
--vt-c-black: #181818;
--vt-c-black-soft: #222222;
--vt-c-black-mute: #282828;
--vt-c-indigo: #2c3e50;
--vt-c-divider-light-1: rgba(60, 60, 60, 0.29);
--vt-c-divider-light-2: rgba(60, 60, 60, 0.12);
--vt-c-divider-dark-1: rgba(84, 84, 84, 0.65);
--vt-c-divider-dark-2: rgba(84, 84, 84, 0.48);
--vt-c-text-light-1: var(--vt-c-indigo);
--vt-c-text-light-2: rgba(60, 60, 60, 0.66);
--vt-c-text-dark-1: var(--vt-c-white);
--vt-c-text-dark-2: rgba(235, 235, 235, 0.64);
}
/* semantic color variables for this project */
:root {
--color-background: var(--vt-c-white);
--color-background-soft: var(--vt-c-white-soft);
--color-background-mute: var(--vt-c-white-mute);
--color-border: var(--vt-c-divider-light-2);
--color-border-hover: var(--vt-c-divider-light-1);
--color-heading: var(--vt-c-text-light-1);
--color-text: var(--vt-c-text-light-1);
--section-gap: 160px;
}
@media (prefers-color-scheme: dark) {
:root {
--color-background: var(--vt-c-black);
--color-background-soft: var(--vt-c-black-soft);
--color-background-mute: var(--vt-c-black-mute);
--color-border: var(--vt-c-divider-dark-2);
--color-border-hover: var(--vt-c-divider-dark-1);
--color-heading: var(--vt-c-text-dark-1);
--color-text: var(--vt-c-text-dark-2);
}
}
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
font-weight: normal;
}
body {
min-height: 100vh;
color: var(--color-text);
background: var(--color-background);
transition:
color 0.5s,
background-color 0.5s;
line-height: 1.6;
font-family:
Inter,
-apple-system,
BlinkMacSystemFont,
'Segoe UI',
Roboto,
Oxygen,
Ubuntu,
Cantarell,
'Fira Sans',
'Droid Sans',
'Helvetica Neue',
sans-serif;
font-size: 15px;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}

1
src/assets/logo.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 261.76 226.69"><path d="M161.096.001l-30.225 52.351L100.647.001H-.005l130.877 226.688L261.749.001z" fill="#41b883"/><path d="M161.096.001l-30.225 52.351L100.647.001H52.346l78.526 136.01L209.398.001z" fill="#34495e"/></svg>

After

Width:  |  Height:  |  Size: 276 B

35
src/assets/main.css Normal file
View File

@@ -0,0 +1,35 @@
@import './base.css';
#app {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
font-weight: normal;
}
a,
.green {
text-decoration: none;
color: hsla(160, 100%, 37%, 1);
transition: 0.4s;
padding: 3px;
}
@media (hover: hover) {
a:hover {
background-color: hsla(160, 100%, 37%, 0.2);
}
}
@media (min-width: 1024px) {
body {
display: flex;
place-items: center;
}
#app {
display: grid;
grid-template-columns: 1fr 1fr;
padding: 0 2rem;
}
}

232
src/components/ChatTest.vue Normal file
View File

@@ -0,0 +1,232 @@
<template>
<div class="telegram-ui">
<!-- 搜索框 -->
<van-search v-model="searchQuery" placeholder="搜索聊天或用户..." @search="searchFriends" />
<!-- 聊天列表 -->
<van-list>
<van-cell v-for="chat in chats" :key="chat.id" :title="chat.name" :label="chat.lastMessage"
@click="openChat(chat)">
<template #icon>
<img class="avatar" :src="chat.avatar" alt="头像" />
</template>
</van-cell>
</van-list>
<!-- 聊天窗口 -->
<van-nav-bar :title="currentChat.name" left-text="返回" />
<div class="messages">
<div v-for="(msg, index) in messages" :key="index" :class="['message', msg.from === '我' ? 'me' : 'other']">
<div class="bubble">
<span class="text">{{ msg.text }}</span>
</div>
<div class="receipt" v-if="msg.from === '我'">
<span :class="msg.isRead ? 'read' : 'unread'">
{{ msg.isRead ? '✓ 已读' : '✓ 未读' }}
</span>
</div>
</div>
</div>
<div class="chat-input">
<van-field v-model="newMessage" placeholder="输入消息..." @keyup.enter="sendMessage" />
<van-button type="primary" @click="sendMessage">发送</van-button>
</div>
<!-- 用户信息 -->
<van-card :title="currentChat.name" :desc="currentChat.signature" :thumb="currentChat.avatar" />
<van-button type="success" @click="addFriend">添加好友</van-button>
</div>
</template>
<script setup>
import { ref, onMounted, computed } from 'vue'
import { emitter, connection } from '@/network/signalr'
import 'vant/lib/index.css'
const searchQuery = ref('')
//const isRead = ref(false) // 消息已读状态
const chats = ref([
{ id: 1, name: "小明", avatar: "/0A16339584.png", lastMessage: "你好" },
{ id: 2, name: "小红", avatar: "/0A16339584.png", lastMessage: "在吗?" }
])
const chatMessages = ref({
1: [{ id: 101, from: "小明", text: "你好!", isRead: false }],
2: [{ id: 102, from: "小红", text: "在吗?", isRead: false }]
})
const currentChat = ref({
id: 1,
name: "小明",
avatar: "/0A16339584.png",
signature: "热爱编程和生活"
})
const messages = computed(() => chatMessages.value[currentChat.value.id] || [])
const newMessage = ref("")
onMounted(() => {
emitter.on('SendPrivateMessage', ({ success, message, userid, messageId }) => {
if (success) {
if (!chatMessages.value[userid]) {
chatMessages.value[userid] = []
}
chatMessages.value[userid].push({
id: messageId,
from: chats.value.find(c => c.id === userid)?.name || "未知用户",
text: message,
isRead: false
})
currentChat.value.lastMessage = message
if (currentChat.value.id === userid) {
sendIsRead(messageId)
console.log("收到消息,已发送已读回执:", messageId)
}
} else {
chatMessages.value[currentChat.value.id].push({
id: messageId,
from: "我",
text: message,
isRead: false
})
currentChat.value.lastMessage = message
}
})
emitter.on('SendReadReceipt', (messageId) => {
for (const chatId in chatMessages.value) {
const msg = chatMessages.value[chatId].find(m => m.id === messageId)
if (msg) {
msg.isRead = true
break
}
}
})
})
function openChat(chat) {
currentChat.value = chat
//messages.value = chatMessages.value[chat.id] || []
// 遍历当前聊天窗口的消息
messages.value.forEach(m => {
if (m.from === chat.name && !m.isRead) {
sendIsRead(m.id) // 通知后端这条消息已读
console.log("打开聊天窗口,已发送已读回执:", m.id)
m.isRead = true // 前端立即更新状态
}
})
}
function sendIsRead(messageId) {
connection.send("SendReadReceipt", messageId)
}
async function searchFriends() {
const result = await connection.invoke("SearchFriends", searchQuery.value)
if (result.success) {
chats.value.push({ id: result.userid, name: result.username, avatar: "/0A16339584.png", lastMessage: "222" })
}
}
function sendMessage() {
connection.send("SendPrivateMessage", currentChat.value.id.toString(), newMessage.value)
newMessage.value = ""
}
function addFriend() {
console.log("添加好友 test 方法")
}
</script>
<style scoped>
.telegram-ui {
padding: 10px;
}
.avatar {
width: 40px;
height: 40px;
border-radius: 50%;
}
.messages {
margin: 10px 0;
}
.message.me {
text-align: right;
}
.message.other {
text-align: left;
}
.chat-input {
display: flex;
gap: 8px;
margin-top: 10px;
}
.messages {
padding: 10px;
}
.message {
margin: 8px 0;
display: flex;
flex-direction: column;
}
.message.me {
align-items: flex-end;
}
.message.other {
align-items: flex-start;
}
.bubble {
max-width: 70%;
padding: 8px 12px;
border-radius: 16px;
color: #fff;
font-size: 14px;
}
.message.me .bubble {
background-color: #4a90e2;
/* 蓝色 */
}
.message.other .bubble {
background-color: #e5e5ea;
/* 灰色 */
color: #000;
}
.receipt {
font-size: 12px;
margin-top: 2px;
}
.read {
color: #4a90e2;
/* 蓝色已读 */
}
.unread {
color: #999;
/* 灰色未读 */
}
</style>

View File

@@ -0,0 +1,142 @@
<template>
<div class="chat-app" v-if="true">
<h2>多群聊聊天室</h2>
<!-- 群组选择 -->
<select v-model="currentGroup" @change="joinGroup">
<option v-for="g in groups" :key="g" :value="g">{{ g }}</option>
</select>
<button @click="leaveGroup">离开当前群组</button>
<button @click="joinGroup">加入当前群组</button>
<p>当前在线人数: {{ onlineCount }}</p>
<p>当前群组在线人数: {{ groupOnlineCount }}</p>
<button @click="stopConnection">停止连接</button>
<button @click="getFormData">获取表单数据</button>
<!-- 消息显示 -->
<ul class="messages">
<li v-for="(msg, index) in messages" :key="index">
{{ msg }}
</li>
</ul>
<!-- 输入框和发送按钮 -->
<input v-model="newMessage" placeholder="输入消息..." @keyup.enter="sendMessage" />
<input v-model="userName" placeholder="输入用户名..." />
<button @click="sendMessage">发送</button>
</div>
<!-- <template v-if="true">
<LoginTest />
</template> -->
</template>
<script setup>
import { ref, onMounted } from 'vue'
// import LoginTest from './views/LoginTest.vue'
import { emitter, connection } from '@/network/signalr'
//import { m } from 'vue-router/dist/useApi-D6ckOsFy.js'
const groups = ref(['群聊A', '群聊B', '群聊C'])
const currentGroup = ref(groups.value[0])
const messages = ref([])
const newMessage = ref('')
const userName = ref('') // 可以改为动态输入
const onlineCount = ref(0)
const groupOnlineCount = ref(0) // 存储每个群组的在线人数
let previousGroup = null // 记录之前的群组
onMounted(async () => {
emitter.on('ReceiveMessage', ({ group, user, message }) => {
if (group === currentGroup.value) {
messages.value.push(`${user}@${group}: ${message} `)
}
})
emitter.on("OnlineCount", (count) => {
onlineCount.value = count
})
emitter.on("GroupCount", ({ groupName, count }) => {
if (groupName === currentGroup.value) {
groupOnlineCount.value = count
}
})
// 监听连接成功事件,自动加入群组
emitter.on('Connected', async () => {
await joinGroup()
})
if (connection && connection.state === 'Connected') {
await joinGroup()
}
})
async function stopConnection() {
if (connection) {
await connection.stop()
console.log("连接已停止!")
}
}
//获取用户表单
async function getFormData() {
const data = await connection.invoke("GetFormData")
console.log("获取表单数据:", data)
data.forEach(u => {
console.log((u["Id"], u["Name"], u["Password"], u["CreatedDate"]))
console.log(`Id: ${u[0]}, Name: ${u[1]}, Password: ${u[2]}, Created: ${u[3]} LastModifiedDate: ${u[4]}`)
messages.value.push(`Id: ${u[0]}, Name: ${u[1]}, Password: ${u[2]}, Created: ${u[3]} LastModifiedDate: ${u[4]}`)
})
}
async function joinGroup() {
if (connection) {
// 如果之前有群组,先退出
if (previousGroup && previousGroup !== currentGroup.value) {
await connection.send('LeaveGroup', previousGroup)
}
await connection.send('JoinGroup', currentGroup.value)
previousGroup = currentGroup.value // 记录当前群组为之前的群组
messages.value.push(`已加入群组: ${currentGroup.value}`)
}
}
async function leaveGroup() {
if (connection && currentGroup.value) {
await connection.send('LeaveGroup', currentGroup.value)
messages.value.push(`已离开群组: ${currentGroup.value}`)
previousGroup = null // 离开后不记录之前的群组
}
}
async function sendMessage() {
if (newMessage.value.trim() !== '') {
await connection.send('SendMessageToGroup', currentGroup.value, userName.value, newMessage.value)
newMessage.value = ''
}
}
</script>
<style scoped>
.chat-app {
width: 400px;
margin: auto;
border: 1px solid #3da1b3;
padding: 10px;
}
.messages {
height: 200px;
overflow-y: auto;
border: 1px solid #476781;
margin: 10px 0;
padding: 5px;
}
</style>

View File

@@ -0,0 +1,86 @@
<template>
<div class="item">
<i>
<slot name="icon"></slot>
</i>
<div class="details">
<h3>
<slot name="heading"></slot>
</h3>
<slot></slot>
</div>
</div>
</template>
<style scoped>
.item {
margin-top: 2rem;
display: flex;
position: relative;
}
.details {
flex: 1;
margin-left: 1rem;
}
i {
display: flex;
place-items: center;
place-content: center;
width: 32px;
height: 32px;
color: var(--color-text);
}
h3 {
font-size: 1.2rem;
font-weight: 500;
margin-bottom: 0.4rem;
color: var(--color-heading);
}
@media (min-width: 1024px) {
.item {
margin-top: 0;
padding: 0.4rem 0 1rem calc(var(--section-gap) / 2);
}
i {
top: calc(50% - 25px);
left: -26px;
position: absolute;
border: 1px solid var(--color-border);
background: var(--color-background);
border-radius: 8px;
width: 50px;
height: 50px;
}
.item:before {
content: ' ';
border-left: 1px solid var(--color-border);
position: absolute;
left: 0;
bottom: calc(50% + 25px);
height: calc(50% - 25px);
}
.item:after {
content: ' ';
border-left: 1px solid var(--color-border);
position: absolute;
left: 0;
top: calc(50% + 25px);
height: calc(50% - 25px);
}
.item:first-of-type:before {
display: none;
}
.item:last-of-type:after {
display: none;
}
}
</style>

View File

@@ -0,0 +1,11 @@
import { describe, it, expect } from 'vitest'
import { mount } from '@vue/test-utils'
import HelloWorld from '../HelloWorld.vue'
describe('HelloWorld', () => {
it('renders properly', () => {
const wrapper = mount(HelloWorld, { props: { msg: 'Hello Vitest' } })
expect(wrapper.text()).toContain('Hello Vitest')
})
})

View File

@@ -0,0 +1,7 @@
<template>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor">
<path
d="M15 4a1 1 0 1 0 0 2V4zm0 11v-1a1 1 0 0 0-1 1h1zm0 4l-.707.707A1 1 0 0 0 16 19h-1zm-4-4l.707-.707A1 1 0 0 0 11 14v1zm-4.707-1.293a1 1 0 0 0-1.414 1.414l1.414-1.414zm-.707.707l-.707-.707.707.707zM9 11v-1a1 1 0 0 0-.707.293L9 11zm-4 0h1a1 1 0 0 0-1-1v1zm0 4H4a1 1 0 0 0 1.707.707L5 15zm10-9h2V4h-2v2zm2 0a1 1 0 0 1 1 1h2a3 3 0 0 0-3-3v2zm1 1v6h2V7h-2zm0 6a1 1 0 0 1-1 1v2a3 3 0 0 0 3-3h-2zm-1 1h-2v2h2v-2zm-3 1v4h2v-4h-2zm1.707 3.293l-4-4-1.414 1.414 4 4 1.414-1.414zM11 14H7v2h4v-2zm-4 0c-.276 0-.525-.111-.707-.293l-1.414 1.414C5.42 15.663 6.172 16 7 16v-2zm-.707 1.121l3.414-3.414-1.414-1.414-3.414 3.414 1.414 1.414zM9 12h4v-2H9v2zm4 0a3 3 0 0 0 3-3h-2a1 1 0 0 1-1 1v2zm3-3V3h-2v6h2zm0-6a3 3 0 0 0-3-3v2a1 1 0 0 1 1 1h2zm-3-3H3v2h10V0zM3 0a3 3 0 0 0-3 3h2a1 1 0 0 1 1-1V0zM0 3v6h2V3H0zm0 6a3 3 0 0 0 3 3v-2a1 1 0 0 1-1-1H0zm3 3h2v-2H3v2zm1-1v4h2v-4H4zm1.707 4.707l.586-.586-1.414-1.414-.586.586 1.414 1.414z"
/>
</svg>
</template>

View File

@@ -0,0 +1,7 @@
<template>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="17" fill="currentColor">
<path
d="M11 2.253a1 1 0 1 0-2 0h2zm-2 13a1 1 0 1 0 2 0H9zm.447-12.167a1 1 0 1 0 1.107-1.666L9.447 3.086zM1 2.253L.447 1.42A1 1 0 0 0 0 2.253h1zm0 13H0a1 1 0 0 0 1.553.833L1 15.253zm8.447.833a1 1 0 1 0 1.107-1.666l-1.107 1.666zm0-14.666a1 1 0 1 0 1.107 1.666L9.447 1.42zM19 2.253h1a1 1 0 0 0-.447-.833L19 2.253zm0 13l-.553.833A1 1 0 0 0 20 15.253h-1zm-9.553-.833a1 1 0 1 0 1.107 1.666L9.447 14.42zM9 2.253v13h2v-13H9zm1.553-.833C9.203.523 7.42 0 5.5 0v2c1.572 0 2.961.431 3.947 1.086l1.107-1.666zM5.5 0C3.58 0 1.797.523.447 1.42l1.107 1.666C2.539 2.431 3.928 2 5.5 2V0zM0 2.253v13h2v-13H0zm1.553 13.833C2.539 15.431 3.928 15 5.5 15v-2c-1.92 0-3.703.523-5.053 1.42l1.107 1.666zM5.5 15c1.572 0 2.961.431 3.947 1.086l1.107-1.666C9.203 13.523 7.42 13 5.5 13v2zm5.053-11.914C11.539 2.431 12.928 2 14.5 2V0c-1.92 0-3.703.523-5.053 1.42l1.107 1.666zM14.5 2c1.573 0 2.961.431 3.947 1.086l1.107-1.666C18.203.523 16.421 0 14.5 0v2zm3.5.253v13h2v-13h-2zm1.553 12.167C18.203 13.523 16.421 13 14.5 13v2c1.573 0 2.961.431 3.947 1.086l1.107-1.666zM14.5 13c-1.92 0-3.703.523-5.053 1.42l1.107 1.666C11.539 15.431 12.928 15 14.5 15v-2z"
/>
</svg>
</template>

View File

@@ -0,0 +1,7 @@
<template>
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="20" fill="currentColor">
<path
d="M11.447 8.894a1 1 0 1 0-.894-1.789l.894 1.789zm-2.894-.789a1 1 0 1 0 .894 1.789l-.894-1.789zm0 1.789a1 1 0 1 0 .894-1.789l-.894 1.789zM7.447 7.106a1 1 0 1 0-.894 1.789l.894-1.789zM10 9a1 1 0 1 0-2 0h2zm-2 2.5a1 1 0 1 0 2 0H8zm9.447-5.606a1 1 0 1 0-.894-1.789l.894 1.789zm-2.894-.789a1 1 0 1 0 .894 1.789l-.894-1.789zm2 .789a1 1 0 1 0 .894-1.789l-.894 1.789zm-1.106-2.789a1 1 0 1 0-.894 1.789l.894-1.789zM18 5a1 1 0 1 0-2 0h2zm-2 2.5a1 1 0 1 0 2 0h-2zm-5.447-4.606a1 1 0 1 0 .894-1.789l-.894 1.789zM9 1l.447-.894a1 1 0 0 0-.894 0L9 1zm-2.447.106a1 1 0 1 0 .894 1.789l-.894-1.789zm-6 3a1 1 0 1 0 .894 1.789L.553 4.106zm2.894.789a1 1 0 1 0-.894-1.789l.894 1.789zm-2-.789a1 1 0 1 0-.894 1.789l.894-1.789zm1.106 2.789a1 1 0 1 0 .894-1.789l-.894 1.789zM2 5a1 1 0 1 0-2 0h2zM0 7.5a1 1 0 1 0 2 0H0zm8.553 12.394a1 1 0 1 0 .894-1.789l-.894 1.789zm-1.106-2.789a1 1 0 1 0-.894 1.789l.894-1.789zm1.106 1a1 1 0 1 0 .894 1.789l-.894-1.789zm2.894.789a1 1 0 1 0-.894-1.789l.894 1.789zM8 19a1 1 0 1 0 2 0H8zm2-2.5a1 1 0 1 0-2 0h2zm-7.447.394a1 1 0 1 0 .894-1.789l-.894 1.789zM1 15H0a1 1 0 0 0 .553.894L1 15zm1-2.5a1 1 0 1 0-2 0h2zm12.553 2.606a1 1 0 1 0 .894 1.789l-.894-1.789zM17 15l.447.894A1 1 0 0 0 18 15h-1zm1-2.5a1 1 0 1 0-2 0h2zm-7.447-5.394l-2 1 .894 1.789 2-1-.894-1.789zm-1.106 1l-2-1-.894 1.789 2 1 .894-1.789zM8 9v2.5h2V9H8zm8.553-4.894l-2 1 .894 1.789 2-1-.894-1.789zm.894 0l-2-1-.894 1.789 2 1 .894-1.789zM16 5v2.5h2V5h-2zm-4.553-3.894l-2-1-.894 1.789 2 1 .894-1.789zm-2.894-1l-2 1 .894 1.789 2-1L8.553.106zM1.447 5.894l2-1-.894-1.789-2 1 .894 1.789zm-.894 0l2 1 .894-1.789-2-1-.894 1.789zM0 5v2.5h2V5H0zm9.447 13.106l-2-1-.894 1.789 2 1 .894-1.789zm0 1.789l2-1-.894-1.789-2 1 .894 1.789zM10 19v-2.5H8V19h2zm-6.553-3.894l-2-1-.894 1.789 2 1 .894-1.789zM2 15v-2.5H0V15h2zm13.447 1.894l2-1-.894-1.789-2 1 .894 1.789zM18 15v-2.5h-2V15h2z"
/>
</svg>
</template>

View File

@@ -0,0 +1,7 @@
<template>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor">
<path
d="M10 3.22l-.61-.6a5.5 5.5 0 0 0-7.666.105 5.5 5.5 0 0 0-.114 7.665L10 18.78l8.39-8.4a5.5 5.5 0 0 0-.114-7.665 5.5 5.5 0 0 0-7.666-.105l-.61.61z"
/>
</svg>
</template>

View File

@@ -0,0 +1,19 @@
<!-- This icon is from <https://github.com/Templarian/MaterialDesign>, distributed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0) license-->
<template>
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
aria-hidden="true"
role="img"
class="iconify iconify--mdi"
width="24"
height="24"
preserveAspectRatio="xMidYMid meet"
viewBox="0 0 24 24"
>
<path
d="M20 18v-4h-3v1h-2v-1H9v1H7v-1H4v4h16M6.33 8l-1.74 4H7v-1h2v1h6v-1h2v1h2.41l-1.74-4H6.33M9 5v1h6V5H9m12.84 7.61c.1.22.16.48.16.8V18c0 .53-.21 1-.6 1.41c-.4.4-.85.59-1.4.59H4c-.55 0-1-.19-1.4-.59C2.21 19 2 18.53 2 18v-4.59c0-.32.06-.58.16-.8L4.5 7.22C4.84 6.41 5.45 6 6.33 6H7V5c0-.55.18-1 .57-1.41C7.96 3.2 8.44 3 9 3h6c.56 0 1.04.2 1.43.59c.39.41.57.86.57 1.41v1h.67c.88 0 1.49.41 1.83 1.22l2.34 5.39z"
fill="currentColor"
></path>
</svg>
</template>

27
src/main.js Normal file
View File

@@ -0,0 +1,27 @@
import './assets/main.css'
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
// 引入 Vant 组件
import { Search, Cell, List, NavBar, Card, Field, Button } from 'vant'
import 'vant/lib/index.css'
const app = createApp(App)
// 注册 Vant 组件
app.use(Search)
app.use(Cell)
app.use(List)
app.use(NavBar)
app.use(Card)
app.use(Field)
app.use(Button)
app.use(createPinia())
app.use(router)
app.mount('#app')

102
src/network/signalr.js Normal file
View File

@@ -0,0 +1,102 @@
import * as signalR from '@microsoft/signalr'
import * as msgpack from '@microsoft/signalr-protocol-msgpack'
import mitt from 'mitt'
import router from '@/router'
export const emitter = mitt()
let connection = null
// 注册消息处理函数
function registerHandlers(conn) {
conn.on('ReceiveMessage', (group, user, message) => {
emitter.emit('ReceiveMessage', { group, user, message })
})
conn.on('OnlineCount', (count) => {
emitter.emit('OnlineCount', count)
})
conn.on('GroupCount', (groupName, count) => {
emitter.emit('GroupCount', { groupName, count })
})
conn.on('RegisterResult', (success, message) => {
emitter.emit('RegisterResult', { success, message })
})
conn.on('LoginResult', async (success, accessToken, refreshToken) => {
emitter.emit('LoginResult', { success, accessToken, refreshToken })
})
conn.on('SendPrivateMessage', (success, message, userid, messageId) => {
emitter.emit('SendPrivateMessage', { success, message, userid, messageId })
})
conn.on('SendReadReceipt', (messageId) => {
emitter.emit('SendReadReceipt', messageId)
})
}
// 初始连接(不带 token
async function createConnection() {
connection = new signalR.HubConnectionBuilder()
.withUrl('http://192.168.1.254:5162/Chat')
.withHubProtocol(new msgpack.MessagePackHubProtocol())
.withAutomaticReconnect()
.build()
registerHandlers(connection)
await connection.start()
emitter.emit('Connected') // 通知页面连接成功
return connection
}
// 刷新 AccessToken
async function RefreshAccessToken() {
const oldRefreshToken = localStorage.getItem('refreshToken')
if (!oldRefreshToken) return
connection.send('RefreshAccessToken', oldRefreshToken)
connection.off('ReceiveNewAccessToken')
connection.on('ReceiveNewAccessToken', async (newAccessToken, newRefreshToken) => {
localStorage.setItem('accessToken', newAccessToken)
localStorage.setItem('refreshToken', newRefreshToken)
await reconnectWithToken()
})
connection.off('RefreshFailed')
connection.on('RefreshFailed', (message) => {
console.error('刷新失败:', message)
localStorage.removeItem('accessToken')
localStorage.removeItem('refreshToken')
router.push('/')
})
}
// 使用新的 token 重建连接
async function reconnectWithToken() {
const accessToken = localStorage.getItem('accessToken')
if (!accessToken) return
if (connection) {
await connection.stop()
}
connection = new signalR.HubConnectionBuilder()
.withUrl(`http://192.168.1.254:5162/Chat?access_token=${accessToken}`)
.withHubProtocol(new msgpack.MessagePackHubProtocol())
.withAutomaticReconnect()
.build()
registerHandlers(connection)
await connection.start()
emitter.emit('Connected') // 通知页面连接成功
}
// 页面加载时自动执行
;(async () => {
await createConnection()
await RefreshAccessToken() // 尝试刷新 token 并重连
})()
export { connection, reconnectWithToken }

27
src/router/index.js Normal file
View File

@@ -0,0 +1,27 @@
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: () => import('@/views/LoginTest.vue'),
},
{
path: '/chat',
name: 'chat',
component: () => import('@/components/HelloWorld.vue'),
},
{
path: '/chattest',
name: 'chattest',
// route level code-splitting
// this generates a separate chunk (About.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import('@/components/ChatTest.vue'),
},
],
})
export default router

12
src/stores/counter.js Normal file
View File

@@ -0,0 +1,12 @@
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
return { count, doubleCount, increment }
})

44
src/views/HomeView.vue Normal file
View File

@@ -0,0 +1,44 @@
<script setup>
defineProps({
msg: {
type: String,
required: true,
},
})
</script>
<template>
<div class="greetings">
<h1 class="green">{{ msg }}</h1>
<h3>
Youve successfully created a project with
<a href="https://vite.dev/" target="_blank" rel="noopener">Vite</a> +
<a href="https://vuejs.org/" target="_blank" rel="noopener">Vue 3</a>.
</h3>
</div>
</template>
<style scoped>
h1 {
font-weight: 500;
font-size: 2.6rem;
position: relative;
top: -10px;
}
h3 {
font-size: 1.2rem;
}
.greetings h1,
.greetings h3 {
text-align: center;
}
@media (min-width: 1024px) {
.greetings h1,
.greetings h3 {
text-align: left;
}
}
</style>

168
src/views/LoginTest.vue Normal file
View File

@@ -0,0 +1,168 @@
<template>
<div class="auth-container">
<div class="auth-box">
<h2>{{ isLogin ? "登录你的账户" : "创建新账户" }}</h2>
<form @submit.prevent="handleSubmit">
<div v-if="isLogin" class="form-group">
<label>邮箱</label>
<input v-model="email" type="email" required />
</div>
<div v-if="isLogin" class="form-group">
<label>密码</label>
<input v-model="password" type="password" required />
</div>
<!-- 注册时额外字段 -->
<!-- <div v-if="!isLogin" class="form-group">
<label>确认密码</label>
<input v-model="confirmPassword" type="password" required />
</div> -->
<button type="submit" class="btn-primary">
{{ isLogin ? "登录" : "注册" }}
</button>
</form>
<p class="switch-mode">
{{ isLogin ? "没有账户?" : "已有账户?" }}
<a href="#" @click.prevent="isLogin = !isLogin">
{{ isLogin ? "注册" : "登录" }}
</a>
</p>
</div>
</div>
</template>
<script setup>
import { ref, onMounted } from "vue";
import { connection, reconnectWithToken, emitter } from '@/network/signalr'
import { useRouter } from 'vue-router'
const isLogin = ref(true);
const email = ref("");
const password = ref("");
const confirmPassword = ref("");
const router = useRouter()
onMounted(async () => {
// 启动SignalR连接
//await startConnection();
emitter.on("RegisterResult", ({ success, message }) => {
alert(message);
if (success) {
isLogin.value = true; // 注册成功后切换到登录界面
console.log("注册成功:", message);
return
}
console.error("注册失败:", message);
});
emitter.on("LoginResult", async ({ success, accessToken, refreshToken }) => {
if (success) {
localStorage.setItem("accessToken", accessToken);
localStorage.setItem("refreshToken", refreshToken);
console.log("登录成功:", accessToken, "=========", refreshToken);
await reconnectWithToken();
router.push("/chattest"); // 登录成功后跳转到主界面 隐藏登录注册界面
return
}
console.error("登录失败:", accessToken); // 这里accessToken实际上是错误信息
});
});
function RegisterRequest() {
connection.send("Register")
.catch(err => console.error("注册请求失败:", err));
}
function LoginRequest(email, password) {
connection.send("LoginAuthentication", email, password)
.catch(err => console.error("登录请求失败:", err));
}
function handleSubmit() {
if (!isLogin.value && password.value !== confirmPassword.value) {
alert("两次密码不一致!");
return;
}
if (isLogin.value) {
LoginRequest(email.value, password.value);
} else {
RegisterRequest(email.value, password.value);
}
}
</script>
<style scoped>
.auth-container {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background: #f3f2f1;
}
.auth-box {
background: #fff;
padding: 2rem;
width: 350px;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
h2 {
margin-bottom: 1.5rem;
color: #0078d4;
/* 微软蓝 */
text-align: center;
}
.form-group {
margin-bottom: 1rem;
}
label {
display: block;
margin-bottom: 0.3rem;
font-weight: 500;
}
input {
width: 100%;
padding: 0.6rem;
border: 1px solid #ccc;
border-radius: 4px;
}
.btn-primary {
width: 100%;
padding: 0.8rem;
background: #0078d4;
color: #fff;
border: none;
border-radius: 4px;
font-weight: bold;
cursor: pointer;
}
.btn-primary:hover {
background: #005a9e;
}
.switch-mode {
margin-top: 1rem;
text-align: center;
}
.switch-mode a {
color: #0078d4;
text-decoration: none;
font-weight: 500;
}
</style>

24
vite.config.js Normal file
View File

@@ -0,0 +1,24 @@
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import vueDevTools from 'vite-plugin-vue-devtools'
// https://vite.dev/config/
export default defineConfig({
plugins: [
vue(),
vueJsx(),
vueDevTools(),
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
},
},
server: {
port: 5173,
host: '0.0.0.0',
},
})

14
vitest.config.js Normal file
View File

@@ -0,0 +1,14 @@
import { fileURLToPath } from 'node:url'
import { mergeConfig, defineConfig, configDefaults } from 'vitest/config'
import viteConfig from './vite.config'
export default mergeConfig(
viteConfig,
defineConfig({
test: {
environment: 'jsdom',
exclude: [...configDefaults.exclude, 'e2e/**'],
root: fileURLToPath(new URL('./', import.meta.url)),
},
}),
)