# Contents Control **Interactive table of contents navigation** 📋 The Contents Control provides an automatically generated, hierarchical table of contents for quick document navigation. Click any heading to jump to that section with smooth scrolling and visual highlighting. Perfect for long documents with multiple sections. Positioned in the northwest by default. --- ## Overview The Contents Control extracts all headings from your document and displays them in a structured, clickable table of contents. Navigate long documents quickly and understand document structure at a glance. ### Position - **Default**: Northwest (nw) - top-left corner - **Appearance**: 📋 icon when collapsed - **Title**: "Contents" ### Key Features - 📋 **Automatic extraction** - Finds all headings (h1-h6) in document - 🔍 **Search functionality** - Filter headings by text - 🎯 **Click to navigate** - Smooth scroll to any heading - ✨ **Visual feedback** - Temporary highlight on target heading - 🔄 **Auto-refresh** - Updates when document structure changes - 📐 **Hierarchical display** - Proper indentation for heading levels --- ## Configuration ### Enable/Disable ```javascript new TestDriveJSUI({ container: '#editor', controls: { contentsControl: true // Enable (default: true) } }); ``` ### Custom Position ```javascript new TestDriveJSUI({ container: '#editor', controlPositions: { contentsControl: 'nw' // Northwest (default), or: ne, e, se, s, sw, w } }); ``` --- ## Features ### 1. Automatic Heading Extraction The Contents Control automatically scans your document for headings (h1-h6) and builds a table of contents. #### How It Works **Scanning**: - Queries document for `h1, h2, h3, h4, h5, h6` elements - Extracts heading text and level - Generates unique IDs for navigation (if not present) **ID Generation**: - Converts heading text to URL-safe format - Removes special characters - Replaces spaces with hyphens - Ensures uniqueness with counter suffix if needed **Example**: ```markdown # Getting Started ## Installation Steps ### Prerequisites ``` Becomes: ```javascript [ { id: 'getting-started', text: 'Getting Started', level: 1 }, { id: 'installation-steps', text: 'Installation Steps', level: 2 }, { id: 'prerequisites', text: 'Prerequisites', level: 3 } ] ``` --- ### 2. Hierarchical Display Headings are displayed with indentation based on their level. #### Indentation Rules - **H1**: No indentation (0px) - **H2**: 15px indent - **H3**: 30px indent - **H4**: 45px indent - **H5**: 60px indent - **H6**: 75px indent **Formula**: `indent = (level - 1) × 15px` #### Visual Indicators Each heading link shows: - **Level badge**: `H1`, `H2`, etc. (gray color) - **Heading text**: Blue, underlined on hover - **Hover effect**: Light gray background **Example Display**: ``` H1 Getting Started H2 Installation Steps H3 Prerequisites H3 Download H2 Configuration H3 Basic Setup H3 Advanced Options ``` --- ### 3. Search Functionality Filter headings by text to quickly find sections in large documents. #### Usage 1. Type in the search box at the top of the Contents panel 2. Results filter in real-time as you type 3. Matching headings remain visible 4. Clear search to show all headings **Search behavior**: - Case-insensitive - Partial text matching - Searches heading text only (not IDs) - Updates status count: "Found X headings" **Example**: ``` Search: "install" Results: H1 Getting Started H2 Installation Steps H2 Uninstall Guide ``` --- ### 4. Click to Navigate Click any heading in the Contents panel to jump to that section. #### Navigation Behavior **Smooth scrolling**: - Animated scroll to target heading - Position: `block: 'start'` (heading at top) - Duration: Browser default (~500ms) **Visual highlight**: - Target heading gets yellow background (`#fff3cd`) - Highlight fades after 1.5 seconds - Smooth transition (300ms ease) **Example user flow**: 1. User clicks "Installation Steps" in Contents 2. Document smoothly scrolls to that heading 3. Heading briefly highlights in yellow 4. Highlight fades back to normal --- ### 5. Refresh Functionality Update the table of contents when document structure changes. #### Manual Refresh **Button**: "🔄 Refresh Contents" at bottom of panel **Usage**: - Click to re-scan document for headings - Shows "✅ Updated" confirmation for 1 second - Rebuilds entire table of contents **When to use**: - After adding new headings via section editing - After programmatically modifying document - To ensure TOC is up-to-date #### Auto-Refresh **Automatic detection** every 5 seconds: - Counts current headings in document - Compares to stored count - Refreshes automatically if different **Silent updates**: - No visual feedback (unlike manual refresh) - Preserves scroll position - Maintains search query **Disable auto-refresh**: ```javascript const editor = new TestDriveJSUI({ container: '#editor' }); clearInterval(editor.contentsControl.updateInterval); editor.contentsControl.updateInterval = null; ``` --- ### 6. Heading Status Shows count of headings found. **Display**: "Found X heading(s)" (gray text, centered) **Updates**: - After manual refresh - During search filtering - On auto-refresh **Example**: ``` Found 12 headings (all headings) Found 3 headings (filtered by search) No headings found (empty document) ``` --- ## Examples ### Basic Usage ```javascript const editor = new TestDriveJSUI({ container: '#editor', markdown: '# Chapter 1\\n\\n## Section 1.1\\n\\n## Section 1.2', controls: { contentsControl: true } }); ``` ### Custom Position (Bottom-Left) ```javascript // Move to southwest (bottom-left) const editor = new TestDriveJSUI({ container: '#editor', controlPositions: { contentsControl: 'sw' } }); ``` ### Documentation Viewer Setup ```javascript // Perfect for long documentation const editor = new TestDriveJSUI({ container: '#viewer', mode: 'view', // Read-only controls: { editControl: false, statusControl: false, contentsControl: true, // Only show TOC debugControl: false } }); ``` ### Programmatic Navigation ```javascript const editor = new TestDriveJSUI({ container: '#editor' }); // Navigate to specific heading by ID editor.contentsControl.navigateToHeading('installation-steps'); // Or find and navigate by text const heading = editor.contentsControl.headings.find(h => h.text.includes('Installation') ); if (heading) { editor.contentsControl.navigateToHeading(heading.id); } ``` ### Track Navigation Events ```javascript const editor = new TestDriveJSUI({ container: '#editor' }); // Monitor which sections users visit const originalNavigate = editor.contentsControl.navigateToHeading.bind(editor.contentsControl); editor.contentsControl.navigateToHeading = function(headingId) { const heading = this.headings.find(h => h.id === headingId); console.log(`User navigated to: ${heading?.text || headingId}`); // Analytics fetch('/api/analytics', { method: 'POST', body: JSON.stringify({ event: 'toc_navigation', heading: heading?.text, timestamp: new Date().toISOString() }) }); return originalNavigate(headingId); }; ``` --- ## API Reference ### Properties Access via `editor.contentsControl`: ```javascript const contentsCtrl = editor.contentsControl; // Array of extracted headings contentsCtrl.headings = [ { id: 'getting-started', text: 'Getting Started', level: 1, element: HTMLElement, // Reference to heading element index: 0 }, // ... more headings ]; // Current search query contentsCtrl.searchQuery = 'install'; // Last scan timestamp contentsCtrl.lastScanTime = 1702742452123; // Auto-refresh interval ID contentsCtrl.updateInterval = 12345; // Configuration contentsCtrl.config.position = 'nw'; // Compass position contentsCtrl.config.icon = '📋'; // Panel icon contentsCtrl.config.title = 'Contents'; // Panel title contentsCtrl.isExpanded; // true if expanded ``` ### Methods ```javascript const contentsCtrl = editor.contentsControl; // Extract headings from document const headings = contentsCtrl.extractHeadings(); // Returns: Array of heading objects // Filter headings by search query const filtered = contentsCtrl.filterHeadings(headings, 'install'); // Returns: Array of matching headings // Navigate to heading with smooth scroll const success = contentsCtrl.navigateToHeading('installation-steps'); // Returns: true if heading found, false otherwise // Handle search input contentsCtrl.handleSearch('configuration'); // Updates searchQuery and rebuilds content // Refresh contents manually contentsCtrl.refreshContents(); // Re-scans document and updates display // Generate content HTML const html = contentsCtrl.generateContent(); // Returns: HTML string for panel content ``` --- ## Advanced Usage ### Custom Heading ID Format ```javascript const editor = new TestDriveJSUI({ container: '#editor' }); // Override ID generation const originalExtract = editor.contentsControl.extractHeadings.bind(editor.contentsControl); editor.contentsControl.extractHeadings = function() { const result = originalExtract(); // Custom ID format: section-1-2-3 result.forEach((heading, index) => { heading.id = `section-${index + 1}`; heading.element.id = heading.id; }); this.headings = result; return result; }; ``` ### Collapse All Sections Except One ```javascript const editor = new TestDriveJSUI({ container: '#editor' }); function focusOnSection(headingId) { // Navigate to heading editor.contentsControl.navigateToHeading(headingId); // Highlight in TOC const tocItems = document.querySelectorAll('.contents-item a'); tocItems.forEach(item => { if (item.getAttribute('href') === `#${headingId}`) { item.style.fontWeight = 'bold'; item.style.backgroundColor = '#e7f3ff'; } else { item.style.fontWeight = 'normal'; item.style.backgroundColor = 'transparent'; } }); } focusOnSection('installation-steps'); ``` ### Export Table of Contents ```javascript const editor = new TestDriveJSUI({ container: '#editor' }); function exportTOC() { const toc = editor.contentsControl.headings.map(h => ({ level: h.level, text: h.text, id: h.id })); // As JSON const json = JSON.stringify(toc, null, 2); // As Markdown const markdown = toc.map(h => { const indent = ' '.repeat(h.level - 1); return `${indent}- [${h.text}](#${h.id})`; }).join('\\n'); console.log('JSON:', json); console.log('Markdown:', markdown); return { json, markdown }; } exportTOC(); ``` ### Custom Search Logic ```javascript const editor = new TestDriveJSUI({ container: '#editor' }); // Override filter to search by level too const originalFilter = editor.contentsControl.filterHeadings.bind(editor.contentsControl); editor.contentsControl.filterHeadings = function(headings, query) { if (!query || query.trim() === '') { return headings; } // Support "h1", "h2" prefixes const levelMatch = query.match(/^h([1-6])\s*/i); if (levelMatch) { const level = parseInt(levelMatch[1]); const textQuery = query.substring(levelMatch[0].length); let results = headings.filter(h => h.level === level); if (textQuery) { results = results.filter(h => h.text.toLowerCase().includes(textQuery.toLowerCase()) ); } return results; } // Default text search return originalFilter(headings, query); }; ``` --- ## Troubleshooting ### No Headings Found **Problem**: Contents panel shows "No headings found in document" **Causes & Solutions**: 1. **Document has no headings** - Add headings to your markdown: `# Heading`, `## Subheading` - Click "🔄 Refresh" after adding headings 2. **Headings not rendered yet** - Wait for markdown rendering to complete - Use manual refresh button 3. **Wrong selector** - Verify headings are actual `