initial commit

This commit is contained in:
Jiao77
2026-03-01 09:13:24 +08:00
commit 72baa341cc
43 changed files with 12560 additions and 0 deletions

View File

@@ -0,0 +1,297 @@
<template>
<div class="comment-section">
<h3 class="text-xl font-bold mb-6">评论</h3>
<!-- 评论输入框 -->
<div v-if="isLoggedIn" class="mb-8">
<textarea
v-model="newComment"
placeholder="写下你的评论..."
class="w-full p-4 border border-border rounded-lg bg-background focus:outline-none focus:ring-2 focus:ring-primary-500 resize-none"
rows="4"
></textarea>
<div class="flex justify-end mt-2">
<button
@click="submitComment"
:disabled="!newComment.trim() || submitting"
class="btn-primary disabled:opacity-50 disabled:cursor-not-allowed"
>
{{ submitting ? '发布中...' : '发布评论' }}
</button>
</div>
</div>
<!-- 未登录提示 -->
<div v-else class="mb-8 p-4 bg-muted rounded-lg text-center">
<p class="text-foreground/60">
<a href="/login" class="text-primary-500 hover:underline">登录</a> 后参与评论
</p>
</div>
<!-- 评论列表 -->
<div v-if="loading" class="text-center py-8">
<div class="animate-spin w-8 h-8 border-2 border-primary-500 border-t-transparent rounded-full mx-auto"></div>
<p class="mt-2 text-foreground/40">加载评论中...</p>
</div>
<div v-else-if="comments.length === 0" class="text-center py-8 text-foreground/40">
<p>暂无评论来抢沙发吧</p>
</div>
<div v-else class="space-y-6">
<div v-for="comment in comments" :key="comment.id" class="comment-item">
<div class="flex gap-4">
<!-- 头像 -->
<div class="flex-shrink-0">
<div class="w-10 h-10 rounded-full bg-primary-100 dark:bg-primary-900 flex items-center justify-center">
<span class="text-primary-600 dark:text-primary-400 font-medium">
{{ (comment.user.nickname || comment.user.username)[0].toUpperCase() }}
</span>
</div>
</div>
<!-- 内容 -->
<div class="flex-1 min-w-0">
<div class="flex items-center gap-2 mb-1">
<span class="font-medium">{{ comment.user.nickname || comment.user.username }}</span>
<span class="text-xs text-foreground/40">{{ formatDate(comment.created_at) }}</span>
</div>
<p class="text-foreground/80 whitespace-pre-wrap">{{ comment.content }}</p>
<!-- 回复按钮 -->
<button
@click="replyTo = comment.id"
class="text-sm text-primary-500 hover:underline mt-2"
>
回复
</button>
</div>
</div>
<!-- 回复输入框 -->
<div v-if="replyTo === comment.id" class="mt-4 ml-14">
<textarea
v-model="replyContent"
placeholder="写下你的回复..."
class="w-full p-3 border border-border rounded-lg bg-background focus:outline-none focus:ring-2 focus:ring-primary-500 resize-none text-sm"
rows="3"
></textarea>
<div class="flex justify-end gap-2 mt-2">
<button @click="replyTo = null" class="btn-secondary text-sm">取消</button>
<button
@click="submitReply(comment.id)"
:disabled="!replyContent.trim() || submitting"
class="btn-primary text-sm disabled:opacity-50"
>
回复
</button>
</div>
</div>
<!-- 子评论 -->
<div v-if="comment.replies && comment.replies.length > 0" class="mt-4 ml-14 space-y-4">
<div v-for="reply in comment.replies" :key="reply.id" class="flex gap-3">
<div class="flex-shrink-0">
<div class="w-8 h-8 rounded-full bg-primary-100 dark:bg-primary-900 flex items-center justify-center">
<span class="text-primary-600 dark:text-primary-400 text-sm font-medium">
{{ (reply.user.nickname || reply.user.username)[0].toUpperCase() }}
</span>
</div>
</div>
<div class="flex-1">
<div class="flex items-center gap-2 mb-1">
<span class="font-medium text-sm">{{ reply.user.nickname || reply.user.username }}</span>
<span class="text-xs text-foreground/40">{{ formatDate(reply.created_at) }}</span>
</div>
<p class="text-foreground/80 text-sm">{{ reply.content }}</p>
</div>
</div>
</div>
</div>
</div>
<!-- 分页 -->
<div v-if="pagination.totalPage > 1" class="flex justify-center gap-2 mt-8">
<button
@click="loadPage(pagination.page - 1)"
:disabled="pagination.page <= 1"
class="btn-secondary disabled:opacity-50"
>
上一页
</button>
<span class="px-4 py-2 text-foreground/60">
{{ pagination.page }} / {{ pagination.totalPage }}
</span>
<button
@click="loadPage(pagination.page + 1)"
:disabled="pagination.page >= pagination.totalPage"
class="btn-secondary disabled:opacity-50"
>
下一页
</button>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
const props = defineProps<{
postId: string;
apiBaseUrl?: string;
}>();
const apiBaseUrl = props.apiBaseUrl || 'http://localhost:8080/api';
// 状态
const comments = ref<any[]>([]);
const loading = ref(true);
const submitting = ref(false);
const newComment = ref('');
const replyTo = ref<number | null>(null);
const replyContent = ref('');
const pagination = ref({
page: 1,
pageSize: 20,
total: 0,
totalPage: 0,
});
// 计算属性 - 仅在浏览器环境中访问 localStorage
const isLoggedIn = computed(() => {
if (typeof window === 'undefined') return false;
return !!localStorage.getItem('token');
});
// 获取认证头
function getAuthHeaders(): Record<string, string> {
if (typeof window === 'undefined') return {};
const token = localStorage.getItem('token');
return token ? { Authorization: `Bearer ${token}` } : {};
}
// 加载评论
async function loadComments() {
loading.value = true;
try {
const response = await fetch(
`${apiBaseUrl}/comments?post_id=${props.postId}&page=${pagination.value.page}&page_size=${pagination.value.pageSize}`
);
const data = await response.json();
if (response.ok) {
comments.value = data.data;
pagination.value = data.pagination;
}
} catch (error) {
console.error('Failed to load comments:', error);
} finally {
loading.value = false;
}
}
// 提交评论
async function submitComment() {
if (!newComment.value.trim()) return;
submitting.value = true;
try {
const response = await fetch(`${apiBaseUrl}/comments`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify({
post_id: props.postId,
content: newComment.value,
}),
});
if (response.ok) {
newComment.value = '';
await loadComments();
} else {
const error = await response.json();
alert(error.error || '发布失败');
}
} catch (error) {
console.error('Failed to submit comment:', error);
alert('发布失败,请稍后重试');
} finally {
submitting.value = false;
}
}
// 提交回复
async function submitReply(parentId: number) {
if (!replyContent.value.trim()) return;
submitting.value = true;
try {
const response = await fetch(`${apiBaseUrl}/comments`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify({
post_id: props.postId,
parent_id: parentId,
content: replyContent.value,
}),
});
if (response.ok) {
replyContent.value = '';
replyTo.value = null;
await loadComments();
} else {
const error = await response.json();
alert(error.error || '回复失败');
}
} catch (error) {
console.error('Failed to submit reply:', error);
alert('回复失败,请稍后重试');
} finally {
submitting.value = false;
}
}
// 加载指定页
function loadPage(page: number) {
pagination.value.page = page;
loadComments();
}
// 格式化日期
function formatDate(dateString: string) {
const date = new Date(dateString);
const now = new Date();
const diff = now.getTime() - date.getTime();
const minutes = Math.floor(diff / 60000);
const hours = Math.floor(diff / 3600000);
const days = Math.floor(diff / 86400000);
if (minutes < 1) return '刚刚';
if (minutes < 60) return `${minutes} 分钟前`;
if (hours < 24) return `${hours} 小时前`;
if (days < 30) return `${days} 天前`;
return date.toLocaleDateString('zh-CN', {
year: 'numeric',
month: 'short',
day: 'numeric',
});
}
onMounted(() => {
loadComments();
});
</script>
<style scoped>
.comment-section {
@apply mt-12 pt-8 border-t border-border;
}
</style>

View File

@@ -0,0 +1,23 @@
<template>
<div class="inline-flex items-center gap-4 px-4 py-2 bg-primary-100 dark:bg-primary-900 rounded-lg">
<button
@click="count--"
class="w-8 h-8 flex items-center justify-center rounded-full bg-primary-500 text-white hover:bg-primary-600 transition-colors"
>
-
</button>
<span class="text-2xl font-bold min-w-[2rem] text-center">{{ count }}</span>
<button
@click="count++"
class="w-8 h-8 flex items-center justify-center rounded-full bg-primary-500 text-white hover:bg-primary-600 transition-colors"
>
+
</button>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
const count = ref(0);
</script>

View File

@@ -0,0 +1,134 @@
<template>
<button
@click="toggleLike"
:disabled="loading"
class="like-button flex items-center gap-2 px-4 py-2 rounded-full transition-all duration-300"
:class="[
liked
? 'bg-red-100 dark:bg-red-900/30 text-red-500'
: 'bg-muted hover:bg-red-50 dark:hover:bg-red-900/20 text-foreground/60 hover:text-red-500'
]"
>
<!-- 心形图标 -->
<svg
class="w-5 h-5 transition-transform duration-300"
:class="{ 'scale-125': animating }"
viewBox="0 0 24 24"
fill="currentColor"
>
<path
d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"
/>
</svg>
<!-- 点赞数 -->
<span class="font-medium">{{ likeCount }}</span>
</button>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue';
const props = defineProps<{
postId: string;
apiBaseUrl?: string;
}>();
const emit = defineEmits<{
(e: 'update', liked: boolean, count: number): void;
}>();
const apiBaseUrl = props.apiBaseUrl || 'http://localhost:8080/api';
// 状态
const liked = ref(false);
const likeCount = ref(0);
const loading = ref(false);
const animating = ref(false);
// 获取认证头
function getAuthHeaders(): Record<string, string> {
// 仅在浏览器环境中访问 localStorage
if (typeof window === 'undefined') return {};
const token = localStorage.getItem('token');
return token ? { Authorization: `Bearer ${token}` } : {};
}
// 加载点赞状态
async function loadLikeStatus() {
loading.value = true;
try {
const response = await fetch(
`${apiBaseUrl}/likes?post_id=${props.postId}`,
{
headers: getAuthHeaders(),
}
);
if (response.ok) {
const data = await response.json();
liked.value = data.liked;
likeCount.value = data.like_count;
}
} catch (error) {
console.error('Failed to load like status:', error);
} finally {
loading.value = false;
}
}
// 切换点赞
async function toggleLike() {
loading.value = true;
try {
const response = await fetch(`${apiBaseUrl}/likes`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify({
post_id: props.postId,
}),
});
if (response.ok) {
const data = await response.json();
liked.value = data.liked;
likeCount.value = data.like_count;
// 触发动画
if (data.liked) {
animating.value = true;
setTimeout(() => {
animating.value = false;
}, 300);
}
emit('update', data.liked, data.like_count);
} else {
const error = await response.json();
console.error('Failed to toggle like:', error);
}
} catch (error) {
console.error('Failed to toggle like:', error);
} finally {
loading.value = false;
}
}
onMounted(() => {
loadLikeStatus();
});
</script>
<style scoped>
.like-button {
@apply cursor-pointer select-none;
}
.like-button:disabled {
@apply cursor-wait;
}
</style>

View File

@@ -0,0 +1,305 @@
<template>
<div class="login-container">
<div class="login-card">
<div class="tabs">
<button
:class="['tab', { active: mode === 'login' }]"
@click="mode = 'login'"
>
登录
</button>
<button
:class="['tab', { active: mode === 'register' }]"
@click="mode = 'register'"
>
注册
</button>
</div>
<form @submit.prevent="handleSubmit" class="form">
<div class="form-group">
<label for="username">用户名</label>
<input
id="username"
v-model="form.username"
type="text"
placeholder="请输入用户名"
required
/>
</div>
<div class="form-group" v-if="mode === 'register'">
<label for="email">邮箱</label>
<input
id="email"
v-model="form.email"
type="email"
placeholder="请输入邮箱"
required
/>
</div>
<div class="form-group">
<label for="password">密码</label>
<input
id="password"
v-model="form.password"
type="password"
placeholder="请输入密码"
required
/>
</div>
<div class="form-group" v-if="mode === 'register'">
<label for="confirmPassword">确认密码</label>
<input
id="confirmPassword"
v-model="form.confirmPassword"
type="password"
placeholder="请再次输入密码"
required
/>
</div>
<div v-if="error" class="error-message">{{ error }}</div>
<div v-if="success" class="success-message">{{ success }}</div>
<button type="submit" class="submit-btn" :disabled="loading">
{{ loading ? '处理中...' : (mode === 'login' ? '登录' : '注册') }}
</button>
</form>
<div class="divider">
<span></span>
</div>
<button class="github-btn" @click="handleGithubLogin">
<svg viewBox="0 0 24 24" width="20" height="20">
<path fill="currentColor" d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"/>
</svg>
使用 GitHub 登录
</button>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
const mode = ref<'login' | 'register'>('login')
const loading = ref(false)
const error = ref('')
const success = ref('')
const form = reactive({
username: '',
email: '',
password: '',
confirmPassword: ''
})
const API_BASE = import.meta.env.PUBLIC_API_BASE || 'http://localhost:8080'
async function handleSubmit() {
error.value = ''
success.value = ''
if (mode.value === 'register' && form.password !== form.confirmPassword) {
error.value = '两次输入的密码不一致'
return
}
loading.value = true
try {
const endpoint = mode.value === 'login' ? '/api/auth/login' : '/api/auth/register'
const body = mode.value === 'login'
? { username: form.username, password: form.password }
: { username: form.username, email: form.email, password: form.password }
const response = await fetch(`${API_BASE}${endpoint}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
})
const data = await response.json()
if (!response.ok) {
error.value = data.error || '操作失败'
return
}
if (data.token) {
localStorage.setItem('token', data.token)
localStorage.setItem('user', JSON.stringify(data.user))
success.value = mode.value === 'login' ? '登录成功!' : '注册成功!'
window.dispatchEvent(new CustomEvent('user-login', { detail: data.user }))
setTimeout(() => {
window.location.href = '/'
}, 1000)
}
} catch (err) {
error.value = '网络错误,请稍后重试'
console.error(err)
} finally {
loading.value = false
}
}
function handleGithubLogin() {
error.value = 'GitHub 登录功能即将上线'
}
</script>
<style scoped>
.login-container {
display: flex;
justify-content: center;
align-items: center;
min-height: 60vh;
padding: 2rem;
}
.login-card {
background: var(--card-bg, #fff);
border-radius: 12px;
box-shadow: 0 4px 24px rgba(0, 0, 0, 0.1);
padding: 2rem;
width: 100%;
max-width: 400px;
}
.tabs {
display: flex;
margin-bottom: 1.5rem;
border-bottom: 2px solid var(--border-color, #e5e7eb);
}
.tab {
flex: 1;
padding: 0.75rem 1rem;
border: none;
background: none;
cursor: pointer;
font-size: 1rem;
color: var(--text-muted, #6b7280);
transition: all 0.3s;
}
.tab.active {
color: var(--primary, #3b82f6);
border-bottom: 2px solid var(--primary, #3b82f6);
margin-bottom: -2px;
}
.form-group {
margin-bottom: 1rem;
}
.form-group label {
display: block;
margin-bottom: 0.5rem;
font-size: 0.875rem;
font-weight: 500;
color: var(--text, #374151);
}
.form-group input {
width: 100%;
padding: 0.75rem 1rem;
border: 1px solid var(--border-color, #d1d5db);
border-radius: 8px;
font-size: 1rem;
transition: border-color 0.2s;
}
.form-group input:focus {
outline: none;
border-color: var(--primary, #3b82f6);
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}
.error-message {
color: #ef4444;
font-size: 0.875rem;
margin-bottom: 1rem;
padding: 0.5rem;
background: #fef2f2;
border-radius: 6px;
}
.success-message {
color: #22c55e;
font-size: 0.875rem;
margin-bottom: 1rem;
padding: 0.5rem;
background: #f0fdf4;
border-radius: 6px;
}
.submit-btn {
width: 100%;
padding: 0.875rem;
background: var(--primary, #3b82f6);
color: white;
border: none;
border-radius: 8px;
font-size: 1rem;
font-weight: 500;
cursor: pointer;
transition: background 0.3s;
}
.submit-btn:hover:not(:disabled) {
background: var(--primary-hover, #2563eb);
}
.submit-btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.divider {
display: flex;
align-items: center;
margin: 1.5rem 0;
}
.divider::before,
.divider::after {
content: '';
flex: 1;
height: 1px;
background: var(--border-color, #e5e7eb);
}
.divider span {
padding: 0 1rem;
color: var(--text-muted, #9ca3af);
font-size: 0.875rem;
}
.github-btn {
width: 100%;
display: flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
padding: 0.875rem;
background: #24292e;
color: white;
border: none;
border-radius: 8px;
font-size: 1rem;
cursor: pointer;
transition: background 0.3s;
}
.github-btn:hover {
background: #1a1e22;
}
</style>

View File

@@ -0,0 +1,67 @@
---
/**
* TypstBlock 组件
*
* 用于在 MDX 文章中渲染 Typst 数学公式和复杂排版。
*
* 使用方式:
* <TypstBlock>
* $ integral_0^infinity e^(-x^2) dif x = sqrt(pi) / 2 $
* </TypstBlock>
*
* 注意:此组件需要在构建时安装 Typst 编译器。
* 如果 Typst 未安装,会显示原始代码块作为降级方案。
*/
interface Props {
class?: string;
}
const { class: className = '' } = Astro.props;
// 获取子内容Typst 代码)
const content = await Astro.slots.render('default');
const typstCode = content?.trim() || '';
---
<div class:list={['typst-block', 'my-6', className]}>
{/*
Typst 渲染区域
在实际实现中,这里会调用 Typst 编译器将代码渲染为 SVG
目前作为占位符显示
*/}
<div class="p-4 bg-muted rounded-lg border border-border overflow-x-auto">
{typstCode ? (
<div class="flex flex-col items-center">
{/* SVG 输出区域 (构建时会被替换为实际的 Typst 渲染结果) */}
<div class="typst-output text-lg" data-typst-code={typstCode}>
<code class="font-mono text-primary-600 dark:text-primary-400">
{typstCode}
</code>
</div>
<span class="text-xs text-foreground/40 mt-2">Typst 公式</span>
</div>
) : (
<p class="text-foreground/40 text-center">请提供 Typst 代码</p>
)}
</div>
</div>
<style>
.typst-block {
/* 确保 Typst 内容居中显示 */
text-align: center;
}
.typst-output {
/* 为数学公式提供合适的样式 */
font-family: 'Latin Modern Math', 'STIX Two Math', 'Noto Serif SC', serif;
line-height: 1.8;
}
.typst-output svg {
/* SVG 输出样式 */
max-width: 100%;
height: auto;
}
</style>