🎯 Interactive Fragments Guide
Interactive fragments make pedagogical messages engaging by allowing students to interact with content, answer questions, and receive feedback.
Fragment Types
1. Radio Buttons (radio_)
Multiple choice questions with immediate feedback.
Basic Syntax
What is 2 + 2?
- 3{:21}
- 4{:20}
- 5{:21}
{: .i-radio}
Flag System
Flag | Meaning | Visual Feedback |
---|---|---|
{:20} | ✅ Correct answer | Green highlight |
{:21} | ❌ Wrong answer | Red highlight |
No flag | 💬 Comment/hint | Italic, non-clickable |
Advanced Examples
With Multiple Correct Answers:
Which are even numbers?
- 2{:20}
- 3{:21}
- 4{:20}
- 5{:21}
- Hint: Even numbers are divisible by 2
{: .i-radio}
With Custom Styling:
Select the capital of France:
- London{:21 .text-error}
- Paris{:20 .text-success .font-bold}
- Berlin{:21 .text-error}
{: .i-radio}
With LaTeX Math:
Solve: $x^2 = 4$
- $x = 2${:21}
- $x = -2${:21}
- $x = \pm 2${:20}
- Remember: Consider both roots!
{: .i-radio}
2. Math Input (maths_)
Text input for mathematical answers with validation.
Basic Syntax
mathPCAVersion: 1
question: "Calculate: $\int_0^1 x^2 dx$"
answer: "1/3"
tolerance: 0.001
unit: ""
Features
- Accepts numeric answers
- Tolerance for approximate answers
- Optional units
- LaTeX rendering in questions
Advanced Example
3. Interactive Graphs (graph_)
Dynamic, interactive mathematical graphs.
Basic Syntax
Multiple Functions
Interactive Features
- Zoom and pan
- Trace function values
- Show coordinates on hover
- Toggle functions on/off
4. Interactive Code (codex_)
Executable code environments for programming education.
Basic Syntax
codexPCAVersion: 1
script_path: "intro/hello_world.py"
Features
- Live code execution
- Syntax highlighting
- Error feedback
- Test cases
- Hidden test validation
Example with Inline Code
codexPCAVersion: 1
language: python
starter_code: |
# Calculate the area of a circle
radius = 5
# Your code here
area =
print(f"Area: {area}")
solution: |
import math
radius = 5
area = math.pi * radius ** 2
print(f"Area: {area}")
tests:
- input: ""
expected: "Area: 78.53981633974483"
JavaScript Integration
Interactive fragments dispatch events for tracking:
// Listen for radio button answers
document.addEventListener('i-radio-answered', (e) => {
console.log('Answer:', e.detail);
// e.detail contains: {fragmentIndex, flag, isCorrect, timestamp}
});
// Listen for math input
document.addEventListener('i-maths-answered', (e) => {
console.log('Math answer:', e.detail);
// e.detail contains: {fragmentIndex, answer, isCorrect, timestamp}
});
Data Storage
Answers are stored in localStorage:
// Retrieve all answers
const answers = JSON.parse(localStorage.getItem('pm-answers')) || {};
// Clear answers
localStorage.removeItem('pm-answers');
Best Practices
For Radio Questions
- Always include a correct answer (flag 20)
- Provide hints as non-flagged items
- Use clear, unambiguous wording
- Test all options for clarity
- Consider partial credit with custom flags
For Math Input
- Set appropriate tolerance for decimal answers
- Specify units when needed
- Provide hints for complex problems
- Accept equivalent forms (e.g., 0.5 and 1/2)
For Graphs
- Choose appropriate scale for the content
- Use contrasting colors for multiple functions
- Label axes and functions clearly
- Enable grid for coordinate reading
For Code Exercises
- Provide starter code when helpful
- Include clear instructions in comments
- Test edge cases in validation
- Give helpful error messages
- Build complexity gradually
Combining Interactive Elements
Create rich learning experiences by combining fragments:
## Example: Quadratic Functions
Consider the function $f(x) = x^2 - 4x + 3$
### Visualization
```yaml
graphPCAVersion: 1
xmin: -1
xmax: 5
ymin: -2
ymax: 4
functions:
- expression: "x^2 - 4*x + 3"
color: "blue"
Question 1
Where does the function cross the x-axis?
Question 2
Find the vertex of the parabola.
Practice Code
codexPCAVersion: 1
language: python
starter_code: |
# Find the roots of f(x) = x^2 - 4x + 3
import math
# Quadratic formula: x = (-b ± √(b²-4ac)) / 2a
a = 1
b = -4
c = 3
# Calculate discriminant
discriminant =
# Calculate roots
root1 =
root2 =
print(f"Roots: {root1} and {root2}")
## Validation & Feedback
### Immediate Feedback
- Radio buttons show color changes
- Math inputs validate on submit
- Code runs with test results
### Progress Tracking
- Answers saved automatically
- Score calculation available
- Time tracking included
### Custom Validation
Create custom validators for complex scenarios:
```python
def validate_answer(student_answer, correct_answer, tolerance=0.01):
"""Custom validation logic"""
return abs(student_answer - correct_answer) <= tolerance
Accessibility
Interactive fragments support: - Keyboard navigation - Screen reader announcements - High contrast modes - Focus indicators - Error descriptions
Performance Considerations
- Lazy Loading: Interactive components load on demand
- Debouncing: Input validation is debounced
- Caching: Answers cached locally
- Optimization: Graphs render efficiently
Advanced Features
Conditional Rendering
Show/hide content based on answers:
if (userAnswer.isCorrect) {
showElement('.success-message');
} else {
showElement('.hint-message');
}
Adaptive Learning
Track performance and adjust difficulty:
const performance = calculatePerformance();
if (performance < 0.6) {
loadEasierQuestions();
} else {
loadHarderQuestions();
}
Analytics Integration
Send interaction data to analytics:
document.addEventListener('i-radio-answered', (e) => {
analytics.track('QuestionAnswered', {
type: 'radio',
correct: e.detail.isCorrect,
question: e.detail.fragmentIndex
});
});
Interactive fragments transform static content into engaging learning experiences. Combine them thoughtfully to create effective pedagogical messages.
NumberInputPCA (number_)
A versioned numeric input fragment designed for simple numeric answers with bounds, step, units, and tolerance.
Author with a YAML code block:
- Use
correct_values
to define multiple acceptable values, each with its tolerance:
Rendering
- Server parses the YAML into a number_
fragment.
- The template renders a pm-number-input
component.
- The component displays:
- a table of parameters
- a numeric input with optional unit
- a live value preview and hint
- a Check button and feedback
Styling
- The input uses the KaTeX font stack to harmonize with math content.
- Colors are theme-driven via CSS vars (--pm-ok
, --pm-err
).
Examples
- See pms/examples/number_input_example.md
for ready-to-copy snippets.
Here's a markdown example with inline LaTeX using KaTeX syntax:
Mathematical Examples
Basic Operations
The quadratic formula is $x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$ where $a \neq 0$.
Greek Letters and Symbols
Einstein's famous equation: $E = mc^2$ where $c$ is the speed of light. The area of a circle is $A = \pi r^2$ and circumference is $C = 2\pi r$.
Fractions and Superscripts
- Simple fraction: $\frac{1}{2}$
- Complex fraction: $\frac{a + b}{c - d}$
- Exponents: $x^{2n+1}$ and $e^{i\pi} + 1 = 0$
Summations and Integrals
The sum $\sum_{i=1}^{n} i = \frac{n(n+1)}{2}$ and the integral $\int_{0}^{\infty} e^{-x} dx = 1$.
Sets and Logic
- Set notation: $A \cup B$, $A \cap B$, $A \subseteq B$
- Logic symbols: $\forall x \in \mathbb{R}, \exists y$ such that $x < y$
Matrices (inline)
Identity matrix: $I = \begin{pmatrix} 1 & 0 \ 0 & 1 \end{pmatrix}$
Special Functions
- Trigonometry: $\sin(\theta) + \cos(\theta) = \sqrt{2}\sin(\theta + \frac{\pi}{4})$
- Logarithms: $\log_2(8) = 3$ and $\ln(e) = 1$
Accents and Decorations
Vector notation: $\vec{v} = \langle x, y, z \rangle$ and $\bar{x} = \frac{1}{n}\sum_{i=1}^{n} x_i$
This demonstrates various inline LaTeX expressions that render beautifully in markdown with KaTeX support.