feat: add comprehensive tutorial system with editor and player

Added complete tutorial system including:
- TutorialEditor component with form-based step editing and validation
- Tutorial type definitions and validation system
- Tutorial data converter utility for existing content
- Access control hooks for development features
- Storybook integration and configuration
- Tutorial editor page routing

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Thomas Hallock
2025-09-20 17:52:28 -05:00
parent 4ef6ac5f16
commit 579caf1a26
41 changed files with 5189 additions and 0 deletions

View File

@@ -0,0 +1,48 @@
import type { StorybookConfig } from '@storybook/nextjs';
import { join, dirname } from "path"
/**
* This function is used to resolve the absolute path of a package.
* It is needed in projects that use Yarn PnP or are set up within a monorepo.
*/
function getAbsolutePath(value: string): any {
return dirname(require.resolve(join(value, 'package.json')))
}
const config: StorybookConfig = {
"stories": [
"../src/**/*.mdx",
"../src/**/*.stories.@(js|jsx|mjs|ts|tsx)"
],
"addons": [
getAbsolutePath('@storybook/addon-docs'),
getAbsolutePath('@storybook/addon-onboarding')
],
"framework": {
"name": getAbsolutePath('@storybook/nextjs'),
"options": {
"nextConfigPath": "../next.config.js"
}
},
"staticDirs": [
"../public"
],
"typescript": {
"reactDocgen": "react-docgen-typescript"
},
"webpackFinal": async (config) => {
// Handle PandaCSS styled-system imports
if (config.resolve) {
config.resolve.alias = {
...config.resolve.alias,
// Map styled-system imports to the actual directory
'../../styled-system/css': join(__dirname, '../styled-system/css/index.mjs'),
'../../styled-system/patterns': join(__dirname, '../styled-system/patterns/index.mjs'),
'../styled-system/css': join(__dirname, '../styled-system/css/index.mjs'),
'../styled-system/patterns': join(__dirname, '../styled-system/patterns/index.mjs')
}
}
return config
}
};
export default config;

View File

@@ -0,0 +1,15 @@
import type { Preview } from '@storybook/nextjs'
import '../styled-system/styles.css'
const preview: Preview = {
parameters: {
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/i,
},
},
},
};
export default preview;

View File

@@ -0,0 +1,500 @@
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { describe, it, expect, vi, beforeEach } from 'vitest'
import TutorialEditorPage from '../page'
// Mock Next.js router
vi.mock('next/navigation', () => ({
useRouter: () => ({
push: vi.fn(),
back: vi.fn(),
forward: vi.fn(),
refresh: vi.fn(),
}),
useSearchParams: () => new URLSearchParams(),
usePathname: () => '/tutorial-editor',
}))
// Mock the AbacusReact component
vi.mock('@soroban/abacus-react', () => ({
AbacusReact: ({ value, onValueChange, callbacks }: any) => (
<div data-testid="mock-abacus">
<div data-testid="abacus-value">{value}</div>
<button
data-testid="mock-bead-0"
onClick={() => {
const newValue = value + 1
onValueChange?.(newValue)
callbacks?.onBeadClick?.({
columnIndex: 0,
beadType: 'earth',
position: 0,
active: false
})
}}
>
Mock Bead
</button>
</div>
)
}))
describe('Tutorial Editor Page Integration Tests', () => {
beforeEach(() => {
vi.clearAllMocks()
})
describe('Page Structure and Navigation', () => {
it('renders the complete tutorial editor page with all components', () => {
render(<TutorialEditorPage />)
// Check main page elements
expect(screen.getByText('Tutorial Editor & Debugger')).toBeInTheDocument()
expect(screen.getByText(/Guided Addition Tutorial/)).toBeInTheDocument()
// Check mode selector buttons
expect(screen.getByText('Editor')).toBeInTheDocument()
expect(screen.getByText('Player')).toBeInTheDocument()
expect(screen.getByText('Split')).toBeInTheDocument()
// Check options
expect(screen.getByText('Debug Info')).toBeInTheDocument()
expect(screen.getByText('Auto Save')).toBeInTheDocument()
// Check export functionality
expect(screen.getByText('Export Debug')).toBeInTheDocument()
})
it('switches between editor, player, and split modes correctly', async () => {
render(<TutorialEditorPage />)
// Default should be editor mode
expect(screen.getByText('Edit Tutorial')).toBeInTheDocument()
// Switch to player mode
fireEvent.click(screen.getByText('Player'))
await waitFor(() => {
expect(screen.queryByText('Edit Tutorial')).not.toBeInTheDocument()
expect(screen.getByTestId('mock-abacus')).toBeInTheDocument()
expect(screen.getByText(/Step 1 of/)).toBeInTheDocument()
})
// Switch to split mode
fireEvent.click(screen.getByText('Split'))
await waitFor(() => {
// Should show both editor and player
expect(screen.getByText('Edit Tutorial')).toBeInTheDocument()
expect(screen.getByTestId('mock-abacus')).toBeInTheDocument()
})
// Switch back to editor mode
fireEvent.click(screen.getByText('Editor'))
await waitFor(() => {
expect(screen.getByText('Edit Tutorial')).toBeInTheDocument()
expect(screen.queryByTestId('mock-abacus')).not.toBeInTheDocument()
})
})
it('toggles debug information display', () => {
render(<TutorialEditorPage />)
const debugInfoCheckbox = screen.getByLabelText('Debug Info')
expect(debugInfoCheckbox).toBeChecked() // Should be checked by default
// Should show validation status when debug info is enabled
expect(screen.getByText('Tutorial validation passed ✓')).toBeInTheDocument()
// Toggle debug info off
fireEvent.click(debugInfoCheckbox)
expect(debugInfoCheckbox).not.toBeChecked()
// Validation status should be hidden
expect(screen.queryByText('Tutorial validation passed ✓')).not.toBeInTheDocument()
})
it('toggles auto save option', () => {
render(<TutorialEditorPage />)
const autoSaveCheckbox = screen.getByLabelText('Auto Save')
expect(autoSaveCheckbox).not.toBeChecked() // Should be unchecked by default
fireEvent.click(autoSaveCheckbox)
expect(autoSaveCheckbox).toBeChecked()
})
})
describe('Editor Mode Functionality', () => {
it('supports complete tutorial editing workflow in editor mode', async () => {
render(<TutorialEditorPage />)
// Start in editor mode
expect(screen.getByText('Edit Tutorial')).toBeInTheDocument()
// Enter edit mode
fireEvent.click(screen.getByText('Edit Tutorial'))
await waitFor(() => {
expect(screen.getByText('Save Changes')).toBeInTheDocument()
})
// Edit tutorial metadata
const titleInput = screen.getByDisplayValue('Guided Addition Tutorial')
fireEvent.change(titleInput, { target: { value: 'Advanced Addition Tutorial' } })
// Save changes
fireEvent.click(screen.getByText('Save Changes'))
// Should show saving status
await waitFor(() => {
expect(screen.getByText('Saving...')).toBeInTheDocument()
})
// Should show saved status
await waitFor(() => {
expect(screen.getByText('Saved!')).toBeInTheDocument()
}, { timeout: 2000 })
})
it('handles validation errors and displays them appropriately', async () => {
render(<TutorialEditorPage />)
fireEvent.click(screen.getByText('Edit Tutorial'))
await waitFor(() => {
expect(screen.getByText('Save Changes')).toBeInTheDocument()
})
// Clear the title to trigger validation error
const titleInput = screen.getByDisplayValue('Guided Addition Tutorial')
fireEvent.change(titleInput, { target: { value: '' } })
// Try to save
fireEvent.click(screen.getByText('Save Changes'))
// Should show validation error
await waitFor(() => {
expect(screen.getByText(/validation error/)).toBeInTheDocument()
})
})
it('integrates preview functionality with player mode', async () => {
render(<TutorialEditorPage />)
fireEvent.click(screen.getByText('Edit Tutorial'))
await waitFor(() => {
expect(screen.getByText('Save Changes')).toBeInTheDocument()
})
// Look for preview buttons in the editor
const previewButtons = screen.getAllByText(/Preview/)
if (previewButtons.length > 0) {
fireEvent.click(previewButtons[0])
// Should switch to player mode for preview
await waitFor(() => {
expect(screen.getByTestId('mock-abacus')).toBeInTheDocument()
})
}
})
})
describe('Player Mode Functionality', () => {
it('supports interactive tutorial playthrough in player mode', async () => {
render(<TutorialEditorPage />)
// Switch to player mode
fireEvent.click(screen.getByText('Player'))
await waitFor(() => {
expect(screen.getByTestId('mock-abacus')).toBeInTheDocument()
expect(screen.getByText(/Step 1 of/)).toBeInTheDocument()
})
// Should show debug controls in player mode
expect(screen.getByText('Debug')).toBeInTheDocument()
expect(screen.getByText('Steps')).toBeInTheDocument()
// Interact with the abacus
const bead = screen.getByTestId('mock-bead-0')
fireEvent.click(bead)
// Should update abacus value
await waitFor(() => {
const abacusValue = screen.getByTestId('abacus-value')
expect(abacusValue).toHaveTextContent('1')
})
// Should show step completion feedback
await waitFor(() => {
const successMessage = screen.queryByText(/Great! You completed/)
if (successMessage) {
expect(successMessage).toBeInTheDocument()
}
})
})
it('tracks and displays debug events in player mode', async () => {
render(<TutorialEditorPage />)
// Switch to player mode
fireEvent.click(screen.getByText('Player'))
await waitFor(() => {
expect(screen.getByTestId('mock-abacus')).toBeInTheDocument()
})
// Interact with abacus to generate events
const bead = screen.getByTestId('mock-bead-0')
fireEvent.click(bead)
// Should show debug events panel at bottom
await waitFor(() => {
const debugEventsPanel = screen.queryByText('Debug Events')
if (debugEventsPanel) {
expect(debugEventsPanel).toBeInTheDocument()
}
})
})
it('supports step navigation and debugging features', async () => {
render(<TutorialEditorPage />)
fireEvent.click(screen.getByText('Player'))
await waitFor(() => {
expect(screen.getByText('Steps')).toBeInTheDocument()
})
// Open step list
fireEvent.click(screen.getByText('Steps'))
await waitFor(() => {
expect(screen.getByText('Tutorial Steps')).toBeInTheDocument()
})
// Should show step list
const stepItems = screen.getAllByText(/^\d+\./)
expect(stepItems.length).toBeGreaterThan(0)
// Test auto-advance feature
const autoAdvanceCheckbox = screen.getByLabelText('Auto-advance')
fireEvent.click(autoAdvanceCheckbox)
expect(autoAdvanceCheckbox).toBeChecked()
})
})
describe('Split Mode Functionality', () => {
it('displays both editor and player simultaneously in split mode', async () => {
render(<TutorialEditorPage />)
// Switch to split mode
fireEvent.click(screen.getByText('Split'))
await waitFor(() => {
// Should show both editor and player components
expect(screen.getByText('Edit Tutorial')).toBeInTheDocument()
expect(screen.getByTestId('mock-abacus')).toBeInTheDocument()
expect(screen.getByText(/Step 1 of/)).toBeInTheDocument()
})
// Should be able to interact with both sides
fireEvent.click(screen.getByText('Edit Tutorial'))
await waitFor(() => {
expect(screen.getByText('Save Changes')).toBeInTheDocument()
})
// Player side should still be functional
const bead = screen.getByTestId('mock-bead-0')
fireEvent.click(bead)
await waitFor(() => {
const abacusValue = screen.getByTestId('abacus-value')
expect(abacusValue).toHaveTextContent('1')
})
})
it('synchronizes changes between editor and player in split mode', async () => {
render(<TutorialEditorPage />)
fireEvent.click(screen.getByText('Split'))
await waitFor(() => {
expect(screen.getByText('Edit Tutorial')).toBeInTheDocument()
expect(screen.getByTestId('mock-abacus')).toBeInTheDocument()
})
// Edit tutorial in editor side
fireEvent.click(screen.getByText('Edit Tutorial'))
await waitFor(() => {
expect(screen.getByText('Save Changes')).toBeInTheDocument()
})
const titleInput = screen.getByDisplayValue('Guided Addition Tutorial')
fireEvent.change(titleInput, { target: { value: 'Modified Tutorial' } })
// The changes should be reflected in the tutorial state
// (This tests that both sides work with the same tutorial state)
expect(titleInput).toHaveValue('Modified Tutorial')
})
})
describe('Debug and Export Features', () => {
it('exports debug data correctly', () => {
render(<TutorialEditorPage />)
// Mock URL.createObjectURL and related methods
const mockCreateObjectURL = vi.fn(() => 'mock-url')
const mockRevokeObjectURL = vi.fn()
const mockClick = vi.fn()
global.URL.createObjectURL = mockCreateObjectURL
global.URL.revokeObjectURL = mockRevokeObjectURL
// Mock document.createElement to return a mock anchor element
const originalCreateElement = document.createElement
document.createElement = vi.fn((tagName) => {
if (tagName === 'a') {
return {
href: '',
download: '',
click: mockClick
} as any
}
return originalCreateElement.call(document, tagName)
})
// Click export button
fireEvent.click(screen.getByText('Export Debug'))
// Should create blob and trigger download
expect(mockCreateObjectURL).toHaveBeenCalled()
expect(mockClick).toHaveBeenCalled()
// Restore original methods
document.createElement = originalCreateElement
})
it('tracks events and displays them in debug panel', async () => {
render(<TutorialEditorPage />)
// Switch to player mode to generate events
fireEvent.click(screen.getByText('Player'))
await waitFor(() => {
expect(screen.getByTestId('mock-abacus')).toBeInTheDocument()
})
// Generate some events
const bead = screen.getByTestId('mock-bead-0')
fireEvent.click(bead)
fireEvent.click(bead)
// Should show debug events
await waitFor(() => {
const debugEventsPanel = screen.queryByText('Debug Events')
if (debugEventsPanel) {
expect(debugEventsPanel).toBeInTheDocument()
// Should show event entries
const eventEntries = screen.getAllByText('VALUE_CHANGED')
expect(eventEntries.length).toBeGreaterThan(0)
}
})
})
it('displays validation status correctly in debug mode', async () => {
render(<TutorialEditorPage />)
// Debug info should be enabled by default
expect(screen.getByText('Tutorial validation passed ✓')).toBeInTheDocument()
// Switch to editor and make invalid changes
fireEvent.click(screen.getByText('Edit Tutorial'))
await waitFor(() => {
expect(screen.getByText('Save Changes')).toBeInTheDocument()
})
// Clear title to trigger validation error
const titleInput = screen.getByDisplayValue('Guided Addition Tutorial')
fireEvent.change(titleInput, { target: { value: '' } })
// Try to save to trigger validation
fireEvent.click(screen.getByText('Save Changes'))
// Should show validation error status
await waitFor(() => {
expect(screen.getByText(/validation error/)).toBeInTheDocument()
})
})
})
describe('Error Handling and Edge Cases', () => {
it('handles errors gracefully and maintains application stability', async () => {
render(<TutorialEditorPage />)
// Test rapid mode switching
fireEvent.click(screen.getByText('Player'))
fireEvent.click(screen.getByText('Split'))
fireEvent.click(screen.getByText('Editor'))
await waitFor(() => {
expect(screen.getByText('Edit Tutorial')).toBeInTheDocument()
})
// Test that the application remains functional
fireEvent.click(screen.getByText('Edit Tutorial'))
await waitFor(() => {
expect(screen.getByText('Save Changes')).toBeInTheDocument()
})
})
it('preserves state when switching between modes', async () => {
render(<TutorialEditorPage />)
// Make changes in editor mode
fireEvent.click(screen.getByText('Edit Tutorial'))
await waitFor(() => {
expect(screen.getByText('Save Changes')).toBeInTheDocument()
})
const titleInput = screen.getByDisplayValue('Guided Addition Tutorial')
fireEvent.change(titleInput, { target: { value: 'Temporary Change' } })
// Switch to player mode
fireEvent.click(screen.getByText('Player'))
await waitFor(() => {
expect(screen.getByTestId('mock-abacus')).toBeInTheDocument()
})
// Switch back to editor mode
fireEvent.click(screen.getByText('Editor'))
await waitFor(() => {
expect(screen.getByText('Edit Tutorial')).toBeInTheDocument()
})
// Changes should be preserved in the component state
// (Though they're not saved until explicitly saved)
})
it('handles window resize and responsive behavior', () => {
render(<TutorialEditorPage />)
// Test that the application renders without errors
expect(screen.getByText('Tutorial Editor & Debugger')).toBeInTheDocument()
// Switch to split mode which tests layout handling
fireEvent.click(screen.getByText('Split'))
// Should render both panels
expect(screen.getByText('Edit Tutorial')).toBeInTheDocument()
expect(screen.getByTestId('mock-abacus')).toBeInTheDocument()
})
})
})

View File

@@ -0,0 +1,509 @@
'use client'
import { useState, useCallback } from 'react'
import { TutorialEditor } from '../../components/tutorial/TutorialEditor'
import { TutorialPlayer } from '../../components/tutorial/TutorialPlayer'
import { DevAccessProvider, EditorProtected } from '../../hooks/useAccessControl'
import { getTutorialForEditor, validateTutorialConversion } from '../../utils/tutorialConverter'
import { Tutorial, TutorialValidation, StepValidationError, TutorialEvent } from '../../types/tutorial'
import { css } from '../../styled-system/css'
import { hstack, vstack } from '../../styled-system/patterns'
interface EditorMode {
mode: 'editor' | 'player' | 'split'
showDebugInfo: boolean
autoSave: boolean
}
export default function TutorialEditorPage() {
const [tutorial, setTutorial] = useState<Tutorial>(() => getTutorialForEditor())
const [editorMode, setEditorMode] = useState<EditorMode>({
mode: 'editor',
showDebugInfo: true,
autoSave: false
})
const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle')
const [validationResult, setValidationResult] = useState(() => validateTutorialConversion())
const [debugEvents, setDebugEvents] = useState<TutorialEvent[]>([])
// Save tutorial (placeholder - would connect to actual backend)
const handleSave = useCallback(async (updatedTutorial: Tutorial) => {
setSaveStatus('saving')
try {
// Simulate API call
await new Promise(resolve => setTimeout(resolve, 1000))
// In real implementation, this would save to backend
console.log('Saving tutorial:', updatedTutorial)
setTutorial(updatedTutorial)
setSaveStatus('saved')
// Reset status after 2 seconds
setTimeout(() => setSaveStatus('idle'), 2000)
} catch (error) {
console.error('Failed to save tutorial:', error)
setSaveStatus('error')
}
}, [])
// Validate tutorial (enhanced validation)
const handleValidate = useCallback(async (tutorialToValidate: Tutorial): Promise<TutorialValidation> => {
const errors: StepValidationError[] = []
const warnings: StepValidationError[] = []
// Validate tutorial metadata
if (!tutorialToValidate.title.trim()) {
errors.push({
stepId: '',
field: 'title',
message: 'Tutorial title is required',
severity: 'error'
})
}
if (!tutorialToValidate.description.trim()) {
warnings.push({
stepId: '',
field: 'description',
message: 'Tutorial description is recommended',
severity: 'warning'
})
}
if (tutorialToValidate.steps.length === 0) {
errors.push({
stepId: '',
field: 'steps',
message: 'Tutorial must have at least one step',
severity: 'error'
})
}
// Validate each step
tutorialToValidate.steps.forEach((step, index) => {
// Required fields
if (!step.title.trim()) {
errors.push({
stepId: step.id,
field: 'title',
message: `Step ${index + 1}: Title is required`,
severity: 'error'
})
}
if (!step.problem.trim()) {
errors.push({
stepId: step.id,
field: 'problem',
message: `Step ${index + 1}: Problem is required`,
severity: 'error'
})
}
if (!step.description.trim()) {
warnings.push({
stepId: step.id,
field: 'description',
message: `Step ${index + 1}: Description is recommended`,
severity: 'warning'
})
}
// Value validation
if (step.startValue < 0 || step.targetValue < 0) {
errors.push({
stepId: step.id,
field: 'values',
message: `Step ${index + 1}: Values cannot be negative`,
severity: 'error'
})
}
if (step.startValue === step.targetValue) {
warnings.push({
stepId: step.id,
field: 'values',
message: `Step ${index + 1}: Start and target values are the same`,
severity: 'warning'
})
}
// Highlight beads validation
if (step.highlightBeads) {
step.highlightBeads.forEach((highlight, bIndex) => {
if (highlight.columnIndex < 0 || highlight.columnIndex > 4) {
errors.push({
stepId: step.id,
field: 'highlightBeads',
message: `Step ${index + 1}: Highlight bead ${bIndex + 1} has invalid column index`,
severity: 'error'
})
}
if (highlight.beadType === 'earth' && highlight.position !== undefined) {
if (highlight.position < 0 || highlight.position > 3) {
errors.push({
stepId: step.id,
field: 'highlightBeads',
message: `Step ${index + 1}: Earth bead position must be 0-3`,
severity: 'error'
})
}
}
})
}
// Multi-step validation
if (step.expectedAction === 'multi-step') {
if (!step.multiStepInstructions || step.multiStepInstructions.length === 0) {
errors.push({
stepId: step.id,
field: 'multiStepInstructions',
message: `Step ${index + 1}: Multi-step actions require instructions`,
severity: 'error'
})
}
}
// Tooltip validation
if (!step.tooltip.content.trim() || !step.tooltip.explanation.trim()) {
warnings.push({
stepId: step.id,
field: 'tooltip',
message: `Step ${index + 1}: Tooltip content should be complete`,
severity: 'warning'
})
}
// Error messages validation
if (!step.errorMessages.wrongBead.trim() || !step.errorMessages.wrongAction.trim() || !step.errorMessages.hint.trim()) {
warnings.push({
stepId: step.id,
field: 'errorMessages',
message: `Step ${index + 1}: All error messages should be provided`,
severity: 'warning'
})
}
})
const validation: TutorialValidation = {
isValid: errors.length === 0,
errors,
warnings
}
setValidationResult(validation)
return validation
}, [])
// Preview step in player mode
const handlePreview = useCallback((tutorialToPreview: Tutorial, stepIndex: number) => {
setTutorial(tutorialToPreview)
setEditorMode(prev => ({ ...prev, mode: 'player' }))
// The TutorialPlayer will handle jumping to the specific step
}, [])
// Handle debug events from player
const handleDebugEvent = useCallback((event: TutorialEvent) => {
setDebugEvents(prev => [...prev.slice(-50), event]) // Keep last 50 events
}, [])
// Mode switching
const switchMode = useCallback((mode: EditorMode['mode']) => {
setEditorMode(prev => ({ ...prev, mode }))
}, [])
const toggleDebugInfo = useCallback(() => {
setEditorMode(prev => ({ ...prev, showDebugInfo: !prev.showDebugInfo }))
}, [])
const toggleAutoSave = useCallback(() => {
setEditorMode(prev => ({ ...prev, autoSave: !prev.autoSave }))
}, [])
// Export tutorial data for debugging
const exportTutorialData = useCallback(() => {
const data = {
tutorial,
validation: validationResult,
debugEvents: debugEvents.slice(-20),
timestamp: new Date().toISOString()
}
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `tutorial-debug-${Date.now()}.json`
a.click()
URL.revokeObjectURL(url)
}, [tutorial, validationResult, debugEvents])
return (
<DevAccessProvider>
<EditorProtected fallback={
<div className={css({
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '100vh',
textAlign: 'center'
})}>
<div>
<h1 className={css({ fontSize: '2xl', fontWeight: 'bold', mb: 4 })}>
Access Restricted
</h1>
<p className={css({ color: 'gray.600', mb: 4 })}>
Tutorial editor requires administrative privileges.
</p>
<p className={css({ fontSize: 'sm', color: 'gray.500' })}>
In development mode, this would check your actual permissions.
</p>
</div>
</div>
}>
<div className={css({ height: '100vh', display: 'flex', flexDirection: 'column' })}>
{/* Header controls */}
<div className={css({
bg: 'white',
borderBottom: '1px solid',
borderColor: 'gray.200',
p: 4
})}>
<div className={hstack({ justifyContent: 'space-between', alignItems: 'center' })}>
<div>
<h1 className={css({ fontSize: 'xl', fontWeight: 'bold' })}>
Tutorial Editor & Debugger
</h1>
<p className={css({ fontSize: 'sm', color: 'gray.600' })}>
{tutorial.title} - {tutorial.steps.length} steps
</p>
</div>
<div className={hstack({ gap: 4 })}>
{/* Mode selector */}
<div className={hstack({ gap: 1 })}>
{(['editor', 'player', 'split'] as const).map((mode) => (
<button
key={mode}
onClick={() => switchMode(mode)}
className={css({
px: 3,
py: 1,
fontSize: 'sm',
border: '1px solid',
borderColor: editorMode.mode === mode ? 'blue.300' : 'gray.300',
borderRadius: 'md',
bg: editorMode.mode === mode ? 'blue.500' : 'white',
color: editorMode.mode === mode ? 'white' : 'gray.700',
cursor: 'pointer',
textTransform: 'capitalize',
_hover: { bg: editorMode.mode === mode ? 'blue.600' : 'gray.50' }
})}
>
{mode}
</button>
))}
</div>
{/* Options */}
<div className={hstack({ gap: 2 })}>
<label className={hstack({ gap: 1, fontSize: 'sm' })}>
<input
type="checkbox"
checked={editorMode.showDebugInfo}
onChange={toggleDebugInfo}
/>
Debug Info
</label>
<label className={hstack({ gap: 1, fontSize: 'sm' })}>
<input
type="checkbox"
checked={editorMode.autoSave}
onChange={toggleAutoSave}
/>
Auto Save
</label>
</div>
{/* Actions */}
<div className={hstack({ gap: 2 })}>
<button
onClick={exportTutorialData}
className={css({
px: 3,
py: 1,
fontSize: 'sm',
border: '1px solid',
borderColor: 'gray.300',
borderRadius: 'md',
bg: 'white',
cursor: 'pointer',
_hover: { bg: 'gray.50' }
})}
>
Export Debug
</button>
{saveStatus !== 'idle' && (
<div className={css({
px: 3,
py: 1,
fontSize: 'sm',
borderRadius: 'md',
bg: saveStatus === 'saving' ? 'blue.100' :
saveStatus === 'saved' ? 'green.100' : 'red.100',
color: saveStatus === 'saving' ? 'blue.700' :
saveStatus === 'saved' ? 'green.700' : 'red.700'
})}>
{saveStatus === 'saving' ? 'Saving...' :
saveStatus === 'saved' ? 'Saved!' : 'Error!'}
</div>
)}
</div>
</div>
</div>
{/* Validation status */}
{editorMode.showDebugInfo && validationResult && (
<div className={css({ mt: 3 })}>
{!validationResult.isValid ? (
<div className={css({
p: 2,
bg: 'red.50',
border: '1px solid',
borderColor: 'red.200',
borderRadius: 'md',
fontSize: 'sm'
})}>
<strong className={css({ color: 'red.800' })}>
{validationResult.errors.length} validation error(s)
</strong>
{validationResult.warnings.length > 0 && (
<span className={css({ color: 'yellow.700', ml: 2 })}>
and {validationResult.warnings.length} warning(s)
</span>
)}
</div>
) : validationResult.warnings.length > 0 ? (
<div className={css({
p: 2,
bg: 'yellow.50',
border: '1px solid',
borderColor: 'yellow.200',
borderRadius: 'md',
fontSize: 'sm',
color: 'yellow.700'
})}>
Tutorial is valid with {validationResult.warnings.length} warning(s)
</div>
) : (
<div className={css({
p: 2,
bg: 'green.50',
border: '1px solid',
borderColor: 'green.200',
borderRadius: 'md',
fontSize: 'sm',
color: 'green.700'
})}>
Tutorial validation passed
</div>
)}
</div>
)}
</div>
{/* Main content area */}
<div className={css({ flex: 1, display: 'flex' })}>
{editorMode.mode === 'editor' && (
<TutorialEditor
tutorial={tutorial}
onSave={handleSave}
onValidate={handleValidate}
onPreview={handlePreview}
/>
)}
{editorMode.mode === 'player' && (
<TutorialPlayer
tutorial={tutorial}
isDebugMode={true}
showDebugPanel={editorMode.showDebugInfo}
onEvent={handleDebugEvent}
onTutorialComplete={(score, timeSpent) => {
console.log('Tutorial completed:', { score, timeSpent })
}}
/>
)}
{editorMode.mode === 'split' && (
<div className={css({ display: 'flex', width: '100%' })}>
<div className={css({ width: '50%', borderRight: '1px solid', borderColor: 'gray.200' })}>
<TutorialEditor
tutorial={tutorial}
onSave={handleSave}
onValidate={handleValidate}
onPreview={handlePreview}
/>
</div>
<div className={css({ width: '50%' })}>
<TutorialPlayer
tutorial={tutorial}
isDebugMode={true}
showDebugPanel={editorMode.showDebugInfo}
onEvent={handleDebugEvent}
/>
</div>
</div>
)}
</div>
{/* Debug panel */}
{editorMode.showDebugInfo && debugEvents.length > 0 && (
<div className={css({
maxHeight: '200px',
bg: 'gray.900',
color: 'white',
p: 4,
overflowY: 'auto',
fontFamily: 'mono',
fontSize: 'xs'
})}>
<h4 className={css({ fontWeight: 'bold', mb: 2 })}>
Debug Events ({debugEvents.length})
</h4>
<div className={vstack({ gap: 1, alignItems: 'flex-start' })}>
{debugEvents.slice(-10).reverse().map((event, index) => (
<div key={index} className={css({ opacity: 1 - (index * 0.1) })}>
<span className={css({ color: 'blue.300' })}>
{event.timestamp.toLocaleTimeString()}
</span>
{' '}
<span className={css({ color: 'green.300' })}>
{event.type}
</span>
{' '}
{event.type === 'VALUE_CHANGED' && (
<span>{event.oldValue} {event.newValue}</span>
)}
{event.type === 'STEP_COMPLETED' && (
<span className={css({ color: event.success ? 'green.400' : 'red.400' })}>
{event.success ? 'SUCCESS' : 'FAILED'}
</span>
)}
{event.type === 'ERROR_OCCURRED' && (
<span className={css({ color: 'red.400' })}>{event.error}</span>
)}
</div>
))}
</div>
</div>
)}
</div>
</EditorProtected>
</DevAccessProvider>
)
}

View File

@@ -0,0 +1,60 @@
import type { Meta, StoryObj } from '@storybook/react'
import { DevAccessProvider, useEditorAccess } from '../../hooks/useAccessControl'
// Simple component that tests access control
function AccessControlDisplay() {
const access = useEditorAccess()
return (
<div style={{ padding: '20px', fontFamily: 'monospace' }}>
<h2>Access Control Test</h2>
<div>
<strong>Can Access Editor:</strong> {access.canAccessEditor ? 'Yes' : 'No'}
</div>
<div>
<strong>Can Edit Tutorials:</strong> {access.canEditTutorials ? 'Yes' : 'No'}
</div>
<div>
<strong>Can Publish:</strong> {access.canPublishTutorials ? 'Yes' : 'No'}
</div>
<div>
<strong>Can Delete:</strong> {access.canDeleteTutorials ? 'Yes' : 'No'}
</div>
{access.reason && (
<div>
<strong>Reason:</strong> {access.reason}
</div>
)}
</div>
)
}
function AccessControlWithProvider() {
return (
<DevAccessProvider>
<AccessControlDisplay />
</DevAccessProvider>
)
}
const meta: Meta<typeof AccessControlWithProvider> = {
title: 'Debug/AccessControl',
component: AccessControlWithProvider,
parameters: {
docs: {
description: {
component: 'Test the access control hook in isolation'
}
}
}
}
export default meta
type Story = StoryObj<typeof AccessControlWithProvider>
export const WithDevAccess: Story = {}
// Test without provider to see if that causes issues
export const WithoutProvider: Story = {
render: () => <AccessControlDisplay />
}

View File

@@ -0,0 +1,45 @@
import type { Meta, StoryObj } from '@storybook/react'
import { getTutorialForEditor } from '../../utils/tutorialConverter'
// Simple component that just displays tutorial data
function TutorialDataDisplay() {
const tutorial = getTutorialForEditor()
return (
<div style={{ padding: '20px', fontFamily: 'monospace' }}>
<h2>Tutorial Data Structure</h2>
<div>
<strong>Title:</strong> {tutorial.title}
</div>
<div>
<strong>Steps Count:</strong> {tutorial.steps?.length || 0}
</div>
<div>
<strong>Steps Array:</strong> {Array.isArray(tutorial.steps) ? 'Yes' : 'No'}
</div>
<details style={{ marginTop: '20px' }}>
<summary>Raw Tutorial Data</summary>
<pre style={{ background: '#f5f5f5', padding: '10px', fontSize: '12px' }}>
{JSON.stringify(tutorial, null, 2)}
</pre>
</details>
</div>
)
}
const meta: Meta<typeof TutorialDataDisplay> = {
title: 'Debug/TutorialData',
component: TutorialDataDisplay,
parameters: {
docs: {
description: {
component: 'Simple display of tutorial data to test data structure without complex components'
}
}
}
}
export default meta
type Story = StoryObj<typeof TutorialDataDisplay>
export const BasicData: Story = {}

View File

@@ -0,0 +1,694 @@
'use client'
import { useState, useCallback, useEffect } from 'react'
import { TutorialPlayer } from './TutorialPlayer'
import { css } from '../../styled-system/css'
import { stack, hstack, vstack } from '../../styled-system/patterns'
import { Tutorial, TutorialStep, TutorialValidation, StepValidationError } from '../../types/tutorial'
interface TutorialEditorProps {
tutorial: Tutorial
onSave?: (tutorial: Tutorial) => Promise<void>
onValidate?: (tutorial: Tutorial) => Promise<TutorialValidation>
onPreview?: (tutorial: Tutorial, stepIndex: number) => void
className?: string
}
interface EditorState {
isEditing: boolean
isDirty: boolean
selectedStepIndex: number | null
previewStepIndex: number | null
validation: TutorialValidation | null
isSaving: boolean
}
export function TutorialEditor({
tutorial: initialTutorial,
onSave,
onValidate,
onPreview,
className
}: TutorialEditorProps) {
const [tutorial, setTutorial] = useState<Tutorial>(initialTutorial)
const [editorState, setEditorState] = useState<EditorState>({
isEditing: false,
isDirty: false,
selectedStepIndex: null,
previewStepIndex: null,
validation: null,
isSaving: false
})
// Auto-validate when tutorial changes
useEffect(() => {
if (onValidate && editorState.isDirty) {
onValidate(tutorial).then(validation => {
setEditorState(prev => ({ ...prev, validation }))
})
}
}, [tutorial, onValidate, editorState.isDirty])
// Tutorial metadata handlers
const updateTutorialMeta = useCallback((updates: Partial<Tutorial>) => {
setTutorial(prev => ({ ...prev, ...updates, updatedAt: new Date() }))
setEditorState(prev => ({ ...prev, isDirty: true }))
}, [])
// Step management
const addStep = useCallback(() => {
const newStep: TutorialStep = {
id: `step-${Date.now()}`,
title: 'New Step',
problem: '0 + 0',
description: 'Add step description here',
startValue: 0,
targetValue: 0,
expectedAction: 'add',
actionDescription: 'Describe the action to take',
tooltip: {
content: 'Tooltip title',
explanation: 'Tooltip explanation'
},
errorMessages: {
wrongBead: 'Wrong bead error message',
wrongAction: 'Wrong action error message',
hint: 'Hint message'
}
}
setTutorial(prev => ({
...prev,
steps: [...prev.steps, newStep],
updatedAt: new Date()
}))
setEditorState(prev => ({
...prev,
isDirty: true,
selectedStepIndex: tutorial.steps.length
}))
}, [tutorial.steps.length])
const duplicateStep = useCallback((stepIndex: number) => {
const stepToDuplicate = tutorial.steps[stepIndex]
if (!stepToDuplicate) return
const duplicatedStep: TutorialStep = {
...stepToDuplicate,
id: `step-${Date.now()}`,
title: `${stepToDuplicate.title} (Copy)`
}
const newSteps = [...tutorial.steps]
newSteps.splice(stepIndex + 1, 0, duplicatedStep)
setTutorial(prev => ({
...prev,
steps: newSteps,
updatedAt: new Date()
}))
setEditorState(prev => ({
...prev,
isDirty: true,
selectedStepIndex: stepIndex + 1
}))
}, [tutorial.steps])
const deleteStep = useCallback((stepIndex: number) => {
if (tutorial.steps.length <= 1) return // Don't delete the last step
const newSteps = tutorial.steps.filter((_, index) => index !== stepIndex)
setTutorial(prev => ({
...prev,
steps: newSteps,
updatedAt: new Date()
}))
setEditorState(prev => ({
...prev,
isDirty: true,
selectedStepIndex: prev.selectedStepIndex === stepIndex ? null : prev.selectedStepIndex
}))
}, [tutorial.steps])
const moveStep = useCallback((fromIndex: number, toIndex: number) => {
if (fromIndex === toIndex) return
const newSteps = [...tutorial.steps]
const [movedStep] = newSteps.splice(fromIndex, 1)
newSteps.splice(toIndex, 0, movedStep)
setTutorial(prev => ({
...prev,
steps: newSteps,
updatedAt: new Date()
}))
setEditorState(prev => ({
...prev,
isDirty: true,
selectedStepIndex: toIndex
}))
}, [tutorial.steps])
const updateStep = useCallback((stepIndex: number, updates: Partial<TutorialStep>) => {
const newSteps = [...tutorial.steps]
newSteps[stepIndex] = { ...newSteps[stepIndex], ...updates }
setTutorial(prev => ({
...prev,
steps: newSteps,
updatedAt: new Date()
}))
setEditorState(prev => ({ ...prev, isDirty: true }))
}, [tutorial.steps])
// Editor actions
const toggleEdit = useCallback(() => {
setEditorState(prev => ({ ...prev, isEditing: !prev.isEditing }))
}, [])
const previewStep = useCallback((stepIndex: number) => {
setEditorState(prev => ({ ...prev, previewStepIndex: stepIndex }))
onPreview?.(tutorial, stepIndex)
}, [tutorial, onPreview])
const saveTutorial = useCallback(async () => {
if (!onSave) return
setEditorState(prev => ({ ...prev, isSaving: true }))
try {
await onSave(tutorial)
setEditorState(prev => ({
...prev,
isDirty: false,
isSaving: false
}))
} catch (error) {
console.error('Failed to save tutorial:', error)
setEditorState(prev => ({ ...prev, isSaving: false }))
}
}, [tutorial, onSave])
// Validation helpers
const getStepErrors = useCallback((stepIndex: number): StepValidationError[] => {
if (!editorState.validation) return []
return editorState.validation.errors.filter(error =>
error.stepId === tutorial.steps[stepIndex]?.id
)
}, [editorState.validation, tutorial.steps])
const getStepWarnings = useCallback((stepIndex: number): StepValidationError[] => {
if (!editorState.validation) return []
return editorState.validation.warnings.filter(warning =>
warning.stepId === tutorial.steps[stepIndex]?.id
)
}, [editorState.validation, tutorial.steps])
return (
<div className={css({
display: 'flex',
flexDirection: 'column',
height: '100vh',
bg: 'gray.50'
}, className)}>
{/* Header */}
<div className={css({
bg: 'white',
borderBottom: '1px solid',
borderColor: 'gray.200',
p: 4
})}>
<div className={hstack({ justifyContent: 'space-between', alignItems: 'center' })}>
<div>
<h1 className={css({ fontSize: '2xl', fontWeight: 'bold' })}>
Tutorial Editor
</h1>
<p className={css({ color: 'gray.600' })}>
{tutorial.title} {editorState.isDirty && '*'}
</p>
</div>
<div className={hstack({ gap: 2 })}>
<button
onClick={toggleEdit}
className={css({
px: 4,
py: 2,
border: '1px solid',
borderColor: 'blue.300',
borderRadius: 'md',
bg: editorState.isEditing ? 'blue.500' : 'white',
color: editorState.isEditing ? 'white' : 'blue.700',
cursor: 'pointer',
_hover: { bg: editorState.isEditing ? 'blue.600' : 'blue.50' }
})}
>
{editorState.isEditing ? 'Stop Editing' : 'Edit Tutorial'}
</button>
{editorState.isDirty && (
<button
onClick={saveTutorial}
disabled={editorState.isSaving || !editorState.validation?.isValid}
className={css({
px: 4,
py: 2,
border: '1px solid',
borderColor: 'green.300',
borderRadius: 'md',
bg: 'green.500',
color: 'white',
cursor: editorState.isSaving ? 'not-allowed' : 'pointer',
opacity: editorState.isSaving || !editorState.validation?.isValid ? 0.5 : 1,
_hover: !editorState.isSaving && editorState.validation?.isValid ? { bg: 'green.600' } : {}
})}
>
{editorState.isSaving ? 'Saving...' : 'Save Changes'}
</button>
)}
</div>
</div>
{/* Validation summary */}
{editorState.validation && (
<div className={css({ mt: 3 })}>
{!editorState.validation.isValid && (
<div className={css({
p: 3,
bg: 'red.50',
border: '1px solid',
borderColor: 'red.200',
borderRadius: 'md',
fontSize: 'sm'
})}>
<strong className={css({ color: 'red.800' })}>
{editorState.validation.errors.length} error(s) found
</strong>
{editorState.validation.warnings.length > 0 && (
<span className={css({ color: 'yellow.700', ml: 2 })}>
and {editorState.validation.warnings.length} warning(s)
</span>
)}
</div>
)}
</div>
)}
</div>
<div className={hstack({ flex: 1, gap: 0 })}>
{/* Editor sidebar */}
{editorState.isEditing && (
<div className={css({
w: '400px',
bg: 'white',
borderRight: '1px solid',
borderColor: 'gray.200',
p: 4,
overflowY: 'auto'
})}>
{/* Tutorial metadata */}
<div className={css({ mb: 6 })}>
<h3 className={css({ fontWeight: 'bold', mb: 3 })}>Tutorial Info</h3>
<div className={stack({ gap: 3 })}>
<div>
<label className={css({ fontSize: 'sm', fontWeight: 'medium', mb: 1, display: 'block' })}>
Title
</label>
<input
type="text"
value={tutorial.title}
onChange={(e) => updateTutorialMeta({ title: e.target.value })}
className={css({
w: 'full',
p: 2,
border: '1px solid',
borderColor: 'gray.300',
borderRadius: 'md',
fontSize: 'sm'
})}
/>
</div>
<div>
<label className={css({ fontSize: 'sm', fontWeight: 'medium', mb: 1, display: 'block' })}>
Description
</label>
<textarea
value={tutorial.description}
onChange={(e) => updateTutorialMeta({ description: e.target.value })}
rows={3}
className={css({
w: 'full',
p: 2,
border: '1px solid',
borderColor: 'gray.300',
borderRadius: 'md',
fontSize: 'sm',
resize: 'vertical'
})}
/>
</div>
<div className={hstack({ gap: 2 })}>
<div>
<label className={css({ fontSize: 'sm', fontWeight: 'medium', mb: 1, display: 'block' })}>
Category
</label>
<input
type="text"
value={tutorial.category}
onChange={(e) => updateTutorialMeta({ category: e.target.value })}
className={css({
w: 'full',
p: 2,
border: '1px solid',
borderColor: 'gray.300',
borderRadius: 'md',
fontSize: 'sm'
})}
/>
</div>
<div>
<label className={css({ fontSize: 'sm', fontWeight: 'medium', mb: 1, display: 'block' })}>
Difficulty
</label>
<select
value={tutorial.difficulty}
onChange={(e) => updateTutorialMeta({ difficulty: e.target.value as any })}
className={css({
w: 'full',
p: 2,
border: '1px solid',
borderColor: 'gray.300',
borderRadius: 'md',
fontSize: 'sm'
})}
>
<option value="beginner">Beginner</option>
<option value="intermediate">Intermediate</option>
<option value="advanced">Advanced</option>
</select>
</div>
</div>
<div>
<label className={css({ fontSize: 'sm', fontWeight: 'medium', mb: 1, display: 'block' })}>
Tags (comma-separated)
</label>
<input
type="text"
value={tutorial.tags.join(', ')}
onChange={(e) => updateTutorialMeta({
tags: e.target.value.split(',').map(tag => tag.trim()).filter(Boolean)
})}
className={css({
w: 'full',
p: 2,
border: '1px solid',
borderColor: 'gray.300',
borderRadius: 'md',
fontSize: 'sm'
})}
/>
</div>
</div>
</div>
{/* Steps list */}
<div>
<div className={hstack({ justifyContent: 'space-between', alignItems: 'center', mb: 3 })}>
<h3 className={css({ fontWeight: 'bold' })}>Steps ({tutorial.steps.length})</h3>
<button
onClick={addStep}
className={css({
px: 3,
py: 1,
bg: 'blue.500',
color: 'white',
borderRadius: 'md',
fontSize: 'sm',
cursor: 'pointer',
_hover: { bg: 'blue.600' }
})}
>
+ Add Step
</button>
</div>
<div className={stack({ gap: 2 })}>
{tutorial.steps.map((step, index) => {
const errors = getStepErrors(index)
const warnings = getStepWarnings(index)
const hasIssues = errors.length > 0 || warnings.length > 0
return (
<div
key={step.id}
className={css({
p: 3,
border: '1px solid',
borderColor: hasIssues ? 'red.300' :
editorState.selectedStepIndex === index ? 'blue.300' : 'gray.200',
borderRadius: 'md',
bg: editorState.selectedStepIndex === index ? 'blue.50' : 'white',
cursor: 'pointer',
_hover: { bg: editorState.selectedStepIndex === index ? 'blue.100' : 'gray.50' }
})}
onClick={() => setEditorState(prev => ({
...prev,
selectedStepIndex: prev.selectedStepIndex === index ? null : index
}))}
>
<div className={hstack({ justifyContent: 'space-between', alignItems: 'center', mb: 1 })}>
<div className={css({ fontSize: 'sm', fontWeight: 'medium' })}>
{index + 1}. {step.title}
</div>
<div className={hstack({ gap: 1 })}>
<button
onClick={(e) => {
e.stopPropagation()
previewStep(index)
}}
className={css({
px: 2,
py: 1,
fontSize: 'xs',
border: '1px solid',
borderColor: 'green.300',
borderRadius: 'sm',
bg: 'green.50',
color: 'green.700',
cursor: 'pointer',
_hover: { bg: 'green.100' }
})}
>
Preview
</button>
<button
onClick={(e) => {
e.stopPropagation()
duplicateStep(index)
}}
className={css({
px: 2,
py: 1,
fontSize: 'xs',
border: '1px solid',
borderColor: 'gray.300',
borderRadius: 'sm',
bg: 'white',
cursor: 'pointer',
_hover: { bg: 'gray.50' }
})}
>
Copy
</button>
{tutorial.steps.length > 1 && (
<button
onClick={(e) => {
e.stopPropagation()
deleteStep(index)
}}
className={css({
px: 2,
py: 1,
fontSize: 'xs',
border: '1px solid',
borderColor: 'red.300',
borderRadius: 'sm',
bg: 'red.50',
color: 'red.700',
cursor: 'pointer',
_hover: { bg: 'red.100' }
})}
>
Delete
</button>
)}
</div>
</div>
<div className={css({ fontSize: 'xs', color: 'gray.600' })}>
{step.problem}
</div>
{hasIssues && (
<div className={css({ mt: 2, fontSize: 'xs' })}>
{errors.map((error, i) => (
<div key={i} className={css({ color: 'red.600' })}>
{error.message}
</div>
))}
{warnings.map((warning, i) => (
<div key={i} className={css({ color: 'yellow.600' })}>
{warning.message}
</div>
))}
</div>
)}
{/* Step details editor */}
{editorState.selectedStepIndex === index && (
<div className={css({ mt: 3, pt: 3, borderTop: '1px solid', borderColor: 'gray.200' })}>
<div className={stack({ gap: 2 })}>
<div>
<label className={css({ fontSize: 'xs', fontWeight: 'medium', mb: 1, display: 'block' })}>
Title
</label>
<input
type="text"
value={step.title}
onChange={(e) => updateStep(index, { title: e.target.value })}
className={css({
w: 'full',
p: 2,
border: '1px solid',
borderColor: 'gray.300',
borderRadius: 'md',
fontSize: 'xs'
})}
/>
</div>
<div>
<label className={css({ fontSize: 'xs', fontWeight: 'medium', mb: 1, display: 'block' })}>
Problem
</label>
<input
type="text"
value={step.problem}
onChange={(e) => updateStep(index, { problem: e.target.value })}
className={css({
w: 'full',
p: 2,
border: '1px solid',
borderColor: 'gray.300',
borderRadius: 'md',
fontSize: 'xs'
})}
/>
</div>
<div>
<label className={css({ fontSize: 'xs', fontWeight: 'medium', mb: 1, display: 'block' })}>
Description
</label>
<textarea
value={step.description}
onChange={(e) => updateStep(index, { description: e.target.value })}
rows={2}
className={css({
w: 'full',
p: 2,
border: '1px solid',
borderColor: 'gray.300',
borderRadius: 'md',
fontSize: 'xs',
resize: 'vertical'
})}
/>
</div>
<div className={hstack({ gap: 2 })}>
<div>
<label className={css({ fontSize: 'xs', fontWeight: 'medium', mb: 1, display: 'block' })}>
Start Value
</label>
<input
type="number"
value={step.startValue}
onChange={(e) => updateStep(index, { startValue: parseInt(e.target.value) || 0 })}
className={css({
w: 'full',
p: 2,
border: '1px solid',
borderColor: 'gray.300',
borderRadius: 'md',
fontSize: 'xs'
})}
/>
</div>
<div>
<label className={css({ fontSize: 'xs', fontWeight: 'medium', mb: 1, display: 'block' })}>
Target Value
</label>
<input
type="number"
value={step.targetValue}
onChange={(e) => updateStep(index, { targetValue: parseInt(e.target.value) || 0 })}
className={css({
w: 'full',
p: 2,
border: '1px solid',
borderColor: 'gray.300',
borderRadius: 'md',
fontSize: 'xs'
})}
/>
</div>
</div>
<div>
<label className={css({ fontSize: 'xs', fontWeight: 'medium', mb: 1, display: 'block' })}>
Action Description
</label>
<textarea
value={step.actionDescription}
onChange={(e) => updateStep(index, { actionDescription: e.target.value })}
rows={2}
className={css({
w: 'full',
p: 2,
border: '1px solid',
borderColor: 'gray.300',
borderRadius: 'md',
fontSize: 'xs',
resize: 'vertical'
})}
/>
</div>
</div>
</div>
)}
</div>
)
})}
</div>
</div>
</div>
)}
{/* Main content - Tutorial Player */}
<div className={css({ flex: 1 })}>
<TutorialPlayer
tutorial={tutorial}
initialStepIndex={editorState.previewStepIndex || 0}
isDebugMode={true}
showDebugPanel={editorState.isEditing}
/>
</div>
</div>
</div>
)
}

View File

@@ -0,0 +1,170 @@
import type { Meta, StoryObj } from '@storybook/react'
import { action } from '@storybook/addon-actions'
import { TutorialPlayer } from './TutorialPlayer'
import { DevAccessProvider } from '../../hooks/useAccessControl'
import { getTutorialForEditor } from '../../utils/tutorialConverter'
const meta: Meta<typeof TutorialPlayer> = {
title: 'Tutorial/TutorialPlayer',
component: TutorialPlayer,
parameters: {
layout: 'fullscreen',
docs: {
description: {
component: `
The TutorialPlayer component provides an interactive environment for users to complete tutorial steps.
It includes navigation controls, step-by-step guidance, an interactive abacus, and optional debugging features.
## Features
- Step-by-step navigation with progress tracking
- Interactive abacus with highlighted beads
- Error handling and feedback
- Debug panel for development
- Event logging and analytics
- Auto-advance option for smoother experience
`
}
}
},
decorators: [
(Story) => (
<DevAccessProvider>
<div style={{ height: '100vh' }}>
<Story />
</div>
</DevAccessProvider>
)
],
tags: ['autodocs']
}
export default meta
type Story = StoryObj<typeof meta>
const mockTutorial = getTutorialForEditor()
export const Default: Story = {
args: {
tutorial: mockTutorial,
initialStepIndex: 0,
isDebugMode: false,
showDebugPanel: false,
onStepChange: action('step-changed'),
onStepComplete: action('step-completed'),
onTutorialComplete: action('tutorial-completed'),
onEvent: action('tutorial-event')
},
parameters: {
docs: {
description: {
story: 'Default tutorial player starting from the first step with minimal UI.'
}
}
}
}
export const WithDebugMode: Story = {
args: {
...Default.args,
isDebugMode: true,
showDebugPanel: true
},
parameters: {
docs: {
description: {
story: 'Tutorial player with debug mode enabled, showing debug panel and additional controls for development.'
}
}
}
}
export const StartingFromMiddle: Story = {
args: {
...Default.args,
initialStepIndex: 4, // Starting from heaven bead introduction
isDebugMode: true,
showDebugPanel: false
},
parameters: {
docs: {
description: {
story: 'Tutorial player starting from the middle of the tutorial (heaven bead introduction).'
}
}
}
}
export const ComplexStep: Story = {
args: {
...Default.args,
initialStepIndex: 6, // Five complement step
isDebugMode: true,
showDebugPanel: true
},
parameters: {
docs: {
description: {
story: 'Tutorial player on a complex multi-step instruction (five complements) with full debugging enabled.'
}
}
}
}
export const MinimalTutorial: Story = {
args: {
tutorial: {
...mockTutorial,
steps: mockTutorial.steps.slice(0, 3) // Only first 3 steps
},
initialStepIndex: 0,
isDebugMode: false,
showDebugPanel: false,
onStepChange: action('step-changed'),
onStepComplete: action('step-completed'),
onTutorialComplete: action('tutorial-completed'),
onEvent: action('tutorial-event')
},
parameters: {
docs: {
description: {
story: 'Minimal tutorial with only the first 3 basic addition steps for testing shorter tutorials.'
}
}
}
}
export const InteractiveDemo: Story = {
args: {
...Default.args,
isDebugMode: true,
showDebugPanel: true
},
parameters: {
docs: {
description: {
story: `
Interactive demo showing all tutorial player features:
**Try these interactions:**
1. Click on highlighted beads to progress through steps
2. Use navigation buttons to jump between steps
3. Toggle the step list sidebar to see all available steps
4. Monitor the debug panel for real-time events
5. Enable auto-advance to automatically progress after completing steps
**Features demonstrated:**
- Bead highlighting and interaction feedback
- Progress tracking and validation
- Error messages for incorrect actions
- Tooltip guidance and explanations
- Event logging and debugging
`
}
}
},
play: async ({ canvasElement }) => {
// Optional: Add play function for automated interactions in Storybook
const canvas = canvasElement
console.log('Tutorial player ready for interaction', canvas)
}
}

View File

@@ -0,0 +1,112 @@
import type { Meta, StoryObj } from '@storybook/react'
import { useState } from 'react'
import { css } from '../../styled-system/css'
import { getTutorialForEditor } from '../../utils/tutorialConverter'
// Minimal tutorial player that only shows the step info without AbacusReact
function MinimalTutorialPlayer() {
const tutorial = getTutorialForEditor()
const [currentStepIndex] = useState(0)
// Safely get current step with proper validation
const currentStep = tutorial.steps && Array.isArray(tutorial.steps) && tutorial.steps[currentStepIndex]
if (!currentStep) {
return <div>No step available</div>
}
return (
<div className={css({ p: 4, border: '1px solid gray', borderRadius: 'md' })}>
<h2>Minimal Tutorial Player</h2>
<div>
<strong>Tutorial:</strong> {tutorial.title}
</div>
<div>
<strong>Step:</strong> {currentStep.title}
</div>
<div>
<strong>Problem:</strong> {currentStep.problem}
</div>
<div>
<strong>Description:</strong> {currentStep.description}
</div>
{/* Test the problematic array operations */}
<div>
<strong>Highlight Beads:</strong> {
currentStep.highlightBeads && Array.isArray(currentStep.highlightBeads)
? `${currentStep.highlightBeads.length} beads`
: 'None'
}
</div>
{/* Test steps array */}
<div>
<strong>Total Steps:</strong> {
tutorial.steps && Array.isArray(tutorial.steps)
? tutorial.steps.length
: 'Unknown'
}
</div>
</div>
)
}
const meta: Meta<typeof MinimalTutorialPlayer> = {
title: 'Debug/MinimalTutorialPlayer',
component: MinimalTutorialPlayer,
parameters: {
docs: {
description: {
component: 'Minimal tutorial player without AbacusReact to isolate the array error'
}
}
}
}
export default meta
type Story = StoryObj<typeof MinimalTutorialPlayer>
export const WithoutAbacus: Story = {}
// Test with manually created minimal tutorial data
export const WithMinimalData: Story = {
render: () => {
const minimalTutorial = {
id: 'test',
title: 'Test Tutorial',
description: 'Test',
category: 'test',
difficulty: 'beginner' as const,
estimatedDuration: 5,
steps: [
{
id: 'step1',
title: 'Test Step',
problem: '1 + 1',
description: 'Add one',
startValue: 0,
targetValue: 1,
highlightBeads: [{ columnIndex: 0, beadType: 'earth' as const, position: 0 }],
expectedAction: 'add' as const,
actionDescription: 'Add bead',
tooltip: { content: 'Test', explanation: 'Test' },
errorMessages: { wrongBead: 'Wrong', wrongAction: 'Wrong', hint: 'Hint' }
}
],
tags: ['test'],
author: 'test'
}
const currentStep = minimalTutorial.steps[0]
return (
<div style={{ padding: '20px' }}>
<h2>Manual Minimal Data</h2>
<div>Steps: {minimalTutorial.steps.length}</div>
<div>Current Step: {currentStep.title}</div>
<div>Highlight Beads: {currentStep.highlightBeads?.length || 0}</div>
</div>
)
}
}

View File

@@ -0,0 +1,456 @@
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { TutorialEditor } from '../TutorialEditor'
import { TutorialPlayer } from '../TutorialPlayer'
import { DevAccessProvider } from '../../../hooks/useAccessControl'
import { getTutorialForEditor } from '../../../utils/tutorialConverter'
import type { Tutorial, TutorialValidation } from '../../../types/tutorial'
// Mock the AbacusReact component for integration tests
vi.mock('@soroban/abacus-react', () => ({
AbacusReact: ({ value, onValueChange, callbacks }: any) => (
<div data-testid="mock-abacus">
<div data-testid="abacus-value">{value}</div>
<button
data-testid="mock-bead-0"
onClick={() => {
onValueChange?.(value + 1)
callbacks?.onBeadClick?.({
columnIndex: 0,
beadType: 'earth',
position: 0,
active: false
})
}}
>
Mock Bead
</button>
</div>
)
}))
describe('Tutorial Editor Integration Tests', () => {
let mockTutorial: Tutorial
let mockOnSave: ReturnType<typeof vi.fn>
let mockOnValidate: ReturnType<typeof vi.fn>
let mockOnPreview: ReturnType<typeof vi.fn>
beforeEach(() => {
vi.clearAllMocks()
mockTutorial = getTutorialForEditor()
mockOnSave = vi.fn()
mockOnValidate = vi.fn().mockResolvedValue({
isValid: true,
errors: [],
warnings: []
} as TutorialValidation)
mockOnPreview = vi.fn()
})
const renderTutorialEditor = () => {
return render(
<DevAccessProvider>
<TutorialEditor
tutorial={mockTutorial}
onSave={mockOnSave}
onValidate={mockOnValidate}
onPreview={mockOnPreview}
/>
</DevAccessProvider>
)
}
describe('Complete Tutorial Editing Workflow', () => {
it('supports complete tutorial editing workflow from start to finish', async () => {
renderTutorialEditor()
// 1. Initial state - read-only mode
expect(screen.getByText('Guided Addition Tutorial')).toBeInTheDocument()
expect(screen.getByText('Edit Tutorial')).toBeInTheDocument()
expect(screen.queryByText('Save Changes')).not.toBeInTheDocument()
// 2. Enter edit mode
fireEvent.click(screen.getByText('Edit Tutorial'))
expect(screen.getByText('Save Changes')).toBeInTheDocument()
expect(screen.getByText('Cancel')).toBeInTheDocument()
// 3. Edit tutorial metadata
const titleInput = screen.getByDisplayValue('Guided Addition Tutorial')
fireEvent.change(titleInput, { target: { value: 'Advanced Addition Tutorial' } })
expect(titleInput).toHaveValue('Advanced Addition Tutorial')
const descriptionInput = screen.getByDisplayValue(/Learn basic addition/)
fireEvent.change(descriptionInput, { target: { value: 'Master advanced addition techniques' } })
expect(descriptionInput).toHaveValue('Master advanced addition techniques')
// 4. Expand and edit a step
const firstStep = screen.getByText(/1\. .+/)
fireEvent.click(firstStep)
// Find step editing form
const stepTitleInputs = screen.getAllByDisplayValue(/.*/)
const stepTitleInput = stepTitleInputs.find(input =>
(input as HTMLInputElement).value.includes('Basic') ||
(input as HTMLInputElement).value.includes('Introduction')
)
if (stepTitleInput) {
fireEvent.change(stepTitleInput, { target: { value: 'Advanced Introduction Step' } })
expect(stepTitleInput).toHaveValue('Advanced Introduction Step')
}
// 5. Add a new step
const addStepButton = screen.getByText('+ Add Step')
const initialStepCount = screen.getAllByText(/^\d+\./).length
fireEvent.click(addStepButton)
await waitFor(() => {
const newStepCount = screen.getAllByText(/^\d+\./).length
expect(newStepCount).toBe(initialStepCount + 1)
})
// 6. Preview functionality
const previewButtons = screen.getAllByText(/Preview/)
if (previewButtons.length > 0) {
fireEvent.click(previewButtons[0])
expect(mockOnPreview).toHaveBeenCalled()
}
// 7. Save changes
fireEvent.click(screen.getByText('Save Changes'))
await waitFor(() => {
expect(mockOnValidate).toHaveBeenCalled()
expect(mockOnSave).toHaveBeenCalledWith(expect.objectContaining({
title: 'Advanced Addition Tutorial',
description: 'Master advanced addition techniques'
}))
})
})
it('handles step management operations correctly', async () => {
renderTutorialEditor()
fireEvent.click(screen.getByText('Edit Tutorial'))
// Get initial step count
const initialSteps = screen.getAllByText(/^\d+\./)
const initialCount = initialSteps.length
// Add a step
fireEvent.click(screen.getByText('+ Add Step'))
await waitFor(() => {
expect(screen.getAllByText(/^\d+\./).length).toBe(initialCount + 1)
})
// Expand the first step and duplicate it
fireEvent.click(screen.getByText(/1\. .+/))
const duplicateButton = screen.queryByText('Duplicate')
if (duplicateButton) {
fireEvent.click(duplicateButton)
await waitFor(() => {
expect(screen.getAllByText(/^\d+\./).length).toBe(initialCount + 2)
})
}
// Try to delete a step (but not if it's the last one)
const deleteButton = screen.queryByText('Delete')
if (deleteButton && !deleteButton.hasAttribute('disabled')) {
const currentCount = screen.getAllByText(/^\d+\./).length
fireEvent.click(deleteButton)
await waitFor(() => {
expect(screen.getAllByText(/^\d+\./).length).toBe(currentCount - 1)
})
}
})
it('validates tutorial data before saving', async () => {
// Set up validation to fail
mockOnValidate.mockResolvedValueOnce({
isValid: false,
errors: [
{
stepId: '',
field: 'title',
message: 'Title cannot be empty',
severity: 'error' as const
}
],
warnings: []
})
renderTutorialEditor()
fireEvent.click(screen.getByText('Edit Tutorial'))
// Clear the title to trigger validation error
const titleInput = screen.getByDisplayValue('Guided Addition Tutorial')
fireEvent.change(titleInput, { target: { value: '' } })
// Try to save
fireEvent.click(screen.getByText('Save Changes'))
await waitFor(() => {
expect(mockOnValidate).toHaveBeenCalled()
expect(mockOnSave).not.toHaveBeenCalled()
expect(screen.getByText('Title cannot be empty')).toBeInTheDocument()
})
})
it('shows validation warnings without blocking save', async () => {
// Set up validation with warnings only
mockOnValidate.mockResolvedValueOnce({
isValid: true,
errors: [],
warnings: [
{
stepId: '',
field: 'description',
message: 'Description could be more detailed',
severity: 'warning' as const
}
]
})
renderTutorialEditor()
fireEvent.click(screen.getByText('Edit Tutorial'))
fireEvent.click(screen.getByText('Save Changes'))
await waitFor(() => {
expect(mockOnValidate).toHaveBeenCalled()
expect(mockOnSave).toHaveBeenCalled()
expect(screen.getByText('Description could be more detailed')).toBeInTheDocument()
})
})
})
describe('Tutorial Player Integration', () => {
const renderTutorialPlayer = () => {
return render(
<DevAccessProvider>
<TutorialPlayer
tutorial={mockTutorial}
isDebugMode={true}
showDebugPanel={true}
onStepComplete={vi.fn()}
onTutorialComplete={vi.fn()}
onEvent={vi.fn()}
/>
</DevAccessProvider>
)
}
it('integrates tutorial player for preview functionality', async () => {
renderTutorialPlayer()
// Check that tutorial loads correctly
expect(screen.getByText('Guided Addition Tutorial')).toBeInTheDocument()
// Check that first step is displayed
const stepInfo = screen.getByText(/Step 1 of/)
expect(stepInfo).toBeInTheDocument()
// Check that abacus is rendered
expect(screen.getByTestId('mock-abacus')).toBeInTheDocument()
// Check debug features are available
expect(screen.getByText('Debug')).toBeInTheDocument()
expect(screen.getByText('Steps')).toBeInTheDocument()
// Test step navigation
const nextButton = screen.getByText('Next →')
expect(nextButton).toBeDisabled() // Should be disabled until step is completed
// Complete a step by interacting with abacus
const bead = screen.getByTestId('mock-bead-0')
fireEvent.click(bead)
// Check that step completion is handled
await waitFor(() => {
const completionMessage = screen.queryByText(/Great! You completed/)
if (completionMessage) {
expect(completionMessage).toBeInTheDocument()
}
})
})
it('supports debug panel and step jumping', async () => {
renderTutorialPlayer()
// Open step list
const stepsButton = screen.getByText('Steps')
fireEvent.click(stepsButton)
// Check that step list is displayed
expect(screen.getByText('Tutorial Steps')).toBeInTheDocument()
// Check that steps are listed
const stepListItems = screen.getAllByText(/^\d+\./)
expect(stepListItems.length).toBeGreaterThan(0)
// Test auto-advance toggle
const autoAdvanceCheckbox = screen.getByLabelText('Auto-advance')
expect(autoAdvanceCheckbox).toBeInTheDocument()
fireEvent.click(autoAdvanceCheckbox)
expect(autoAdvanceCheckbox).toBeChecked()
})
})
describe('Access Control Integration', () => {
it('enforces access control for editor features', () => {
// Test that editor is wrapped in access control
render(
<DevAccessProvider>
<TutorialEditor
tutorial={mockTutorial}
onSave={mockOnSave}
onValidate={mockOnValidate}
onPreview={mockOnPreview}
/>
</DevAccessProvider>
)
// Should render editor when access is granted (DevAccessProvider grants access)
expect(screen.getByText('Edit Tutorial')).toBeInTheDocument()
})
it('handles read-only mode when save is not provided', () => {
render(
<DevAccessProvider>
<TutorialEditor
tutorial={mockTutorial}
onValidate={mockOnValidate}
onPreview={mockOnPreview}
/>
</DevAccessProvider>
)
// Should not show edit button when onSave is not provided
expect(screen.queryByText('Edit Tutorial')).not.toBeInTheDocument()
expect(screen.getByText('Guided Addition Tutorial')).toBeInTheDocument()
})
})
describe('Error Handling and Edge Cases', () => {
it('handles tutorial with no steps gracefully', () => {
const emptyTutorial = { ...mockTutorial, steps: [] }
expect(() => {
render(
<DevAccessProvider>
<TutorialEditor
tutorial={emptyTutorial}
onSave={mockOnSave}
onValidate={mockOnValidate}
onPreview={mockOnPreview}
/>
</DevAccessProvider>
)
}).not.toThrow()
expect(screen.getByText('Guided Addition Tutorial')).toBeInTheDocument()
})
it('handles async validation errors gracefully', async () => {
mockOnValidate.mockRejectedValueOnce(new Error('Validation service unavailable'))
renderTutorialEditor()
fireEvent.click(screen.getByText('Edit Tutorial'))
fireEvent.click(screen.getByText('Save Changes'))
await waitFor(() => {
expect(mockOnValidate).toHaveBeenCalled()
expect(mockOnSave).not.toHaveBeenCalled()
})
})
it('handles save operation failures gracefully', async () => {
mockOnSave.mockRejectedValueOnce(new Error('Save failed'))
renderTutorialEditor()
fireEvent.click(screen.getByText('Edit Tutorial'))
fireEvent.click(screen.getByText('Save Changes'))
await waitFor(() => {
expect(mockOnSave).toHaveBeenCalled()
})
})
it('preserves unsaved changes when canceling edit mode', () => {
renderTutorialEditor()
fireEvent.click(screen.getByText('Edit Tutorial'))
// Make some changes
const titleInput = screen.getByDisplayValue('Guided Addition Tutorial')
fireEvent.change(titleInput, { target: { value: 'Modified Title' } })
// Cancel editing
fireEvent.click(screen.getByText('Cancel'))
// Should return to read-only mode with original title
expect(screen.getByText('Guided Addition Tutorial')).toBeInTheDocument()
expect(screen.queryByText('Modified Title')).not.toBeInTheDocument()
})
})
describe('Performance and User Experience', () => {
it('provides immediate feedback for user actions', async () => {
renderTutorialEditor()
// Test immediate response to mode toggle
fireEvent.click(screen.getByText('Edit Tutorial'))
expect(screen.getByText('Save Changes')).toBeInTheDocument()
// Test immediate response to form changes
const titleInput = screen.getByDisplayValue('Guided Addition Tutorial')
fireEvent.change(titleInput, { target: { value: 'New Title' } })
expect(titleInput).toHaveValue('New Title')
// Test immediate response to step expansion
const firstStep = screen.getByText(/1\. .+/)
fireEvent.click(firstStep)
// Should show step editing controls immediately
await waitFor(() => {
expect(screen.queryByText('Preview')).toBeInTheDocument()
})
})
it('maintains consistent state across operations', async () => {
renderTutorialEditor()
fireEvent.click(screen.getByText('Edit Tutorial'))
// Make multiple changes
const titleInput = screen.getByDisplayValue('Guided Addition Tutorial')
fireEvent.change(titleInput, { target: { value: 'Updated Tutorial' } })
// Add a step
const initialCount = screen.getAllByText(/^\d+\./).length
fireEvent.click(screen.getByText('+ Add Step'))
await waitFor(() => {
expect(screen.getAllByText(/^\d+\./).length).toBe(initialCount + 1)
})
// Verify title change is still preserved
expect(screen.getByDisplayValue('Updated Tutorial')).toBeInTheDocument()
// Save and verify both changes are included
fireEvent.click(screen.getByText('Save Changes'))
await waitFor(() => {
expect(mockOnSave).toHaveBeenCalledWith(expect.objectContaining({
title: 'Updated Tutorial',
steps: expect.arrayContaining([expect.any(Object)])
}))
})
})
})
})

View File

@@ -0,0 +1,572 @@
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { TutorialEditor } from '../TutorialEditor'
import { DevAccessProvider } from '../../../hooks/useAccessControl'
import type { Tutorial, TutorialValidation } from '../../../types/tutorial'
const mockTutorial: Tutorial = {
id: 'test-tutorial',
title: 'Test Tutorial',
description: 'A test tutorial for editing',
category: 'test',
difficulty: 'beginner',
estimatedDuration: 15,
steps: [
{
id: 'step-1',
title: 'Step 1',
problem: '0 + 1',
description: 'Add one',
startValue: 0,
targetValue: 1,
highlightBeads: [{ columnIndex: 0, beadType: 'earth', position: 0 }],
expectedAction: 'add',
actionDescription: 'Click the first bead',
tooltip: {
content: 'Test tooltip',
explanation: 'Test explanation'
},
errorMessages: {
wrongBead: 'Wrong bead clicked',
wrongAction: 'Wrong action',
hint: 'Test hint'
}
},
{
id: 'step-2',
title: 'Step 2',
problem: '1 + 1',
description: 'Add another one',
startValue: 1,
targetValue: 2,
expectedAction: 'add',
actionDescription: 'Click the second bead',
tooltip: {
content: 'Second tooltip',
explanation: 'Second explanation'
},
errorMessages: {
wrongBead: 'Wrong bead for step 2',
wrongAction: 'Wrong action for step 2',
hint: 'Step 2 hint'
}
}
],
tags: ['test'],
author: 'Test Author',
version: '1.0.0',
createdAt: new Date(),
updatedAt: new Date(),
isPublished: false
}
const mockValidationResult: TutorialValidation = {
isValid: true,
errors: [],
warnings: []
}
const renderTutorialEditor = (props: Partial<React.ComponentProps<typeof TutorialEditor>> = {}) => {
const defaultProps = {
tutorial: mockTutorial,
onSave: vi.fn(),
onValidate: vi.fn().mockResolvedValue(mockValidationResult),
onPreview: vi.fn()
}
return render(
<DevAccessProvider>
<TutorialEditor {...defaultProps} {...props} />
</DevAccessProvider>
)
}
describe('TutorialEditor', () => {
beforeEach(() => {
vi.clearAllMocks()
})
describe('Initial Rendering', () => {
it('renders tutorial information in read-only mode by default', () => {
renderTutorialEditor()
expect(screen.getByText('Test Tutorial')).toBeInTheDocument()
expect(screen.getByText('A test tutorial for editing')).toBeInTheDocument()
expect(screen.getByText('test')).toBeInTheDocument()
expect(screen.getByText('beginner')).toBeInTheDocument()
expect(screen.getByText('15 minutes')).toBeInTheDocument()
})
it('shows edit tutorial button when onSave is provided', () => {
renderTutorialEditor()
expect(screen.getByText('Edit Tutorial')).toBeInTheDocument()
})
it('does not show edit button when onSave is not provided', () => {
renderTutorialEditor({ onSave: undefined })
expect(screen.queryByText('Edit Tutorial')).not.toBeInTheDocument()
})
it('displays tutorial steps in collapsed state', () => {
renderTutorialEditor()
expect(screen.getByText('1. Step 1')).toBeInTheDocument()
expect(screen.getByText('2. Step 2')).toBeInTheDocument()
expect(screen.getByText('0 + 1')).toBeInTheDocument()
expect(screen.getByText('1 + 1')).toBeInTheDocument()
})
})
describe('Edit Mode Toggle', () => {
it('enters edit mode when edit button is clicked', () => {
renderTutorialEditor()
const editButton = screen.getByText('Edit Tutorial')
fireEvent.click(editButton)
expect(screen.getByText('Save Changes')).toBeInTheDocument()
expect(screen.getByText('Cancel')).toBeInTheDocument()
expect(screen.queryByText('Edit Tutorial')).not.toBeInTheDocument()
})
it('exits edit mode when cancel button is clicked', () => {
renderTutorialEditor()
// Enter edit mode
fireEvent.click(screen.getByText('Edit Tutorial'))
expect(screen.getByText('Save Changes')).toBeInTheDocument()
// Exit edit mode
fireEvent.click(screen.getByText('Cancel'))
expect(screen.getByText('Edit Tutorial')).toBeInTheDocument()
expect(screen.queryByText('Save Changes')).not.toBeInTheDocument()
})
it('shows form inputs in edit mode', () => {
renderTutorialEditor()
fireEvent.click(screen.getByText('Edit Tutorial'))
// Check for tutorial metadata inputs
expect(screen.getByDisplayValue('Test Tutorial')).toBeInTheDocument()
expect(screen.getByDisplayValue('A test tutorial for editing')).toBeInTheDocument()
expect(screen.getByDisplayValue('test')).toBeInTheDocument()
})
})
describe('Tutorial Metadata Editing', () => {
it('allows editing tutorial title', () => {
renderTutorialEditor()
fireEvent.click(screen.getByText('Edit Tutorial'))
const titleInput = screen.getByDisplayValue('Test Tutorial')
fireEvent.change(titleInput, { target: { value: 'Updated Tutorial Title' } })
expect(titleInput).toHaveValue('Updated Tutorial Title')
})
it('allows editing tutorial description', () => {
renderTutorialEditor()
fireEvent.click(screen.getByText('Edit Tutorial'))
const descriptionInput = screen.getByDisplayValue('A test tutorial for editing')
fireEvent.change(descriptionInput, { target: { value: 'Updated description' } })
expect(descriptionInput).toHaveValue('Updated description')
})
it('allows editing category and difficulty', () => {
renderTutorialEditor()
fireEvent.click(screen.getByText('Edit Tutorial'))
const categoryInput = screen.getByDisplayValue('test')
const difficultySelect = screen.getByDisplayValue('beginner')
fireEvent.change(categoryInput, { target: { value: 'advanced' } })
fireEvent.change(difficultySelect, { target: { value: 'intermediate' } })
expect(categoryInput).toHaveValue('advanced')
expect(difficultySelect).toHaveValue('intermediate')
})
it('allows editing estimated duration', () => {
renderTutorialEditor()
fireEvent.click(screen.getByText('Edit Tutorial'))
const durationInput = screen.getByDisplayValue('15')
fireEvent.change(durationInput, { target: { value: '20' } })
expect(durationInput).toHaveValue('20')
})
it('allows editing tags', () => {
renderTutorialEditor()
fireEvent.click(screen.getByText('Edit Tutorial'))
const tagsInput = screen.getByDisplayValue('test')
fireEvent.change(tagsInput, { target: { value: 'test, advanced, math' } })
expect(tagsInput).toHaveValue('test, advanced, math')
})
})
describe('Step Management', () => {
it('expands step editing form when step is clicked', () => {
renderTutorialEditor()
fireEvent.click(screen.getByText('Edit Tutorial'))
const stepButton = screen.getByText('1. Step 1')
fireEvent.click(stepButton)
// Check for step editing inputs
expect(screen.getByDisplayValue('Step 1')).toBeInTheDocument()
expect(screen.getByDisplayValue('0 + 1')).toBeInTheDocument()
expect(screen.getByDisplayValue('Add one')).toBeInTheDocument()
})
it('allows editing step properties', () => {
renderTutorialEditor()
fireEvent.click(screen.getByText('Edit Tutorial'))
fireEvent.click(screen.getByText('1. Step 1'))
const stepTitleInput = screen.getByDisplayValue('Step 1')
const problemInput = screen.getByDisplayValue('0 + 1')
const descriptionInput = screen.getByDisplayValue('Add one')
fireEvent.change(stepTitleInput, { target: { value: 'Updated Step Title' } })
fireEvent.change(problemInput, { target: { value: '2 + 2' } })
fireEvent.change(descriptionInput, { target: { value: 'Updated description' } })
expect(stepTitleInput).toHaveValue('Updated Step Title')
expect(problemInput).toHaveValue('2 + 2')
expect(descriptionInput).toHaveValue('Updated description')
})
it('shows add step button in edit mode', () => {
renderTutorialEditor()
fireEvent.click(screen.getByText('Edit Tutorial'))
expect(screen.getByText('+ Add Step')).toBeInTheDocument()
})
it('adds new step when add button is clicked', () => {
renderTutorialEditor()
fireEvent.click(screen.getByText('Edit Tutorial'))
const initialStepCount = screen.getAllByText(/^\d+\./).length
fireEvent.click(screen.getByText('+ Add Step'))
const newStepCount = screen.getAllByText(/^\d+\./).length
expect(newStepCount).toBe(initialStepCount + 1)
})
it('shows step action buttons when step is expanded', () => {
renderTutorialEditor()
fireEvent.click(screen.getByText('Edit Tutorial'))
fireEvent.click(screen.getByText('1. Step 1'))
expect(screen.getByText('Preview')).toBeInTheDocument()
expect(screen.getByText('Duplicate')).toBeInTheDocument()
expect(screen.getByText('Delete')).toBeInTheDocument()
})
it('duplicates step when duplicate button is clicked', () => {
renderTutorialEditor()
fireEvent.click(screen.getByText('Edit Tutorial'))
fireEvent.click(screen.getByText('1. Step 1'))
const initialStepCount = screen.getAllByText(/^\d+\./).length
fireEvent.click(screen.getByText('Duplicate'))
const newStepCount = screen.getAllByText(/^\d+\./).length
expect(newStepCount).toBe(initialStepCount + 1)
})
it('removes step when delete button is clicked', () => {
renderTutorialEditor()
fireEvent.click(screen.getByText('Edit Tutorial'))
fireEvent.click(screen.getByText('1. Step 1'))
const initialStepCount = screen.getAllByText(/^\d+\./).length
fireEvent.click(screen.getByText('Delete'))
const newStepCount = screen.getAllByText(/^\d+\./).length
expect(newStepCount).toBe(initialStepCount - 1)
})
})
describe('Preview Functionality', () => {
it('calls onPreview when step preview button is clicked', () => {
const onPreview = vi.fn()
renderTutorialEditor({ onPreview })
fireEvent.click(screen.getByText('Edit Tutorial'))
fireEvent.click(screen.getByText('1. Step 1'))
fireEvent.click(screen.getByText('Preview'))
expect(onPreview).toHaveBeenCalledWith(expect.any(Object), 0)
})
it('calls onPreview when global preview button is clicked', () => {
const onPreview = vi.fn()
renderTutorialEditor({ onPreview })
fireEvent.click(screen.getByText('Edit Tutorial'))
const previewButtons = screen.getAllByText('Preview Tutorial')
fireEvent.click(previewButtons[0])
expect(onPreview).toHaveBeenCalledWith(expect.any(Object), 0)
})
})
describe('Save Functionality', () => {
it('calls onSave when save button is clicked', async () => {
const onSave = vi.fn()
renderTutorialEditor({ onSave })
fireEvent.click(screen.getByText('Edit Tutorial'))
// Make a change
const titleInput = screen.getByDisplayValue('Test Tutorial')
fireEvent.change(titleInput, { target: { value: 'Updated Title' } })
fireEvent.click(screen.getByText('Save Changes'))
await waitFor(() => {
expect(onSave).toHaveBeenCalledWith(expect.objectContaining({
title: 'Updated Title'
}))
})
})
it('calls validation before saving', async () => {
const onValidate = vi.fn().mockResolvedValue(mockValidationResult)
const onSave = vi.fn()
renderTutorialEditor({ onSave, onValidate })
fireEvent.click(screen.getByText('Edit Tutorial'))
fireEvent.click(screen.getByText('Save Changes'))
await waitFor(() => {
expect(onValidate).toHaveBeenCalled()
})
})
it('prevents saving when validation fails', async () => {
const onValidate = vi.fn().mockResolvedValue({
isValid: false,
errors: [{ stepId: '', field: 'title', message: 'Title required', severity: 'error' }],
warnings: []
})
const onSave = vi.fn()
renderTutorialEditor({ onSave, onValidate })
fireEvent.click(screen.getByText('Edit Tutorial'))
fireEvent.click(screen.getByText('Save Changes'))
await waitFor(() => {
expect(onValidate).toHaveBeenCalled()
expect(onSave).not.toHaveBeenCalled()
})
})
})
describe('Validation Display', () => {
it('shows validation errors when validation fails', async () => {
const onValidate = vi.fn().mockResolvedValue({
isValid: false,
errors: [{ stepId: '', field: 'title', message: 'Title is required', severity: 'error' }],
warnings: []
})
renderTutorialEditor({ onValidate })
fireEvent.click(screen.getByText('Edit Tutorial'))
fireEvent.click(screen.getByText('Save Changes'))
await waitFor(() => {
expect(screen.getByText('Title is required')).toBeInTheDocument()
})
})
it('shows validation warnings', async () => {
const onValidate = vi.fn().mockResolvedValue({
isValid: true,
errors: [],
warnings: [{ stepId: '', field: 'description', message: 'Description could be longer', severity: 'warning' }]
})
renderTutorialEditor({ onValidate })
fireEvent.click(screen.getByText('Edit Tutorial'))
fireEvent.click(screen.getByText('Save Changes'))
await waitFor(() => {
expect(screen.getByText('Description could be longer')).toBeInTheDocument()
})
})
it('displays step-specific validation errors', async () => {
const onValidate = vi.fn().mockResolvedValue({
isValid: false,
errors: [{ stepId: 'step-1', field: 'problem', message: 'Problem is required', severity: 'error' }],
warnings: []
})
renderTutorialEditor({ onValidate })
fireEvent.click(screen.getByText('Edit Tutorial'))
fireEvent.click(screen.getByText('1. Step 1'))
fireEvent.click(screen.getByText('Save Changes'))
await waitFor(() => {
expect(screen.getByText('Problem is required')).toBeInTheDocument()
})
})
})
describe('Step Reordering', () => {
it('shows move up/down buttons for steps', () => {
renderTutorialEditor()
fireEvent.click(screen.getByText('Edit Tutorial'))
fireEvent.click(screen.getByText('1. Step 1'))
// Step 1 should have move down button but no move up
expect(screen.getByLabelText(/Move.*down/i)).toBeInTheDocument()
expect(screen.queryByLabelText(/Move.*up/i)).not.toBeInTheDocument()
})
it('enables both move buttons for middle steps', () => {
const tutorialWithMoreSteps = {
...mockTutorial,
steps: [
...mockTutorial.steps,
{
id: 'step-3',
title: 'Step 3',
problem: '2 + 1',
description: 'Add one more',
startValue: 2,
targetValue: 3,
expectedAction: 'add',
actionDescription: 'Click the third bead',
tooltip: { content: 'Third tooltip', explanation: 'Third explanation' },
errorMessages: { wrongBead: 'Wrong bead', wrongAction: 'Wrong action', hint: 'Hint' }
}
]
}
renderTutorialEditor({ tutorial: tutorialWithMoreSteps })
fireEvent.click(screen.getByText('Edit Tutorial'))
fireEvent.click(screen.getByText('2. Step 2'))
// Middle step should have both buttons
expect(screen.getByLabelText(/Move.*up/i)).toBeInTheDocument()
expect(screen.getByLabelText(/Move.*down/i)).toBeInTheDocument()
})
})
describe('Accessibility', () => {
it('has proper ARIA attributes for form controls', () => {
renderTutorialEditor()
fireEvent.click(screen.getByText('Edit Tutorial'))
const titleInput = screen.getByDisplayValue('Test Tutorial')
expect(titleInput).toHaveAttribute('aria-label')
})
it('has proper heading structure', () => {
renderTutorialEditor()
expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('Test Tutorial')
})
it('has proper button roles and labels', () => {
renderTutorialEditor()
const editButton = screen.getByText('Edit Tutorial')
expect(editButton).toHaveAttribute('type', 'button')
})
})
describe('Edge Cases', () => {
it('handles empty tutorial gracefully', () => {
const emptyTutorial = { ...mockTutorial, steps: [], title: '', description: '' }
expect(() => {
renderTutorialEditor({ tutorial: emptyTutorial })
}).not.toThrow()
})
it('handles tutorial with single step', () => {
const singleStepTutorial = { ...mockTutorial, steps: [mockTutorial.steps[0]] }
renderTutorialEditor({ tutorial: singleStepTutorial })
fireEvent.click(screen.getByText('Edit Tutorial'))
expect(screen.getByText('1. Step 1')).toBeInTheDocument()
expect(screen.queryByText('2.')).not.toBeInTheDocument()
})
it('handles invalid step data gracefully', () => {
const invalidStepTutorial = {
...mockTutorial,
steps: [{
...mockTutorial.steps[0],
startValue: -1,
targetValue: -1
}]
}
expect(() => {
renderTutorialEditor({ tutorial: invalidStepTutorial })
}).not.toThrow()
})
it('prevents deleting the last step', () => {
const singleStepTutorial = { ...mockTutorial, steps: [mockTutorial.steps[0]] }
renderTutorialEditor({ tutorial: singleStepTutorial })
fireEvent.click(screen.getByText('Edit Tutorial'))
fireEvent.click(screen.getByText('1. Step 1'))
const deleteButton = screen.getByText('Delete')
expect(deleteButton).toBeDisabled()
})
})
describe('Read-only Mode', () => {
it('does not show edit controls when onSave is not provided', () => {
renderTutorialEditor({ onSave: undefined })
expect(screen.queryByText('Edit Tutorial')).not.toBeInTheDocument()
expect(screen.getByText('Test Tutorial')).toBeInTheDocument()
expect(screen.getByText('1. Step 1')).toBeInTheDocument()
})
it('allows clicking steps in read-only mode for viewing', () => {
renderTutorialEditor({ onSave: undefined })
fireEvent.click(screen.getByText('1. Step 1'))
// Should show step details but no edit controls
expect(screen.getByText('0 + 1')).toBeInTheDocument()
expect(screen.queryByDisplayValue('Step 1')).not.toBeInTheDocument()
})
})
})

View File

@@ -0,0 +1,385 @@
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { TutorialPlayer } from '../TutorialPlayer'
import { DevAccessProvider } from '../../../hooks/useAccessControl'
import type { Tutorial, TutorialEvent } from '../../../types/tutorial'
// Mock the AbacusReact component
vi.mock('@soroban/abacus-react', () => ({
AbacusReact: ({ value, onValueChange, callbacks }: any) => (
<div data-testid="mock-abacus">
<div data-testid="abacus-value">{value}</div>
<button
data-testid="mock-bead-0"
onClick={() => {
onValueChange?.(value + 1)
callbacks?.onBeadClick?.({
columnIndex: 0,
beadType: 'earth',
position: 0,
active: false
})
}}
>
Mock Bead
</button>
</div>
)
}))
const mockTutorial: Tutorial = {
id: 'test-tutorial',
title: 'Test Tutorial',
description: 'A test tutorial',
category: 'test',
difficulty: 'beginner',
estimatedDuration: 10,
steps: [
{
id: 'step-1',
title: 'Step 1',
problem: '0 + 1',
description: 'Add one',
startValue: 0,
targetValue: 1,
highlightBeads: [{ columnIndex: 0, beadType: 'earth', position: 0 }],
expectedAction: 'add',
actionDescription: 'Click the first bead',
tooltip: {
content: 'Test tooltip',
explanation: 'Test explanation'
},
errorMessages: {
wrongBead: 'Wrong bead clicked',
wrongAction: 'Wrong action',
hint: 'Test hint'
}
},
{
id: 'step-2',
title: 'Step 2',
problem: '1 + 1',
description: 'Add another one',
startValue: 1,
targetValue: 2,
expectedAction: 'add',
actionDescription: 'Click the second bead',
tooltip: {
content: 'Second tooltip',
explanation: 'Second explanation'
},
errorMessages: {
wrongBead: 'Wrong bead for step 2',
wrongAction: 'Wrong action for step 2',
hint: 'Step 2 hint'
}
}
],
tags: ['test'],
author: 'Test Author',
version: '1.0.0',
createdAt: new Date(),
updatedAt: new Date(),
isPublished: true
}
const renderTutorialPlayer = (props: Partial<React.ComponentProps<typeof TutorialPlayer>> = {}) => {
const defaultProps = {
tutorial: mockTutorial,
initialStepIndex: 0,
isDebugMode: false,
showDebugPanel: false
}
return render(
<DevAccessProvider>
<TutorialPlayer {...defaultProps} {...props} />
</DevAccessProvider>
)
}
describe('TutorialPlayer', () => {
beforeEach(() => {
vi.clearAllMocks()
})
describe('Basic Rendering', () => {
it('renders tutorial title and current step information', () => {
renderTutorialPlayer()
expect(screen.getByText('Test Tutorial')).toBeInTheDocument()
expect(screen.getByText(/Step 1 of 2: Step 1/)).toBeInTheDocument()
expect(screen.getByText('0 + 1')).toBeInTheDocument()
expect(screen.getByText('Add one')).toBeInTheDocument()
})
it('renders the abacus component', () => {
renderTutorialPlayer()
expect(screen.getByTestId('mock-abacus')).toBeInTheDocument()
expect(screen.getByTestId('abacus-value')).toHaveTextContent('0')
})
it('shows tooltip information', () => {
renderTutorialPlayer()
expect(screen.getByText('Test tooltip')).toBeInTheDocument()
expect(screen.getByText('Test explanation')).toBeInTheDocument()
})
it('shows progress bar', () => {
renderTutorialPlayer()
const progressBar = screen.getByRole('progressbar', { hidden: true }) ||
document.querySelector('[style*="width"]')
expect(progressBar).toBeInTheDocument()
})
})
describe('Navigation', () => {
it('disables previous button on first step', () => {
renderTutorialPlayer()
const prevButton = screen.getByText('← Previous')
expect(prevButton).toBeDisabled()
})
it('enables next button when step is completed', async () => {
const onStepComplete = vi.fn()
renderTutorialPlayer({ onStepComplete })
// Complete the step by clicking the mock bead
const bead = screen.getByTestId('mock-bead-0')
fireEvent.click(bead)
await waitFor(() => {
const nextButton = screen.getByText('Next →')
expect(nextButton).not.toBeDisabled()
})
})
it('navigates to next step when next button is clicked', async () => {
const onStepChange = vi.fn()
renderTutorialPlayer({ onStepChange })
// Complete first step
const bead = screen.getByTestId('mock-bead-0')
fireEvent.click(bead)
await waitFor(() => {
const nextButton = screen.getByText('Next →')
fireEvent.click(nextButton)
})
expect(onStepChange).toHaveBeenCalledWith(1, mockTutorial.steps[1])
})
it('shows "Complete Tutorial" button on last step', () => {
renderTutorialPlayer({ initialStepIndex: 1 })
expect(screen.getByText('Complete Tutorial')).toBeInTheDocument()
})
})
describe('Step Completion', () => {
it('marks step as completed when target value is reached', async () => {
const onStepComplete = vi.fn()
renderTutorialPlayer({ onStepComplete })
const bead = screen.getByTestId('mock-bead-0')
fireEvent.click(bead)
await waitFor(() => {
expect(screen.getByText(/Great! You completed this step correctly/)).toBeInTheDocument()
expect(onStepComplete).toHaveBeenCalledWith(0, mockTutorial.steps[0], true)
})
})
it('calls onTutorialComplete when tutorial is finished', async () => {
const onTutorialComplete = vi.fn()
renderTutorialPlayer({
initialStepIndex: 1, // Start on last step
onTutorialComplete
})
// Complete the last step
const bead = screen.getByTestId('mock-bead-0')
fireEvent.click(bead)
await waitFor(() => {
const completeButton = screen.getByText('Complete Tutorial')
fireEvent.click(completeButton)
})
expect(onTutorialComplete).toHaveBeenCalled()
})
})
describe('Debug Mode', () => {
it('shows debug controls when debug mode is enabled', () => {
renderTutorialPlayer({ isDebugMode: true })
expect(screen.getByText('Debug')).toBeInTheDocument()
expect(screen.getByText('Steps')).toBeInTheDocument()
expect(screen.getByLabelText('Auto-advance')).toBeInTheDocument()
})
it('shows debug panel when enabled', () => {
renderTutorialPlayer({ isDebugMode: true, showDebugPanel: true })
expect(screen.getByText('Debug Panel')).toBeInTheDocument()
expect(screen.getByText('Current State')).toBeInTheDocument()
expect(screen.getByText('Event Log')).toBeInTheDocument()
})
it('shows step list sidebar when enabled', () => {
renderTutorialPlayer({ isDebugMode: true })
const stepsButton = screen.getByText('Steps')
fireEvent.click(stepsButton)
expect(screen.getByText('Tutorial Steps')).toBeInTheDocument()
expect(screen.getByText('1. Step 1')).toBeInTheDocument()
expect(screen.getByText('2. Step 2')).toBeInTheDocument()
})
it('allows jumping to specific step from step list', () => {
const onStepChange = vi.fn()
renderTutorialPlayer({ isDebugMode: true, onStepChange })
const stepsButton = screen.getByText('Steps')
fireEvent.click(stepsButton)
const step2Button = screen.getByText('2. Step 2')
fireEvent.click(step2Button)
expect(onStepChange).toHaveBeenCalledWith(1, mockTutorial.steps[1])
})
})
describe('Event Logging', () => {
it('logs events when onEvent callback is provided', () => {
const onEvent = vi.fn()
renderTutorialPlayer({ onEvent })
const bead = screen.getByTestId('mock-bead-0')
fireEvent.click(bead)
expect(onEvent).toHaveBeenCalledWith(
expect.objectContaining({
type: 'BEAD_CLICKED',
timestamp: expect.any(Date)
})
)
})
it('logs step started event on mount', () => {
const onEvent = vi.fn()
renderTutorialPlayer({ onEvent })
expect(onEvent).toHaveBeenCalledWith(
expect.objectContaining({
type: 'STEP_STARTED',
stepId: 'step-1',
timestamp: expect.any(Date)
})
)
})
it('logs value changed events', () => {
const onEvent = vi.fn()
renderTutorialPlayer({ onEvent })
const bead = screen.getByTestId('mock-bead-0')
fireEvent.click(bead)
expect(onEvent).toHaveBeenCalledWith(
expect.objectContaining({
type: 'VALUE_CHANGED',
oldValue: 0,
newValue: 1,
timestamp: expect.any(Date)
})
)
})
})
describe('Error Handling', () => {
it('shows error message for wrong bead clicks', async () => {
renderTutorialPlayer()
// Mock a wrong bead click by directly calling the callback
// In real usage, this would come from the AbacusReact component
const wrongBeadClick = {
columnIndex: 1, // Wrong column
beadType: 'earth' as const,
position: 0,
active: false
}
// Simulate wrong bead click through the mock
const mockAbacus = screen.getByTestId('mock-abacus')
// We need to trigger this through the component's callback system
// For now, we'll test the error display indirectly
})
})
describe('Auto-advance Feature', () => {
it('enables auto-advance when checkbox is checked', () => {
renderTutorialPlayer({ isDebugMode: true })
const autoAdvanceCheckbox = screen.getByLabelText('Auto-advance')
fireEvent.click(autoAdvanceCheckbox)
expect(autoAdvanceCheckbox).toBeChecked()
})
})
describe('Accessibility', () => {
it('has proper ARIA attributes', () => {
renderTutorialPlayer()
// Check for proper heading structure
expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('Test Tutorial')
expect(screen.getByRole('heading', { level: 2 })).toHaveTextContent('0 + 1')
})
it('has keyboard navigation support', () => {
renderTutorialPlayer()
const nextButton = screen.getByText('Next →')
const prevButton = screen.getByText('← Previous')
expect(nextButton).toHaveAttribute('type', 'button')
expect(prevButton).toHaveAttribute('type', 'button')
})
})
describe('Edge Cases', () => {
it('handles empty tutorial gracefully', () => {
const emptyTutorial = { ...mockTutorial, steps: [] }
expect(() => {
renderTutorialPlayer({ tutorial: emptyTutorial })
}).not.toThrow()
})
it('handles invalid initial step index', () => {
expect(() => {
renderTutorialPlayer({ initialStepIndex: 999 })
}).not.toThrow()
})
it('handles tutorial with single step', () => {
const singleStepTutorial = {
...mockTutorial,
steps: [mockTutorial.steps[0]]
}
renderTutorialPlayer({ tutorial: singleStepTutorial })
expect(screen.getByText('Complete Tutorial')).toBeInTheDocument()
expect(screen.getByText('← Previous')).toBeDisabled()
})
})
})

View File

@@ -0,0 +1,227 @@
'use client'
import { createContext, useContext, ReactNode } from 'react'
import { AccessContext, UserRole, Permission } from '../types/tutorial'
// Default context value (no permissions)
const defaultAccessContext: AccessContext = {
userId: undefined,
roles: [],
isAuthenticated: false,
isAdmin: false,
canEdit: false,
canPublish: false,
canDelete: false,
}
// Create context
const AccessControlContext = createContext<AccessContext>(defaultAccessContext)
// Provider component
interface AccessControlProviderProps {
children: ReactNode
userId?: string
roles?: UserRole[]
isAuthenticated?: boolean
}
export function AccessControlProvider({
children,
userId,
roles = [],
isAuthenticated = false
}: AccessControlProviderProps) {
// Calculate permissions based on roles
const permissions = roles.flatMap(role => role.permissions)
// Check if user has admin role
const isAdmin = roles.some(role => role.name === 'admin' || role.name === 'superuser')
// Check specific permissions
const canEdit = isAdmin || permissions.some(p =>
p.resource === 'tutorial' && p.actions.includes('update')
)
const canPublish = isAdmin || permissions.some(p =>
p.resource === 'tutorial' && p.actions.includes('publish')
)
const canDelete = isAdmin || permissions.some(p =>
p.resource === 'tutorial' && p.actions.includes('delete')
)
const accessContext: AccessContext = {
userId,
roles,
isAuthenticated,
isAdmin,
canEdit,
canPublish,
canDelete,
}
return (
<AccessControlContext.Provider value={accessContext}>
{children}
</AccessControlContext.Provider>
)
}
// Hook to use access control
export function useAccessControl(): AccessContext {
const context = useContext(AccessControlContext)
if (!context) {
throw new Error('useAccessControl must be used within an AccessControlProvider')
}
return context
}
// Hook for conditional rendering based on permissions
export function usePermission(
resource: Permission['resource'],
action: Permission['actions'][number]
): boolean {
const { isAdmin, roles } = useAccessControl()
if (isAdmin) return true
return roles.some(role =>
role.permissions.some(permission =>
permission.resource === resource && permission.actions.includes(action)
)
)
}
// Hook for editor access specifically
export function useEditorAccess(): {
canAccessEditor: boolean
canEditTutorials: boolean
canPublishTutorials: boolean
canDeleteTutorials: boolean
reason?: string
} {
const { isAuthenticated, isAdmin, canEdit, canPublish, canDelete } = useAccessControl()
if (!isAuthenticated) {
return {
canAccessEditor: false,
canEditTutorials: false,
canPublishTutorials: false,
canDeleteTutorials: false,
reason: 'Authentication required'
}
}
const canAccessEditor = isAdmin || canEdit
return {
canAccessEditor,
canEditTutorials: canEdit,
canPublishTutorials: canPublish,
canDeleteTutorials: canDelete,
reason: canAccessEditor ? undefined : 'Insufficient permissions'
}
}
// Higher-order component for protecting routes
interface ProtectedComponentProps {
children: ReactNode
fallback?: ReactNode
requirePermissions?: {
resource: Permission['resource']
actions: Permission['actions']
}[]
}
export function ProtectedComponent({
children,
fallback = <div>Access denied</div>,
requirePermissions = []
}: ProtectedComponentProps) {
const { isAuthenticated, roles, isAdmin } = useAccessControl()
if (!isAuthenticated) {
return <>{fallback}</>
}
if (isAdmin) {
return <>{children}</>
}
// Check if user has all required permissions
const hasAllPermissions = requirePermissions.every(({ resource, actions }) =>
roles.some(role =>
role.permissions.some(permission =>
permission.resource === resource &&
actions.every(action => permission.actions.includes(action))
)
)
)
if (!hasAllPermissions) {
return <>{fallback}</>
}
return <>{children}</>
}
// Component for editor-specific protection
interface EditorProtectedProps {
children: ReactNode
fallback?: ReactNode
}
export function EditorProtected({ children, fallback }: EditorProtectedProps) {
const { canAccessEditor, reason } = useEditorAccess()
if (!canAccessEditor) {
return (
<>{fallback || (
<div className="text-center p-8">
<h2 className="text-xl font-semibold mb-2">Access Restricted</h2>
<p className="text-gray-600">{reason}</p>
</div>
)}</>
)
}
return <>{children}</>
}
// Dev mode provider (for development without auth)
export function DevAccessProvider({ children }: { children: ReactNode }) {
const devRoles: UserRole[] = [
{
id: 'dev-admin',
name: 'admin',
permissions: [
{
resource: 'tutorial',
actions: ['create', 'read', 'update', 'delete', 'publish']
},
{
resource: 'step',
actions: ['create', 'read', 'update', 'delete']
},
{
resource: 'user',
actions: ['read', 'update']
},
{
resource: 'system',
actions: ['read']
}
]
}
]
return (
<AccessControlProvider
userId="dev-user"
roles={devRoles}
isAuthenticated={true}
>
{children}
</AccessControlProvider>
)
}

View File

@@ -0,0 +1,54 @@
import type { Meta, StoryObj } from '@storybook/nextjs';
import { fn } from 'storybook/test';
import { Button } from './Button';
// More on how to set up stories at: https://storybook.js.org/docs/writing-stories#default-export
const meta = {
title: 'Example/Button',
component: Button,
parameters: {
// Optional parameter to center the component in the Canvas. More info: https://storybook.js.org/docs/configure/story-layout
layout: 'centered',
},
// This component will have an automatically generated Autodocs entry: https://storybook.js.org/docs/writing-docs/autodocs
tags: ['autodocs'],
// More on argTypes: https://storybook.js.org/docs/api/argtypes
argTypes: {
backgroundColor: { control: 'color' },
},
// Use `fn` to spy on the onClick arg, which will appear in the actions panel once invoked: https://storybook.js.org/docs/essentials/actions#action-args
args: { onClick: fn() },
} satisfies Meta<typeof Button>;
export default meta;
type Story = StoryObj<typeof meta>;
// More on writing stories with args: https://storybook.js.org/docs/writing-stories/args
export const Primary: Story = {
args: {
primary: true,
label: 'Button',
},
};
export const Secondary: Story = {
args: {
label: 'Button',
},
};
export const Large: Story = {
args: {
size: 'large',
label: 'Button',
},
};
export const Small: Story = {
args: {
size: 'small',
label: 'Button',
},
};

View File

@@ -0,0 +1,39 @@
import './button.css';
export interface ButtonProps {
/** Is this the principal call to action on the page? */
primary?: boolean;
/** What background color to use */
backgroundColor?: string;
/** How large should the button be? */
size?: 'small' | 'medium' | 'large';
/** Button contents */
label: string;
/** Optional click handler */
onClick?: () => void;
}
/** Primary UI component for user interaction */
export const Button = ({
primary = false,
size = 'medium',
backgroundColor,
label,
...props
}: ButtonProps) => {
const mode = primary ? 'storybook-button--primary' : 'storybook-button--secondary';
return (
<button
type="button"
className={['storybook-button', `storybook-button--${size}`, mode].join(' ')}
{...props}
>
{label}
<style jsx>{`
button {
background-color: ${backgroundColor};
}
`}</style>
</button>
);
};

View File

@@ -0,0 +1,446 @@
import { Meta } from "@storybook/addon-docs/blocks";
import Image from "next/image";
import Github from "./assets/github.svg";
import Discord from "./assets/discord.svg";
import Youtube from "./assets/youtube.svg";
import Tutorials from "./assets/tutorials.svg";
import Styling from "./assets/styling.png";
import Context from "./assets/context.png";
import Assets from "./assets/assets.png";
import Docs from "./assets/docs.png";
import Share from "./assets/share.png";
import FigmaPlugin from "./assets/figma-plugin.png";
import Testing from "./assets/testing.png";
import Accessibility from "./assets/accessibility.png";
import Theming from "./assets/theming.png";
import AddonLibrary from "./assets/addon-library.png";
export const RightArrow = () => <svg
viewBox="0 0 14 14"
width="8px"
height="14px"
style={{
marginLeft: '4px',
display: 'inline-block',
shapeRendering: 'inherit',
verticalAlign: 'middle',
fill: 'currentColor',
'path fill': 'currentColor'
}}
>
<path d="m11.1 7.35-5.5 5.5a.5.5 0 0 1-.7-.7L10.04 7 4.9 1.85a.5.5 0 1 1 .7-.7l5.5 5.5c.2.2.2.5 0 .7Z" />
</svg>
<Meta title="Configure your project" />
<div className="sb-container">
<div className='sb-section-title'>
# Configure your project
Because Storybook works separately from your app, you'll need to configure it for your specific stack and setup. Below, explore guides for configuring Storybook with popular frameworks and tools. If you get stuck, learn how you can ask for help from our community.
</div>
<div className="sb-section">
<div className="sb-section-item">
<Image
src={Styling}
alt="A wall of logos representing different styling technologies"
width={0}
height={0}
style={{ width: '100%', height: 'auto' }}
/>
<h4 className="sb-section-item-heading">Add styling and CSS</h4>
<p className="sb-section-item-paragraph">Like with web applications, there are many ways to include CSS within Storybook. Learn more about setting up styling within Storybook.</p>
<a
href="https://storybook.js.org/docs/configure/styling-and-css/?renderer=react&ref=configure"
target="_blank"
>Learn more<RightArrow /></a>
</div>
<div className="sb-section-item">
<Image
width={0}
height={0}
style={{ width: '100%', height: 'auto' }}
src={Context}
alt="An abstraction representing the composition of data for a component"
/>
<h4 className="sb-section-item-heading">Provide context and mocking</h4>
<p className="sb-section-item-paragraph">Often when a story doesn't render, it's because your component is expecting a specific environment or context (like a theme provider) to be available.</p>
<a
href="https://storybook.js.org/docs/writing-stories/decorators/?renderer=react&ref=configure#context-for-mocking"
target="_blank"
>Learn more<RightArrow /></a>
</div>
<div className="sb-section-item">
<Image
width={0}
height={0}
style={{ width: '100%', height: 'auto' }}
src={Assets}
alt="A representation of typography and image assets"
/>
<div>
<h4 className="sb-section-item-heading">Load assets and resources</h4>
<p className="sb-section-item-paragraph">To link static files (like fonts) to your projects and stories, use the
`staticDirs` configuration option to specify folders to load when
starting Storybook.</p>
<a
href="https://storybook.js.org/docs/configure/images-and-assets/?renderer=react&ref=configure"
target="_blank"
>Learn more<RightArrow /></a>
</div>
</div>
</div>
</div>
<div className="sb-container">
<div className='sb-section-title'>
# Do more with Storybook
Now that you know the basics, let's explore other parts of Storybook that will improve your experience. This list is just to get you started. You can customise Storybook in many ways to fit your needs.
</div>
<div className="sb-section">
<div className="sb-features-grid">
<div className="sb-grid-item">
<Image
width={0}
height={0}
style={{ width: '100%', height: 'auto' }}
src={Docs}
alt="A screenshot showing the autodocs tag being set, pointing a docs page being generated"
/>
<h4 className="sb-section-item-heading">Autodocs</h4>
<p className="sb-section-item-paragraph">Auto-generate living,
interactive reference documentation from your components and stories.</p>
<a
href="https://storybook.js.org/docs/writing-docs/autodocs/?renderer=react&ref=configure"
target="_blank"
>Learn more<RightArrow /></a>
</div>
<div className="sb-grid-item">
<Image
width={0}
height={0}
style={{ width: '100%', height: 'auto' }}
src={Share}
alt="A browser window showing a Storybook being published to a chromatic.com URL"
/>
<h4 className="sb-section-item-heading">Publish to Chromatic</h4>
<p className="sb-section-item-paragraph">Publish your Storybook to review and collaborate with your entire team.</p>
<a
href="https://storybook.js.org/docs/sharing/publish-storybook/?renderer=react&ref=configure#publish-storybook-with-chromatic"
target="_blank"
>Learn more<RightArrow /></a>
</div>
<div className="sb-grid-item">
<Image
width={0}
height={0}
style={{ width: '100%', height: 'auto' }}
src={FigmaPlugin}
alt="Windows showing the Storybook plugin in Figma"
/>
<h4 className="sb-section-item-heading">Figma Plugin</h4>
<p className="sb-section-item-paragraph">Embed your stories into Figma to cross-reference the design and live
implementation in one place.</p>
<a
href="https://storybook.js.org/docs/sharing/design-integrations/?renderer=react&ref=configure#embed-storybook-in-figma-with-the-plugin"
target="_blank"
>Learn more<RightArrow /></a>
</div>
<div className="sb-grid-item">
<Image
width={0}
height={0}
style={{ width: '100%', height: 'auto' }}
src={Testing}
alt="Screenshot of tests passing and failing"
/>
<h4 className="sb-section-item-heading">Testing</h4>
<p className="sb-section-item-paragraph">Use stories to test a component in all its variations, no matter how
complex.</p>
<a
href="https://storybook.js.org/docs/writing-tests/?renderer=react&ref=configure"
target="_blank"
>Learn more<RightArrow /></a>
</div>
<div className="sb-grid-item">
<Image
width={0}
height={0}
style={{ width: '100%', height: 'auto' }}
src={Accessibility}
alt="Screenshot of accessibility tests passing and failing"
/>
<h4 className="sb-section-item-heading">Accessibility</h4>
<p className="sb-section-item-paragraph">Automatically test your components for a11y issues as you develop.</p>
<a
href="https://storybook.js.org/docs/writing-tests/accessibility-testing/?renderer=react&ref=configure"
target="_blank"
>Learn more<RightArrow /></a>
</div>
<div className="sb-grid-item">
<Image
width={0}
height={0}
style={{ width: '100%', height: 'auto' }}
src={Theming}
alt="Screenshot of Storybook in light and dark mode"
/>
<h4 className="sb-section-item-heading">Theming</h4>
<p className="sb-section-item-paragraph">Theme Storybook's UI to personalize it to your project.</p>
<a
href="https://storybook.js.org/docs/configure/theming/?renderer=react&ref=configure"
target="_blank"
>Learn more<RightArrow /></a>
</div>
</div>
</div>
</div>
<div className='sb-addon'>
<div className='sb-addon-text'>
<h4>Addons</h4>
<p className="sb-section-item-paragraph">Integrate your tools with Storybook to connect workflows.</p>
<a
href="https://storybook.js.org/addons/?ref=configure"
target="_blank"
>Discover all addons<RightArrow /></a>
</div>
<div className='sb-addon-img'>
<Image
width={650}
height={347}
src={AddonLibrary}
alt="Integrate your tools with Storybook to connect workflows."
/>
</div>
</div>
<div className="sb-section sb-socials">
<div className="sb-section-item">
<Image
width={32}
height={32}
layout="fixed"
src={Github}
alt="Github logo"
className="sb-explore-image"
/>
Join our contributors building the future of UI development.
<a
href="https://github.com/storybookjs/storybook"
target="_blank"
>Star on GitHub<RightArrow /></a>
</div>
<div className="sb-section-item">
<Image
width={33}
height={32}
layout="fixed"
src={Discord}
alt="Discord logo"
className="sb-explore-image"
/>
<div>
Get support and chat with frontend developers.
<a
href="https://discord.gg/storybook"
target="_blank"
>Join Discord server<RightArrow /></a>
</div>
</div>
<div className="sb-section-item">
<Image
width={32}
height={32}
layout="fixed"
src={Youtube}
alt="Youtube logo"
className="sb-explore-image"
/>
<div>
Watch tutorials, feature previews and interviews.
<a
href="https://www.youtube.com/@chromaticui"
target="_blank"
>Watch on YouTube<RightArrow /></a>
</div>
</div>
<div className="sb-section-item">
<Image
width={33}
height={32}
layout="fixed"
src={Tutorials}
alt="A book"
className="sb-explore-image"
/>
<p>Follow guided walkthroughs on for key workflows.</p>
<a
href="https://storybook.js.org/tutorials/?ref=configure"
target="_blank"
>Discover tutorials<RightArrow /></a>
</div>
</div>
<style>
{`
.sb-container {
margin-bottom: 48px;
}
.sb-section {
width: 100%;
display: flex;
flex-direction: row;
gap: 20px;
}
img {
object-fit: cover;
}
.sb-section-title {
margin-bottom: 32px;
}
.sb-section a:not(h1 a, h2 a, h3 a) {
font-size: 14px;
}
.sb-section-item, .sb-grid-item {
flex: 1;
display: flex;
flex-direction: column;
}
.sb-section-item-heading {
padding-top: 20px !important;
padding-bottom: 5px !important;
margin: 0 !important;
}
.sb-section-item-paragraph {
margin: 0;
padding-bottom: 10px;
}
.sb-chevron {
margin-left: 5px;
}
.sb-features-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-gap: 32px 20px;
}
.sb-socials {
display: grid;
grid-template-columns: repeat(4, 1fr);
}
.sb-socials p {
margin-bottom: 10px;
}
.sb-explore-image {
max-height: 32px;
align-self: flex-start;
}
.sb-addon {
width: 100%;
display: flex;
align-items: center;
position: relative;
background-color: #EEF3F8;
border-radius: 5px;
border: 1px solid rgba(0, 0, 0, 0.05);
background: #EEF3F8;
height: 180px;
margin-bottom: 48px;
overflow: hidden;
}
.sb-addon-text {
padding-left: 48px;
max-width: 240px;
}
.sb-addon-text h4 {
padding-top: 0px;
}
.sb-addon-img {
position: absolute;
left: 345px;
top: 0;
height: 100%;
width: 200%;
overflow: hidden;
}
.sb-addon-img img {
width: 650px;
transform: rotate(-15deg);
margin-left: 40px;
margin-top: -72px;
box-shadow: 0 0 1px rgba(255, 255, 255, 0);
backface-visibility: hidden;
}
@media screen and (max-width: 800px) {
.sb-addon-img {
left: 300px;
}
}
@media screen and (max-width: 600px) {
.sb-section {
flex-direction: column;
}
.sb-features-grid {
grid-template-columns: repeat(1, 1fr);
}
.sb-socials {
grid-template-columns: repeat(2, 1fr);
}
.sb-addon {
height: 280px;
align-items: flex-start;
padding-top: 32px;
overflow: hidden;
}
.sb-addon-text {
padding-left: 24px;
}
.sb-addon-img {
right: 0;
left: 0;
top: 130px;
bottom: 0;
overflow: hidden;
height: auto;
width: 124%;
}
.sb-addon-img img {
width: 1200px;
transform: rotate(-12deg);
margin-left: 0;
margin-top: 48px;
margin-bottom: -40px;
margin-left: -24px;
}
}
`}
</style>

View File

@@ -0,0 +1,34 @@
import type { Meta, StoryObj } from '@storybook/nextjs';
import { fn } from 'storybook/test';
import { Header } from './Header';
const meta = {
title: 'Example/Header',
component: Header,
// This component will have an automatically generated Autodocs entry: https://storybook.js.org/docs/writing-docs/autodocs
tags: ['autodocs'],
parameters: {
// More on how to position stories at: https://storybook.js.org/docs/configure/story-layout
layout: 'fullscreen',
},
args: {
onLogin: fn(),
onLogout: fn(),
onCreateAccount: fn(),
},
} satisfies Meta<typeof Header>;
export default meta;
type Story = StoryObj<typeof meta>;
export const LoggedIn: Story = {
args: {
user: {
name: 'Jane Doe',
},
},
};
export const LoggedOut: Story = {};

View File

@@ -0,0 +1,54 @@
import { Button } from './Button';
import './header.css';
type User = {
name: string;
};
export interface HeaderProps {
user?: User;
onLogin?: () => void;
onLogout?: () => void;
onCreateAccount?: () => void;
}
export const Header = ({ user, onLogin, onLogout, onCreateAccount }: HeaderProps) => (
<header>
<div className="storybook-header">
<div>
<svg width="32" height="32" viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg">
<g fill="none" fillRule="evenodd">
<path
d="M10 0h12a10 10 0 0110 10v12a10 10 0 01-10 10H10A10 10 0 010 22V10A10 10 0 0110 0z"
fill="#FFF"
/>
<path
d="M5.3 10.6l10.4 6v11.1l-10.4-6v-11zm11.4-6.2l9.7 5.5-9.7 5.6V4.4z"
fill="#555AB9"
/>
<path
d="M27.2 10.6v11.2l-10.5 6V16.5l10.5-6zM15.7 4.4v11L6 10l9.7-5.5z"
fill="#91BAF8"
/>
</g>
</svg>
<h1>Acme</h1>
</div>
<div>
{user ? (
<>
<span className="welcome">
Welcome, <b>{user.name}</b>!
</span>
<Button size="small" onClick={onLogout} label="Log out" />
</>
) : (
<>
<Button size="small" onClick={onLogin} label="Log in" />
<Button primary size="small" onClick={onCreateAccount} label="Sign up" />
</>
)}
</div>
</div>
</header>
);

View File

@@ -0,0 +1,33 @@
import type { Meta, StoryObj } from '@storybook/nextjs';
import { expect, userEvent, within } from 'storybook/test';
import { Page } from './Page';
const meta = {
title: 'Example/Page',
component: Page,
parameters: {
// More on how to position stories at: https://storybook.js.org/docs/configure/story-layout
layout: 'fullscreen',
},
} satisfies Meta<typeof Page>;
export default meta;
type Story = StoryObj<typeof meta>;
export const LoggedOut: Story = {};
// More on component testing: https://storybook.js.org/docs/writing-tests/interaction-testing
export const LoggedIn: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const loginButton = canvas.getByRole('button', { name: /Log in/i });
await expect(loginButton).toBeInTheDocument();
await userEvent.click(loginButton);
await expect(loginButton).not.toBeInTheDocument();
const logoutButton = canvas.getByRole('button', { name: /Log out/i });
await expect(logoutButton).toBeInTheDocument();
},
};

View File

@@ -0,0 +1,73 @@
import React from 'react';
import { Header } from './Header';
import './page.css';
type User = {
name: string;
};
export const Page: React.FC = () => {
const [user, setUser] = React.useState<User>();
return (
<article>
<Header
user={user}
onLogin={() => setUser({ name: 'Jane Doe' })}
onLogout={() => setUser(undefined)}
onCreateAccount={() => setUser({ name: 'Jane Doe' })}
/>
<section className="storybook-page">
<h2>Pages in Storybook</h2>
<p>
We recommend building UIs with a{' '}
<a href="https://componentdriven.org" target="_blank" rel="noopener noreferrer">
<strong>component-driven</strong>
</a>{' '}
process starting with atomic components and ending with pages.
</p>
<p>
Render pages with mock data. This makes it easy to build and review page states without
needing to navigate to them in your app. Here are some handy patterns for managing page
data in Storybook:
</p>
<ul>
<li>
Use a higher-level connected component. Storybook helps you compose such data from the
"args" of child component stories
</li>
<li>
Assemble data in the page component from your services. You can mock these services out
using Storybook.
</li>
</ul>
<p>
Get a guided tutorial on component-driven development at{' '}
<a href="https://storybook.js.org/tutorials/" target="_blank" rel="noopener noreferrer">
Storybook tutorials
</a>
. Read more in the{' '}
<a href="https://storybook.js.org/docs" target="_blank" rel="noopener noreferrer">
docs
</a>
.
</p>
<div className="tip-wrapper">
<span className="tip">Tip</span> Adjust the width of the canvas with the{' '}
<svg width="10" height="10" viewBox="0 0 12 12" xmlns="http://www.w3.org/2000/svg">
<g fill="none" fillRule="evenodd">
<path
d="M1.5 5.2h4.8c.3 0 .5.2.5.4v5.1c-.1.2-.3.3-.4.3H1.4a.5.5 0 01-.5-.4V5.7c0-.3.2-.5.5-.5zm0-2.1h6.9c.3 0 .5.2.5.4v7a.5.5 0 01-1 0V4H1.5a.5.5 0 010-1zm0-2.1h9c.3 0 .5.2.5.4v9.1a.5.5 0 01-1 0V2H1.5a.5.5 0 010-1zm4.3 5.2H2V10h3.8V6.2z"
id="a"
fill="#999"
/>
</g>
</svg>
Viewports addon in the toolbar
</div>
</section>
</article>
);
};

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" fill="none" viewBox="0 0 48 48"><title>Accessibility</title><circle cx="24.334" cy="24" r="24" fill="#A849FF" fill-opacity=".3"/><path fill="#A470D5" fill-rule="evenodd" d="M27.8609 11.585C27.8609 9.59506 26.2497 7.99023 24.2519 7.99023C22.254 7.99023 20.6429 9.65925 20.6429 11.585C20.6429 13.575 22.254 15.1799 24.2519 15.1799C26.2497 15.1799 27.8609 13.575 27.8609 11.585ZM21.8922 22.6473C21.8467 23.9096 21.7901 25.4788 21.5897 26.2771C20.9853 29.0462 17.7348 36.3314 17.3325 37.2275C17.1891 37.4923 17.1077 37.7955 17.1077 38.1178C17.1077 39.1519 17.946 39.9902 18.9802 39.9902C19.6587 39.9902 20.253 39.6293 20.5814 39.0889L20.6429 38.9874L24.2841 31.22C24.2841 31.22 27.5529 37.9214 27.9238 38.6591C28.2948 39.3967 28.8709 39.9902 29.7168 39.9902C30.751 39.9902 31.5893 39.1519 31.5893 38.1178C31.5893 37.7951 31.3639 37.2265 31.3639 37.2265C30.9581 36.3258 27.698 29.0452 27.0938 26.2771C26.8975 25.4948 26.847 23.9722 26.8056 22.7236C26.7927 22.333 26.7806 21.9693 26.7653 21.6634C26.7008 21.214 27.0231 20.8289 27.4097 20.7005L35.3366 18.3253C36.3033 18.0685 36.8834 16.9773 36.6256 16.0144C36.3678 15.0515 35.2722 14.4737 34.3055 14.7305C34.3055 14.7305 26.8619 17.1057 24.2841 17.1057C21.7062 17.1057 14.456 14.7947 14.456 14.7947C13.4893 14.5379 12.3937 14.9873 12.0715 15.9502C11.7493 16.9131 12.3293 18.0044 13.3604 18.3253L21.2873 20.7005C21.674 20.8289 21.9318 21.214 21.9318 21.6634C21.9174 21.9493 21.9053 22.2857 21.8922 22.6473Z" clip-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 456 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 829 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="33" height="32" fill="none" viewBox="0 0 33 32"><g clip-path="url(#clip0_10031_177575)"><mask id="mask0_10031_177575" style="mask-type:luminance" width="33" height="25" x="0" y="4" maskUnits="userSpaceOnUse"><path fill="#fff" d="M32.5034 4.00195H0.503906V28.7758H32.5034V4.00195Z"/></mask><g mask="url(#mask0_10031_177575)"><path fill="#5865F2" d="M27.5928 6.20817C25.5533 5.27289 23.3662 4.58382 21.0794 4.18916C21.0378 4.18154 20.9962 4.20057 20.9747 4.23864C20.6935 4.73863 20.3819 5.3909 20.1637 5.90358C17.7042 5.53558 15.2573 5.53558 12.8481 5.90358C12.6299 5.37951 12.307 4.73863 12.0245 4.23864C12.003 4.20184 11.9614 4.18281 11.9198 4.18916C9.63431 4.58255 7.44721 5.27163 5.40641 6.20817C5.38874 6.21578 5.3736 6.22848 5.36355 6.24497C1.21508 12.439 0.078646 18.4809 0.636144 24.4478C0.638667 24.477 0.655064 24.5049 0.677768 24.5227C3.41481 26.5315 6.06609 27.7511 8.66815 28.5594C8.70979 28.5721 8.75392 28.5569 8.78042 28.5226C9.39594 27.6826 9.94461 26.7968 10.4151 25.8653C10.4428 25.8107 10.4163 25.746 10.3596 25.7244C9.48927 25.3945 8.66058 24.9922 7.86343 24.5354C7.80038 24.4986 7.79533 24.4084 7.85333 24.3653C8.02108 24.2397 8.18888 24.109 8.34906 23.977C8.37804 23.9529 8.41842 23.9478 8.45249 23.963C13.6894 26.3526 19.359 26.3526 24.5341 23.963C24.5682 23.9465 24.6086 23.9516 24.6388 23.9757C24.799 24.1077 24.9668 24.2397 25.1358 24.3653C25.1938 24.4084 25.19 24.4986 25.127 24.5354C24.3298 25.0011 23.5011 25.3945 22.6296 25.7232C22.5728 25.7447 22.5476 25.8107 22.5754 25.8653C23.0559 26.7955 23.6046 27.6812 24.2087 28.5213C24.234 28.5569 24.2794 28.5721 24.321 28.5594C26.9357 27.7511 29.5869 26.5315 32.324 24.5227C32.348 24.5049 32.3631 24.4783 32.3656 24.4491C33.0328 17.5506 31.2481 11.5584 27.6344 6.24623C27.6256 6.22848 27.6105 6.21578 27.5928 6.20817ZM11.1971 20.8146C9.62043 20.8146 8.32129 19.3679 8.32129 17.5913C8.32129 15.8146 9.59523 14.368 11.1971 14.368C12.8115 14.368 14.0981 15.8273 14.0729 17.5913C14.0729 19.3679 12.7989 20.8146 11.1971 20.8146ZM21.8299 20.8146C20.2533 20.8146 18.9541 19.3679 18.9541 17.5913C18.9541 15.8146 20.228 14.368 21.8299 14.368C23.4444 14.368 24.7309 15.8273 24.7057 17.5913C24.7057 19.3679 23.4444 20.8146 21.8299 20.8146Z"/></g></g><defs><clipPath id="clip0_10031_177575"><rect width="32" height="32" fill="#fff" transform="translate(0.5)"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" fill="none" viewBox="0 0 32 32"><path fill="#161614" d="M16.0001 0C7.16466 0 0 7.17472 0 16.0256C0 23.1061 4.58452 29.1131 10.9419 31.2322C11.7415 31.3805 12.0351 30.8845 12.0351 30.4613C12.0351 30.0791 12.0202 28.8167 12.0133 27.4776C7.56209 28.447 6.62283 25.5868 6.62283 25.5868C5.89499 23.7345 4.8463 23.2419 4.8463 23.2419C3.39461 22.2473 4.95573 22.2678 4.95573 22.2678C6.56242 22.3808 7.40842 23.9192 7.40842 23.9192C8.83547 26.3691 11.1514 25.6609 12.0645 25.2514C12.2081 24.2156 12.6227 23.5087 13.0803 23.1085C9.52648 22.7032 5.7906 21.3291 5.7906 15.1886C5.7906 13.4389 6.41563 12.0094 7.43916 10.8871C7.27303 10.4834 6.72537 8.85349 7.59415 6.64609C7.59415 6.64609 8.93774 6.21539 11.9953 8.28877C13.2716 7.9337 14.6404 7.75563 16.0001 7.74953C17.3599 7.75563 18.7297 7.9337 20.0084 8.28877C23.0623 6.21539 24.404 6.64609 24.404 6.64609C25.2749 8.85349 24.727 10.4834 24.5608 10.8871C25.5868 12.0094 26.2075 13.4389 26.2075 15.1886C26.2075 21.3437 22.4645 22.699 18.9017 23.0957C19.4756 23.593 19.9869 24.5683 19.9869 26.0634C19.9869 28.2077 19.9684 29.9334 19.9684 30.4613C19.9684 30.8877 20.2564 31.3874 21.0674 31.2301C27.4213 29.1086 32 23.1037 32 16.0256C32 7.17472 24.8364 0 16.0001 0ZM5.99257 22.8288C5.95733 22.9084 5.83227 22.9322 5.71834 22.8776C5.60229 22.8253 5.53711 22.7168 5.57474 22.6369C5.60918 22.5549 5.7345 22.5321 5.85029 22.587C5.9666 22.6393 6.03284 22.7489 5.99257 22.8288ZM6.7796 23.5321C6.70329 23.603 6.55412 23.5701 6.45291 23.4581C6.34825 23.3464 6.32864 23.197 6.40601 23.125C6.4847 23.0542 6.62937 23.0874 6.73429 23.1991C6.83895 23.3121 6.85935 23.4605 6.7796 23.5321ZM7.31953 24.4321C7.2215 24.5003 7.0612 24.4363 6.96211 24.2938C6.86407 24.1513 6.86407 23.9804 6.96422 23.9119C7.06358 23.8435 7.2215 23.905 7.32191 24.0465C7.41968 24.1914 7.41968 24.3623 7.31953 24.4321ZM8.23267 25.4743C8.14497 25.5712 7.95818 25.5452 7.82146 25.413C7.68156 25.2838 7.64261 25.1004 7.73058 25.0035C7.81934 24.9064 8.00719 24.9337 8.14497 25.0648C8.28381 25.1938 8.3262 25.3785 8.23267 25.4743ZM9.41281 25.8262C9.37413 25.9517 9.19423 26.0088 9.013 25.9554C8.83203 25.9005 8.7136 25.7535 8.75016 25.6266C8.78778 25.5003 8.96848 25.4408 9.15104 25.4979C9.33174 25.5526 9.45044 25.6985 9.41281 25.8262ZM10.7559 25.9754C10.7604 26.1076 10.6067 26.2172 10.4165 26.2196C10.2252 26.2238 10.0704 26.1169 10.0683 25.9868C10.0683 25.8534 10.2185 25.7448 10.4098 25.7416C10.6001 25.7379 10.7559 25.8441 10.7559 25.9754ZM12.0753 25.9248C12.0981 26.0537 11.9658 26.1862 11.7769 26.2215C11.5912 26.2554 11.4192 26.1758 11.3957 26.0479C11.3726 25.9157 11.5072 25.7833 11.6927 25.7491C11.8819 25.7162 12.0512 25.7937 12.0753 25.9248Z"/></svg>

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="33" height="32" fill="none" viewBox="0 0 33 32"><g clip-path="url(#clip0_10031_177597)"><path fill="#B7F0EF" fill-rule="evenodd" d="M17 7.87059C17 6.48214 17.9812 5.28722 19.3431 5.01709L29.5249 2.99755C31.3238 2.64076 33 4.01717 33 5.85105V22.1344C33 23.5229 32.0188 24.7178 30.6569 24.9879L20.4751 27.0074C18.6762 27.3642 17 25.9878 17 24.1539L17 7.87059Z" clip-rule="evenodd" opacity=".7"/><path fill="#87E6E5" fill-rule="evenodd" d="M1 5.85245C1 4.01857 2.67623 2.64215 4.47507 2.99895L14.6569 5.01848C16.0188 5.28861 17 6.48354 17 7.87198V24.1553C17 25.9892 15.3238 27.3656 13.5249 27.0088L3.34311 24.9893C1.98119 24.7192 1 23.5242 1 22.1358V5.85245Z" clip-rule="evenodd"/><path fill="#61C1FD" fill-rule="evenodd" d="M15.543 5.71289C15.543 5.71289 16.8157 5.96289 17.4002 6.57653C17.9847 7.19016 18.4521 9.03107 18.4521 9.03107C18.4521 9.03107 18.4521 25.1106 18.4521 26.9629C18.4521 28.8152 19.3775 31.4174 19.3775 31.4174L17.4002 28.8947L16.2575 31.4174C16.2575 31.4174 15.543 29.0765 15.543 27.122C15.543 25.1674 15.543 5.71289 15.543 5.71289Z" clip-rule="evenodd"/></g><defs><clipPath id="clip0_10031_177597"><rect width="32" height="32" fill="#fff" transform="translate(0.5)"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.2 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" fill="none" viewBox="0 0 32 32"><path fill="#ED1D24" d="M31.3313 8.44657C30.9633 7.08998 29.8791 6.02172 28.5022 5.65916C26.0067 5.00026 16 5.00026 16 5.00026C16 5.00026 5.99333 5.00026 3.4978 5.65916C2.12102 6.02172 1.03665 7.08998 0.668678 8.44657C0 10.9053 0 16.0353 0 16.0353C0 16.0353 0 21.1652 0.668678 23.6242C1.03665 24.9806 2.12102 26.0489 3.4978 26.4116C5.99333 27.0703 16 27.0703 16 27.0703C16 27.0703 26.0067 27.0703 28.5022 26.4116C29.8791 26.0489 30.9633 24.9806 31.3313 23.6242C32 21.1652 32 16.0353 32 16.0353C32 16.0353 32 10.9053 31.3313 8.44657Z"/><path fill="#fff" d="M12.7266 20.6934L21.0902 16.036L12.7266 11.3781V20.6934Z"/></svg>

After

Width:  |  Height:  |  Size: 716 B

View File

@@ -0,0 +1,30 @@
.storybook-button {
display: inline-block;
cursor: pointer;
border: 0;
border-radius: 3em;
font-weight: 700;
line-height: 1;
font-family: 'Nunito Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
}
.storybook-button--primary {
background-color: #555ab9;
color: white;
}
.storybook-button--secondary {
box-shadow: rgba(0, 0, 0, 0.15) 0px 0px 0px 1px inset;
background-color: transparent;
color: #333;
}
.storybook-button--small {
padding: 10px 16px;
font-size: 12px;
}
.storybook-button--medium {
padding: 11px 20px;
font-size: 14px;
}
.storybook-button--large {
padding: 12px 24px;
font-size: 16px;
}

View File

@@ -0,0 +1,32 @@
.storybook-header {
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
padding: 15px 20px;
font-family: 'Nunito Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
}
.storybook-header svg {
display: inline-block;
vertical-align: top;
}
.storybook-header h1 {
display: inline-block;
vertical-align: top;
margin: 6px 0 6px 10px;
font-weight: 700;
font-size: 20px;
line-height: 1;
}
.storybook-header button + button {
margin-left: 10px;
}
.storybook-header .welcome {
margin-right: 10px;
color: #333;
font-size: 14px;
}

View File

@@ -0,0 +1,68 @@
.storybook-page {
margin: 0 auto;
padding: 48px 20px;
max-width: 600px;
color: #333;
font-size: 14px;
line-height: 24px;
font-family: 'Nunito Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
}
.storybook-page h2 {
display: inline-block;
vertical-align: top;
margin: 0 0 4px;
font-weight: 700;
font-size: 32px;
line-height: 1;
}
.storybook-page p {
margin: 1em 0;
}
.storybook-page a {
color: inherit;
}
.storybook-page ul {
margin: 1em 0;
padding-left: 30px;
}
.storybook-page li {
margin-bottom: 8px;
}
.storybook-page .tip {
display: inline-block;
vertical-align: top;
margin-right: 10px;
border-radius: 1em;
background: #e7fdd8;
padding: 4px 12px;
color: #357a14;
font-weight: 700;
font-size: 11px;
line-height: 12px;
}
.storybook-page .tip-wrapper {
margin-top: 40px;
margin-bottom: 40px;
font-size: 13px;
line-height: 20px;
}
.storybook-page .tip-wrapper svg {
display: inline-block;
vertical-align: top;
margin-top: 3px;
margin-right: 4px;
width: 12px;
height: 12px;
}
.storybook-page .tip-wrapper svg path {
fill: #1ea7fd;
}

View File

@@ -0,0 +1,183 @@
// Tutorial system type definitions
export interface TutorialStep {
id: string
title: string
problem: string
description: string
startValue: number
targetValue: number
highlightBeads?: Array<{
columnIndex: number
beadType: 'heaven' | 'earth'
position?: number // for earth beads, 0-3
}>
expectedAction: 'add' | 'remove' | 'multi-step'
actionDescription: string
tooltip: {
content: string
explanation: string
}
errorMessages: {
wrongBead: string
wrongAction: string
hint: string
}
multiStepInstructions?: string[]
}
export interface PracticeStep {
id: string
title: string
description: string
skillLevel: 'basic' | 'heaven' | 'five-complements' | 'mixed'
problemCount: number
maxTerms: number // max numbers to add in a single problem
}
export interface Problem {
id: string
terms: number[]
userAnswer?: number
isCorrect?: boolean
}
export interface Tutorial {
id: string
title: string
description: string
category: string
difficulty: 'beginner' | 'intermediate' | 'advanced'
estimatedDuration: number // in minutes
steps: TutorialStep[]
practiceSteps?: PracticeStep[]
tags: string[]
author: string
version: string
createdAt: Date
updatedAt: Date
isPublished: boolean
}
export interface TutorialProgress {
tutorialId: string
userId?: string
currentStepIndex: number
completedSteps: string[] // step ids
startedAt: Date
lastAccessedAt: Date
completedAt?: Date
score?: number
timeSpent: number // in seconds
}
export interface TutorialSession {
id: string
tutorial: Tutorial
progress: TutorialProgress
currentStep: TutorialStep
isDebugMode: boolean
debugHistory: Array<{
stepId: string
timestamp: Date
action: string
value: number
success: boolean
}>
}
// Editor specific types
export interface TutorialTemplate {
name: string
description: string
defaultSteps: Partial<TutorialStep>[]
}
export interface StepValidationError {
stepId: string
field: string
message: string
severity: 'error' | 'warning'
}
export interface TutorialValidation {
isValid: boolean
errors: StepValidationError[]
warnings: StepValidationError[]
}
// Access control types (future-ready)
export interface UserRole {
id: string
name: string
permissions: Permission[]
}
export interface Permission {
resource: 'tutorial' | 'step' | 'user' | 'system'
actions: ('create' | 'read' | 'update' | 'delete' | 'publish')[]
conditions?: Record<string, any>
}
export interface AccessContext {
userId?: string
roles: UserRole[]
isAuthenticated: boolean
isAdmin: boolean
canEdit: boolean
canPublish: boolean
canDelete: boolean
}
// Navigation and UI state types
export interface NavigationState {
currentStepIndex: number
canGoNext: boolean
canGoPrevious: boolean
totalSteps: number
completionPercentage: number
}
export interface UIState {
isPlaying: boolean
isPaused: boolean
isEditing: boolean
showDebugPanel: boolean
showStepList: boolean
autoAdvance: boolean
playbackSpeed: number
}
// Event types for tutorial interaction
export type TutorialEvent =
| { type: 'STEP_STARTED'; stepId: string; timestamp: Date }
| { type: 'STEP_COMPLETED'; stepId: string; success: boolean; timestamp: Date }
| { type: 'BEAD_CLICKED'; stepId: string; beadInfo: any; timestamp: Date }
| { type: 'VALUE_CHANGED'; stepId: string; oldValue: number; newValue: number; timestamp: Date }
| { type: 'ERROR_OCCURRED'; stepId: string; error: string; timestamp: Date }
| { type: 'TUTORIAL_COMPLETED'; tutorialId: string; score: number; timestamp: Date }
| { type: 'TUTORIAL_ABANDONED'; tutorialId: string; lastStepId: string; timestamp: Date }
// API response types
export interface TutorialListResponse {
tutorials: Tutorial[]
total: number
page: number
limit: number
hasMore: boolean
}
export interface TutorialDetailResponse {
tutorial: Tutorial
userProgress?: TutorialProgress
canEdit: boolean
canDelete: boolean
}
export interface SaveTutorialRequest {
tutorial: Omit<Tutorial, 'id' | 'createdAt' | 'updatedAt'>
}
export interface SaveTutorialResponse {
tutorial: Tutorial
validation: TutorialValidation
}

View File

@@ -0,0 +1,345 @@
// Utility to extract and convert the existing GuidedAdditionTutorial data
import { Tutorial, TutorialStep as NewTutorialStep } from '../types/tutorial'
// Import the existing tutorial step interface to match the current structure
interface ExistingTutorialStep {
id: string
title: string
problem: string
description: string
startValue: number
targetValue: number
highlightBeads?: Array<{
columnIndex: number
beadType: 'heaven' | 'earth'
position?: number
}>
expectedAction: 'add' | 'remove' | 'multi-step'
actionDescription: string
tooltip: {
content: string
explanation: string
}
errorMessages: {
wrongBead: string
wrongAction: string
hint: string
}
multiStepInstructions?: string[]
}
// The tutorial steps from GuidedAdditionTutorial.tsx (extracted from the actual file)
export const guidedAdditionSteps: ExistingTutorialStep[] = [
// Phase 1: Basic Addition (1-4)
{
id: 'basic-1',
title: 'Basic Addition: 0 + 1',
problem: '0 + 1',
description: 'Start by adding your first earth bead',
startValue: 0,
targetValue: 1,
highlightBeads: [{ columnIndex: 0, beadType: 'earth', position: 0 }],
expectedAction: 'add',
actionDescription: 'Click the first earth bead to move it up',
tooltip: {
content: 'Adding earth beads',
explanation: 'Earth beads (bottom) are worth 1 each. Push them UP to activate them.'
},
errorMessages: {
wrongBead: 'Click the highlighted earth bead at the bottom',
wrongAction: 'Move the bead UP to add it',
hint: 'Earth beads move up when adding numbers 1-4'
}
},
{
id: 'basic-2',
title: 'Basic Addition: 1 + 1',
problem: '1 + 1',
description: 'Add the second earth bead to make 2',
startValue: 1,
targetValue: 2,
highlightBeads: [{ columnIndex: 0, beadType: 'earth', position: 1 }],
expectedAction: 'add',
actionDescription: 'Click the second earth bead to move it up',
tooltip: {
content: 'Building up earth beads',
explanation: 'Continue adding earth beads one by one for numbers 2, 3, and 4'
},
errorMessages: {
wrongBead: 'Click the highlighted earth bead',
wrongAction: 'Move the bead UP to add it',
hint: 'You need 2 earth beads for the number 2'
}
},
{
id: 'basic-3',
title: 'Basic Addition: 2 + 1',
problem: '2 + 1',
description: 'Add the third earth bead to make 3',
startValue: 2,
targetValue: 3,
highlightBeads: [{ columnIndex: 0, beadType: 'earth', position: 2 }],
expectedAction: 'add',
actionDescription: 'Click the third earth bead to move it up',
tooltip: {
content: 'Adding earth beads in sequence',
explanation: 'Continue adding earth beads one by one until you reach 4'
},
errorMessages: {
wrongBead: 'Click the highlighted earth bead',
wrongAction: 'Move the bead UP to add it',
hint: 'You need 3 earth beads for the number 3'
}
},
{
id: 'basic-4',
title: 'Basic Addition: 3 + 1',
problem: '3 + 1',
description: 'Add the fourth earth bead to make 4',
startValue: 3,
targetValue: 4,
highlightBeads: [{ columnIndex: 0, beadType: 'earth', position: 3 }],
expectedAction: 'add',
actionDescription: 'Click the fourth earth bead to complete 4',
tooltip: {
content: 'Maximum earth beads',
explanation: 'Four earth beads is the maximum - next we need a different approach'
},
errorMessages: {
wrongBead: 'Click the highlighted earth bead',
wrongAction: 'Move the bead UP to add it',
hint: 'Four earth beads represent the number 4'
}
},
// Phase 2: Introduction to Heaven Bead
{
id: 'heaven-intro',
title: 'Heaven Bead: 0 + 5',
problem: '0 + 5',
description: 'Use the heaven bead to represent 5',
startValue: 0,
targetValue: 5,
highlightBeads: [{ columnIndex: 0, beadType: 'heaven' }],
expectedAction: 'add',
actionDescription: 'Click the heaven bead to activate it',
tooltip: {
content: 'Heaven bead = 5',
explanation: 'The single bead above the bar represents 5'
},
errorMessages: {
wrongBead: 'Click the heaven bead at the top',
wrongAction: 'Move the heaven bead DOWN to activate it',
hint: 'The heaven bead is worth 5 points'
}
},
{
id: 'heaven-plus-earth',
title: 'Combining: 5 + 1',
problem: '5 + 1',
description: 'Add 1 to 5 by activating one earth bead',
startValue: 5,
targetValue: 6,
highlightBeads: [{ columnIndex: 0, beadType: 'earth', position: 0 }],
expectedAction: 'add',
actionDescription: 'Click the first earth bead to make 6',
tooltip: {
content: 'Heaven + Earth = 6',
explanation: 'When you have room in the earth section, simply add directly'
},
errorMessages: {
wrongBead: 'Click the first earth bead',
wrongAction: 'Move the earth bead UP to add it',
hint: 'With the heaven bead active, add earth beads for 6, 7, 8, 9'
}
},
// Phase 3: Five Complements (when earth section is full)
{
id: 'complement-intro',
title: 'Five Complement: 3 + 4',
problem: '3 + 4',
description: 'Need to add 4, but only have 1 earth bead space. Use complement: 4 = 5 - 1',
startValue: 3,
targetValue: 7,
highlightBeads: [
{ columnIndex: 0, beadType: 'heaven' },
{ columnIndex: 0, beadType: 'earth', position: 0 }
],
expectedAction: 'multi-step',
actionDescription: 'First add heaven bead (5), then remove 1 earth bead',
multiStepInstructions: [
'Click the heaven bead to add 5',
'Click the first earth bead to remove 1'
],
tooltip: {
content: 'Five Complement: 4 = 5 - 1',
explanation: 'When you need to add 4 but only have 1 space, use: add 5, remove 1'
},
errorMessages: {
wrongBead: 'Follow the two-step process: heaven bead first, then remove earth bead',
wrongAction: 'Add heaven bead, then remove earth bead',
hint: 'Complement thinking: 4 = 5 - 1, so add 5 and take away 1'
}
},
{
id: 'complement-2',
title: 'Five Complement: 2 + 3',
problem: '2 + 3',
description: 'Add 3 to make 5 by using complement: 3 = 5 - 2',
startValue: 2,
targetValue: 5,
highlightBeads: [
{ columnIndex: 0, beadType: 'heaven' },
{ columnIndex: 0, beadType: 'earth', position: 0 },
{ columnIndex: 0, beadType: 'earth', position: 1 }
],
expectedAction: 'multi-step',
actionDescription: 'Add heaven bead (5), then remove 2 earth beads',
multiStepInstructions: [
'Click the heaven bead to add 5',
'Click the first earth bead to remove it',
'Click the second earth bead to remove it'
],
tooltip: {
content: 'Five Complement: 3 = 5 - 2',
explanation: 'To add 3, think: 3 = 5 - 2, so add 5 and take away 2'
},
errorMessages: {
wrongBead: 'Follow the multi-step process: add heaven, then remove earth beads',
wrongAction: 'Add heaven bead first, then remove the necessary earth beads',
hint: 'Complement: 3 = 5 - 2, so add heaven and remove 2 earth'
}
},
// Phase 4: More complex combinations
{
id: 'complex-1',
title: 'Complex: 6 + 2',
problem: '6 + 2',
description: 'Add 2 more to 6 (which has heaven + 1 earth)',
startValue: 6,
targetValue: 8,
highlightBeads: [
{ columnIndex: 0, beadType: 'earth', position: 1 },
{ columnIndex: 0, beadType: 'earth', position: 2 }
],
expectedAction: 'add',
actionDescription: 'Add two more earth beads',
tooltip: {
content: 'Direct addition when possible',
explanation: 'When you have space in the earth section, just add directly'
},
errorMessages: {
wrongBead: 'Click the next earth beads in sequence',
wrongAction: 'Move the earth beads UP to add them',
hint: 'You have room for 2 more earth beads'
}
},
{
id: 'complex-2',
title: 'Complex: 7 + 4',
problem: '7 + 4',
description: 'Add 4 to 7, but no room for 4 earth beads. Use complement again',
startValue: 7,
targetValue: 11,
highlightBeads: [
{ columnIndex: 1, beadType: 'heaven' },
{ columnIndex: 0, beadType: 'earth', position: 0 },
{ columnIndex: 0, beadType: 'earth', position: 1 }
],
expectedAction: 'multi-step',
actionDescription: 'This will move to tens place: activate left heaven, remove 3 earth',
multiStepInstructions: [
'Click the heaven bead in the tens column (left)',
'Click the first earth bead to remove it',
'Click the second earth bead to remove it'
],
tooltip: {
content: 'Carrying to tens place',
explanation: '7 + 4 = 11, which needs the tens column heaven bead'
},
errorMessages: {
wrongBead: 'Work with the tens column (left side) and remove earth beads',
wrongAction: 'Activate tens heaven, then remove earth beads from ones',
hint: '11 = 10 + 1, so activate tens heaven and adjust ones'
}
}
]
// Convert the existing tutorial format to our new format
export function convertGuidedAdditionTutorial(): Tutorial {
const tutorial: Tutorial = {
id: 'guided-addition-tutorial',
title: 'Guided Addition Tutorial',
description: 'Learn basic addition on the soroban abacus, from simple earth bead movements to five complements and carrying',
category: 'Basic Operations',
difficulty: 'beginner',
estimatedDuration: 20, // minutes
steps: guidedAdditionSteps,
tags: ['addition', 'basic', 'earth beads', 'heaven beads', 'complements', 'carrying'],
author: 'Soroban Abacus System',
version: '1.0.0',
createdAt: new Date('2024-01-01'),
updatedAt: new Date(),
isPublished: true
}
return tutorial
}
// Helper to validate that the existing tutorial steps work with our new interfaces
export function validateTutorialConversion(): { isValid: boolean; errors: string[] } {
const errors: string[] = []
try {
const tutorial = convertGuidedAdditionTutorial()
// Basic validation
if (!tutorial.id || !tutorial.title || !tutorial.steps.length) {
errors.push('Missing required tutorial fields')
}
// Validate each step
tutorial.steps.forEach((step, index) => {
if (!step.id || !step.title || !step.problem) {
errors.push(`Step ${index + 1}: Missing required fields`)
}
if (typeof step.startValue !== 'number' || typeof step.targetValue !== 'number') {
errors.push(`Step ${index + 1}: Invalid start or target value`)
}
if (!step.tooltip?.content || !step.tooltip?.explanation) {
errors.push(`Step ${index + 1}: Missing tooltip content`)
}
if (!step.errorMessages?.wrongBead || !step.errorMessages?.wrongAction || !step.errorMessages?.hint) {
errors.push(`Step ${index + 1}: Missing error messages`)
}
if (step.expectedAction === 'multi-step' && (!step.multiStepInstructions || step.multiStepInstructions.length === 0)) {
errors.push(`Step ${index + 1}: Multi-step action missing instructions`)
}
})
} catch (error) {
errors.push(`Conversion failed: ${error}`)
}
return {
isValid: errors.length === 0,
errors
}
}
// Helper to export tutorial data for use in the editor
export function getTutorialForEditor(): Tutorial {
const validation = validateTutorialConversion()
if (!validation.isValid) {
console.warn('Tutorial validation errors:', validation.errors)
}
return convertGuidedAdditionTutorial()
}