// ๐ŸŽค createLyricsComponentHandler - Advanced Lyrics Component with Brain Intelligence // Location: .vscode-extensions/cipher-autonomous-dev/src/handlers/createLyricsComponentHandler.ts import * as fs from 'fs'; import * as path from 'path'; import * as vscode from 'vscode'; // ===== โœ… UNIFIED ARCHITECTURE IMPORTS ===== import { displayBrainSuggestions } from '../../shared/displayUtils'; import { getBrainInterface, isBrainAvailable, shareAnalysisData } from '../../shared/utils'; export async function createLyricsComponentHandler(): Promise { try { const brainAvailable = isBrainAvailable(); const message = brainAvailable ? '๐ŸŽค Creating lyrics component with Brain intelligence...' : '๐ŸŽค Creating lyrics component...'; vscode.window.showInformationMessage(message); // ================================================================= // ๐ŸŽฏ COMPONENT TYPE SELECTION // ================================================================= const componentType = await vscode.window.showQuickPick([ { label: '๐ŸŽค Lyrics Analyzer', description: 'Analyze lyrics structure, rhyme, and sentiment', detail: 'Components for lyrics analysis and feedback', type: 'analyzer' }, { label: 'โœ๏ธ Lyrics Editor', description: 'Interactive lyrics writing and editing', detail: 'Rich text editor with music-specific features', type: 'editor' }, { label: '๐ŸŽต Song Structure', description: 'Verse, chorus, bridge organization', detail: 'Components for song structure management', type: 'structure' }, { label: '๐ŸŽถ Rhyme Helper', description: 'Rhyme suggestions and pattern analysis', detail: 'AI-powered rhyming assistance', type: 'rhyme' }, { label: '๐Ÿ“Š Lyrics Dashboard', description: 'Complete lyrics management system', detail: 'Full-featured lyrics workspace', type: 'dashboard' }, { label: '๐Ÿค– AI Lyrics Generator', description: 'Brain-powered lyrics generation', detail: 'Let Cipher create lyrics based on themes', type: 'generator' } ], { placeHolder: 'Choose lyrics component type', title: '๐ŸŽค Lyrics Component Creator' }); if (!componentType) { vscode.window.showWarningMessage('Lyrics component creation canceled.'); return; } // Get component name const componentName = await vscode.window.showInputBox({ prompt: `Enter ${componentType.label} component name`, placeHolder: 'example: LyricsAnalyzer, SongEditor, RhymeHelper', validateInput: (value) => { if (!value || value.trim().length === 0) { return 'Component name is required'; } if (!/^[A-Z][a-zA-Z0-9]*$/.test(value.trim())) { return 'Component name must start with uppercase letter and be PascalCase'; } return null; } }); if (!componentName) { vscode.window.showWarningMessage('Component creation canceled.'); return; } // ================================================================= // ๐Ÿง  BRAIN-ENHANCED COMPONENT GENERATION // ================================================================= const workspace = vscode.workspace.workspaceFolders?.[0]; if (!workspace) { vscode.window.showErrorMessage('No workspace folder found.'); return; } await generateLyricsComponent( componentType.type as string, componentName.trim(), workspace.uri.fsPath ); // ================================================================= // ๐ŸŽฏ COMPLETION & SUGGESTIONS // ================================================================= await showLyricsComponentComplete(componentType.type as string, componentName.trim()); } catch (error) { vscode.window.showErrorMessage(`Lyrics component creation failed: ${error}`); // Learn from errors if (isBrainAvailable()) { await shareAnalysisData('lyrics-component-error', { error: error?.toString(), timestamp: Date.now() }); } } } // ============================================================================= // ๐ŸŽค LYRICS COMPONENT GENERATION ENGINE // ============================================================================= async function generateLyricsComponent(type: string, name: string, workspacePath: string): Promise { const componentPath = path.join(workspacePath, 'src', 'components', `${name}.tsx`); const stylePath = path.join(workspacePath, 'src', 'components', `${name}.module.css`); const testPath = path.join(workspacePath, 'src', 'components', `${name}.test.tsx`); // Ensure components directory exists const componentsDir = path.join(workspacePath, 'src', 'components'); if (!fs.existsSync(componentsDir)) { fs.mkdirSync(componentsDir, { recursive: true }); } let component: string; let styles: string; let tests: string; // Generate based on type switch (type) { case 'analyzer': component = await generateLyricsAnalyzer(name); styles = generateAnalyzerStyles(); tests = generateAnalyzerTests(name); break; case 'editor': component = await generateLyricsEditor(name); styles = generateEditorStyles(); tests = generateEditorTests(name); break; case 'structure': component = await generateSongStructure(name); styles = generateStructureStyles(); tests = generateStructureTests(name); break; case 'rhyme': component = await generateRhymeHelper(name); styles = generateRhymeStyles(); tests = generateRhymeTests(name); break; case 'dashboard': component = await generateLyricsDashboard(name); styles = generateDashboardStyles(); tests = generateDashboardTests(name); break; case 'generator': component = await generateAILyricsGenerator(name); styles = generateGeneratorStyles(); tests = generateGeneratorTests(name); break; default: component = await generateBasicLyricsComponent(name); styles = generateBasicStyles(); tests = generateBasicTests(name); } // Write files fs.writeFileSync(componentPath, component, 'utf8'); fs.writeFileSync(stylePath, styles, 'utf8'); fs.writeFileSync(testPath, tests, 'utf8'); // ๐Ÿง  Learn from component creation if (isBrainAvailable()) { await shareAnalysisData('lyrics-component-created', { type, name, timestamp: Date.now(), filesCreated: 3 }); } // Open the created component const document = await vscode.workspace.openTextDocument(componentPath); await vscode.window.showTextDocument(document); vscode.window.showInformationMessage(`โœ… Created lyrics component: ${name}.tsx with styles and tests`); } // ============================================================================= // ๐ŸŽค COMPONENT GENERATORS // ============================================================================= async function generateLyricsAnalyzer(name: string): Promise { const brainEnhanced = isBrainAvailable(); return `import React, { useState, useEffect } from 'react'; import styles from './${name}.module.css'; interface ${name}Props { lyrics?: string; onAnalysisComplete?: (analysis: LyricsAnalysis) => void; realTimeAnalysis?: boolean; ${brainEnhanced ? 'brainPowered?: boolean;' : ''} } interface LyricsAnalysis { wordCount: number; verseCount: number; chorusCount: number; rhymeScheme: string; sentiment: 'positive' | 'negative' | 'neutral'; themes: string[]; readabilityScore: number; suggestions: string[]; ${brainEnhanced ? 'brainInsights?: BrainInsight[];' : ''} } ${brainEnhanced ? ` interface BrainInsight { type: 'suggestion' | 'pattern' | 'improvement'; message: string; confidence: number; } ` : ''} export const ${name}: React.FC<${name}Props> = ({ lyrics = '', onAnalysisComplete, realTimeAnalysis = false, ${brainEnhanced ? 'brainPowered = true,' : ''} }) => { const [currentLyrics, setCurrentLyrics] = useState(lyrics); const [analysis, setAnalysis] = useState(null); const [isAnalyzing, setIsAnalyzing] = useState(false); ${brainEnhanced ? 'const [brainInsights, setBrainInsights] = useState([]);' : ''} useEffect(() => { if (realTimeAnalysis && currentLyrics.length > 0) { const debounceTimer = setTimeout(() => { analyzeLyrics(currentLyrics); }, 500); return () => clearTimeout(debounceTimer); } }, [currentLyrics, realTimeAnalysis]); const analyzeLyrics = async (text: string) => { if (!text.trim()) return; setIsAnalyzing(true); try { // Basic analysis const basicAnalysis = performBasicAnalysis(text); ${brainEnhanced ? ` // Brain-enhanced analysis let enhancedAnalysis = basicAnalysis; if (brainPowered) { enhancedAnalysis = await enhanceWithBrainIntelligence(basicAnalysis, text); } setAnalysis(enhancedAnalysis); onAnalysisComplete?.(enhancedAnalysis); ` : ` setAnalysis(basicAnalysis); onAnalysisComplete?.(basicAnalysis); `} } catch (error) { console.error('Lyrics analysis failed:', error); } finally { setIsAnalyzing(false); } }; const performBasicAnalysis = (text: string): LyricsAnalysis => { const lines = text.split('\\n').filter(line => line.trim().length > 0); const words = text.split(/\\s+/).filter(word => word.length > 0); return { wordCount: words.length, verseCount: countVerses(lines), chorusCount: countChoruses(lines), rhymeScheme: analyzeRhymeScheme(lines), sentiment: analyzeSentiment(text), themes: extractThemes(text), readabilityScore: calculateReadability(text), suggestions: generateSuggestions(text, lines, words) }; }; ${brainEnhanced ? ` const enhanceWithBrainIntelligence = async (analysis: LyricsAnalysis, text: string): Promise => { try { // Simulate brain API call const brainResponse = await fetch('/api/brain/analyze-lyrics', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text, analysis }) }); if (brainResponse.ok) { const brainData = await brainResponse.json(); setBrainInsights(brainData.insights || []); return { ...analysis, suggestions: [...analysis.suggestions, ...brainData.suggestions], brainInsights: brainData.insights }; } } catch (error) { console.warn('Brain enhancement failed:', error); } return analysis; }; ` : ''} // Helper functions const countVerses = (lines: string[]): number => { let verses = 0; let inVerse = false; for (const line of lines) { if (line.trim().length > 0) { if (!inVerse) { verses++; inVerse = true; } } else { inVerse = false; } } return verses; }; const countChoruses = (lines: string[]): number => { const lineFreq = new Map(); for (const line of lines) { const normalized = line.trim().toLowerCase(); if (normalized.length > 0) { lineFreq.set(normalized, (lineFreq.get(normalized) || 0) + 1); } } return Array.from(lineFreq.values()).filter(count => count > 1).length; }; const analyzeRhymeScheme = (lines: string[]): string => { const rhymes = lines.map(line => { const words = line.trim().split(/\\s+/); const lastWord = words[words.length - 1]?.toLowerCase().replace(/[^a-z]/g, ''); return lastWord?.slice(-2) || ''; }); const rhymeMap = new Map(); let currentLetter = 'A'; const scheme = []; for (const rhyme of rhymes) { if (!rhyme) continue; if (!rhymeMap.has(rhyme)) { rhymeMap.set(rhyme, currentLetter); currentLetter = String.fromCharCode(currentLetter.charCodeAt(0) + 1); } scheme.push(rhymeMap.get(rhyme)); } return scheme.join(''); }; const analyzeSentiment = (text: string): 'positive' | 'negative' | 'neutral' => { const positive = ['love', 'happy', 'joy', 'beautiful', 'amazing', 'wonderful', 'great']; const negative = ['sad', 'pain', 'hurt', 'broken', 'alone', 'cry', 'dark', 'lost']; const words = text.toLowerCase().split(/\\s+/); const positiveCount = words.filter(word => positive.some(p => word.includes(p))).length; const negativeCount = words.filter(word => negative.some(n => word.includes(n))).length; if (positiveCount > negativeCount) return 'positive'; if (negativeCount > positiveCount) return 'negative'; return 'neutral'; }; const extractThemes = (text: string): string[] => { const themes = { 'Love': ['love', 'heart', 'romance'], 'Loss': ['lost', 'gone', 'goodbye'], 'Hope': ['hope', 'dream', 'future'], 'Freedom': ['free', 'fly', 'escape'], 'Time': ['time', 'moment', 'forever'] }; const textLower = text.toLowerCase(); const detectedThemes = []; for (const [theme, keywords] of Object.entries(themes)) { if (keywords.some(keyword => textLower.includes(keyword))) { detectedThemes.push(theme); } } return detectedThemes.length > 0 ? detectedThemes : ['General']; }; const calculateReadability = (text: string): number => { const sentences = text.split(/[.!?]+/).filter(s => s.trim().length > 0); const words = text.split(/\\s+/).filter(w => w.length > 0); if (sentences.length === 0 || words.length === 0) return 0; const avgWordsPerSentence = words.length / sentences.length; const score = Math.max(0, Math.min(100, 100 - (avgWordsPerSentence - 10) * 5)); return Math.round(score); }; const generateSuggestions = (text: string, lines: string[], words: string[]): string[] => { const suggestions = []; if (words.length < 50) { suggestions.push('Consider expanding for more depth'); } if (lines.length < 8) { suggestions.push('Add more verses to develop the story'); } if (!text.toLowerCase().includes('chorus')) { suggestions.push('Consider adding a chorus section'); } return suggestions; }; return (

๐ŸŽค Lyrics Analyzer ${brainEnhanced ? '๐Ÿง ' : ''}

{isAnalyzing &&
Analyzing...
}