Skip to content

Basic Markdown Pattern Detection (4 block types + 3 inline types) #56

Closed

Description

@malibio

Phase 1.2: Basic Markdown Pattern Detection (4 block types + 3 inline types)

Parent Epic: #54
Depends on: #55

Overview

Implement real-time markdown pattern detection that recognizes 4 essential block types and 3 inline formatting types during typing, setting the foundation for WYSIWYG processing in #57.

Context

With ContentEditable foundation in place (#55), we need intelligent pattern recognition that detects markdown syntax as users type. This creates the data layer that WYSIWYG processing will use to apply visual formatting.

Markdown Patterns to Support

Block Types (4 Essential)

  1. Headers: # H1, ## H2, ### H3, #### H4, ##### H5, ###### H6
  2. Bullet Lists: - item, * item, + item
  3. Blockquotes: > quoted text
  4. Code Blocks: code block

Inline Types (3 Essential)

  1. Bold: **bold text**, __bold text__
  2. Italic: *italic text*, _italic text_
  3. Inline Code: ``code``

Requirements

Technical Requirements

  1. Real-time Pattern Detection

    • Detect patterns as user types (on input events)
    • Maintain cursor position during pattern recognition
    • Handle partial patterns during typing
    • Support pattern removal/editing
  2. Pattern Data Structure

    interface MarkdownPattern {
      type: 'header' | 'bullet' | 'blockquote' | 'codeblock' | 'bold' | 'italic' | 'inlinecode';
      level?: number; // For headers (1-6)
      start: number; // Character position start
      end: number; // Character position end
      syntax: string; // Original syntax (e.g., "##", "**")
      content: string; // Text without syntax
    }
  3. Pattern Recognition Engine

    • Efficient regex-based detection
    • Handle overlapping patterns appropriately
    • Maintain pattern state during edits
    • Export pattern data for WYSIWYG processing

Implementation Details

File Structure:

  • Create: src/lib/services/markdownPatternDetector.ts
  • Modify: src/lib/design/components/BaseNode.svelte (integrate pattern detection)
  • Create: src/lib/types/markdownPatterns.ts (type definitions)

Core Pattern Detection Logic:

class MarkdownPatternDetector {
  detectPatterns(content: string): MarkdownPattern[] {
    const patterns: MarkdownPattern[] = [];
    
    // Block patterns (must be detected first)
    patterns.push(...this.detectHeaders(content));
    patterns.push(...this.detectBullets(content));
    patterns.push(...this.detectBlockquotes(content));
    patterns.push(...this.detectCodeBlocks(content));
    
    // Inline patterns (within blocks)
    patterns.push(...this.detectInlinePatterns(content, patterns));
    
    return patterns;
  }
  
  private detectHeaders(content: string): MarkdownPattern[] {
    // Detect ## Header patterns at line start
  }
  
  private detectBullets(content: string): MarkdownPattern[] {
    // Detect - item patterns at line start
  }
  
  // ... other pattern detection methods
}

Integration with ContentEditable:

<\!-- In BaseNode.svelte -->
<script>
  import { MarkdownPatternDetector } from '$lib/services/markdownPatternDetector';
  
  let patternDetector = new MarkdownPatternDetector();
  let detectedPatterns: MarkdownPattern[] = [];
  
  function handleContentEditableInput(event) {
    content = event.currentTarget.textContent;
    
    // Detect patterns for WYSIWYG processing
    detectedPatterns = patternDetector.detectPatterns(content);
    
    dispatch('contentChanged', { nodeId, content, patterns: detectedPatterns });
  }
</script>

Pattern Detection Requirements

Headers (# Title)

  • Detect 1-6 # characters at line start
  • Must have space after # symbols
  • Extract header level and content text
  • Handle multi-line headers appropriately

Bullet Lists (- item)

  • Detect -, *, + at line start (with optional spaces)
  • Extract bullet type and item content
  • Support nested bullets with indentation
  • Handle empty bullet points

Blockquotes (> text)

  • Detect > at line start
  • Support multi-line blockquotes
  • Handle nested blockquotes (>> text)
  • Extract quoted content properly

Code Blocks (code)

  • Detect triple or quadruple backticks
  • Extract language specification if present
  • Handle multi-line code content
  • Preserve whitespace and formatting

Inline Formatting

  • Bold: **text** and __text__ variants
  • Italic: *text* and _text_ (avoiding bold conflicts)
  • Inline Code: ``code`` with single backticks

Acceptance Criteria

Pattern Detection Accuracy

  • Headers: Correctly detects all 6 levels with proper content extraction
  • Bullets: Detects -, *, + variants at line start
  • Blockquotes: Handles single and multi-line quotes
  • Code blocks: Proper language detection and content preservation
  • Bold: Both **bold** and __bold__ variants
  • Italic: *italic* without conflicting with bold **bold**
  • Inline code: Single backtick ``code`` detection

Real-time Performance

  • Pattern detection on every input event (< 10ms)
  • No cursor position disruption during typing
  • Handles partial patterns during typing (# → ## → ## Header)
  • Efficient updates (only recompute changed sections)

Edge Cases

  • Escaped markdown (\\# should not trigger header)
  • Mixed patterns (bold within headers, etc.)
  • Empty patterns (## with no content)
  • Pattern removal (deleting # converts back to text)
  • Multi-line pattern editing

Data Structure

  • Pattern objects contain accurate start/end positions
  • Content extraction excludes syntax characters
  • Proper type classification for all supported patterns
  • Pattern hierarchy preserved (blocks before inline)

Testing Requirements

  1. Unit Tests - markdownPatternDetector.test.ts

    • Test each pattern type individually
    • Verify edge cases and error handling
    • Test pattern position accuracy
  2. Integration Tests - baseNodePatterns.test.ts

    • Real-time detection during typing
    • ContentEditable integration
    • Event dispatch verification
  3. Performance Tests

    • Large text content pattern detection
    • Rapid typing pattern updates
    • Memory usage during pattern detection

Implementation Notes

Pattern Priority:

  1. Block patterns detected first (establish structure)
  2. Inline patterns within block content
  3. Avoid conflicts between similar patterns

Cursor Position Preservation:

  • Track cursor position before pattern detection
  • Restore cursor after pattern processing
  • Handle cursor position shifts during pattern changes

Future Preparation:

Files to Create/Modify

New Files:

  • src/lib/services/markdownPatternDetector.ts - Core detection logic
  • src/lib/types/markdownPatterns.ts - Type definitions
  • src/lib/services/markdownPatternDetector.test.ts - Unit tests

Modified Files:

  • src/lib/design/components/BaseNode.svelte - Integrate pattern detection
  • src/lib/components/TextNode.svelte - Handle pattern events

Related Issues


This pattern detection foundation enables the WYSIWYG processing that will make typing markdown feel native and intuitive, setting up the smart conversion features in Phase 2.

🤖 Generated with Claude Code

Co-Authored-By: Claude [email protected]

Activity

  1. added
    enhancement
    on Aug 11, 2025
  2. self-assigned this
    on Aug 12, 2025
  3. malibio commented on Aug 16, 2025

    @malibio
    CollaboratorAuthor

    ✅ COMPLETED - Part of Epic #63 which has been successfully implemented. The ContentEditable foundation with smart markdown features is working correctly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

enhancement

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions