# Status Control **Real-time document statistics and change tracking** ๐Ÿ“Š The Status Control provides comprehensive document analytics including word count, character count, reading time estimation, document structure analysis, and change tracking. Monitor your document metrics in real-time as you write and edit. Positioned in the east by default. --- ## Overview The Status Control continuously monitors your document and provides detailed statistics about content, structure, and reading metrics. Perfect for writers, editors, and content creators who need to track document metrics. ### Position - **Default**: East (e) - middle-right side - **Appearance**: ๐Ÿ“Š icon when collapsed - **Title**: "Status" ### Key Features - ๐Ÿ“Š **Real-time statistics** - Word/character count, reading time - ๐Ÿ“ˆ **Change tracking** - Visual indicators for increases/decreases - ๐Ÿ“ **Document structure** - Paragraphs, headings, lists, images, links - ๐Ÿ”„ **Auto-refresh** - Updates every 10 seconds automatically - ๐Ÿ“ค **Export functionality** - Download statistics as JSON --- ## Configuration ### Enable/Disable ```javascript new TestDriveJSUI({ container: '#editor', controls: { statusControl: true // Enable (default: true) } }); ``` ### Custom Position ```javascript new TestDriveJSUI({ container: '#editor', controlPositions: { statusControl: 'e' // East (default), or: nw, ne, se, s, sw, w } }); ``` --- ## Features ### 1. Content Statistics #### Word Count Shows total words in the document, calculated by splitting text on whitespace and filtering empty strings. **Display**: Large, blue-colored number with change indicator **Example**: `1,247 (+23)` - Document has 1,247 words, increased by 23 since last update #### Character Count Total characters including spaces. **Display**: Formatted with thousand separators **Also tracks**: Characters without spaces (internal metric) #### Reading Time Estimated reading time in minutes based on average reading speed. **Calculation**: Total words รท 200 words per minute (configurable) **Display**: `5 min (+1)` - Takes 5 minutes to read, increased by 1 minute **Tip**: Useful for blog posts, articles, and documentation to estimate reader time investment #### Sentence Count Approximate sentence count based on punctuation (., !, ?). **Use case**: Track writing complexity and paragraph length --- ### 2. Document Structure The Status Control analyzes your document structure and counts: #### Paragraphs Total `

` elements in the rendered HTML. **Use case**: Ensure proper document segmentation #### Headings Total headings (h1-h6) in the document. **Use case**: Verify document outline and hierarchy **Tip**: Good documents typically have 1 h1 and logical heading progression #### Lists Total lists (ordered and unordered). **Use case**: Track enumeration and structured content #### Images Total images in the document. **Use case**: Monitor visual content distribution #### Links Total hyperlinks in the document. **Use case**: Track references and external resources --- ### 3. Change Tracking #### Visual Indicators Changes since last update are shown with: **Positive changes** (increases): - Green color: `#28a745` - Plus sign: `(+5)` - Indicates growth in that metric **Negative changes** (decreases): - Red color: `#dc3545` - Minus sign: `(-3)` - Indicates reduction in that metric **No change**: No indicator shown #### Example Display ``` Words: 1,247 (+23) Characters: 6,543 (+145) Reading Time: 6 min Sentences: 89 (+2) ``` The green numbers show the document grew by 23 words, 145 characters, and 2 sentences. --- ### 4. Actions #### ๐Ÿ”„ Refresh Manually refresh statistics immediately. **Usage**: - Click "๐Ÿ”„ Refresh" button - Shows "โœ… Updated" confirmation for 1 second **When to use**: - After making significant edits - When you want immediate feedback - To see updated change indicators **Note**: Statistics auto-refresh every 10 seconds, so manual refresh is optional #### ๐Ÿ“Š Export Export statistics to JSON file for external analysis. **Usage**: - Click "๐Ÿ“Š Export" button - Downloads: `document-stats-YYYY-MM-DD.json` **File contents**: ```json { "timestamp": "2025-12-16T14:30:52.123Z", "document": { "title": "My Document", "url": "http://localhost:8080/editor.html" }, "statistics": { "characters": 6543, "charactersNoSpaces": 5421, "words": 1247, "sentences": 89, "paragraphs": 34, "headings": 12, "lists": 5, "images": 3, "links": 18, "readingTimeMinutes": 6 }, "metadata": { "wordsPerMinute": 200, "analysisDate": "2025-12-16T14:30:52.123Z" } } ``` **Use cases**: - Track document evolution over time - Compare statistics across multiple documents - Generate reports for clients or stakeholders - Integrate with external analytics tools --- ### 5. Auto-Refresh The Status Control automatically refreshes every **10 seconds** to keep statistics current. **Behavior**: - Silent background updates - Preserves change tracking between updates - Minimal performance impact - Continues while control is expanded or collapsed **Disable auto-refresh**: Not currently supported via config (always enabled) --- ## Examples ### Basic Usage ```javascript const editor = new TestDriveJSUI({ container: '#editor', markdown: '# My Document\\n\\nThis is a sample paragraph.', controls: { statusControl: true } }); ``` ### Custom Position (Top-Right) ```javascript // Move status control to northeast (top-right) const editor = new TestDriveJSUI({ container: '#editor', controlPositions: { statusControl: 'ne' // Top-right corner } }); ``` ### Blog Post Writer Setup ```javascript // Emphasize word count for blog writing const editor = new TestDriveJSUI({ container: '#editor', controls: { editControl: true, // Save and export statusControl: true, // Track word count goal contentsControl: false, debugControl: false } }); // Monitor word count for target goal setInterval(() => { const stats = editor.statusControl.stats; const targetWords = 1500; if (stats.words >= targetWords) { console.log(`๐ŸŽ‰ Goal reached! ${stats.words} words written.`); } else { const remaining = targetWords - stats.words; console.log(`โœ๏ธ Keep writing! ${remaining} words to go.`); } }, 5000); ``` ### Export Statistics for Reporting ```javascript const editor = new TestDriveJSUI({ container: '#editor' }); // Programmatically export stats document.getElementById('report-btn').addEventListener('click', () => { // Refresh to get latest stats editor.statusControl.refreshStats(); // Export to JSON setTimeout(() => { editor.statusControl.exportStats(); }, 100); }); ``` --- ## API Reference ### Properties Access via `editor.statusControl`: ```javascript const statusCtrl = editor.statusControl; // Current statistics object statusCtrl.stats = { characters: 6543, charactersNoSpaces: 5421, words: 1247, sentences: 89, paragraphs: 34, headings: 12, lists: 5, images: 3, links: 18, readingTimeMinutes: 6 }; // Previous statistics (for change tracking) statusCtrl.previousStats = { /* ... */ }; // Last update timestamp statusCtrl.lastUpdateTime = 1702742452123; // Reading speed setting (words per minute) statusCtrl.wordsPerMinute = 200; // Adjustable // Auto-refresh interval ID statusCtrl.updateInterval = 12345; ``` ### Methods ```javascript const statusCtrl = editor.statusControl; // Analyze document and update statistics statusCtrl.analyzeDocument(); // Returns: stats object // Calculate changes since last update const changes = statusCtrl.calculateChanges(); // Returns: { words: { current, previous, change, hasChanged }, ... } // Format statistics as HTML const html = statusCtrl.formatStatistics(); // Returns: HTML string // Refresh stats and update display statusCtrl.refreshStats(); // Export statistics to JSON file statusCtrl.exportStats(); // Calculate readability score (Flesch Reading Ease) const readability = statusCtrl.calculateReadabilityScore(); // Returns: { score: 65, level: 'Standard' } // Configuration statusCtrl.config.position = 'e'; // Compass position statusCtrl.config.icon = '๐Ÿ“Š'; // Panel icon statusCtrl.config.title = 'Status'; // Panel title statusCtrl.isExpanded; // true if expanded ``` ### Readability Levels The `calculateReadabilityScore()` method returns: | Score Range | Level | Description | |-------------|-------|-------------| | 90-100 | Very Easy | 5th grade level | | 80-89 | Easy | 6th grade level | | 70-79 | Fairly Easy | 7th grade level | | 60-69 | Standard | 8th-9th grade level | | 50-59 | Fairly Difficult | 10th-12th grade level | | 30-49 | Difficult | College level | | 0-29 | Very Difficult | College graduate level | **Note**: Readability scoring uses simplified Flesch Reading Ease formula with approximated syllable counts. --- ## Advanced Usage ### Custom Reading Speed ```javascript const editor = new TestDriveJSUI({ container: '#editor' }); // Adjust for faster readers (250 words per minute) editor.statusControl.wordsPerMinute = 250; editor.statusControl.refreshStats(); // Or slower readers (150 words per minute) editor.statusControl.wordsPerMinute = 150; editor.statusControl.refreshStats(); ``` ### Programmatic Access ```javascript const editor = new TestDriveJSUI({ container: '#editor' }); // Get current word count const wordCount = editor.statusControl.stats.words; console.log(`Current word count: ${wordCount}`); // Get reading time const readingTime = editor.statusControl.stats.readingTimeMinutes; console.log(`Estimated reading time: ${readingTime} minutes`); // Check if document structure is balanced const stats = editor.statusControl.stats; const avgParasPerHeading = stats.paragraphs / stats.headings; console.log(`Average paragraphs per section: ${avgParasPerHeading.toFixed(1)}`); ``` ### Change Detection ```javascript const editor = new TestDriveJSUI({ container: '#editor' }); // Monitor specific changes const original = editor.statusControl.stats.words; // ... user edits document ... editor.statusControl.refreshStats(); const current = editor.statusControl.stats.words; const delta = current - original; if (delta > 0) { console.log(`Added ${delta} words`); } else if (delta < 0) { console.log(`Removed ${Math.abs(delta)} words`); } ``` ### Custom Auto-Refresh Interval ```javascript const editor = new TestDriveJSUI({ container: '#editor' }); // Stop default 10-second refresh clearInterval(editor.statusControl.updateInterval); // Set custom 5-second refresh editor.statusControl.updateInterval = setInterval(() => { editor.statusControl.refreshStats(); }, 5000); ``` --- ## Troubleshooting ### Statistics Not Updating **Problem**: Numbers don't change after editing **Solutions**: 1. Click "๐Ÿ”„ Refresh" button manually 2. Check if auto-refresh is running: `editor.statusControl.updateInterval` 3. Verify StatusControl is loaded: `typeof StatusControl !== 'undefined'` 4. Check browser console for JavaScript errors ### Incorrect Word Count **Problem**: Word count seems wrong **Causes & Solutions**: 1. **Whitespace handling**: Multiple spaces count as one separator (correct behavior) 2. **HTML tags**: Only text content is counted, not HTML markup 3. **Code blocks**: Code is included in word count 4. **Special characters**: Punctuation is included in words **Manual verification**: ```javascript // Get exact text being counted const contentArea = document.querySelector('#markitect-content'); const text = contentArea.textContent; const words = text.trim().split(/\s+/).filter(w => w.length > 0); console.log('Words:', words.length, words); ``` ### Export Button Not Working **Problem**: Clicking export does nothing **Solutions**: 1. Check browser's download settings 2. Verify pop-up/download permissions 3. Test programmatically: `editor.statusControl.exportStats()` 4. Check browser console for errors 5. Try different browser ### Reading Time Seems Wrong **Problem**: Estimated reading time is too short/long **Solution**: Adjust reading speed ```javascript // For technical content (slower reading) editor.statusControl.wordsPerMinute = 150; // For light reading (faster) editor.statusControl.wordsPerMinute = 250; // Refresh to recalculate editor.statusControl.refreshStats(); ``` **Factors affecting reading time**: - Technical complexity - Reader expertise level - Language proficiency - Content density --- ## Best Practices ### For Writers 1. **Set word count goals** - Monitor progress toward target lengths 2. **Track reading time** - Ensure articles fit time budgets (e.g., 5-minute reads) 3. **Balance structure** - Use heading/paragraph ratios to check organization 4. **Export regularly** - Save statistics to track writing productivity over time ### For Editors 1. **Monitor changes** - Use change indicators to track editing impact 2. **Verify readability** - Check `calculateReadabilityScore()` for target audience 3. **Structure analysis** - Ensure proper heading hierarchy and paragraph distribution 4. **Compare versions** - Export stats before/after editing to quantify improvements ### For Developers 1. **Integrate with backend** - Send statistics to server for analytics 2. **Custom thresholds** - Set alerts for minimum/maximum word counts 3. **Programmatic access** - Use API for automated quality checks 4. **Performance** - Monitor update frequency if handling very large documents Example integration: ```javascript const editor = new TestDriveJSUI({ container: '#editor' }); // Auto-save with statistics editor.on('save', async (data) => { const stats = editor.statusControl.stats; await fetch('/api/documents', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ markdown: data.markdown, statistics: stats, timestamp: new Date().toISOString() }) }); }); ``` --- ## Performance Considerations ### For Large Documents (10,000+ words) **Impact**: Auto-refresh every 10 seconds may cause lag **Solutions**: 1. Increase refresh interval: ```javascript clearInterval(editor.statusControl.updateInterval); editor.statusControl.updateInterval = setInterval(() => { editor.statusControl.refreshStats(); }, 30000); // 30 seconds instead ``` 2. Disable auto-refresh, use manual only: ```javascript clearInterval(editor.statusControl.updateInterval); editor.statusControl.updateInterval = null; // User clicks Refresh button when needed ``` 3. Lazy calculation - only analyze visible sections ### Memory Usage Statistics use minimal memory (< 1KB). Change tracking stores two copies of stats object. No memory leaks if control is properly destroyed via `destroy()`. --- ## Related Features - **[Edit Control](edit-control.md)** - Save/export document - **[Contents Control](contents-control.md)** - Navigate document structure - **[Section Editing](section-editing.md)** - Triggers statistics updates --- **See Also**: - [API Reference](../api/status-control.md) - [Examples](../../examples/) --- **Version**: 1.0.0 **Last Updated**: 2025-12-16