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

@ -27,9 +27,10 @@ const selectedCourse = ref<any>(null);
const isLoading = ref(false);
const isLoadingDetail = ref(false);
const isEnrolling = ref(false);
const showAllCategories = ref(false);
const { t } = useI18n();
const { currentUser } = useAuth();
const { fetchCategories } = useCategory();
const { fetchCourses, fetchCourseById, enrollCourse } = useCourse();
@ -142,59 +143,10 @@ onMounted(() => {
<!-- LEFT SIDEBAR: Category Filter -->
<div class="w-full lg:w-64 flex-shrink-0 lg:sticky lg:top-24">
<div class="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden">
<q-expansion-item
expand-separator
:label="`หมวดหมู่ (${selectedCategoryIds.length})`"
class="font-bold text-slate-900"
header-class="bg-white"
text-color="slate-900"
:header-style="{ color: '#0f172a' }"
default-opened
>
<q-list class="bg-white border-t border-slate-200">
<q-item
v-for="cat in (showAllCategories ? categories : categories.slice(0, 4))"
:key="cat.id"
tag="label"
clickable
v-ripple
dense
>
<q-item-section avatar>
<q-checkbox
v-model="selectedCategoryIds"
:val="cat.id"
color="primary"
dense
class="checkbox-visible"
/>
</q-item-section>
<q-item-section>
<q-item-label class="text-sm font-medium text-slate-900">{{ getLocalizedText(cat.name) }}</q-item-label>
</q-item-section>
</q-item>
<!-- Show More/Less Button -->
<q-item
v-if="categories.length > 4"
clickable
v-ripple
@click="showAllCategories = !showAllCategories"
class="text-blue-600 font-bold text-sm"
>
<q-item-section>
<div class="flex items-center gap-1">
{{ showAllCategories ? 'แสดงน้อยลง' : 'แสดงเพิ่มเติม' }}
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" :class="showAllCategories ? 'rotate-180' : ''">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
</div>
</q-item-section>
</q-item>
</q-list>
</q-expansion-item>
</div>
<CategorySidebar
:categories="categories"
v-model="selectedCategoryIds"
/>
</div>
<!-- RIGHT CONTENT: Course Grid -->
@ -248,95 +200,13 @@ onMounted(() => {
<q-spinner size="3rem" color="primary" />
</div>
<div v-else-if="selectedCourse" class="grid grid-cols-1 lg:grid-cols-12 gap-8">
<!-- Main Content (Left Column) -->
<div class="lg:col-span-8">
<!-- Hero Video Placeholder -->
<div
class="w-full aspect-video bg-slate-900 rounded-3xl overflow-hidden relative shadow-lg mb-8 group"
>
<img
v-if="selectedCourse.thumbnail_url"
:src="selectedCourse.thumbnail_url"
class="absolute inset-0 w-full h-full object-cover opacity-60 group-hover:opacity-40 transition-opacity"
/>
</div>
<h1 class="text-3xl md:text-4xl font-bold mb-4 text-slate-900 dark:text-white tracking-tight">
{{ getLocalizedText(selectedCourse.title) }}
</h1>
<p class="text-slate-600 dark:text-slate-400 text-lg leading-relaxed mb-8">
{{ getLocalizedText(selectedCourse.description) }}
</p>
<!-- Course Syllabus -->
<div class="bg-white dark:bg-slate-800 rounded-3xl p-8 shadow-sm border border-slate-100 dark:border-slate-700">
<h3 class="text-xl font-bold mb-6 text-slate-900 flex items-center gap-2">
<span class="w-1 h-6 bg-blue-500 rounded-full"></span>
{{ $t('course.courseContent') }}
</h3>
<div class="space-y-4">
<div v-for="(chapter, index) in selectedCourse.chapters" :key="chapter.id" class="border border-slate-200 dark:border-slate-700 rounded-xl overflow-hidden">
<div class="bg-slate-50 dark:bg-slate-700/50 p-4 flex justify-between items-center cursor-pointer">
<div class="font-bold text-slate-800 dark:text-slate-100">
<span class="opacity-50 mr-2">Chapter {{ Number(index) + 1 }}</span>
{{ getLocalizedText(chapter.title) }}
</div>
<span class="text-xs font-bold px-3 py-1 bg-white rounded-full border border-slate-200">
{{ chapter.lessons ? chapter.lessons.length : 0 }} Lessons
</span>
</div>
<!-- Lessons -->
<div class="divide-y divide-slate-100 dark:divide-slate-700 bg-white dark:bg-slate-800">
<div v-for="(lesson, lIndex) in chapter.lessons" :key="lesson.id" class="p-4 flex justify-between items-center hover:bg-slate-50 dark:hover:bg-slate-700 transition-colors">
<div class="flex items-center gap-3">
<div class="w-6 h-6 rounded-full bg-slate-100 dark:bg-slate-700 flex items-center justify-center text-[10px] font-bold text-slate-500 dark:text-slate-400">
{{ Number(lIndex) + 1 }}
</div>
<span class="text-slate-700 dark:text-slate-200 font-medium text-sm">{{ getLocalizedText(lesson.title) }}</span>
</div>
<span class="text-xs text-slate-400">{{ lesson.duration_minutes || 0 }}:00</span>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Sidebar (Right Column) -->
<div class="lg:col-span-4">
<div class="bg-white rounded-3xl p-6 shadow-lg border border-slate-100 sticky top-24">
<q-btn
@click="handleEnroll(selectedCourse.id)"
unelevated
rounded
class="w-full py-3 text-lg font-bold bg-gradient-to-r from-blue-600 to-indigo-600 text-white shadow-lg"
:loading="isEnrolling"
:label="$t('course.enrollNow')"
>
<template v-slot:loading>
<q-spinner-facebook />
</template>
</q-btn>
<div class="text-sm space-y-3 pt-4 border-t border-slate-100">
<div class="flex justify-between text-slate-600 dark:text-black">
<span>{{ $t('course.certificate') }}</span>
<span class="font-bold text-slate-900 dark:text-black">{{ selectedCourse.have_certificate ? 'มีใบประกาศฯ' : 'ไม่มี' }}</span>
</div>
<div v-if="selectedCourse.instructor_name" class="flex justify-between text-slate-600 dark:text-black">
<span>สอน</span>
<span class="font-bold text-slate-900 dark:text-black">{{ selectedCourse.instructor_name }}</span>
</div>
<div v-if="selectedCourse.level" class="flex justify-between text-slate-600 dark:text-black">
<span>ระด</span>
<span class="font-bold text-slate-900 dark:text-black">{{ selectedCourse.level }}</span>
</div>
</div>
</div>
</div>
</div>
<CourseDetailView
v-else-if="selectedCourse"
:course="selectedCourse"
:user="currentUser"
@back="showDetail = false"
@enroll="handleEnroll"
/>
</div>
</div>
</template>

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>

View file

@ -50,44 +50,29 @@ const passwordForm = reactive({
})
const nameRules = [(val: string) => !!val || t('common.required')]
const emailRules = [
(val: string) => !!val || t('common.required'),
(val: string) => /.+@.+\..+/.test(val) || t('common.invalidEmail')
]
const phoneRules = [
(val: string) => !!val || t('common.required'),
(val: string) => /^0[0-9]{8,9}$/.test(val) || t('common.invalidPhone')
]
const passwordRules = [
(val: string) => !!val || t('common.required'),
(val: string) => val.length >= 6 || t('common.passwordTooShort'),
(val: string) => val !== passwordForm.currentPassword || 'รหัสผ่านใหม่ต้องไม่ซ้ำกับรหัสผ่านปัจจุบัน'
]
const confirmPasswordRules = [
(val: string) => !!val || t('common.required'),
(val: string) => val === passwordForm.newPassword || t('common.passwordsDoNotMatch')
]
// Rules have been moved to components
const showCurrentPassword = ref(false)
const showNewPassword = ref(false)
const showConfirmPassword = ref(false)
const fileInput = ref<HTMLInputElement | null>(null)
const fileInput = ref<HTMLInputElement | null>(null) // Used in view mode (outside component)
const toggleEdit = (edit: boolean) => {
isEditing.value = edit
}
const triggerUpload = () => {
fileInput.value?.click()
}
// Updated to accept File object directly (or Event for view mode compatibility if needed)
const handleFileUpload = async (fileOrEvent: File | Event) => {
let file: File | null = null
const handleFileUpload = async (event: Event) => {
const target = event.target as HTMLInputElement
if (target.files && target.files[0]) {
const file = target.files[0]
if (fileOrEvent instanceof File) {
file = fileOrEvent
} else {
// Fallback for native input change event
const target = (fileOrEvent as Event).target as HTMLInputElement
if (target.files && target.files[0]) {
file = target.files[0]
}
}
if (file) {
// Preview
const reader = new FileReader()
reader.onload = (e) => {
@ -103,13 +88,17 @@ const handleFileUpload = async (event: Event) => {
if (result.success && result.data?.avatar_url) {
userData.value.photoURL = result.data.avatar_url
} else {
// error ( 500) preview alert
console.error('Upload failed:', result.error)
alert(result.error || t('profile.updateError'))
}
}
}
// Trigger upload for VIEW mode avatar click
const triggerUpload = () => {
fileInput.value?.click()
}
const handleUpdateProfile = async () => {
@ -277,241 +266,19 @@ onMounted(() => {
<div v-else class="grid grid-cols-1 lg:grid-cols-2 gap-8 fade-in">
<div class="card-premium p-8 h-fit">
<h2 class="text-xl font-bold flex items-center gap-3 text-slate-900 dark:text-white mb-6">
<q-icon name="person" class="text-blue-500 text-2xl" />
{{ $t('profile.editPersonalDesc') }}
</h2>
<div class="flex flex-col gap-6">
<div class="flex items-center gap-6">
<div class="relative group cursor-pointer" @click="triggerUpload">
<UserAvatar
:photo-u-r-l="userData.photoURL"
:first-name="userData.firstName"
:last-name="userData.lastName"
size="80"
class="rounded-2xl border-2 border-slate-100 dark:border-white/10"
/>
<!-- Hover Overlay only if has photo (optional) or always? User didn't specify, keeping simple clickable -->
<div class="absolute inset-0 bg-black/40 rounded-2xl flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
<q-icon name="camera_alt" class="text-white text-xl" />
</div>
<!-- Hidden Input -->
<input ref="fileInput" type="file" class="hidden" accept="image/*" @change="handleFileUpload" >
</div>
<div class="flex flex-col gap-2">
<div class="font-bold text-slate-900 dark:text-white mb-1">{{ $t('profile.yourAvatar') }}</div>
<!-- Buttons Row -->
<div class="flex items-center gap-3">
<template v-if="userData.photoURL">
<q-btn
unelevated
rounded
color="primary"
:label="$t('profile.changeAvatar')"
class="font-bold shadow-lg shadow-blue-500/30"
@click="triggerUpload"
/>
</template>
<template v-else>
<q-btn
unelevated
rounded
color="primary"
:label="$t('profile.uploadNew')"
class="font-bold shadow-lg shadow-blue-500/30"
@click="triggerUpload"
/>
</template>
</div>
<!-- Add Limit Text -->
<div class="mt-1 text-xs text-slate-500 dark:text-slate-400">
{{ $t('profile.uploadLimit') }}
</div>
</div>
</div>
<q-separator class="bg-slate-100 dark:bg-white/5" />
<q-form @submit="handleUpdateProfile" class="flex flex-col gap-6">
<div class="grid grid-cols-1 gap-4">
<div class="space-y-1">
<label class="text-xs font-bold text-slate-500 dark:text-slate-400 ml-1 uppercase">{{ $t('profile.prefix') }}</label>
<q-select
v-model="userData.prefix"
:options="['นาย', 'นาง', 'นางสาว']"
outlined
dense
rounded
class="premium-q-input"
popup-content-class="text-slate-900"
/>
</div>
<div class="grid grid-cols-2 gap-4">
<div>
<label class="text-xs font-bold text-slate-500 dark:text-slate-400 ml-1 uppercase">{{ $t('profile.firstName') }}</label>
<q-input
v-model="userData.firstName"
outlined dense rounded
class="premium-q-input"
:rules="nameRules"
hide-bottom-space
/>
</div>
<div>
<label class="text-xs font-bold text-slate-500 dark:text-slate-400 ml-1 uppercase">{{ $t('profile.lastName') }}</label>
<q-input
v-model="userData.lastName"
outlined dense rounded
class="premium-q-input"
:rules="nameRules"
hide-bottom-space
/>
</div>
</div>
<div>
<div class="flex justify-between items-end mb-1">
<label class="text-xs font-bold text-slate-500 dark:text-slate-400 ml-1 uppercase">{{ $t('profile.email') }}</label>
</div>
<q-input
v-model="userData.email"
type="email"
outlined dense rounded
class="premium-q-input"
:rules="emailRules"
hide-bottom-space
disable
:hint="$t('profile.emailHint')"
/>
</div>
<div>
<label class="text-xs font-bold text-slate-500 dark:text-slate-400 ml-1 uppercase">{{ $t('profile.phone') }}</label>
<q-input
v-model="userData.phone"
outlined dense rounded
class="premium-q-input"
:rules="phoneRules"
hide-bottom-space
/>
</div>
</div>
<div class="pt-2">
<q-btn
type="submit"
unelevated
rounded
color="primary"
class="w-full py-3 font-bold text-base shadow-lg shadow-blue-500/20"
:label="$t('common.save')"
:loading="isProfileSaving"
/>
</div>
</q-form>
</div> <!-- Close the wrapper div -->
</div>
<ProfileEditForm
v-model="userData"
:loading="isProfileSaving"
@submit="handleUpdateProfile"
@upload="handleFileUpload"
/>
<div class="card-premium p-8 h-fit">
<h2 class="text-xl font-bold flex items-center gap-3 text-slate-900 dark:text-white mb-6">
<q-icon name="lock" class="text-amber-500 text-2xl" />
{{ $t('profile.security') }}
</h2>
<q-form @submit="handleUpdatePassword" class="flex flex-col gap-6">
<div class="text-sm text-slate-500 dark:text-slate-400 mb-2">
{{ $t('profile.securityDesc') }}
</div>
<div class="space-y-4">
<div>
<label class="text-xs font-bold text-slate-500 dark:text-slate-400 ml-1 uppercase">{{ $t('profile.currentPassword') }}</label>
<q-input
v-model="passwordForm.currentPassword"
:type="showCurrentPassword ? 'text' : 'password'"
outlined dense rounded
class="premium-q-input"
placeholder=""
:rules="[val => !!val || $t('common.required')]"
>
<template v-slot:append>
<q-icon
:name="showCurrentPassword ? 'visibility_off' : 'visibility'"
class="cursor-pointer text-slate-400"
@click="showCurrentPassword = !showCurrentPassword"
/>
</template>
</q-input>
</div>
<q-separator class="bg-slate-100 dark:bg-white/5 my-2" />
<div>
<label class="text-xs font-bold text-slate-500 dark:text-slate-400 ml-1 uppercase">{{ $t('profile.newPassword') }}</label>
<q-input
v-model="passwordForm.newPassword"
:type="showNewPassword ? 'text' : 'password'"
outlined dense rounded
class="premium-q-input"
:placeholder="$t('profile.newPasswordHint')"
:rules="passwordRules"
>
<template v-slot:append>
<q-icon
:name="showNewPassword ? 'visibility_off' : 'visibility'"
class="cursor-pointer text-slate-400"
@click="showNewPassword = !showNewPassword"
/>
</template>
</q-input>
</div>
<div>
<label class="text-xs font-bold text-slate-500 dark:text-slate-400 ml-1 uppercase">{{ $t('profile.confirmNewPassword') }}</label>
<q-input
v-model="passwordForm.confirmPassword"
:type="showConfirmPassword ? 'text' : 'password'"
outlined dense rounded
class="premium-q-input"
:placeholder="$t('profile.confirmPasswordHint')"
:rules="confirmPasswordRules"
>
<template v-slot:append>
<q-icon
:name="showConfirmPassword ? 'visibility_off' : 'visibility'"
class="cursor-pointer text-slate-400"
@click="showConfirmPassword = !showConfirmPassword"
/>
</template>
</q-input>
</div>
</div>
<div class="pt-2">
<q-btn
type="submit"
unelevated
rounded
class="w-full py-3 font-bold text-base shadow-lg shadow-amber-500/20"
style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); color: white;"
:label="$t('profile.changePasswordBtn')"
:loading="isPasswordSaving"
/>
</div>
</q-form>
</div>
<PasswordChangeForm
v-model="passwordForm"
:loading="isPasswordSaving"
@submit="handleUpdatePassword"
/>
</div>
</div>