feat: 接入两端用户名登录和独立学习空间 (#2)
This commit is contained in:
@@ -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/
|
||||
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"Vue.volar",
|
||||
"vitest.explorer",
|
||||
"ms-playwright.playwright"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { expect, test } from '@playwright/test'
|
||||
|
||||
test('username login, private empty space, logout and history protection', async ({ page }) => {
|
||||
const user = { id: 42, username: 'fictional-reader', role: 'learner' }
|
||||
await page.route('**/api/v1/**', async route => {
|
||||
const path = new URL(route.request().url()).pathname
|
||||
let data: unknown = null
|
||||
if (path.endsWith('/login')) {
|
||||
expect(route.request().postDataJSON()).toEqual({ username: user.username, password: 'fictional-password' })
|
||||
data = { token: 'fictional-session', user }
|
||||
} else if (path.endsWith('/me')) data = user
|
||||
else if (path.endsWith('/space')) data = { ownerId: user.id, language: 'en' }
|
||||
await route.fulfill({ json: { code: 200, data } })
|
||||
})
|
||||
await page.goto('/')
|
||||
await expect(page.getByRole('heading', { name: '欢迎回来' })).toBeVisible()
|
||||
await page.getByLabel('账号').fill(user.username)
|
||||
await page.getByLabel('密码', { exact: true }).fill('fictional-password')
|
||||
await page.getByRole('button', { name: '登录', exact: true }).click()
|
||||
await expect(page.getByRole('heading', { name: '我的书库' })).toBeVisible()
|
||||
await expect(page.getByText('书库还是空的')).toBeVisible()
|
||||
await expect(page.getByText(user.username, { exact: true })).toBeVisible()
|
||||
await page.reload()
|
||||
await expect(page.getByRole('heading', { name: '我的书库' })).toBeVisible()
|
||||
await page.goto('/?history=1')
|
||||
await expect(page.getByRole('heading', { name: '我的书库' })).toBeVisible()
|
||||
await page.getByRole('button', { name: '退出登录' }).click()
|
||||
await expect(page.getByRole('heading', { name: '欢迎回来' })).toBeVisible()
|
||||
await page.goBack()
|
||||
await expect(page.getByText(user.username, { exact: true })).toHaveCount(0)
|
||||
await expect(page.getByRole('heading', { name: '欢迎回来' })).toBeVisible()
|
||||
})
|
||||
|
||||
test('invalid credentials stay on login with accessible feedback', async ({ page }) => {
|
||||
await page.route('**/api/v1/login', route => route.fulfill({ status: 401, json: { code: 401, msg: '账号或密码错误' } }))
|
||||
await page.goto('/login')
|
||||
await page.getByLabel('账号').fill('fictional-reader')
|
||||
await page.getByLabel('密码', { exact: true }).fill('fictional-wrong-password')
|
||||
await page.getByRole('button', { name: '登录', exact: true }).click()
|
||||
await expect(page.getByRole('alert')).toHaveText('账号或密码错误')
|
||||
await expect(page.getByRole('heading', { name: '我的书库' })).toHaveCount(0)
|
||||
})
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "@tsconfig/node24/tsconfig.json",
|
||||
"include": ["./**/*"]
|
||||
}
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta name="theme-color" content="#284c38">
|
||||
<title>LexGo · 学习空间</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"name": "learner",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "run-p type-check \"build-only {@}\" --",
|
||||
"preview": "vite preview",
|
||||
"test:unit": "vitest",
|
||||
"test:e2e": "playwright test",
|
||||
"build-only": "vite build",
|
||||
"type-check": "vue-tsc --build"
|
||||
},
|
||||
"dependencies": {
|
||||
"element-plus": "^2.14.5",
|
||||
"pinia": "^4.0.2",
|
||||
"vue": "^3.5.40",
|
||||
"vue-router": "^5.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.61.1",
|
||||
"@tsconfig/node24": "^24.0.4",
|
||||
"@types/jsdom": "^28.0.3",
|
||||
"@types/node": "^24.13.3",
|
||||
"@vitejs/plugin-vue": "^6.0.8",
|
||||
"@vue/test-utils": "^2.4.11",
|
||||
"@vue/tsconfig": "^0.9.1",
|
||||
"jsdom": "^29.1.1",
|
||||
"npm-run-all2": "^9.0.2",
|
||||
"typescript": "~6.0.0",
|
||||
"vite": "^8.1.5",
|
||||
"vitest": "^4.1.10",
|
||||
"vue-tsc": "^3.3.7"
|
||||
},
|
||||
"engines": {
|
||||
"node": "22.22.1"
|
||||
},
|
||||
"packageManager": "pnpm@9.15.1"
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { defineConfig, devices } from '@playwright/test'
|
||||
|
||||
// Local development traffic must bypass any workstation HTTP proxy.
|
||||
process.env.NO_PROXY = [process.env.NO_PROXY, '127.0.0.1', 'localhost'].filter(Boolean).join(',')
|
||||
|
||||
export default defineConfig({
|
||||
testDir: './e2e',
|
||||
forbidOnly: !!process.env.CI,
|
||||
retries: 0,
|
||||
reporter: 'list',
|
||||
use: { baseURL: 'http://127.0.0.1:5173', headless: true, trace: 'off' },
|
||||
projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'], channel: 'chrome' } }],
|
||||
webServer: { command: 'npm run dev -- --host 127.0.0.1', url: 'http://127.0.0.1:5173', reuseExistingServer: !process.env.CI },
|
||||
})
|
||||
Generated
+2144
File diff suppressed because it is too large
Load Diff
Binary file not shown.
|
After Width: | Height: | Size: 4.2 KiB |
@@ -0,0 +1,12 @@
|
||||
<script setup lang="ts">
|
||||
import { watch } from 'vue'
|
||||
import { RouterView, useRouter } from 'vue-router'
|
||||
import { useSessionStore } from './stores/session'
|
||||
const session = useSessionStore()
|
||||
const router = useRouter()
|
||||
watch(() => session.user, user => {
|
||||
if (!user && router.currentRoute.value.meta.private) void router.replace('/login')
|
||||
})
|
||||
</script>
|
||||
|
||||
<template><RouterView /></template>
|
||||
@@ -0,0 +1,114 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { useSessionStore, TOKEN_KEY } from '../stores/session'
|
||||
|
||||
// All accounts and tokens in these tests are deliberately fictitious.
|
||||
const user = { id: 7, username: 'fictional-reader', role: 'learner' }
|
||||
const ok = (data: unknown) => new Response(JSON.stringify({ code: 200, data }), { status: 200 })
|
||||
const denied = () => new Response(JSON.stringify({ code: 401, msg: '账号或密码错误' }), { status: 401 })
|
||||
const loginResult = () => ok({ token: 'fictional-token', expiresAt: '2030-01-01', user })
|
||||
|
||||
describe('learner session boundaries', () => {
|
||||
beforeEach(() => {
|
||||
sessionStorage.clear()
|
||||
setActivePinia(createPinia())
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('accepts a username without email format and stores only the opaque token', async () => {
|
||||
const fetch = vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(loginResult())
|
||||
const store = useSessionStore()
|
||||
await store.login('fictional-reader', 'fictional-password')
|
||||
expect(JSON.parse(fetch.mock.calls[0]![1]!.body as string)).toEqual({ username: 'fictional-reader', password: 'fictional-password' })
|
||||
expect(store.user).toEqual(user)
|
||||
expect(sessionStorage.getItem(TOKEN_KEY)).toBe('fictional-token')
|
||||
expect(sessionStorage.length).toBe(1)
|
||||
})
|
||||
|
||||
it('failed account switch clears the previous private identity and space', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(loginResult()).mockResolvedValueOnce(ok({ ownerId: 7, language: 'en' })).mockResolvedValueOnce(denied())
|
||||
const store = useSessionStore()
|
||||
await store.login('fictional-reader', 'fictional-password')
|
||||
await store.loadSpace()
|
||||
await expect(store.login('fictional-other', 'incorrect')).rejects.toThrow('账号或密码错误')
|
||||
expect(store.user).toBeNull()
|
||||
expect(store.space).toBeNull()
|
||||
expect(sessionStorage.getItem(TOKEN_KEY)).toBeNull()
|
||||
})
|
||||
|
||||
it('validates a persisted session before exposing identity and clears it on 401', async () => {
|
||||
sessionStorage.setItem(TOKEN_KEY, 'fictional-expired-token')
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(denied())
|
||||
const store = useSessionStore()
|
||||
expect(store.user).toBeNull()
|
||||
await store.restore()
|
||||
expect(store.user).toBeNull()
|
||||
expect(sessionStorage.getItem(TOKEN_KEY)).toBeNull()
|
||||
})
|
||||
|
||||
it('clears identity and space when a private request gets 401', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(loginResult()).mockResolvedValueOnce(denied())
|
||||
const store = useSessionStore()
|
||||
await store.login('fictional-reader', 'fictional-password')
|
||||
await expect(store.loadSpace()).rejects.toThrow()
|
||||
expect(store.user).toBeNull()
|
||||
expect(store.space).toBeNull()
|
||||
expect(sessionStorage.getItem(TOKEN_KEY)).toBeNull()
|
||||
})
|
||||
|
||||
it('clears locally immediately even if server logout fails', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(loginResult()).mockRejectedValueOnce(new Error('offline'))
|
||||
const store = useSessionStore()
|
||||
await store.login('fictional-reader', 'fictional-password')
|
||||
const logout = store.logout()
|
||||
expect(store.user).toBeNull()
|
||||
expect(store.space).toBeNull()
|
||||
expect(sessionStorage.getItem(TOKEN_KEY)).toBeNull()
|
||||
await expect(logout).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('does not resurrect private space from a response arriving after logout', async () => {
|
||||
let finish!: (value: Response) => void
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(loginResult()).mockImplementationOnce(() => new Promise(resolve => { finish = resolve })).mockResolvedValueOnce(ok(null))
|
||||
const store = useSessionStore()
|
||||
await store.login('fictional-reader', 'fictional-password')
|
||||
const request = store.loadSpace()
|
||||
await store.logout()
|
||||
finish(ok({ ownerId: 7, language: 'en' }))
|
||||
await request
|
||||
expect(store.space).toBeNull()
|
||||
expect(store.user).toBeNull()
|
||||
})
|
||||
|
||||
it('an old request 401 cannot clear a newly signed-in account', async () => {
|
||||
let finish!: (value: Response) => void
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(loginResult()).mockImplementationOnce(() => new Promise(resolve => { finish = resolve })).mockResolvedValueOnce(ok({ token: 'fictional-new-token', user: { ...user, id: 9 } }))
|
||||
const store = useSessionStore()
|
||||
await store.login('fictional-reader', 'fictional-password')
|
||||
const request = store.loadSpace()
|
||||
await store.login('fictional-other', 'fictional-password')
|
||||
finish(denied())
|
||||
await expect(request).rejects.toThrow()
|
||||
expect(store.user?.id).toBe(9)
|
||||
})
|
||||
|
||||
it('a late login response cannot restore a session after logout', async () => {
|
||||
let finish!: (value: Response) => void
|
||||
vi.spyOn(globalThis, 'fetch').mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))
|
||||
const store = useSessionStore()
|
||||
const request = store.login('fictional-reader', 'fictional-password')
|
||||
await store.logout()
|
||||
finish(loginResult())
|
||||
await request
|
||||
expect(store.user).toBeNull()
|
||||
expect(sessionStorage.getItem(TOKEN_KEY)).toBeNull()
|
||||
})
|
||||
|
||||
it('does not expose a space whose owner differs from the authenticated account', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(loginResult()).mockResolvedValueOnce(ok({ ownerId: 99, language: 'en' }))
|
||||
const store = useSessionStore()
|
||||
await store.login('fictional-reader', 'fictional-password')
|
||||
await expect(store.loadSpace()).rejects.toThrow()
|
||||
expect(store.space).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,6 @@
|
||||
<template>
|
||||
<svg class="book-mark" viewBox="0 0 64 64" fill="none" aria-hidden="true">
|
||||
<path d="M32 18C24 12 14 12 6 15v36c8-3 18-3 26 3 8-6 18-6 26-3V15c-8-3-18-3-26 3Z" stroke="currentColor" stroke-width="2" stroke-linejoin="round" />
|
||||
<path d="M32 18v36M15 24c4-1 7 0 10 1M15 32c4-1 7 0 10 1M40 25c3-1 6-2 10-1M40 33c3-1 6-2 10-1" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
|
||||
</svg>
|
||||
</template>
|
||||
@@ -0,0 +1,9 @@
|
||||
import { createApp } from 'vue'
|
||||
import { createPinia } from 'pinia'
|
||||
import App from './App.vue'
|
||||
import router from './router'
|
||||
import 'element-plus/es/components/button/style/css'
|
||||
import 'element-plus/es/components/input/style/css'
|
||||
import './style.css'
|
||||
|
||||
createApp(App).use(createPinia()).use(router).mount('#app')
|
||||
@@ -0,0 +1,18 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
import { useSessionStore } from '../stores/session'
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHistory(import.meta.env.BASE_URL),
|
||||
routes: [
|
||||
{ path: '/login', name: 'login', component: () => import('../views/LoginView.vue') },
|
||||
{ path: '/', name: 'library', meta: { private: true }, component: () => import('../views/LibraryView.vue') },
|
||||
{ path: '/:pathMatch(.*)*', redirect: '/' },
|
||||
],
|
||||
})
|
||||
router.beforeEach(async to => {
|
||||
const session = useSessionStore()
|
||||
await session.restore()
|
||||
if (to.meta.private && !session.user) return '/login'
|
||||
if (to.name === 'login' && session.user) return '/'
|
||||
})
|
||||
export default router
|
||||
@@ -0,0 +1,95 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
|
||||
export const TOKEN_KEY = 'lexgo-learner-token'
|
||||
interface User { id: number; username: string; role: 'admin' | 'learner' }
|
||||
interface Space { ownerId: number; language: 'en' }
|
||||
interface Login { token: string; expiresAt: string; user: User }
|
||||
|
||||
export const useSessionStore = defineStore('session', () => {
|
||||
const user = ref<User | null>(null)
|
||||
const space = ref<Space | null>(null)
|
||||
const notice = ref('')
|
||||
let token = sessionStorage.getItem(TOKEN_KEY) ?? ''
|
||||
// Invalidate all in-flight work on any session boundary, including failed switches.
|
||||
let generation = 0
|
||||
let initialized = false
|
||||
let restoring: Promise<void> | undefined
|
||||
|
||||
function clear() {
|
||||
generation++
|
||||
token = ''
|
||||
user.value = null
|
||||
space.value = null
|
||||
sessionStorage.removeItem(TOKEN_KEY)
|
||||
}
|
||||
|
||||
async function request<T>(path: string, method = 'GET', body?: unknown, auth = token, version = generation): Promise<T> {
|
||||
const response = await fetch(`/api/v1/${path}`, {
|
||||
method,
|
||||
headers: { ...(auth ? { Authorization: `Bearer ${auth}` } : {}), ...(body ? { 'Content-Type': 'application/json' } : {}) },
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
cache: 'no-store',
|
||||
})
|
||||
if (response.status === 401 && version === generation) {
|
||||
clear()
|
||||
notice.value = '登录已失效,请重新登录。'
|
||||
}
|
||||
const result = await response.json()
|
||||
if (!response.ok || result.code !== 200) throw new Error(result.msg || '请求失败,请稍后重试。')
|
||||
return result.data as T
|
||||
}
|
||||
|
||||
async function login(username: string, password: string) {
|
||||
clear()
|
||||
initialized = true
|
||||
notice.value = ''
|
||||
const version = generation
|
||||
const result = await request<Login>('login', 'POST', { username, password }, '', version)
|
||||
if (version !== generation) return
|
||||
sessionStorage.setItem(TOKEN_KEY, result.token)
|
||||
token = result.token
|
||||
user.value = result.user
|
||||
}
|
||||
|
||||
async function restore() {
|
||||
if (initialized) return
|
||||
if (restoring) return restoring
|
||||
const version = generation
|
||||
restoring = (async () => {
|
||||
try {
|
||||
if (!token) return
|
||||
const account = await request<User>('me')
|
||||
if (version === generation) user.value = account
|
||||
} catch {
|
||||
if (version === generation) {
|
||||
clear()
|
||||
notice.value = '暂时无法恢复登录,请重新登录。'
|
||||
}
|
||||
} finally {
|
||||
initialized = true
|
||||
restoring = undefined
|
||||
}
|
||||
})()
|
||||
return restoring
|
||||
}
|
||||
|
||||
async function loadSpace() {
|
||||
if (!user.value) throw new Error('请先登录。')
|
||||
const version = generation
|
||||
const ownerId = user.value.id
|
||||
const result = await request<Space>('space')
|
||||
if (version !== generation) return
|
||||
if (result.ownerId !== ownerId || result.language !== 'en') throw new Error('学习空间暂时无法加载,请稍后重试。')
|
||||
space.value = result
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
const previousToken = token
|
||||
clear()
|
||||
notice.value = ''
|
||||
if (previousToken) await request<null>('logout', 'POST', undefined, previousToken, -1)
|
||||
}
|
||||
|
||||
return { user, space, notice, login, restore, logout, loadSpace }
|
||||
})
|
||||
@@ -0,0 +1,65 @@
|
||||
:root {
|
||||
font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
|
||||
color: #233d31;
|
||||
background: #f7f5ee;
|
||||
font-synthesis: none;
|
||||
--el-color-primary: #315c43;
|
||||
--el-color-primary-light-3: #597f66;
|
||||
--el-color-primary-light-5: #8da493;
|
||||
--el-color-primary-light-7: #bdccc0;
|
||||
--el-color-primary-light-9: #eef2eb;
|
||||
--el-color-primary-dark-2: #264a35;
|
||||
--el-border-radius-base: 8px;
|
||||
--el-font-size-base: 15px;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; min-width: 320px; }
|
||||
button, input { font: inherit; }
|
||||
button:focus-visible, a:focus-visible { outline: 3px solid #bc803d; outline-offset: 4px; }
|
||||
a { color: inherit; }
|
||||
.brand { font-family: Georgia, serif; font-size: 30px; font-weight: 700; letter-spacing: -1px; text-decoration: none; }
|
||||
.brand-dot { color: #ba8345; }
|
||||
.login-page { min-height: 100dvh; display: grid; grid-template-columns: minmax(340px, 1fr) minmax(400px, 1fr); }
|
||||
.welcome { background: #284c38; color: #f7f5ee; padding: 46px 10%; display: flex; flex-direction: column; justify-content: space-between; }
|
||||
.welcome .brand { color: #f7f5ee; }
|
||||
.welcome-copy { padding: 80px 0; max-width: 450px; }
|
||||
.welcome-copy h2 { font-family: Georgia, 'Microsoft YaHei', serif; font-weight: 400; font-size: clamp(32px, 3.3vw, 52px); line-height: 1.55; letter-spacing: 2px; margin: 26px 0; }
|
||||
.welcome-copy p { font-size: 16px; color: #d4dfd2; line-height: 1.9; }
|
||||
.book-mark { width: 60px; height: 60px; color: #d6b980; }
|
||||
.welcome-foot { font-size: 13px; letter-spacing: 2px; color: #c4d1c0; }
|
||||
.login-main { display: grid; place-items: center; padding: 48px 28px; }
|
||||
.login-form { width: min(100%, 360px); }
|
||||
.eyebrow { color: #687568; font-size: 12px; letter-spacing: 3px; }
|
||||
h1 { font-size: 30px; font-weight: 600; margin: 14px 0; letter-spacing: 1px; }
|
||||
.subtle { color: #748073; font-size: 14px; line-height: 1.8; }
|
||||
.login-form form { margin-top: 36px; }
|
||||
.field { display: block; margin-bottom: 22px; }
|
||||
.field label { display: block; font-size: 14px; margin-bottom: 10px; }
|
||||
.el-input { --el-input-height: 46px; --el-input-bg-color: #fffefa; --el-input-border-color: #d6dccf; }
|
||||
.el-button { min-height: 42px; }
|
||||
.login-submit { width: 100%; margin-top: 8px; height: 48px; letter-spacing: 4px; }
|
||||
.notice { padding: 12px 15px; background: #fff0e7; border: 1px solid #ebc3a8; color: #8b4324; border-radius: 6px; font-size: 14px; line-height: 1.6; }
|
||||
.site-header { padding: 24px max(24px, calc((100vw - 1200px) / 2)); border-bottom: 1px solid #e0e3d8; display: flex; align-items: center; gap: 32px; background: #fffdf7; }
|
||||
.site-header nav { flex: 1; }
|
||||
.active-nav { font-size: 15px; text-decoration: none; padding: 13px 0; border-bottom: 2px solid #315c43; }
|
||||
.account { display: flex; align-items: center; gap: 18px; font-size: 14px; }
|
||||
.account-name { max-width: 200px; overflow: hidden; text-overflow: ellipsis; }
|
||||
.library { max-width: 1120px; margin: 60px auto; padding: 0 28px; }
|
||||
.library-title { display: flex; align-items: center; justify-content: space-between; gap: 20px; margin-bottom: 38px; }
|
||||
.language { border: 1px solid #d9decf; padding: 9px 17px; border-radius: 20px; font-size: 13px; background: #fffdf7; }
|
||||
.empty-library { background: #fffdf8; border: 1px solid #e0e3d8; border-radius: 12px; min-height: 360px; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 44px 20px; text-align: center; }
|
||||
.empty-library .book-mark { color: #6e8967; width: 56px; height: 56px; }
|
||||
.empty-library h2 { font-weight: 500; font-size: 21px; margin: 26px 0 4px; }
|
||||
.loading { padding: 80px 24px; text-align: center; color: #748073; }
|
||||
@media (max-width: 760px) {
|
||||
.login-page { grid-template-columns: 1fr; }
|
||||
.welcome { padding: 28px; }
|
||||
.welcome-copy, .welcome-foot { display: none; }
|
||||
.login-main { padding: 50px 28px 70px; align-items: start; }
|
||||
.site-header { padding: 20px; gap: 22px; flex-wrap: wrap; }
|
||||
.account { margin-left: auto; gap: 10px; }
|
||||
.account-name { max-width: 120px; }
|
||||
.site-header nav { order: 3; flex-basis: 100%; padding-top: 8px; }
|
||||
.library { margin-top: 32px; padding: 0 20px; }
|
||||
h1 { font-size: 26px; }
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { RouterLink, useRouter } from 'vue-router'
|
||||
import { ElButton } from 'element-plus'
|
||||
import BookMark from '../components/BookMark.vue'
|
||||
import { useSessionStore } from '../stores/session'
|
||||
const session = useSessionStore()
|
||||
const router = useRouter()
|
||||
const loading = ref(true)
|
||||
const error = ref('')
|
||||
async function load() {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try { await session.loadSpace() }
|
||||
catch (reason) { error.value = reason instanceof Error ? reason.message : '暂时无法加载,请重试。' }
|
||||
finally { loading.value = false }
|
||||
}
|
||||
async function logout() {
|
||||
try { await session.logout() }
|
||||
catch { session.notice = '已退出此设备。服务器暂时无法连接,请稍后重试。' }
|
||||
finally { await router.replace('/login') }
|
||||
}
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="session.user">
|
||||
<header class="site-header">
|
||||
<RouterLink to="/" class="brand">LexGo<span class="brand-dot">.</span></RouterLink>
|
||||
<nav aria-label="学习导航"><RouterLink to="/" class="active-nav">我的书库</RouterLink></nav>
|
||||
<div class="account">
|
||||
<span class="account-name">{{ session.user.username }}</span>
|
||||
<ElButton text @click="logout">退出登录</ElButton>
|
||||
</div>
|
||||
</header>
|
||||
<main class="library">
|
||||
<div class="library-title"><div><h1>我的书库</h1><p class="subtle">你的阅读与学习,从这里开始。</p></div><span class="language">英语</span></div>
|
||||
<p v-if="loading" role="status" class="loading">正在加载…</p>
|
||||
<div v-else-if="error" class="notice"><p role="alert">{{ error }}</p><ElButton @click="load">重试</ElButton></div>
|
||||
<section v-else-if="session.space" class="empty-library" aria-label="书库内容">
|
||||
<BookMark /><h2>书库还是空的</h2><p class="subtle">这里将收纳你的阅读内容。</p>
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,61 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { ElButton, ElInput } from 'element-plus'
|
||||
import BookMark from '../components/BookMark.vue'
|
||||
import { useSessionStore } from '../stores/session'
|
||||
const session = useSessionStore()
|
||||
const router = useRouter()
|
||||
const username = ref('')
|
||||
const password = ref('')
|
||||
const busy = ref(false)
|
||||
const error = ref('')
|
||||
async function submit() {
|
||||
if (busy.value) return
|
||||
error.value = ''
|
||||
session.notice = ''
|
||||
if (!username.value.trim() || !password.value) {
|
||||
error.value = '请输入账号和密码。'
|
||||
return
|
||||
}
|
||||
busy.value = true
|
||||
try {
|
||||
await session.login(username.value.trim(), password.value)
|
||||
if (session.user) await router.replace('/')
|
||||
} catch (reason) {
|
||||
error.value = reason instanceof Error ? reason.message : '登录失败,请稍后重试。'
|
||||
session.notice = ''
|
||||
} finally {
|
||||
password.value = ''
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="login-page">
|
||||
<aside class="welcome">
|
||||
<div class="brand">LexGo<span class="brand-dot">.</span></div>
|
||||
<div class="welcome-copy">
|
||||
<BookMark />
|
||||
</div>
|
||||
</aside>
|
||||
<main class="login-main">
|
||||
<div class="login-form">
|
||||
<h1>欢迎回来</h1>
|
||||
<p v-if="error || session.notice" role="alert" class="notice">{{ error || session.notice }}</p>
|
||||
<form @submit.prevent="submit">
|
||||
<div class="field">
|
||||
<label for="username">账号</label>
|
||||
<ElInput id="username" v-model="username" type="text" autocomplete="username" placeholder="请输入账号" :disabled="busy" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="password">密码</label>
|
||||
<ElInput id="password" v-model="password" type="password" autocomplete="current-password" placeholder="请输入密码" show-password :disabled="busy" />
|
||||
</div>
|
||||
<ElButton class="login-submit" type="primary" native-type="submit" :loading="busy">登录</ElButton>
|
||||
</form>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"extends": "@vue/tsconfig/tsconfig.dom.json",
|
||||
"include": ["env.d.ts", "src/**/*", "src/**/*.vue"],
|
||||
"exclude": ["src/**/__tests__/*"],
|
||||
"compilerOptions": {
|
||||
// Extra safety for array and object lookups, but may have false positives.
|
||||
"noUncheckedIndexedAccess": true,
|
||||
|
||||
// Path mapping for cleaner imports.
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
},
|
||||
|
||||
// `vue-tsc --build` produces a .tsbuildinfo file for incremental type-checking.
|
||||
// Specified here to keep it out of the root directory.
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.node.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.app.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.vitest.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// TSConfig for modules that run in Node.js environment via either transpilation or type-stripping.
|
||||
{
|
||||
"extends": "@tsconfig/node24/tsconfig.json",
|
||||
"include": [
|
||||
"vite.config.*",
|
||||
"vitest.config.*",
|
||||
"cypress.config.*",
|
||||
"playwright.config.*",
|
||||
"eslint.config.*"
|
||||
],
|
||||
"compilerOptions": {
|
||||
// Most tools use transpilation instead of Node.js's native type-stripping.
|
||||
// Bundler mode provides a smoother developer experience.
|
||||
"module": "preserve",
|
||||
"moduleResolution": "bundler",
|
||||
|
||||
// Include Node.js types and avoid accidentally including other `@types/*` packages.
|
||||
"types": ["node"],
|
||||
|
||||
// Disable emitting output during `vue-tsc --build`, which is used for type-checking only.
|
||||
"noEmit": true,
|
||||
"allowImportingTsExtensions": true,
|
||||
|
||||
// `vue-tsc --build` produces a .tsbuildinfo file for incremental type-checking.
|
||||
// Specified here to keep it out of the root directory.
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"extends": "./tsconfig.app.json",
|
||||
|
||||
// Override to include only test files and clear exclusions.
|
||||
// Application code imported in tests is automatically included via module resolution.
|
||||
"include": ["src/**/__tests__/*", "env.d.ts"],
|
||||
"exclude": [],
|
||||
|
||||
"compilerOptions": {
|
||||
// Vitest runs in a different environment than the application code.
|
||||
// Adjust lib and types accordingly.
|
||||
"lib": [],
|
||||
"types": ["node", "jsdom"],
|
||||
|
||||
// `vue-tsc --build` produces a .tsbuildinfo file for incremental type-checking.
|
||||
// Specified here to keep it out of the root directory.
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.vitest.tsbuildinfo"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { fileURLToPath, URL } from 'node:url'
|
||||
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
vue(),
|
||||
|
||||
],
|
||||
server: { proxy: { '/api': 'http://127.0.0.1:8000' } },
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': fileURLToPath(new URL('./src', import.meta.url)),
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,14 @@
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { mergeConfig, defineConfig, configDefaults } from 'vitest/config'
|
||||
import viteConfig from './vite.config.ts'
|
||||
|
||||
export default mergeConfig(
|
||||
viteConfig,
|
||||
defineConfig({
|
||||
test: {
|
||||
environment: 'jsdom',
|
||||
exclude: [...configDefaults.exclude, 'e2e/**'],
|
||||
root: fileURLToPath(new URL('./', import.meta.url)),
|
||||
},
|
||||
}),
|
||||
)
|
||||
Reference in New Issue
Block a user