/** * Automated Tutorial Video Creator * * This script automates browser interactions to create a tutorial video * showing how to use CodePractice AI website. * * Usage: node scripts/create-tutorial-video.js */ const { chromium } = require('playwright'); const path = require('path'); const fs = require('fs'); // Configuration const CONFIG = { // Website URL (local or production) websiteUrl: process.env.WEBSITE_URL || 'http://localhost:3000', // Video output settings outputDir: path.join(__dirname, '../tutorial-videos'), videoFileName: `tutorial-${new Date().toISOString().split('T')[0]}.mp4`, // Timing settings (in milliseconds) - 3x faster delays: { short: 15, // Quick pause medium: 30, // Normal pause long: 60, // Longer pause typing: 3, // Delay between keystrokes (very fast) scroll: 0, // No scroll animation }, // Code to type in the editor sampleCode: `def twoSum(nums, target): num_map = {} for i, num in enumerate(nums): complement = target - num if complement in num_map: return [num_map[complement], i] num_map[num] = i return [] `, }; // Helper function to move hand cursor to target with smooth animation // Cursor continues from last position to new position async function moveHandToTarget(page, toX, toY) { // Get current cursor position const currentPos = await page.evaluate(() => { if (window.getPlaywrightCursorPos) { return window.getPlaywrightCursorPos(); } return { x: window.innerWidth / 2, y: window.innerHeight / 2 }; }); const fromX = currentPos.x; const fromY = currentPos.y; // Calculate distance and steps for smooth animation (3x faster) const distance = Math.sqrt(Math.pow(toX - fromX, 2) + Math.pow(toY - fromY, 2)); const steps = Math.max(3, Math.min(15, Math.floor(distance / 30))); // Much fewer steps for very fast movement const stepDelay = 3; // 3ms per step for very fast animation // Animate cursor movement for (let i = 0; i <= steps; i++) { const progress = i / steps; // Use easing function for smooth movement (ease-in-out) const eased = progress < 0.5 ? 2 * progress * progress : 1 - Math.pow(-2 * progress + 2, 2) / 2; const currentX = fromX + (toX - fromX) * eased; const currentY = fromY + (toY - fromY) * eased; // Move mouse await page.mouse.move(currentX, currentY); // Update visual cursor indicator await page.evaluate(({ x, y }) => { if (window.movePlaywrightCursor) { window.movePlaywrightCursor(x, y); } }, { x: currentX, y: currentY }); // Small delay for smooth animation await page.waitForTimeout(stepDelay); } // Small pause at target await page.waitForTimeout(15); } // No scrolling - keep page fixed async function createTutorialVideo() { console.log('šŸŽ¬ Starting tutorial video creation...'); // Ensure output directory exists if (!fs.existsSync(CONFIG.outputDir)) { fs.mkdirSync(CONFIG.outputDir, { recursive: true }); } const outputPath = path.join(CONFIG.outputDir, CONFIG.videoFileName); console.log(`šŸ“¹ Output: ${outputPath}`); const browser = await chromium.launch({ headless: false, args: ['--start-maximized'], }); const context = await browser.newContext({ viewport: null, recordVideo: { dir: CONFIG.outputDir, size: { width: 1920, height: 1080 }, }, }); const page = await context.newPage(); // Inject cursor indicator async function injectCursorIndicator() { await page.evaluate(() => { if (document.getElementById('playwright-cursor-indicator')) return; const cursorIndicator = document.createElement('div'); cursorIndicator.id = 'playwright-cursor-indicator'; cursorIndicator.innerHTML = 'šŸ‘†'; cursorIndicator.style.cssText = ` position: fixed; z-index: 999999; pointer-events: none; font-size: 24px; transform: translate(-50%, -50%); transition: none; `; document.body.appendChild(cursorIndicator); let mouseX = window.innerWidth / 2; let mouseY = window.innerHeight / 2; window.movePlaywrightCursor = function(x, y) { mouseX = x; mouseY = y; cursorIndicator.style.left = mouseX + 'px'; cursorIndicator.style.top = mouseY + 'px'; }; window.getPlaywrightCursorPos = function() { return { x: mouseX, y: mouseY }; }; document.addEventListener('mousedown', () => { cursorIndicator.innerHTML = 'šŸ‘‡'; }); document.addEventListener('mouseup', () => { cursorIndicator.innerHTML = 'šŸ‘†'; }); }); } try { console.log('🌐 Navigating to website...'); await page.goto(CONFIG.websiteUrl, { waitUntil: 'networkidle' }); await page.waitForTimeout(CONFIG.delays.long); // Wait for Next.js to fully hydrate console.log('ā³ Waiting for page to fully load...'); try { await page.waitForFunction(() => { const body = document.body; if (!body) return false; const hasButtons = body.querySelectorAll('button').length > 0; const hasContent = body.textContent && body.textContent.length > 100; const isNotLoading = !body.textContent?.includes('self.__next_f') || (body.textContent.length > 500 && !body.textContent.startsWith('(self.__next_f')); return hasButtons && hasContent && isNotLoading; }, { timeout: 15000 }); console.log('āœ… Page fully loaded'); } catch (e) { console.log('āš ļø Page load timeout, continuing...'); await page.waitForTimeout(2000); } await page.waitForTimeout(200); await injectCursorIndicator(); console.log('āœ… Cursor indicator injected'); // ============================================ // TASK 1: Close sign up modal // Mouse starts from center, moves to close button // ============================================ console.log('šŸ“‹ Task 1: Closing sign up modal...'); // Wait for modal to appear and check if it exists await page.waitForTimeout(2000); // Clear localStorage to ensure modal shows (if needed) await page.evaluate(() => { localStorage.removeItem('betaSignupDismissed'); }); // Wait a bit more for modal to appear after clearing localStorage await page.waitForTimeout(500); // Check if modal is visible const modalVisible = await page.evaluate(() => { // Check for backdrop with z-50 const backdrop = document.querySelector('.fixed.inset-0.z-50, .fixed.inset-0[class*="z-"]'); // Check for modal content const modalContent = document.querySelector('[class*="rounded-2xl"][class*="shadow-2xl"]'); // Check for Maybe Later button const maybeLaterBtn = Array.from(document.querySelectorAll('button')).find(btn => btn.textContent?.includes('Maybe Later') ); return !!(backdrop || modalContent || maybeLaterBtn); }); if (!modalVisible) { console.log('ā„¹ļø No signup modal found, continuing...'); } else { console.log('āœ… Signup modal detected'); } let signupClosed = false; // Method 1: Try "Maybe Later" button (most reliable for BetaSignupModal) try { const maybeLaterBtn = page.locator('button:has-text("Maybe Later")').first(); const isVisible = await maybeLaterBtn.isVisible({ timeout: 3000 }).catch(() => false); if (isVisible) { const btnBox = await maybeLaterBtn.boundingBox(); if (btnBox) { await moveHandToTarget(page, btnBox.x + btnBox.width / 2, btnBox.y + btnBox.height / 2); await maybeLaterBtn.click({ timeout: 2000 }); await page.waitForTimeout(200); signupClosed = true; console.log('āœ… Sign up modal closed (via Maybe Later button)'); } } } catch (e) { // Continue to next method } // Method 2: Try close button with aria-label="Close" (X icon) if (!signupClosed) { try { const closeBtn = page.locator('button[aria-label="Close"]').first(); if (await closeBtn.isVisible({ timeout: 1000 }).catch(() => false)) { const btnBox = await closeBtn.boundingBox(); if (btnBox) { await moveHandToTarget(page, btnBox.x + btnBox.width / 2, btnBox.y + btnBox.height / 2); await closeBtn.click({ timeout: 2000 }); await page.waitForTimeout(200); signupClosed = true; console.log('āœ… Sign up modal closed (via Close button)'); } } } catch (e) { // Continue } } // Method 3: Try clicking backdrop (closes modal) if (!signupClosed) { try { const backdrop = page.locator('.fixed.inset-0.bg-black\\/50').first(); if (await backdrop.isVisible({ timeout: 1000 }).catch(() => false)) { const backdropBox = await backdrop.boundingBox(); if (backdropBox) { // Click on backdrop (not center, slightly offset) await moveHandToTarget(page, backdropBox.x + 100, backdropBox.y + 100); await page.mouse.click(backdropBox.x + 100, backdropBox.y + 100); await page.waitForTimeout(200); signupClosed = true; console.log('āœ… Sign up modal closed (via backdrop click)'); } } } catch (e) { // Continue } } // Method 4: Use page.evaluate to find and click close button if (!signupClosed) { const modalClosed = await page.evaluate(() => { // Find button with aria-label="Close" const closeBtn = document.querySelector('button[aria-label="Close"]'); if (closeBtn) { closeBtn.click(); return true; } // Find "Maybe Later" button const buttons = Array.from(document.querySelectorAll('button')); const maybeLater = buttons.find(btn => btn.textContent?.includes('Maybe Later')); if (maybeLater) { maybeLater.click(); return true; } // Click backdrop const backdrop = document.querySelector('.fixed.inset-0.bg-black\\/50, [class*="backdrop"]'); if (backdrop) { backdrop.click(); return true; } return false; }); if (modalClosed) { await page.waitForTimeout(200); signupClosed = true; console.log('āœ… Sign up modal closed (via evaluate)'); } } // Method 5: Try Escape key if (!signupClosed) { await page.keyboard.press('Escape'); await page.waitForTimeout(200); console.log('āš ļø Used Escape key to close modal'); } // Verify modal is closed await page.waitForTimeout(200); // ============================================ // TASK 2: Skip the tour // Mouse continues from previous position (close button or center) // ============================================ console.log('šŸ“‹ Task 2: Skipping tour...'); const skipTourSelectors = [ 'button:has-text("Skip")', 'button:has-text("Skip Tour")', 'button[class*="skip"]', ]; let tourSkipped = false; for (const selector of skipTourSelectors) { try { const skipBtn = page.locator(selector).first(); const isVisible = await skipBtn.isVisible({ timeout: 2000 }).catch(() => false); if (isVisible) { const btnBox = await skipBtn.boundingBox(); if (btnBox) { await moveHandToTarget(page, btnBox.x + btnBox.width / 2, btnBox.y + btnBox.height / 2); await skipBtn.click({ timeout: 2000 }); await page.waitForTimeout(60); for (let i = 0; i < 3; i++) { const overlayGone = await page.evaluate(() => { const tourOverlay = document.querySelector('.fixed.inset-0.z-\\[9999\\]'); return !tourOverlay || tourOverlay.style.display === 'none' || !tourOverlay.offsetParent; }); if (overlayGone) break; await page.waitForTimeout(30); } tourSkipped = true; console.log('āœ… Tour skipped'); break; } } } catch (e) { // Continue } } if (!tourSkipped) { await page.keyboard.press('Escape'); await page.waitForTimeout(30); } // ============================================ // TASK 3: Click on recommend question button // Mouse continues from previous position (Skip button) // ============================================ console.log('šŸ“‹ Task 3: Clicking Start Recommended Problem...'); const startButton = page.locator('#tour-start-recommended-button, button:has-text("Start Recommended Problem"), button:has-text("Start Recommended")').first(); if (await startButton.isVisible({ timeout: 5000 }).catch(() => false)) { const startBox = await startButton.boundingBox(); if (startBox) { await moveHandToTarget(page, startBox.x + startBox.width / 2, startBox.y + startBox.height / 2); const navigationPromise = Promise.race([ page.waitForNavigation({ waitUntil: 'networkidle', timeout: 15000 }).catch(() => null), page.waitForLoadState('networkidle', { timeout: 15000 }).catch(() => null), page.waitForURL(url => url.pathname === '/practice', { timeout: 15000 }).catch(() => null), ]); try { await startButton.click({ timeout: 2000 }); } catch (e) { await page.evaluate((buttonId) => { const btn = document.getElementById(buttonId) || Array.from(document.querySelectorAll('button')).find(b => b.textContent?.includes('Start Recommended Problem') || b.textContent?.includes('Start Recommended') ); if (btn) btn.click(); }, 'tour-start-recommended-button'); await page.waitForTimeout(500); } console.log('ā³ Waiting for navigation...'); await navigationPromise; await page.waitForTimeout(200); console.log('āœ… Navigated to practice page'); } } // ============================================ // TASK 4: On practice page, skip the tour // Mouse continues from previous position (Recommended button) // ============================================ console.log('šŸ“‹ Task 4: Skipping tour on practice page...'); // Wait for practice page to fully load and tour to appear await page.waitForTimeout(1500); // Clear practice tour completion to ensure it shows await page.evaluate(() => { localStorage.removeItem('practiceTourCompleted'); }); await page.waitForTimeout(500); // Check if tour overlay is present let tourPresent = await page.evaluate(() => { const tourOverlay = document.querySelector('.fixed.inset-0.z-\\[9999\\], [class*="z-50"], [class*="tour"]'); return !!tourOverlay; }); // If not found, wait a bit more and check again if (!tourPresent) { await page.waitForTimeout(1000); tourPresent = await page.evaluate(() => { const tourOverlay = document.querySelector('.fixed.inset-0.z-\\[9999\\], [class*="z-50"], [class*="tour"]'); return !!tourOverlay; }); } if (!tourPresent) { console.log('ā„¹ļø No tour found on practice page, continuing...'); } else { console.log('āœ… Tour detected on practice page'); } let practiceTourSkipped = false; // Method 1: Try to find Skip button using page.evaluate (most reliable) // Wait a bit for tour to fully render await page.waitForTimeout(500); const skipFound = await page.evaluate(() => { // First, find the tour overlay/modal const tourOverlay = document.querySelector('.fixed.inset-0.z-\\[9999\\], [class*="z-50"], [class*="tour"]'); if (!tourOverlay) return false; // Find Skip button - look for exact text match first const buttons = Array.from(tourOverlay.querySelectorAll('button, [role="button"]')); let skipBtn = buttons.find(btn => { const text = (btn.textContent || '').toLowerCase().trim(); return text === 'skip'; }); // If not found, try partial match if (!skipBtn) { skipBtn = buttons.find(btn => { const text = (btn.textContent || '').toLowerCase().trim(); return text.includes('skip'); }); } if (skipBtn) { const rect = skipBtn.getBoundingClientRect(); if (rect.width > 0 && rect.height > 0) { // Scroll into view if needed skipBtn.scrollIntoView({ behavior: 'instant', block: 'center' }); skipBtn.click(); return true; } } return false; }); if (skipFound) { await page.waitForTimeout(500); // Verify tour is gone - check multiple times let tourGone = false; for (let i = 0; i < 5; i++) { tourGone = await page.evaluate(() => { const tourOverlay = document.querySelector('.fixed.inset-0.z-\\[9999\\], [class*="z-50"], [class*="tour"]'); return !tourOverlay || tourOverlay.style.display === 'none' || !tourOverlay.offsetParent; }); if (tourGone) break; await page.waitForTimeout(200); } if (tourGone) { practiceTourSkipped = true; console.log('āœ… Practice page tour skipped (via evaluate)'); } else { console.log('āš ļø Tour still present after skip, trying again...'); } } // Method 2: Try using locators with mouse movement (target Skip button specifically) if (!practiceTourSkipped) { // Wait for Skip button to be visible await page.waitForTimeout(500); const skipPracticeTourSelectors = [ 'button:has-text("Skip")', // Exact match first '[class*="tour"] button:has-text("Skip")', '.fixed.inset-0 button:has-text("Skip")', 'button[class*="skip"]', ]; for (const selector of skipPracticeTourSelectors) { try { const skipBtn = page.locator(selector).first(); if (await skipBtn.isVisible({ timeout: 3000 }).catch(() => false)) { const btnBox = await skipBtn.boundingBox(); if (btnBox) { // Move mouse to Skip button and click await moveHandToTarget(page, btnBox.x + btnBox.width / 2, btnBox.y + btnBox.height / 2); await skipBtn.click({ timeout: 2000 }); await page.waitForTimeout(500); // Verify tour is gone const tourGone = await page.evaluate(() => { const tourOverlay = document.querySelector('.fixed.inset-0.z-\\[9999\\], [class*="z-50"], [class*="tour"]'); return !tourOverlay || tourOverlay.style.display === 'none' || !tourOverlay.offsetParent; }); if (tourGone) { practiceTourSkipped = true; console.log(`āœ… Practice page tour skipped (via selector: ${selector})`); break; } else { console.log(`āš ļø Tour still present after clicking Skip with ${selector}`); } } } } catch (e) { // Continue } } } // Method 3: Try Escape key multiple times if (!practiceTourSkipped) { for (let i = 0; i < 3; i++) { await page.keyboard.press('Escape'); await page.waitForTimeout(200); // Check if tour is gone const tourGone = await page.evaluate(() => { const tourOverlay = document.querySelector('.fixed.inset-0.z-\\[9999\\], [class*="z-50"], [class*="tour"]'); return !tourOverlay || tourOverlay.style.display === 'none' || !tourOverlay.offsetParent; }); if (tourGone) { practiceTourSkipped = true; console.log(`āœ… Practice page tour skipped (via Escape key, attempt ${i + 1})`); break; } } if (!practiceTourSkipped) { console.log('āš ļø Tour may still be visible, but continuing...'); } } // Final verification and wait to ensure tour is dismissed let finalTourGone = false; for (let i = 0; i < 10; i++) { finalTourGone = await page.evaluate(() => { const tourOverlay = document.querySelector('.fixed.inset-0.z-\\[9999\\], [class*="z-50"], [class*="tour"]'); return !tourOverlay || tourOverlay.style.display === 'none' || !tourOverlay.offsetParent; }); if (finalTourGone) { console.log(`āœ… Tour confirmed dismissed (check ${i + 1})`); break; } await page.waitForTimeout(200); } if (!finalTourGone) { // Force remove tour overlay if still present await page.evaluate(() => { const tourOverlay = document.querySelector('.fixed.inset-0.z-\\[9999\\], [class*="z-50"], [class*="tour"]'); if (tourOverlay && tourOverlay.parentNode) { tourOverlay.remove(); } // Also mark tour as completed in localStorage localStorage.setItem('practiceTourCompleted', 'true'); }); console.log('āš ļø Force removed tour overlay'); } await page.waitForTimeout(300); // ============================================ // TASK 5: Write sample code in the editor // Mouse continues from previous position (Skip button) // ============================================ console.log('šŸ“‹ Task 5: Writing code in editor...'); // Wait for editor to be ready await page.waitForTimeout(500); const editorSelector = '#tour-code-editor, .monaco-editor, .cm-editor'; const editor = page.locator(editorSelector).first(); let editorBox = null; if (await editor.isVisible({ timeout: 3000 }).catch(() => false)) { editorBox = await editor.boundingBox().catch(() => null); if (editorBox) { // Move mouse to editor and click to focus await moveHandToTarget(page, editorBox.x + editorBox.width / 2, editorBox.y + editorBox.height / 2); await page.mouse.click(editorBox.x + editorBox.width / 2, editorBox.y + editorBox.height / 2); await page.waitForTimeout(200); } } // Set code directly by manipulating the hidden textarea and triggering events console.log('āŒØļø Setting code in editor...'); const codeSet = await page.evaluate((sampleCode) => { // Try Monaco editor - find the hidden textarea const monacoTextarea = document.querySelector('.monaco-editor textarea, .monaco-editor .inputarea'); if (monacoTextarea) { const textarea = monacoTextarea; // Set value directly textarea.value = sampleCode; // Trigger multiple events to ensure Monaco and React both see the change textarea.dispatchEvent(new Event('input', { bubbles: true, cancelable: true })); textarea.dispatchEvent(new Event('change', { bubbles: true, cancelable: true })); textarea.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, cancelable: true, key: 'a' })); textarea.dispatchEvent(new KeyboardEvent('keyup', { bubbles: true, cancelable: true, key: 'a' })); // Also trigger on the Monaco container const monacoContainer = document.querySelector('.monaco-editor'); if (monacoContainer) { monacoContainer.dispatchEvent(new Event('input', { bubbles: true })); } return { success: true, type: 'monaco-textarea', length: sampleCode.length }; } // Try CodeMirror const cmEditor = document.querySelector('.cm-editor'); if (cmEditor) { const cmContent = cmEditor.querySelector('.cm-content'); if (cmContent) { // Set text content cmContent.textContent = sampleCode; // Trigger events cmContent.dispatchEvent(new Event('input', { bubbles: true })); cmContent.dispatchEvent(new Event('change', { bubbles: true })); return { success: true, type: 'codemirror-dom', length: sampleCode.length }; } } return { success: false, type: 'none', length: 0 }; }, CONFIG.sampleCode); if (codeSet.success) { console.log(`āœ… Code set in editor (${codeSet.type}, ${codeSet.length} chars)`); await page.waitForTimeout(300); } else { console.log('āš ļø Direct API failed, trying keyboard typing...'); // Fallback: Use keyboard typing await page.evaluate(() => { const monacoTextarea = document.querySelector('.monaco-editor textarea, .monaco-editor .inputarea'); if (monacoTextarea) { monacoTextarea.focus(); monacoTextarea.click(); } else { const cmEditor = document.querySelector('.cm-editor, .cm-content'); if (cmEditor) { cmEditor.focus(); cmEditor.click(); } } }); await page.waitForTimeout(200); await page.keyboard.press('Control+A'); await page.waitForTimeout(100); await page.keyboard.press('Delete'); await page.waitForTimeout(100); // Type code character by character for (const char of CONFIG.sampleCode) { await page.keyboard.type(char, { delay: CONFIG.delays.typing }); } await page.waitForTimeout(200); } // Verify code was actually written const codeTyped = await page.evaluate(() => { // Check Monaco view-lines (rendered content) - most reliable const monacoLines = document.querySelector('.monaco-editor .view-lines'); if (monacoLines) { const text = monacoLines.textContent || ''; return { typed: text.length > 10, length: text.length, preview: text.substring(0, 50), type: 'monaco-lines' }; } // Check Monaco textarea const monacoTextarea = document.querySelector('.monaco-editor textarea, .monaco-editor .inputarea'); if (monacoTextarea) { const value = monacoTextarea.value || ''; return { typed: value.length > 10, length: value.length, preview: value.substring(0, 50), type: 'monaco-textarea' }; } // Check CodeMirror const cmEditor = document.querySelector('.cm-editor, .cm-content'); if (cmEditor) { const text = cmEditor.textContent || ''; return { typed: text.length > 10, length: text.length, preview: text.substring(0, 50), type: 'codemirror' }; } return { typed: false, length: 0, preview: '', type: 'none' }; }); if (codeTyped.typed) { console.log(`āœ… Code verified in editor (${codeTyped.type}, ${codeTyped.length} chars): ${codeTyped.preview}...`); } else { console.log(`āš ļø Code verification failed (${codeTyped.type}, length: ${codeTyped.length})`); } // ============================================ // TASK 6: Hit the Run button // Mouse continues from previous position (editor) // ============================================ console.log('šŸ“‹ Task 6: Clicking Run button...'); const runButton = page.locator('#tour-run-button, button:has-text("Run")').first(); if (await runButton.isVisible({ timeout: 2000 }).catch(() => false)) { const runBox = await runButton.boundingBox(); if (runBox) { await moveHandToTarget(page, runBox.x + runBox.width / 2, runBox.y + runBox.height / 2); await runButton.click({ force: true, timeout: 2000 }); console.log('āœ… Run button clicked'); // Wait for code execution to complete and results to show console.log('ā³ Waiting for code execution...'); await page.waitForTimeout(3000); console.log('āœ… Code execution completed'); } } // All tasks complete await page.waitForTimeout(500); console.log('āœ… All tasks completed!'); } catch (error) { console.error('āŒ Error during recording:', error); } finally { await page.close(); await context.close(); await browser.close(); console.log(`šŸ“¹ Video saved: ${outputPath}`); console.log(`\nšŸ’” Tip: Convert to MP4 using ffmpeg:\n ffmpeg -i "${outputPath}" -c:v libx264 -c:a aac "${outputPath}"`); } } createTutorialVideo().catch(console.error);