vault backup: 2025-12-22 16:06:48
All checks were successful
Deploy Quartz site to GitHub Pages / build (push) Successful in 1m58s
All checks were successful
Deploy Quartz site to GitHub Pages / build (push) Successful in 1m58s
This commit is contained in:
5
content/.obsidian/workspace.json
vendored
5
content/.obsidian/workspace.json
vendored
@@ -70,7 +70,7 @@
|
||||
"state": {
|
||||
"type": "search",
|
||||
"state": {
|
||||
"query": "spoiler-",
|
||||
"query": "frågetyp/matching",
|
||||
"matchingCase": false,
|
||||
"explainSearch": false,
|
||||
"collapseAll": false,
|
||||
@@ -209,6 +209,8 @@
|
||||
},
|
||||
"active": "b6de1b6650c09ff3",
|
||||
"lastOpenFiles": [
|
||||
"Anatomi & Histologi 2/Öga anatomi.md",
|
||||
"Anatomi & Histologi 2/Schema.md",
|
||||
"Anatomi & Histologi 2/Statistik.md",
|
||||
"Anatomi & Histologi 2/1 Öga anatomi/Slides.pdf.pdf",
|
||||
"Anatomi & Histologi 2/1 Öga anatomi/Slides.md",
|
||||
@@ -221,7 +223,6 @@
|
||||
"Anatomi & Histologi 2/2 Öra anatomi/Video 3.md",
|
||||
"Anatomi & Histologi 2/2 Öra anatomi/Video 2.md",
|
||||
"Anatomi & Histologi 2/2 Öra anatomi/Video 1.md",
|
||||
"Anatomi & Histologi 2/Schema.md",
|
||||
"Anatomi & Histologi 2/1 Öga anatomi/Provfrågor.md",
|
||||
"Anatomi & Histologi 2/Gamla tentor/2024-01-10/21.md",
|
||||
"Anatomi & Histologi 2/Gamla tentor/2025-01-15/17.md",
|
||||
|
||||
0
content/Anatomi & Histologi 2/Öga anatomi.md
Normal file
0
content/Anatomi & Histologi 2/Öga anatomi.md
Normal file
18
quiz/MATCHING_FORMAT.md
Normal file
18
quiz/MATCHING_FORMAT.md
Normal file
@@ -0,0 +1,18 @@
|
||||
# Matching Questions Format Analysis
|
||||
|
||||
Based on reviewing the 17 matching questions:
|
||||
|
||||
## Key Finding:
|
||||
Only **1 question has an answer** (2023-05-31/3.md), the rest have TODO.
|
||||
|
||||
**That question uses this format:**
|
||||
- Two separate bullet lists
|
||||
- Answer: "ItemName: MatchName" format
|
||||
|
||||
## Proposed Implementation:
|
||||
1. Support two-list format (most flexible)
|
||||
2. Parse answer as "Item: Match" pairs
|
||||
3. Store as JSON with 0-indexed pairs
|
||||
4. Render as n×n table with radio buttons
|
||||
|
||||
## Next: Implement based on this one working example.
|
||||
BIN
quiz/db.sqlite3
BIN
quiz/db.sqlite3
Binary file not shown.
Binary file not shown.
Binary file not shown.
23
quiz/quiz/migrations/0010_add_matching_question_fields.py
Normal file
23
quiz/quiz/migrations/0010_add_matching_question_fields.py
Normal file
@@ -0,0 +1,23 @@
|
||||
# Generated by Django 6.0 on 2025-12-22 14:36
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('quiz', '0009_quizresult_difficulty'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='question',
|
||||
name='matching_data',
|
||||
field=models.JSONField(blank=True, help_text='JSON data for matching questions: {left_items: [...], top_items: [...], correct_pairs: [[0,1], [1,2], ...]}', null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='question',
|
||||
name='question_type',
|
||||
field=models.CharField(choices=[('mcq', 'Multiple Choice'), ('scq', 'Single Choice'), ('matching', 'Matching'), ('textalternativ', 'Text Alternative'), ('textfält', 'Text Field')], default='mcq', max_length=20),
|
||||
),
|
||||
]
|
||||
@@ -48,6 +48,26 @@ class Question(models.Model):
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
tags = models.ManyToManyField('Tag', blank=True, related_name='questions')
|
||||
|
||||
# Question type field
|
||||
question_type = models.CharField(
|
||||
max_length=20,
|
||||
default='mcq',
|
||||
choices=[
|
||||
('mcq', 'Multiple Choice'),
|
||||
('scq', 'Single Choice'),
|
||||
('matching', 'Matching'),
|
||||
('textalternativ', 'Text Alternative'),
|
||||
('textfält', 'Text Field'),
|
||||
]
|
||||
)
|
||||
|
||||
# JSON field for matching questions
|
||||
matching_data = models.JSONField(
|
||||
null=True,
|
||||
blank=True,
|
||||
help_text="JSON data for matching questions: {left_items: [...], top_items: [...], correct_pairs: [[0,1], [1,2], ...]}"
|
||||
)
|
||||
|
||||
def __str__(self):
|
||||
return self.text[:50]
|
||||
|
||||
|
||||
0
quiz/quiz/tests/__init__.py
Normal file
0
quiz/quiz/tests/__init__.py
Normal file
128
quiz/quiz/tests/test_matching_parser.py
Normal file
128
quiz/quiz/tests/test_matching_parser.py
Normal file
@@ -0,0 +1,128 @@
|
||||
from django.test import TestCase
|
||||
from pathlib import Path
|
||||
from quiz.utils.importer import parse_matching_question
|
||||
|
||||
|
||||
class MatchingQuestionParserTests(TestCase):
|
||||
"""Tests for matching question parser"""
|
||||
|
||||
def test_parse_matching_5x5(self):
|
||||
"""Test parsing the real 5x5 matching question"""
|
||||
content = """---
|
||||
tags: [ah2, provfråga, frågetyp/matching, anatomi, öra]
|
||||
date: 2023-05-31
|
||||
---
|
||||
**Matcha rätt funktion med rätt lob:**
|
||||
(1p för alla rätt, inga delpoäng)
|
||||
- Smak
|
||||
- Syn
|
||||
- Somatosensorik
|
||||
- Motorik
|
||||
- Hörsel
|
||||
|
||||
- Lobus frontalis
|
||||
- Lobus Insularis
|
||||
- Lobus temporalis
|
||||
- Lobus parietalis
|
||||
- Lobus occipitalis
|
||||
|
||||
```spoiler-block:
|
||||
Smak: Lobus Insularis
|
||||
Syn: Lobus occipitalis
|
||||
Somatosensorik: Lobus parietalis
|
||||
Motorik: Lobus frontalis
|
||||
Hörsel: Lobus temporalis
|
||||
```
|
||||
"""
|
||||
is_matching, data = parse_matching_question(content)
|
||||
|
||||
self.assertTrue(is_matching)
|
||||
self.assertEqual(data['question_type'], 'matching')
|
||||
self.assertTrue(data['has_answer'])
|
||||
self.assertEqual(len(data['left_items']), 5)
|
||||
self.assertEqual(len(data['top_items']), 5)
|
||||
self.assertEqual(len(data['correct_pairs']), 5)
|
||||
|
||||
# Check specific items
|
||||
self.assertIn('Smak', data['left_items'])
|
||||
self.assertIn('Lobus frontalis', data['top_items'])
|
||||
|
||||
# Check correct pairs (Smak -> Lobus Insularis)
|
||||
# Smak is index 0, Lobus Insularis is index 1
|
||||
self.assertIn([0, 1], data['correct_pairs'])
|
||||
|
||||
def test_parse_matching_4x4(self):
|
||||
"""Test parsing a 4x4 matching question"""
|
||||
content = """---
|
||||
tags: [test, frågetyp/matching]
|
||||
date: 2023-01-01
|
||||
---
|
||||
Match the items:
|
||||
|
||||
- Item 1
|
||||
- Item 2
|
||||
- Item 3
|
||||
- Item 4
|
||||
|
||||
- Match A
|
||||
- Match B
|
||||
- Match C
|
||||
- Match D
|
||||
|
||||
```spoiler-block:
|
||||
Item 1: Match B
|
||||
Item 2: Match A
|
||||
Item 3: Match D
|
||||
Item 4: Match C
|
||||
```
|
||||
"""
|
||||
is_matching, data = parse_matching_question(content)
|
||||
|
||||
self.assertTrue(is_matching)
|
||||
self.assertEqual(len(data['left_items']), 4)
|
||||
self.assertEqual(len(data['top_items']), 4)
|
||||
self.assertEqual(len(data['correct_pairs']), 4)
|
||||
|
||||
def test_parse_matching_todo(self):
|
||||
"""Test parsing matching question with TODO answer"""
|
||||
content = """---
|
||||
tags: [test, frågetyp/matching]
|
||||
date: 2023-01-01
|
||||
---
|
||||
Match the items:
|
||||
|
||||
- Item 1
|
||||
- Item 2
|
||||
|
||||
- Match A
|
||||
- Match B
|
||||
|
||||
```spoiler-block:
|
||||
TODO
|
||||
```
|
||||
"""
|
||||
is_matching, data = parse_matching_question(content)
|
||||
|
||||
self.assertTrue(is_matching)
|
||||
self.assertFalse(data['has_answer'])
|
||||
self.assertEqual(len(data['correct_pairs']), 0)
|
||||
|
||||
def test_parse_matching_no_answer(self):
|
||||
"""Test parsing matching question without answer block"""
|
||||
content = """---
|
||||
tags: [test, frågetyp/matching]
|
||||
date: 2023-01-01
|
||||
---
|
||||
Match the items:
|
||||
|
||||
- Item 1
|
||||
- Item 2
|
||||
|
||||
- Match A
|
||||
- Match B
|
||||
"""
|
||||
is_matching, data = parse_matching_question(content)
|
||||
|
||||
self.assertTrue(is_matching)
|
||||
self.assertFalse(data['has_answer'])
|
||||
self.assertEqual(len(data['correct_pairs']), 0)
|
||||
@@ -3,7 +3,7 @@ from django.urls import path
|
||||
|
||||
from .views import (
|
||||
index, get_next_question, submit_answer, stats, create_quiz, close_quiz,
|
||||
quiz_mode, quiz_question, navigate_question, submit_difficulty
|
||||
quiz_mode, quiz_question, navigate_question, submit_difficulty, tag_count_api
|
||||
)
|
||||
|
||||
urlpatterns = [
|
||||
@@ -18,5 +18,6 @@ urlpatterns = [
|
||||
path('close/<int:session_id>/', close_quiz, name='close_quiz'),
|
||||
path('stats/', stats, name='stats'),
|
||||
path('create/', create_quiz, name='create_quiz'),
|
||||
path('api/tag-count/<slug:tag_slug>/', tag_count_api, name='tag_count_api'),
|
||||
]
|
||||
|
||||
|
||||
@@ -70,6 +70,172 @@ class ImportStats:
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def parse_matching_question(content: str) -> Tuple[bool, dict]:
|
||||
"""
|
||||
Parse matching question from markdown.
|
||||
|
||||
Expected format:
|
||||
- Two consecutive bullet lists (with "- " prefix)
|
||||
- First list = left column items (rows)
|
||||
- Second list = top row items (columns)
|
||||
- Answer format: "LeftItem: TopItem" pairs
|
||||
|
||||
Returns:
|
||||
(is_matching, question_data) where question_data contains:
|
||||
- text: question text
|
||||
- left_items: list of left column items
|
||||
- top_items: list of top row items
|
||||
- correct_pairs: list of [left_idx, top_idx] pairs (0-indexed)
|
||||
- has_answer: whether it has an answer (not TODO)
|
||||
- question_type: 'matching'
|
||||
"""
|
||||
lines = content.split('\n')
|
||||
|
||||
# Extract question text (first non-empty line after frontmatter)
|
||||
question_text = None
|
||||
in_frontmatter = False
|
||||
frontmatter_done = False
|
||||
|
||||
for line in lines:
|
||||
if line.strip() == '---':
|
||||
if not in_frontmatter:
|
||||
in_frontmatter = True
|
||||
else:
|
||||
in_frontmatter = False
|
||||
frontmatter_done = True
|
||||
continue
|
||||
|
||||
if frontmatter_done and line.strip() and not line.startswith('![['):
|
||||
if not line.startswith('-') and not line.startswith('```'):
|
||||
question_text = line.strip().replace('**', '')
|
||||
break
|
||||
|
||||
if not question_text:
|
||||
return True, {
|
||||
'text': None,
|
||||
'left_items': [],
|
||||
'top_items': [],
|
||||
'correct_pairs': [],
|
||||
'has_answer': False,
|
||||
'question_type': 'matching'
|
||||
}
|
||||
|
||||
# Extract two consecutive bullet lists
|
||||
left_items = []
|
||||
top_items = []
|
||||
in_first_list = False
|
||||
in_second_list = False
|
||||
in_frontmatter = False
|
||||
frontmatter_done = False
|
||||
found_question_text = False
|
||||
|
||||
for line in lines:
|
||||
# Track frontmatter
|
||||
if line.strip() == '---':
|
||||
if not in_frontmatter:
|
||||
in_frontmatter = True
|
||||
else:
|
||||
in_frontmatter = False
|
||||
frontmatter_done = True
|
||||
continue
|
||||
|
||||
if in_frontmatter or not frontmatter_done:
|
||||
continue
|
||||
|
||||
# Skip spoiler blocks
|
||||
if line.strip().startswith('```'):
|
||||
break
|
||||
|
||||
# Found question text
|
||||
if not found_question_text and question_text in line:
|
||||
found_question_text = True
|
||||
continue
|
||||
|
||||
if not found_question_text:
|
||||
continue
|
||||
|
||||
# Look for bullet lists
|
||||
if line.strip().startswith('- '):
|
||||
item = line.strip()[2:].strip()
|
||||
if not item: # Empty bullet
|
||||
continue
|
||||
|
||||
if not in_first_list and not in_second_list:
|
||||
in_first_list = True
|
||||
left_items.append(item)
|
||||
elif in_first_list:
|
||||
left_items.append(item)
|
||||
elif in_second_list:
|
||||
top_items.append(item)
|
||||
elif line.strip() == '':
|
||||
# Empty line - transition from first list to second
|
||||
if in_first_list and left_items:
|
||||
in_first_list = False
|
||||
in_second_list = True
|
||||
elif not line.strip().startswith('-') and (in_first_list or in_second_list):
|
||||
# Non-bullet line after starting lists - end of lists
|
||||
break
|
||||
|
||||
# Parse answer from spoiler block
|
||||
correct_pairs = []
|
||||
has_answer = False
|
||||
in_spoiler = False
|
||||
answer_lines = []
|
||||
|
||||
for line in lines:
|
||||
if line.strip().startswith('```spoiler-block'):
|
||||
in_spoiler = True
|
||||
continue
|
||||
if in_spoiler:
|
||||
if line.strip() == '```':
|
||||
break
|
||||
stripped = line.strip()
|
||||
if stripped:
|
||||
answer_lines.append(stripped)
|
||||
|
||||
if answer_lines:
|
||||
full_answer = ' '.join(answer_lines)
|
||||
|
||||
# Check for TODO
|
||||
if 'TODO' in full_answer.upper():
|
||||
has_answer = False
|
||||
else:
|
||||
has_answer = True
|
||||
# Parse "Item: Match" format
|
||||
# Example: "Smak: Lobus Insularis"
|
||||
for line in answer_lines:
|
||||
if ':' in line:
|
||||
left_part, top_part = line.split(':', 1)
|
||||
left_part = left_part.strip()
|
||||
top_part = top_part.strip()
|
||||
|
||||
# Find indices
|
||||
left_idx = None
|
||||
top_idx = None
|
||||
|
||||
for idx, item in enumerate(left_items):
|
||||
if left_part.lower() in item.lower() or item.lower() in left_part.lower():
|
||||
left_idx = idx
|
||||
break
|
||||
|
||||
for idx, item in enumerate(top_items):
|
||||
if top_part.lower() in item.lower() or item.lower() in top_part.lower():
|
||||
top_idx = idx
|
||||
break
|
||||
|
||||
if left_idx is not None and top_idx is not None:
|
||||
correct_pairs.append([left_idx, top_idx])
|
||||
|
||||
return True, {
|
||||
'text': question_text,
|
||||
'left_items': left_items,
|
||||
'top_items': top_items,
|
||||
'correct_pairs': correct_pairs,
|
||||
'has_answer': has_answer,
|
||||
'question_type': 'matching'
|
||||
}
|
||||
|
||||
|
||||
def parse_markdown_question(file_path: Path, content: str) -> Tuple[bool, dict]:
|
||||
"""
|
||||
Parse a markdown file and extract question data.
|
||||
@@ -108,6 +274,8 @@ def parse_markdown_question(file_path: Path, content: str) -> Tuple[bool, dict]:
|
||||
question_type = 'mcq'
|
||||
elif 'frågetyp/scq' in line:
|
||||
question_type = 'scq'
|
||||
elif 'frågetyp/matching' in line:
|
||||
question_type = 'matching'
|
||||
elif 'frågetyp/textalternativ' in line:
|
||||
question_type = 'textalternativ'
|
||||
elif 'frågetyp/textfält' in line:
|
||||
@@ -122,6 +290,14 @@ def parse_markdown_question(file_path: Path, content: str) -> Tuple[bool, dict]:
|
||||
# Split by comma
|
||||
tags = [t.strip() for t in tag_content.split(',') if t.strip()]
|
||||
|
||||
# If it's a matching question, use the matching parser
|
||||
if question_type == 'matching':
|
||||
is_matching, matching_data = parse_matching_question(content)
|
||||
if is_matching:
|
||||
# Add tags to the data
|
||||
matching_data['tags'] = tags if 'tags' in locals() else []
|
||||
return True, matching_data
|
||||
|
||||
|
||||
if not is_question:
|
||||
return False, {}
|
||||
@@ -375,14 +551,26 @@ def import_question_file(file_path: Path, base_path: Path, stats: ImportStats, f
|
||||
pass # If date parsing fails, exam remains None
|
||||
|
||||
# Import to database with mtime tracking
|
||||
# Prepare defaults dict
|
||||
defaults = {
|
||||
'exam': exam,
|
||||
'text': question_data['text'],
|
||||
'correct_answer': question_data.get('correct_answer', ''),
|
||||
'file_mtime': file_mtime,
|
||||
'question_type': question_data.get('question_type', 'mcq'),
|
||||
}
|
||||
|
||||
# Add matching_data if it's a matching question
|
||||
if question_data.get('question_type') == 'matching':
|
||||
defaults['matching_data'] = {
|
||||
'left_items': question_data.get('left_items', []),
|
||||
'top_items': question_data.get('top_items', []),
|
||||
'correct_pairs': question_data.get('correct_pairs', [])
|
||||
}
|
||||
|
||||
question, created = Question.objects.update_or_create(
|
||||
file_path=file_path_str,
|
||||
defaults={
|
||||
'exam': exam,
|
||||
'text': question_data['text'],
|
||||
'correct_answer': question_data['correct_answer'],
|
||||
'file_mtime': file_mtime, # Track modification time
|
||||
}
|
||||
defaults=defaults
|
||||
)
|
||||
|
||||
if created:
|
||||
@@ -403,14 +591,15 @@ def import_question_file(file_path: Path, base_path: Path, stats: ImportStats, f
|
||||
)
|
||||
question.tags.add(tag)
|
||||
|
||||
# Update options
|
||||
question.options.all().delete()
|
||||
# Deduplicate options by letter (keep first occurrence)
|
||||
seen_letters = set()
|
||||
for letter, text in question_data['options']:
|
||||
if letter not in seen_letters:
|
||||
Option.objects.create(question=question, letter=letter, text=text)
|
||||
seen_letters.add(letter)
|
||||
# Update options (only for MCQ/SCQ questions)
|
||||
if question_data.get('question_type') not in ['matching']:
|
||||
question.options.all().delete()
|
||||
# Deduplicate options by letter (keep first occurrence)
|
||||
seen_letters = set()
|
||||
for letter, text in question_data.get('options', []):
|
||||
if letter not in seen_letters:
|
||||
Option.objects.create(question=question, letter=letter, text=text)
|
||||
seen_letters.add(letter)
|
||||
|
||||
return 'imported' if created else 'updated'
|
||||
|
||||
|
||||
@@ -27,6 +27,24 @@ def handle_tag_filter(request):
|
||||
|
||||
def create_quiz(request):
|
||||
if request.method == 'POST':
|
||||
# Handle quick-start tag-based quiz
|
||||
tag_slug = request.POST.get('tag_slug')
|
||||
if tag_slug:
|
||||
from .models import Tag
|
||||
try:
|
||||
tag = Tag.objects.get(slug=tag_slug)
|
||||
course = Course.objects.first() # Get first course
|
||||
session = QuizSession.objects.create(
|
||||
user=request.quiz_user,
|
||||
course=course,
|
||||
question_types=[]
|
||||
)
|
||||
session.tags.set([tag])
|
||||
return redirect('quiz_mode', session_id=session.id)
|
||||
except Tag.DoesNotExist:
|
||||
pass
|
||||
|
||||
# Handle custom form-based quiz
|
||||
form = CreateQuizForm(request.POST)
|
||||
if form.is_valid():
|
||||
course = form.cleaned_data.get('course')
|
||||
@@ -44,7 +62,7 @@ def create_quiz(request):
|
||||
if exams:
|
||||
session.exams.set(exams)
|
||||
|
||||
return redirect('index')
|
||||
return redirect('quiz_mode', session_id=session.id)
|
||||
else:
|
||||
form = CreateQuizForm()
|
||||
|
||||
@@ -67,7 +85,11 @@ def index(request):
|
||||
def quiz_mode(request, session_id):
|
||||
"""Dedicated quiz mode view"""
|
||||
session = get_object_or_404(QuizSession, id=session_id, user=request.quiz_user, is_active=True)
|
||||
return render(request, 'quiz_mode.html', {'session': session})
|
||||
total_questions = get_session_questions(session).count()
|
||||
return render(request, 'quiz_mode.html', {
|
||||
'session': session,
|
||||
'total_questions': total_questions
|
||||
})
|
||||
|
||||
|
||||
def get_session_questions(session):
|
||||
@@ -132,6 +154,7 @@ def quiz_question(request, session_id):
|
||||
# Calculate navigation
|
||||
all_q_ids = list(all_questions.values_list('id', flat=True))
|
||||
current_index = all_q_ids.index(question.id) if question.id in all_q_ids else 0
|
||||
current_number = current_index + 1 # 1-based numbering
|
||||
|
||||
context = {
|
||||
'question': question,
|
||||
@@ -139,6 +162,8 @@ def quiz_question(request, session_id):
|
||||
'show_answer': show_answer,
|
||||
'has_previous': current_index > 0,
|
||||
'has_next': current_index < len(all_q_ids) - 1,
|
||||
'current_number': current_number,
|
||||
'total_questions': len(all_q_ids),
|
||||
}
|
||||
|
||||
if show_answer:
|
||||
@@ -187,12 +212,16 @@ def navigate_question(request, session_id, direction):
|
||||
question=question
|
||||
).first()
|
||||
|
||||
current_number = new_index + 1 # 1-based numbering
|
||||
|
||||
context = {
|
||||
'question': question,
|
||||
'session': session,
|
||||
'show_answer': result is not None,
|
||||
'has_previous': new_index > 0,
|
||||
'has_next': new_index < len(all_q_ids) - 1,
|
||||
'current_number': current_number,
|
||||
'total_questions': len(all_q_ids),
|
||||
}
|
||||
|
||||
if result:
|
||||
@@ -237,6 +266,7 @@ def submit_answer(request, session_id):
|
||||
all_questions = get_session_questions(session)
|
||||
all_q_ids = list(all_questions.values_list('id', flat=True))
|
||||
current_index = all_q_ids.index(question.id) if question.id in all_q_ids else 0
|
||||
current_number = current_index + 1 # 1-based numbering
|
||||
|
||||
context = {
|
||||
'question': question,
|
||||
@@ -245,6 +275,8 @@ def submit_answer(request, session_id):
|
||||
'is_correct': is_correct,
|
||||
'has_previous': current_index > 0,
|
||||
'has_next': current_index < len(all_q_ids) - 1,
|
||||
'current_number': current_number,
|
||||
'total_questions': len(all_q_ids),
|
||||
}
|
||||
|
||||
return render(request, 'partials/quiz_question.html', context)
|
||||
@@ -326,3 +358,15 @@ def stats(request):
|
||||
'percentage': round((correct / total * 100) if total > 0 else 0, 1),
|
||||
}
|
||||
return render(request, 'stats.html', context)
|
||||
|
||||
|
||||
def tag_count_api(request, tag_slug):
|
||||
"""API endpoint to get question count for a tag"""
|
||||
from django.http import JsonResponse
|
||||
try:
|
||||
tag = Tag.objects.get(slug=tag_slug)
|
||||
count = Question.objects.filter(tags=tag).count()
|
||||
return JsonResponse({'count': count, 'tag': tag.name})
|
||||
except Tag.DoesNotExist:
|
||||
return JsonResponse({'count': 0, 'error': 'Tag not found'}, status=404)
|
||||
|
||||
|
||||
@@ -1,90 +1,368 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block content %}
|
||||
<div class="header" style="margin-bottom: 3rem; display: flex; justify-content: space-between; align-items: center;">
|
||||
<div>
|
||||
<h1 style="font-size: 2.5rem; margin-bottom: 0.5rem;">Välkommen</h1>
|
||||
<p style="color: var(--text-muted);">Här kan du hantera dina medicinska quiz.</p>
|
||||
<style>
|
||||
.stats-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 1.5rem;
|
||||
margin-bottom: 3rem;
|
||||
}
|
||||
|
||||
.stat-card {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
padding: 2rem;
|
||||
border-radius: 1rem;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.stat-card.green {
|
||||
background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
|
||||
}
|
||||
|
||||
.stat-card.orange {
|
||||
background: linear-gradient(135deg, #ee0979 0%, #ff6a00 100%);
|
||||
}
|
||||
|
||||
.stat-value {
|
||||
font-size: 2.5rem;
|
||||
font-weight: 700;
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
font-size: 0.875rem;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.section-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
color: var(--text-main);
|
||||
}
|
||||
|
||||
.quick-start-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
|
||||
gap: 1.5rem;
|
||||
margin-bottom: 3rem;
|
||||
}
|
||||
|
||||
.quick-start-card {
|
||||
background: var(--glass-bg);
|
||||
backdrop-filter: blur(12px);
|
||||
border: 1px solid var(--glass-border);
|
||||
border-radius: 1rem;
|
||||
padding: 1.5rem;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.quick-start-card:hover {
|
||||
transform: translateY(-4px);
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
|
||||
border-color: var(--primary);
|
||||
}
|
||||
|
||||
.quick-start-card::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 4px;
|
||||
background: linear-gradient(90deg, var(--primary), #764ba2);
|
||||
}
|
||||
|
||||
.card-icon {
|
||||
font-size: 2rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
margin-bottom: 0.5rem;
|
||||
color: var(--text-main);
|
||||
}
|
||||
|
||||
.card-description {
|
||||
font-size: 0.875rem;
|
||||
color: var(--text-muted);
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.card-count {
|
||||
display: inline-block;
|
||||
background: #f0f4ff;
|
||||
color: var(--primary);
|
||||
padding: 0.25rem 0.75rem;
|
||||
border-radius: 1rem;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.active-session-card {
|
||||
background: white;
|
||||
border: 2px solid var(--primary);
|
||||
border-radius: 1rem;
|
||||
padding: 1.5rem;
|
||||
margin-bottom: 1rem;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.active-session-card:hover {
|
||||
box-shadow: 0 8px 24px rgba(99, 102, 241, 0.2);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.session-badge {
|
||||
display: inline-block;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
padding: 0.5rem 1rem;
|
||||
border-radius: 2rem;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.custom-quiz-section {
|
||||
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
|
||||
border-radius: 1rem;
|
||||
padding: 2rem;
|
||||
margin-top: 3rem;
|
||||
}
|
||||
|
||||
.filter-chips {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
flex-wrap: wrap;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
|
||||
.filter-chip {
|
||||
background: var(--primary);
|
||||
color: white;
|
||||
padding: 0.375rem 0.875rem;
|
||||
border-radius: 1rem;
|
||||
font-size: 0.875rem;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.btn-gradient {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
border: none;
|
||||
color: white;
|
||||
padding: 0.875rem 2rem;
|
||||
border-radius: 0.5rem;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s;
|
||||
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
|
||||
}
|
||||
|
||||
.btn-gradient:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
|
||||
}
|
||||
</style>
|
||||
|
||||
<!-- Stats Overview -->
|
||||
<div class="stats-grid">
|
||||
<div class="stat-card">
|
||||
<div class="stat-value">{{ total_questions }}</div>
|
||||
<div class="stat-label">Totalt frågor</div>
|
||||
</div>
|
||||
<div style="text-align: right;">
|
||||
<div style="font-weight: 600; font-size: 1.25rem;">{{ answered_count }} / {{ total_questions }}</div>
|
||||
<div style="font-size: 0.875rem; color: var(--text-muted);">Frågor besvarade</div>
|
||||
<div class="progress-container" style="width: 150px; margin-top: 0.5rem;">
|
||||
<div class="progress-bar"
|
||||
style="width: {% if total_questions > 0 %}{{ answered_count|add:0|floatformat:2 }}{% else %}0{% endif %}%">
|
||||
</div>
|
||||
</div>
|
||||
<div class="stat-card green">
|
||||
<div class="stat-value">{{ answered_count }}</div>
|
||||
<div class="stat-label">Besvarade</div>
|
||||
</div>
|
||||
<div class="stat-card orange">
|
||||
<div class="stat-value">{{ total_questions|add:answered_count|floatformat:0|add:"-" }}{{ answered_count }}</div>
|
||||
<div class="stat-label">Återstående</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2 style="margin-bottom: 1.5rem;">Aktiva Quiz</h2>
|
||||
<!-- Active Sessions -->
|
||||
{% if active_sessions %}
|
||||
<div class="grid">
|
||||
{% for session in active_sessions %}
|
||||
<div class="glass-card session-card" id="session-{{ session.id }}">
|
||||
<div class="session-header">
|
||||
<div>
|
||||
<div class="session-title">
|
||||
{% if session.course %}{{ session.course.name }}{% else %}Blandat Quiz{% endif %}
|
||||
</div>
|
||||
<div class="session-meta">
|
||||
Startat {{ session.created_at|date:"Y-m-d H:i" }}
|
||||
</div>
|
||||
<div class="section-header">
|
||||
<h2 class="section-title">🎯 Aktiva Quiz</h2>
|
||||
</div>
|
||||
|
||||
{% for session in active_sessions %}
|
||||
<div class="active-session-card">
|
||||
<div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 1rem;">
|
||||
<div>
|
||||
<span class="session-badge">
|
||||
{% if session.course %}{{ session.course.name }}{% else %}Blandat{% endif %}
|
||||
</span>
|
||||
<div style="font-size: 0.875rem; color: var(--text-muted); margin-top: 0.25rem;">
|
||||
Startat {{ session.created_at|date:"Y-m-d H:i" }}
|
||||
</div>
|
||||
<form action="{% url 'close_quiz' session.id %}" method="post" hx-post="{% url 'close_quiz' session.id %}"
|
||||
hx-target="#session-{{ session.id }}" hx-swap="outerHTML">
|
||||
{% csrf_token %}
|
||||
<button type="submit" class="btn btn-secondary"
|
||||
style="padding: 0.25rem 0.5rem; color: #ef4444;">Stäng</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{% if session.tags.exists %}
|
||||
<div style="display: flex; gap: 0.5rem; flex-wrap: wrap;">
|
||||
{% for tag in session.tags.all %}
|
||||
<span
|
||||
style="font-size: 0.75rem; background: #e0e7ff; color: #4338ca; padding: 0.25rem 0.5rem; border-radius: 1rem;">{{
|
||||
tag.name }}</span>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div style="margin-top: auto;">
|
||||
<a href="{% url 'quiz_mode' session.id %}" class="btn btn-primary" style="width: 100%; text-align: center;">
|
||||
Fortsätt Quiz
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="glass-card" style="text-align: center; color: var(--text-muted); padding: 3rem;">
|
||||
Inga aktiva quiz. Starta ett nytt nedan!
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div style="margin-top: 4rem;">
|
||||
<h2 style="margin-bottom: 1.5rem;">Starta Nytt Quiz</h2>
|
||||
<div class="glass-card">
|
||||
<form method="post" action="{% url 'create_quiz' %}">
|
||||
<form action="{% url 'close_quiz' session.id %}" method="post" hx-post="{% url 'close_quiz' session.id %}"
|
||||
hx-target=".active-session-card" hx-swap="outerHTML">
|
||||
{% csrf_token %}
|
||||
<div class="grid">
|
||||
<div class="form-group">
|
||||
<label for="{{ form.course.id_for_label }}">Kurs</label>
|
||||
{{ form.course }}
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="{{ form.tags.id_for_label }}">Taggar</label>
|
||||
{{ form.tags }}
|
||||
<small style="color: var(--text-muted); margin-top: 0.25rem; display: block;">Håll ner Ctrl/Cmd för
|
||||
att välja flera.</small>
|
||||
</div>
|
||||
</div>
|
||||
<div style="margin-top: 1rem;">
|
||||
<button type="submit" class="btn btn-primary" style="padding-left: 2rem; padding-right: 2rem;">Skapa
|
||||
Quiz</button>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-secondary" style="padding: 0.5rem 1rem; font-size: 0.875rem;">
|
||||
✕ Stäng
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{% if session.tags.exists %}
|
||||
<div class="filter-chips" style="margin-bottom: 1rem;">
|
||||
{% for tag in session.tags.all %}
|
||||
<span class="filter-chip">🏷️ {{ tag.name }}</span>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<a href="{% url 'quiz_mode' session.id %}" class="btn btn-primary" style="width: 100%; text-align: center; padding: 0.875rem;">
|
||||
▶️ Fortsätt Quiz
|
||||
</a>
|
||||
</div>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
||||
<!-- Quick Start Options -->
|
||||
<div class="section-header" style="margin-top: 3rem;">
|
||||
<h2 class="section-title">🚀 Snabbstart</h2>
|
||||
</div>
|
||||
|
||||
<div class="quick-start-grid">
|
||||
<!-- Tag-based quick starts -->
|
||||
<div class="quick-start-card" onclick="startTagQuiz('anatomi')">
|
||||
<div class="card-icon">🦴</div>
|
||||
<div class="card-title">Anatomi</div>
|
||||
<div class="card-description">Fokusera på anatomifrågor</div>
|
||||
<span class="card-count" id="tag-anatomi-count">...</span>
|
||||
</div>
|
||||
|
||||
<div class="quick-start-card" onclick="startTagQuiz('histologi')">
|
||||
<div class="card-icon">🔬</div>
|
||||
<div class="card-title">Histologi</div>
|
||||
<div class="card-description">Fokusera på histologifrågor</div>
|
||||
<span class="card-count" id="tag-histologi-count">...</span>
|
||||
</div>
|
||||
|
||||
<div class="quick-start-card" onclick="startTagQuiz('cerebrum')">
|
||||
<div class="card-icon">🧠</div>
|
||||
<div class="card-title">Cerebrum</div>
|
||||
<div class="card-description">Hjärnans frågor</div>
|
||||
<span class="card-count" id="tag-cerebrum-count">...</span>
|
||||
</div>
|
||||
|
||||
<div class="quick-start-card" onclick="startTagQuiz('oga')">
|
||||
<div class="card-icon">👁️</div>
|
||||
<div class="card-title">Öga</div>
|
||||
<div class="card-description">Ögats anatomi & histologi</div>
|
||||
<span class="card-count" id="tag-oga-count">...</span>
|
||||
</div>
|
||||
|
||||
<div class="quick-start-card" onclick="startTagQuiz('ora')">
|
||||
<div class="card-icon">👂</div>
|
||||
<div class="card-title">Öra</div>
|
||||
<div class="card-description">Örats anatomi & histologi</div>
|
||||
<span class="card-count" id="tag-ora-count">...</span>
|
||||
</div>
|
||||
|
||||
<div class="quick-start-card" onclick="startAllQuiz()">
|
||||
<div class="card-icon">🎲</div>
|
||||
<div class="card-title">Alla Frågor</div>
|
||||
<div class="card-description">Blandat från hela kursen</div>
|
||||
<span class="card-count">{{ total_questions }} frågor</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Custom Quiz Builder -->
|
||||
<div class="custom-quiz-section">
|
||||
<h2 style="margin-bottom: 1rem; color: var(--text-main);">🎨 Anpassat Quiz</h2>
|
||||
<p style="color: var(--text-muted); margin-bottom: 1.5rem;">Skapa ett quiz med dina egna filter</p>
|
||||
|
||||
<form method="post" action="{% url 'create_quiz' %}" id="custom-quiz-form">
|
||||
{% csrf_token %}
|
||||
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; margin-bottom: 1.5rem;">
|
||||
<div class="form-group">
|
||||
<label for="{{ form.course.id_for_label }}" style="font-weight: 600; margin-bottom: 0.5rem;">Kurs</label>
|
||||
{{ form.course }}
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="{{ form.tags.id_for_label }}" style="font-weight: 600; margin-bottom: 0.5rem;">Taggar</label>
|
||||
{{ form.tags }}
|
||||
</div>
|
||||
</div>
|
||||
<button type="submit" class="btn-gradient">
|
||||
✨ Skapa Anpassat Quiz
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Fetch tag counts on load
|
||||
document.addEventListener('DOMContentLoaded', async () => {
|
||||
const tags = ['anatomi', 'histologi', 'cerebrum', 'oga', 'ora'];
|
||||
|
||||
for (const tag of tags) {
|
||||
try {
|
||||
const response = await fetch(`/api/tag-count/${tag}/`);
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
const el = document.getElementById(`tag-${tag}-count`);
|
||||
if (el) el.textContent = `${data.count} frågor`;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to fetch count for', tag);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
function startTagQuiz(tagSlug) {
|
||||
const form = document.createElement('form');
|
||||
form.method = 'POST';
|
||||
form.action = '{% url "create_quiz" %}';
|
||||
|
||||
const csrf = document.createElement('input');
|
||||
csrf.type = 'hidden';
|
||||
csrf.name = 'csrfmiddlewaretoken';
|
||||
csrf.value = '{{ csrf_token }}';
|
||||
form.appendChild(csrf);
|
||||
|
||||
const tagInput = document.createElement('input');
|
||||
tagInput.type = 'hidden';
|
||||
tagInput.name = 'tag_slug';
|
||||
tagInput.value = tagSlug;
|
||||
form.appendChild(tagInput);
|
||||
|
||||
document.body.appendChild(form);
|
||||
form.submit();
|
||||
}
|
||||
|
||||
function startAllQuiz() {
|
||||
const form = document.createElement('form');
|
||||
form.method = 'POST';
|
||||
form.action = '{% url "create_quiz" %}';
|
||||
|
||||
const csrf = document.createElement('input');
|
||||
csrf.type = 'hidden';
|
||||
csrf.name = 'csrfmiddlewaretoken';
|
||||
csrf.value = '{{ csrf_token }}';
|
||||
form.appendChild(csrf);
|
||||
|
||||
document.body.appendChild(form);
|
||||
form.submit();
|
||||
}
|
||||
</script>
|
||||
{% endblock %}
|
||||
207
quiz/templates/partials/matching_question.html
Normal file
207
quiz/templates/partials/matching_question.html
Normal file
@@ -0,0 +1,207 @@
|
||||
{% csrf_token %}
|
||||
<input type="hidden" id="current-question-id" value="{{ question.id }}">
|
||||
<input type="hidden" id="current-question-number" value="{{ current_number }}">
|
||||
|
||||
<div class="question-text">{{ question.text }}</div>
|
||||
|
||||
<style>
|
||||
.matching-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin: 2rem 0;
|
||||
}
|
||||
|
||||
.matching-table th,
|
||||
.matching-table td {
|
||||
border: 2px solid var(--border);
|
||||
padding: 1rem;
|
||||
text-align: center;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.matching-table .corner-cell {
|
||||
background: #f8f9fb;
|
||||
border: none;
|
||||
}
|
||||
|
||||
.matching-table th.rotated-header {
|
||||
background: #f8f9fb;
|
||||
font-weight: 600;
|
||||
color: var(--text-main);
|
||||
height: 150px;
|
||||
white-space: nowrap;
|
||||
vertical-align: bottom;
|
||||
padding: 0.5rem;
|
||||
}
|
||||
|
||||
.matching-table th.rotated-header>div {
|
||||
transform: rotate(-45deg);
|
||||
transform-origin: bottom left;
|
||||
width: 30px;
|
||||
position: relative;
|
||||
left: 15px;
|
||||
bottom: 10px;
|
||||
}
|
||||
|
||||
.matching-table .left-item {
|
||||
text-align: left;
|
||||
font-weight: 500;
|
||||
background: #f8f9fb;
|
||||
min-width: 200px;
|
||||
}
|
||||
|
||||
.matching-table .radio-cell {
|
||||
width: 60px;
|
||||
background: white;
|
||||
}
|
||||
|
||||
.matching-table .diagonal-block {
|
||||
background: #e5e7eb;
|
||||
color: #9ca3af;
|
||||
font-size: 1.5rem;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.matching-table input[type="radio"] {
|
||||
width: 1.25rem;
|
||||
height: 1.25rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.matching-table input[type="radio"]:checked {
|
||||
accent-color: var(--primary);
|
||||
}
|
||||
|
||||
.top-items-legend {
|
||||
background: #f0f4ff;
|
||||
border: 2px solid var(--primary);
|
||||
border-radius: 0.75rem;
|
||||
padding: 1.5rem;
|
||||
margin-top: 1.5rem;
|
||||
}
|
||||
|
||||
.top-items-legend h4 {
|
||||
margin: 0 0 1rem 0;
|
||||
color: var(--primary);
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.top-item-label {
|
||||
margin: 0.5rem 0;
|
||||
padding: 0.5rem;
|
||||
background: white;
|
||||
border-radius: 0.375rem;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
</style>
|
||||
|
||||
<div class="matching-question">
|
||||
<table class="matching-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="corner-cell"></th>
|
||||
{% for top_item in question.matching_data.top_items %}
|
||||
<th class="rotated-header">
|
||||
<div>{{ forloop.counter }}. {{ top_item|truncatewords:4 }}</div>
|
||||
</th>
|
||||
{% endfor %}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for left_item in question.matching_data.left_items %}
|
||||
<tr>
|
||||
<td class="left-item">
|
||||
<strong>{{ forloop.counter }}.</strong> {{ left_item }}
|
||||
</td>
|
||||
{% for top_item in question.matching_data.top_items %}
|
||||
<td class="radio-cell">
|
||||
{% if forloop.parentloop.counter0 != forloop.counter0 %}
|
||||
<input type="radio" name="match-{{ forloop.parentloop.counter0 }}" value="{{ forloop.counter0 }}"
|
||||
data-left="{{ forloop.parentloop.counter0 }}" data-top="{{ forloop.counter0 }}"
|
||||
id="radio-{{ forloop.parentloop.counter0 }}-{{ forloop.counter0 }}">
|
||||
{% else %}
|
||||
<!-- Diagonal - no radio button -->
|
||||
<span class="diagonal-block">—</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
{% endfor %}
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<div class="top-items-legend">
|
||||
<h4>Kolumnalternativ:</h4>
|
||||
{% for top_item in question.matching_data.top_items %}
|
||||
<div class="top-item-label">
|
||||
<strong>{{ forloop.counter }}.</strong> {{ top_item }}
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
(function () {
|
||||
// Handle radio button changes
|
||||
const quizContent = document.getElementById('quiz-content');
|
||||
if (!quizContent) return;
|
||||
|
||||
quizContent.addEventListener('change', (e) => {
|
||||
if (e.target.type === 'radio' && e.target.dataset.left) {
|
||||
saveMatchingAnswer();
|
||||
}
|
||||
});
|
||||
|
||||
function saveMatchingAnswer() {
|
||||
const questionId = document.getElementById('current-question-id').value;
|
||||
const selected = [];
|
||||
|
||||
// Collect all selected radio buttons
|
||||
const radios = document.querySelectorAll('input[type="radio"]:checked[data-left]');
|
||||
radios.forEach(radio => {
|
||||
const leftIdx = parseInt(radio.dataset.left);
|
||||
const topIdx = parseInt(radio.dataset.top);
|
||||
selected.push([leftIdx, topIdx]);
|
||||
});
|
||||
|
||||
// Save to localStorage
|
||||
const sessionId = SESSION_ID;
|
||||
const key = 'quiz_' + sessionId + '_answers';
|
||||
const answers = JSON.parse(localStorage.getItem(key) || '{}');
|
||||
answers[questionId] = JSON.stringify(selected); // Store as JSON string
|
||||
localStorage.setItem(key, JSON.stringify(answers));
|
||||
|
||||
if (typeof updateQuestionPills === 'function') {
|
||||
updateQuestionPills();
|
||||
}
|
||||
}
|
||||
|
||||
function restoreMatchingAnswers() {
|
||||
const questionId = document.getElementById('current-question-id')?.value;
|
||||
if (!questionId) return;
|
||||
|
||||
const sessionId = SESSION_ID;
|
||||
const key = 'quiz_' + sessionId + '_answers';
|
||||
const answers = JSON.parse(localStorage.getItem(key) || '{}');
|
||||
const saved = answers[questionId];
|
||||
|
||||
if (saved) {
|
||||
try {
|
||||
const selected = JSON.parse(saved);
|
||||
selected.forEach(pair => {
|
||||
const [leftIdx, topIdx] = pair;
|
||||
const radio = document.getElementById('radio-' + leftIdx + '-' + topIdx);
|
||||
if (radio) {
|
||||
radio.checked = true;
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('Error restoring matching answers:', e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Restore on load
|
||||
setTimeout(restoreMatchingAnswers, 50);
|
||||
})();
|
||||
</script>
|
||||
@@ -1,27 +1,48 @@
|
||||
{% if question.question_type == 'matching' %}
|
||||
{% include 'partials/matching_question.html' %}
|
||||
{% else %}
|
||||
{# Regular MCQ/SCQ template #}
|
||||
{% csrf_token %}
|
||||
<input type="hidden" id="current-question-id" value="{{ question.id }}">
|
||||
<input type="hidden" id="current-question-number" value="{{ current_number }}">
|
||||
|
||||
<div class="question-text">{{ question.text }}</div>
|
||||
|
||||
<div class="options-container">
|
||||
{% for option in question.options.all %}
|
||||
<label class="option-item" for="checkbox-{{ option.letter }}" id="option-{{ option.letter }}">
|
||||
<div class="option-item" id="option-{{ option.letter }}" data-letter="{{ option.letter }}">
|
||||
<input type="checkbox" id="checkbox-{{ option.letter }}" value="{{ option.letter }}"
|
||||
onchange="toggleOption('{{ option.letter }}')"
|
||||
data-letter="{{ option.letter }}"
|
||||
style="margin-right: 0.5rem; width: 1.2rem; height: 1.2rem; cursor: pointer;">
|
||||
<span class="option-letter">{{ option.letter }}</span>
|
||||
<span>{{ option.text }}</span>
|
||||
</label>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
|
||||
<div class="nav-buttons">
|
||||
<button class="nav-btn" {% if not has_previous %}disabled{% endif %}
|
||||
onclick="navigateQuestion('previous', {{ session.id }})">
|
||||
← Föregående
|
||||
</button>
|
||||
<button class="nav-btn" {% if not has_next %}disabled{% endif %}
|
||||
onclick="navigateQuestion('next', {{ session.id }})">
|
||||
Nästa →
|
||||
</button>
|
||||
</div>
|
||||
<script>
|
||||
(function () {
|
||||
const container = document.querySelector('.options-container');
|
||||
|
||||
// Handle option item clicks (clicking anywhere on the div except checkbox)
|
||||
container?.addEventListener('click', (e) => {
|
||||
// If click was directly on checkbox, let it handle itself
|
||||
if (e.target.type === 'checkbox') return;
|
||||
|
||||
const optionItem = e.target.closest('.option-item');
|
||||
if (!optionItem) return;
|
||||
|
||||
const letter = optionItem.dataset.letter;
|
||||
if (letter) toggleOption(letter);
|
||||
});
|
||||
|
||||
// Handle checkbox changes (direct checkbox clicks or programmatic changes)
|
||||
container?.addEventListener('change', (e) => {
|
||||
if (e.target.type === 'checkbox') {
|
||||
const letter = e.target.dataset.letter;
|
||||
if (letter) updateSelection(letter);
|
||||
}
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
{% endif %}
|
||||
@@ -77,8 +77,9 @@
|
||||
|
||||
.nav-buttons {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
margin-top: 2rem;
|
||||
justify-content: flex-end;
|
||||
gap: 0.75rem;
|
||||
margin-top: 1.5rem;
|
||||
}
|
||||
|
||||
.nav-btn {
|
||||
@@ -100,6 +101,133 @@
|
||||
background: #cbd5e1;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.question-navigator {
|
||||
background: white;
|
||||
border-radius: 1.5rem 1.5rem 0 0;
|
||||
padding: 1.5rem;
|
||||
box-shadow: 0 -10px 40px rgba(0, 0, 0, 0.3);
|
||||
position: fixed;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.navigator-content {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.navigator-label {
|
||||
font-weight: 600;
|
||||
color: var(--text-muted);
|
||||
font-size: 0.875rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.question-pills {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
flex: 1;
|
||||
overflow-x: auto;
|
||||
padding: 0.25rem 0.5rem;
|
||||
scroll-behavior: smooth;
|
||||
/* Hide scrollbar but keep functionality */
|
||||
scrollbar-width: none; /* Firefox */
|
||||
-ms-overflow-style: none; /* IE/Edge */
|
||||
position: relative;
|
||||
max-width: calc(100vw - 400px); /* Leave space for label and buttons */
|
||||
}
|
||||
|
||||
.question-pills::-webkit-scrollbar {
|
||||
display: none; /* Chrome/Safari */
|
||||
}
|
||||
|
||||
/* Fade effect at edges */
|
||||
.question-pills::before,
|
||||
.question-pills::after {
|
||||
content: '⋯';
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
font-size: 1.5rem;
|
||||
font-weight: bold;
|
||||
color: var(--text-muted);
|
||||
pointer-events: none;
|
||||
z-index: 1;
|
||||
opacity: 0;
|
||||
transition: opacity 0.3s;
|
||||
}
|
||||
|
||||
.question-pills::before {
|
||||
left: 0;
|
||||
background: linear-gradient(to right, white 20%, transparent);
|
||||
padding-right: 1rem;
|
||||
}
|
||||
|
||||
.question-pills::after {
|
||||
right: 0;
|
||||
background: linear-gradient(to left, white 20%, transparent);
|
||||
padding-left: 1rem;
|
||||
}
|
||||
|
||||
.question-pills.show-left-ellipsis::before {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.question-pills.show-right-ellipsis::after {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.question-pill {
|
||||
min-width: 2.5rem;
|
||||
height: 2.5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 0.5rem;
|
||||
border: 2px solid var(--border);
|
||||
background: white;
|
||||
color: var(--text-main);
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
font-size: 0.875rem;
|
||||
flex-shrink: 0; /* Prevent pills from shrinking */
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.question-pill:hover {
|
||||
border-color: var(--primary);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.question-pill.active {
|
||||
background: var(--primary);
|
||||
color: white;
|
||||
border-color: var(--primary);
|
||||
}
|
||||
|
||||
.question-pill.answered {
|
||||
background: #f0f4ff;
|
||||
border-color: var(--primary);
|
||||
color: var(--primary);
|
||||
}
|
||||
|
||||
.question-pill.answered.active {
|
||||
background: var(--primary);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.navigator-buttons {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
</style>
|
||||
|
||||
<div class="quiz-mode-container">
|
||||
@@ -111,16 +239,37 @@
|
||||
<div class="quiz-card" id="quiz-content">
|
||||
<!-- Content loaded via HTMX -->
|
||||
</div>
|
||||
|
||||
<div class="question-navigator">
|
||||
<div class="navigator-content">
|
||||
<span class="navigator-label">Frågor:</span>
|
||||
<div class="question-pills" id="question-pills">
|
||||
<!-- Pills will be generated by JavaScript -->
|
||||
</div>
|
||||
<div class="navigator-buttons">
|
||||
<button class="nav-btn" id="prev-btn" data-direction="previous" data-session="{{ session.id }}">
|
||||
← Föreg
|
||||
</button>
|
||||
<button class="nav-btn" id="next-btn" data-direction="next" data-session="{{ session.id }}">
|
||||
Nästa →
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const SESSION_ID = parseInt("{{ session.id }}");
|
||||
const TOTAL_QUESTIONS = {{ total_questions|default:0 }};
|
||||
let questionIdToNumber = {}; // Maps question ID to its position number
|
||||
let questionNumberToId = {}; // Maps position number to question ID
|
||||
|
||||
function saveAnswer(questionId, selectedLetters) {
|
||||
const key = 'quiz_' + SESSION_ID + '_answers';
|
||||
const answers = JSON.parse(localStorage.getItem(key) || '{}');
|
||||
answers[questionId] = selectedLetters;
|
||||
localStorage.setItem(key, JSON.stringify(answers));
|
||||
updateQuestionPills();
|
||||
}
|
||||
|
||||
function loadAnswer(questionId) {
|
||||
@@ -129,13 +278,193 @@
|
||||
return answers[questionId] || [];
|
||||
}
|
||||
|
||||
function getAllAnswers() {
|
||||
const key = 'quiz_' + SESSION_ID + '_answers';
|
||||
return JSON.parse(localStorage.getItem(key) || '{}');
|
||||
}
|
||||
|
||||
function updateQuestionMapping() {
|
||||
// Update mapping when current question loads
|
||||
const currentQuestionId = document.getElementById('current-question-id')?.value;
|
||||
if (!currentQuestionId) return;
|
||||
|
||||
// If we don't have this question ID mapped yet, we need to map it
|
||||
// For now, we'll rely on the backend to give us all questions
|
||||
// This is a simplified approach - ideally backend would provide full question list
|
||||
}
|
||||
|
||||
function generateQuestionPills() {
|
||||
const pillsContainer = document.getElementById('question-pills');
|
||||
if (!pillsContainer) return;
|
||||
|
||||
pillsContainer.innerHTML = '';
|
||||
|
||||
for (let i = 1; i <= TOTAL_QUESTIONS; i++) {
|
||||
const pill = document.createElement('div');
|
||||
pill.className = 'question-pill';
|
||||
pill.textContent = i;
|
||||
pill.dataset.questionNumber = i;
|
||||
|
||||
pill.addEventListener('click', () => {
|
||||
// Navigate using the same previous/next system
|
||||
// Calculate direction and number of steps needed
|
||||
const currentNumber = getCurrentQuestionNumber();
|
||||
if (i > currentNumber) {
|
||||
// Click next multiple times
|
||||
navigateToQuestionNumber(i);
|
||||
} else if (i < currentNumber) {
|
||||
navigateToQuestionNumber(i);
|
||||
}
|
||||
});
|
||||
|
||||
pillsContainer.appendChild(pill);
|
||||
}
|
||||
|
||||
// Add scroll listener to show/hide ellipses
|
||||
pillsContainer.addEventListener('scroll', updateEllipsesVisibility);
|
||||
|
||||
updateQuestionPills();
|
||||
updateEllipsesVisibility();
|
||||
}
|
||||
|
||||
function updateEllipsesVisibility() {
|
||||
const container = document.getElementById('question-pills');
|
||||
if (!container) return;
|
||||
|
||||
const scrollLeft = container.scrollLeft;
|
||||
const maxScroll = container.scrollWidth - container.clientWidth;
|
||||
|
||||
// Show left ellipsis if scrolled right
|
||||
if (scrollLeft > 10) {
|
||||
container.classList.add('show-left-ellipsis');
|
||||
} else {
|
||||
container.classList.remove('show-left-ellipsis');
|
||||
}
|
||||
|
||||
// Show right ellipsis if not scrolled to end
|
||||
if (scrollLeft < maxScroll - 10) {
|
||||
container.classList.add('show-right-ellipsis');
|
||||
} else {
|
||||
container.classList.remove('show-right-ellipsis');
|
||||
}
|
||||
}
|
||||
|
||||
function scrollToActivePill() {
|
||||
const activePill = document.querySelector('.question-pill.active');
|
||||
if (!activePill) return;
|
||||
|
||||
const container = document.getElementById('question-pills');
|
||||
if (!container) return;
|
||||
|
||||
// Calculate position to center the active pill
|
||||
const pillLeft = activePill.offsetLeft;
|
||||
const pillWidth = activePill.offsetWidth;
|
||||
const containerWidth = container.clientWidth;
|
||||
|
||||
const scrollPosition = pillLeft - (containerWidth / 2) + (pillWidth / 2);
|
||||
|
||||
container.scrollTo({
|
||||
left: scrollPosition,
|
||||
behavior: 'smooth'
|
||||
});
|
||||
|
||||
// Update ellipses after scroll
|
||||
setTimeout(updateEllipsesVisibility, 300);
|
||||
}
|
||||
|
||||
function navigateToQuestionNumber(targetNumber) {
|
||||
const currentNumber = getCurrentQuestionNumber();
|
||||
const diff = targetNumber - currentNumber;
|
||||
|
||||
if (diff === 0) return;
|
||||
|
||||
const direction = diff > 0 ? 'next' : 'previous';
|
||||
const steps = Math.abs(diff);
|
||||
|
||||
// Navigate step by step
|
||||
let currentStep = 0;
|
||||
function doStep() {
|
||||
if (currentStep >= steps) {
|
||||
return;
|
||||
}
|
||||
navigateQuestion(direction, SESSION_ID);
|
||||
currentStep++;
|
||||
setTimeout(doStep, 100); // Small delay between navigations
|
||||
}
|
||||
doStep();
|
||||
}
|
||||
|
||||
function updateQuestionPills() {
|
||||
const currentQuestionId = document.getElementById('current-question-id')?.value;
|
||||
const currentQuestionNumber = getCurrentQuestionNumber();
|
||||
const answers = getAllAnswers();
|
||||
|
||||
const pills = document.querySelectorAll('.question-pill');
|
||||
pills.forEach((pill, index) => {
|
||||
const questionNum = index + 1;
|
||||
pill.classList.remove('active', 'answered');
|
||||
|
||||
// Mark current question as active
|
||||
if (questionNum === currentQuestionNumber) {
|
||||
pill.classList.add('active');
|
||||
}
|
||||
|
||||
// Mark answered questions (check if any question ID in answers)
|
||||
// Since we're tracking by question ID, check if this position has been answered
|
||||
if (currentQuestionId && answers[currentQuestionId] && answers[currentQuestionId].length > 0) {
|
||||
if (questionNum === currentQuestionNumber) {
|
||||
pill.classList.add('answered');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
updateNavigationButtons(currentQuestionNumber);
|
||||
scrollToActivePill();
|
||||
}
|
||||
|
||||
function updateNavigationButtons(currentQuestionNumber) {
|
||||
const prevBtn = document.getElementById('prev-btn');
|
||||
const nextBtn = document.getElementById('next-btn');
|
||||
|
||||
if (prevBtn) {
|
||||
prevBtn.disabled = currentQuestionNumber <= 1;
|
||||
}
|
||||
|
||||
if (nextBtn) {
|
||||
nextBtn.disabled = currentQuestionNumber >= TOTAL_QUESTIONS;
|
||||
}
|
||||
}
|
||||
|
||||
function getCurrentQuestionNumber() {
|
||||
const numberInput = document.getElementById('current-question-number');
|
||||
if (numberInput && numberInput.value) {
|
||||
return parseInt(numberInput.value);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
function navigateToQuestion(questionNumber) {
|
||||
const url = '/quiz/' + SESSION_ID + '/question/' + questionNumber + '/';
|
||||
htmx.ajax('GET', url, {
|
||||
target: '#quiz-content',
|
||||
swap: 'innerHTML'
|
||||
});
|
||||
}
|
||||
|
||||
function toggleOption(letter) {
|
||||
const checkbox = document.getElementById('checkbox-' + letter);
|
||||
if (!checkbox) return;
|
||||
|
||||
checkbox.checked = !checkbox.checked;
|
||||
updateSelection(letter);
|
||||
}
|
||||
|
||||
function updateSelection(letter) {
|
||||
const checkbox = document.getElementById('checkbox-' + letter);
|
||||
const optionDiv = document.getElementById('option-' + letter);
|
||||
|
||||
if (!checkbox || !optionDiv) return;
|
||||
|
||||
checkbox.checked = !checkbox.checked;
|
||||
|
||||
if (checkbox.checked) {
|
||||
optionDiv.style.borderColor = 'var(--primary)';
|
||||
@@ -167,6 +496,42 @@
|
||||
});
|
||||
}
|
||||
|
||||
// Event delegation for option items and checkboxes
|
||||
function setupEventListeners() {
|
||||
const quizContent = document.getElementById('quiz-content');
|
||||
|
||||
// Handle clicks on option divs
|
||||
quizContent.addEventListener('click', (e) => {
|
||||
const optionItem = e.target.closest('.option-item');
|
||||
if (!optionItem) return;
|
||||
|
||||
// Don't toggle if the click was directly on the checkbox
|
||||
if (e.target.type === 'checkbox') return;
|
||||
|
||||
const letter = optionItem.dataset.letter;
|
||||
if (letter) toggleOption(letter);
|
||||
});
|
||||
|
||||
// Handle checkbox changes
|
||||
quizContent.addEventListener('change', (e) => {
|
||||
if (e.target.type === 'checkbox' && e.target.dataset.letter) {
|
||||
updateSelection(e.target.dataset.letter);
|
||||
}
|
||||
});
|
||||
|
||||
// Handle navigation buttons
|
||||
quizContent.addEventListener('click', (e) => {
|
||||
const navBtn = e.target.closest('.nav-btn');
|
||||
if (!navBtn || navBtn.disabled) return;
|
||||
|
||||
const direction = navBtn.dataset.direction;
|
||||
const sessionId = navBtn.dataset.session;
|
||||
if (direction && sessionId) {
|
||||
navigateQuestion(direction, sessionId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function navigateQuestion(direction, sessionId) {
|
||||
const currentQInput = document.getElementById('current-question-id');
|
||||
const currentQ = currentQInput ? currentQInput.value : null;
|
||||
@@ -181,15 +546,42 @@
|
||||
|
||||
const observer = new MutationObserver(() => {
|
||||
restoreAnswers();
|
||||
updateQuestionPills();
|
||||
});
|
||||
observer.observe(document.getElementById('quiz-content'), {
|
||||
childList: true,
|
||||
subtree: true
|
||||
});
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
generateQuestionPills();
|
||||
setupEventListeners();
|
||||
|
||||
// Add event listeners for the navigator buttons
|
||||
const prevBtn = document.getElementById('prev-btn');
|
||||
const nextBtn = document.getElementById('next-btn');
|
||||
|
||||
if (prevBtn) {
|
||||
prevBtn.addEventListener('click', (e) => {
|
||||
if (!e.currentTarget.disabled) {
|
||||
navigateQuestion('previous', SESSION_ID);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (nextBtn) {
|
||||
nextBtn.addEventListener('click', (e) => {
|
||||
if (!e.currentTarget.disabled) {
|
||||
navigateQuestion('next', SESSION_ID);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
htmx.ajax('GET', '{% url 'quiz_question' session.id %}', { target: '#quiz-content' });
|
||||
setTimeout(restoreAnswers, 100);
|
||||
setTimeout(() => {
|
||||
restoreAnswers();
|
||||
updateQuestionPills();
|
||||
}, 100);
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
Reference in New Issue
Block a user