feat: Implement core e-learning features including video playback, user profile management, and course discovery.

This commit is contained in:
supalerk-ar66 2026-02-02 17:13:58 +07:00
parent 2cd1d481aa
commit a648c41b72
11 changed files with 1085 additions and 747 deletions

View file

@ -241,12 +241,16 @@ const loadLesson = async (lessonId: number) => {
}
}
// Video Player Ref (Component)
const videoPlayerComp = ref(null)
// Video & Progress State
const initialSeekTime = ref(0)
const maxWatchedTime = ref(0) // Anti-rewind monotonic tracking
const lastSavedTime = ref(-1)
const lastSavedTimestamp = ref(0) // Server throttle timestamp
const lastLocalSaveTimestamp = ref(0) // Local throttle timestamp
const currentDuration = ref(0) // Track duration for save logic
// Helper: Get Local Storage Key
const getLocalProgressKey = (lessonId: number) => {
@ -278,25 +282,33 @@ const saveLocalProgress = (lessonId: number, time: number) => {
}
}
const onVideoMetadataLoaded = () => {
if (videoRef.value) {
// Bind Media Preferences (Volume/Mute)
applyTo(videoRef.value)
// Resume playback if we have a saved position
if (initialSeekTime.value > 0) {
// Ensure we don't seek past duration
const seekTo = Math.min(initialSeekTime.value, videoRef.value.duration || Infinity)
videoRef.value.currentTime = seekTo
}
}
// Handler: Video Time Update (from Component)
const handleVideoTimeUpdate = (cTime: number, dur: number) => {
currentDuration.value = dur || 0
// Update Monotonic Progress
if (cTime > maxWatchedTime.value) {
maxWatchedTime.value = cTime
}
// Logic: Periodic Save
if (currentLesson.value?.id) {
const now = Date.now()
// 1. Local Save Throttle (5 seconds)
if (now - lastLocalSaveTimestamp.value > 5000) {
saveLocalProgress(currentLesson.value.id, maxWatchedTime.value)
lastLocalSaveTimestamp.value = now
}
// 2. Server Save Throttle (handled inside performSaveProgress)
// Note: We don't check isPlaying here because if time is updating, it IS playing.
performSaveProgress(false, false)
}
}
const togglePlay = () => {
if (!videoRef.value) return
if (isPlaying.value) videoRef.value.pause()
else videoRef.value.play()
isPlaying.value = !isPlaying.value
const onVideoMetadataLoaded = () => {
// Component handles seek and volume
}
const isCompleting = ref(false) // Flag to prevent race conditions during completion
@ -308,7 +320,7 @@ const isCompleting = ref(false) // Flag to prevent race conditions during comple
// Main Server Save Function
const performSaveProgress = async (force: boolean = false, keepalive: boolean = false) => {
const lesson = currentLesson.value
if (!videoRef.value || !lesson || lesson.type !== 'VIDEO') return
if (!lesson || lesson.type !== 'VIDEO') return
if (!lesson.progress) return
// 1. Completed Guard: Stop everything if already completed
@ -319,7 +331,7 @@ const performSaveProgress = async (force: boolean = false, keepalive: boolean =
const now = Date.now()
const maxSec = Math.floor(maxWatchedTime.value) // Use max watched time
const durationSec = Math.floor(videoRef.value.duration || 0)
const durationSec = Math.floor(currentDuration.value || 0)
// 3. Monotonic Check: Don't save if progress hasn't increased (unless forced)
if (!force && maxSec <= lastSavedTime.value) return
@ -371,50 +383,6 @@ const markLessonAsCompletedLocally = (lessonId: number) => {
}
}
const updateProgress = () => {
if (!videoRef.value) return
// UI Update
currentTime.value = videoRef.value.currentTime
duration.value = videoRef.value.duration
videoProgress.value = (currentTime.value / duration.value) * 100
// Update Monotonic Progress
if (currentTime.value > maxWatchedTime.value) {
maxWatchedTime.value = currentTime.value
}
// Logic: Periodic Save
if (isPlaying.value && currentLesson.value?.id) {
const now = Date.now()
// 1. Local Save Throttle (5 seconds)
if (now - lastLocalSaveTimestamp.value > 5000) {
saveLocalProgress(currentLesson.value.id, maxWatchedTime.value)
lastLocalSaveTimestamp.value = now
}
// 2. Server Save Throttle (handled inside performSaveProgress)
performSaveProgress(false, false)
}
}
// Volume Controls Logic replaced by useMediaPrefs
const volumeIcon = computed(() => {
if (isMuted.value || volume.value === 0) return 'volume_off'
if (volume.value < 0.5) return 'volume_down'
return 'volume_up'
})
const handleToggleMute = () => {
setMuted(!isMuted.value)
}
const handleVolumeChange = (val: any) => {
const newVol = typeof val === 'number' ? val : Number(val.target.value)
setVolume(newVol)
}
const videoSrc = computed(() => {
if (!currentLesson.value) return ''
// Use explicit video_url from API first
@ -428,70 +396,8 @@ const videoSrc = computed(() => {
return ''
})
// ==========================================
// 3. (Progress Tracking)
// ==========================================
// 10
// Event Listeners for Robustness
onMounted(() => {
// Page/Tab Visibility Logic
if (import.meta.client) {
document.addEventListener('visibilitychange', handleVisibilityChange)
window.addEventListener('pagehide', handlePageHide)
}
})
onBeforeUnmount(() => {
if (import.meta.client) {
document.removeEventListener('visibilitychange', handleVisibilityChange)
window.removeEventListener('pagehide', handlePageHide)
}
// Final save attempt when component destroys
if (currentLesson.value?.id) {
saveLocalProgress(currentLesson.value.id, maxWatchedTime.value)
}
// Only save if not completed
if (currentLesson.value?.progress && !currentLesson.value.progress.is_completed) {
performSaveProgress(true, true)
}
})
const handleVisibilityChange = () => {
if (document.hidden) {
if (currentLesson.value?.id) {
saveLocalProgress(currentLesson.value.id, maxWatchedTime.value)
}
performSaveProgress(true, true) // Force save with keepalive
}
}
const handlePageHide = () => {
// Triggered on page refresh, close tab, or navigation
if (currentLesson.value?.id) {
saveLocalProgress(currentLesson.value.id, maxWatchedTime.value)
}
performSaveProgress(true, true)
}
// Watch Video Events
watch(isPlaying, (playing) => {
if (!playing) {
// Paused: Save immediately
if (currentLesson.value?.id) {
saveLocalProgress(currentLesson.value.id, maxWatchedTime.value)
}
performSaveProgress(true, false)
}
})
// (Complete)
const onVideoEnded = async () => {
isPlaying.value = false
// Safety check BEFORE trying to save
const lesson = currentLesson.value
if (!lesson || !lesson.progress || lesson.progress.is_completed || isCompleting.value) return
@ -505,22 +411,6 @@ const onVideoEnded = async () => {
}
}
const formatTime = (time: number) => {
const m = Math.floor(time / 60)
const s = Math.floor(time % 60)
return `${m}:${s.toString().padStart(2, '0')}`
}
const currentTimeDisplay = computed(() => formatTime(currentTime.value))
const durationDisplay = computed(() => formatTime(duration.value || 0))
const seek = (e: MouseEvent) => {
if (!videoRef.value) return
const rect = (e.currentTarget as HTMLElement).getBoundingClientRect()
const percent = (e.clientX - rect.left) / rect.width
videoRef.value.currentTime = percent * videoRef.value.duration
}
onMounted(() => {
loadCourseData()
})
@ -557,75 +447,16 @@ onBeforeUnmount(() => {
</q-header>
<!-- Sidebar (Curriculum) -->
<q-drawer
<!-- Sidebar (Curriculum) -->
<CurriculumSidebar
v-model="sidebarOpen"
show-if-above
bordered
side="left"
:width="320"
:breakpoint="1024"
class="bg-[var(--bg-surface)]"
content-class="bg-[var(--bg-surface)]"
>
<div v-if="courseData" class="h-full scroll">
<q-list class="pb-10">
<!-- Announcements Sidebar Item -->
<q-item
clickable
v-ripple
@click="handleOpenAnnouncements"
class="bg-blue-50 dark:bg-blue-900/10 border-b border-blue-100 dark:border-blue-900/20"
>
<q-item-section>
<q-item-label class="font-bold text-slate-800 dark:text-blue-200 text-sm pl-2">
{{ $t('classroom.announcements', 'ประกาศในคอร์ส') }}
</q-item-label>
</q-item-section>
<q-item-section side v-if="hasUnreadAnnouncements">
<q-badge color="red" rounded label="New" />
</q-item-section>
</q-item>
<template v-for="chapter in courseData.chapters" :key="chapter.id">
<q-item-label header class="bg-slate-100 dark:bg-slate-800 text-[var(--text-main)] font-bold sticky top-0 z-10 border-b dark:border-white/5 text-sm py-4">
{{ getLocalizedText(chapter.title) }}
</q-item-label>
<q-item
v-for="lesson in chapter.lessons"
:key="lesson.id"
clickable
v-ripple
:active="currentLesson?.id === lesson.id"
active-class="bg-blue-50 text-blue-700 dark:bg-blue-900/20 dark:text-blue-200 font-medium"
class="border-b border-gray-50 dark:border-white/5"
@click="!lesson.is_locked && handleLessonSelect(lesson.id)"
:disable="lesson.is_locked"
>
<q-item-section avatar v-if="lesson.is_locked">
<q-icon name="lock" size="xs" color="grey" />
</q-item-section>
<q-item-section>
<q-item-label class="text-sm md:text-base line-clamp-2 text-[var(--text-main)]">
{{ getLocalizedText(lesson.title) }}
</q-item-label>
</q-item-section>
<q-item-section side>
<q-icon v-if="lesson.is_completed" name="check_circle" color="positive" size="xs" />
<q-icon v-else-if="currentLesson?.id === lesson.id" name="play_circle" color="primary" size="xs" />
<q-icon v-else name="radio_button_unchecked" color="grey-4" size="xs" />
</q-item-section>
</q-item>
</template>
</q-list>
</div>
<div v-else-if="isLoading" class="p-6 text-center text-slate-500">
<q-spinner color="primary" size="2em" />
<div class="mt-2 text-xs">{{ $t('classroom.loadingCurriculum') }}</div>
</div>
</q-drawer>
:courseData="courseData"
:currentLessonId="currentLesson?.id"
:isLoading="isLoading"
:hasUnreadAnnouncements="hasUnreadAnnouncements"
@select-lesson="handleLessonSelect"
@open-announcements="handleOpenAnnouncements"
/>
<!-- Main Content -->
<q-page-container class="bg-white dark:bg-slate-900">
@ -633,44 +464,15 @@ onBeforeUnmount(() => {
<!-- Video Player & Content Area -->
<div class="w-full max-w-7xl mx-auto p-4 md:p-6 flex-grow">
<!-- Video Player -->
<div v-if="currentLesson && videoSrc" class="bg-black rounded-xl overflow-hidden shadow-2xl mb-6 aspect-video relative group ring-1 ring-white/10">
<video
ref="videoRef"
:src="videoSrc"
class="w-full h-full object-contain"
@click="togglePlay"
@timeupdate="updateProgress"
@loadedmetadata="onVideoMetadataLoaded"
@ended="onVideoEnded"
/>
<!-- Custom Controls Overlay (Simplified) -->
<div class="absolute bottom-0 left-0 right-0 p-4 bg-gradient-to-t from-black/80 via-black/40 to-transparent transition-opacity opacity-0 group-hover:opacity-100">
<div class="flex items-center gap-4 text-white">
<q-btn flat round dense :icon="isPlaying ? 'pause' : 'play_arrow'" @click.stop="togglePlay" />
<div class="relative flex-grow h-1.5 bg-white/20 rounded-full cursor-pointer group/progress overflow-hidden" @click="seek">
<div class="absolute top-0 left-0 h-full bg-blue-500 rounded-full group-hover/progress:bg-blue-400 transition-all shadow-[0_0_10px_rgba(59,130,246,0.5)]" :style="{ width: videoProgress + '%' }"></div>
</div>
<span class="text-xs font-mono font-medium opacity-90">{{ currentTimeDisplay }} / {{ durationDisplay }}</span>
<!-- Volume Control -->
<div class="flex items-center gap-2 group/volume">
<q-btn flat round dense :icon="volumeIcon" @click.stop="handleToggleMute" color="white" />
<div class="w-0 group-hover/volume:w-20 overflow-hidden transition-all duration-300 flex items-center">
<input
type="range"
min="0"
max="1"
step="0.1"
:value="volume"
@input="handleVolumeChange"
class="w-20 h-1 bg-white/30 rounded-lg appearance-none cursor-pointer accent-blue-500"
/>
</div>
</div>
</div>
</div>
</div>
<VideoPlayer
v-if="currentLesson && videoSrc"
ref="videoPlayerComp"
:src="videoSrc"
:initialSeekTime="initialSeekTime"
@timeupdate="handleVideoTimeUpdate"
@ended="onVideoEnded"
@loadedmetadata="onVideoMetadataLoaded"
/>
<!-- Lesson Info -->
<div v-if="currentLesson" class="bg-[var(--bg-surface)] p-6 md:p-8 rounded-3xl shadow-sm border border-[var(--border-color)]">
@ -746,98 +548,10 @@ onBeforeUnmount(() => {
</q-page-container>
<!-- Announcements Modal -->
<q-dialog v-model="showAnnouncementsModal" backdrop-filter="blur(4px)">
<q-card class="min-w-[320px] md:min-w-[600px] rounded-3xl overflow-hidden bg-white dark:bg-slate-900 shadow-2xl">
<q-card-section class="bg-white dark:bg-slate-900 border-b border-gray-100 dark:border-white/5 p-5 flex items-center justify-between sticky top-0 z-10">
<div>
<div class="text-xl font-bold flex items-center gap-2 text-slate-900 dark:text-white">
<div class="w-10 h-10 rounded-full bg-blue-50 dark:bg-blue-900/30 text-primary flex items-center justify-center">
<q-icon name="campaign" size="22px" />
</div>
{{ $t('classroom.announcements', 'ประกาศในคอร์สเรียน') }}
</div>
<div class="text-xs text-slate-500 dark:text-slate-400 ml-12 mt-1">{{ announcements.length }} รายการ</div>
</div>
<q-btn icon="close" flat round dense v-close-popup class="text-slate-400 hover:text-slate-700 dark:hover:text-white bg-slate-50 dark:bg-slate-800" />
</q-card-section>
<q-card-section class="p-0 scroll max-h-[70vh] bg-slate-50 dark:bg-[#0B0F1A]">
<div v-if="announcements.length > 0" class="p-4 space-y-4">
<div
v-for="(ann, index) in announcements"
:key="index"
class="p-5 rounded-2xl bg-white dark:bg-slate-800 shadow-sm border border-gray-200 dark:border-white/5 transition-all hover:shadow-md relative overflow-hidden group"
:class="{'ring-2 ring-orange-200 dark:ring-orange-900/40 bg-orange-50/50 dark:bg-orange-900/10': ann.is_pinned}"
>
<!-- Pinned Banner -->
<div v-if="ann.is_pinned" class="absolute top-0 right-0 p-3">
<q-icon name="push_pin" color="orange" size="18px" class="transform rotate-45" />
</div>
<div class="flex items-start gap-4 mb-3">
<q-avatar
:color="ann.is_pinned ? 'orange-100' : 'blue-50'"
:text-color="ann.is_pinned ? 'orange-700' : 'blue-700'"
size="42px"
font-size="20px"
class="shadow-sm"
>
<span class="font-bold">{{ (getLocalizedText(ann.title) || 'A').charAt(0) }}</span>
</q-avatar>
<div class="flex-1">
<div class="font-bold text-lg text-slate-900 dark:text-white leading-tight pr-8 capitalize font-display">
{{ getLocalizedText(ann.title) || 'ประกาศ' }}
</div>
<div class="text-xs text-slate-500 dark:text-slate-400 flex items-center gap-2 mt-1.5">
<span class="flex items-center gap-1 bg-slate-100 dark:bg-slate-700 px-2 py-0.5 rounded-md">
<q-icon name="today" size="12px" />
{{ new Date(ann.created_at || Date.now()).toLocaleDateString('th-TH', { day: 'numeric', month: 'short', year: 'numeric' }) }}
</span>
<span class="flex items-center gap-1 bg-slate-100 dark:bg-slate-700 px-2 py-0.5 rounded-md">
<q-icon name="access_time" size="12px" />
{{ new Date(ann.created_at || Date.now()).toLocaleTimeString('th-TH', { hour: '2-digit', minute: '2-digit' }) }}
</span>
</div>
</div>
</div>
<div class="text-slate-600 dark:text-slate-300 text-sm leading-relaxed whitespace-pre-line pl-[58px] mb-4">
{{ getLocalizedText(ann.content) }}
</div>
<!-- Attachments in Announcement -->
<div v-if="ann.attachments && ann.attachments.length > 0" class="pl-[58px] mt-4 pt-4 border-t border-gray-100 dark:border-white/5">
<div class="text-xs font-bold text-slate-500 dark:text-slate-400 mb-3 flex items-center gap-1.5 uppercase tracking-wider">
<q-icon name="attach_file" /> {{ $t('classroom.attachments') || 'Attachments' }}
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
<a
v-for="file in ann.attachments"
:key="file.id"
:href="file.presigned_url"
target="_blank"
class="flex items-center gap-3 p-3 rounded-xl bg-gray-50 dark:bg-slate-700/50 hover:bg-blue-50 dark:hover:bg-blue-900/20 text-sm text-slate-700 dark:text-slate-200 border border-gray-200 dark:border-white/10 hover:border-blue-200 dark:hover:border-blue-700/50 transition-all group/file"
>
<div class="w-8 h-8 rounded-lg bg-white dark:bg-slate-600 flex items-center justify-center shadow-sm text-red-500">
<q-icon name="description" size="18px" />
</div>
<span class="truncate flex-1 font-medium">{{ file.file_name }}</span>
<q-icon name="download" size="14px" class="text-slate-400 group-hover/file:text-blue-500" />
</a>
</div>
</div>
</div>
</div>
<div v-else class="flex flex-col items-center justify-center p-12 text-slate-400 min-h-[300px]">
<div class="w-24 h-24 bg-slate-100 dark:bg-slate-800 rounded-full mb-6 flex items-center justify-center">
<q-icon name="notifications_off" size="3rem" class="text-slate-300 dark:text-slate-600" />
</div>
<div class="text-base font-medium text-slate-600 dark:text-slate-400">{{ $t('classroom.noAnnouncements', 'ไม่มีประกาศในขณะนี้') }}</div>
<div class="text-sm text-slate-400 mt-2">โพสตใหม จากผสอนจะปรากฏท</div>
</div>
</q-card-section>
</q-card>
</q-dialog>
<AnnouncementModal
v-model="showAnnouncementsModal"
:announcements="announcements"
/>
</q-layout>
</template>