Skip to content

Refactor: Remove header-specific logic from BaseNode and TextareaController #311

Closed

Description

@malibio

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--h1 through .node--h6)
  • Lines 969-1009: CSS variables for header typography and icon positioning
  • Line 412: headerLevelChanged event in dispatcher (header-specific event)
  • Line 438: headerLevelChanged event handler in controller events

TextareaController (packages/desktop-app/src/lib/design/components/textarea-controller.ts):

  • Line 44: headerLevelChanged event in interface (header-specific event)
  • Line 127: currentHeaderLevel state tracking (header-specific state)
  • Lines 760-839: Pattern detection logic that emits headerLevelChanged events
  • Lines 772-776: Header level metadata extraction and event emission

Why This Violates Separation of Concerns

  1. BaseNode is abstract: It should provide core node functionality without knowing about specific node types like headers
  2. TextareaController is universal: It manages textarea behavior for ALL node types, not just headers
  3. HeaderNode exists: We have a dedicated component specifically for header logic - that's where all header code should live
  4. 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()
  • positionCursor action 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 - correct
  • headerLevelChanged ❌ Header-specific - violation
  • nodeTypeConversionDetected ✅ 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:

  • currentHeaderLevel state tracking
  • Header level metadata extraction in base controller
  • All headerLevelChanged event 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 type

Proposed 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

  1. Remove state tracking (line 127):

    - private currentHeaderLevel: number = 0;
  2. Remove event from interface (line 44):

    export interface TextareaControllerEvents {
      contentChanged: (content: string) => void;
    - headerLevelChanged: (level: number) => void;
      // ... rest
    }
  3. Remove initialization (lines 232-233):

    - this.currentHeaderLevel = ContentProcessor.getInstance().parseHeaderLevel(content);
  4. 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

  1. Remove event from dispatcher (line 412):

    const dispatch = createEventDispatcher<{
      contentChanged: { content: string };
    - headerLevelChanged: { level: number };
      // ... rest
    }>();```
  2. Remove event handler (line 438):

    const controllerEvents: TextareaControllerEvents = {
      contentChanged: (content: string) => dispatch('contentChanged', { content }),
    - headerLevelChanged: (level: number) => dispatch('headerLevelChanged', { level }),
      // ... rest
    };
  3. 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

  1. 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>
  2. 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

Phase 4: Update BaseNodeViewer Event Handling

  1. Remove headerLevelChanged forwarding (check all instances):

    <BaseNode
      {nodeId}
      on:contentChanged={handleContentChange}
    - on:headerLevelChanged={handleHeaderLevelChange}
      on:nodeTypeChanged={handleNodeTypeChange}
    />
  2. 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:

  1. Pattern detection captures cursor position (line 782-785):

    const cursorPosition =
      config.desiredCursorPosition !== undefined
        ? config.desiredCursorPosition
        : this.getCursorPosition();
  2. Position passed in nodeTypeConversionDetected event (line 810-814):

    this.events.nodeTypeConversionDetected({
      nodeId: this.nodeId,
      newNodeType: config.targetNodeType,
      cleanedContent: cleanedContent,
      cursorPosition: cursorPosition // ← THIS IS CRITICAL
    });
  3. FocusManager preserves position through component switch:

    focusManager.setEditingNodeFromTypeConversion(nodeId, cursorPosition);
  4. 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:

  1. HeaderNode wrapper sets variables:

    .header-h1 {
      --font-size: 2rem;
      --line-height: 1.2;
      --icon-vertical-position: calc(0.25rem + (2rem * 1.2 / 2));
    }
  2. BaseNode indicator reads variables:

    .node__indicator {
      top: var(--icon-vertical-position); /* ← Inherits from wrapper */
    }
  3. 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 autoFocus prop 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 headerLevelChanged on content change

Manual Test Scenarios

  1. 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
  2. Header Level Changes:

    • Type "## Hello"
    • Add # to make "### Hello" → verify h3 styling
    • Remove # to make "## Hello" → verify h2 styling
  3. Bidirectional Conversion:

    • Create header "## Title"
    • Backspace to remove hashtags → verify converts to text
    • Type "## " again → verify converts back to header
  4. Icon Alignment:

    • Create all header levels (h1-h6)
    • Verify icon vertically centered on first line for each
    • Take screenshots, compare to current implementation
  5. 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 headerLevelChanged references in TextareaController
  • No headerLevelChanged references in BaseNode
  • No header CSS (.node--h1 etc) 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:

  1. Phase 1: Remove TextareaController logic

    • Single file change
    • Remove event emission, state tracking
    • Tests may fail temporarily
  2. Phase 2: Update HeaderNode (if needed)

    • Verify $effect already exists (lines 60-66)
    • Add any missing header level detection
    • Tests should start passing
  3. Phase 3: Remove BaseNode logic

    • Remove event handling
    • Remove CSS classes
    • Tests should fully pass
  4. Phase 4: Update BaseNodeViewer

    • Remove event forwarding
    • Clean up any header-specific handling
  5. 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


Implementation Priority: Medium
Estimated Effort: 4-6 hours
Risk Level: Medium (careful testing required)
Architecture Impact: High (improves separation of concerns)

Activity

  1. self-assigned this
    on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions