feat: Implement initial e-learning platform frontend structure including dashboard, course management, authentication, and common UI components.

This commit is contained in:
supalerk-ar66 2026-02-27 10:05:33 +07:00
parent aceeb80d9a
commit ad11c6b7c5
44 changed files with 720 additions and 578 deletions

View file

@ -1,9 +1,9 @@
<script setup lang="ts">
/**
* @file quiz.vue
* @description Quiz Interface.
* Manages the entire quiz lifecycle: Start -> Taking -> Results -> Review.
* Features a timer, question navigation, and detailed result analysis.
* @description หนาสำหรบทำแบบทดสอบ (Quiz Interface)
* ดการวงจรชตของการทำแบบทดสอบทงหมด: เรมต -> ทำขอสอบ -> ผลลพธ -> ทบทวน
* เจอรบเวลา การนำทางระหวางคำถาม และการวเคราะหผลลพธอยางละเอยด
*/
definePageMeta({
@ -17,7 +17,7 @@ const router = useRouter()
const $q = useQuasar()
const { fetchCourseLearningInfo, fetchLessonContent, submitQuiz: apiSubmitQuiz, markLessonComplete } = useCourse()
// State Management
// (State Management)
const currentScreen = ref<'start' | 'taking' | 'result' | 'review'>('start')
const timeLeft = ref(0)
let timerInterval: ReturnType<typeof setInterval> | null = null
@ -30,20 +30,20 @@ const quizData = ref<any>(null)
const isLoading = ref(true)
const isSubmitting = ref(false)
// Quiz Taking State
// (Quiz Taking State)
const currentQuestionIndex = ref(0)
const userAnswers = ref<Record<number, number>>({}) // questionId -> choiceId
const visitedQuestions = ref<Set<number>>(new Set()) // Track visited indices
const userAnswers = ref<Record<number, number>>({}) // ID -> ID (questionId -> choiceId)
const visitedQuestions = ref<Set<number>>(new Set()) // (Track visited indices)
const quizResult = ref<any>(null)
// Tracking visited questions
// (Tracking visited questions)
watch(currentQuestionIndex, (newVal) => {
visitedQuestions.value.add(newVal)
}, { immediate: true })
// Helper: Get Status Color Class
// : (Helper: Get Status Color Class)
const getQuestionStatusClass = (index: number, questionId: number) => {
// 1. Current = Blue
// 1. = (Current = Blue)
if (index === currentQuestionIndex.value) {
return 'bg-blue-500 text-white border-blue-600 ring-2 ring-blue-200 dark:ring-blue-900'
}
@ -51,32 +51,29 @@ const getQuestionStatusClass = (index: number, questionId: number) => {
const hasAnswer = userAnswers.value[questionId] !== undefined
const isVisited = visitedQuestions.value.has(index)
// 2. Completed = Green
// 2. = (Completed = Green)
if (hasAnswer) {
return 'bg-emerald-500 text-white border-emerald-600'
}
// 3. Skipped = Orange (Visited but no answer)
// Note: If we are strictly following "Skipped" definition:
// "user pressed Skip or moved forward on a skippable question without saving an answer"
// In this linear flow, merely visiting and leaving empty counts as skipped.
// 3. = () (Skipped = Orange (Visited but no answer))
// :
//
if (isVisited && !hasAnswer) {
return 'bg-orange-500 text-white border-orange-600'
}
// 4. Not Started = Grey
// 4. = (Not Started = Grey)
return 'bg-slate-200 text-slate-400 border-slate-300 dark:bg-white/5 dark:border-white/5 dark:text-slate-600 hover:bg-slate-300 dark:hover:bg-white/10'
}
const jumpToQuestion = (targetIndex: number) => {
if (targetIndex === currentQuestionIndex.value) return
// Validation before leaving current (same logic as Next)
// (Validation before leaving current)
if (targetIndex > currentQuestionIndex.value) {
// If jumping forward, we must validate the CURRENT question requirements
// unless we treat grid jumps as free navigation?
// Req: "user cannot go Next until the question is answered and saved" (if not skippable).
// So we must check restriction on the current spot before leaving.
//
// ()
const isAnswered = userAnswers.value[currentQuestion.value.id] !== undefined
const isSkippable = quizData.value?.is_skippable
@ -91,12 +88,12 @@ const jumpToQuestion = (targetIndex: number) => {
}
}
// If jumping backward? Usually allowed freely.
// (If jumping backward? Usually allowed freely.)
currentQuestionIndex.value = targetIndex
}
// Computed
// Computed (Computed Properties)
const currentQuestion = computed(() => {
if (!quizData.value || !quizData.value.questions) return null
return quizData.value.questions[currentQuestionIndex.value]
@ -116,7 +113,7 @@ const timerDisplay = computed(() => {
return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
})
// Helper for localization
// (Helper for localization)
const getLocalizedText = (text: any) => {
if (!text) return ''
if (typeof text === 'string') return text
@ -126,7 +123,7 @@ const getLocalizedText = (text: any) => {
const lessonProgress = ref<any>(null)
// Data Fetching
// (Data Fetching)
const loadData = async () => {
isLoading.value = true
try {
@ -138,9 +135,9 @@ const loadData = async () => {
if (courseId && lessonId) {
const lessonRes = await fetchLessonContent(courseId, lessonId)
if (lessonRes.success) {
// Determine if data is directly the quiz or nested
// (Determine if data is directly the quiz or nested)
quizData.value = lessonRes.data.quiz || lessonRes.data
lessonProgress.value = lessonRes.progress // Capture progress
lessonProgress.value = lessonRes.progress // (Capture progress)
if (quizData.value?.time_limit) {
timeLeft.value = quizData.value.time_limit * 60
}
@ -153,7 +150,7 @@ const loadData = async () => {
}
}
// Helper for shuffling
// (Helper for shuffling)
const shuffleArray = <T>(array: T[]): T[] => {
return array
.map(value => ({ value, sort: Math.random() }))
@ -161,18 +158,18 @@ const shuffleArray = <T>(array: T[]): T[] => {
.map(({ value }) => value)
}
// Quiz Actions
// (Quiz Actions)
const startQuiz = () => {
// Deep copy to reset and apply shuffle
// (Deep copy to reset and apply shuffle)
const rawQuiz = JSON.parse(JSON.stringify(quizData.value))
if (rawQuiz) {
// Shuffle Questions
// (Shuffle Questions)
if (rawQuiz.shuffle_questions && rawQuiz.questions) {
rawQuiz.questions = shuffleArray(rawQuiz.questions)
}
// Shuffle Choices
// (Shuffle Choices)
if (rawQuiz.shuffle_choices && rawQuiz.questions) {
rawQuiz.questions.forEach((q: any) => {
if (q.choices) {
@ -180,7 +177,7 @@ const startQuiz = () => {
}
})
}
// Update state with shuffled data
// (Update state with shuffled data)
quizData.value = rawQuiz
}
@ -196,7 +193,7 @@ const startQuiz = () => {
}, 1000)
}
// Mark first as visited
// (Mark first as visited)
visitedQuestions.value = new Set([0])
}
@ -209,12 +206,12 @@ const selectAnswer = (choiceId: number) => {
const nextQuestion = () => {
if (!currentQuestion.value) return
// Allow skip if quiz is skippable or question is answered
// (Allow skip if quiz is skippable or question is answered)
const isAnswered = userAnswers.value[currentQuestion.value.id] !== undefined
const isSkippable = quizData.value?.is_skippable
if (!isAnswered && !isSkippable) {
// Show warning
// (Show warning)
$q.notify({
type: 'warning',
message: t('quiz.pleaseSelectAnswer', 'กรุณาเลือกคำตอบ'),
@ -241,7 +238,7 @@ const retryQuiz = () => {
}
const submitQuiz = async (auto = false) => {
// 1. Manual Validation: Check if all questions are answered
// 1. (Manual Validation: Check if all questions are answered)
if (!auto) {
const answeredCount = Object.keys(userAnswers.value).length
if (answeredCount < totalQuestions.value) {
@ -254,7 +251,7 @@ const submitQuiz = async (auto = false) => {
return
}
// Premium Confirmation before submission
// (Premium Confirmation before submission)
$q.dialog({
title: `<div class="text-slate-900 dark:text-white font-black text-xl">${t('quiz.warningTitle')}</div>`,
message: `<div class="text-slate-600 dark:text-slate-300 text-base leading-relaxed mt-2">${t('quiz.submitConfirm')}</div>`,
@ -285,33 +282,33 @@ const submitQuiz = async (auto = false) => {
}
const processSubmitQuiz = async (auto = false) => {
// 2. Start Submission Process
// 2. (Start Submission Process)
if (timerInterval) clearInterval(timerInterval)
isSubmitting.value = true
currentScreen.value = 'result' // Switch to result screen to show progress
currentScreen.value = 'result' // (Switch to result screen to show progress)
try {
// Prepare Payload
// API (Prepare Payload)
const answersPayload = Object.entries(userAnswers.value).map(([qId, cId]) => ({
question_id: Number(qId),
choice_id: cId
}))
// Check if already passed
// (Check if already passed)
const alreadyPassed = lessonProgress.value?.is_passed || lessonProgress.value?.is_completed || false
// Call API
// API (Call API)
const res = await apiSubmitQuiz(courseId, lessonId, answersPayload, alreadyPassed)
if (res.success && res.data) {
quizResult.value = res.data
// Update local progress if passed and not previously passed
// (Update local progress if passed and not previously passed)
if (res.data.is_passed && !alreadyPassed) {
if (lessonProgress.value) lessonProgress.value.is_passed = true
}
} else {
// Fallback error handling
// (Fallback error handling)
$q.notify({
type: 'negative',
message: res.error || 'Failed to submit quiz'
@ -364,14 +361,14 @@ const reviewQuiz = () => {
currentScreen.value = 'review'
}
// Helper to get choice label (A, B, C...)
// ID (A, B, C...) (Helper to get choice label (A, B, C...))
const getChoiceLabel = (index: number) => {
return String.fromCharCode(65 + index) // 65 is 'A'
}
const getCorrectChoiceId = (questionId: number) => {
if (!quizResult.value?.answers_review) return null
// Type checking for safety
// (Type checking for safety)
const review = Array.isArray(quizResult.value.answers_review)
? quizResult.value.answers_review.find((r: any) => r.question_id === questionId)
: null
@ -384,7 +381,7 @@ const getCorrectChoiceId = (questionId: number) => {
<q-page-container>
<q-page>
<div class="quiz-shell min-h-screen bg-slate-50 dark:bg-[#0b0f1a] text-slate-900 dark:text-slate-200 antialiased selection:bg-blue-500/20 transition-colors">
<!-- Header -->
<!-- วนห (Header) -->
<header class="h-14 bg-white dark:!bg-[var(--bg-surface)] fixed top-0 inset-x-0 z-[100] flex items-center px-6 border-b border-slate-200 dark:border-white/5 transition-colors">
<div class="flex items-center w-full justify-between">
<div class="flex items-center">
@ -410,7 +407,7 @@ const getCorrectChoiceId = (questionId: number) => {
</div>
</header>
<!-- Main Content Area -->
<!-- นทเนอหาหล (Main Content Area) -->
<main class="pt-14 h-screen flex items-center justify-center overflow-y-auto px-4 custom-scrollbar">
<div v-if="isLoading" class="flex flex-col items-center gap-4">
@ -435,9 +432,9 @@ const getCorrectChoiceId = (questionId: number) => {
</div>
<template v-else>
<!-- 1. START SCREEN -->
<!-- 1. หนาเรมต (START SCREEN) -->
<div v-if="currentScreen === 'start'" class="w-full max-w-[640px] animate-fade-in py-12">
<!-- ... (Start Screen is unchanged but needs to be here for context) ... -->
<!-- ... (หนาแรกยงคงเหมอนเด แปะไวเป reference) ... -->
<div class="bg-white dark:!bg-[#1e293b] border border-slate-200 dark:border-white/5 rounded-[32px] p-8 md:p-14 shadow-lg dark:shadow-2xl relative overflow-hidden transition-colors">
<div class="flex justify-center mb-10">
@ -459,7 +456,7 @@ const getCorrectChoiceId = (questionId: number) => {
</p>
</div>
<!-- Instruction Box -->
<!-- กลองคำแนะนำ (Instruction Box) -->
<div class="bg-slate-50 dark:bg-[#0b121f]/80 p-8 rounded-3xl mb-8 border border-slate-100 dark:border-white/5">
<h3 class="text-[12px] font-black text-slate-500 dark:text-slate-400 mb-6 uppercase tracking-[0.2em] flex items-center gap-2">
{{ $t('quiz.instructionTitle') }}
@ -483,17 +480,16 @@ const getCorrectChoiceId = (questionId: number) => {
</div>
</div>
<!-- 2. TAKING SCREEN -->
<!-- 2. TAKING SCREEN -->
<!-- 2. หนาทำแบบทดสอบ (TAKING SCREEN) -->
<div v-if="currentScreen === 'taking'" class="w-full max-w-[840px] animate-fade-in py-12">
<div v-if="currentQuestion" class="bg-white dark:!bg-[#1e293b] border border-slate-200 dark:border-white/5 rounded-[32px] p-8 md:p-12 shadow-xl relative overflow-hidden">
<!-- Progress Bar -->
<!-- แถบความคบหน (Progress Bar) -->
<div class="absolute top-0 left-0 right-0 h-1.5 bg-slate-100 dark:bg-white/5">
<div class="h-full bg-blue-500 transition-all duration-300" :style="{ width: ((currentQuestionIndex + 1) / totalQuestions) * 100 + '%' }"></div>
</div>
<!-- Question Map / Pagination -->
<!-- แผนทคำถาม / การเปลยนหน (Question Map / Pagination) -->
<div class="flex flex-wrap gap-2 mb-8 mt-4">
<button
v-for="(q, idx) in quizData?.questions"
@ -506,12 +502,12 @@ const getCorrectChoiceId = (questionId: number) => {
</button>
</div>
<!-- Question Title -->
<!-- อคำถาม (Question Title) -->
<h3 class="text-xl md:text-2xl font-bold text-slate-900 dark:text-white mb-10 leading-relaxed">
{{ getLocalizedText(currentQuestion.question) }}
</h3>
<!-- Choices -->
<!-- วนการเลอกคำตอบ (Choices) -->
<div class="flex flex-col gap-4 mb-12">
<button
v-for="choice in currentQuestion.choices"
@ -533,7 +529,7 @@ const getCorrectChoiceId = (questionId: number) => {
<!-- Controls -->
<!-- มควบคมตางๆ (Controls) -->
<div class="flex justify-between items-center pt-8 border-t border-slate-100 dark:border-white/5">
<button
@click="prevQuestion"
@ -563,7 +559,7 @@ const getCorrectChoiceId = (questionId: number) => {
<!-- 3. RESULT SCREEN -->
<!-- 3. หนาผลลพธการทำแบบทดสอบ (RESULT SCREEN) -->
<div v-if="currentScreen === 'result'" class="w-full max-w-[640px] animate-fade-in py-12">
<div class="bg-white dark:!bg-[#1e293b] border border-slate-200 dark:border-white/5 rounded-[40px] p-10 shadow-2xl text-center relative overflow-hidden">
@ -586,7 +582,7 @@ const getCorrectChoiceId = (questionId: number) => {
</p>
</div>
<!-- Score Card -->
<!-- ตรแสดงคะแนน (Score Card) -->
<div class="bg-slate-50 dark:bg-[#0b121f] rounded-3xl p-6 mb-8 flex items-center justify-around border border-slate-100 dark:border-white/5">
<div class="text-center">
<div class="text-xs font-black text-slate-400 uppercase tracking-widest mb-1">{{ $t('quiz.scoreLabel') }}</div>
@ -626,7 +622,7 @@ const getCorrectChoiceId = (questionId: number) => {
</div>
</div>
<!-- 4. REVIEW SCREEN -->
<!-- 4. หนาทบทวนขอสอบ (REVIEW SCREEN) -->
<div v-if="currentScreen === 'review'" class="w-full max-w-[840px] animate-fade-in py-12 pb-24">
<div class="space-y-6">
<div
@ -652,7 +648,7 @@ const getCorrectChoiceId = (questionId: number) => {
'border-slate-100 dark:border-white/5 opacity-80 dark:opacity-40': userAnswers[question.id] !== choice.id && choice.id !== getCorrectChoiceId(question.id)
}"
>
<!-- Indicator Icon -->
<!-- ไอคอนสถานะ (Indicator Icon) -->
<div
class="w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 font-bold text-sm border-2"
:class="{
@ -668,7 +664,7 @@ const getCorrectChoiceId = (questionId: number) => {
<span class="font-medium text-slate-700 dark:text-slate-300">{{ getLocalizedText(choice.text) }}</span>
<!-- Label Badge -->
<!-- ายแสดงสถานะ (Label Badge) -->
<div v-if="choice.id === getCorrectChoiceId(question.id)" class="ml-auto px-2 py-0.5 bg-emerald-100 dark:bg-emerald-500/20 text-emerald-700 dark:text-emerald-300 text-xs font-bold rounded uppercase tracking-wider">
{{ $t('quiz.correctLabel', 'Correct') }}
</div>
@ -695,11 +691,11 @@ const getCorrectChoiceId = (questionId: number) => {
</main>
</div> <!-- Close quiz-shell -->
</div> <!-- ดสวนเปลอกขอสอบ (Close quiz-shell) -->
<!-- Question Navigator Sidebar/Floating (Desktop) - Outside Main Flow -->
<!-- Using QPageSticky properly inside q-page/q-layout context we added -->
<!-- อปอปแผนทคำถาม (เดสกอป) - อยนอกพนททำงานปกต (Question Navigator Sidebar/Floating (Desktop) - Outside Main Flow) -->
<!-- ใชงาน QPageSticky ใหกท (Using QPageSticky properly inside q-page/q-layout context we added) -->
<q-page-sticky
v-if="false"
position="top-right"