Repository navigation
Description
Problem Statement
The current architecture violates separation of concerns by having header-specific logic scattered across BaseNode and TextareaController - components that should be node-type agnostic.
Code Locations with Architecture Violations
BaseNode (packages/desktop-app/src/lib/design/components/base-node.svelte):
- Lines 943-1019: Header-specific CSS classes (
.node--h1through.node--h6) - Lines 969-1009: CSS variables for header typography and icon positioning
- Line 412:
headerLevelChangedevent in dispatcher (header-specific event) - Line 438:
headerLevelChangedevent handler in controller events
TextareaController (packages/desktop-app/src/lib/design/components/textarea-controller.ts):
- Line 44:
headerLevelChangedevent in interface (header-specific event) - Line 127:
currentHeaderLevelstate tracking (header-specific state) - Lines 760-839: Pattern detection logic that emits
headerLevelChangedevents - Lines 772-776: Header level metadata extraction and event emission
Why This Violates Separation of Concerns
- BaseNode is abstract: It should provide core node functionality without knowing about specific node types like headers
- TextareaController is universal: It manages textarea behavior for ALL node types, not just headers
- HeaderNode exists: We have a dedicated component specifically for header logic - that's where all header code should live
- Plugin system handles detection: Pattern detection is properly abstracted through the plugin registry
Investigation Findings
1. Pattern Detection & Cursor Positioning Flow
Current Flow (Text → Header Conversion)
User types: "### " → Space triggers input event
↓
TextareaController.handleInput() (line 558)
↓
TextareaController.detectPatterns() (line 635)
↓
TextareaController.detectNodeTypeConversion() (line 760)
↓
pluginRegistry.detectPatternInContent() - Pattern matches!
↓
CRITICAL: Capture cursor position BEFORE event (line 782-785)
desiredCursorPosition = config.desiredCursorPosition ?? getCursorPosition()
↓
Emit events using untrack() (lines 803-818):
- headerLevelChanged event (line 806) ❌ SHOULD NOT BE HERE
- nodeTypeConversionDetected event (line 810)
↓
BaseNodeViewer.handleNodeTypeChange() receives event
↓
focusManager.setEditingNodeFromTypeConversion(nodeId, cursorPosition)
Sets cursor type: 'node-type-conversion' with preserved position
↓
nodeManager.updateNodeType(nodeId, 'header')
Component switches: BaseNode → HeaderNode
↓
HeaderNode mounts with autoFocus=true
↓
positionCursor action applies cursor (position-cursor.ts:125-142)
- Focuses textarea
- Sets cursor to preserved position
- Retries after 10ms to handle component switch timing
↓
User is ready to type with cursor at correct position
Critical Cursor Positioning Details:
- Cursor position captured in TextareaController line 782-785
- Position comes from
config.desiredCursorPosition(from plugin) OR current cursor position - For headers: Plugin config doesn't set desiredCursorPosition, so uses current position
- Position preserved through
focusManager.setEditingNodeFromTypeConversion() positionCursoraction handles actual DOM manipulation (lines 125-142)- Retry logic ensures cursor survives component switch
Bidirectional Conversion (Header → Text)
User backspaces to remove "### "
↓
detectNodeTypeConversion() runs again
↓
NO pattern detected (lines 820-838)
↓
Emit nodeTypeConversionDetected with nodeType='text'
↓
Component switches: HeaderNode → BaseNode
↓
Same cursor preservation flow
2. Icon Vertical Alignment System
Current Implementation (DUPLICATION):
BaseNode CSS (lines 943-1009):
.node--h1 {
--font-size: 2rem;
--line-height: 1.2;
--icon-vertical-position: calc(0.25rem + (2rem * 1.2 / 2));
}
/* ...through h6 */HeaderNode CSS (lines 163-233):
.header-h1 {
--font-size: 2rem;
--line-height: 1.2;
--icon-vertical-position: calc(0.25rem + (2rem * 1.2 / 2));
}
/* ...through h6 */Mathematical Formula:
icon-vertical-position = containerPadding + (fontSize × lineHeight / 2)
= 0.25rem + (fontSize × lineHeight / 2)
CSS Variable Inheritance Test:
✅ CSS custom properties inherit through wrapper elements
✅ HeaderNode wrapper sets --icon-vertical-position
✅ BaseNode's .node__indicator uses var(--icon-vertical-position)
✅ This WILL work - BaseNode header CSS is redundant
3. Event Flow Architecture
Current Events (Problematic):
TextareaController emits:
contentChanged✅ Generic - correctheaderLevelChanged❌ Header-specific - violationnodeTypeConversionDetected✅ Generic - correct
BaseNode receives and forwards:
headerLevelChanged❌ Should not know about headers
Should Be:
HeaderNode watches content changes:
(() => {
const newLevel = parseHeaderLevel(content);
if (newLevel !== headerLevel) {
headerLevel = newLevel;
dispatch('headerLevelChanged', { level: newLevel });
}
});4. Reactivity & $effect Blocks
Current Header-Specific Reactivity in TextareaController:
Line 232-233 (VIOLATION):
// Initialize header level tracking
this.currentHeaderLevel = ContentProcessor.getInstance().parseHeaderLevel(content);Lines 772-776 (VIOLATION):
untrack(() => {
if (metadata.headerLevel !== undefined) {
this.events.headerLevelChanged(metadata.headerLevel as number);
}
});Should Be Removed:
currentHeaderLevelstate tracking- Header level metadata extraction in base controller
- All
headerLevelChangedevent emissions
5. Test Coverage Analysis
Existing Tests:
packages/desktop-app/src/tests/components/header-node-pattern-detection.test.ts- 363 lines of comprehensive pattern detection tests
- Tests h1-h6 detection, bidirectional conversion, edge cases
- Tests slash command integration
- These tests MUST continue passing
Key Test Expectations:
// Pattern detection must work (line 71-77)
const result = registry.detectPatternInContent('# Title');
expect(result?.config.targetNodeType).toBe('header');
expect(result?.metadata?.headerLevel).toBe(1);
expect(result?.config.cleanContent).toBe(false); // Keep syntax!
// Cursor positioning during conversion (lines 197-204)
// User types: "## "
// Pattern detected → convert to header
// Cursor must be at position ready to typeProposed Solution
Architecture Overview
┌─────────────────────────────────────────────────────────┐
│ Plugin Registry (Pattern Detection) │
│ - Detects "### " pattern │
│ - Returns: { targetNodeType: 'header', metadata } │
│ - NO header-specific logic in base components │
└─────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────┐
│ TextareaController (Generic) │
│ - Detects patterns via registry │
│ - Emits: nodeTypeConversionDetected (generic event) │
│ - REMOVES: headerLevelChanged event │
│ - REMOVES: currentHeaderLevel state │
└─────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────┐
│ BaseNode (Generic) │
│ - Forwards nodeTypeConversionDetected │
│ - REMOVES: headerLevelChanged event handling │
│ - REMOVES: .node--h1 through .node--h6 CSS │
└─────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────┐
│ HeaderNode (Header-Specific) │
│ - Watches content changes via $effect │
│ - Parses header level from content │
│ - Sets CSS variables for icon positioning │
│ - Emits headerLevelChanged when level changes │
└─────────────────────────────────────────────────────────┘
Step-by-Step Implementation Plan
Phase 1: Remove TextareaController Header Logic
-
Remove state tracking (line 127):
- private currentHeaderLevel: number = 0;
-
Remove event from interface (line 44):
export interface TextareaControllerEvents { contentChanged: (content: string) => void; - headerLevelChanged: (level: number) => void; // ... rest }
-
Remove initialization (lines 232-233):
- this.currentHeaderLevel = ContentProcessor.getInstance().parseHeaderLevel(content);
-
Remove event emission (lines 772-776):
untrack(() => { - if (metadata.headerLevel !== undefined) { - this.events.headerLevelChanged(metadata.headerLevel as number); - } // Keep this part: this.events.nodeTypeConversionDetected({...}); });
Phase 2: Remove BaseNode Header Logic
-
Remove event from dispatcher (line 412):
const dispatch = createEventDispatcher<{ contentChanged: { content: string }; - headerLevelChanged: { level: number }; // ... rest }>();```
-
Remove event handler (line 438):
const controllerEvents: TextareaControllerEvents = { contentChanged: (content: string) => dispatch('contentChanged', { content }), - headerLevelChanged: (level: number) => dispatch('headerLevelChanged', { level }), // ... rest };
-
Remove header CSS classes (lines 943-1019):
- /* Header styling with CSS variables for dynamic positioning */ - /* Shared header class - eliminates code duplication */ - .node--h1, .node--h2, .node--h3, .node--h4, .node--h5, .node--h6 { ... } - /* All header-specific CSS */
Phase 3: Enhance HeaderNode
-
Add content watching $effect (HeaderNode already has this at lines 60-66, verify it works):
<script> let headerLevel = $state(parseHeaderLevel(content)); $effect(() => { const newLevel = parseHeaderLevel(internalContent); if (newLevel !== headerLevel) { headerLevel = newLevel; // This event is for parent components that need to know dispatch('headerLevelChanged', { level: newLevel }); } }); </script>
-
Verify CSS variable inheritance:
- HeaderNode wrapper already sets
--icon-vertical-position(lines 163-233) - BaseNode indicator uses
var(--icon-vertical-position)(line 880) - ✅ This already works - just need to remove BaseNode duplicates
- HeaderNode wrapper already sets
Phase 4: Update BaseNodeViewer Event Handling
-
Remove headerLevelChanged forwarding (check all instances):
<BaseNode {nodeId} on:contentChanged={handleContentChange} - on:headerLevelChanged={handleHeaderLevelChange} on:nodeTypeChanged={handleNodeTypeChange} />
-
HeaderNode events stay the same (it emits headerLevelChanged for its own purposes):
<HeaderNode {nodeId} on:contentChanged={handleContentChange} on:headerLevelChanged={() => { // Header level change is handled automatically through content updates // No special action needed in viewer }} />
Critical Implementation Details
Cursor Positioning Preservation
MUST PRESERVE THIS EXACT BEHAVIOR:
-
Pattern detection captures cursor position (line 782-785):
const cursorPosition = config.desiredCursorPosition !== undefined ? config.desiredCursorPosition : this.getCursorPosition();
-
Position passed in nodeTypeConversionDetected event (line 810-814):
this.events.nodeTypeConversionDetected({ nodeId: this.nodeId, newNodeType: config.targetNodeType, cleanedContent: cleanedContent, cursorPosition: cursorPosition // ← THIS IS CRITICAL });
-
FocusManager preserves position through component switch:
focusManager.setEditingNodeFromTypeConversion(nodeId, cursorPosition);
-
positionCursor action applies it (position-cursor.ts:125-142):
case 'node-type-conversion': controller.focus(); controller.setCursorPosition(data.position); // Retry to handle component switch timing setTimeout(() => { if (textarea.selectionStart !== data.position) { controller.setCursorPosition(data.position); } }, 10);
DO NOT TOUCH THIS FLOW - It's working correctly and is node-type agnostic.
CSS Variable Inheritance Proof
Test to verify icon alignment will work:
-
HeaderNode wrapper sets variables:
.header-h1 { --font-size: 2rem; --line-height: 1.2; --icon-vertical-position: calc(0.25rem + (2rem * 1.2 / 2)); }
-
BaseNode indicator reads variables:
.node__indicator { top: var(--icon-vertical-position); /* ← Inherits from wrapper */ }
-
CSS custom properties inherit through DOM:
<div class="header-h1"> <!-- Sets --icon-vertical-position --> <BaseNode> <!-- Inherits the variable --> <div class="node__indicator" /> <!-- Uses inherited value --> </BaseNode> </div>
✅ This will work - CSS variables inherit by default.
Event Flow Changes
Before:
User types "### " → TextareaController emits headerLevelChanged
→ BaseNode forwards headerLevelChanged
→ HeaderNode receives (but doesn't use it)
After:
User types "### " → TextareaController emits nodeTypeConversionDetected
→ BaseNode forwards nodeTypeConversionDetected
→ BaseNodeViewer switches to HeaderNode
→ HeaderNode detects level via $effect on content
→ HeaderNode emits headerLevelChanged (for parent use)
Risks & Mitigation
Risk 1: Icon Misalignment
Symptom: Header icons positioned incorrectly after removing BaseNode CSS
Cause: CSS variable inheritance failure
Mitigation:
- Test with all header levels (h1-h6)
- Visual regression test: Take screenshots before/after
- Manual test: Create headers, verify icon alignment
Acceptance Criteria: Icons vertically centered on first line for all header levels
Risk 2: Cursor Wrong Position
Symptom: Cursor at beginning of content instead of ready-to-type position
Cause: Breaking cursor preservation flow
Mitigation:
- DO NOT MODIFY lines 782-785 in TextareaController
- DO NOT MODIFY nodeTypeConversionDetected event structure
- DO NOT MODIFY positionCursor action
- Test: Type "### ", space should trigger conversion with cursor after space
Acceptance Criteria: After typing "### " + space, cursor is positioned ready to type heading text
Risk 3: Lost Edit Mode During Conversion
Symptom: Node switches to view mode instead of staying editable
Cause: Focus manager state cleared during component switch
Mitigation:
- Preserve
focusManager.setEditingNodeFromTypeConversion()call - Verify
autoFocusprop passed correctly to HeaderNode - Test: Type pattern, verify textarea stays focused
Acceptance Criteria: After pattern triggers conversion, user can immediately continue typing
Risk 4: Header Level Not Updating
Symptom: Icon size/position doesn't change when typing more/fewer #
Cause: HeaderNode $effect not detecting content changes
Mitigation:
- Verify $effect watches
internalContent(line 61-66 already does this) - Test: Type "## " then add another #, verify h3 styling applied
Acceptance Criteria: Typing "### a" then backspacing to "## a" changes header level from 3 to 2
Risk 5: Bidirectional Conversion Broken
Symptom: Can't convert back to text by removing hashtags
Cause: Pattern detection logic modified incorrectly
Mitigation:
- DO NOT MODIFY lines 820-838 (reverse conversion logic)
- Test: Create header, backspace all hashtags, verify converts to text
Acceptance Criteria: Removing all hashtags converts header back to text node
Testing Strategy
Unit Tests to Verify
✅ Existing tests MUST pass:
packages/desktop-app/src/tests/components/header-node-pattern-detection.test.ts(all 363 lines)- All pattern detection tests (h1-h6, bidirectional, edge cases)
- All slash command integration tests
🔧 Update these tests:
- Remove tests that verify TextareaController emits
headerLevelChanged - Remove tests that verify BaseNode forwards
headerLevelChanged - Add tests that verify HeaderNode emits
headerLevelChangedon content change
Manual Test Scenarios
-
Pattern Detection:
- Type "### " → verify converts to h3, cursor ready to type
- Type "# " → verify converts to h1, cursor ready to type
- Type "###### " → verify converts to h6, cursor ready to type
-
Header Level Changes:
- Type "## Hello"
- Add # to make "### Hello" → verify h3 styling
- Remove # to make "## Hello" → verify h2 styling
-
Bidirectional Conversion:
- Create header "## Title"
- Backspace to remove hashtags → verify converts to text
- Type "## " again → verify converts back to header
-
Icon Alignment:
- Create all header levels (h1-h6)
- Verify icon vertically centered on first line for each
- Take screenshots, compare to current implementation
-
Cursor Positioning:
- Type "### " → verify cursor after space (ready to type)
- NOT at beginning of content
- NOT in view mode (still editing)
Visual Regression Checks
- Screenshot all header levels before changes
- Screenshot all header levels after changes
- Pixel-perfect comparison of icon positioning
- Verify no layout shifts
Acceptance Criteria Checklist
- All existing tests pass
- No
headerLevelChangedreferences in TextareaController - No
headerLevelChangedreferences in BaseNode - No header CSS (
.node--h1etc) in BaseNode - HeaderNode $effect updates header level on content change
- Icon alignment perfect for all header levels (h1-h6)
- Cursor positioned correctly after pattern detection
- Edit mode maintained during node type conversion
- Bidirectional conversion works (header ↔ text)
- Visual regression test passes (screenshots identical)
Implementation Order
Minimize Breakage Strategy:
-
Phase 1: Remove TextareaController logic
- Single file change
- Remove event emission, state tracking
- Tests may fail temporarily
-
Phase 2: Update HeaderNode (if needed)
- Verify $effect already exists (lines 60-66)
- Add any missing header level detection
- Tests should start passing
-
Phase 3: Remove BaseNode logic
- Remove event handling
- Remove CSS classes
- Tests should fully pass
-
Phase 4: Update BaseNodeViewer
- Remove event forwarding
- Clean up any header-specific handling
-
Phase 5: Verification
- Run full test suite
- Manual testing
- Visual regression
- Performance check
Code Examples
Before: TextareaController (VIOLATION)
// Line 44 - Header-specific event
export interface TextareaControllerEvents {
headerLevelChanged: (level: number) => void; // ❌ Should not be here
}
// Line 127 - Header-specific state
private currentHeaderLevel: number = 0; // ❌ Should not be here
// Lines 772-776 - Header-specific logic
untrack(() => {
if (metadata.headerLevel !== undefined) {
this.events.headerLevelChanged(metadata.headerLevel as number); // ❌
}
});After: TextareaController (CLEAN)
// Just generic pattern detection
export interface TextareaControllerEvents {
contentChanged: (content: string) => void;
nodeTypeConversionDetected: (data: {...}) => void; // ✅ Generic
}
// No header-specific state
// Generic pattern handling
untrack(() => {
this.events.nodeTypeConversionDetected({
nodeId: this.nodeId,
newNodeType: config.targetNodeType,
cleanedContent: cleanedContent,
cursorPosition: cursorPosition
}); // ✅ Generic, works for all node types
});Before: BaseNode CSS (DUPLICATION)
/* Lines 943-1019 - Should NOT be in BaseNode */
.node--h1 {
--font-size: 2rem;
--line-height: 1.2;
--icon-vertical-position: calc(0.25rem + (2rem * 1.2 / 2));
}
/* ...through h6 - ALL DUPLICATED */After: HeaderNode CSS (SINGLE SOURCE)
/* Lines 163-233 - Already exists, just remove BaseNode duplicates */
.header-h1 {
--font-size: 2rem;
--line-height: 1.2;
--icon-vertical-position: calc(0.25rem + (2rem * 1.2 / 2));
}
/* ...through h6 - SINGLE SOURCE OF TRUTH */HeaderNode Content Watching (VERIFY EXISTS)
<script>
// Lines 58-66 - This already exists, verify it handles level changes
let headerLevel = $state(parseHeaderLevel(content));
$effect(() => {
const newLevel = parseHeaderLevel(internalContent);
if (newLevel !== headerLevel) {
headerLevel = newLevel;
// Emit for parent components that care about header level
dispatch('headerLevelChanged', { level: newLevel });
}
});
</script>Alternative Approaches Considered
Alternative 1: Keep headerLevelChanged in Base Components
Pros: Less code change
Cons: Violates separation of concerns, sets bad precedent for future node types
Verdict: ❌ Rejected - architecture violation outweighs convenience
Alternative 2: Generic metadataChanged Event
Pros: Could handle any node type metadata generically
Cons: More complex, harder to type-check, still doesn't solve CSS duplication
Verdict: 🤔 Consider for future, but doesn't solve current violations
Alternative 3: Remove HeaderNode, Handle in BaseNode
Pros: Simpler component tree
Cons: Makes BaseNode a god object, violates single responsibility
Verdict: ❌ Rejected - moves in wrong direction
Success Metrics
- ✅ Zero references to "header" in TextareaController
- ✅ Zero references to "header" in BaseNode (except base styling)
- ✅ All existing tests pass
- ✅ Icon alignment pixel-perfect
- ✅ Cursor positioning works correctly
- ✅ Edit mode preserved during conversions
- ✅ Code is more maintainable (single responsibility)
Related Issues
- Migrate to textarea-based editor (Logseq approach) #274: TextareaController implementation (introduced this architecture)
- Implement HeaderNode component with textarea #275: HeaderNode implementation (should have removed base component logic)
- Refactor cursor positioning to reactive action-based architecture #281: FocusManager refactor (cursor positioning system we must preserve)
Implementation Priority: Medium
Estimated Effort: 4-6 hours
Risk Level: Medium (careful testing required)
Architecture Impact: High (improves separation of concerns)
Activity
refactor: Remove header-specific logic from BaseNode and TextareaCont…
fix: Address code review findings from issue #311 refactor
Refactor: Remove header-specific logic from BaseNode and TextareaCont…
refactor: Replace $effect blocks with $derived patterns (Phase 1) (#316)
refactor: Move HeaderNode newline stripping from $effect to event han…
Refactor: Remove header-specific logic from BaseNode and TextareaCont…
refactor: Replace $effect blocks with $derived patterns (Phase 1) (#316)
refactor: Move HeaderNode newline stripping from $effect to event han…
Refactor: Remove header-specific logic from BaseNode and TextareaCont…
refactor: Replace $effect blocks with $derived patterns (Phase 1) (#316)
refactor: Move HeaderNode newline stripping from $effect to event han…
Refactor: Remove header-specific logic from BaseNode and TextareaCont…
refactor: Replace $effect blocks with $derived patterns (Phase 1) (#316)
refactor: Move HeaderNode newline stripping from $effect to event han…