Skip to content

Visual UI for Explainroo. Explainer videos and product demos made by your AI agent. Free and open source: a local voice (Kokoro), word timing (Whisper) and a canvas renderer turn a script into a narrated MP4.

Add files via upload

jastfan97955441b2d9
diff --git a/src/App.tsx b/src/App.tsx
new file mode 100644
index 0000000..ef620b1
--- /dev/null
+++ b/src/App.tsx
@@ -0,0 +1,423 @@
+import React, { useState, useEffect } from 'react';
+import { Project, Scene, VisualElement, ThemeLook, THEME_CONFIGS } from './types/explainroo';
+import { PREBUILT_TEMPLATES } from './templates/prebuiltTemplates';
+import { Navbar } from './components/explainroo/Navbar';
+import { VideoPlayer } from './components/explainroo/VideoPlayer';
+import { SceneList } from './components/explainroo/SceneList';
+import { ScriptEditor } from './components/explainroo/ScriptEditor';
+import { VisualToolbox } from './components/explainroo/VisualToolbox';
+import { ElementInspector } from './components/explainroo/ElementInspector';
+import { AIGeneratorModal } from './components/explainroo/AIGeneratorModal';
+import { ExportModal } from './components/explainroo/ExportModal';
+import { TemplatesModal } from './components/explainroo/TemplatesModal';
+import { audioEngine } from './utils/audioEngine';
+
+export const App: React.FC = () => {
+ // Load initial project from localStorage or default template
+ const [project, setProject] = useState<Project>(() => {
+ try {
+ const saved = localStorage.getItem('explainroo_project');
+ if (saved) {
+ return JSON.parse(saved);
+ }
+ } catch {
+ // Fallback
+ }
+ return PREBUILT_TEMPLATES[0];
+ });
+
+ const [activeSceneIndex, setActiveSceneIndex] = useState<number>(0);
+ const [selectedElementId, setSelectedElementId] = useState<string | null>(null);
+
+ // Modals
+ const [showAiModal, setShowAiModal] = useState<boolean>(false);
+ const [showTemplatesModal, setShowTemplatesModal] = useState<boolean>(false);
+ const [showExportModal, setShowExportModal] = useState<boolean>(false);
+
+ // Persist project changes
+ useEffect(() => {
+ try {
+ localStorage.setItem('explainroo_project', JSON.stringify(project));
+ } catch {
+ // Ignore quota errors
+ }
+ }, [project]);
+
+ // Safe active scene
+ const activeScene: Scene =
+ project.scenes[activeSceneIndex] || project.scenes[0] || {
+ id: 'scene-default',
+ title: 'Scene 1',
+ narration: '',
+ elements: [],
+ durationSeconds: 7,
+ };
+
+ const selectedElement =
+ activeScene.elements.find((el) => el.id === selectedElementId) || null;
+
+ // Active theme look config
+ const activeThemeLook = activeScene.lookOverride || project.look;
+ const themeConfig = THEME_CONFIGS[activeThemeLook] || THEME_CONFIGS.whiteboard;
+
+ // Handlers for Project & Scenes
+ const handleUpdateTitle = (title: string) => {
+ setProject((prev) => ({ ...prev, title }));
+ };
+
+ const handleSelectLook = (look: ThemeLook) => {
+ setProject((prev) => ({ ...prev, look }));
+ audioEngine.playPop();
+ };
+
+ const handleSelectScene = (index: number) => {
+ if (index >= 0 && index < project.scenes.length) {
+ setActiveSceneIndex(index);
+ setSelectedElementId(null);
+ audioEngine.playWhoosh();
+ }
+ };
+
+ const handleAddScene = () => {
+ const newSceneNum = project.scenes.length + 1;
+ const newScene: Scene = {
+ id: `scene-${Date.now()}`,
+ title: `Scene ${newSceneNum}`,
+ narration: 'Describe what happens next in this part of the video...',
+ durationSeconds: 7,
+ transition: 'fade',
+ elements: [],
+ };
+
+ setProject((prev) => ({
+ ...prev,
+ scenes: [...prev.scenes, newScene],
+ }));
+ setActiveSceneIndex(project.scenes.length);
+ setSelectedElementId(null);
+ audioEngine.playPop();
+ };
+
+ const handleDuplicateScene = (index: number) => {
+ const target = project.scenes[index];
+ if (!target) return;
+
+ const dupScene: Scene = {
+ ...target,
+ id: `scene-${Date.now()}`,
+ title: `${target.title} (Copy)`,
+ elements: target.elements.map((el) => ({ ...el, id: `el-${Date.now()}-${Math.random()}` })),
+ };
+
+ const updated = [...project.scenes];
+ updated.splice(index + 1, 0, dupScene);
+ setProject((prev) => ({ ...prev, scenes: updated }));
+ setActiveSceneIndex(index + 1);
+ audioEngine.playPop();
+ };
+
+ const handleDeleteScene = (index: number) => {
+ if (project.scenes.length <= 1) return;
+ const updated = project.scenes.filter((_, idx) => idx !== index);
+ setProject((prev) => ({ ...prev, scenes: updated }));
+ setActiveSceneIndex(Math.max(0, index - 1));
+ setSelectedElementId(null);
+ audioEngine.playPop();
+ };
+
+ const handleMoveScene = (index: number, direction: 'prev' | 'next') => {
+ const targetIdx = direction === 'prev' ? index - 1 : index + 1;
+ if (targetIdx < 0 || targetIdx >= project.scenes.length) return;
+
+ const updated = [...project.scenes];
+ const [moved] = updated.splice(index, 1);
+ updated.splice(targetIdx, 0, moved);
+
+ setProject((prev) => ({ ...prev, scenes: updated }));
+ setActiveSceneIndex(targetIdx);
+ audioEngine.playPop();
+ };
+
+ // Handlers for Elements
+ const handleAddElement = (elementPartial: Partial<VisualElement>) => {
+ const newEl: VisualElement = {
+ id: `el-${Date.now()}`,
+ type: elementPartial.type || 'rectangle',
+ x: elementPartial.x ?? 540,
+ y: elementPartial.y ?? 300,
+ width: elementPartial.width ?? 180,
+ height: elementPartial.height ?? 120,
+ label: elementPartial.label || '',
+ color: elementPartial.color || themeConfig.primaryColor,
+ strokeWidth: elementPartial.strokeWidth ?? 2.5,
+ roughness: elementPartial.roughness ?? 1.4,
+ animation: elementPartial.animation || 'pop',
+ triggerTimeSec: elementPartial.triggerTimeSec ?? 0.5,
+ ...elementPartial,
+ };
+
+ setProject((prev) => {
+ const updatedScenes = [...prev.scenes];
+ const current = updatedScenes[activeSceneIndex];
+ if (!current) return prev;
+ updatedScenes[activeSceneIndex] = {
+ ...current,
+ elements: [...current.elements, newEl],
+ };
+ return { ...prev, scenes: updatedScenes };
+ });
+
+ setSelectedElementId(newEl.id);
+ };
+
+ const handleUpdateElement = (id: string, updates: Partial<VisualElement>) => {
+ setProject((prev) => {
+ const updatedScenes = [...prev.scenes];
+ const current = updatedScenes[activeSceneIndex];
+ if (!current) return prev;
+ updatedScenes[activeSceneIndex] = {
+ ...current,
+ elements: current.elements.map((el) => (el.id === id ? { ...el, ...updates } : el)),
+ };
+ return { ...prev, scenes: updatedScenes };
+ });
+ };
+
+ const handleUpdateElementPosition = (id: string, x: number, y: number) => {
+ handleUpdateElement(id, { x, y });
+ };
+
+ const handleDeleteElement = (id: string) => {
+ setProject((prev) => {
+ const updatedScenes = [...prev.scenes];
+ const current = updatedScenes[activeSceneIndex];
+ if (!current) return prev;
+ updatedScenes[activeSceneIndex] = {
+ ...current,
+ elements: current.elements.filter((el) => el.id !== id),
+ };
+ return { ...prev, scenes: updatedScenes };
+ });
+ setSelectedElementId(null);
+ audioEngine.playPop();
+ };
+
+ const handleDuplicateElement = (element: VisualElement) => {
+ const dup: VisualElement = {
+ ...element,
+ id: `el-${Date.now()}`,
+ x: element.x + 30,
+ y: element.y + 30,
+ };
+ handleAddElement(dup);
+ };
+
+ const handleUpdateNarration = (narration: string) => {
+ setProject((prev) => {
+ const updatedScenes = [...prev.scenes];
+ const current = updatedScenes[activeSceneIndex];
+ if (!current) return prev;
+ const wordCount = narration.split(/\s+/).filter(Boolean).length;
+ const calculatedDuration = Math.max(5, Math.round(wordCount / 2.5));
+
+ updatedScenes[activeSceneIndex] = {
+ ...current,
+ narration,
+ durationSeconds: calculatedDuration,
+ };
+ return { ...prev, scenes: updatedScenes };
+ });
+ };
+
+ const handleUpdateCustomAudio = (url?: string, filename?: string) => {
+ setProject((prev) => {
+ const updatedScenes = [...prev.scenes];
+ const current = updatedScenes[activeSceneIndex];
+ if (!current) return prev;
+ updatedScenes[activeSceneIndex] = {
+ ...current,
+ customAudioUrl: url,
+ customAudioName: filename,
+ };
+ return { ...prev, scenes: updatedScenes };
+ });
+ };
+
+ const handleUpdateElementTriggerWord = (elementId: string, word: string) => {
+ // Also estimate time based on position of word in narration
+ const words = activeScene.narration
+ .split(/\s+/)
+ .map((w) => w.toLowerCase().replace(/[^a-z0-9]/g, ''));
+ const wordIdx = words.indexOf(word.toLowerCase());
+ const estTime = wordIdx >= 0 ? Math.max(0.2, (wordIdx / words.length) * activeScene.durationSeconds) : 0.5;
+
+ handleUpdateElement(elementId, {
+ triggerWord: word,
+ triggerTimeSec: parseFloat(estTime.toFixed(1)),
+ });
+ };
+
+ const handleResetProject = () => {
+ if (window.confirm('Reset project back to default template?')) {
+ setProject(PREBUILT_TEMPLATES[0]);
+ setActiveSceneIndex(0);
+ setSelectedElementId(null);
+ }
+ };
+
+ // Keyboard Shortcuts: Space for Play/Pause, Esc for deselect
+ useEffect(() => {
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) {
+ return;
+ }
+ if (e.key === 'Escape') {
+ setSelectedElementId(null);
+ } else if (e.key === 'ArrowRight' && e.altKey) {
+ handleSelectScene(activeSceneIndex + 1);
+ } else if (e.key === 'ArrowLeft' && e.altKey) {
+ handleSelectScene(activeSceneIndex - 1);
+ }
+ };
+
+ window.addEventListener('keydown', handleKeyDown);
+ return () => window.removeEventListener('keydown', handleKeyDown);
+ }, [activeSceneIndex, project.scenes.length]);
+
+ return (
+ <div className="min-h-screen w-full flex flex-col bg-slate-950 text-slate-100 font-sans antialiased overflow-x-hidden">
+ {/* Top Studio Navbar */}
+ <Navbar
+ title={project.title}
+ onUpdateTitle={handleUpdateTitle}
+ look={project.look}
+ onSelectLook={handleSelectLook}
+ onOpenAiModal={() => setShowAiModal(true)}
+ onOpenTemplates={() => setShowTemplatesModal(true)}
+ onOpenExport={() => setShowExportModal(true)}
+ onResetProject={handleResetProject}
+ />
+
+ {/* Main Studio Workspace Grid */}
+ <main className="flex-1 max-w-7xl mx-auto w-full p-3 sm:p-4 md:p-6 grid grid-cols-1 lg:grid-cols-12 gap-4 items-start">
+ {/* Left Column (3 cols): Scene Navigation & Visual Toolbox */}
+ <div className="lg:col-span-3 flex flex-col gap-4">
+ <SceneList
+ scenes={project.scenes}
+ activeSceneIndex={activeSceneIndex}
+ onSelectScene={handleSelectScene}
+ onAddScene={handleAddScene}
+ onDuplicateScene={handleDuplicateScene}
+ onDeleteScene={handleDeleteScene}
+ onMoveScene={handleMoveScene}
+ />
+
+ <VisualToolbox
+ onAddElement={handleAddElement}
+ primaryColor={themeConfig.primaryColor}
+ />
+ </div>
+
+ {/* Center Column (6 cols): 16:9 Video Player & Spoken Narration Script */}
+ <div className="lg:col-span-6 flex flex-col gap-4">
+ <VideoPlayer
+ scene={activeScene}
+ theme={activeThemeLook}
+ selectedElementId={selectedElementId}
+ onSelectElement={(id) => setSelectedElementId(id)}
+ onUpdateElementPosition={handleUpdateElementPosition}
+ currentSceneIndex={activeSceneIndex}
+ totalScenes={project.scenes.length}
+ onPrevScene={() => handleSelectScene(activeSceneIndex - 1)}
+ onNextScene={() => handleSelectScene(activeSceneIndex + 1)}
+ musicTrack={project.musicTrack}
+ autoDuck={project.autoDuck}
+ voiceRate={project.voiceRate}
+ voicePitch={project.voicePitch}
+ />
+
+ <ScriptEditor
+ scene={activeScene}
+ selectedElementId={selectedElementId}
+ onUpdateNarration={handleUpdateNarration}
+ onUpdateElementTriggerWord={handleUpdateElementTriggerWord}
+ onUpdateCustomAudio={handleUpdateCustomAudio}
+ voiceRate={project.voiceRate}
+ voicePitch={project.voicePitch}
+ />
+ </div>
+
+ {/* Right Column (3 cols): Element Inspector */}
+ <div className="lg:col-span-3 flex flex-col gap-4">
+ <ElementInspector
+ element={selectedElement}
+ onUpdateElement={handleUpdateElement}
+ onDeleteElement={handleDeleteElement}
+ onDuplicateElement={handleDuplicateElement}
+ sceneDuration={activeScene.durationSeconds}
+ />
+
+ {/* Quick Guide Card */}
+ <div className="bg-slate-900/60 border border-slate-800/80 rounded-2xl p-4 text-xs space-y-2">
+ <span className="font-bold text-amber-400 block uppercase tracking-wider text-[10px]">
+ How Explainroo Works
+ </span>
+ <p className="text-slate-400 leading-relaxed text-[11px]">
+ 1. <strong>Write Narration</strong>: Type what the voiceover says for each scene.
+ </p>
+ <p className="text-slate-400 leading-relaxed text-[11px]">
+ 2. <strong>Add Visuals</strong>: Click items in the toolbox and position them on the 16:9 canvas.
+ </p>
+ <p className="text-slate-400 leading-relaxed text-[11px]">
+ 3. <strong>Word Sync</strong>: Click any word in the script to anchor your drawing to that moment.
+ </p>
+ <p className="text-slate-400 leading-relaxed text-[11px]">
+ 4. <strong>Export</strong>: Download the video or export the <code className="text-slate-300">script.md</code> & <code className="text-slate-300">scenes.js</code> bundle!
+ </p>
+ </div>
+ </div>
+ </main>
+
+ {/* Studio Footer */}
+ <footer className="w-full border-t border-slate-900 bg-slate-950 py-3 text-center text-xs text-slate-500">
+ <div className="max-w-7xl mx-auto px-4 flex items-center justify-between flex-wrap gap-2">
+ <div className="flex items-center gap-2">
+ <span className="font-semibold text-slate-300">Explainroo UI</span>
+ <span className="text-slate-600">·</span>
+ <span>Visual Studio for Explainer Videos & Architecture Demos</span>
+ </div>
+ <span className="font-mono text-[11px] text-slate-600">
+ [Space] Play/Pause · [Alt + ←/→] Switch Scene · [Esc] Deselect
+ </span>
+ </div>
+ </footer>
+
+ {/* Modals */}
+ <AIGeneratorModal
+ isOpen={showAiModal}
+ onClose={() => setShowAiModal(false)}
+ onProjectGenerated={(newProject) => {
+ setProject(newProject);
+ setActiveSceneIndex(0);
+ setSelectedElementId(null);
+ }}
+ />
+
+ <TemplatesModal
+ isOpen={showTemplatesModal}
+ onClose={() => setShowTemplatesModal(false)}
+ onSelectTemplate={(tmpl) => {
+ setProject(tmpl);
+ setActiveSceneIndex(0);
+ setSelectedElementId(null);
+ }}
+ />
+
+ <ExportModal
+ isOpen={showExportModal}
+ onClose={() => setShowExportModal(false)}
+ project={project}
+ />
+ </div>
+ );
+};
diff --git a/src/components/explainroo/AIGeneratorModal.tsx b/src/components/explainroo/AIGeneratorModal.tsx
new file mode 100644
index 0000000..d2fb60e
--- /dev/null
+++ b/src/components/explainroo/AIGeneratorModal.tsx
@@ -0,0 +1,241 @@
+import React, { useState } from 'react';
+import {
+ X,
+ Sparkles,
+ Github,
+ Loader2,
+} from 'lucide-react';
+import { Project, ThemeLook, THEME_CONFIGS } from '../../types/explainroo';
+import { audioEngine } from '../../utils/audioEngine';
+
+interface AIGeneratorModalProps {
+ isOpen: boolean;
+ onClose: () => void;
+ onProjectGenerated: (project: Project) => void;
+}
+
+const POPULAR_SUGGESTIONS = [
+ 'How DNS resolves a website domain',
+ 'What is Docker containerization?',
+ 'How Stripe processes credit card payments',
+ 'Git rebase vs merge explained visually',
+ 'How Redis in-memory caching works',
+];
+
+export const AIGeneratorModal: React.FC<AIGeneratorModalProps> = ({
+ isOpen,
+ onClose,
+ onProjectGenerated,
+}) => {
+ const [prompt, setPrompt] = useState('');
+ const [repoUrl, setRepoUrl] = useState('');
+ const [look, setLook] = useState<ThemeLook>('whiteboard');
+ const [numScenes, setNumScenes] = useState<number>(3);
+ const [isLoading, setIsLoading] = useState<boolean>(false);
+ const [error, setError] = useState<string | null>(null);
+ const [generationStep, setGenerationStep] = useState<string>('');
+
+ if (!isOpen) return null;
+
+ const handleGenerate = async () => {
+ if (!prompt.trim()) {
+ setError('Please provide a topic or repository name to explain.');
+ return;
+ }
+
+ setError(null);
+ setIsLoading(true);
+ setGenerationStep('Designing video architecture & script...');
+
+ try {
+ const stepTimer1 = setTimeout(() => {
+ setGenerationStep('Synthesizing visual diagrams & mockups...');
+ }, 1400);
+
+ const stepTimer2 = setTimeout(() => {
+ setGenerationStep('Synchronizing drawings with spoken word anchors...');
+ }, 2800);
+
+ const response = await fetch('/api/explainroo/ai-generate', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ prompt: prompt.trim(),
+ repoUrl: repoUrl.trim(),
+ look,
+ numScenes,
+ }),
+ });
+
+ clearTimeout(stepTimer1);
+ clearTimeout(stepTimer2);
+
+ if (!response.ok) {
+ const errData = await response.json();
+ throw new Error(errData.error || 'Failed to generate explainer video');
+ }
+
+ const project: Project = await response.json();
+ audioEngine.playDrawChime();
+ onProjectGenerated(project);
+ onClose();
+ } catch (err: any) {
+ console.error(err);
+ setError(err.message || 'Error communicating with AI service');
+ } finally {
+ setIsLoading(false);
+ setGenerationStep('');
+ }
+ };
+
+ return (
+ <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/80 backdrop-blur-md animate-fade-in">
+ <div className="relative w-full max-w-lg bg-slate-900 border border-slate-800 rounded-2xl p-6 shadow-2xl flex flex-col">
+ {/* Header */}
+ <div className="flex items-center justify-between pb-4 border-b border-slate-800">
+ <div className="flex items-center gap-2.5">
+ <div className="w-8 h-8 rounded-lg bg-gradient-to-tr from-amber-500 to-orange-500 flex items-center justify-center text-slate-950">
+ <Sparkles className="w-4 h-4 fill-slate-950" />
+ </div>
+ <div>
+ <h3 className="text-base font-bold text-white tracking-tight">
+ AI Explainer Video Generator
+ </h3>
+ <p className="text-xs text-slate-400">
+ Turn any concept or GitHub repo into a narrated animated video
+ </p>
+ </div>
+ </div>
+ <button
+ onClick={onClose}
+ disabled={isLoading}
+ className="p-1.5 text-slate-400 hover:text-white rounded-lg hover:bg-slate-800 transition-colors cursor-pointer"
+ >
+ <X className="w-5 h-5" />
+ </button>
+ </div>
+
+ {/* Form Body */}
+ <div className="py-4 space-y-4">
+ {error && (
+ <div className="p-3 rounded-xl bg-rose-500/10 border border-rose-500/30 text-rose-300 text-xs">
+ {error}
+ </div>
+ )}
+
+ {/* Topic Prompt Input */}
+ <div>
+ <label className="text-xs font-semibold text-slate-300 block mb-1.5">
+ What do you want to explain?
+ </label>
+ <textarea
+ rows={2}
+ value={prompt}
+ onChange={(e) => setPrompt(e.target.value)}
+ placeholder="e.g. How DNS works, What is an API, or paste a GitHub repo summary..."
+ className="w-full bg-slate-950 border border-slate-800 focus:border-amber-400 rounded-xl p-3 text-xs sm:text-sm text-slate-200 outline-none resize-none"
+ />
+
+ {/* Quick Suggestion Chips */}
+ <div className="flex flex-wrap gap-1.5 mt-2">
+ {POPULAR_SUGGESTIONS.map((sug) => (
+ <button
+ key={sug}
+ type="button"
+ onClick={() => setPrompt(sug)}
+ className="px-2 py-0.5 rounded-md bg-slate-950/80 hover:bg-slate-800 border border-slate-800 text-[11px] text-slate-400 hover:text-amber-300 transition-colors cursor-pointer"
+ >
+ {sug.length > 38 ? sug.slice(0, 35) + '...' : sug}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Optional GitHub URL */}
+ <div>
+ <label className="text-xs font-semibold text-slate-300 block mb-1.5 flex items-center gap-1.5">
+ <Github className="w-3.5 h-3.5 text-slate-400" />
+ <span>GitHub Repository Link (Optional)</span>
+ </label>
+ <input
+ type="text"
+ value={repoUrl}
+ onChange={(e) => setRepoUrl(e.target.value)}
+ placeholder="https://github.com/facebook/react"
+ className="w-full bg-slate-950 border border-slate-800 focus:border-cyan-400 rounded-xl px-3 py-2 text-xs font-mono text-slate-200 outline-none"
+ />
+ </div>
+
+ {/* Settings Grid: Look & Scene count */}
+ <div className="grid grid-cols-2 gap-3 pt-1">
+ <div>
+ <label className="text-xs font-semibold text-slate-300 block mb-1.5">
+ Visual Look Style
+ </label>
+ <select
+ value={look}
+ onChange={(e) => setLook(e.target.value as ThemeLook)}
+ className="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs text-slate-200 outline-none cursor-pointer"
+ >
+ {Object.entries(THEME_CONFIGS).map(([key, cfg]) => (
+ <option key={key} value={key}>
+ {cfg.name}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ <div>
+ <label className="text-xs font-semibold text-slate-300 block mb-1.5">
+ Number of Scenes
+ </label>
+ <select
+ value={numScenes}
+ onChange={(e) => setNumScenes(parseInt(e.target.value, 10))}
+ className="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs text-slate-200 outline-none cursor-pointer"
+ >
+ <option value={3}>3 Scenes (~20 seconds)</option>
+ <option value={4}>4 Scenes (~30 seconds)</option>
+ <option value={5}>5 Scenes (~45 seconds)</option>
+ </select>
+ </div>
+ </div>
+
+ {/* Generation Progress state */}
+ {isLoading && (
+ <div className="p-3.5 rounded-xl bg-amber-500/10 border border-amber-500/30 flex items-center gap-3 animate-fade-in">
+ <Loader2 className="w-5 h-5 text-amber-400 animate-spin shrink-0" />
+ <div className="text-xs">
+ <span className="font-semibold text-amber-300 block">
+ Creating Your Explainer Video...
+ </span>
+ <span className="text-slate-400 text-[11px]">{generationStep}</span>
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Footer CTAs */}
+ <div className="pt-3 border-t border-slate-800 flex items-center justify-end gap-2">
+ <button
+ type="button"
+ onClick={onClose}
+ disabled={isLoading}
+ className="px-4 py-2 text-xs font-medium text-slate-400 hover:text-white rounded-xl transition-colors cursor-pointer"
+ >
+ Cancel
+ </button>
+ <button
+ type="button"
+ onClick={handleGenerate}
+ disabled={isLoading || !prompt.trim()}
+ className="flex items-center gap-1.5 px-4 py-2 rounded-xl bg-gradient-to-r from-amber-500 to-orange-500 hover:from-amber-400 hover:to-orange-400 text-slate-950 text-xs font-bold shadow-lg transition-transform active:scale-95 cursor-pointer disabled:opacity-50"
+ >
+ <Sparkles className="w-3.5 h-3.5" />
+ <span>Generate Video</span>
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/src/components/explainroo/ElementInspector.tsx b/src/components/explainroo/ElementInspector.tsx
new file mode 100644
index 0000000..76c746a
--- /dev/null
+++ b/src/components/explainroo/ElementInspector.tsx
@@ -0,0 +1,203 @@
+import React from 'react';
+import {
+ Trash2,
+ Copy,
+ Sliders,
+} from 'lucide-react';
+import { VisualElement, AnimationType } from '../../types/explainroo';
+
+interface ElementInspectorProps {
+ element: VisualElement | null;
+ onUpdateElement: (id: string, updates: Partial<VisualElement>) => void;
+ onDeleteElement: (id: string) => void;
+ onDuplicateElement: (element: VisualElement) => void;
+ sceneDuration: number;
+}
+
+const COLOR_PRESETS = [
+ { label: 'Cyan', hex: '#38bdf8' },
+ { label: 'Emerald', hex: '#10b981' },
+ { label: 'Amber', hex: '#fbbf24' },
+ { label: 'Purple', hex: '#a855f7' },
+ { label: 'Rose', hex: '#f43f5e' },
+ { label: 'Dark Slate', hex: '#0f172a' },
+ { label: 'White', hex: '#ffffff' },
+];
+
+export const ElementInspector: React.FC<ElementInspectorProps> = ({
+ element,
+ onUpdateElement,
+ onDeleteElement,
+ onDuplicateElement,
+ sceneDuration,
+}) => {
+ if (!element) {
+ return (
+ <div className="bg-slate-900 border border-slate-800 rounded-2xl p-4 flex flex-col items-center justify-center text-center py-8">
+ <Sliders className="w-8 h-8 text-slate-600 mb-2" />
+ <h4 className="text-xs font-semibold text-slate-300">No Element Selected</h4>
+ <p className="text-[11px] text-slate-500 mt-1 max-w-[200px]">
+ Click any element on the preview canvas to edit its label, colors, and word trigger.
+ </p>
+ </div>
+ );
+ }
+
+ return (
+ <div className="bg-slate-900 border border-slate-800 rounded-2xl p-4 flex flex-col gap-3">
+ {/* Header */}
+ <div className="flex items-center justify-between pb-2 border-b border-slate-800">
+ <div>
+ <span className="text-[10px] font-mono uppercase text-amber-400 font-bold tracking-wider">
+ {element.type}
+ </span>
+ <h3 className="text-xs font-bold text-slate-200 truncate max-w-[140px]">
+ {element.label || 'Element Properties'}
+ </h3>
+ </div>
+
+ <div className="flex items-center gap-1">
+ <button
+ onClick={() => onDuplicateElement(element)}
+ className="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-slate-800 transition-colors cursor-pointer"
+ title="Duplicate element"
+ >
+ <Copy className="w-3.5 h-3.5" />
+ </button>
+ <button
+ onClick={() => onDeleteElement(element.id)}
+ className="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-rose-500/10 transition-colors cursor-pointer"
+ title="Delete element"
+ >
+ <Trash2 className="w-3.5 h-3.5" />
+ </button>
+ </div>
+ </div>
+
+ {/* Label & Text input */}
+ <div className="space-y-2">
+ <div>
+ <label className="text-[10px] font-semibold text-slate-400 uppercase tracking-wider block mb-1">
+ Display Label
+ </label>
+ <input
+ type="text"
+ value={element.label || ''}
+ onChange={(e) => onUpdateElement(element.id, { label: e.target.value })}
+ className="w-full bg-slate-950 border border-slate-800 focus:border-cyan-400/80 rounded-lg px-2.5 py-1.5 text-xs text-slate-200 outline-none"
+ placeholder="Text / Title"
+ />
+ </div>
+
+ {element.type === 'browser_window' && (
+ <div>
+ <label className="text-[10px] font-semibold text-slate-400 uppercase tracking-wider block mb-1">
+ Browser URL
+ </label>
+ <input
+ type="text"
+ value={element.url || ''}
+ onChange={(e) => onUpdateElement(element.id, { url: e.target.value })}
+ className="w-full bg-slate-950 border border-slate-800 focus:border-cyan-400/80 rounded-lg px-2.5 py-1.5 text-xs font-mono text-slate-200 outline-none"
+ placeholder="https://..."
+ />
+ </div>
+ )}
+
+ {element.type === 'code_block' && (
+ <div>
+ <label className="text-[10px] font-semibold text-slate-400 uppercase tracking-wider block mb-1">
+ Code Snippet
+ </label>
+ <textarea
+ rows={3}
+ value={element.codeSnippet || ''}
+ onChange={(e) => onUpdateElement(element.id, { codeSnippet: e.target.value })}
+ className="w-full bg-slate-950 border border-slate-800 focus:border-cyan-400/80 rounded-lg p-2 text-xs font-mono text-slate-200 outline-none resize-none"
+ placeholder="Code lines..."
+ />
+ </div>
+ )}
+ </div>
+
+ {/* Color Palette */}
+ <div>
+ <label className="text-[10px] font-semibold text-slate-400 uppercase tracking-wider block mb-1.5">
+ Stroke Color
+ </label>
+ <div className="flex items-center gap-1.5 flex-wrap">
+ {COLOR_PRESETS.map((color) => (
+ <button
+ key={color.hex}
+ onClick={() => onUpdateElement(element.id, { color: color.hex })}
+ style={{ backgroundColor: color.hex }}
+ className={`w-6 h-6 rounded-full border transition-transform cursor-pointer ${
+ element.color === color.hex
+ ? 'ring-2 ring-amber-400 scale-110 border-white'
+ : 'border-slate-700/80 hover:scale-105'
+ }`}
+ title={color.label}
+ />
+ ))}
+ </div>
+ </div>
+
+ {/* Animation Style */}
+ <div>
+ <label className="text-[10px] font-semibold text-slate-400 uppercase tracking-wider block mb-1">
+ Entrance Animation
+ </label>
+ <div className="grid grid-cols-2 gap-1.5 text-xs">
+ {(['pop', 'draw', 'slide', 'fade'] as AnimationType[]).map((anim) => (
+ <button
+ key={anim}
+ onClick={() => onUpdateElement(element.id, { animation: anim })}
+ className={`p-1.5 rounded-lg border text-left capitalize transition-colors cursor-pointer ${
+ element.animation === anim
+ ? 'bg-amber-500/15 border-amber-500/40 text-amber-300 font-semibold'
+ : 'bg-slate-950 border-slate-800 text-slate-400 hover:text-white'
+ }`}
+ >
+ {anim}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Word Sync Trigger */}
+ <div className="pt-1 border-t border-slate-800">
+ <label className="text-[10px] font-semibold text-slate-400 uppercase tracking-wider block mb-1">
+ Word Anchor Trigger
+ </label>
+ <div className="flex items-center gap-2">
+ <input
+ type="text"
+ value={element.triggerWord || ''}
+ onChange={(e) => onUpdateElement(element.id, { triggerWord: e.target.value })}
+ className="flex-1 bg-slate-950 border border-slate-800 focus:border-cyan-400/80 rounded-lg px-2.5 py-1 text-xs text-slate-200 outline-none"
+ placeholder="Type or click word above"
+ />
+ </div>
+ </div>
+
+ {/* Trigger Time Slider (fallback offset) */}
+ <div>
+ <div className="flex items-center justify-between text-[10px] text-slate-400 mb-1">
+ <span>Appearance Time</span>
+ <span className="font-mono text-cyan-400">{element.triggerTimeSec?.toFixed(1) || '0.0'}s</span>
+ </div>
+ <input
+ type="range"
+ min={0}
+ max={sceneDuration}
+ step={0.1}
+ value={element.triggerTimeSec || 0}
+ onChange={(e) =>
+ onUpdateElement(element.id, { triggerTimeSec: parseFloat(e.target.value) })
+ }
+ className="w-full h-1 bg-slate-800 rounded-lg appearance-none cursor-pointer accent-cyan-400"
+ />
+ </div>
+ </div>
+ );
+};
diff --git a/src/components/explainroo/ExportModal.tsx b/src/components/explainroo/ExportModal.tsx
new file mode 100644
index 0000000..b7bb85b
--- /dev/null
+++ b/src/components/explainroo/ExportModal.tsx
@@ -0,0 +1,424 @@
+import React, { useState } from 'react';
+import {
+ X,
+ Download,
+ Film,
+ FileCode,
+ FileText,
+ Copy,
+ Check,
+ Camera,
+ Archive,
+ Terminal,
+ Globe,
+ FileJson,
+ ExternalLink,
+} from 'lucide-react';
+import { Project } from '../../types/explainroo';
+import {
+ downloadProjectZip,
+ downloadTextFile,
+ downloadStandaloneHtml,
+ downloadProjectJson,
+ generateScriptMd,
+ generateScenesJs,
+ generateStandaloneHtml,
+} from '../../utils/cliExporter';
+import { videoRecorder } from '../../utils/videoRecorder';
+import { audioEngine } from '../../utils/audioEngine';
+
+interface ExportModalProps {
+ isOpen: boolean;
+ onClose: () => void;
+ project: Project;
+}
+
+export const ExportModal: React.FC<ExportModalProps> = ({
+ isOpen,
+ onClose,
+ project,
+}) => {
+ const [activeTab, setActiveTab] = useState<'video' | 'standalone' | 'cli' | 'snapshot'>('standalone');
+ const [copiedType, setCopiedType] = useState<string | null>(null);
+ const [isRecordingVideo, setIsRecordingVideo] = useState(false);
+ const [recordProgress, setRecordProgress] = useState(0);
+
+ if (!isOpen) return null;
+
+ const scriptMd = generateScriptMd(project);
+ const scenesJs = generateScenesJs(project);
+
+ const handleCopy = (text: string, type: string) => {
+ navigator.clipboard.writeText(text);
+ setCopiedType(type);
+ audioEngine.playPop();
+ setTimeout(() => setCopiedType(null), 2000);
+ };
+
+ const handleDownloadSnapshot = () => {
+ const canvas = document.querySelector('canvas');
+ if (!canvas) return;
+ const dataUrl = canvas.toDataURL('image/png');
+ const a = document.createElement('a');
+ a.href = dataUrl;
+ a.download = `${project.title.toLowerCase().replace(/[^a-z0-9]/g, '-')}-snapshot.png`;
+ a.click();
+ audioEngine.playPop();
+ };
+
+ const handleDownloadStandalone = () => {
+ downloadStandaloneHtml(project);
+ audioEngine.playDrawChime();
+ };
+
+ const handlePreviewStandalone = () => {
+ const html = generateStandaloneHtml(project);
+ const blob = new Blob([html], { type: 'text/html;charset=utf-8' });
+ const url = URL.createObjectURL(blob);
+ window.open(url, '_blank');
+ audioEngine.playPop();
+ };
+
+ const handleDownloadJsonBackup = () => {
+ downloadProjectJson(project);
+ audioEngine.playPop();
+ };
+
+ const handleStartVideoRecording = async () => {
+ const canvas = document.querySelector('canvas');
+ if (!canvas) return;
+
+ setIsRecordingVideo(true);
+ setRecordProgress(0);
+
+ const started = videoRecorder.start(canvas);
+ if (!started) {
+ setIsRecordingVideo(false);
+ return;
+ }
+
+ // Determine recording duration based on active scene or total duration
+ const totalSec = project.scenes.reduce((acc, sc) => acc + (sc.durationSeconds || 7), 0);
+ const recDuration = Math.max(4, Math.min(30, totalSec));
+
+ let sec = 0;
+ const interval = setInterval(() => {
+ sec += 0.5;
+ setRecordProgress(Math.min(100, Math.round((sec / recDuration) * 100)));
+ if (sec >= recDuration) {
+ clearInterval(interval);
+ videoRecorder.stop().then((blob) => {
+ setIsRecordingVideo(false);
+ if (blob) {
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `${project.title.toLowerCase().replace(/[^a-z0-9]/g, '-')}.webm`;
+ a.click();
+ URL.revokeObjectURL(url);
+ audioEngine.playDrawChime();
+ }
+ });
+ }
+ }, 500);
+ };
+
+ return (
+ <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/80 backdrop-blur-md animate-fade-in">
+ <div className="relative w-full max-w-xl bg-slate-900 border border-slate-800 rounded-2xl p-6 shadow-2xl flex flex-col max-h-[85vh]">
+ {/* Header */}
+ <div className="flex items-center justify-between pb-3 border-b border-slate-800">
+ <div>
+ <h3 className="text-base font-bold text-white tracking-tight">Export & Direct Download</h3>
+ <p className="text-xs text-slate-400">
+ Download offline-ready standalone player, video, or Explainroo CLI files
+ </p>
+ </div>
+ <button
+ onClick={onClose}
+ className="p-1.5 text-slate-400 hover:text-white rounded-lg hover:bg-slate-800 transition-colors cursor-pointer"
+ >
+ <X className="w-5 h-5" />
+ </button>
+ </div>
+
+ {/* Tab Switcher */}
+ <div className="flex items-center gap-1 p-1 bg-slate-950 rounded-xl my-4 text-xs font-medium">
+ <button
+ onClick={() => setActiveTab('standalone')}
+ className={`flex-1 py-1.5 rounded-lg flex items-center justify-center gap-1.5 transition-colors cursor-pointer ${
+ activeTab === 'standalone'
+ ? 'bg-slate-800 text-amber-300 font-bold shadow-sm'
+ : 'text-slate-400 hover:text-white'
+ }`}
+ >
+ <Globe className="w-3.5 h-3.5" />
+ <span>Standalone Player</span>
+ </button>
+
+ <button
+ onClick={() => setActiveTab('video')}
+ className={`flex-1 py-1.5 rounded-lg flex items-center justify-center gap-1.5 transition-colors cursor-pointer ${
+ activeTab === 'video'
+ ? 'bg-slate-800 text-orange-300 font-bold shadow-sm'
+ : 'text-slate-400 hover:text-white'
+ }`}
+ >
+ <Film className="w-3.5 h-3.5" />
+ <span>Video Recording</span>
+ </button>
+
+ <button
+ onClick={() => setActiveTab('cli')}
+ className={`flex-1 py-1.5 rounded-lg flex items-center justify-center gap-1.5 transition-colors cursor-pointer ${
+ activeTab === 'cli'
+ ? 'bg-slate-800 text-cyan-300 font-bold shadow-sm'
+ : 'text-slate-400 hover:text-white'
+ }`}
+ >
+ <Terminal className="w-3.5 h-3.5" />
+ <span>CLI Bundle</span>
+ </button>
+
+ <button
+ onClick={() => setActiveTab('snapshot')}
+ className={`flex-1 py-1.5 rounded-lg flex items-center justify-center gap-1.5 transition-colors cursor-pointer ${
+ activeTab === 'snapshot'
+ ? 'bg-slate-800 text-emerald-300 font-bold shadow-sm'
+ : 'text-slate-400 hover:text-white'
+ }`}
+ >
+ <Camera className="w-3.5 h-3.5" />
+ <span>Snapshot</span>
+ </button>
+ </div>
+
+ {/* Tab: Standalone Offline Player */}
+ {activeTab === 'standalone' && (
+ <div className="space-y-4 py-2">
+ <div className="p-4 rounded-xl bg-slate-950 border border-amber-500/30 flex flex-col gap-2.5">
+ <div className="flex items-center justify-between">
+ <span className="text-xs font-bold text-amber-300 flex items-center gap-1.5">
+ <Globe className="w-4 h-4 text-amber-400" />
+ <span>1-Click Zero-Install HTML Player (.html)</span>
+ </span>
+ <span className="px-2 py-0.5 rounded bg-amber-400/20 text-[10px] font-mono text-amber-300 font-semibold">
+ Offline Ready
+ </span>
+ </div>
+ <p className="text-xs text-slate-300 leading-relaxed">
+ Directly downloads a single self-contained <code className="text-amber-300">.html</code> file with all your scenes, vector diagrams, Whisper karaoke subtitles, and voice synthesis embedded.
+ </p>
+ <ul className="text-[11px] text-slate-400 space-y-1 list-disc list-inside">
+ <li>Double-click to open and play in any web browser with <strong>zero server or Node.js</strong> needed.</li>
+ <li>Share via email, send on Slack/Discord, or host on GitHub Pages/Netlify.</li>
+ <li>Includes interactive scrubber, play/pause, voice controls, and fullscreen mode.</li>
+ </ul>
+ </div>
+
+ <div className="flex items-center gap-2">
+ <button
+ onClick={handleDownloadStandalone}
+ className="flex-1 flex items-center justify-center gap-2 py-3 rounded-xl bg-gradient-to-r from-amber-500 to-orange-500 hover:from-amber-400 hover:to-orange-400 text-slate-950 font-bold text-xs shadow-lg transition-transform active:scale-95 cursor-pointer"
+ >
+ <Download className="w-4 h-4" />
+ <span>Download Standalone Player (.html)</span>
+ </button>
+
+ <button
+ onClick={handlePreviewStandalone}
+ className="px-3.5 py-3 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-200 hover:text-white font-semibold text-xs border border-slate-700 transition-colors cursor-pointer flex items-center gap-1.5"
+ title="Preview standalone player in new browser tab"
+ >
+ <ExternalLink className="w-3.5 h-3.5" />
+ <span>Preview</span>
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* Tab: Video Export */}
+ {activeTab === 'video' && (
+ <div className="space-y-4 py-2">
+ <div className="p-4 rounded-xl bg-slate-950 border border-slate-800 flex flex-col gap-2">
+ <div className="flex items-center justify-between">
+ <span className="text-xs font-bold text-slate-200">Browser Video Capture</span>
+ <span className="text-[11px] font-mono text-cyan-400">1280x720 30FPS</span>
+ </div>
+ <p className="text-xs text-slate-400">
+ Directly captures and renders the current video animation into a downloadable WebM/MP4 video file.
+ </p>
+
+ {isRecordingVideo && (
+ <div className="pt-2">
+ <div className="flex items-center justify-between text-[11px] text-amber-400 mb-1 font-mono">
+ <span>Recording Canvas Stream...</span>
+ <span>{recordProgress}%</span>
+ </div>
+ <div className="w-full h-1.5 bg-slate-800 rounded-full overflow-hidden">
+ <div
+ className="h-full bg-amber-400 transition-all duration-300"
+ style={{ width: `${recordProgress}%` }}
+ />
+ </div>
+ </div>
+ )}
+ </div>
+
+ <button
+ onClick={handleStartVideoRecording}
+ disabled={isRecordingVideo}
+ className="w-full flex items-center justify-center gap-2 py-3 rounded-xl bg-gradient-to-r from-orange-500 to-amber-500 hover:from-orange-400 hover:to-amber-400 text-slate-950 font-bold text-xs shadow-lg transition-transform active:scale-95 cursor-pointer disabled:opacity-50"
+ >
+ <Film className="w-4 h-4" />
+ <span>{isRecordingVideo ? 'Rendering Video...' : 'Record & Download Video'}</span>
+ </button>
+ </div>
+ )}
+
+ {/* Tab: Explainroo CLI Bundle */}
+ {activeTab === 'cli' && (
+ <div className="space-y-3 py-2 overflow-y-auto max-h-[48vh]">
+ {/* Full ZIP */}
+ <div className="p-3.5 rounded-xl bg-slate-950 border border-slate-800">
+ <div className="flex items-center justify-between mb-2">
+ <span className="text-xs font-bold text-slate-200 flex items-center gap-1.5">
+ <Archive className="w-4 h-4 text-cyan-400" />
+ <span>Full Project ZIP Package</span>
+ </span>
+ <button
+ onClick={() => downloadProjectZip(project)}
+ className="px-3 py-1 bg-cyan-500 hover:bg-cyan-400 text-slate-950 text-xs font-bold rounded-lg transition-colors cursor-pointer"
+ >
+ Download .zip
+ </button>
+ </div>
+ <p className="text-[11px] text-slate-400">
+ Includes <code className="text-slate-300">standalone-player.html</code>, <code className="text-slate-300">script.md</code>, <code className="text-slate-300">scenes.js</code>, and <code className="text-slate-300">explainroo.config.json</code> ready to run via the Explainroo terminal CLI.
+ </p>
+ </div>
+
+ {/* Direct Project JSON Backup */}
+ <div className="p-3 rounded-xl bg-slate-950 border border-slate-800 flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <FileJson className="w-4 h-4 text-purple-400" />
+ <div>
+ <span className="text-xs font-semibold text-slate-200 block">Project Backup (.json)</span>
+ <span className="text-[10px] text-slate-500">Save full studio state to reload anytime</span>
+ </div>
+ </div>
+ <button
+ onClick={handleDownloadJsonBackup}
+ className="px-2.5 py-1 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs font-medium transition-colors cursor-pointer flex items-center gap-1"
+ title="Download .explainroo.json backup"
+ >
+ <Download className="w-3.5 h-3.5" />
+ <span>Save JSON</span>
+ </button>
+ </div>
+
+ {/* Individual Files: script.md */}
+ <div className="p-3 rounded-xl bg-slate-950 border border-slate-800 flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <FileText className="w-4 h-4 text-amber-400" />
+ <div>
+ <span className="text-xs font-semibold text-slate-200 block">script.md</span>
+ <span className="text-[10px] text-slate-500">Narration text & scene breaks</span>
+ </div>
+ </div>
+ <div className="flex items-center gap-1.5">
+ <button
+ onClick={() => handleCopy(scriptMd, 'script')}
+ className="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs flex items-center gap-1 transition-colors cursor-pointer"
+ >
+ {copiedType === 'script' ? <Check className="w-3.5 h-3.5 text-emerald-400" /> : <Copy className="w-3.5 h-3.5" />}
+ <span>{copiedType === 'script' ? 'Copied' : 'Copy'}</span>
+ </button>
+ <button
+ onClick={() => downloadTextFile('script.md', scriptMd)}
+ className="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs transition-colors cursor-pointer"
+ title="Download script.md"
+ >
+ <Download className="w-3.5 h-3.5" />
+ </button>
+ </div>
+ </div>
+
+ {/* Individual Files: scenes.js */}
+ <div className="p-3 rounded-xl bg-slate-950 border border-slate-800 flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <FileCode className="w-4 h-4 text-cyan-400" />
+ <div>
+ <span className="text-xs font-semibold text-slate-200 block">scenes.js</span>
+ <span className="text-[10px] text-slate-500">Canvas drawings & coordinates</span>
+ </div>
+ </div>
+ <div className="flex items-center gap-1.5">
+ <button
+ onClick={() => handleCopy(scenesJs, 'scenes')}
+ className="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs flex items-center gap-1 transition-colors cursor-pointer"
+ >
+ {copiedType === 'scenes' ? <Check className="w-3.5 h-3.5 text-emerald-400" /> : <Copy className="w-3.5 h-3.5" />}
+ <span>{copiedType === 'scenes' ? 'Copied' : 'Copy'}</span>
+ </button>
+ <button
+ onClick={() => downloadTextFile('scenes.js', scenesJs)}
+ className="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs transition-colors cursor-pointer"
+ title="Download scenes.js"
+ >
+ <Download className="w-3.5 h-3.5" />
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Tab: Snapshot PNG */}
+ {activeTab === 'snapshot' && (
+ <div className="space-y-4 py-2">
+ <div className="p-4 rounded-xl bg-slate-950 border border-slate-800 text-center space-y-2">
+ <Camera className="w-8 h-8 text-emerald-400 mx-auto" />
+ <h4 className="text-xs font-bold text-slate-200">High-Resolution Canvas Snapshot</h4>
+ <p className="text-xs text-slate-400 max-w-sm mx-auto">
+ Download a clean, crystal-clear 1280x720 PNG of your current visual scene for presentations, tweets, or documentation.
+ </p>
+ </div>
+
+ <button
+ onClick={handleDownloadSnapshot}
+ className="w-full flex items-center justify-center gap-2 py-3 rounded-xl bg-emerald-500 hover:bg-emerald-400 text-slate-950 font-bold text-xs shadow-lg transition-transform active:scale-95 cursor-pointer"
+ >
+ <Download className="w-4 h-4" />
+ <span>Download Snapshot PNG</span>
+ </button>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
+
+ {/* Tab 3: Snapshot PNG */}
+ {activeTab === 'snapshot' && (
+ <div className="space-y-4 py-2">
+ <div className="p-4 rounded-xl bg-slate-950 border border-slate-800 text-center space-y-2">
+ <Camera className="w-8 h-8 text-emerald-400 mx-auto" />
+ <h4 className="text-xs font-bold text-slate-200">High-Resolution Canvas Snapshot</h4>
+ <p className="text-xs text-slate-400 max-w-sm mx-auto">
+ Download a clean, crystal-clear 1280x720 PNG of your current visual scene for presentations, tweets, or documentation.
+ </p>
+ </div>
+
+ <button
+ onClick={handleDownloadSnapshot}
+ className="w-full flex items-center justify-center gap-2 py-3 rounded-xl bg-emerald-500 hover:bg-emerald-400 text-slate-950 font-bold text-xs shadow-lg transition-transform active:scale-95 cursor-pointer"
+ >
+ <Download className="w-4 h-4" />
+ <span>Download Snapshot PNG</span>
+ </button>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
diff --git a/src/components/explainroo/Navbar.tsx b/src/components/explainroo/Navbar.tsx
new file mode 100644
index 0000000..4d9038b
--- /dev/null
+++ b/src/components/explainroo/Navbar.tsx
@@ -0,0 +1,125 @@
+import React from 'react';
+import {
+ Sparkles,
+ Layers,
+ Download,
+ Palette,
+ RotateCcw,
+} from 'lucide-react';
+import { ThemeLook, THEME_CONFIGS } from '../../types/explainroo';
+
+interface NavbarProps {
+ title: string;
+ onUpdateTitle: (title: string) => void;
+ look: ThemeLook;
+ onSelectLook: (look: ThemeLook) => void;
+ onOpenAiModal: () => void;
+ onOpenTemplates: () => void;
+ onOpenExport: () => void;
+ onResetProject: () => void;
+}
+
+export const Navbar: React.FC<NavbarProps> = ({
+ title,
+ onUpdateTitle,
+ look,
+ onSelectLook,
+ onOpenAiModal,
+ onOpenTemplates,
+ onOpenExport,
+ onResetProject,
+}) => {
+ return (
+ <header className="w-full bg-slate-900 border-b border-slate-800 text-slate-100 sticky top-0 z-40 select-none">
+ <div className="max-w-7xl mx-auto px-4 h-15 flex items-center justify-between gap-3">
+ {/* Brand & Repo Info */}
+ <div className="flex items-center gap-3 shrink-0">
+ <div className="w-8 h-8 rounded-lg bg-gradient-to-tr from-amber-500 via-orange-500 to-rose-500 flex items-center justify-center shadow-[0_0_15px_rgba(249,115,22,0.4)]">
+ <span className="text-base font-black text-white">🦘</span>
+ </div>
+ <div>
+ <div className="flex items-center gap-2">
+ <span className="font-extrabold text-base tracking-tight text-white">
+ Explainroo <span className="text-amber-400 font-bold">UI</span>
+ </span>
+ <span className="px-1.5 py-0.5 rounded bg-amber-400/15 border border-amber-400/30 text-[10px] font-mono font-semibold text-amber-300">
+ v1.0
+ </span>
+ </div>
+ <p className="hidden md:block text-[11px] text-slate-400 leading-none">
+ Visual studio for animated software explainer videos
+ </p>
+ </div>
+ </div>
+
+ {/* Project Title Input */}
+ <div className="flex-1 max-w-md hidden sm:block">
+ <input
+ type="text"
+ value={title}
+ onChange={(e) => onUpdateTitle(e.target.value)}
+ className="w-full bg-slate-950/60 hover:bg-slate-950 border border-slate-800 focus:border-amber-400/80 rounded-lg px-3 py-1.5 text-xs sm:text-sm font-medium text-slate-200 outline-none transition-colors"
+ placeholder="Explainer Video Title..."
+ />
+ </div>
+
+ {/* Look Style Dropdown */}
+ <div className="flex items-center gap-1.5 shrink-0">
+ <div className="relative flex items-center bg-slate-950 border border-slate-800 rounded-lg px-2.5 py-1 text-xs">
+ <Palette className="w-3.5 h-3.5 text-amber-400 mr-1.5 shrink-0" />
+ <select
+ value={look}
+ onChange={(e) => onSelectLook(e.target.value as ThemeLook)}
+ className="bg-transparent text-slate-200 text-xs font-medium outline-none cursor-pointer pr-1"
+ >
+ {Object.entries(THEME_CONFIGS).map(([key, config]) => (
+ <option key={key} value={key} className="bg-slate-900 text-slate-200">
+ {config.name}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ {/* AI Generator CTA */}
+ <button
+ onClick={onOpenAiModal}
+ className="flex items-center gap-1.5 px-3 py-1.5 bg-gradient-to-r from-amber-500 to-orange-500 hover:from-amber-400 hover:to-orange-400 text-slate-950 text-xs font-bold rounded-lg shadow-[0_0_15px_rgba(245,158,11,0.3)] transition-all cursor-pointer active:scale-95"
+ title="Generate complete explainer video from prompt or repo URL"
+ >
+ <Sparkles className="w-3.5 h-3.5" />
+ <span className="hidden xs:inline">AI Generator</span>
+ </button>
+
+ {/* Templates Gallery */}
+ <button
+ onClick={onOpenTemplates}
+ className="flex items-center gap-1 px-2.5 py-1.5 bg-slate-800 hover:bg-slate-700 text-slate-200 hover:text-white text-xs font-medium rounded-lg border border-slate-700/80 transition-colors cursor-pointer"
+ title="Explore prebuilt explainer templates"
+ >
+ <Layers className="w-3.5 h-3.5 text-cyan-400" />
+ <span className="hidden md:inline">Templates</span>
+ </button>
+
+ {/* Export Video & CLI Bundle */}
+ <button
+ onClick={onOpenExport}
+ className="flex items-center gap-1.5 px-3 py-1.5 bg-cyan-500/15 hover:bg-cyan-500/25 border border-cyan-500/40 text-cyan-300 text-xs font-semibold rounded-lg transition-colors cursor-pointer"
+ title="Export MP4/WebM Video or Explainroo CLI files"
+ >
+ <Download className="w-3.5 h-3.5" />
+ <span>Export</span>
+ </button>
+
+ {/* Reset Project */}
+ <button
+ onClick={onResetProject}
+ className="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-slate-800 transition-colors cursor-pointer"
+ title="Reset to default project"
+ >
+ <RotateCcw className="w-3.5 h-3.5" />
+ </button>
+ </div>
+ </div>
+ </header>
+ );
+};
diff --git a/src/components/explainroo/SceneList.tsx b/src/components/explainroo/SceneList.tsx
new file mode 100644
index 0000000..735845f
--- /dev/null
+++ b/src/components/explainroo/SceneList.tsx
@@ -0,0 +1,130 @@
+import React from 'react';
+import {
+ Plus,
+ Trash2,
+ Copy,
+ ChevronLeft,
+ ChevronRight,
+ Film,
+} from 'lucide-react';
+import { Scene } from '../../types/explainroo';
+
+interface SceneListProps {
+ scenes: Scene[];
+ activeSceneIndex: number;
+ onSelectScene: (index: number) => void;
+ onAddScene: () => void;
+ onDuplicateScene: (index: number) => void;
+ onDeleteScene: (index: number) => void;
+ onMoveScene: (index: number, direction: 'prev' | 'next') => void;
+}
+
+export const SceneList: React.FC<SceneListProps> = ({
+ scenes,
+ activeSceneIndex,
+ onSelectScene,
+ onAddScene,
+ onDuplicateScene,
+ onDeleteScene,
+ onMoveScene,
+}) => {
+ return (
+ <div className="bg-slate-900 border border-slate-800 rounded-2xl p-3 flex flex-col gap-2">
+ <div className="flex items-center justify-between px-1 pb-1 border-b border-slate-800">
+ <div className="flex items-center gap-1.5">
+ <Film className="w-3.5 h-3.5 text-amber-400" />
+ <h3 className="text-xs font-bold uppercase tracking-wider text-slate-200">
+ Scenes ({scenes.length})
+ </h3>
+ </div>
+
+ <button
+ onClick={onAddScene}
+ className="flex items-center gap-1 px-2 py-1 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-200 hover:text-white text-xs font-medium border border-slate-700/80 transition-colors cursor-pointer"
+ title="Add a new blank scene"
+ >
+ <Plus className="w-3.5 h-3.5 text-amber-400" />
+ <span>New Scene</span>
+ </button>
+ </div>
+
+ {/* Horizontal Scrollable Scene Strips */}
+ <div className="flex items-center gap-2 overflow-x-auto py-1 pr-1 scrollbar-thin">
+ {scenes.map((scene, idx) => {
+ const isActive = idx === activeSceneIndex;
+
+ return (
+ <div
+ key={scene.id}
+ onClick={() => onSelectScene(idx)}
+ className={`min-w-[170px] max-w-[200px] flex-1 p-2.5 rounded-xl border transition-all cursor-pointer flex flex-col justify-between select-none ${
+ isActive
+ ? 'bg-amber-500/10 border-amber-400/80 ring-1 ring-amber-400 shadow-[0_0_15px_rgba(251,191,36,0.15)]'
+ : 'bg-slate-950/70 border-slate-800 hover:border-slate-700 hover:bg-slate-950'
+ }`}
+ >
+ <div>
+ <div className="flex items-center justify-between text-[10px] text-slate-400 mb-1">
+ <span className="font-mono font-bold text-amber-400">
+ #{idx + 1}
+ </span>
+ <span>{scene.durationSeconds || 7}s</span>
+ </div>
+ <h4 className="text-xs font-bold text-slate-200 truncate">
+ {scene.title || `Scene ${idx + 1}`}
+ </h4>
+ <p className="text-[11px] text-slate-400 line-clamp-1 mt-0.5">
+ {scene.narration || 'No spoken narration yet'}
+ </p>
+ </div>
+
+ {/* Bottom bar inside card */}
+ <div className="flex items-center justify-between pt-2 mt-2 border-t border-slate-800/80 text-[10px] text-slate-400">
+ <span>{scene.elements.length} visuals</span>
+
+ {/* Micro Actions */}
+ <div
+ className="flex items-center gap-0.5"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <button
+ disabled={idx === 0}
+ onClick={() => onMoveScene(idx, 'prev')}
+ className="p-1 rounded text-slate-500 hover:text-white disabled:opacity-30"
+ title="Move left"
+ >
+ <ChevronLeft className="w-3 h-3" />
+ </button>
+ <button
+ disabled={idx === scenes.length - 1}
+ onClick={() => onMoveScene(idx, 'next')}
+ className="p-1 rounded text-slate-500 hover:text-white disabled:opacity-30"
+ title="Move right"
+ >
+ <ChevronRight className="w-3 h-3" />
+ </button>
+ <button
+ onClick={() => onDuplicateScene(idx)}
+ className="p-1 rounded text-slate-500 hover:text-cyan-400"
+ title="Duplicate scene"
+ >
+ <Copy className="w-3 h-3" />
+ </button>
+ {scenes.length > 1 && (
+ <button
+ onClick={() => onDeleteScene(idx)}
+ className="p-1 rounded text-slate-500 hover:text-rose-400"
+ title="Delete scene"
+ >
+ <Trash2 className="w-3 h-3" />
+ </button>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ );
+};
diff --git a/src/components/explainroo/ScriptEditor.tsx b/src/components/explainroo/ScriptEditor.tsx
new file mode 100644
index 0000000..cac28bc
--- /dev/null
+++ b/src/components/explainroo/ScriptEditor.tsx
@@ -0,0 +1,320 @@
+import React, { useState, useRef, useEffect } from 'react';
+import {
+ Volume2,
+ Sparkles,
+ Clock,
+ Check,
+ RefreshCw,
+ Upload,
+ Trash2,
+ Mic,
+} from 'lucide-react';
+import { Scene, VisualElement } from '../../types/explainroo';
+import { audioEngine } from '../../utils/audioEngine';
+
+interface ScriptEditorProps {
+ scene: Scene;
+ selectedElementId: string | null;
+ onUpdateNarration: (text: string) => void;
+ onUpdateElementTriggerWord: (elementId: string, word: string) => void;
+ onUpdateCustomAudio?: (url?: string, filename?: string) => void;
+ voiceRate: number;
+ voicePitch: number;
+}
+
+export const ScriptEditor: React.FC<ScriptEditorProps> = ({
+ scene,
+ selectedElementId,
+ onUpdateNarration,
+ onUpdateElementTriggerWord,
+ onUpdateCustomAudio,
+ voiceRate,
+ voicePitch,
+}) => {
+ const [isPolishing, setIsPolishing] = useState(false);
+ const [isPlayingVoice, setIsPlayingVoice] = useState(false);
+ const [liveSpokenWordIndex, setLiveSpokenWordIndex] = useState<number>(-1);
+
+ // Subscribe to real-time word boundary updates from AudioEngine
+ useEffect(() => {
+ const unsub = audioEngine.addWordListener((_word, _charIdx, wordIdx) => {
+ setLiveSpokenWordIndex(wordIdx);
+ if (wordIdx < 0) {
+ setIsPlayingVoice(false);
+ }
+ });
+ return () => unsub();
+ }, []);
+
+ const words = scene.narration
+ .split(/\s+/)
+ .filter((w) => w.length > 0)
+ .map((rawWord) => rawWord.replace(/[.,/#!$%^&*;:{}=\-_`~()?"']/g, ''));
+
+ const wordCount = words.length;
+ // Estimated reading time at ~150 words per minute (2.5 words per second)
+ const estimatedSeconds = Math.max(3, Math.round(wordCount / 2.5));
+
+ // Find currently selected element
+ const selectedElement = scene.elements.find((el) => el.id === selectedElementId);
+
+ // Map each word to elements that trigger on it
+ const wordTriggerMap: Record<string, VisualElement[]> = {};
+ scene.elements.forEach((el) => {
+ if (el.triggerWord) {
+ const cleanTrigger = el.triggerWord.toLowerCase().replace(/[^a-z0-9]/g, '');
+ if (!wordTriggerMap[cleanTrigger]) {
+ wordTriggerMap[cleanTrigger] = [];
+ }
+ wordTriggerMap[cleanTrigger].push(el);
+ }
+ });
+
+ const handlePolishWithAi = async () => {
+ if (!scene.narration) return;
+ try {
+ setIsPolishing(true);
+ const res = await fetch('/api/explainroo/improve-script', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ text: scene.narration, goal: 'punchy and conversational' }),
+ });
+ if (res.ok) {
+ const data = await res.json();
+ if (data.improvedText) {
+ onUpdateNarration(data.improvedText);
+ audioEngine.playDrawChime();
+ }
+ }
+ } catch (err) {
+ console.error('Failed to polish script:', err);
+ } finally {
+ setIsPolishing(false);
+ }
+ };
+
+ const fileInputRef = useRef<HTMLInputElement | null>(null);
+
+ const handleAudioUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ if (!file) return;
+ const url = URL.createObjectURL(file);
+ if (onUpdateCustomAudio) {
+ onUpdateCustomAudio(url, file.name);
+ }
+ audioEngine.playPop();
+ };
+
+ const handleRemoveCustomAudio = () => {
+ if (onUpdateCustomAudio) {
+ onUpdateCustomAudio(undefined, undefined);
+ }
+ audioEngine.stopCustomAudio();
+ setIsPlayingVoice(false);
+ };
+
+ const handleTestVoice = () => {
+ if (isPlayingVoice) {
+ audioEngine.stopSpeaking();
+ setIsPlayingVoice(false);
+ setLiveSpokenWordIndex(-1);
+ } else {
+ setIsPlayingVoice(true);
+ if (scene.customAudioUrl) {
+ audioEngine.playCustomAudio(scene.customAudioUrl, () => {
+ setIsPlayingVoice(false);
+ setLiveSpokenWordIndex(-1);
+ });
+ } else {
+ audioEngine.speakNarration(
+ scene.narration,
+ (_word, _charIdx, wordIdx) => {
+ setLiveSpokenWordIndex(wordIdx);
+ },
+ () => {
+ setIsPlayingVoice(false);
+ setLiveSpokenWordIndex(-1);
+ },
+ voiceRate,
+ voicePitch
+ );
+ }
+ }
+ };
+
+ const handleWordChipClick = (wordText: string) => {
+ if (!selectedElement) return;
+ const clean = wordText.toLowerCase();
+ onUpdateElementTriggerWord(selectedElement.id, clean);
+ audioEngine.playPop();
+ };
+
+ return (
+ <div className="bg-slate-900 border border-slate-800 rounded-2xl p-4 flex flex-col gap-3">
+ {/* Header */}
+ <div className="flex items-center justify-between pb-2 border-b border-slate-800">
+ <div>
+ <h3 className="text-xs font-bold uppercase tracking-wider text-slate-300">
+ Voiceover Script & Word Sync
+ </h3>
+ <p className="text-[11px] text-slate-500">
+ Explainroo synchronizes your drawings with spoken words
+ </p>
+ </div>
+
+ <div className="flex items-center gap-2">
+ {/* Audio Test Voice */}
+ <button
+ onClick={handleTestVoice}
+ className={`flex items-center gap-1 px-2.5 py-1 text-xs font-medium rounded-lg border transition-colors cursor-pointer ${
+ isPlayingVoice
+ ? 'bg-amber-500/20 text-amber-300 border-amber-500/40'
+ : 'bg-slate-800 text-slate-300 border-slate-700 hover:text-white'
+ }`}
+ title="Preview spoken narration"
+ >
+ <Volume2 className="w-3.5 h-3.5 text-amber-400" />
+ <span>{isPlayingVoice ? 'Speaking...' : 'Listen'}</span>
+ </button>
+
+ {/* AI Polish Script */}
+ <button
+ onClick={handlePolishWithAi}
+ disabled={isPolishing || !scene.narration}
+ className="flex items-center gap-1 px-2.5 py-1 bg-amber-500/15 hover:bg-amber-500/25 border border-amber-500/30 text-amber-300 text-xs font-semibold rounded-lg transition-colors cursor-pointer disabled:opacity-50"
+ title="Make script punchier using AI"
+ >
+ {isPolishing ? (
+ <RefreshCw className="w-3.5 h-3.5 animate-spin" />
+ ) : (
+ <Sparkles className="w-3.5 h-3.5" />
+ )}
+ <span>AI Polish</span>
+ </button>
+ </div>
+ </div>
+
+ {/* Narration Text Area */}
+ <div className="relative">
+ <textarea
+ rows={3}
+ value={scene.narration}
+ onChange={(e) => onUpdateNarration(e.target.value)}
+ placeholder="Write the narration voiceover for this scene..."
+ className="w-full bg-slate-950 border border-slate-800 focus:border-cyan-400/80 rounded-xl p-3 text-xs sm:text-sm text-slate-200 outline-none resize-none transition-colors"
+ />
+ <div className="flex items-center justify-between text-[11px] text-slate-500 px-1 mt-1">
+ <span className="flex items-center gap-1">
+ <Clock className="w-3 h-3 text-slate-400" />
+ <span>~{estimatedSeconds}s spoken ({wordCount} words)</span>
+ </span>
+ <span className="italic text-slate-400">
+ {selectedElement
+ ? `Click a word below to anchor "${selectedElement.label || selectedElement.type}"`
+ : 'Select an element to sync it to a word'}
+ </span>
+ </div>
+ </div>
+
+ {/* Custom Audio Upload Row */}
+ <div className="flex items-center justify-between p-2 rounded-xl bg-slate-950/70 border border-slate-800/80">
+ <div className="flex items-center gap-2 overflow-hidden">
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept="audio/*"
+ onChange={handleAudioUpload}
+ className="hidden"
+ />
+ <Mic className="w-3.5 h-3.5 text-slate-400 shrink-0" />
+ {scene.customAudioUrl ? (
+ <div className="flex items-center gap-1.5 truncate">
+ <span className="w-2 h-2 rounded-full bg-emerald-400 shrink-0 animate-pulse" />
+ <span className="text-xs text-emerald-300 font-mono truncate max-w-[180px]">
+ {scene.customAudioName || 'Custom Audio'}
+ </span>
+ </div>
+ ) : (
+ <span className="text-xs text-slate-400">
+ Web Speech TTS active · Or upload voiceover file
+ </span>
+ )}
+ </div>
+
+ <div className="flex items-center gap-1.5 shrink-0">
+ {scene.customAudioUrl ? (
+ <button
+ onClick={handleRemoveCustomAudio}
+ className="p-1 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-slate-800 transition-colors cursor-pointer"
+ title="Remove custom audio and use Web Speech TTS"
+ >
+ <Trash2 className="w-3.5 h-3.5" />
+ </button>
+ ) : (
+ <button
+ onClick={() => fileInputRef.current?.click()}
+ className="inline-flex items-center gap-1 px-2 py-1 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-200 text-xs font-medium border border-slate-700 transition-colors cursor-pointer"
+ title="Upload MP3 or WAV voiceover track"
+ >
+ <Upload className="w-3 h-3 text-slate-400" />
+ <span>Upload MP3/WAV</span>
+ </button>
+ )}
+ </div>
+ </div>
+
+ {/* Interactive Word Sync Chips */}
+ {words.length > 0 && (
+ <div className="pt-2">
+ <span className="text-[10px] font-semibold tracking-wider uppercase text-slate-400 block mb-2">
+ Click Word to Anchor Selected Element:
+ </span>
+ <div className="flex flex-wrap gap-1.5 max-h-36 overflow-y-auto pr-1">
+ {words.map((w, idx) => {
+ const clean = w.toLowerCase();
+ const isAttachedToSelected =
+ selectedElement &&
+ selectedElement.triggerWord?.toLowerCase().replace(/[^a-z0-9]/g, '') === clean;
+ const attachedElements = wordTriggerMap[clean] || [];
+ const isSpeakingNow = liveSpokenWordIndex === idx;
+
+ return (
+ <button
+ key={`${w}-${idx}`}
+ onClick={() => handleWordChipClick(w)}
+ className={`inline-flex items-center gap-1 px-2 py-1 rounded-lg text-xs font-medium transition-all cursor-pointer border ${
+ isSpeakingNow
+ ? 'bg-amber-400 text-slate-950 font-black border-amber-300 scale-110 shadow-[0_0_18px_rgba(251,191,36,0.95)] ring-2 ring-amber-300 z-10 animate-pulse'
+ : isAttachedToSelected
+ ? 'bg-amber-400 text-slate-950 font-bold border-amber-300 shadow-[0_0_12px_rgba(251,191,36,0.4)] scale-105'
+ : attachedElements.length > 0
+ ? 'bg-cyan-950/60 border-cyan-500/40 text-cyan-300 hover:border-cyan-400'
+ : 'bg-slate-950/60 border-slate-800/80 text-slate-300 hover:border-slate-700 hover:bg-slate-800/60'
+ }`}
+ title={
+ isSpeakingNow
+ ? `Currently speaking: "${w}"`
+ : selectedElement
+ ? `Click to trigger "${selectedElement.label || selectedElement.type}" on "${w}"`
+ : `${attachedElements.length} element(s) trigger here`
+ }
+ >
+ <span>{w}</span>
+ {attachedElements.length > 0 && !isAttachedToSelected && !isSpeakingNow && (
+ <span className="w-1.5 h-1.5 rounded-full bg-cyan-400" />
+ )}
+ {isAttachedToSelected && !isSpeakingNow && (
+ <Check className="w-3 h-3 text-slate-950 stroke-[3]" />
+ )}
+ {isSpeakingNow && (
+ <span className="w-1.5 h-1.5 rounded-full bg-slate-950 animate-ping" />
+ )}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/src/components/explainroo/TemplatesModal.tsx b/src/components/explainroo/TemplatesModal.tsx
new file mode 100644
index 0000000..ecc1c43
--- /dev/null
+++ b/src/components/explainroo/TemplatesModal.tsx
@@ -0,0 +1,87 @@
+import { X, ArrowRight, Layers } from 'lucide-react';
+import { Project } from '../../types/explainroo';
+import { PREBUILT_TEMPLATES } from '../../templates/prebuiltTemplates';
+import { audioEngine } from '../../utils/audioEngine';
+
+interface TemplatesModalProps {
+ isOpen: boolean;
+ onClose: () => void;
+ onSelectTemplate: (project: Project) => void;
+}
+
+export const TemplatesModal: React.FC<TemplatesModalProps> = ({
+ isOpen,
+ onClose,
+ onSelectTemplate,
+}) => {
+ if (!isOpen) return null;
+
+ return (
+ <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/80 backdrop-blur-md animate-fade-in">
+ <div className="relative w-full max-w-2xl bg-slate-900 border border-slate-800 rounded-2xl p-6 shadow-2xl flex flex-col max-h-[85vh]">
+ {/* Header */}
+ <div className="flex items-center justify-between pb-4 border-b border-slate-800">
+ <div className="flex items-center gap-2">
+ <Layers className="w-5 h-5 text-amber-400" />
+ <div>
+ <h3 className="text-base font-bold text-white tracking-tight">
+ Pre-built Explainer Templates
+ </h3>
+ <p className="text-xs text-slate-400">
+ Jumpstart your video with hand-crafted diagrams and scripts
+ </p>
+ </div>
+ </div>
+ <button
+ onClick={onClose}
+ className="p-1.5 text-slate-400 hover:text-white rounded-lg hover:bg-slate-800 transition-colors cursor-pointer"
+ >
+ <X className="w-5 h-5" />
+ </button>
+ </div>
+
+ {/* Templates Grid */}
+ <div className="py-4 grid grid-cols-1 sm:grid-cols-2 gap-3 overflow-y-auto pr-1">
+ {PREBUILT_TEMPLATES.map((tmpl) => (
+ <div
+ key={tmpl.id}
+ className="p-4 rounded-xl bg-slate-950 border border-slate-800/80 hover:border-slate-700 hover:bg-slate-950/90 transition-all flex flex-col justify-between group"
+ >
+ <div>
+ <div className="flex items-center justify-between text-[11px] font-mono text-slate-400 mb-2">
+ <span className="capitalize px-2 py-0.5 rounded bg-slate-900 border border-slate-800 text-amber-300">
+ {tmpl.look} look
+ </span>
+ <span>{tmpl.scenes.length} Scenes</span>
+ </div>
+ <h4 className="text-sm font-bold text-slate-100 group-hover:text-amber-400 transition-colors">
+ {tmpl.title}
+ </h4>
+ <p className="text-xs text-slate-400 mt-1 line-clamp-2 leading-relaxed">
+ {tmpl.description}
+ </p>
+ </div>
+
+ <div className="pt-4 mt-2 flex items-center justify-between border-t border-slate-800/60">
+ <span className="text-[11px] text-slate-500 font-mono">
+ Music: {tmpl.musicTrack}
+ </span>
+ <button
+ onClick={() => {
+ onSelectTemplate(tmpl);
+ audioEngine.playDrawChime();
+ onClose();
+ }}
+ className="flex items-center gap-1 px-3 py-1.5 bg-amber-500/15 hover:bg-amber-500/25 border border-amber-500/30 text-amber-300 text-xs font-semibold rounded-lg transition-colors cursor-pointer"
+ >
+ <span>Load Project</span>
+ <ArrowRight className="w-3.5 h-3.5" />
+ </button>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/src/components/explainroo/VideoPlayer.tsx b/src/components/explainroo/VideoPlayer.tsx
new file mode 100644
index 0000000..455b01a
--- /dev/null
+++ b/src/components/explainroo/VideoPlayer.tsx
@@ -0,0 +1,553 @@
+import React, { useRef, useEffect, useState, useCallback } from 'react';
+import {
+ Play,
+ Pause,
+ RotateCcw,
+ Volume2,
+ VolumeX,
+ Music,
+ Maximize2,
+ Minimize2,
+ ChevronLeft,
+ ChevronRight,
+} from 'lucide-react';
+import { Scene, ThemeLook } from '../../types/explainroo';
+import { renderSceneToCanvas } from '../../utils/canvasRenderer';
+import { audioEngine } from '../../utils/audioEngine';
+
+interface VideoPlayerProps {
+ scene: Scene;
+ theme: ThemeLook;
+ selectedElementId: string | null;
+ onSelectElement: (id: string | null) => void;
+ onUpdateElementPosition: (id: string, x: number, y: number) => void;
+ currentSceneIndex: number;
+ totalScenes: number;
+ onPrevScene: () => void;
+ onNextScene: () => void;
+ musicTrack: string;
+ autoDuck: boolean;
+ voiceRate: number;
+ voicePitch: number;
+}
+
+export const VideoPlayer: React.FC<VideoPlayerProps> = ({
+ scene,
+ theme,
+ selectedElementId,
+ onSelectElement,
+ onUpdateElementPosition,
+ currentSceneIndex,
+ totalScenes,
+ onPrevScene,
+ onNextScene,
+ musicTrack,
+ voiceRate,
+ voicePitch,
+}) => {
+ const canvasRef = useRef<HTMLCanvasElement | null>(null);
+ const containerRef = useRef<HTMLDivElement | null>(null);
+
+ const [isPlaying, setIsPlaying] = useState<boolean>(false);
+ const [currentTime, setCurrentTime] = useState<number>(0);
+ const [playbackSpeed, setPlaybackSpeed] = useState<number>(1);
+ const [isVoiceMuted, setIsVoiceMuted] = useState<boolean>(false);
+ const [isMusicEnabled, setIsMusicEnabled] = useState<boolean>(true);
+ const [isFullscreen, setIsFullscreen] = useState<boolean>(false);
+ const [isSubtitlesEnabled, setIsSubtitlesEnabled] = useState<boolean>(true);
+ const [liveWordIndex, setLiveWordIndex] = useState<number>(-1);
+
+ // Subscribe to real-time word boundary notifications from AudioEngine
+ useEffect(() => {
+ const unsub = audioEngine.addWordListener((_word, _charIdx, wordIdx) => {
+ setLiveWordIndex(wordIdx);
+ });
+ return () => unsub();
+ }, []);
+
+ // Dragging state for interactive canvas editing
+ const [draggingElementId, setDraggingElementId] = useState<string | null>(null);
+ const [dragOffset, setDragOffset] = useState<{ x: number; y: number }>({ x: 0, y: 0 });
+
+ const duration = scene.durationSeconds || 7;
+
+ // Render canvas whenever state changes
+ const redrawCanvas = useCallback(
+ (time: number, selectedId: string | null) => {
+ const canvas = canvasRef.current;
+ if (!canvas) return;
+ renderSceneToCanvas({
+ canvas,
+ scene,
+ currentTime: time,
+ theme,
+ selectedElementId: selectedId,
+ interactiveMode: !isPlaying,
+ });
+ },
+ [scene, theme, isPlaying]
+ );
+
+ // Redraw when scene, time, theme, or selection changes
+ useEffect(() => {
+ redrawCanvas(currentTime, selectedElementId);
+ }, [redrawCanvas, currentTime, selectedElementId]);
+
+ // Reset playback time and live subtitle sync when scene changes
+ useEffect(() => {
+ setCurrentTime(0);
+ setLiveWordIndex(-1);
+ }, [scene.id]);
+
+ // Keep a ref to the latest time so the rAF loop does not need to call parent callbacks inside setState
+ const currentTimeRef = useRef<number>(0);
+ currentTimeRef.current = currentTime;
+
+ // Animation frame loop for smooth playback
+ useEffect(() => {
+ let animId: number;
+ let lastTimestamp: number | null = null;
+
+ if (isPlaying) {
+ if (isMusicEnabled) {
+ audioEngine.startMusic(musicTrack);
+ }
+
+ // Trigger voiceover (custom uploaded audio or Web Speech synthesis)
+ if (!isVoiceMuted) {
+ if (scene.customAudioUrl) {
+ audioEngine.playCustomAudio(scene.customAudioUrl);
+ } else if (scene.narration) {
+ audioEngine.speakNarration(
+ scene.narration,
+ (_word, _charIdx, wordIdx) => {
+ setLiveWordIndex(wordIdx);
+ },
+ () => {
+ setLiveWordIndex(-1);
+ },
+ voiceRate,
+ voicePitch
+ );
+ }
+ }
+
+ const loop = (timestamp: number) => {
+ if (!lastTimestamp) lastTimestamp = timestamp;
+ const delta = (timestamp - lastTimestamp) / 1000;
+ lastTimestamp = timestamp;
+
+ const nextTime = currentTimeRef.current + delta * playbackSpeed;
+
+ if (nextTime >= duration) {
+ if (currentSceneIndex < totalScenes - 1) {
+ setCurrentTime(0);
+ setLiveWordIndex(-1);
+ onNextScene();
+ } else {
+ setCurrentTime(duration);
+ setIsPlaying(false);
+ setLiveWordIndex(-1);
+ audioEngine.stopSpeaking();
+ return;
+ }
+ } else {
+ setCurrentTime(nextTime);
+ }
+
+ animId = requestAnimationFrame(loop);
+ };
+
+ animId = requestAnimationFrame(loop);
+ } else {
+ setLiveWordIndex(-1);
+ audioEngine.stopSpeaking();
+ }
+
+ return () => {
+ if (animId) cancelAnimationFrame(animId);
+ setLiveWordIndex(-1);
+ audioEngine.stopSpeaking();
+ };
+ }, [
+ isPlaying,
+ playbackSpeed,
+ duration,
+ currentSceneIndex,
+ totalScenes,
+ onNextScene,
+ isMusicEnabled,
+ musicTrack,
+ isVoiceMuted,
+ scene.narration,
+ voiceRate,
+ voicePitch,
+ ]);
+
+ const togglePlay = () => {
+ if (currentTime >= duration) {
+ setCurrentTime(0);
+ }
+ setIsPlaying((prev) => !prev);
+ };
+
+ const handleRewind = () => {
+ setIsPlaying(false);
+ setCurrentTime(0);
+ setLiveWordIndex(-1);
+ audioEngine.stopSpeaking();
+ audioEngine.playWhoosh();
+ };
+
+ const handleSeek = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const newTime = parseFloat(e.target.value);
+ setCurrentTime(newTime);
+ if (!isPlaying) {
+ setLiveWordIndex(-1);
+ }
+ };
+
+ // Canvas Mouse / Touch interactions for direct visual manipulation
+ const getCanvasCoords = (clientX: number, clientY: number) => {
+ const canvas = canvasRef.current;
+ if (!canvas) return { x: 0, y: 0 };
+ const rect = canvas.getBoundingClientRect();
+ const scaleX = canvas.width / rect.width;
+ const scaleY = canvas.height / rect.height;
+ return {
+ x: (clientX - rect.left) * scaleX,
+ y: (clientY - rect.top) * scaleY,
+ };
+ };
+
+ const handlePointerDown = (e: React.PointerEvent<HTMLCanvasElement>) => {
+ if (isPlaying) return;
+ const { x, y } = getCanvasCoords(e.clientX, e.clientY);
+
+ // Hit test reverse (top-most elements first)
+ const reversed = [...scene.elements].reverse();
+ const hit = reversed.find((el) => {
+ return (
+ x >= el.x &&
+ x <= el.x + el.width &&
+ y >= el.y &&
+ y <= el.y + el.height
+ );
+ });
+
+ if (hit) {
+ onSelectElement(hit.id);
+ setDraggingElementId(hit.id);
+ setDragOffset({ x: x - hit.x, y: y - hit.y });
+ audioEngine.playPop();
+ } else {
+ onSelectElement(null);
+ setDraggingElementId(null);
+ }
+ };
+
+ const handlePointerMove = (e: React.PointerEvent<HTMLCanvasElement>) => {
+ if (!draggingElementId || isPlaying) return;
+ const { x, y } = getCanvasCoords(e.clientX, e.clientY);
+ const newX = Math.round(x - dragOffset.x);
+ const newY = Math.round(y - dragOffset.y);
+ onUpdateElementPosition(draggingElementId, newX, newY);
+ };
+
+ const handlePointerUp = () => {
+ setDraggingElementId(null);
+ };
+
+ // Fullscreen toggle
+ const toggleFullscreen = () => {
+ if (!document.fullscreenElement) {
+ containerRef.current?.requestFullscreen().catch(() => {});
+ setIsFullscreen(true);
+ } else {
+ document.exitFullscreen().catch(() => {});
+ setIsFullscreen(false);
+ }
+ };
+
+ return (
+ <div
+ ref={containerRef}
+ className="flex flex-col bg-slate-950 border border-slate-800 rounded-2xl overflow-hidden shadow-2xl relative select-none"
+ >
+ {/* 16:9 Cinema Canvas Container */}
+ <div className="relative w-full aspect-video bg-slate-950 flex items-center justify-center overflow-hidden">
+ <canvas
+ ref={canvasRef}
+ width={1280}
+ height={720}
+ onPointerDown={handlePointerDown}
+ onPointerMove={handlePointerMove}
+ onPointerUp={handlePointerUp}
+ className="w-full h-full object-contain cursor-crosshair touch-none"
+ title="Click or drag elements on the canvas to position them"
+ />
+
+ {/* Big Center Play Overlay Button when paused at beginning */}
+ {!isPlaying && currentTime === 0 && (
+ <button
+ onClick={togglePlay}
+ className="absolute inset-0 flex items-center justify-center bg-slate-950/20 hover:bg-slate-950/30 transition-colors group cursor-pointer"
+ >
+ <div className="w-16 h-16 rounded-full bg-amber-500 hover:bg-amber-400 text-slate-950 flex items-center justify-center shadow-[0_0_30px_rgba(245,158,11,0.5)] group-hover:scale-110 transition-transform">
+ <Play className="w-7 h-7 fill-slate-950 ml-1" />
+ </div>
+ </button>
+ )}
+
+ {/* Scene Indicator Stamp */}
+ <div className="absolute top-3 left-4 bg-slate-900/90 backdrop-blur border border-slate-700/80 px-2.5 py-1 rounded-md text-[11px] font-mono text-slate-300 pointer-events-none">
+ Scene {currentSceneIndex + 1} / {totalScenes} · {scene.title}
+ </div>
+
+ {/* Whisper-style Dynamic Captions: Pure Yellow Word Highlight */}
+ {isSubtitlesEnabled && scene.narration && (
+ <div className="absolute bottom-4 inset-x-0 flex justify-center pointer-events-none z-20 px-4">
+ <div className="inline-flex items-center px-4 py-2 rounded-2xl bg-slate-950/90 backdrop-blur-md border border-slate-700/80 shadow-[0_4px_24px_rgba(0,0,0,0.7)] text-center max-w-[90%]">
+ <p className="text-xs sm:text-sm font-semibold tracking-wide text-slate-300 flex flex-wrap justify-center items-center gap-1.5 leading-relaxed">
+ {(() => {
+ const words = scene.narration.split(/\s+/).filter(Boolean);
+ if (words.length === 0) return null;
+ const progress = Math.min(0.999, Math.max(0, currentTime / Math.max(0.1, duration)));
+ const computedFallbackIdx = Math.min(words.length - 1, Math.floor(progress * words.length));
+ const activeIdx =
+ isPlaying && liveWordIndex >= 0 && liveWordIndex < words.length
+ ? liveWordIndex
+ : computedFallbackIdx;
+
+ // Rolling window of up to 7 words centered around active word
+ const windowSize = Math.min(words.length, 7);
+ const half = Math.floor(windowSize / 2);
+ let startIdx = Math.max(0, activeIdx - half);
+ let endIdx = Math.min(words.length, startIdx + windowSize);
+ if (endIdx - startIdx < windowSize) {
+ startIdx = Math.max(0, endIdx - windowSize);
+ }
+
+ return words.slice(startIdx, endIdx).map((w, sliceIdx) => {
+ const actualIdx = startIdx + sliceIdx;
+ const isCurrent = actualIdx === activeIdx;
+ const isPast = actualIdx < activeIdx;
+ return (
+ <span
+ key={actualIdx}
+ className={`inline-block px-1.5 py-0.5 rounded transition-all duration-150 ${
+ isCurrent
+ ? 'bg-amber-400 text-slate-950 font-black scale-110 shadow-[0_0_16px_rgba(251,191,36,0.9)] ring-2 ring-amber-300'
+ : isPast
+ ? 'text-slate-400 font-medium'
+ : 'text-slate-200 font-medium'
+ }`}
+ >
+ {w}
+ </span>
+ );
+ });
+ })()}
+ </p>
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Floating Scrub Timeline & Playback Bar */}
+ <div className="bg-slate-900/95 border-t border-slate-800 p-3 sm:px-5 flex flex-col gap-2">
+ {/* Timeline Range Scrubber */}
+ <div className="flex items-center gap-3">
+ <span className="text-[11px] font-mono tabular-nums text-slate-400 w-12 text-right">
+ {currentTime.toFixed(1)}s
+ </span>
+
+ <div className="flex-1 relative flex items-center">
+ <input
+ type="range"
+ min={0}
+ max={duration}
+ step={0.05}
+ value={currentTime}
+ onChange={handleSeek}
+ className="w-full h-1.5 bg-slate-800 rounded-lg appearance-none cursor-pointer accent-amber-400 hover:accent-amber-300"
+ />
+
+ {/* Word Anchors Tick Marks on Timeline */}
+ <div className="absolute inset-x-0 -bottom-3 flex justify-between pointer-events-none px-1">
+ {scene.elements.map((el) => {
+ const leftPercent = ((el.triggerTimeSec || 0) / duration) * 100;
+ return (
+ <div
+ key={el.id}
+ style={{ left: `${leftPercent}%` }}
+ className="absolute -top-1 w-1.5 h-1.5 rounded-full bg-cyan-400"
+ title={`"${el.label || el.type}" triggers at ${el.triggerTimeSec?.toFixed(1)}s`}
+ />
+ );
+ })}
+ </div>
+ </div>
+
+ <span className="text-[11px] font-mono tabular-nums text-slate-400 w-12">
+ {duration.toFixed(1)}s
+ </span>
+ </div>
+
+ {/* Interactive Cue Markers Row */}
+ {scene.elements.length > 0 && (
+ <div className="flex items-center gap-1.5 overflow-x-auto py-0.5 text-[10px] scrollbar-none">
+ <span className="text-[9px] font-bold text-slate-500 uppercase tracking-widest shrink-0">
+ Cues:
+ </span>
+ {scene.elements.map((el) => {
+ const t = el.triggerTimeSec || 0;
+ const isPassed = currentTime >= t;
+ const isSelected = selectedElementId === el.id;
+ return (
+ <button
+ key={el.id}
+ onClick={() => {
+ setCurrentTime(t);
+ onSelectElement(el.id);
+ }}
+ className={`px-2 py-0.5 rounded-md border flex items-center gap-1 shrink-0 transition-colors cursor-pointer text-[10px] ${
+ isSelected
+ ? 'bg-cyan-500/20 border-cyan-400 text-cyan-300 font-semibold'
+ : isPassed
+ ? 'bg-slate-800/90 border-slate-750 text-slate-200'
+ : 'bg-slate-950/70 border-slate-800 text-slate-500 hover:text-slate-300'
+ }`}
+ title={`Jump to ${el.label || el.type} (${t.toFixed(1)}s)`}
+ >
+ <span
+ className="w-1.5 h-1.5 rounded-full shrink-0"
+ style={{ backgroundColor: el.color || '#38bdf8' }}
+ />
+ <span className="truncate max-w-[100px]">{el.label || el.type}</span>
+ <span className="font-mono text-[9px] opacity-60">{t.toFixed(1)}s</span>
+ </button>
+ );
+ })}
+ </div>
+ )}
+
+ {/* Transport Controls */}
+ <div className="flex items-center justify-between flex-wrap gap-2 pt-1">
+ {/* Left: Scene Jumpers & Play */}
+ <div className="flex items-center gap-1.5 sm:gap-2">
+ <button
+ onClick={onPrevScene}
+ disabled={currentSceneIndex === 0}
+ className="p-1.5 rounded-lg text-slate-400 hover:text-white disabled:opacity-40 hover:bg-slate-800 transition-colors cursor-pointer"
+ title="Previous Scene"
+ >
+ <ChevronLeft className="w-4 h-4" />
+ </button>
+
+ <button
+ onClick={togglePlay}
+ className="p-2 rounded-xl bg-amber-400 hover:bg-amber-300 text-slate-950 font-bold transition-transform active:scale-95 cursor-pointer shadow-[0_0_15px_rgba(251,191,36,0.3)]"
+ title={isPlaying ? 'Pause (Space)' : 'Play (Space)'}
+ >
+ {isPlaying ? <Pause className="w-4 h-4 fill-slate-950" /> : <Play className="w-4 h-4 fill-slate-950 ml-0.5" />}
+ </button>
+
+ <button
+ onClick={onNextScene}
+ disabled={currentSceneIndex >= totalScenes - 1}
+ className="p-1.5 rounded-lg text-slate-400 hover:text-white disabled:opacity-40 hover:bg-slate-800 transition-colors cursor-pointer"
+ title="Next Scene"
+ >
+ <ChevronRight className="w-4 h-4" />
+ </button>
+
+ <button
+ onClick={handleRewind}
+ className="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-slate-800 transition-colors cursor-pointer ml-1"
+ title="Rewind to start"
+ >
+ <RotateCcw className="w-3.5 h-3.5" />
+ </button>
+ </div>
+
+ {/* Right: Audio Toggles & Speed */}
+ <div className="flex items-center gap-2 sm:gap-3 text-xs">
+ {/* CC Subtitles Toggle */}
+ <button
+ onClick={() => setIsSubtitlesEnabled((s) => !s)}
+ className={`px-1.5 py-0.5 rounded-md border font-mono text-[10px] font-bold tracking-wider transition-colors cursor-pointer ${
+ isSubtitlesEnabled
+ ? 'bg-amber-400/20 border-amber-400/50 text-amber-300'
+ : 'bg-slate-950 border-slate-800 text-slate-500 hover:text-slate-400'
+ }`}
+ title={isSubtitlesEnabled ? 'Live Subtitles Enabled (CC)' : 'Live Subtitles Disabled'}
+ >
+ CC
+ </button>
+
+ {/* Speed Selector */}
+ <div className="flex items-center gap-0.5 bg-slate-950 px-1 py-0.5 rounded-md border border-slate-800 font-mono text-[11px]">
+ {[0.75, 1, 1.25].map((spd) => (
+ <button
+ key={spd}
+ onClick={() => setPlaybackSpeed(spd)}
+ className={`px-1.5 py-0.5 rounded cursor-pointer ${
+ playbackSpeed === spd
+ ? 'bg-amber-400/20 text-amber-300 font-bold'
+ : 'text-slate-400 hover:text-white'
+ }`}
+ >
+ {spd}x
+ </button>
+ ))}
+ </div>
+
+ {/* Voice Narration Audio Toggle */}
+ <button
+ onClick={() => setIsVoiceMuted((v) => !v)}
+ className={`p-1.5 rounded-lg border transition-colors cursor-pointer ${
+ isVoiceMuted
+ ? 'bg-rose-500/10 border-rose-500/30 text-rose-400'
+ : 'bg-slate-800 border-slate-700 text-slate-300 hover:text-white'
+ }`}
+ title={isVoiceMuted ? 'Voiceover Muted' : 'Voiceover Active'}
+ >
+ {isVoiceMuted ? <VolumeX className="w-3.5 h-3.5" /> : <Volume2 className="w-3.5 h-3.5" />}
+ </button>
+
+ {/* Background Music Toggle */}
+ <button
+ onClick={() => {
+ if (isMusicEnabled) {
+ audioEngine.stopMusic();
+ setIsMusicEnabled(false);
+ } else {
+ setIsMusicEnabled(true);
+ if (isPlaying) audioEngine.startMusic(musicTrack);
+ }
+ }}
+ className={`p-1.5 rounded-lg border transition-colors cursor-pointer ${
+ isMusicEnabled
+ ? 'bg-amber-500/15 border-amber-500/30 text-amber-300'
+ : 'bg-slate-800 border-slate-700 text-slate-500'
+ }`}
+ title={isMusicEnabled ? 'Music Enabled (Auto-Ducked)' : 'Music Disabled'}
+ >
+ <Music className="w-3.5 h-3.5" />
+ </button>
+
+ {/* Fullscreen */}
+ <button
+ onClick={toggleFullscreen}
+ className="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-slate-800 transition-colors cursor-pointer"
+ title="Toggle Fullscreen"
+ >
+ {isFullscreen ? <Minimize2 className="w-3.5 h-3.5" /> : <Maximize2 className="w-3.5 h-3.5" />}
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/src/components/explainroo/VisualToolbox.tsx b/src/components/explainroo/VisualToolbox.tsx
new file mode 100644
index 0000000..3c08b09
--- /dev/null
+++ b/src/components/explainroo/VisualToolbox.tsx
@@ -0,0 +1,262 @@
+import React from 'react';
+import {
+ Server,
+ Database,
+ Cloud,
+ Laptop,
+ Shield,
+ Layout,
+ Terminal,
+ Smartphone,
+ Square,
+ Circle,
+ MoveRight,
+ Code,
+ Type,
+ CheckCircle2,
+ Tag,
+ Zap,
+ Key,
+ Globe,
+ User,
+} from 'lucide-react';
+import { ElementType, VisualElement } from '../../types/explainroo';
+import { audioEngine } from '../../utils/audioEngine';
+
+interface VisualToolboxProps {
+ onAddElement: (element: Partial<VisualElement>) => void;
+ primaryColor: string;
+}
+
+export const VisualToolbox: React.FC<VisualToolboxProps> = ({
+ onAddElement,
+ primaryColor,
+}) => {
+ const tools = [
+ {
+ category: 'Architecture',
+ items: [
+ {
+ type: 'client' as ElementType,
+ label: 'Client Laptop',
+ icon: Laptop,
+ def: { width: 180, height: 130, color: '#38bdf8', label: 'Client App' },
+ },
+ {
+ type: 'server' as ElementType,
+ label: 'Server Rack',
+ icon: Server,
+ def: { width: 180, height: 120, color: '#10b981', label: 'Node Server' },
+ },
+ {
+ type: 'database' as ElementType,
+ label: 'Database',
+ icon: Database,
+ def: { width: 160, height: 150, color: '#a855f7', label: 'PostgreSQL DB' },
+ },
+ {
+ type: 'cloud' as ElementType,
+ label: 'Cloud / DNS',
+ icon: Cloud,
+ def: { width: 220, height: 140, color: '#3b82f6', label: 'Cloud Service' },
+ },
+ {
+ type: 'api_gateway' as ElementType,
+ label: 'API Gateway',
+ icon: Shield,
+ def: { width: 170, height: 150, color: '#fbbf24', label: 'API Gateway' },
+ },
+ ],
+ },
+ {
+ category: 'UI Mockups',
+ items: [
+ {
+ type: 'browser_window' as ElementType,
+ label: 'Browser Window',
+ icon: Layout,
+ def: {
+ width: 380,
+ height: 220,
+ color: '#3b82f6',
+ label: 'Web Application UI',
+ url: 'https://app.io',
+ },
+ },
+ {
+ type: 'terminal_window' as ElementType,
+ label: 'Terminal Window',
+ icon: Terminal,
+ def: {
+ width: 360,
+ height: 180,
+ color: '#38bdf8',
+ label: 'npm install explainroo',
+ subtext: 'Ready',
+ },
+ },
+ {
+ type: 'phone_mockup' as ElementType,
+ label: 'Phone Screen',
+ icon: Smartphone,
+ def: { width: 140, height: 240, color: '#0f172a', label: 'Mobile App' },
+ },
+ ],
+ },
+ {
+ category: 'Shapes & Arrows',
+ items: [
+ {
+ type: 'arrow' as ElementType,
+ label: 'Straight Arrow',
+ icon: MoveRight,
+ def: { width: 160, height: 0, color: '#f97316', label: 'Request' },
+ },
+ {
+ type: 'rectangle' as ElementType,
+ label: 'Box Container',
+ icon: Square,
+ def: { width: 180, height: 120, color: primaryColor, label: 'Component' },
+ },
+ {
+ type: 'circle' as ElementType,
+ label: 'Circle / Node',
+ icon: Circle,
+ def: { width: 110, height: 110, color: primaryColor, label: 'Node' },
+ },
+ {
+ type: 'checkmark' as ElementType,
+ label: 'Checkmark Stamp',
+ icon: CheckCircle2,
+ def: { width: 70, height: 70, color: '#10b981' },
+ },
+ {
+ type: 'badge' as ElementType,
+ label: 'Step Badge',
+ icon: Tag,
+ def: { width: 120, height: 38, color: '#fbbf24', label: 'Step 1' },
+ },
+ ],
+ },
+ {
+ category: 'Code & Text',
+ items: [
+ {
+ type: 'code_block' as ElementType,
+ label: 'Code Block',
+ icon: Code,
+ def: {
+ width: 320,
+ height: 150,
+ color: '#38bdf8',
+ codeSnippet: 'const api = createClient();\nawait api.connect();',
+ },
+ },
+ {
+ type: 'text' as ElementType,
+ label: 'Title Text',
+ icon: Type,
+ def: { width: 280, height: 32, color: primaryColor, label: 'Core Mechanism' },
+ },
+ ],
+ },
+ {
+ category: 'Tech & Network Icons',
+ items: [
+ {
+ type: 'icon' as ElementType,
+ label: 'Redis / Cache',
+ icon: Zap,
+ def: { width: 70, height: 70, color: '#ef4444', iconName: 'zap', label: 'Cache' },
+ },
+ {
+ type: 'icon' as ElementType,
+ label: 'Auth / Token',
+ icon: Key,
+ def: { width: 70, height: 70, color: '#f59e0b', iconName: 'key', label: 'JWT' },
+ },
+ {
+ type: 'icon' as ElementType,
+ label: 'Global CDN / Web',
+ icon: Globe,
+ def: { width: 70, height: 70, color: '#06b6d4', iconName: 'globe', label: 'Edge CDN' },
+ },
+ {
+ type: 'icon' as ElementType,
+ label: 'Client User',
+ icon: User,
+ def: { width: 70, height: 70, color: '#ec4899', iconName: 'user', label: 'End User' },
+ },
+ ],
+ },
+ ];
+
+ const handleItemClick = (item: any) => {
+ // Generate at randomized center coordinate
+ const offsetX = Math.floor(Math.random() * 80) - 40;
+ const offsetY = Math.floor(Math.random() * 60) - 30;
+
+ const newElement: Partial<VisualElement> = {
+ id: `el-${Date.now()}`,
+ type: item.type,
+ x: 640 - item.def.width / 2 + offsetX,
+ y: 360 - item.def.height / 2 + offsetY,
+ width: item.def.width,
+ height: item.def.height,
+ color: item.def.color,
+ label: item.def.label,
+ subtext: item.def.subtext,
+ url: item.def.url,
+ codeSnippet: item.def.codeSnippet,
+ iconName: item.def.iconName,
+ strokeWidth: 2.5,
+ roughness: 1.4,
+ animation: 'pop',
+ triggerTimeSec: 0.5,
+ };
+
+ onAddElement(newElement);
+ audioEngine.playPop();
+ };
+
+ return (
+ <div className="bg-slate-900 border border-slate-800 rounded-2xl p-4 flex flex-col gap-4">
+ <div className="flex items-center justify-between pb-2 border-b border-slate-800">
+ <div>
+ <h3 className="text-xs font-bold uppercase tracking-wider text-slate-300">Visual Toolbox</h3>
+ <p className="text-[11px] text-slate-500">Click to add diagrams and mockups</p>
+ </div>
+ </div>
+
+ <div className="space-y-4">
+ {tools.map((section) => (
+ <div key={section.category}>
+ <span className="text-[10px] font-semibold tracking-wider uppercase text-slate-400 block mb-2">
+ {section.category}
+ </span>
+ <div className="grid grid-cols-2 gap-1.5">
+ {section.items.map((item) => {
+ const IconComponent = item.icon;
+ return (
+ <button
+ key={item.label}
+ onClick={() => handleItemClick(item)}
+ className="flex items-center gap-2 p-2 rounded-xl bg-slate-950/60 hover:bg-slate-800 border border-slate-800/80 hover:border-slate-700 text-left transition-colors cursor-pointer group active:scale-95"
+ title={`Add ${item.label} to scene`}
+ >
+ <div className="w-6 h-6 rounded-lg bg-slate-900 flex items-center justify-center shrink-0 group-hover:bg-amber-400/10 transition-colors">
+ <IconComponent className="w-3.5 h-3.5 text-slate-400 group-hover:text-amber-400" />
+ </div>
+ <span className="text-xs font-medium text-slate-300 truncate">
+ {item.label}
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+};
diff --git a/src/index.css b/src/index.css
new file mode 100644
index 0000000..473bae8
--- /dev/null
+++ b/src/index.css
@@ -0,0 +1,50 @@
+@import "tailwindcss";
+@custom-variant dark (&:where(.dark, .dark *));
+
+@layer base {
+ * {
+ box-sizing: border-box;
+ -webkit-tap-highlight-color: transparent;
+ }
+
+ body {
+ font-family: 'Plus Jakarta Sans', system-ui, -apple-system, sans-serif;
+ background-color: #020617;
+ color: #f8fafc;
+ }
+}
+
+/* Custom scrollbars for timeline and lists */
+.scrollbar-thin::-webkit-scrollbar {
+ height: 6px;
+ width: 6px;
+}
+
+.scrollbar-thin::-webkit-scrollbar-track {
+ background: rgba(15, 23, 42, 0.6);
+ border-radius: 9999px;
+}
+
+.scrollbar-thin::-webkit-scrollbar-thumb {
+ background: rgba(51, 65, 85, 0.8);
+ border-radius: 9999px;
+}
+
+.scrollbar-thin::-webkit-scrollbar-thumb:hover {
+ background: rgba(100, 116, 139, 1);
+}
+
+@keyframes fadeIn {
+ from {
+ opacity: 0;
+ transform: scale(0.98);
+ }
+ to {
+ opacity: 1;
+ transform: scale(1);
+ }
+}
+
+.animate-fade-in {
+ animation: fadeIn 0.15s cubic-bezier(0.16, 1, 0.3, 1) forwards;
+}
diff --git a/src/main.tsx b/src/main.tsx
new file mode 100644
index 0000000..a64bea3
--- /dev/null
+++ b/src/main.tsx
@@ -0,0 +1,21 @@
+import React from 'react';
+import ReactDOM from 'react-dom/client';
+import { App } from './App';
+import './index.css';
+import { registerSW } from 'virtual:pwa-register';
+
+registerSW({
+ immediate: true,
+ onNeedRefresh() {
+ console.log('Explainroo Studio PWA update available');
+ },
+ onOfflineReady() {
+ console.log('Explainroo Studio ready for offline creation');
+ },
+});
+
+ReactDOM.createRoot(document.getElementById('root')!).render(
+ <React.StrictMode>
+ <App />
+ </React.StrictMode>
+);
diff --git a/src/templates/prebuiltTemplates.ts b/src/templates/prebuiltTemplates.ts
new file mode 100644
index 0000000..0a1f894
--- /dev/null
+++ b/src/templates/prebuiltTemplates.ts
@@ -0,0 +1,566 @@
+import { Project } from '../types/explainroo';
+
+export const PREBUILT_TEMPLATES: Project[] = [
+ {
+ id: 'dns-explainer',
+ title: 'How DNS Works: From URL to Website',
+ description: 'A visual journey showing how your browser turns human names into IP addresses in under 50 milliseconds.',
+ look: 'whiteboard',
+ musicTrack: 'lofi',
+ musicVolume: 0.3,
+ voicePitch: 1.0,
+ voiceRate: 1.0,
+ autoDuck: true,
+ scenes: [
+ {
+ id: 'dns-s1',
+ title: 'Entering the Web Address',
+ narration: 'Whenever you open your browser and type google.com, your computer has no idea where that server is. It needs an IP address.',
+ durationSeconds: 7,
+ transition: 'fade',
+ elements: [
+ {
+ id: 'e-client-1',
+ type: 'client',
+ x: 180,
+ y: 280,
+ width: 220,
+ height: 150,
+ label: 'Your Computer',
+ color: '#0f172a',
+ strokeWidth: 3,
+ animation: 'pop',
+ triggerWord: 'computer',
+ triggerTimeSec: 0.5,
+ },
+ {
+ id: 'e-browser-1',
+ type: 'browser_window',
+ x: 520,
+ y: 200,
+ width: 540,
+ height: 280,
+ label: 'Searching for google.com...',
+ url: 'https://google.com',
+ color: '#3b82f6',
+ strokeWidth: 2.5,
+ animation: 'slide',
+ triggerWord: 'browser',
+ triggerTimeSec: 1.8,
+ },
+ {
+ id: 'e-arrow-1',
+ type: 'arrow',
+ x: 410,
+ y: 340,
+ width: 100,
+ height: 0,
+ label: 'Requests URL',
+ color: '#f97316',
+ strokeWidth: 2.5,
+ animation: 'draw',
+ triggerWord: 'type',
+ triggerTimeSec: 3.2,
+ },
+ ],
+ },
+ {
+ id: 'dns-s2',
+ title: 'The Recursive Resolver',
+ narration: 'Your computer sends a query to a recursive resolver, usually managed by your internet service provider or Cloudflare.',
+ durationSeconds: 7,
+ transition: 'fade',
+ elements: [
+ {
+ id: 'e-client-2',
+ type: 'client',
+ x: 150,
+ y: 290,
+ width: 200,
+ height: 130,
+ label: 'Client',
+ color: '#0f172a',
+ strokeWidth: 2.5,
+ animation: 'pop',
+ triggerTimeSec: 0.2,
+ },
+ {
+ id: 'e-cloud-resolver',
+ type: 'cloud',
+ x: 540,
+ y: 240,
+ width: 320,
+ height: 200,
+ label: 'DNS Resolver\n1.1.1.1',
+ color: '#3b82f6',
+ strokeWidth: 3,
+ animation: 'pop',
+ triggerWord: 'resolver',
+ triggerTimeSec: 1.5,
+ },
+ {
+ id: 'e-arrow-query',
+ type: 'arrow',
+ x: 360,
+ y: 340,
+ width: 170,
+ height: 0,
+ label: 'Who is google.com?',
+ color: '#f97316',
+ strokeWidth: 2.5,
+ animation: 'draw',
+ triggerWord: 'query',
+ triggerTimeSec: 2.8,
+ },
+ ],
+ },
+ {
+ id: 'dns-s3',
+ title: 'Root & TLD Servers',
+ narration: 'The resolver asks the root server, which points to the .com TLD server, finally finding the authoritative nameserver.',
+ durationSeconds: 8,
+ transition: 'fade',
+ elements: [
+ {
+ id: 'e-resolver-s3',
+ type: 'cloud',
+ x: 160,
+ y: 260,
+ width: 240,
+ height: 160,
+ label: 'Resolver',
+ color: '#3b82f6',
+ strokeWidth: 2.5,
+ animation: 'pop',
+ triggerTimeSec: 0.2,
+ },
+ {
+ id: 'e-root-server',
+ type: 'server',
+ x: 560,
+ y: 160,
+ width: 200,
+ height: 120,
+ label: 'Root Server (.)',
+ color: '#0f172a',
+ strokeWidth: 2.5,
+ animation: 'pop',
+ triggerWord: 'root',
+ triggerTimeSec: 1.4,
+ },
+ {
+ id: 'e-tld-server',
+ type: 'server',
+ x: 880,
+ y: 360,
+ width: 240,
+ height: 130,
+ label: 'TLD Server (.com)',
+ color: '#10b981',
+ strokeWidth: 2.5,
+ animation: 'pop',
+ triggerWord: 'TLD',
+ triggerTimeSec: 3.8,
+ },
+ {
+ id: 'e-arrow-chain-1',
+ type: 'curved_arrow',
+ x: 410,
+ y: 280,
+ width: 140,
+ height: -60,
+ label: '1. Ask Root',
+ color: '#f97316',
+ strokeWidth: 2,
+ animation: 'draw',
+ triggerTimeSec: 2.0,
+ },
+ {
+ id: 'e-arrow-chain-2',
+ type: 'curved_arrow',
+ x: 770,
+ y: 240,
+ width: 100,
+ height: 120,
+ label: '2. Go to .com',
+ color: '#10b981',
+ strokeWidth: 2,
+ animation: 'draw',
+ triggerTimeSec: 4.5,
+ },
+ ],
+ },
+ {
+ id: 'dns-s4',
+ title: 'Connection Established',
+ narration: 'Armed with the exact IP address, your browser connects directly to the server, and the webpage renders seamlessly.',
+ durationSeconds: 7,
+ transition: 'fade',
+ elements: [
+ {
+ id: 'e-client-final',
+ type: 'client',
+ x: 180,
+ y: 280,
+ width: 220,
+ height: 150,
+ label: 'Client Connected',
+ color: '#0f172a',
+ strokeWidth: 3,
+ animation: 'pop',
+ triggerTimeSec: 0.2,
+ },
+ {
+ id: 'e-target-server',
+ type: 'server',
+ x: 780,
+ y: 260,
+ width: 240,
+ height: 160,
+ label: 'Web Server\n142.250.190.46',
+ color: '#10b981',
+ strokeWidth: 3,
+ animation: 'pop',
+ triggerWord: 'server',
+ triggerTimeSec: 1.5,
+ },
+ {
+ id: 'e-arrow-success',
+ type: 'arrow',
+ x: 410,
+ y: 350,
+ width: 360,
+ height: 0,
+ label: 'HTTP GET / · 200 OK',
+ color: '#10b981',
+ strokeWidth: 3.5,
+ animation: 'draw',
+ triggerWord: 'renders',
+ triggerTimeSec: 3.0,
+ },
+ {
+ id: 'e-check-dns',
+ type: 'checkmark',
+ x: 580,
+ y: 160,
+ width: 80,
+ height: 80,
+ color: '#10b981',
+ strokeWidth: 3,
+ animation: 'pop',
+ triggerTimeSec: 4.5,
+ },
+ ],
+ },
+ ],
+ },
+ {
+ id: 'api-analogy',
+ title: 'What is an API? The Restaurant Analogy',
+ description: 'Understand APIs intuitively through a restaurant: you are the customer, the waiter is the API, and the kitchen is the backend.',
+ look: 'darktech',
+ musicTrack: 'tech',
+ musicVolume: 0.25,
+ voicePitch: 1.0,
+ voiceRate: 1.0,
+ autoDuck: true,
+ scenes: [
+ {
+ id: 'api-s1',
+ title: 'The Customer at the Table',
+ narration: 'Imagine you are sitting in a restaurant looking at the menu. You know what you want to order, but you cannot walk directly into the kitchen.',
+ durationSeconds: 7,
+ transition: 'fade',
+ elements: [
+ {
+ id: 'e-customer',
+ type: 'client',
+ x: 200,
+ y: 280,
+ width: 220,
+ height: 160,
+ label: 'Client (You)',
+ color: '#38bdf8',
+ strokeWidth: 3,
+ animation: 'pop',
+ triggerWord: 'customer',
+ triggerTimeSec: 0.5,
+ },
+ {
+ id: 'e-badge-order',
+ type: 'badge',
+ x: 480,
+ y: 240,
+ width: 180,
+ height: 48,
+ label: 'Order: Pizza #42',
+ color: '#fbbf24',
+ strokeWidth: 2,
+ animation: 'pop',
+ triggerWord: 'order',
+ triggerTimeSec: 2.5,
+ },
+ ],
+ },
+ {
+ id: 'api-s2',
+ title: 'The Waiter is the API',
+ narration: 'Enter the waiter, your Application Programming Interface. The waiter takes your request, translates it, and brings it safely to the kitchen.',
+ durationSeconds: 8,
+ transition: 'fade',
+ elements: [
+ {
+ id: 'e-customer-s2',
+ type: 'client',
+ x: 150,
+ y: 280,
+ width: 200,
+ height: 140,
+ label: 'Client App',
+ color: '#38bdf8',
+ strokeWidth: 2.5,
+ animation: 'pop',
+ triggerTimeSec: 0.2,
+ },
+ {
+ id: 'e-waiter-api',
+ type: 'api_gateway',
+ x: 520,
+ y: 240,
+ width: 240,
+ height: 200,
+ label: 'API Gateway\n(The Waiter)',
+ color: '#fbbf24',
+ strokeWidth: 3,
+ animation: 'pop',
+ triggerWord: 'waiter',
+ triggerTimeSec: 1.2,
+ },
+ {
+ id: 'e-kitchen-db',
+ type: 'database',
+ x: 900,
+ y: 250,
+ width: 200,
+ height: 180,
+ label: 'Kitchen Database',
+ color: '#a855f7',
+ strokeWidth: 3,
+ animation: 'pop',
+ triggerWord: 'kitchen',
+ triggerTimeSec: 4.0,
+ },
+ {
+ id: 'e-arrow-order',
+ type: 'arrow',
+ x: 360,
+ y: 340,
+ width: 150,
+ height: 0,
+ label: 'POST /order',
+ color: '#38bdf8',
+ strokeWidth: 2.5,
+ animation: 'draw',
+ triggerWord: 'request',
+ triggerTimeSec: 2.5,
+ },
+ ],
+ },
+ {
+ id: 'api-s3',
+ title: 'Serving the Response',
+ narration: 'The kitchen cooks the meal, packages it cleanly as structured JSON data, and the API serves it right back to your screen.',
+ durationSeconds: 7,
+ transition: 'fade',
+ elements: [
+ {
+ id: 'e-customer-s3',
+ type: 'client',
+ x: 180,
+ y: 280,
+ width: 220,
+ height: 150,
+ label: 'Client (Received Data)',
+ color: '#38bdf8',
+ strokeWidth: 3,
+ animation: 'pop',
+ triggerTimeSec: 0.2,
+ },
+ {
+ id: 'e-code-response',
+ type: 'code_block',
+ x: 500,
+ y: 220,
+ width: 440,
+ height: 220,
+ label: '{\n "status": "success",\n "dish": "Margherita",\n "deliveredIn": "14ms"\n}',
+ color: '#10b981',
+ strokeWidth: 2,
+ animation: 'draw',
+ triggerWord: 'JSON',
+ triggerTimeSec: 2.0,
+ },
+ {
+ id: 'e-check-api',
+ type: 'checkmark',
+ x: 1000,
+ y: 290,
+ width: 90,
+ height: 90,
+ color: '#10b981',
+ strokeWidth: 3,
+ animation: 'pop',
+ triggerTimeSec: 3.5,
+ },
+ ],
+ },
+ ],
+ },
+ {
+ id: 'git-branching',
+ title: 'Git Branching & Merge Explained Visually',
+ description: 'Learn why branching is lightweight and how commits form an immutable directed graph.',
+ look: 'blueprint',
+ musicTrack: 'tech',
+ musicVolume: 0.25,
+ voicePitch: 1.0,
+ voiceRate: 1.0,
+ autoDuck: true,
+ scenes: [
+ {
+ id: 'git-s1',
+ title: 'The Main Branch Line',
+ narration: 'Every Git repository begins with a commit history along the main branch. Each commit points to its parent snapshot.',
+ durationSeconds: 7,
+ transition: 'fade',
+ elements: [
+ {
+ id: 'e-c1',
+ type: 'circle',
+ x: 240,
+ y: 330,
+ width: 80,
+ height: 80,
+ label: 'C1',
+ color: '#ffffff',
+ strokeWidth: 3,
+ animation: 'pop',
+ triggerTimeSec: 0.4,
+ },
+ {
+ id: 'e-arr-c1-c2',
+ type: 'arrow',
+ x: 325,
+ y: 370,
+ width: 110,
+ height: 0,
+ color: '#38bdf8',
+ strokeWidth: 2.5,
+ animation: 'draw',
+ triggerTimeSec: 1.5,
+ },
+ {
+ id: 'e-c2',
+ type: 'circle',
+ x: 440,
+ y: 330,
+ width: 80,
+ height: 80,
+ label: 'C2',
+ color: '#ffffff',
+ strokeWidth: 3,
+ animation: 'pop',
+ triggerTimeSec: 1.8,
+ },
+ {
+ id: 'e-arr-c2-c3',
+ type: 'arrow',
+ x: 525,
+ y: 370,
+ width: 110,
+ height: 0,
+ color: '#38bdf8',
+ strokeWidth: 2.5,
+ animation: 'draw',
+ triggerTimeSec: 2.8,
+ },
+ {
+ id: 'e-c3',
+ type: 'circle',
+ x: 640,
+ y: 330,
+ width: 80,
+ height: 80,
+ label: 'C3 (main)',
+ color: '#facc15',
+ strokeWidth: 3,
+ animation: 'pop',
+ triggerTimeSec: 3.2,
+ },
+ ],
+ },
+ {
+ id: 'git-s2',
+ title: 'Spawning a Feature Branch',
+ narration: 'When you type git branch feature, Git simply creates a movable pointer pointing to the current commit without duplicating files.',
+ durationSeconds: 7,
+ transition: 'fade',
+ elements: [
+ {
+ id: 'e-c2-s2',
+ type: 'circle',
+ x: 340,
+ y: 400,
+ width: 70,
+ height: 70,
+ label: 'C2',
+ color: '#ffffff',
+ strokeWidth: 2.5,
+ animation: 'pop',
+ triggerTimeSec: 0.2,
+ },
+ {
+ id: 'e-c3-s2',
+ type: 'circle',
+ x: 520,
+ y: 400,
+ width: 70,
+ height: 70,
+ label: 'C3',
+ color: '#ffffff',
+ strokeWidth: 2.5,
+ animation: 'pop',
+ triggerTimeSec: 0.4,
+ },
+ {
+ id: 'e-c4-feat',
+ type: 'circle',
+ x: 680,
+ y: 220,
+ width: 80,
+ height: 80,
+ label: 'C4 (feat)',
+ color: '#38bdf8',
+ strokeWidth: 3,
+ animation: 'pop',
+ triggerWord: 'feature',
+ triggerTimeSec: 2.0,
+ },
+ {
+ id: 'e-arr-branch',
+ type: 'curved_arrow',
+ x: 570,
+ y: 390,
+ width: 100,
+ height: -140,
+ label: 'Branch off',
+ color: '#38bdf8',
+ strokeWidth: 2.5,
+ animation: 'draw',
+ triggerTimeSec: 1.5,
+ },
+ ],
+ },
+ ],
+ },
+];
diff --git a/src/types/explainroo.ts b/src/types/explainroo.ts
new file mode 100644
index 0000000..71a6560
--- /dev/null
+++ b/src/types/explainroo.ts
@@ -0,0 +1,154 @@
+export type ThemeLook = 'whiteboard' | 'darktech' | 'blueprint' | 'chalkboard';
+
+export type AnimationType = 'draw' | 'fade' | 'pop' | 'slide' | 'typewriter';
+
+export type ElementType =
+ // Shapes & sketches
+ | 'rectangle'
+ | 'circle'
+ | 'arrow'
+ | 'curved_arrow'
+ | 'bracket'
+ | 'highlight'
+ | 'speech_bubble'
+ // Architecture & Diagrams
+ | 'client'
+ | 'server'
+ | 'database'
+ | 'cloud'
+ | 'api_gateway'
+ | 'queue'
+ // UI Mockups
+ | 'browser_window'
+ | 'terminal_window'
+ | 'phone_mockup'
+ // Text, Code, Annotations
+ | 'text'
+ | 'code_block'
+ | 'badge'
+ | 'checkmark'
+ | 'cross'
+ | 'icon';
+
+export interface VisualElement {
+ id: string;
+ type: ElementType;
+ x: number; // 0 to 1280
+ y: number; // 0 to 720
+ width: number;
+ height: number;
+ rotation?: number;
+ label?: string;
+ subtext?: string;
+ color: string;
+ strokeWidth: number;
+ roughness?: number; // 0 to 3
+ fillStyle?: 'hachure' | 'solid' | 'cross-hatch' | 'none';
+ fillColor?: string;
+ iconName?: string;
+ codeSnippet?: string;
+ url?: string;
+ animation: AnimationType;
+ triggerWord?: string; // Word in script that triggers this visual
+ triggerTimeSec?: number; // Calculated or explicit second mark
+ durationMs?: number; // Animation duration in ms
+ order?: number;
+}
+
+export interface Scene {
+ id: string;
+ title: string;
+ narration: string;
+ elements: VisualElement[];
+ durationSeconds: number;
+ transition?: 'none' | 'fade' | 'slide_left' | 'wipe';
+ lookOverride?: ThemeLook;
+ customAudioUrl?: string;
+ customAudioName?: string;
+}
+
+export interface Project {
+ id: string;
+ title: string;
+ description: string;
+ repoUrl?: string;
+ look: ThemeLook;
+ scenes: Scene[];
+ musicTrack: string;
+ musicVolume: number; // 0 to 1
+ voicePitch: number; // 0.8 to 1.3
+ voiceRate: number; // 0.85 to 1.3
+ autoDuck: boolean;
+}
+
+export interface WordTimestamp {
+ word: string;
+ cleanWord: string;
+ startTime: number;
+ endTime: number;
+ index: number;
+}
+
+export interface ThemeConfig {
+ id: ThemeLook;
+ name: string;
+ description: string;
+ background: string;
+ primaryColor: string;
+ secondaryColor: string;
+ accentColor: string;
+ textColor: string;
+ fontFamily: string;
+ paperGrid?: boolean;
+}
+
+export const THEME_CONFIGS: Record<ThemeLook, ThemeConfig> = {
+ whiteboard: {
+ id: 'whiteboard',
+ name: 'Hand-drawn Whiteboard',
+ description: 'Signature Explainroo sketchy pencil and marker strokes on warm textured board',
+ background: '#faf9f5',
+ primaryColor: '#0f172a',
+ secondaryColor: '#3b82f6',
+ accentColor: '#f97316',
+ textColor: '#1e293b',
+ fontFamily: '"Plus Jakarta Sans", sans-serif',
+ paperGrid: true,
+ },
+ darktech: {
+ id: 'darktech',
+ name: 'Modern Dark Tech',
+ description: 'Sleek neon cyan and amber glowing diagrams on deep midnight slate',
+ background: '#090d16',
+ primaryColor: '#38bdf8',
+ secondaryColor: '#a855f7',
+ accentColor: '#fbbf24',
+ textColor: '#f8fafc',
+ fontFamily: '"JetBrains Mono", monospace',
+ paperGrid: false,
+ },
+ blueprint: {
+ id: 'blueprint',
+ name: 'Architectural Blueprint',
+ description: 'Crisp white and cyan engineering schematics on deep blueprint navy',
+ background: '#0c2340',
+ primaryColor: '#ffffff',
+ secondaryColor: '#38bdf8',
+ accentColor: '#facc15',
+ textColor: '#f1f5f9',
+ fontFamily: '"JetBrains Mono", monospace',
+ paperGrid: true,
+ },
+ chalkboard: {
+ id: 'chalkboard',
+ name: 'Classroom Chalkboard',
+ description: 'Soft white, yellow, and pastel chalk marks on deep forest blackboard',
+ background: '#15251d',
+ primaryColor: '#f8fafc',
+ secondaryColor: '#fde047',
+ accentColor: '#6ee7b7',
+ textColor: '#f1f5f9',
+ fontFamily: '"Caveat", cursive, sans-serif',
+ paperGrid: false,
+ },
+};
diff --git a/src/utils/audioEngine.ts b/src/utils/audioEngine.ts
new file mode 100644
index 0000000..cdc21f3
--- /dev/null
+++ b/src/utils/audioEngine.ts
@@ -0,0 +1,432 @@
+// Audio Engine with real-time generative background music, Web Speech TTS, and auto-ducking
+
+export interface AudioPlaybackState {
+ isPlaying: boolean;
+ currentTime: number;
+ currentWordIndex: number;
+ duckingActive: boolean;
+}
+
+export type WordBoundaryListener = (word: string, charIndex: number, wordIndex: number) => void;
+
+class AudioEngine {
+ private ctx: AudioContext | null = null;
+ private musicGain: GainNode | null = null;
+ private sfxGain: GainNode | null = null;
+ private masterGain: GainNode | null = null;
+ private isMusicPlaying = false;
+ private musicInterval: number | null = null;
+ private currentTrack = 'lofi';
+ private speechUtterance: SpeechSynthesisUtterance | null = null;
+ private wordListeners: Set<WordBoundaryListener> = new Set();
+ private currentWordIndex: number = -1;
+ private currentSpokenWord: string = '';
+ private fallbackWordTimer: number | null = null;
+ private hasReceivedNativeBoundary: boolean = false;
+
+ public getCurrentTrack(): string {
+ return this.currentTrack;
+ }
+
+ public isSpeaking(): boolean {
+ return Boolean(this.speechUtterance);
+ }
+
+ public addWordListener(listener: WordBoundaryListener): () => void {
+ this.wordListeners.add(listener);
+ if (this.currentWordIndex >= 0) {
+ try {
+ listener(this.currentSpokenWord, 0, this.currentWordIndex);
+ } catch {}
+ }
+ return () => {
+ this.wordListeners.delete(listener);
+ };
+ }
+
+ public notifyWord(word: string, charIndex: number, wordIndex: number) {
+ this.currentSpokenWord = word;
+ this.currentWordIndex = wordIndex;
+ this.wordListeners.forEach((listener) => {
+ try {
+ listener(word, charIndex, wordIndex);
+ } catch (err) {
+ console.error('Error in word listener:', err);
+ }
+ });
+ }
+
+ public getCurrentWord(): { word: string; index: number } {
+ return { word: this.currentSpokenWord, index: this.currentWordIndex };
+ }
+
+ private initContext() {
+ if (!this.ctx) {
+ const AudioCtx = window.AudioContext || (window as any).webkitAudioContext;
+ this.ctx = new AudioCtx();
+
+ this.masterGain = this.ctx.createGain();
+ this.masterGain.gain.setValueAtTime(0.9, this.ctx.currentTime);
+ this.masterGain.connect(this.ctx.destination);
+
+ this.musicGain = this.ctx.createGain();
+ this.musicGain.gain.setValueAtTime(0.25, this.ctx.currentTime);
+ this.musicGain.connect(this.masterGain);
+
+ this.sfxGain = this.ctx.createGain();
+ this.sfxGain.gain.setValueAtTime(0.4, this.ctx.currentTime);
+ this.sfxGain.connect(this.masterGain);
+ }
+
+ if (this.ctx.state === 'suspended') {
+ this.ctx.resume().catch(() => {});
+ }
+ }
+
+ // Play Sound Effects
+ public playPop() {
+ try {
+ this.initContext();
+ if (!this.ctx || !this.sfxGain) return;
+ const t = this.ctx.currentTime;
+ const osc = this.ctx.createOscillator();
+ const gain = this.ctx.createGain();
+
+ osc.type = 'sine';
+ osc.frequency.setValueAtTime(320, t);
+ osc.frequency.exponentialRampToValueAtTime(740, t + 0.08);
+
+ gain.gain.setValueAtTime(0.3, t);
+ gain.gain.exponentialRampToValueAtTime(0.001, t + 0.09);
+
+ osc.connect(gain);
+ gain.connect(this.sfxGain);
+
+ osc.start(t);
+ osc.stop(t + 0.1);
+ } catch {
+ // Audio fallback
+ }
+ }
+
+ public playWhoosh() {
+ try {
+ this.initContext();
+ if (!this.ctx || !this.sfxGain) return;
+ const t = this.ctx.currentTime;
+
+ // Filtered noise swoosh
+ const bufferSize = this.ctx.sampleRate * 0.2;
+ const buffer = this.ctx.createBuffer(1, bufferSize, this.ctx.sampleRate);
+ const output = buffer.getChannelData(0);
+ for (let i = 0; i < bufferSize; i++) {
+ output[i] = (Math.random() * 2 - 1) * 0.3;
+ }
+
+ const noise = this.ctx.createBufferSource();
+ noise.buffer = buffer;
+
+ const filter = this.ctx.createBiquadFilter();
+ filter.type = 'bandpass';
+ filter.frequency.setValueAtTime(400, t);
+ filter.frequency.exponentialRampToValueAtTime(1400, t + 0.1);
+ filter.frequency.exponentialRampToValueAtTime(300, t + 0.2);
+ filter.Q.value = 3.0;
+
+ const gain = this.ctx.createGain();
+ gain.gain.setValueAtTime(0.01, t);
+ gain.gain.linearRampToValueAtTime(0.2, t + 0.08);
+ gain.gain.exponentialRampToValueAtTime(0.001, t + 0.2);
+
+ noise.connect(filter);
+ filter.connect(gain);
+ gain.connect(this.sfxGain);
+
+ noise.start(t);
+ noise.stop(t + 0.2);
+ } catch {
+ // Audio fallback
+ }
+ }
+
+ public playDrawChime() {
+ try {
+ this.initContext();
+ if (!this.ctx || !this.sfxGain) return;
+ const t = this.ctx.currentTime;
+ const notes = [523.25, 659.25, 783.99]; // C5, E5, G5
+ notes.forEach((freq, idx) => {
+ const osc = this.ctx!.createOscillator();
+ const gain = this.ctx!.createGain();
+ osc.type = 'triangle';
+ osc.frequency.setValueAtTime(freq, t + idx * 0.04);
+ gain.gain.setValueAtTime(0.12, t + idx * 0.04);
+ gain.gain.exponentialRampToValueAtTime(0.001, t + idx * 0.04 + 0.25);
+ osc.connect(gain);
+ gain.connect(this.sfxGain!);
+ osc.start(t + idx * 0.04);
+ osc.stop(t + idx * 0.04 + 0.28);
+ });
+ } catch {
+ // Audio fallback
+ }
+ }
+
+ // Audio Ducking: lowers music when narrator is speaking
+ public setDucking(active: boolean) {
+ if (!this.ctx || !this.musicGain) return;
+ const t = this.ctx.currentTime;
+ const target = active ? 0.08 : 0.25;
+ this.musicGain.gain.cancelScheduledValues(t);
+ this.musicGain.gain.linearRampToValueAtTime(target, t + 0.25);
+ }
+
+ // Generative Background Music Tracks
+ public startMusic(track: string = 'lofi') {
+ this.initContext();
+ this.stopMusic();
+ this.currentTrack = track;
+ this.isMusicPlaying = true;
+
+ // Generative chord progression based on track
+ const chordProgressions: Record<string, number[][]> = {
+ lofi: [
+ [261.63, 329.63, 392.0, 493.88], // Cmaj7
+ [220.0, 261.63, 329.63, 392.0], // Am7
+ [174.61, 220.0, 261.63, 329.63], // Fmaj7
+ [196.0, 246.94, 293.66, 349.23], // G7
+ ],
+ tech: [
+ [130.81, 196.0, 261.63, 392.0], // C power
+ [110.0, 164.81, 220.0, 329.63], // A power
+ [146.83, 220.0, 293.66, 440.0], // D power
+ [123.47, 185.0, 246.94, 370.0], // B power
+ ],
+ acoustic: [
+ [261.63, 329.63, 392.0], // C
+ [196.0, 246.94, 293.66], // G
+ [220.0, 261.63, 329.63], // Am
+ [174.61, 220.0, 261.63], // F
+ ],
+ };
+
+ const chords = chordProgressions[track] || chordProgressions.lofi;
+ let chordIdx = 0;
+
+ const playChord = () => {
+ if (!this.isMusicPlaying || !this.ctx || !this.musicGain) return;
+ const notes = chords[chordIdx % chords.length];
+ chordIdx++;
+
+ const t = this.ctx.currentTime;
+ notes.forEach((freq, i) => {
+ const osc = this.ctx!.createOscillator();
+ const gain = this.ctx!.createGain();
+ osc.type = track === 'tech' ? 'sawtooth' : 'sine';
+ osc.frequency.setValueAtTime(freq, t);
+
+ const filter = this.ctx!.createBiquadFilter();
+ filter.type = 'lowpass';
+ filter.frequency.setValueAtTime(track === 'tech' ? 1200 : 700, t);
+
+ gain.gain.setValueAtTime(0.02, t);
+ gain.gain.linearRampToValueAtTime(0.08, t + 0.6 + i * 0.05);
+ gain.gain.exponentialRampToValueAtTime(0.005, t + 3.2);
+
+ osc.connect(filter);
+ filter.connect(gain);
+ gain.connect(this.musicGain!);
+
+ osc.start(t);
+ osc.stop(t + 3.3);
+ });
+ };
+
+ playChord();
+ this.musicInterval = window.setInterval(playChord, 3200);
+ }
+
+ public stopMusic() {
+ this.isMusicPlaying = false;
+ if (this.musicInterval) {
+ clearInterval(this.musicInterval);
+ this.musicInterval = null;
+ }
+ }
+
+ // Web Speech API Voiceover with Word Boundary Synchronization
+ public speakNarration(
+ text: string,
+ onWordSpoken?: (word: string, charIndex: number, wordIndex: number) => void,
+ onEnd?: () => void,
+ rate: number = 1.0,
+ pitch: number = 1.0
+ ) {
+ if (!('speechSynthesis' in window)) {
+ if (onEnd) onEnd();
+ return;
+ }
+
+ this.stopSpeaking();
+ this.setDucking(true);
+
+ if (!text || !text.trim()) {
+ if (onEnd) onEnd();
+ return;
+ }
+
+ const trimmedText = text.trim();
+ const wordsList = trimmedText.split(/\s+/).filter(Boolean);
+
+ const utterance = new SpeechSynthesisUtterance(trimmedText);
+ utterance.rate = Math.max(0.7, Math.min(1.5, rate));
+ utterance.pitch = Math.max(0.8, Math.min(1.3, pitch));
+
+ // Try to pick a natural English voice
+ const voices = window.speechSynthesis.getVoices();
+ const naturalVoice = voices.find(
+ (v) => (v.name.includes('Natural') || v.name.includes('Google') || v.name.includes('Siri') || v.name.includes('Samantha') || v.name.includes('Daniel')) && v.lang.startsWith('en')
+ ) || voices.find((v) => v.lang.startsWith('en'));
+
+ if (naturalVoice) {
+ utterance.voice = naturalVoice;
+ }
+
+ this.hasReceivedNativeBoundary = false;
+
+ // Fallback timer: in case SpeechSynthesis onboundary is not fired by the OS/voice
+ // Estimates speech progress (~2.6 words per second scaled by rate)
+ let fallbackIdx = 0;
+ const intervalMs = Math.max(150, Math.round(1000 / (2.6 * utterance.rate)));
+ this.fallbackWordTimer = window.setInterval(() => {
+ if (this.hasReceivedNativeBoundary) {
+ if (this.fallbackWordTimer) {
+ clearInterval(this.fallbackWordTimer);
+ this.fallbackWordTimer = null;
+ }
+ return;
+ }
+ if (fallbackIdx < wordsList.length) {
+ const spokenWord = wordsList[fallbackIdx];
+ if (onWordSpoken) {
+ onWordSpoken(spokenWord, 0, fallbackIdx);
+ }
+ this.notifyWord(spokenWord, 0, fallbackIdx);
+ fallbackIdx++;
+ }
+ }, intervalMs);
+
+ utterance.onboundary = (event) => {
+ if (event.name === 'word') {
+ this.hasReceivedNativeBoundary = true;
+ if (this.fallbackWordTimer) {
+ clearInterval(this.fallbackWordTimer);
+ this.fallbackWordTimer = null;
+ }
+
+ const charIdx = event.charIndex;
+ const slice = trimmedText.slice(charIdx);
+ const match = slice.match(/^[\w'-]+/);
+ const spokenWord = match
+ ? match[0]
+ : event.charLength
+ ? trimmedText.substring(charIdx, charIdx + event.charLength)
+ : '';
+
+ // Calculate 0-based word index
+ const textBefore = trimmedText.slice(0, charIdx);
+ const wordsBefore = textBefore.trim() ? textBefore.trim().split(/\s+/).filter(Boolean) : [];
+ const wordIndex = wordsBefore.length;
+
+ if (onWordSpoken) {
+ onWordSpoken(spokenWord, charIdx, wordIndex);
+ }
+ this.notifyWord(spokenWord, charIdx, wordIndex);
+ }
+ };
+
+ utterance.onend = () => {
+ if (this.fallbackWordTimer) {
+ clearInterval(this.fallbackWordTimer);
+ this.fallbackWordTimer = null;
+ }
+ this.setDucking(false);
+ this.speechUtterance = null;
+ this.notifyWord('', -1, -1);
+ if (onEnd) onEnd();
+ };
+
+ utterance.onerror = () => {
+ if (this.fallbackWordTimer) {
+ clearInterval(this.fallbackWordTimer);
+ this.fallbackWordTimer = null;
+ }
+ this.setDucking(false);
+ this.speechUtterance = null;
+ this.notifyWord('', -1, -1);
+ if (onEnd) onEnd();
+ };
+
+ this.speechUtterance = utterance;
+ window.speechSynthesis.speak(utterance);
+ }
+
+ private customAudio: HTMLAudioElement | null = null;
+
+ public playCustomAudio(url: string, onEnd?: () => void) {
+ this.stopSpeaking();
+ this.setDucking(true);
+ if (this.customAudio) {
+ this.customAudio.pause();
+ this.customAudio = null;
+ }
+ const audio = new Audio(url);
+ audio.onended = () => {
+ this.setDucking(false);
+ this.customAudio = null;
+ this.notifyWord('', -1, -1);
+ if (onEnd) onEnd();
+ };
+ audio.onerror = () => {
+ this.setDucking(false);
+ this.customAudio = null;
+ this.notifyWord('', -1, -1);
+ if (onEnd) onEnd();
+ };
+ this.customAudio = audio;
+ audio.play().catch(() => {});
+ }
+
+ public stopCustomAudio() {
+ if (this.customAudio) {
+ this.customAudio.pause();
+ this.customAudio.currentTime = 0;
+ this.customAudio = null;
+ }
+ this.setDucking(false);
+ this.notifyWord('', -1, -1);
+ }
+
+ public stopSpeaking() {
+ if (this.fallbackWordTimer) {
+ clearInterval(this.fallbackWordTimer);
+ this.fallbackWordTimer = null;
+ }
+ if ('speechSynthesis' in window) {
+ window.speechSynthesis.cancel();
+ }
+ this.speechUtterance = null;
+ this.notifyWord('', -1, -1);
+ this.stopCustomAudio();
+ this.setDucking(false);
+ }
+
+ public stopAll() {
+ this.stopSpeaking();
+ this.stopCustomAudio();
+ this.stopMusic();
+ this.notifyWord('', -1, -1);
+ }
+}
+
+export const audioEngine = new AudioEngine();
diff --git a/src/utils/canvasRenderer.ts b/src/utils/canvasRenderer.ts
new file mode 100644
index 0000000..6af776f
--- /dev/null
+++ b/src/utils/canvasRenderer.ts
@@ -0,0 +1,670 @@
+import rough from 'roughjs';
+import { VisualElement, Scene, ThemeLook, THEME_CONFIGS } from '../types/explainroo';
+
+export interface RenderContext {
+ canvas: HTMLCanvasElement;
+ scene: Scene;
+ currentTime: number; // In seconds relative to scene start
+ theme: ThemeLook;
+ selectedElementId?: string | null;
+ interactiveMode?: boolean;
+}
+
+export function renderSceneToCanvas({
+ canvas,
+ scene,
+ currentTime,
+ theme,
+ selectedElementId,
+ interactiveMode = false,
+}: RenderContext) {
+ const ctx = canvas.getContext('2d');
+ if (!ctx) return;
+
+ const width = canvas.width;
+ const height = canvas.height;
+ const themeCfg = THEME_CONFIGS[theme] || THEME_CONFIGS.whiteboard;
+
+ // 1. Clear & Draw Background
+ ctx.save();
+ ctx.fillStyle = themeCfg.background;
+ ctx.fillRect(0, 0, width, height);
+
+ // 2. Draw Subtle Paper / Blueprint Grid if enabled
+ if (themeCfg.paperGrid) {
+ ctx.strokeStyle = theme === 'blueprint' ? 'rgba(255, 255, 255, 0.08)' : 'rgba(0, 0, 0, 0.04)';
+ ctx.lineWidth = 1;
+ const gridSize = 40;
+
+ ctx.beginPath();
+ for (let x = 0; x <= width; x += gridSize) {
+ ctx.moveTo(x, 0);
+ ctx.lineTo(x, height);
+ }
+ for (let y = 0; y <= height; y += gridSize) {
+ ctx.moveTo(0, y);
+ ctx.lineTo(width, y);
+ }
+ ctx.stroke();
+ }
+
+ // 3. Initialize Rough.js for Hand-drawn Aesthetics
+ const rc = rough.canvas(canvas);
+
+ // 4. Sort Elements by Order
+ const sortedElements = [...scene.elements].sort((a, b) => (a.order || 0) - (b.order || 0));
+
+ // 5. Render Each Element
+ sortedElements.forEach((el) => {
+ const triggerTime = el.triggerTimeSec || 0;
+ const duration = (el.durationMs || 500) / 1000;
+
+ // Calculate entrance animation progress
+ let progress = 1;
+ if (!interactiveMode) {
+ if (currentTime < triggerTime) {
+ return; // Element hasn't entered yet
+ }
+ progress = Math.min(1, Math.max(0, (currentTime - triggerTime) / duration));
+ }
+
+ ctx.save();
+
+ // Animation Transform Easing
+ if (el.animation === 'pop') {
+ const scale = progress < 0.8 ? progress * 1.3 : 1 + (1 - progress) * 0.2;
+ ctx.translate(el.x + el.width / 2, el.y + el.height / 2);
+ ctx.scale(scale, scale);
+ ctx.translate(-(el.x + el.width / 2), -(el.y + el.height / 2));
+ } else if (el.animation === 'slide') {
+ const offset = (1 - progress) * 80;
+ ctx.translate(0, offset);
+ ctx.globalAlpha = progress;
+ } else if (el.animation === 'fade') {
+ ctx.globalAlpha = progress;
+ } else if (el.animation === 'draw') {
+ ctx.globalAlpha = Math.min(1, progress * 1.5);
+ }
+
+ if (el.rotation) {
+ ctx.translate(el.x + el.width / 2, el.y + el.height / 2);
+ ctx.rotate((el.rotation * Math.PI) / 180);
+ ctx.translate(-(el.x + el.width / 2), -(el.y + el.height / 2));
+ }
+
+ // Rough.js configuration options
+ const isSketchy = theme === 'whiteboard' || theme === 'chalkboard';
+ const roughOptions: any = {
+ roughness: isSketchy ? el.roughness || 1.4 : 0.2,
+ bowing: isSketchy ? 1.5 : 0.2,
+ stroke: el.color || themeCfg.primaryColor,
+ strokeWidth: el.strokeWidth || 2.5,
+ };
+
+ if (el.fillStyle && el.fillStyle !== 'none' && el.fillColor) {
+ roughOptions.fill = el.fillColor;
+ roughOptions.fillStyle = el.fillStyle;
+ }
+
+ // Render by Element Type
+ switch (el.type) {
+ case 'rectangle':
+ rc.rectangle(el.x, el.y, el.width, el.height, roughOptions);
+ if (el.label) {
+ drawCenteredText(ctx, el.label, el.x + el.width / 2, el.y + el.height / 2, themeCfg, el.color);
+ }
+ break;
+
+ case 'circle': {
+ const radius = Math.min(el.width, el.height) / 2;
+ rc.circle(el.x + radius, el.y + radius, radius * 2, roughOptions);
+ if (el.label) {
+ drawCenteredText(ctx, el.label, el.x + radius, el.y + radius, themeCfg, el.color);
+ }
+ break;
+ }
+
+ case 'arrow':
+ case 'curved_arrow': {
+ const x1 = el.x;
+ const y1 = el.y;
+ const x2 = el.x + el.width;
+ const y2 = el.y + el.height;
+
+ if (el.type === 'curved_arrow') {
+ const cx = (x1 + x2) / 2;
+ const cy = Math.min(y1, y2) - 30;
+ rc.curve([[x1, y1], [cx, cy], [x2, y2]], roughOptions);
+ } else {
+ rc.line(x1, y1, x2, y2, roughOptions);
+ }
+
+ // Draw Arrowhead
+ const angle = Math.atan2(y2 - y1, x2 - x1);
+ const headLength = 16;
+ const arrowAngle = Math.PI / 6;
+ rc.line(
+ x2,
+ y2,
+ x2 - headLength * Math.cos(angle - arrowAngle),
+ y2 - headLength * Math.sin(angle - arrowAngle),
+ roughOptions
+ );
+ rc.line(
+ x2,
+ y2,
+ x2 - headLength * Math.cos(angle + arrowAngle),
+ y2 - headLength * Math.sin(angle + arrowAngle),
+ roughOptions
+ );
+
+ if (el.label) {
+ drawCenteredText(ctx, el.label, (x1 + x2) / 2, (y1 + y2) / 2 - 14, themeCfg, el.color, 14);
+ }
+ break;
+ }
+
+ case 'browser_window': {
+ drawBrowserMockup(rc, ctx, el, themeCfg, roughOptions);
+ break;
+ }
+
+ case 'terminal_window': {
+ drawTerminalMockup(rc, ctx, el, themeCfg, roughOptions, progress);
+ break;
+ }
+
+ case 'phone_mockup': {
+ drawPhoneMockup(rc, ctx, el, themeCfg, roughOptions);
+ break;
+ }
+
+ case 'server': {
+ drawServerDiagram(rc, ctx, el, themeCfg, roughOptions);
+ break;
+ }
+
+ case 'database': {
+ drawDatabaseDiagram(rc, ctx, el, themeCfg, roughOptions);
+ break;
+ }
+
+ case 'client': {
+ drawClientLaptop(rc, ctx, el, themeCfg, roughOptions);
+ break;
+ }
+
+ case 'cloud': {
+ drawCloudDiagram(rc, ctx, el, themeCfg, roughOptions);
+ break;
+ }
+
+ case 'api_gateway': {
+ drawApiGateway(rc, ctx, el, themeCfg, roughOptions);
+ break;
+ }
+
+ case 'code_block': {
+ drawCodeBlock(rc, ctx, el, themeCfg, roughOptions, progress);
+ break;
+ }
+
+ case 'text': {
+ ctx.font = `600 ${el.height || 28}px ${themeCfg.fontFamily}`;
+ ctx.fillStyle = el.color || themeCfg.textColor;
+ ctx.textAlign = 'left';
+ ctx.textBaseline = 'top';
+
+ const lines = (el.label || '').split('\n');
+ lines.forEach((line, lineIdx) => {
+ ctx.fillText(line, el.x, el.y + lineIdx * ((el.height || 28) * 1.3));
+ });
+
+ if (el.subtext) {
+ ctx.font = `400 16px ${themeCfg.fontFamily}`;
+ ctx.fillStyle = theme === 'darktech' ? '#94a3b8' : '#64748b';
+ ctx.fillText(el.subtext, el.x, el.y + lines.length * ((el.height || 28) * 1.3) + 4);
+ }
+ break;
+ }
+
+ case 'badge': {
+ rc.rectangle(el.x, el.y, el.width, el.height, {
+ ...roughOptions,
+ fill: el.fillColor || `${el.color}22`,
+ fillStyle: 'solid',
+ });
+ drawCenteredText(ctx, el.label || 'Step', el.x + el.width / 2, el.y + el.height / 2, themeCfg, el.color, 14);
+ break;
+ }
+
+ case 'checkmark': {
+ rc.circle(el.x + el.width / 2, el.y + el.height / 2, el.width, {
+ ...roughOptions,
+ fill: '#10b98122',
+ fillStyle: 'solid',
+ stroke: '#10b981',
+ });
+ rc.line(el.x + el.width * 0.25, el.y + el.height * 0.5, el.x + el.width * 0.45, el.y + el.height * 0.72, {
+ stroke: '#10b981',
+ strokeWidth: 3.5,
+ });
+ rc.line(el.x + el.width * 0.45, el.y + el.height * 0.72, el.x + el.width * 0.78, el.y + el.height * 0.28, {
+ stroke: '#10b981',
+ strokeWidth: 3.5,
+ });
+ break;
+ }
+
+ case 'icon': {
+ drawVectorIcon(rc, ctx, el, themeCfg, roughOptions);
+ break;
+ }
+
+ default:
+ rc.rectangle(el.x, el.y, el.width, el.height, roughOptions);
+ if (el.label) {
+ drawCenteredText(ctx, el.label, el.x + el.width / 2, el.y + el.height / 2, themeCfg, el.color);
+ }
+ }
+
+ // Selection Indicator Box (when user clicks in visual editor)
+ if (selectedElementId === el.id) {
+ ctx.strokeStyle = '#38bdf8';
+ ctx.lineWidth = 1.5;
+ ctx.setLineDash([5, 4]);
+ ctx.strokeRect(el.x - 6, el.y - 6, el.width + 12, el.height + 12);
+ ctx.setLineDash([]);
+
+ // 4 Corner Drag Handles
+ ctx.fillStyle = '#38bdf8';
+ const corners = [
+ [el.x - 9, el.y - 9],
+ [el.x + el.width + 3, el.y - 9],
+ [el.x - 9, el.y + el.height + 3],
+ [el.x + el.width + 3, el.y + el.height + 3],
+ ];
+ corners.forEach(([cx, cy]) => {
+ ctx.fillRect(cx, cy, 6, 6);
+ });
+ }
+
+ ctx.restore();
+ });
+
+ ctx.restore();
+}
+
+// Helper: Centered text drawing
+function drawCenteredText(
+ ctx: CanvasRenderingContext2D,
+ text: string,
+ cx: number,
+ cy: number,
+ themeCfg: any,
+ overrideColor?: string,
+ fontSize: number = 18
+) {
+ ctx.save();
+ ctx.font = `600 ${fontSize}px ${themeCfg.fontFamily}`;
+ ctx.fillStyle = overrideColor || themeCfg.textColor;
+ ctx.textAlign = 'center';
+ ctx.textBaseline = 'middle';
+ ctx.fillText(text, cx, cy);
+ ctx.restore();
+}
+
+// Specialized Diagram: Browser Mockup Window
+function drawBrowserMockup(
+ rc: any,
+ ctx: CanvasRenderingContext2D,
+ el: VisualElement,
+ themeCfg: any,
+ roughOptions: any
+) {
+ // Outer frame
+ rc.rectangle(el.x, el.y, el.width, el.height, {
+ ...roughOptions,
+ fill: themeCfg.background === '#090d16' ? '#0f172a' : '#ffffff',
+ fillStyle: 'solid',
+ });
+
+ // Top Title Bar
+ rc.rectangle(el.x, el.y, el.width, 36, {
+ ...roughOptions,
+ fill: themeCfg.background === '#090d16' ? '#1e293b' : '#f1f5f9',
+ fillStyle: 'solid',
+ });
+
+ // 3 Window Traffic Lights
+ const dotY = el.y + 18;
+ rc.circle(el.x + 18, dotY, 9, { stroke: '#ef4444', fill: '#ef4444', fillStyle: 'solid' });
+ rc.circle(el.x + 36, dotY, 9, { stroke: '#f59e0b', fill: '#f59e0b', fillStyle: 'solid' });
+ rc.circle(el.x + 54, dotY, 9, { stroke: '#10b981', fill: '#10b981', fillStyle: 'solid' });
+
+ // URL bar
+ const urlX = el.x + 80;
+ const urlW = el.width - 96;
+ rc.rectangle(urlX, el.y + 7, urlW, 22, {
+ stroke: '#94a3b8',
+ strokeWidth: 1,
+ fill: themeCfg.background === '#090d16' ? '#020617' : '#ffffff',
+ fillStyle: 'solid',
+ });
+
+ ctx.font = '500 11px "JetBrains Mono", monospace';
+ ctx.fillStyle = '#64748b';
+ ctx.textAlign = 'left';
+ ctx.textBaseline = 'middle';
+ ctx.fillText(el.url || 'https://api.example.com/v1/auth', urlX + 8, el.y + 18);
+
+ // Content body
+ if (el.label) {
+ drawCenteredText(ctx, el.label, el.x + el.width / 2, el.y + 36 + (el.height - 36) / 2, themeCfg, el.color, 16);
+ }
+}
+
+// Specialized Diagram: Terminal Window
+function drawTerminalMockup(
+ rc: any,
+ ctx: CanvasRenderingContext2D,
+ el: VisualElement,
+ _themeCfg: any,
+ roughOptions: any,
+ progress: number
+) {
+ rc.rectangle(el.x, el.y, el.width, el.height, {
+ ...roughOptions,
+ fill: '#0f172a',
+ fillStyle: 'solid',
+ stroke: '#334155',
+ });
+
+ // Header bar
+ rc.rectangle(el.x, el.y, el.width, 30, {
+ fill: '#1e293b',
+ fillStyle: 'solid',
+ stroke: '#334155',
+ });
+
+ // Window dots
+ const dotY = el.y + 15;
+ rc.circle(el.x + 16, dotY, 8, { stroke: '#ef4444', fill: '#ef4444', fillStyle: 'solid' });
+ rc.circle(el.x + 32, dotY, 8, { stroke: '#f59e0b', fill: '#f59e0b', fillStyle: 'solid' });
+ rc.circle(el.x + 48, dotY, 8, { stroke: '#10b981', fill: '#10b981', fillStyle: 'solid' });
+
+ // Terminal text lines
+ ctx.font = '600 13px "JetBrains Mono", monospace';
+ ctx.fillStyle = '#38bdf8';
+ ctx.textAlign = 'left';
+ ctx.textBaseline = 'top';
+
+ const command = el.label || 'git commit -m "feat: core architecture"';
+ const fullLength = command.length;
+ const visibleChars = Math.floor(fullLength * progress);
+ const typedCommand = command.slice(0, visibleChars);
+
+ ctx.fillText(`$ ${typedCommand}${progress < 1 ? '▋' : ''}`, el.x + 16, el.y + 44);
+
+ if (progress > 0.7 && el.subtext) {
+ ctx.fillStyle = '#10b981';
+ ctx.fillText(`✓ ${el.subtext}`, el.x + 16, el.y + 70);
+ }
+}
+
+// Specialized Diagram: Phone Mockup
+function drawPhoneMockup(
+ rc: any,
+ ctx: CanvasRenderingContext2D,
+ el: VisualElement,
+ themeCfg: any,
+ roughOptions: any
+) {
+ rc.rectangle(el.x, el.y, el.width, el.height, {
+ ...roughOptions,
+ fill: themeCfg.background === '#090d16' ? '#0f172a' : '#ffffff',
+ fillStyle: 'solid',
+ });
+
+ // Phone notch
+ rc.rectangle(el.x + el.width / 2 - 24, el.y + 6, 48, 8, {
+ fill: '#1e293b',
+ fillStyle: 'solid',
+ stroke: '#1e293b',
+ });
+
+ // Screen Content
+ if (el.label) {
+ drawCenteredText(ctx, el.label, el.x + el.width / 2, el.y + el.height / 2, themeCfg, el.color, 15);
+ }
+}
+
+// Specialized Diagram: Server Stack
+function drawServerDiagram(
+ rc: any,
+ ctx: CanvasRenderingContext2D,
+ el: VisualElement,
+ themeCfg: any,
+ roughOptions: any
+) {
+ const rackHeight = el.height / 3;
+ for (let i = 0; i < 3; i++) {
+ const rackY = el.y + i * rackHeight;
+ rc.rectangle(el.x, rackY, el.width, rackHeight - 4, {
+ ...roughOptions,
+ fill: themeCfg.background === '#090d16' ? '#1e293b' : '#f8fafc',
+ fillStyle: 'solid',
+ });
+
+ // Blinking LED dots
+ rc.circle(el.x + 14, rackY + rackHeight / 2 - 2, 5, {
+ stroke: '#10b981',
+ fill: '#10b981',
+ fillStyle: 'solid',
+ });
+ rc.circle(el.x + 26, rackY + rackHeight / 2 - 2, 5, {
+ stroke: '#38bdf8',
+ fill: '#38bdf8',
+ fillStyle: 'solid',
+ });
+
+ // Server drive vent lines
+ rc.line(el.x + 45, rackY + rackHeight / 2 - 2, el.x + el.width - 15, rackY + rackHeight / 2 - 2, {
+ stroke: '#94a3b8',
+ strokeWidth: 1.5,
+ });
+ }
+
+ if (el.label) {
+ drawCenteredText(ctx, el.label, el.x + el.width / 2, el.y + el.height + 16, themeCfg, el.color, 14);
+ }
+}
+
+// Specialized Diagram: Database Cylinder
+function drawDatabaseDiagram(
+ rc: any,
+ ctx: CanvasRenderingContext2D,
+ el: VisualElement,
+ themeCfg: any,
+ roughOptions: any
+) {
+ const ellipseHeight = 22;
+
+ // Cylinder body
+ rc.rectangle(el.x, el.y + ellipseHeight / 2, el.width, el.height - ellipseHeight, {
+ ...roughOptions,
+ fill: themeCfg.background === '#090d16' ? '#1e293b' : '#f8fafc',
+ fillStyle: 'solid',
+ });
+
+ // Top Ellipse
+ rc.ellipse(el.x + el.width / 2, el.y + ellipseHeight / 2, el.width, ellipseHeight, roughOptions);
+
+ // Bottom Ellipse
+ rc.ellipse(el.x + el.width / 2, el.y + el.height - ellipseHeight / 2, el.width, ellipseHeight, roughOptions);
+
+ if (el.label) {
+ drawCenteredText(ctx, el.label, el.x + el.width / 2, el.y + el.height / 2, themeCfg, el.color, 15);
+ }
+}
+
+// Specialized Diagram: Client Laptop
+function drawClientLaptop(
+ rc: any,
+ ctx: CanvasRenderingContext2D,
+ el: VisualElement,
+ themeCfg: any,
+ roughOptions: any
+) {
+ const screenH = el.height * 0.75;
+ // Screen
+ rc.rectangle(el.x + 10, el.y, el.width - 20, screenH, {
+ ...roughOptions,
+ fill: themeCfg.background === '#090d16' ? '#0f172a' : '#ffffff',
+ fillStyle: 'solid',
+ });
+
+ // Base
+ rc.rectangle(el.x, el.y + screenH, el.width, el.height - screenH, {
+ ...roughOptions,
+ fill: '#334155',
+ fillStyle: 'solid',
+ });
+
+ if (el.label) {
+ drawCenteredText(ctx, el.label, el.x + el.width / 2, el.y + screenH / 2, themeCfg, el.color, 14);
+ }
+}
+
+// Specialized Diagram: Cloud Outline
+function drawCloudDiagram(
+ rc: any,
+ ctx: CanvasRenderingContext2D,
+ el: VisualElement,
+ themeCfg: any,
+ roughOptions: any
+) {
+ const cx = el.x + el.width / 2;
+ const cy = el.y + el.height / 2;
+ const w = el.width;
+ const h = el.height;
+
+ // Composite 3 overlapping rough circles
+ rc.circle(cx - w * 0.22, cy + h * 0.05, h * 0.7, roughOptions);
+ rc.circle(cx + w * 0.22, cy + h * 0.05, h * 0.7, roughOptions);
+ rc.circle(cx, cy - h * 0.15, h * 0.85, roughOptions);
+
+ if (el.label) {
+ drawCenteredText(ctx, el.label, cx, cy, themeCfg, el.color, 15);
+ }
+}
+
+// Specialized Diagram: API Gateway Shield
+function drawApiGateway(
+ rc: any,
+ ctx: CanvasRenderingContext2D,
+ el: VisualElement,
+ themeCfg: any,
+ roughOptions: any
+) {
+ const cx = el.x + el.width / 2;
+ const cy = el.y + el.height / 2;
+ const r = Math.min(el.width, el.height) / 2;
+
+ // Hexagon
+ const points: [number, number][] = [];
+ for (let i = 0; i < 6; i++) {
+ const angle = (i * Math.PI) / 3 - Math.PI / 6;
+ points.push([cx + r * Math.cos(angle), cy + r * Math.sin(angle)]);
+ }
+
+ rc.polygon(points, {
+ ...roughOptions,
+ fill: themeCfg.background === '#090d16' ? '#1e293b' : '#f8fafc',
+ fillStyle: 'solid',
+ });
+
+ drawCenteredText(ctx, el.label || 'API Gateway', cx, cy, themeCfg, el.color, 14);
+}
+
+// Specialized Diagram: Code Block
+function drawCodeBlock(
+ rc: any,
+ ctx: CanvasRenderingContext2D,
+ el: VisualElement,
+ _themeCfg: any,
+ roughOptions: any,
+ progress: number
+) {
+ rc.rectangle(el.x, el.y, el.width, el.height, {
+ ...roughOptions,
+ fill: '#020617',
+ fillStyle: 'solid',
+ stroke: '#1e293b',
+ });
+
+ ctx.font = '500 12px "JetBrains Mono", monospace';
+ ctx.fillStyle = '#f1f5f9';
+ ctx.textAlign = 'left';
+ ctx.textBaseline = 'top';
+
+ const code = el.codeSnippet || el.label || 'const express = require("express");\napp.listen(3000);';
+ const lines = code.split('\n');
+ const visibleLineCount = Math.ceil(lines.length * progress);
+
+ lines.slice(0, visibleLineCount).forEach((line, idx) => {
+ ctx.fillStyle = '#64748b';
+ ctx.fillText(`${idx + 1}`, el.x + 8, el.y + 12 + idx * 18);
+
+ ctx.fillStyle = line.includes('const') || line.includes('function') ? '#38bdf8' : line.includes('return') ? '#a855f7' : '#e2e8f0';
+ ctx.fillText(line, el.x + 32, el.y + 12 + idx * 18);
+ });
+}
+
+// Vector Icons
+function drawVectorIcon(
+ rc: any,
+ ctx: CanvasRenderingContext2D,
+ el: VisualElement,
+ themeCfg: any,
+ roughOptions: any
+) {
+ const icon = el.iconName || 'shield';
+ const cx = el.x + el.width / 2;
+ const cy = el.y + el.height / 2;
+ const size = Math.min(el.width, el.height);
+
+ rc.circle(cx, cy, size, {
+ ...roughOptions,
+ fill: `${el.color}15`,
+ fillStyle: 'solid',
+ });
+
+ ctx.save();
+ ctx.font = `700 ${size * 0.45}px "Plus Jakarta Sans", sans-serif`;
+ ctx.fillStyle = el.color;
+ ctx.textAlign = 'center';
+ ctx.textBaseline = 'middle';
+
+ const iconGlyphs: Record<string, string> = {
+ shield: '🛡️',
+ lock: '🔒',
+ server: '🖥️',
+ database: '💾',
+ cloud: '☁️',
+ globe: '🌐',
+ key: '🔑',
+ user: '👤',
+ rocket: '🚀',
+ zap: '⚡',
+ check: '✅',
+ alert: '⚠️',
+ };
+
+ ctx.fillText(iconGlyphs[icon] || '⚡', cx, cy - 2);
+ ctx.restore();
+
+ if (el.label) {
+ drawCenteredText(ctx, el.label, cx, el.y + el.height + 16, themeCfg, el.color, 14);
+ }
+}
diff --git a/src/utils/cliExporter.ts b/src/utils/cliExporter.ts
new file mode 100644
index 0000000..9d652a2
--- /dev/null
+++ b/src/utils/cliExporter.ts
@@ -0,0 +1,640 @@
+import JSZip from 'jszip';
+import { Project } from '../types/explainroo';
+
+export function generateScriptMd(project: Project): string {
+ let md = `---
+title: "${project.title}"
+look: "${project.look}"
+music: "${project.musicTrack}"
+voiceRate: ${project.voiceRate}
+voicePitch: ${project.voicePitch}
+autoDuck: ${project.autoDuck}
+---\n\n`;
+
+ project.scenes.forEach((scene, idx) => {
+ md += `## Scene ${idx + 1}: ${scene.title}\n\n`;
+ md += `${scene.narration}\n\n`;
+ if (scene.elements.length > 0) {
+ md += `<!-- Visual Elements Anchors:\n`;
+ scene.elements.forEach((el) => {
+ md += ` - [${el.type}] "${el.label || el.type}" triggers on word: "${el.triggerWord || 'start'}"\n`;
+ });
+ md += `-->\n\n`;
+ }
+ });
+
+ return md;
+}
+
+export function generateScenesJs(project: Project): string {
+ let js = `// Generated by Explainroo UI (No-Code Visual Builder)
+// Compatible with Explainroo CLI specifications: node bin/explainroo.js render
+
+export const config = {
+ width: 1280,
+ height: 720,
+ fps: 30,
+ look: '${project.look}',
+ music: '${project.musicTrack}',
+};
+
+export const scenes = [\n`;
+
+ project.scenes.forEach((scene, sIdx) => {
+ js += ` {\n`;
+ js += ` id: '${scene.id}',\n`;
+ js += ` title: '${scene.title.replace(/'/g, "\\'")}',\n`;
+ js += ` durationSeconds: ${scene.durationSeconds},\n`;
+ js += ` elements: [\n`;
+
+ scene.elements.forEach((el) => {
+ js += ` {\n`;
+ js += ` id: '${el.id}',\n`;
+ js += ` type: '${el.type}',\n`;
+ js += ` x: ${el.x},\n`;
+ js += ` y: ${el.y},\n`;
+ js += ` width: ${el.width},\n`;
+ js += ` height: ${el.height},\n`;
+ js += ` label: '${(el.label || '').replace(/'/g, "\\'")}',\n`;
+ js += ` color: '${el.color}',\n`;
+ js += ` animation: '${el.animation}',\n`;
+ js += ` triggerWord: '${el.triggerWord || ''}',\n`;
+ js += ` triggerTimeSec: ${el.triggerTimeSec || 0},\n`;
+ js += ` },\n`;
+ });
+
+ js += ` ],\n`;
+ js += ` draw(ctx, rc, t) {\n`;
+ js += ` // Custom render callback for Explainroo CLI headless renderer\n`;
+ js += ` // Coordinates correspond to 1280x720 canvas canvas\n`;
+ js += ` }\n`;
+ js += ` }${sIdx < project.scenes.length - 1 ? ',' : ''}\n`;
+ });
+
+ js += `];\n\nexport default scenes;\n`;
+ return js;
+}
+
+export function generateConfigJson(project: Project): string {
+ return JSON.stringify(
+ {
+ name: project.title,
+ version: '1.0.0',
+ description: project.description,
+ engine: 'explainroo-v2',
+ render: {
+ width: 1280,
+ height: 720,
+ fps: 30,
+ look: project.look,
+ autoDucking: project.autoDuck,
+ backgroundMusic: project.musicTrack,
+ },
+ },
+ null,
+ 2
+ );
+}
+
+export function generateStandaloneHtml(project: Project): string {
+ const safeProjectJson = JSON.stringify(project).replace(/<\/script>/gi, '<\\/script>');
+
+ return `<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>${project.title.replace(/</g, '&lt;')} - Explainroo Player</title>
+ <script src="https://unpkg.com/[email protected]/bundled/rough.js"></script>
+ <style>
+ * { box-sizing: border-box; margin: 0; padding: 0; }
+ body {
+ background-color: #0b0f19;
+ color: #f1f5f9;
+ font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
+ min-height: 100vh;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ padding: 16px;
+ }
+ .player-wrap {
+ width: 100%;
+ max-width: 1100px;
+ background: #111827;
+ border: 1px solid #1f2937;
+ border-radius: 20px;
+ overflow: hidden;
+ box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.7);
+ display: flex;
+ flex-direction: column;
+ }
+ .header {
+ padding: 12px 20px;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ border-bottom: 1px solid #1f2937;
+ background: #0f172a;
+ }
+ .brand {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ font-weight: 800;
+ font-size: 14px;
+ color: #fff;
+ }
+ .brand span { color: #f59e0b; }
+ .badge {
+ font-size: 11px;
+ padding: 3px 8px;
+ background: rgba(245, 158, 11, 0.15);
+ border: 1px solid rgba(245, 158, 11, 0.3);
+ color: #fbbf24;
+ border-radius: 9999px;
+ font-family: monospace;
+ }
+ .stage {
+ position: relative;
+ width: 100%;
+ aspect-ratio: 16 / 9;
+ background: #090d16;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ overflow: hidden;
+ }
+ canvas {
+ width: 100%;
+ height: 100%;
+ object-fit: contain;
+ display: block;
+ }
+ .subtitles {
+ position: absolute;
+ bottom: 16px;
+ left: 16px;
+ right: 16px;
+ display: flex;
+ justify-content: center;
+ pointer-events: none;
+ z-index: 10;
+ }
+ .subtitles-pill {
+ background: rgba(15, 23, 42, 0.9);
+ backdrop-filter: blur(8px);
+ border: 1px solid rgba(51, 65, 85, 0.8);
+ padding: 8px 18px;
+ border-radius: 9999px;
+ max-width: 90%;
+ text-align: center;
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ gap: 6px;
+ font-size: 13px;
+ font-weight: 600;
+ color: #cbd5e1;
+ box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.5);
+ }
+ .subtitles-pill .active {
+ background: #fbbf24;
+ color: #020617;
+ padding: 1px 6px;
+ border-radius: 4px;
+ font-weight: 900;
+ transform: scale(1.08);
+ box-shadow: 0 0 16px rgba(251, 191, 36, 0.8);
+ transition: all 0.1s ease;
+ }
+ .subtitles-pill .past { color: #64748b; }
+ .controls {
+ background: #0f172a;
+ border-top: 1px solid #1f2937;
+ padding: 12px 20px;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ }
+ .timeline-row {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ }
+ .time-lbl {
+ font-family: monospace;
+ font-size: 11px;
+ color: #94a3b8;
+ width: 44px;
+ }
+ .time-lbl.right { text-align: right; }
+ .slider {
+ flex: 1;
+ height: 6px;
+ -webkit-appearance: none;
+ appearance: none;
+ background: #334155;
+ border-radius: 9999px;
+ outline: none;
+ cursor: pointer;
+ }
+ .slider::-webkit-slider-thumb {
+ -webkit-appearance: none;
+ appearance: none;
+ width: 14px;
+ height: 14px;
+ border-radius: 50%;
+ background: #f59e0b;
+ cursor: pointer;
+ }
+ .buttons-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ }
+ .btn-group {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ }
+ button {
+ background: #1e293b;
+ border: 1px solid #334155;
+ color: #e2e8f0;
+ padding: 6px 14px;
+ border-radius: 8px;
+ font-size: 12px;
+ font-weight: 600;
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ transition: background 0.15s;
+ }
+ button:hover { background: #334155; color: #fff; }
+ button.primary {
+ background: #f59e0b;
+ color: #020617;
+ border-color: #f59e0b;
+ font-weight: 800;
+ }
+ button.primary:hover { background: #d97706; }
+ .scene-title {
+ font-size: 12px;
+ color: #94a3b8;
+ font-weight: 500;
+ }
+ </style>
+</head>
+<body>
+ <div class="player-wrap">
+ <div class="header">
+ <div class="brand">
+ <span>🦘</span> Explainroo <span>UI</span>
+ <span class="badge">Standalone Offline Player</span>
+ </div>
+ <div class="scene-title" id="sceneIndicator">Scene 1 / 1</div>
+ </div>
+
+ <div class="stage">
+ <canvas id="playerCanvas" width="1280" height="720"></canvas>
+ <div class="subtitles" id="subtitlesWrap" style="display: none;">
+ <div class="subtitles-pill" id="subtitlesPill"></div>
+ </div>
+ </div>
+
+ <div class="controls">
+ <div class="timeline-row">
+ <span class="time-lbl" id="curTime">0.0s</span>
+ <input type="range" class="slider" id="scrubber" min="0" max="10" step="0.05" value="0">
+ <span class="time-lbl right" id="totalTime">0.0s</span>
+ </div>
+
+ <div class="buttons-row">
+ <div class="btn-group">
+ <button class="primary" id="playBtn">▶ Play</button>
+ <button id="prevBtn">⏮ Prev</button>
+ <button id="nextBtn">Next ⏭</button>
+ <button id="restartBtn">↺ Restart</button>
+ </div>
+
+ <div class="btn-group">
+ <button id="voiceBtn">🔊 Voice: ON</button>
+ <button id="fsBtn">⛶ Fullscreen</button>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <script>
+ const project = ${safeProjectJson};
+ let currentSceneIdx = 0;
+ let currentTime = 0;
+ let isPlaying = false;
+ let voiceEnabled = true;
+ let lastTimestamp = 0;
+ let liveWordIdx = -1;
+
+ const canvas = document.getElementById('playerCanvas');
+ const ctx = canvas.getContext('2d');
+ const playBtn = document.getElementById('playBtn');
+ const prevBtn = document.getElementById('prevBtn');
+ const nextBtn = document.getElementById('nextBtn');
+ const restartBtn = document.getElementById('restartBtn');
+ const voiceBtn = document.getElementById('voiceBtn');
+ const fsBtn = document.getElementById('fsBtn');
+ const scrubber = document.getElementById('scrubber');
+ const curTimeLbl = document.getElementById('curTime');
+ const totalTimeLbl = document.getElementById('totalTime');
+ const sceneIndicator = document.getElementById('sceneIndicator');
+ const subtitlesWrap = document.getElementById('subtitlesWrap');
+ const subtitlesPill = document.getElementById('subtitlesPill');
+
+ const THEMES = {
+ whiteboard: { bg: '#faf9f5', fg: '#0f172a', font: 'system-ui' },
+ darktech: { bg: '#090d16', fg: '#38bdf8', font: 'system-ui' },
+ blueprint: { bg: '#0c2340', fg: '#ffffff', font: 'monospace' },
+ chalkboard: { bg: '#15251d', fg: '#f8fafc', font: 'system-ui' }
+ };
+
+ function getActiveScene() {
+ return project.scenes[currentSceneIdx] || project.scenes[0];
+ }
+
+ function renderScene(time) {
+ const scene = getActiveScene();
+ const theme = THEMES[project.look] || THEMES.whiteboard;
+ const w = canvas.width;
+ const h = canvas.height;
+
+ ctx.save();
+ ctx.fillStyle = theme.bg;
+ ctx.fillRect(0, 0, w, h);
+
+ // Grid
+ ctx.strokeStyle = project.look === 'blueprint' ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.04)';
+ ctx.lineWidth = 1;
+ for (let x = 0; x < w; x += 40) { ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, h); ctx.stroke(); }
+ for (let y = 0; y < h; y += 40) { ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(w, y); ctx.stroke(); }
+
+ const rc = window.rough ? window.rough.canvas(canvas) : null;
+
+ // Render elements
+ const elements = [...(scene.elements || [])].sort((a,b) => (a.order||0) - (b.order||0));
+ elements.forEach(el => {
+ const trigger = el.triggerTimeSec || 0;
+ if (time < trigger) return;
+ const progress = Math.min(1, Math.max(0, (time - trigger) / 0.5));
+
+ ctx.save();
+ if (el.animation === 'pop') {
+ ctx.translate(el.x + el.width/2, el.y + el.height/2);
+ ctx.scale(progress, progress);
+ ctx.translate(-(el.x + el.width/2), -(el.y + el.height/2));
+ }
+
+ const color = el.color || theme.fg;
+ const opts = { stroke: color, strokeWidth: el.strokeWidth || 2.5, roughness: 1.2 };
+
+ if (rc) {
+ if (el.type === 'rectangle' || el.type === 'browser_window' || el.type === 'terminal_window') {
+ rc.rectangle(el.x, el.y, el.width, el.height, opts);
+ } else if (el.type === 'circle' || el.type === 'database') {
+ const rad = Math.min(el.width, el.height)/2;
+ rc.circle(el.x + rad, el.y + rad, rad * 2, opts);
+ } else if (el.type === 'arrow') {
+ rc.line(el.x, el.y, el.x + el.width, el.y + el.height, opts);
+ } else {
+ rc.rectangle(el.x, el.y, el.width, el.height, opts);
+ }
+ } else {
+ ctx.strokeStyle = color;
+ ctx.lineWidth = el.strokeWidth || 2.5;
+ ctx.strokeRect(el.x, el.y, el.width, el.height);
+ }
+
+ if (el.label) {
+ ctx.font = 'bold 16px ' + theme.font;
+ ctx.fillStyle = color;
+ ctx.textAlign = 'center';
+ ctx.textBaseline = 'middle';
+ ctx.fillText(el.label, el.x + el.width/2, el.y + el.height/2);
+ }
+
+ ctx.restore();
+ });
+
+ ctx.restore();
+ updateSubtitles(scene, time);
+ }
+
+ function updateSubtitles(scene, time) {
+ if (!scene.narration) {
+ subtitlesWrap.style.display = 'none';
+ return;
+ }
+ subtitlesWrap.style.display = 'flex';
+ const words = scene.narration.split(/\\s+/).filter(Boolean);
+ const duration = scene.durationSeconds || 7;
+ const progress = Math.min(0.999, Math.max(0, time / duration));
+ const fallbackIdx = Math.min(words.length - 1, Math.floor(progress * words.length));
+ const activeIdx = (isPlaying && liveWordIdx >= 0) ? liveWordIdx : fallbackIdx;
+
+ const windowSize = Math.min(words.length, 7);
+ const half = Math.floor(windowSize / 2);
+ let startIdx = Math.max(0, activeIdx - half);
+ let endIdx = Math.min(words.length, startIdx + windowSize);
+ if (endIdx - startIdx < windowSize) {
+ startIdx = Math.max(0, endIdx - windowSize);
+ }
+
+ let html = '';
+ for (let i = startIdx; i < endIdx; i++) {
+ const cls = i === activeIdx ? 'active' : (i < activeIdx ? 'past' : '');
+ html += '<span class="' + cls + '">' + words[i] + '</span> ';
+ }
+ subtitlesPill.innerHTML = html;
+ }
+
+ function speakNarration(text) {
+ if (!voiceEnabled || !window.speechSynthesis || !text) return;
+ window.speechSynthesis.cancel();
+ const u = new SpeechSynthesisUtterance(text);
+ u.rate = project.voiceRate || 1.0;
+ u.pitch = project.voicePitch || 1.0;
+ u.onboundary = (e) => {
+ if (e.name === 'word') {
+ const before = text.slice(0, e.charIndex).trim();
+ liveWordIdx = before ? before.split(/\\s+/).filter(Boolean).length : 0;
+ }
+ };
+ u.onend = () => { liveWordIdx = -1; };
+ u.onerror = () => { liveWordIdx = -1; };
+ window.speechSynthesis.speak(u);
+ }
+
+ function stopSpeaking() {
+ if (window.speechSynthesis) window.speechSynthesis.cancel();
+ liveWordIdx = -1;
+ }
+
+ function setScene(idx) {
+ currentSceneIdx = Math.max(0, Math.min(project.scenes.length - 1, idx));
+ currentTime = 0;
+ stopSpeaking();
+ const scene = getActiveScene();
+ scrubber.max = scene.durationSeconds || 7;
+ totalTimeLbl.textContent = (scene.durationSeconds || 7).toFixed(1) + 's';
+ sceneIndicator.textContent = 'Scene ' + (currentSceneIdx + 1) + ' / ' + project.scenes.length + ' · ' + scene.title;
+ renderScene(0);
+ if (isPlaying) {
+ speakNarration(scene.narration);
+ }
+ }
+
+ function loop(timestamp) {
+ if (!isPlaying) return;
+ if (!lastTimestamp) lastTimestamp = timestamp;
+ const delta = (timestamp - lastTimestamp) / 1000;
+ lastTimestamp = timestamp;
+
+ currentTime += delta;
+ const scene = getActiveScene();
+ const duration = scene.durationSeconds || 7;
+
+ if (currentTime >= duration) {
+ if (currentSceneIdx < project.scenes.length - 1) {
+ setScene(currentSceneIdx + 1);
+ } else {
+ currentTime = duration;
+ isPlaying = false;
+ playBtn.textContent = '▶ Play';
+ stopSpeaking();
+ }
+ }
+
+ curTimeLbl.textContent = currentTime.toFixed(1) + 's';
+ scrubber.value = currentTime;
+ renderScene(currentTime);
+ requestAnimationFrame(loop);
+ }
+
+ playBtn.addEventListener('click', () => {
+ isPlaying = !isPlaying;
+ if (isPlaying) {
+ playBtn.textContent = '⏸ Pause';
+ lastTimestamp = performance.now();
+ const scene = getActiveScene();
+ if (currentTime >= (scene.durationSeconds || 7)) currentTime = 0;
+ speakNarration(scene.narration);
+ requestAnimationFrame(loop);
+ } else {
+ playBtn.textContent = '▶ Play';
+ stopSpeaking();
+ }
+ });
+
+ prevBtn.addEventListener('click', () => setScene(currentSceneIdx - 1));
+ nextBtn.addEventListener('click', () => setScene(currentSceneIdx + 1));
+ restartBtn.addEventListener('click', () => {
+ currentTime = 0;
+ stopSpeaking();
+ if (isPlaying) speakNarration(getActiveScene().narration);
+ renderScene(0);
+ });
+
+ voiceBtn.addEventListener('click', () => {
+ voiceEnabled = !voiceEnabled;
+ voiceBtn.textContent = voiceEnabled ? '🔊 Voice: ON' : '🔇 Voice: OFF';
+ if (!voiceEnabled) stopSpeaking();
+ else if (isPlaying) speakNarration(getActiveScene().narration);
+ });
+
+ fsBtn.addEventListener('click', () => {
+ if (!document.fullscreenElement) document.documentElement.requestFullscreen();
+ else document.exitFullscreen();
+ });
+
+ scrubber.addEventListener('input', (e) => {
+ currentTime = parseFloat(e.target.value);
+ curTimeLbl.textContent = currentTime.toFixed(1) + 's';
+ renderScene(currentTime);
+ });
+
+ // Initial load
+ setScene(0);
+ </script>
+</body>
+</html>`;
+}
+
+export async function downloadProjectZip(project: Project) {
+ const zip = new JSZip();
+
+ zip.file('script.md', generateScriptMd(project));
+ zip.file('scenes.js', generateScenesJs(project));
+ zip.file('explainroo.config.json', generateConfigJson(project));
+ zip.file('standalone-player.html', generateStandaloneHtml(project));
+ zip.file('project.explainroo.json', JSON.stringify(project, null, 2));
+ zip.file(
+ 'README.md',
+ `# ${project.title}
+
+Generated with **Explainroo UI** — Visual Explainer Video Studio.
+
+## Included Files:
+1. **standalone-player.html** - Complete zero-install offline interactive video player! Double-click to open in any web browser.
+2. **project.explainroo.json** - Complete project backup to reload back into Explainroo UI.
+3. **script.md** - Narration voiceover script with word anchor markers.
+4. **scenes.js** - Diagram layout and animation coordinate triggers.
+5. **explainroo.config.json** - CLI configuration file.
+
+## Quick CLI Render
+If you have the Explainroo CLI installed:
+\`\`\`bash
+npm install -g explainroo
+explainroo render
+\`\`\`
+`
+ );
+
+ const blob = await zip.generateAsync({ type: 'blob' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `${project.title.toLowerCase().replace(/[^a-z0-9]/g, '-')}-explainroo.zip`;
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ URL.revokeObjectURL(url);
+}
+
+export function downloadStandaloneHtml(project: Project) {
+ const htmlContent = generateStandaloneHtml(project);
+ downloadTextFile(
+ `${project.title.toLowerCase().replace(/[^a-z0-9]/g, '-')}-player.html`,
+ htmlContent
+ );
+}
+
+export function downloadProjectJson(project: Project) {
+ const jsonContent = JSON.stringify(project, null, 2);
+ downloadTextFile(
+ `${project.title.toLowerCase().replace(/[^a-z0-9]/g, '-')}.explainroo.json`,
+ jsonContent
+ );
+}
+
+export function downloadTextFile(filename: string, content: string) {
+ const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = filename;
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ URL.revokeObjectURL(url);
+}
diff --git a/src/utils/videoRecorder.ts b/src/utils/videoRecorder.ts
new file mode 100644
index 0000000..2da6948
--- /dev/null
+++ b/src/utils/videoRecorder.ts
@@ -0,0 +1,62 @@
+// In-browser Video Recorder using Canvas captureStream and MediaRecorder
+
+export class VideoRecorder {
+ private mediaRecorder: MediaRecorder | null = null;
+ private recordedChunks: Blob[] = [];
+ private isRecording = false;
+
+ public start(canvas: HTMLCanvasElement): boolean {
+ try {
+ this.recordedChunks = [];
+ const stream = canvas.captureStream(30); // 30 fps stream
+
+ const options: MediaRecorderOptions = {};
+ if (MediaRecorder.isTypeSupported('video/webm;codecs=vp9,opus')) {
+ options.mimeType = 'video/webm;codecs=vp9,opus';
+ } else if (MediaRecorder.isTypeSupported('video/webm')) {
+ options.mimeType = 'video/webm';
+ } else if (MediaRecorder.isTypeSupported('video/mp4')) {
+ options.mimeType = 'video/mp4';
+ }
+
+ this.mediaRecorder = new MediaRecorder(stream, options);
+
+ this.mediaRecorder.ondataavailable = (event) => {
+ if (event.data && event.data.size > 0) {
+ this.recordedChunks.push(event.data);
+ }
+ };
+
+ this.mediaRecorder.start(250); // Record in 250ms chunks
+ this.isRecording = true;
+ return true;
+ } catch (err) {
+ console.error('Failed to start MediaRecorder:', err);
+ return false;
+ }
+ }
+
+ public stop(): Promise<Blob | null> {
+ return new Promise((resolve) => {
+ if (!this.mediaRecorder || !this.isRecording) {
+ resolve(null);
+ return;
+ }
+
+ this.mediaRecorder.onstop = () => {
+ const mimeType = this.mediaRecorder?.mimeType || 'video/webm';
+ const blob = new Blob(this.recordedChunks, { type: mimeType });
+ this.isRecording = false;
+ resolve(blob);
+ };
+
+ this.mediaRecorder.stop();
+ });
+ }
+
+ public getIsRecording(): boolean {
+ return this.isRecording;
+ }
+}
+
+export const videoRecorder = new VideoRecorder();