Skip to content

Refactor: Extract markdown pattern detection and splitting into unified system #317

Closed

Description

@malibio

Context & Background

The markdown splitting and pattern detection systems are currently spread across multiple files with overlapping responsibilities:

Current Architecture

Markdown Splitter (/packages/desktop-app/src/lib/utils/markdown-splitter.ts):

  • Responsibilities: Splits content at cursor position while preserving markdown formatting
  • Handles: Headers, ordered lists, quote blocks, inline formatting (bold, italic, strikethrough, code)
  • Pattern Detection: Hardcoded regex patterns for each node type (headers, ordered-list, quote-block)
  • Splitting Logic: Custom logic for each pattern type with special cases

Pattern Detection System (/packages/desktop-app/src/lib/services/markdown-pattern-detector.ts):

  • Responsibilities: Detects markdown patterns for WYSIWYG rendering
  • Handles: Headers, bullets, blockquotes, code blocks, bold, italic, inline code
  • Pattern Detection: Separate regex patterns (block vs inline)
  • Usage: Currently used for WYSIWYG transformations, NOT for node type conversions

Plugin System Pattern Detection (/packages/desktop-app/src/lib/plugins/core-plugins.ts):

  • Responsibilities: Pattern-based node type auto-conversion (e.g., typing # converts to header)
  • Handles: Headers, tasks, code blocks, quote blocks, ordered lists
  • Pattern Detection: Each plugin defines its own patternDetection config
  • Integration: TextareaController.detectNodeTypeConversion() uses pluginRegistry.detectPatternInContent()

How They Work Together (Currently)

  1. User Types Content:

    • TextareaController calls detectPatterns() on every content change
    • detectNodeTypeConversion() checks plugin patterns via pluginRegistry.detectPatternInContent()
    • If pattern matches (e.g., # ), dispatches nodeTypeChanged event
  2. User Presses Enter:

    • CreateNodeCommand uses splitMarkdownContent() to split at cursor
    • markdown-splitter.ts has hardcoded checks for headers, ordered-list, quote-block
    • Split result determines beforeContent, afterContent, and cursor position
  3. Rendering:

    • MarkdownPatternDetector (separate service) detects patterns for WYSIWYG display
    • Currently NOT integrated with splitting or node type conversion

Problems to Solve

1. Code Duplication

  • Pattern Definitions: Same patterns defined in 3 places:
    • markdown-splitter.ts: /^(#{1,6}\s+)/ (header detection)
    • core-plugins.ts: /^(#{1,6})\s/ (pattern detection config)
    • markdown-pattern-detector.ts: /^(#{1,6})\s+(.+)$/gm (WYSIWYG rendering)
  • Maintenance Burden: Adding new node type requires updating 3+ files
  • Consistency Risk: Patterns can drift out of sync

2. Tight Coupling

  • Hardcoded Logic: markdown-splitter.ts has hardcoded checks for specific node types:
    // Line 197-243: Header-specific logic
    const headerMatch = content.match(/^(#{1,6}\s+)/);
    if (headerMatch) { /* 45 lines of header-specific logic */ }
    
    // Line 245-268: Ordered-list-specific logic  
    const orderedListMatch = content.match(/^(1\.\s+)/);
    if (orderedListMatch) { /* 23 lines of list-specific logic */ }
    
    // Line 270-293: Quote-block-specific logic
    const quoteBlockMatch = content.match(/^(>\s+)/);
    if (quoteBlockMatch) { /* 23 lines of quote-specific logic */ }
  • Extensibility: Adding new node types requires modifying core splitter logic
  • Plugin System Disconnect: Plugin patterns aren't used for splitting

3. Testability Issues

  • Integration Tests Only: Most tests are integration tests that test entire workflows
  • No Unit Tests: Core splitting logic not tested in isolation
  • Pattern Coverage: No tests for pattern detection edge cases
  • Missing Test File: No markdown-splitter.test.ts exists

4. Complexity & Maintainability

  • Long Functions: splitMarkdownContent() is 148 lines with nested conditionals
  • Overlapping Concerns: Pattern detection mixed with cursor positioning logic
  • State Management: Multiple derived values (openMarkers, closeMarkers, etc.)
  • Cognitive Load: Hard to understand flow without reading entire file

5. Missing Abstractions

  • No Pattern Template System: Each pattern type has bespoke logic
  • No Splitter Strategy: All splitting logic in one monolithic function
  • No Pattern Metadata: Can't describe pattern behavior declaratively

Proposed Solution

High-Level Architecture

Create a unified pattern system that consolidates:

  1. Pattern definitions (from plugins)
  2. Pattern detection (for node type conversion)
  3. Content splitting (markdown-aware)
  4. WYSIWYG rendering (future integration)

Pattern Template System

Introduce a declarative pattern template that each plugin defines:

interface PatternTemplate {
  // Identification
  regex: RegExp;
  nodeType: string;
  priority: number;
  
  // Splitting behavior
  splittingStrategy: 'prefix-inheritance' | 'simple-split' | 'wrapper-split';
  prefixToInherit?: string;  // e.g., "# ", "1. ", "> "
  
  // Cursor positioning
  cursorPlacement: 'after-prefix' | 'start' | 'end';
  
  // Content transformation
  cleanContent?: boolean;
  contentTemplate?: string;
  
  // Metadata extraction
  extractMetadata?: (match: RegExpMatchArray) => Record<string, unknown>;
}

Splitting Strategies

Three well-defined strategies replace hardcoded logic:

1. Prefix Inheritance (headers, ordered-list, quote-block)

{
  splittingStrategy: 'prefix-inheritance',
  prefixToInherit: '# ',  // Inherited on new line
  cursorPlacement: 'after-prefix',
  behavior: {
    atStart: 'create-empty-above',  // Cursor at |# → empty node above
    withinPrefix: 'create-empty-above',  // Cursor at #| → empty node above  
    afterPrefix: 'split-and-inherit'  // Cursor at # |text → split with prefix
  }
}

2. Simple Split (text, tasks)

{
  splittingStrategy: 'simple-split',
  cursorPlacement: 'start',
  behavior: {
    preserveInlineFormatting: true  // Preserve **bold**, *italic*, etc.
  }
}

3. Wrapper Split (code blocks - future)

{
  splittingStrategy: 'wrapper-split',
  openWrapper: '```',
  closeWrapper: '```',
  cursorPlacement: 'inside',
  behavior: {
    completeWrappers: true  // Auto-add closing wrapper if missing
  }
}

Proposed File Structure

src/lib/
├── patterns/
│   ├── types.ts                    # Pattern template types
│   ├── registry.ts                 # Pattern registry (singleton)
│   ├── detector.ts                 # Pattern detection logic
│   ├── splitter/
│   │   ├── index.ts                # Main splitter interface
│   │   ├── strategies/
│   │   │   ├── prefix-inheritance.ts
│   │   │   ├── simple-split.ts
│   │   │   └── wrapper-split.ts
│   │   └── inline-formatting.ts    # Inline format preservation
│   └── markdown-context.ts         # Markdown state analysis (extracted)
├── plugins/
│   └── core-plugins.ts             # Update to use pattern templates
└── utils/
    └── markdown-splitter.ts        # DELETE in Phase 5

Implementation Steps

SIMPLIFIED FOR EARLY-STAGE PROJECT: No backwards compatibility needed since we're in active development with no external users.

Phase 1: Extract Pattern Types & Registry (PR #1)

Goal: Create pattern template system without breaking existing code

Steps:

  1. Create /src/lib/patterns/types.ts:

    export interface PatternTemplate {
      regex: RegExp;
      nodeType: string;
      priority: number;
      splittingStrategy: 'prefix-inheritance' | 'simple-split' | 'wrapper-split';
      // ... rest of interface
    }
    
    export interface SplitResult {
      beforeContent: string;
      afterContent: string;
      newNodeCursorPosition: number;
    }
  2. Create /src/lib/patterns/registry.ts:

    export class PatternRegistry {
      private static instance: PatternRegistry;
      private patterns = new Map<string, PatternTemplate>();
      
      register(pattern: PatternTemplate): void { /* ... */ }
      getPattern(nodeType: string): PatternTemplate | undefined { /* ... */ }
      detectPattern(content: string): PatternTemplate | null { /* ... */ }
    }
  3. Write comprehensive unit tests for registry:

    • Pattern registration
    • Pattern retrieval by node type
    • Pattern detection with priority ordering
    • Edge cases (multiple patterns match, no patterns match)
  4. Validation: Tests pass, no production code changes yet

Phase 2: Implement Splitting Strategies (PR #2)

Goal: Create strategy classes that replicate existing behavior

Steps:

  1. Create /src/lib/patterns/splitter/strategies/prefix-inheritance.ts:

    export class PrefixInheritanceStrategy implements SplittingStrategy {
      split(content: string, position: number, pattern: PatternTemplate): SplitResult {
        // Extract logic from markdown-splitter.ts lines 197-293
        // Generalize for any prefix (not just headers/lists/quotes)
        const prefix = pattern.prefixToInherit;
        const prefixLength = prefix.length;
        
        // Behavior: at start or within prefix → create empty above
        if (position <= prefixLength) {
          return {
            beforeContent: prefix,
            afterContent: content,
            newNodeCursorPosition: prefixLength
          };
        }
        
        // Behavior: after prefix → split and inherit
        const beforeCursor = content.substring(0, position);
        const afterCursor = content.substring(position);
        return {
          beforeContent: beforeCursor,
          afterContent: prefix + afterCursor,
          newNodeCursorPosition: prefixLength
        };
      }
    }
  2. Create /src/lib/patterns/splitter/strategies/simple-split.ts:

    export class SimpleSplitStrategy implements SplittingStrategy {
      split(content: string, position: number, pattern: PatternTemplate): SplitResult {
        // Extract inline formatting logic from markdown-splitter.ts lines 313-343
        const context = analyzeMarkdownContext(content, position);
        
        if (!hasActiveFormatting(context)) {
          // Simple split, no formatting
          return {
            beforeContent: content.substring(0, position),
            afterContent: content.substring(position),
            newNodeCursorPosition: 0
          };
        }
        
        // Preserve inline formatting
        const closingMarkers = getClosingMarkers(context);
        const openingMarkers = getOpeningMarkers(context);
        
        return {
          beforeContent: content.substring(0, position) + closingMarkers,
          afterContent: openingMarkers + content.substring(position),
          newNodeCursorPosition: openingMarkers.length
        };
      }
    }
  3. Extract /src/lib/patterns/markdown-context.ts:

    • Move analyzeMarkdownContext() (lines 28-124)
    • Move getClosingMarkers() (lines 129-159)
    • Move getOpeningMarkers() (lines 164-191)
    • Add comprehensive unit tests for edge cases
  4. Write comprehensive unit tests for each strategy:

    • Test against existing markdown-splitter test cases
    • Verify exact output match with legacy implementation
    • Test edge cases (empty content, position at boundaries, etc.)
  5. Validation: All tests pass, strategies replicate existing behavior

Phase 3: Create Unified Splitter Interface (PR #3)

Goal: Create new splitter that uses strategies internally

Steps:

  1. Create /src/lib/patterns/splitter/index.ts:

    export class PatternSplitter {
      private strategies = new Map<string, SplittingStrategy>();
      
      constructor(private registry: PatternRegistry) {
        this.strategies.set('prefix-inheritance', new PrefixInheritanceStrategy());
        this.strategies.set('simple-split', new SimpleSplitStrategy());
      }
      
      split(content: string, position: number, nodeType: string): SplitResult {
        // Detect pattern for current node type
        const pattern = this.registry.getPattern(nodeType);
        
        if (!pattern) {
          // Fallback to simple split
          return simpleSplit(content, position);
        }
        
        // Use appropriate strategy
        const strategy = this.strategies.get(pattern.splittingStrategy);
        if (!strategy) {
          throw new Error(`Unknown strategy: ${pattern.splittingStrategy}`);
        }
        
        return strategy.split(content, position, pattern);
      }
    }
  2. Write integration tests:

    • Test all node types (header, ordered-list, quote-block, text, task)
    • Compare output with legacy splitMarkdownContent()
    • Test pattern detection + splitting pipeline
  3. Validation: Integration tests pass, output matches legacy implementation

Phase 4: Update Plugin Definitions (PR #4)

Goal: Replace plugin pattern configs with new template format

Steps:

  1. Update /src/lib/plugins/core-plugins.ts:

    export const headerNodePlugin: PluginDefinition = {
      // ... existing config ...
      // REPLACE patternDetection with patternTemplate
      patternTemplate: {
        regex: /^(#{1,6})\s/,
        nodeType: 'header',
        priority: 10,
        splittingStrategy: 'prefix-inheritance',
        prefixToInherit: '# ',  // Dynamic based on match
        cursorPlacement: 'after-prefix',
        cleanContent: false,
        extractMetadata: (match) => ({
          headerLevel: match[1].length
        })
      }
    };
    
    export const orderedListNodePlugin: PluginDefinition = {
      // ... existing config ...
      patternTemplate: {
        regex: /^1\.\s/,
        nodeType: 'ordered-list',
        priority: 10,
        splittingStrategy: 'prefix-inheritance',
        prefixToInherit: '1. ',
        cursorPlacement: 'after-prefix',
        cleanContent: false
      }
    };
  2. DELETE old patternDetection field from all plugins

  3. Register patterns with PatternRegistry on plugin initialization

  4. Write tests: Verify plugin registration populates pattern registry correctly

  5. Validation: Plugin system still works, patterns registered

Phase 5: Migrate CreateNodeCommand & Delete Legacy (PR #5)

Goal: Switch to new system and remove old code

Steps:

  1. Update /src/lib/commands/keyboard/create-node.command.ts:

    // OLD - DELETE:
    const splitResult = splitMarkdownContent(currentContent, cursorPosition);
    
    // NEW:
    const splitter = PatternSplitter.getInstance();
    const splitResult = splitter.split(currentContent, cursorPosition, context.nodeType);
  2. DELETE /src/lib/utils/markdown-splitter.ts entirely

  3. Update all imports across codebase

  4. Remove legacy tests (migrate to new test files if needed)

  5. Write integration tests:

    • Test Enter key behavior for all node types
    • Verify cursor positioning matches legacy behavior
    • Test edge cases (empty content, position boundaries)
  6. Manual testing checklist:

    • Headers: Type # Test, press Enter → splits correctly
    • Ordered lists: Type 1. Item, press Enter → inherits 1.
    • Quote blocks: Type > Quote, press Enter → inherits >
    • Text nodes: Type **bold**, press Enter mid-word → preserves formatting
    • Tasks: Type [ ] Task, press Enter → creates new task
  7. Validation: All integration tests pass, manual tests pass

Phase 6: Documentation & Performance (PR #6)

Goal: Document new system and optimize if needed

Steps:

  1. Create /docs/architecture/pattern-system.md:

    • Explain pattern template system
    • Document splitting strategies
    • Provide examples for plugin authors
  2. Update plugin development guide with pattern template examples

  3. Performance testing:

    • Benchmark pattern detection vs legacy
    • Benchmark splitting vs legacy
    • Optimize hot paths if needed
  4. Add JSDoc comments to all public APIs

Acceptance Criteria

Functional Requirements

  • All existing splitting behavior preserved (headers, ordered-list, quote-block, text, inline formatting)
  • Pattern detection integrated with plugin system (no separate pattern definitions)
  • New node types can be added without modifying core splitter logic
  • Cursor positioning matches legacy behavior exactly

Code Quality Requirements

  • Pattern templates defined declaratively in plugins
  • Splitting strategies isolated in separate classes
  • No code duplication between pattern detection and splitting
  • All public APIs have TypeScript types and JSDoc comments

Testing Requirements

  • Unit tests for pattern registry (registration, retrieval, detection)
  • Unit tests for each splitting strategy (prefix-inheritance, simple-split)
  • Unit tests for markdown context analysis (inline formatting)
  • Integration tests for splitter + pattern detection pipeline
  • All legacy test cases migrated and passing
  • Minimum 90% code coverage for new pattern system code

Performance Requirements

  • Pattern detection performance within 5% of legacy implementation
  • Splitting performance within 5% of legacy implementation
  • No observable UI lag during typing or Enter key press
  • Benchmark tests included for critical paths

Documentation Requirements

  • Architecture documentation explaining pattern system design
  • Plugin development guide updated with pattern template examples
  • JSDoc comments on all public APIs

Technical Considerations

Edge Cases to Handle

  1. Cursor Positioning:

    • Position at start of content (position = 0)
    • Position at end of content (position = content.length)
    • Position within markdown syntax (e.g., |#, #|, # |)
    • Position within inline formatting (e.g., bol|d)
  2. Nested Formatting:

    • Mixed inline formats: ***bold-italic***
    • Nested markers: **bold *italic* bold**
    • Overlapping formats: **bold** and *italic*
  3. Pattern Priority:

    • Multiple patterns match (e.g., # for header vs text)
    • Pattern precedence (block patterns vs inline patterns)
    • Conflicting cursor placement rules
  4. Content Variations:

    • Empty content
    • Whitespace-only content
    • Multiline content (Shift+Enter in text nodes)
    • Content with escaped markdown (e.g., \#)

Integration Points

Systems that use pattern detection/splitting:

  1. CreateNodeCommand (keyboard Enter handling) ✅
  2. TextareaController (pattern detection for node type conversion) ✅
  3. SharedNodeStore (pattern validation) - No changes needed
  4. BaseNodeViewer (content rendering) - No changes needed

Future Integration:

  • WYSIWYG rendering system (Phase 8, separate issue)
  • Markdown import/export (use pattern templates for parsing)

Performance Considerations

Hot Paths:

  • Pattern detection on every keystroke (currently TextareaController.detectPatterns())
  • Content splitting on every Enter key press (currently CreateNodeCommand)

Optimization Strategies:

  • Cache compiled regex patterns
  • Debounce pattern detection (if not already debounced)
  • Use early returns to skip expensive checks
  • Consider memoization for repeated pattern matches

Performance Testing:

// Benchmark pattern detection
const iterations = 10000;
const content = '# This is a header with some content';

console.time('Legacy pattern detection');
for (let i = 0; i < iterations; i++) {
  const headerMatch = content.match(/^(#{1,6}\s+)/);
}
console.timeEnd('Legacy pattern detection');

console.time('New pattern detection');
for (let i = 0; i < iterations; i++) {
  const pattern = patternRegistry.detectPattern(content);
}
console.timeEnd('New pattern detection');

Testing Strategy

Unit Tests (New Files)

Create comprehensive unit tests for each component:

/src/tests/patterns/registry.test.ts:

describe('PatternRegistry', () => {
  it('should register pattern with unique node type', () => { /* ... */ });
  it('should retrieve pattern by node type', () => { /* ... */ });
  it('should detect pattern in content', () => { /* ... */ });
  it('should respect pattern priority when multiple match', () => { /* ... */ });
  it('should return null when no patterns match', () => { /* ... */ });
});

/src/tests/patterns/splitter/prefix-inheritance.test.ts:

describe('PrefixInheritanceStrategy', () => {
  describe('Header splitting', () => {
    it('should create empty node above when cursor at start', () => { /* ... */ });
    it('should create empty node above when cursor within syntax', () => { /* ... */ });
    it('should split and inherit prefix when cursor after syntax', () => { /* ... */ });
  });
  
  describe('Ordered list splitting', () => { /* ... */ });
  describe('Quote block splitting', () => { /* ... */ });
});

/src/tests/patterns/splitter/simple-split.test.ts:

describe('SimpleSplitStrategy', () => {
  it('should split content without formatting', () => { /* ... */ });
  it('should preserve bold formatting on both sides', () => { /* ... */ });
  it('should preserve italic formatting on both sides', () => { /* ... */ });
  it('should preserve code formatting on both sides', () => { /* ... */ });
  it('should preserve mixed formatting', () => { /* ... */ });
});

/src/tests/patterns/markdown-context.test.ts:

describe('analyzeMarkdownContext', () => {
  it('should detect bold formatting', () => { /* ... */ });
  it('should detect nested formatting', () => { /* ... */ });
  it('should track opening and closing markers', () => { /* ... */ });
  it('should handle code blocks correctly', () => { /* ... */ });
});

Integration Tests (Updated Files)

Update existing integration tests to use new system:

/src/tests/integration/create-node-splitting.test.ts (new file):

describe('CreateNodeCommand with Pattern Splitter', () => {
  it('should split header content correctly on Enter', () => { /* ... */ });
  it('should split ordered list content correctly on Enter', () => { /* ... */ });
  it('should split text with inline formatting correctly', () => { /* ... */ });
  // ... migrate tests from existing files
});

Manual Testing Checklist

Before merging Phase 5, perform manual testing:

  • Create header node (# Test), press Enter at different positions
  • Create ordered list (1. Item), press Enter, verify 1. inherited
  • Create quote block (> Quote), press Enter, verify > inherited
  • Type text with bold (**bold**), press Enter mid-word, verify formatting preserved
  • Type text with italic (*italic*), press Enter mid-word, verify formatting preserved
  • Type text with code (`code`), press Enter mid-word, verify formatting preserved
  • Create task ([ ] Task), press Enter, verify new task created
  • Test edge cases: Enter at start, Enter at end, Enter in empty node

Implementation Timeline

Estimated Effort: ~2-3 days (for junior engineer)

  • Phase 1: 3-4 hours (types + registry + tests)
  • Phase 2: 5-6 hours (strategies + tests)
  • Phase 3: 2-3 hours (unified splitter + tests)
  • Phase 4: 1-2 hours (plugin updates + tests)
  • Phase 5: 3-4 hours (migration + deletion + integration tests + manual QA)
  • Phase 6: 3-4 hours (documentation + performance testing)

Recommended Pace: 1-2 PRs per day with code review

Success Metrics

After completion, we should achieve:

  1. Maintainability:

    • Adding new node type requires updating only plugin definition (1 file)
    • Pattern logic consolidated in ~5 small, focused files vs current ~1 large file
    • Clear separation of concerns (detection, splitting, strategies)
  2. Testability:

    • 90%+ code coverage on pattern system
    • Unit tests for all strategies
    • Integration tests for full pipeline
  3. Performance:

    • Within 5% of legacy performance (measured via benchmarks)
    • No observable UI lag
  4. Developer Experience:

    • Clear documentation for plugin authors
    • Type-safe pattern templates
    • Easy to understand strategy system

Future Enhancements (Out of Scope)

These improvements can be tackled in separate issues after the refactor:

  1. WYSIWYG Integration:

    • Use pattern templates for WYSIWYG rendering
    • Consolidate MarkdownPatternDetector with new system
  2. Advanced Splitting Strategies:

    • Wrapper split for code blocks
    • Table split for future table nodes
    • Custom split logic per plugin
  3. Pattern Composition:

    • Support multiple patterns per node type
    • Pattern modifiers (case-insensitive, multiline, etc.)
  4. Performance Optimization:

    • Lazy pattern compilation
    • Pattern caching for hot paths
    • Incremental pattern matching

References

Related Code:

  • /packages/desktop-app/src/lib/utils/markdown-splitter.ts (current implementation)
  • /packages/desktop-app/src/lib/services/markdown-pattern-detector.ts (WYSIWYG patterns)
  • /packages/desktop-app/src/lib/plugins/core-plugins.ts (plugin pattern configs)
  • /packages/desktop-app/src/lib/commands/keyboard/create-node.command.ts (usage site)

Related Tests:

  • /packages/desktop-app/src/tests/utils/inline-formatting-split.test.ts
  • /packages/desktop-app/src/tests/utils/header-cursor-split.test.ts
  • /packages/desktop-app/src/tests/services/header-inheritance.test.ts

Documentation:

  • /docs/architecture/component-architecture-guide.md (component patterns)
  • /docs/architecture/frontend-architecture.md (overall frontend design)

Activity

  1. self-assigned this
    on Oct 21, 2025
  2. added 6 commits that reference this issue on Oct 22, 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