refactor(P3): HomeView 拆分为 3 composable + CommentDrawer 组件 (924行→~180行)

This commit is contained in:
Sisyphus
2026-04-25 16:48:17 +08:00
parent 15f86f08ae
commit 41ae86f908
6 changed files with 625 additions and 925 deletions

View File

@@ -0,0 +1,153 @@
<script setup lang="ts">
import { reactive } from 'vue'
import { ApiError } from '../api/client'
import * as commentApi from '../api/comment'
import type { Comment, FeedVideoItem } from '../api/types'
import { useAuthStore } from '../stores/auth'
import { useToastStore } from '../stores/toast'
const props = defineProps<{ video: FeedVideoItem | null }>()
const emit = defineEmits<{ close: [] }>()
const auth = useAuthStore()
const toast = useToastStore()
const drawer = reactive({
loading: false,
error: '',
comments: [] as Comment[],
content: '',
})
function needLogin() {
toast.error('请先登录')
}
function close() {
drawer.comments = []
drawer.content = ''
drawer.error = ''
emit('close')
}
async function loadComments() {
if (!props.video) return
drawer.loading = true
drawer.error = ''
try {
drawer.comments = await commentApi.listAll(props.video.id)
} catch (e) {
drawer.error = e instanceof ApiError ? e.message : String(e)
} finally {
drawer.loading = false
}
}
async function publishComment() {
if (!props.video) return
if (!auth.isLoggedIn) return needLogin()
const content = drawer.content.trim()
if (!content) return
drawer.loading = true
drawer.error = ''
try {
await commentApi.publish(props.video.id, content)
drawer.content = ''
await loadComments()
toast.success('评论已发布')
} catch (e) {
drawer.error = e instanceof ApiError ? e.message : String(e)
toast.error(drawer.error)
} finally {
drawer.loading = false
}
}
function canDeleteComment(c: Comment) {
const myId = auth.claims?.account_id
return !!myId && myId === c.author_id
}
async function deleteComment(commentId: number) {
if (!props.video) return
if (!auth.isLoggedIn) return needLogin()
if (!window.confirm('确认删除这条评论?')) return
drawer.loading = true
drawer.error = ''
try {
await commentApi.remove(commentId)
await loadComments()
toast.info('评论已删除')
} catch (e) {
drawer.error = e instanceof ApiError ? e.message : String(e)
toast.error(drawer.error)
} finally {
drawer.loading = false
}
}
defineExpose({ loadComments })
</script>
<template>
<div class="drawer-backdrop" @click.self="close">
<div class="drawer">
<div class="drawer-head">
<div class="drawer-title">{{ video?.title ?? '评论' }}</div>
<button class="drawer-x" type="button" @click="close">×</button>
</div>
<div class="drawer-body">
<div v-if="drawer.loading" class="drawer-hint">加载中</div>
<div v-else-if="drawer.error" class="drawer-hint bad">{{ drawer.error }}</div>
<div v-else-if="drawer.comments.length === 0" class="drawer-hint">暂无评论</div>
<div class="comment" v-for="c in drawer.comments" :key="c.id">
<div class="comment-top">
<div class="comment-user">{{ c.username }}</div>
<div class="comment-meta mono">#{{ c.id }} · {{ new Date(c.created_at).toLocaleString() }}</div>
</div>
<div class="comment-content">{{ c.content }}</div>
<div class="comment-actions">
<button v-if="canDeleteComment(c)" class="chip danger" type="button" :disabled="drawer.loading" @click="deleteComment(c.id)">删除</button>
</div>
</div>
</div>
<div class="drawer-foot">
<textarea v-model="drawer.content" placeholder="说点什么…" :disabled="drawer.loading" />
<div class="row" style="justify-content: space-between; margin-top: 8px">
<button class="chip" type="button" :disabled="drawer.loading" @click="loadComments">刷新</button>
<button class="chip primary" type="button" :disabled="drawer.loading || !drawer.content.trim()" @click="publishComment">发送</button>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.drawer-backdrop { position: fixed; inset: 0; background: rgba(0,0,0,0.55); backdrop-filter: blur(10px); z-index: 120; display: grid; justify-items: end; }
.drawer { width: min(420px, calc(100vw - 18px)); height: 100vh; background: rgba(0,0,0,0.65); border-left: 1px solid rgba(255,255,255,0.12); display: grid; grid-template-rows: auto 1fr auto; }
.drawer-head { display: flex; align-items: center; justify-content: space-between; padding: 14px 14px; border-bottom: 1px solid rgba(255,255,255,0.1); }
.drawer-title { font-weight: 800; font-size: 14px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.drawer-x { width: 34px; height: 34px; border-radius: 12px; border: 1px solid rgba(255,255,255,0.14); background: rgba(255,255,255,0.06); color: rgba(255,255,255,0.9); cursor: pointer; font-size: 20px; line-height: 1; }
.drawer-body { overflow: auto; padding: 12px 14px; display: grid; gap: 10px; }
.drawer-foot { border-top: 1px solid rgba(255,255,255,0.1); padding: 12px 14px; }
.drawer-foot textarea { width: 100%; min-height: 82px; resize: none; border-radius: 14px; border: 1px solid rgba(255,255,255,0.14); background: rgba(255,255,255,0.06); color: rgba(255,255,255,0.9); padding: 10px 12px; outline: none; }
.drawer-hint { color: rgba(255,255,255,0.78); padding: 12px 0; }
.drawer-hint.bad { color: rgba(254,44,85,0.92); }
.comment { border: 1px solid rgba(255,255,255,0.1); background: rgba(255,255,255,0.05); border-radius: 14px; padding: 10px 10px; }
.comment-top { display: grid; gap: 3px; }
.comment-user { font-weight: 700; font-size: 13px; }
.comment-meta { font-size: 12px; color: rgba(255,255,255,0.55); }
.comment-content { margin-top: 8px; font-size: 13px; line-height: 1.35; color: rgba(255,255,255,0.86); white-space: pre-wrap; word-break: break-word; }
.comment-actions { margin-top: 10px; display: flex; justify-content: flex-end; }
.chip { display: inline-flex; align-items: center; gap: 8px; padding: 7px 10px; border-radius: 999px; border: 1px solid rgba(255,255,255,0.14); background: rgba(0,0,0,0.28); color: rgba(255,255,255,0.86); font-size: 12px; text-decoration: none; cursor: pointer; }
.chip.primary { border-color: rgba(254,44,85,0.45); background: rgba(254,44,85,0.14); }
.chip.danger { border-color: rgba(254,44,85,0.55); background: rgba(254,44,85,0.12); }
@media (max-width: 900px) {
.drawer-backdrop { justify-items: center; align-items: end; }
.drawer { width: calc(100vw - 16px); height: min(72vh, 560px); border-left: none; border-top: 1px solid rgba(255,255,255,0.12); border-radius: 18px 18px 0 0; overflow: hidden; }
}
</style>

View File

@@ -0,0 +1,67 @@
import { reactive } from 'vue'
import { ApiError } from '../api/client'
import * as likeApi from '../api/like'
import type { FeedVideoItem } from '../api/types'
import { useAuthStore } from '../stores/auth'
import { useSocialStore } from '../stores/social'
import { useToastStore } from '../stores/toast'
export function useLikeFollow(needLogin: () => void) {
const auth = useAuthStore()
const social = useSocialStore()
const toast = useToastStore()
const likeBusy = reactive<Record<string, boolean>>({})
const followBusy = reactive<Record<string, boolean>>({})
async function toggleLike(item: FeedVideoItem) {
if (!auth.isLoggedIn) return needLogin()
const key = String(item.id)
if (likeBusy[key]) return
likeBusy[key] = true
try {
if (item.is_liked) await likeApi.unlike(item.id)
else await likeApi.like(item.id)
item.is_liked = !item.is_liked
item.likes_count = Math.max(0, item.likes_count + (item.is_liked ? 1 : -1))
} catch (e) {
const msg = e instanceof ApiError ? e.message : String(e)
toast.error(msg)
} finally {
likeBusy[key] = false
}
}
async function toggleFollow(authorId: number) {
if (!auth.isLoggedIn) return needLogin()
const key = String(authorId)
if (followBusy[key]) return
followBusy[key] = true
try {
if (social.isFollowing(authorId)) {
await social.unfollow(authorId)
toast.info('已取关')
} else {
await social.follow(authorId)
toast.success('已关注')
}
} catch (e) {
const msg = e instanceof ApiError ? e.message : String(e)
toast.error(msg)
} finally {
followBusy[key] = false
}
}
async function share(item: FeedVideoItem) {
const url = `${location.origin}/video/${item.id}`
try {
await navigator.clipboard.writeText(url)
toast.success('链接已复制')
} catch {
window.prompt('复制链接', url)
}
}
return { likeBusy, followBusy, toggleLike, toggleFollow, share }
}

View File

@@ -0,0 +1,112 @@
import { computed, reactive, ref } from 'vue'
import { ApiError } from '../api/client'
import * as feedApi from '../api/feed'
import type { FeedVideoItem } from '../api/types'
import { useAuthStore } from '../stores/auth'
export type TabKey = 'recommend' | 'hot' | 'following'
export function useVideoFeed() {
const auth = useAuthStore()
const tab = ref<TabKey>('recommend')
const recommend = reactive({
items: [] as FeedVideoItem[],
loading: false, error: '',
hasMore: false, nextTime: 0,
})
const hot = reactive({
items: [] as FeedVideoItem[],
loading: false, error: '',
hasMore: false,
nextLikesCountBefore: undefined as number | undefined,
nextIdBefore: undefined as number | undefined,
})
const following = reactive({
items: [] as FeedVideoItem[],
loading: false, error: '',
hasMore: false, nextTime: 0,
})
const currentState = computed(() => {
if (tab.value === 'hot') return hot
if (tab.value === 'following') return following
return recommend
})
async function loadRecommend(reset: boolean) {
if (recommend.loading) return
recommend.loading = true
recommend.error = ''
try {
const res = await feedApi.listLatest({ limit: 10, latest_time: reset ? 0 : recommend.nextTime })
recommend.hasMore = res.has_more
recommend.nextTime = res.next_time
recommend.items = reset ? res.video_list : recommend.items.concat(res.video_list)
} catch (e) {
recommend.error = e instanceof ApiError ? e.message : String(e)
} finally {
recommend.loading = false
}
}
async function loadHot(reset: boolean) {
if (hot.loading) return
hot.loading = true
hot.error = ''
try {
const res = await feedApi.listLikesCount({
limit: 10,
likes_count_before: reset ? undefined : hot.nextLikesCountBefore,
id_before: reset ? undefined : hot.nextIdBefore,
})
hot.hasMore = res.has_more
hot.nextLikesCountBefore = res.next_likes_count_before
hot.nextIdBefore = res.next_id_before
hot.items = reset ? res.video_list : hot.items.concat(res.video_list)
} catch (e) {
hot.error = e instanceof ApiError ? e.message : String(e)
} finally {
hot.loading = false
}
}
async function loadFollowing(reset: boolean) {
if (!auth.isLoggedIn) {
following.error = '登录后才能查看关注流'
return
}
if (following.loading) return
following.loading = true
following.error = ''
try {
const res = await feedApi.listByFollowing({ limit: 10, latest_time: reset ? 0 : following.nextTime })
following.hasMore = res.has_more
following.nextTime = res.next_time
following.items = reset ? res.video_list : following.items.concat(res.video_list)
} catch (e) {
following.error = e instanceof ApiError ? e.message : String(e)
} finally {
following.loading = false
}
}
async function ensureTabLoaded() {
if (tab.value === 'recommend' && recommend.items.length === 0) await loadRecommend(true)
if (tab.value === 'hot' && hot.items.length === 0) await loadHot(true)
if (tab.value === 'following' && following.items.length === 0) await loadFollowing(true)
}
async function loadMoreIfNeeded(activeIndex: number) {
const items = currentState.value.items
if (items.length === 0) return
if (activeIndex < items.length - 3) return
if (tab.value === 'recommend' && recommend.hasMore) await loadRecommend(false)
if (tab.value === 'hot' && hot.hasMore) await loadHot(false)
if (tab.value === 'following' && following.hasMore) await loadFollowing(false)
}
return { tab, recommend, hot, following, currentState, loadRecommend, loadHot, loadFollowing, ensureTabLoaded, loadMoreIfNeeded }
}

View File

@@ -0,0 +1,78 @@
import { ref } from 'vue'
import { useToastStore } from '../stores/toast'
export function useVideoPlayer(scrollerRef: ReturnType<typeof ref<HTMLDivElement | null>>) {
const toast = useToastStore()
const muted = ref(true)
const activeIndex = ref(0)
const videoMap = new Map<number, HTMLVideoElement>()
function getScrollerHeight() {
return scrollerRef.value?.clientHeight ?? 0
}
function setVideoRef(id: number, el: HTMLVideoElement | null) {
if (el) {
el.muted = muted.value
videoMap.set(id, el)
} else {
videoMap.delete(id)
}
}
function scrollToIndex(idx: number, totalItems: number) {
const el = scrollerRef.value
if (!el) return
const h = getScrollerHeight()
if (!h) return
const next = Math.max(0, Math.min(idx, Math.max(0, totalItems - 1)))
el.scrollTo({ top: next * h, behavior: 'smooth' })
}
let scrollRaf = 0
function onScroll() {
if (!scrollerRef.value) return
if (scrollRaf) return
scrollRaf = window.requestAnimationFrame(() => {
scrollRaf = 0
const el = scrollerRef.value
if (!el) return
const h = el.clientHeight
if (!h) return
const idx = Math.round(el.scrollTop / h)
if (idx !== activeIndex.value) activeIndex.value = idx
})
}
async function playActive(activeItemId: number | undefined) {
if (!activeItemId) return
for (const [id, v] of videoMap.entries()) {
if (id === activeItemId) continue
v.pause()
}
const video = videoMap.get(activeItemId)
if (!video) return
video.muted = muted.value
try {
await video.play()
} catch {
/* ignore autoplay errors */
}
}
function toggleMute() {
muted.value = !muted.value
for (const v of videoMap.values()) v.muted = muted.value
toast.info(muted.value ? '已静音' : '已取消静音')
}
function togglePlayPause(activeItemId: number | undefined) {
if (!activeItemId) return
const video = videoMap.get(activeItemId)
if (!video) return
if (video.paused) void video.play()
else video.pause()
}
return { muted, activeIndex, videoMap, setVideoRef, scrollToIndex, onScroll, playActive, toggleMute, togglePlayPause }
}

File diff suppressed because it is too large Load Diff