Files
testdrive-jsui/docs/features/contents-control.md
tegwick 66cbd5c3d8 docs: comprehensive feature documentation and HTML generation system
Added complete documentation for all TestDrive-JSUI controls and features,
plus flexible HTML generation system supporting standalone and external modes.

Documentation (8 files, 3,533 lines):
- docs/features/README.md: Central hub with overview, config, examples
- docs/features/section-editing.md: Section editing guide
- docs/features/edit-control.md: Document actions and editing tools
- docs/features/status-control.md: Real-time statistics and tracking
- docs/features/contents-control.md: Table of contents navigation
- docs/features/debug-control.md: Development and debugging tools
- docs/features/keyboard-shortcuts.md: Complete shortcuts reference
- docs/features/themes.md: Visual theming and customization

HTML Generation System (3 files, 1,104 lines):
- js/utils/html-generator.js: Dual-mode HTML generator class
  * Standalone mode: All CSS/JS embedded inline
  * External mode: References _jsui/ directory
  * Configurable options for title, content, controls, theme
  * Download and save functionality

- _jsui/ directory: External resources structure
  * README.md: Comprehensive usage guide
  * css/: Symlinked CSS files (base, editor, controls, themes)
  * js/: Symlinked JavaScript files (core, components, controls)
  * Enables smaller HTML files with browser caching

- examples/html-generator-demo.html: Interactive demo
  * Web-based configuration form
  * Side-by-side mode comparison
  * Live generation and preview
  * Download and copy functionality

Key Features:
- 4,637 total lines of documentation and code
- All controls documented with examples and troubleshooting
- Flexible deployment options (standalone vs external)
- Developer-friendly structure with clear guides
- Production-ready system

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-16 14:31:56 +01:00

732 lines
17 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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 `<h1>` - `<h6>` elements (not styled divs)
- Check browser console for errors
**Debug**:
```javascript
// Check if headings exist in DOM
const headings = document.querySelectorAll('h1, h2, h3, h4, h5, h6');
console.log('Headings found:', headings.length);
```
### Navigation Not Working
**Problem**: Clicking headings in TOC doesn't navigate
**Solutions**:
1. **Check for errors**:
```javascript
// Test navigation programmatically
editor.contentsControl.navigateToHeading('your-heading-id');
```
2. **Verify heading IDs**:
```javascript
// List all heading IDs
console.log(editor.contentsControl.headings.map(h => h.id));
```
3. **Scroll container issues**:
- Ensure content is in scrollable container
- Check CSS `overflow` properties
- Try without smooth scroll:
```javascript
const elem = document.getElementById('heading-id');
elem.scrollIntoView({ behavior: 'auto' });
```
### Search Not Working
**Problem**: Typing in search box doesn't filter headings
**Solutions**:
1. **Check console for errors**
2. **Verify control reference**:
```javascript
console.log(editor.contentsControl); // Should not be undefined
```
3. **Test search manually**:
```javascript
editor.contentsControl.handleSearch('your query');
```
4. **Clear search**:
```javascript
editor.contentsControl.searchQuery = '';
editor.contentsControl.buildContent();
```
### Duplicate Headings
**Problem**: Multiple headings with same text cause navigation issues
**Solution**: The control auto-generates unique IDs by appending counters:
```
heading-text → heading-text
heading-text → heading-text-1
heading-text → heading-text-2
```
To use custom IDs:
```html
<h2 id="custom-id-1">Same Text</h2>
<h2 id="custom-id-2">Same Text</h2>
```
### Auto-Refresh Not Working
**Problem**: TOC doesn't update when headings change
**Solutions**:
1. **Check if interval is running**:
```javascript
console.log(editor.contentsControl.updateInterval); // Should be a number
```
2. **Restart auto-refresh**:
```javascript
clearInterval(editor.contentsControl.updateInterval);
editor.contentsControl.updateInterval = setInterval(() => {
const currentCount = document.querySelectorAll('h1, h2, h3, h4, h5, h6').length;
if (currentCount !== editor.contentsControl.headings.length) {
editor.contentsControl.refreshContents();
}
}, 5000);
```
3. **Use manual refresh**: Click the "🔄 Refresh Contents" button
---
## Best Practices
### For Writers
1. **Use logical heading hierarchy** - Don't skip levels (h1 → h3)
2. **Keep headings concise** - Long headings clutter the TOC
3. **Use descriptive text** - Helps readers and search functionality
4. **Refresh after major edits** - Ensure TOC stays current
### For Readers
1. **Use search** - Quickly find sections in long documents
2. **Hover for highlights** - See which section each link goes to
3. **Leave panel expanded** - Keep TOC visible for quick navigation
4. **Bookmark important sections** - Use browser bookmarks with heading IDs
### For Developers
1. **Provide heading IDs** - Don't rely on auto-generation for critical links
2. **Test navigation** - Verify smooth scroll works across browsers
3. **Monitor performance** - Disable auto-refresh for very large documents (500+ headings)
4. **Integrate analytics** - Track which sections users visit most
Example analytics integration:
```javascript
const editor = new TestDriveJSUI({ container: '#editor' });
// Track TOC usage
const originalNav = editor.contentsControl.navigateToHeading.bind(editor.contentsControl);
let navCount = 0;
editor.contentsControl.navigateToHeading = function(headingId) {
navCount++;
console.log(`TOC navigation #${navCount} to: ${headingId}`);
// Send to analytics service
if (window.analytics) {
analytics.track('TOC Navigation', {
headingId,
headingText: this.headings.find(h => h.id === headingId)?.text,
timestamp: new Date().toISOString()
});
}
return originalNav(headingId);
};
```
---
## Performance Considerations
### For Large Documents (100+ headings)
**Impact**: Auto-refresh and search may slow down
**Solutions**:
1. **Increase refresh interval**:
```javascript
clearInterval(editor.contentsControl.updateInterval);
editor.contentsControl.updateInterval = setInterval(() => {
// Check logic
}, 15000); // 15 seconds instead of 5
```
2. **Disable auto-refresh**:
```javascript
clearInterval(editor.contentsControl.updateInterval);
editor.contentsControl.updateInterval = null;
```
3. **Lazy rendering** - Only render visible TOC items (not currently implemented)
### Memory Usage
Each heading stores:
- ID string (~20 bytes)
- Text string (~50 bytes)
- Element reference (8 bytes)
- Level + index (8 bytes)
**Estimate**: ~86 bytes per heading
- 100 headings: ~8.6 KB
- 1000 headings: ~86 KB
Negligible for most documents. No memory leaks if control is properly destroyed.
---
## Related Features
- **[Section Editing](section-editing.md)** - Edit headings, triggers TOC refresh
- **[Status Control](status-control.md)** - Shows heading count statistics
- **[Edit Control](edit-control.md)** - Go to line feature (complementary navigation)
---
**See Also**:
- [API Reference](../api/contents-control.md)
- [Examples](../../examples/)
---
**Version**: 1.0.0
**Last Updated**: 2025-12-16