/** * Slide Factory - Creates Slides from Content Analysis * * Generates slide structures based on: * - Presentation mode (keynote vs business) * - Content analysis results * - Expert methodology recommendations */ import type { Slide, SlideType, SlideData, ContentAnalysis, PresentationMode, ContentSection } from '../types/index.js'; interface SlideTemplate { type: SlideType; requiredFields: string[]; optionalFields: string[]; keynoteSuitable: boolean; businessSuitable: boolean; maxWords: number; } export class SlideFactory { private readonly templates: Map; private usedContent: Set = new Set(); constructor() { this.templates = this.initializeTemplates(); } /** * Check if content has already been used (deduplication) */ private isContentUsed(content: string): boolean { if (!content) return true; const normalized = content.toLowerCase().replace(/[^a-z0-9]/g, '').slice(0, 50); if (this.usedContent.has(normalized)) { return true; } this.usedContent.add(normalized); return false; } /** * Create slides from analyzed content. * * ARCHITECTURE (per KB expert methodologies): * 1. Title slide - always first * 2. Agenda slide - business mode only with 3+ sections * 3. SCQA slides - Situation, Complication (per Minto) * 4. Content slides - from sections with bullets/content * 5. Metrics slide - if data points exist * 6. Solution slide - SCQA answer * 7. STAR moments - only if high-quality (per Duarte) * 8. CTA slide - if call to action exists * 9. Thank you slide - always last */ async createSlides(analysis: ContentAnalysis, mode: PresentationMode): Promise { const slides: Slide[] = []; let slideIndex = 0; // Reset deduplication tracking this.usedContent.clear(); // 1. Title slide (always first) slides.push(this.createTitleSlide(slideIndex++, analysis)); this.isContentUsed(analysis.titles[0] ?? ''); // 2. Agenda slide (business mode with 3+ substantive sections) const substantiveSections = analysis.sections.filter(s => s.level === 2 && (s.bullets.length > 0 || s.content.length > 50) ); if (mode === 'business' && substantiveSections.length >= 3) { slides.push(this.createAgendaSlide(slideIndex++, analysis)); } // 3. Situation/Context slide (from SCQA - must be substantive) if (analysis.scqa.situation && analysis.scqa.situation.length > 30 && !this.isContentUsed(analysis.scqa.situation)) { slides.push(this.createContextSlide(slideIndex++, analysis, mode)); } // 4. Problem/Complication slide (must be substantive) if (analysis.scqa.complication && analysis.scqa.complication.length > 30 && !this.isContentUsed(analysis.scqa.complication)) { slides.push(this.createProblemSlide(slideIndex++, analysis, mode)); } // 5. Content slides from sections with actual content // CRITICAL: Check both header AND content for duplicates for (const section of substantiveSections.slice(0, 4)) { const headerUsed = this.isContentUsed(section.header); const contentUsed = section.content.length > 30 && this.isContentUsed(section.content.slice(0, 80)); if (!headerUsed && !contentUsed) { // Create section slide with bullets if available if (section.bullets.length > 0) { slides.push(this.createSectionBulletSlide(slideIndex++, section, mode)); } else if (section.content.length > 50) { slides.push(this.createSectionContentSlide(slideIndex++, section, mode)); } } } // 6. Key message slides - only if they're real sentences (not headers) for (const message of analysis.keyMessages) { const wordCount = message.split(/\s+/).length; // Must be a real sentence: 6+ words, not a header pattern if (wordCount >= 6 && !/^(The |Our |Your |Overview|Introduction|Conclusion)/i.test(message) && !this.isContentUsed(message)) { slides.push(this.createMessageSlide(slideIndex++, message, mode)); } } // 7. Metrics slide (if we have data points) if (analysis.dataPoints.length >= 2) { slides.push(this.createMetricsSlide(slideIndex++, analysis.dataPoints)); } // 8. Solution/Answer slide (must be substantive) if (analysis.scqa.answer && analysis.scqa.answer.length > 30 && !this.isContentUsed(analysis.scqa.answer)) { slides.push(this.createSolutionSlide(slideIndex++, analysis, mode)); } // 9. STAR moment slides - only if they're complete sentences // Additional validation layer to prevent fragments from slipping through const verbPattern = /\b(is|are|was|were|will|can|should|must|has|have|provides?|enables?|allows?|achieves?|exceeds?|results?|generates?|delivers?|creates?)\b/i; for (const starMoment of analysis.starMoments.slice(0, 2)) { const wordCount = starMoment.split(/\s+/).length; const hasVerb = verbPattern.test(starMoment); // Must be: 6+ words, 40+ chars, have a verb, and not already used if (wordCount >= 6 && starMoment.length >= 40 && hasVerb && !this.isContentUsed(starMoment)) { slides.push(this.createStarMomentSlide(slideIndex++, starMoment, mode)); } } // 10. Call to action slide if (analysis.sparkline.callToAdventure && analysis.sparkline.callToAdventure.length > 20 && !this.isContentUsed(analysis.sparkline.callToAdventure)) { slides.push(this.createCTASlide(slideIndex++, analysis, mode)); } // 11. Thank you slide (always last) slides.push(this.createThankYouSlide(slideIndex++)); return slides; } /** * Create a slide from a section with bullets */ private createSectionBulletSlide(index: number, section: ContentSection, mode: PresentationMode): Slide { const bullets = section.bullets.slice(0, mode === 'keynote' ? 3 : 5); return { index, type: 'bullet-points', data: { title: this.truncate(section.header, 60), bullets: bullets.map(b => this.cleanText(b).slice(0, 80)) }, classes: ['slide-bullet-points'] }; } /** * Create a slide from a section with body content */ private createSectionContentSlide(index: number, section: ContentSection, mode: PresentationMode): Slide { if (mode === 'keynote') { return { index, type: 'single-statement', data: { title: this.truncate(this.extractFirstSentence(section.content), 80), keyMessage: section.header }, classes: ['slide-single-statement'] }; } return { index, type: 'two-column', data: { title: this.truncate(section.header, 60), body: this.truncate(section.content, 200) }, classes: ['slide-two-column'] }; } /** * Extract first sentence from text */ private extractFirstSentence(text: string): string { const cleaned = this.cleanText(text); const match = cleaned.match(/^[^.!?]+[.!?]/); return match ? match[0].trim() : cleaned.slice(0, 100); } /** * Create a metrics slide from data points */ private createMetricsSlide(index: number, dataPoints: Array<{ value: string; label: string }>): Slide { const metrics = dataPoints.slice(0, 4).map(dp => ({ value: dp.value, label: this.cleanText(dp.label).slice(0, 40) })); return { index, type: 'metrics-grid', data: { title: 'Key Metrics', metrics }, classes: ['slide-metrics-grid'] }; } /** * Create a title slide. */ private createTitleSlide(index: number, analysis: ContentAnalysis): Slide { // Prefer SCQA answer as subtitle (the "so what"), then actual keyMessage // Do NOT use keyMessages[0] as it's typically a section header let subtitle = ''; if (analysis.scqa.answer && analysis.scqa.answer.length > 10) { subtitle = analysis.scqa.answer; } else if (analysis.starMoments.length > 0 && analysis.starMoments[0]) { // Use a STAR moment if available subtitle = analysis.starMoments[0]; } return { index, type: 'title', data: { title: analysis.titles[0] ?? 'Presentation', subtitle: this.truncate(subtitle, 80), keyMessage: analysis.scqa.answer }, classes: ['slide-title'] }; } /** * Create an agenda slide. */ private createAgendaSlide(index: number, analysis: ContentAnalysis): Slide { return { index, type: 'agenda', data: { title: 'Agenda', bullets: analysis.keyMessages.map((msg, i) => `${i + 1}. ${this.truncate(msg, 50)}`) }, classes: ['slide-agenda'] }; } /** * Create a context/situation slide. */ private createContextSlide(index: number, analysis: ContentAnalysis, mode: PresentationMode): Slide { if (mode === 'keynote') { return { index, type: 'single-statement', data: { title: this.truncate(analysis.scqa.situation, 80), keyMessage: 'The current state' }, classes: ['slide-single-statement'] }; } return { index, type: 'two-column', data: { title: 'Current Situation', body: analysis.scqa.situation, bullets: analysis.sparkline.whatIs.slice(0, 3) }, classes: ['slide-two-column'] }; } /** * Create a problem/complication slide. */ private createProblemSlide(index: number, analysis: ContentAnalysis, mode: PresentationMode): Slide { if (mode === 'keynote') { return { index, type: 'big-idea', data: { title: this.truncate(analysis.scqa.complication, 60), keyMessage: 'The challenge we face' }, classes: ['slide-big-idea'] }; } return { index, type: 'bullet-points', data: { title: 'The Challenge', body: analysis.scqa.complication, bullets: this.extractBullets(analysis.scqa.complication) }, classes: ['slide-bullet-points'] }; } /** * Create a key message slide. */ private createMessageSlide(index: number, message: string, mode: PresentationMode): Slide { if (mode === 'keynote') { // For keynote: single statement, big impact return { index, type: 'single-statement', data: { title: this.truncate(message, 60), keyMessage: message }, classes: ['slide-single-statement'] }; } // For business: more detail allowed return { index, type: 'bullet-points', data: { title: this.extractActionTitle(message), body: message, bullets: this.extractBullets(message) }, classes: ['slide-bullet-points'] }; } /** * Create a STAR moment slide. */ private createStarMomentSlide(index: number, starMoment: string, mode: PresentationMode): Slide { // Check if it contains a statistic const statMatch = starMoment.match(/(\d+[%xX]|\$[\d,]+(?:\s*(?:million|billion))?)/); if (statMatch && statMatch[1]) { const stat = statMatch[1]; return { index, type: 'big-number', data: { title: stat, subtitle: this.removeStatistic(starMoment, stat), keyMessage: starMoment }, classes: ['slide-big-number'] }; } // Otherwise use as a quote or big idea if (mode === 'keynote') { return { index, type: 'big-idea', data: { title: this.truncate(starMoment, 80), keyMessage: 'A key insight' }, classes: ['slide-big-idea'] }; } return { index, type: 'quote', data: { quote: starMoment, attribution: 'Key Insight' }, classes: ['slide-quote'] }; } /** * Create a solution/answer slide. */ private createSolutionSlide(index: number, analysis: ContentAnalysis, mode: PresentationMode): Slide { if (mode === 'keynote') { return { index, type: 'big-idea', data: { title: this.truncate(analysis.scqa.answer, 60), keyMessage: 'Our answer' }, classes: ['slide-big-idea'] }; } return { index, type: 'two-column', data: { title: 'The Solution', body: analysis.scqa.answer, bullets: analysis.sparkline.whatCouldBe.slice(0, 4) }, classes: ['slide-two-column'] }; } /** * Create a call-to-action slide. */ private createCTASlide(index: number, analysis: ContentAnalysis, mode: PresentationMode): Slide { return { index, type: 'cta', data: { title: mode === 'keynote' ? 'Take Action' : 'Next Steps', body: analysis.sparkline.callToAdventure, keyMessage: 'What we need from you' }, classes: ['slide-cta'] }; } /** * Create a thank you slide. */ private createThankYouSlide(index: number): Slide { return { index, type: 'thank-you', data: { title: 'Thank You', subtitle: 'Questions?' }, classes: ['slide-thank-you'] }; } /** * Initialize slide templates with constraints. */ private initializeTemplates(): Map { const templates = new Map(); // Title slides templates.set('title', { type: 'title', requiredFields: ['title'], optionalFields: ['subtitle', 'author', 'date'], keynoteSuitable: true, businessSuitable: true, maxWords: 15 }); // Big idea (keynote) templates.set('big-idea', { type: 'big-idea', requiredFields: ['title'], optionalFields: ['keyMessage'], keynoteSuitable: true, businessSuitable: false, maxWords: 10 }); // Single statement (keynote) templates.set('single-statement', { type: 'single-statement', requiredFields: ['title'], optionalFields: ['keyMessage'], keynoteSuitable: true, businessSuitable: false, maxWords: 15 }); // Big number templates.set('big-number', { type: 'big-number', requiredFields: ['title'], optionalFields: ['subtitle', 'source'], keynoteSuitable: true, businessSuitable: true, maxWords: 10 }); // Quote templates.set('quote', { type: 'quote', requiredFields: ['quote'], optionalFields: ['attribution', 'source'], keynoteSuitable: true, businessSuitable: true, maxWords: 30 }); // Bullet points (business) templates.set('bullet-points', { type: 'bullet-points', requiredFields: ['title', 'bullets'], optionalFields: ['body'], keynoteSuitable: false, businessSuitable: true, maxWords: 80 }); // Two column (business) templates.set('two-column', { type: 'two-column', requiredFields: ['title'], optionalFields: ['body', 'bullets', 'images'], keynoteSuitable: false, businessSuitable: true, maxWords: 100 }); // Agenda templates.set('agenda', { type: 'agenda', requiredFields: ['title', 'bullets'], optionalFields: [], keynoteSuitable: false, businessSuitable: true, maxWords: 50 }); // CTA templates.set('cta', { type: 'cta', requiredFields: ['title'], optionalFields: ['body', 'keyMessage'], keynoteSuitable: true, businessSuitable: true, maxWords: 30 }); // Thank you templates.set('thank-you', { type: 'thank-you', requiredFields: ['title'], optionalFields: ['subtitle'], keynoteSuitable: true, businessSuitable: true, maxWords: 10 }); return templates; } // === Helper Methods === /** * Clean text by removing all markdown and content markers. * CRITICAL: Must strip all formatting to prevent garbage in slides */ private cleanText(text: string): string { if (!text) return ''; return text // Remove markdown headers .replace(/^#+\s+/gm, '') // Remove bold/italic markers .replace(/\*\*([^*]+)\*\*/g, '$1') .replace(/\*([^*]+)\*/g, '$1') .replace(/__([^_]+)__/g, '$1') .replace(/_([^_]+)_/g, '$1') // Remove markdown links .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1') // Remove table syntax .replace(/\|/g, ' ') .replace(/-{3,}/g, '') // Remove content markers .replace(/\[HEADER\]\s*/g, '') .replace(/\[BULLET\]\s*/g, '') .replace(/\[NUMBERED\]\s*/g, '') .replace(/\[EMPHASIS\]/g, '') .replace(/\[\/EMPHASIS\]/g, '') .replace(/\[CODE BLOCK\]/g, '') .replace(/\[IMAGE\]/g, '') // Normalize whitespace .replace(/\n{2,}/g, ' ') .replace(/\s+/g, ' ') .trim(); } /** * Truncate text to max length at sentence boundary when possible. * CRITICAL: Never cut mid-number (99.5% should not become 99.) */ private truncate(text: string, maxLength: number): string { // First clean the text of all markers const cleanedText = this.cleanText(text); if (!cleanedText || cleanedText.length <= maxLength) { return cleanedText; } // Try to find a sentence boundary within the limit const sentences = cleanedText.match(/[^.!?]+[.!?]/g); if (sentences) { let result = ''; for (const sentence of sentences) { if ((result + sentence).length <= maxLength) { result += sentence; } else { break; } } if (result.length > maxLength * 0.5) { return result.trim(); } } // Fallback: truncate at word boundary, but not mid-number const truncated = cleanedText.slice(0, maxLength); let lastSpace = truncated.lastIndexOf(' '); // Check if we're cutting a number (look for digits after the cut point) const afterCut = cleanedText.slice(lastSpace + 1, maxLength + 10); if (/^[\d.,%$]+/.test(afterCut)) { // We're in the middle of a number, find earlier break lastSpace = truncated.slice(0, lastSpace).lastIndexOf(' '); } if (lastSpace > maxLength * 0.5) { return truncated.slice(0, lastSpace) + '...'; } return truncated + '...'; } /** * Extract an action title from a message. */ private extractActionTitle(message: string): string { // First clean the text const cleanedMessage = this.cleanText(message); // Take first sentence or first N words const firstSentence = cleanedMessage.split(/[.!?]/)[0]; if (firstSentence && firstSentence.length <= 50) { return firstSentence; } const words = cleanedMessage.split(/\s+/).slice(0, 6); return words.join(' '); } /** * Extract bullet points from text. */ private extractBullets(text: string): string[] { if (!text) return []; // Check for explicit bullets const bulletMatches = text.match(/\[BULLET\]\s*(.+)/g); if (bulletMatches && bulletMatches.length > 0) { return bulletMatches.map(b => this.cleanText(b)).slice(0, 5); } // Clean the text first const cleanedText = this.cleanText(text); // Split into sentences and use as bullets const sentences = cleanedText.split(/[.!?]+/).filter(s => s.trim().length > 10); return sentences.slice(0, 5).map(s => s.trim()); } /** * Remove a statistic from text and clean thoroughly. */ private removeStatistic(text: string, stat: string): string { const cleaned = this.cleanText(text) .replace(stat, '') .replace(/^\s*[-–—:,]\s*/, '') .trim(); // Take just the first sentence for context const firstSentence = cleaned.match(/^[^.!?]+[.!?]?/); return firstSentence ? firstSentence[0].slice(0, 80) : cleaned.slice(0, 80); } }