Reading Comprehension
Module Architecture

Technical Overview

The Reading Comprehension module implements a modular three-layer architecture supporting 10 distinct question types aligned with HKDSE English Paper 2 standards. Built on Next.js + React + TypeScript with Redux state management and Ant Design UI components.

โš™๏ธ Orchestration Layer

QuestionPanel manages mode switching (Guide/Exam), Part navigation with locking mechanisms, checkpoint scoring via selectCurrentPartGainedScore, and forced submission logic for exam timeouts.

๐Ÿ”€ Type Router Layer

QuestionContainer implements factory pattern dynamically rendering components based on question.type. Normalizes answer data across formats via mapPointsToCorrectResult.

๐Ÿ“‹ Question Implementations

10 specialized components: Classification, DragAndDrop, MCQ, TextInput, TrueOrFalse, FillInTheBlanks, DragTheWords, InteractiveWordBuilder, ReferentMatching, TimelineMatching, TableCompletion.

10
Question Types
90
Min Exam Duration
2
Practice Modes

๐Ÿ” Redux State Architecture โ€” Detailed Breakdown

+
  • paperData โ€” raw API response (passage + questions)
  • passageData โ€” transformed UI-ready data
  • practiceData โ€” runtime answers: { practiceId, points, userAnswers }
  • examStartTime / timeRemaining โ€” timer state (EXAM_DURATION_MINUTES = 90)
  • activePaperSessionId โ€” session persistence tracking
  • passageDeconstructionDialog โ€” AI Coach UI state
  • Smart Selectors: selectCurrentPartTotalScore, selectCurrentPartGainedScore, selectContentTranslationLocale

Onboarding & Assessment
Personalization Engine

Learner Profiling

Five-State Assessment Flow

Welcome
โ†’
Questioning
โ†’
English
Assessment
โ†’
Settings
โ†’
Finish

Dynamic form rendering based on levelForm.json. Multi-select with multiSelectableMaximum enforcement. Redux state persistence via appStudentPlatformActions.setState.

Assessment Captures

  • Age group: 6-8, 9-11, 12-14, 15-17, 18+
  • English proficiency level (1-10 scale)
  • Interest topics (11 categories)
  • Learning motivation (8 categories)
  • Learning style (8 methods)
  • Academic curiosity (22 subjects)
  • Gender preferences for avatar

๐Ÿ–ฅ๏ธ Iframe Sandboxing โ€” Technical Implementation

+

The assessment is embedded via iframe: {origin}/english-assessment/form/{selectedLevel}/{selectedFormId}.html. Authentication tokens are passed as URL parameters using btoa(token) for Base64 encoding. Cross-origin communication uses window.postMessage API. The payload structure: { selectedLevelId, selectedFormId, formData }. Strict origin checking prevents XSS injection attacks.

๐ŸŽจ Mascot State Machine During Assessment

+
  • Idle: Blue shy character (Image 14) gently pulsing, encouraging hesitant learners
  • Typing: Blue reading character (Image 3) activates when users input domains
  • Validation: Crossed-arms character (Image 18) slides in on successful validation
  • Celebratory: Trophy-holding mascot on assessment completion
  • CSS custom properties persist selected mascot theme throughout session

๐Ÿ“ฑ Responsive Design โ€” Mobile Adaptation

+

useBreakpoints hook for device detection. Background image swapping: imgBubble for desktop, imgBubbleMobile for mobile. Mascot height adjusts from 220px to 200px on mobile. Text scales from 20px to 16px. Touch targets minimum 44px for young learners on tablets.

Interactive Question Types
& Assessment Design

10 Question Formats

๐Ÿ”€ Classification & Drag-Drop

  • Answer cards dragged into categorized slots
  • Visual: green border for correct, red for incorrect
  • Set-based availableAnswers preventing duplicates
  • Drag-back gesture support for correction
  • HKDSE: matching headings to paragraphs

โ˜‘๏ธ Multiple Choice (MCQ)

  • Single-select and multi-select (checkbox) modes
  • Color states: #3695E5 selected, #26A347 correct, #F26E6E incorrect
  • Immediate local validation via isCorrect calculation
  • Key prop reset for clean re-renders on new questions

๐Ÿ“ True/False/Not Given

  • Three-state logic: TRUE, FALSE, NOT GIVEN
  • Grouped format โ€” multiple items per paragraph
  • Color: green True, red False, orange Not Given
  • AI-tolerance for semantic validation

๐Ÿ”ค Fill In The Blanks

  • Text input cloze with Form.useWatch real-time validation
  • Case-insensitive matching, original casing preserved
  • Substring matching: "at an angle" accepts variations

๐ŸŽฏ Drag The Words

  • Word bank โ†’ slots within summary text
  • Collocation and grammatical fit assessment
  • Inline React fragments for seamless reading

๐Ÿงฉ Interactive Word Builder

  • Slot-machine word construction (e.g., BURN + OUT)
  • Morphological awareness training
  • Configurable button arrays with definition hints

๐Ÿ“Š Additional Question Types โ€” Referent, Timeline, Table

+
  • ReferentMatching: Anaphora resolution โ€” connecting pronouns to referents. Supports object mapping, array pairs, and index-based validation.
  • TimelineMatching: Chronological ordering with vertical/horizontal layouts and allowMultipleItemsPerStage for grouping.
  • TableCompletion: Structured data entry with fuzzy matching โ€” EXACT for precision, INCLUDES for flexibility. inputId field mapping for sparse tables.
  • All types feed into universal answer format: Record<string, { answer: any; isCorrect: boolean }>

Dual-Mode Practice System
Exam Mode vs Guide Mode

Mode Architecture

โšก Exam Mode

  • practiceMode === practiceModes.exam.value
  • 90-minute countdown (EXAM_DURATION_MS = 90 * 60 * 1000)
  • Question navigation locks โ€” cannot skip ahead
  • Part group locking โ€” B1/B2 choice locked once selected
  • Forced submission via forceSubmit effect on timeout
  • Hint buttons hidden โ€” disableArticleHints = true
  • Orange accent theme throughout

๐Ÿ›ก๏ธ Guide Mode

  • practiceMode === practiceModes.guide.value
  • No timer โ€” students practice at their own pace
  • AI Coach enabled โ€” hint buttons visible
  • Free Part navigation โ€” allowPartGroupSwitch = true
  • Immediate feedback on submission
  • Skip button available for difficult questions
  • Green accent theme throughout
CapsuleSelect
โ‡„
Mode Switch
โ†’
QuestionPanel
โ†’
QuestionContainer
โ†’
Rendered Question

๐ŸŽฏ ModeSelectionDialog โ€” Activity Logging & Time Calculation

+
  • reportActivityLog calls on every interaction: modeSelectionExam, modeSelectionGuide, modeSelectionExit
  • Dynamic time: totalTimeOptions aggregates timeSec across passage structure
  • Exam card: yellow/amber theme with clock icon, warning about disabled hints
  • Guide card: green theme with lightbulb icon, encouraging text about AI support
  • Structure and Timing info cards below mode selection
  • Focus trapping in modal โ€” close on Escape key

๐Ÿ“‹ ExamInstructions โ€” Dynamic Briefing Generation

+

getPartsForInstructions(passageData) traverses passage structure to identify parts and partGroups. Time aggregation sums timeSec across parts. QuestionTypeClassifier maps types to instructional text: MCQ โ†’ "Select the best answer", TextInput โ†’ "Write your answer", TFNG โ†’ "Indicate TRUE, FALSE, or NOT GIVEN". Collapsible via examInstructionsCollapsed Redux state.

Reading Interface &
Passage Navigation

Accessibility First

๐Ÿ“– PassageContent โ€” Three-Level Parsing

  • Paragraph Level: Numeric IDs (id="p{n}"), hint buttons
  • Sentence Level: splitIntoSentences() for hover-enabled analysis
  • Token Level: splitIntoTokens() for clickable words
  • Performance: React.memo, useMemo, event delegation
  • Vocabulary acquisition: word click โ†’ Redux action โ†’ AI analysis โ†’ collection

๐ŸŽจ Typography & Pagination Controls

  • Font size options: small / medium / large
  • fontSizeOptions constants with immediate visual feedback
  • Pagination: paragraphsPerPage dynamic calculation
  • Sliding window algorithm (max 5 visible dots)
  • Toggle between paginated and full-article views
  • Accessibility: aria-label attributes, keyboard navigation

๐Ÿ”— Paragraph Referencing System

+

Automatic calculation of which paragraphs each question references. Display format: "Refer to paragraphs 2-4". parseParagraphId(element: HTMLElement): number extracts paragraph number from element IDs. Checkpoint branding displays question numbers as gamified checkpoints. getActualPart(passageData, partId) retrieves current part data. getQuestionsForPart(part) counts questions within each part.

โ™ฟ Accessibility & Keyboard Support

+
  • ARIA support: aria-label on interactive elements
  • Keyboard navigation: onKeyDown handlers for Enter/Space keys
  • Focus states: outline: 3px solid var(--acc)
  • Screen reader compatibility with semantic HTML
  • Reduced motion: @media (prefers-reduced-motion) support
  • WCAG 2.1 AA color contrast compliance

๐Ÿ“ DOM Element Parsing Utilities

+

parseParagraphId(element) extracts paragraph number from element or closest parent with ID pattern p{n}. splitIntoSentences(text) uses regex for sentence boundary detection. splitIntoTokens(text) returns { type: 'word' | 'punct' | 'space', value: string }[]. All parsing is memoized to prevent unnecessary recalculation.

AI Coach & Text
Deconstruction Engine

Intelligent Coaching

๐Ÿค– PassageDeconstructionDialog

Multi-modal hint system providing just-in-time scaffolding. Opens on word/paragraph click via setPassageDeconstructionDialog Redux action.

Word
Sentence
Paragraph
Common

๐Ÿ“š Five Knowledge Domains

  • ๐ŸŽฌ Visuals & Clips โ€” multimedia integration
  • ๐Ÿ“– Grammar & Sentence Structure โ€” syntactic analysis
  • ๐ŸŽฏ DSE Strategy & Exam Tips โ€” test-taking heuristics
  • ๐Ÿ”„ Similar Questions & Practice โ€” transfer learning
  • ๐Ÿ“ Vocabulary Deep Dive โ€” semantic analysis

๐ŸŒ Internationalization & Content Delivery

+

getI18nValue(content: MapObject, locale: string) handles multilingual AI responses. Fallback chain: contentTranslationLocale โ†’ zh-HK โ†’ zh-CN โ†’ en. API via useCallGetArticleHint() hook with { hintType, paragraphId, selectedText, locale } parameters. Loading state uses Spin component with size="large". Error handling shows retry button.

๐Ÿ’ฌ MentorFeedback โ€” Multi-Dimensional Parsing

+
  • Handles 7+ question types: MCQ, TextInput, TrueOrFalse, TableCompletion, FillInTheBlanks, DragTheWords, DragAndDrop
  • Two-tier proficiency: PROFICIENT (green) vs EMERGING (red)
  • ReactMarkdown rendering for rich feedback formatting
  • Review mode: marks unanswered questions as "EMERGING" with encouragement

๐Ÿ“Š PartResultDialog โ€” Performance Analytics

+
  • Thresholds: SCORE_RATIO_EXCELLENT = 0.7, SCORE_RATIO_POOR = 0.4
  • Three themes: success (green), progress (blue), keepGoing (orange)
  • Recursive analysis for TableCompletion rows/cells and DragAndDrop groups
  • IconResultMastery (trophy), IconResultProgress (rocket), IconResultFoundation (target)
  • Next steps via areAllTopLevelPartsCompleted()

Activity Logging &
Learning Analytics

Data-Driven Teaching

๐Ÿ“– Reading Behavior

  • fontSizeChange โ€” struggling with text density
  • pageSelect โ€” reading speed patterns
  • paragraphsPerPage โ€” comprehension confidence

โœ๏ธ Attempt Patterns

  • questionSubmit โ€” submission frequency
  • questionFooterNext โ€” progression flow
  • questionFooterSkip โ€” AI Coach avoidance

๐Ÿ†˜ Help-Seeking

  • hintButton โ€” engagement signals
  • Guide Mode usage metrics
  • Correlation with performance data
ReadingLog
โ†’
AttemptLog
โ†’
HelpLog
โ†’
reportActivityLog
โ†’
Teacher Dashboard
โ†’
Heatmap + Feedback

๐Ÿ“‹ Activity Log Structure โ€” Complete Specification

+

reportActivityLog({ module: 'readingComprehension.practice', entity: { paperId, partId, questionId, hintType }, action: 'click', element: 'modeSelectionExam' })

Enriched with timestamp, sessionId, userId. Sent to /api/activity-log endpoint via POST. Supports adaptive recommendations based on hint usage frequency, time per paragraph, and feedback expansion patterns.

๐Ÿ”— Entity Relationship & Contextual Error Analysis

+

Each log includes paperId, partId, userPartId, and questionId. This enables contextual error analysis: which specific question types, paragraphs, or difficulty levels trigger the most help-seeking behavior. Privacy: anonymized before storage, opt-out available, aggregated for teacher dashboards.

Scoring Algorithms &
Assessment Engine

Intelligent Evaluation

๐Ÿงฎ Partial Credit System

scoreRatio = correctCount / totalItems

Returns ApiAnswerResult.PartialCorrect when 0 < correctCount < totalItems.

Example: 5-item T/F question, 3 correct โ†’ 60% โ†’ PartialCorrect

๐ŸŽฏ MATCH_TYPES Enum

  • EXACT: Case-insensitive, trimmed string matching for proper nouns and technical terms
  • INCLUDES: Substring matching accommodating syntactic variations while ensuring semantic correctness
  • "at an angle" accepts "taken at an angle" or "photographed at an angle"
  • Both input and correct answers normalized to lowercase for comparison

๐Ÿค– AI Evaluation Pipeline โ€” TextInput Specifics

+
  • Context retrieval via getArticleForPart
  • Prompt engineering with system prompt as "experienced English teacher"
  • Semantic grading returns only "true" or "false" โ€” prevents hallucination
  • Evaluates meaning, not just keywords โ€” handles spelling variations and paraphrasing
  • Two-phase submission: Submit โ†’ Get Feedback with useCallGetQuestionFeedback API hook
  • MapObject feedback data for i18n localization via contentTranslationLocale

๐Ÿ“ Universal Answer Format โ€” Cross-Question Analytics

+

All question types normalize to Record<string, { answer: any; isCorrect: boolean }>. This enables: AI evaluation pipeline for semantic correctness, cross-question analytics identifying struggling types, Vocabulary Trainer interventions based on specific weaknesses, and Dashboard progress tracking with granular metrics.

Gamification &
Achievement System

Motivation Design

๐Ÿ† Mastery (โ‰ฅ70%)

๐Ÿ†

IconResultMastery

Gold trophy icon. Applied when scoreRatio โ‰ฅ SCORE_RATIO_EXCELLENT. Shows in PartResultDialog success theme.

๐Ÿš€ Progress (40-70%)

๐Ÿš€

IconResultProgress

Blue rocket icon. Applied when SCORE_RATIO_POOR โ‰ค scoreRatio < SCORE_RATIO_EXCELLENT. Progress theme.

๐ŸŽฏ Keep Going (<40%)

๐ŸŽฏ

IconResultFoundation

Orange target icon. Applied when scoreRatio < SCORE_RATIO_POOR. Encouraging message, not failure.

๐Ÿ“Š Progress Visualization & Session Persistence

+
  • Ant Design Progress component with custom gradient: #1296db โ†’ #81e8ff โ†’ #58d2ad
  • Clearance levels: Level 1 (0 pts) through Level 10 (Mastery)
  • activePaperSessionId enables session resumption on browser close
  • AnswerStatus enum: NotStarted, InProgress, Completed
  • Checkpoint terminology: "Checkpoint 3 of 5" for localized progress framing

๐Ÿ”— Connection to Course Adventure & Vocabulary Builder

+

Assessment results propagate to all modules: Vocabulary System determines word list difficulty, Course Adventure routing uses recommendedLevel for entry points, Conversation Role Play calibrates scenario difficulty, Reading Comprehension determines Guided vs Exam mode. Pre-authentication personalization reads localStorage for session continuity โ€” blue detective theme from previous sessions.

The Complete Learning Loop
Listen โ†’ Capture โ†’ Review โ†’ Master

Integrated Ecosystem

๐Ÿ”„ The Four Phases

Listen/Read: PassageContent with pagination, typography controls, paragraph referencing

Capture: 10 question types โ€” Classification, MCQ, TextInput, TrueOrFalse, FillInTheBlanks, DragTheWords, InteractiveWordBuilder, ReferentMatching, TimelineMatching, TableCompletion

Review: Immediate feedback with color-coded answers, PartResultDialog analytics, MentorFeedback AI analysis

Master: Activity logging โ†’ Dashboard โ†’ Vocabulary Builder โ†’ Course Adventure progression

๐Ÿ“Š Platform Integration

  • Vocabulary Pipeline: word click โ†’ AI analysis โ†’ collection โ†’ flashcard
  • Assessment Loop: questionnaire โ†’ profiling โ†’ personalized content
  • Practice Pathway: mode selection โ†’ instructions โ†’ passage โ†’ feedback
  • Feedback Cycle: results โ†’ recommendations โ†’ adaptive content
  • Live Translation integration for multilingual classrooms
  • AI Coach emotional state management for learner support
Read
โ†’
Interact
โ†’
Feedback
โ†’
Progress
โ†’
Personalize

๐Ÿ› ๏ธ Technical Architecture Summary

+
  • Styling: Hybrid SCSS Modules + Tailwind CSS with @apply directives, responsive via useBreakpoints
  • State: Redux slice with memoized selectors, domain-driven architecture
  • i18n: next-i18next with zh-HK / zh-CN / en locale support
  • Performance: React.memo, useMemo, event delegation, code-splitting
  • Logging: reportActivityLog capturing reading behavior, attempt patterns, help-seeking
  • Security: iframe sandboxing, Base64 token encoding, postMessage validation

Same Codebase โ†’ Dual Pedagogical Experiences โ†’ Maximum Platform Value

From onboarding through assessment through practice to mastery โ€” one integrated system.

Speaker Notes

โ† โ†’ Navigate ยท N Notes ยท A Accordions ยท Esc Close