Skip to content

Multi-line Block Behavior (quotes, code blocks) #60

Closed

Description

@malibio

Phase 2.3: Multi-line Block Behavior (quotes, code blocks)

Parent Epic: #54
Depends on: #59

Overview

Implement proper handling of multi-line markdown blocks (blockquotes and code blocks) that span multiple lines within a single node, supporting both traditional multi-line editing and smart conversion to specialized node types.

Context

While headers and bullets convert to separate nodes, blockquotes and code blocks often span multiple lines and should be handled as cohesive content blocks within nodes. This phase adds support for:

  1. Blockquotes (> Line 1\n> Line 2) - Multi-line quoted content
  2. Code blocks (\ncode\n) - Multi-line code content
  3. Proper newline handling within these block types
  4. Future node type support for specialized quote/code nodes

Requirements

Blockquote Support

Single-line Blockquotes

  • Pattern: > This is a quote
  • Behavior: Apply blockquote formatting within node
  • Visual: Left border, indentation, muted color

Multi-line Blockquotes

  • Pattern:
    > This is line one
    > This is line two
    > This continues the quote
    
  • Behavior: Treat as single blockquote block
  • Newline handling: Enter within quote continues quote pattern

Smart Quote Continuation

interface QuoteBlockHandler {
  detectQuoteBlock(content: string, cursorPosition: number): QuoteBlockInfo;
  handleEnterInQuote(content: string, cursorPosition: number): QuoteAction;
  formatQuoteBlock(content: string): FormattedQuote;
}

type QuoteAction = 
  | { type: 'continue-quote'; insertText: '\n> ' }
  | { type: 'end-quote'; insertText: '\n' }
  | { type: 'create-quote-node'; content: string }; // Future enhancement

Code Block Support

Fenced Code Blocks

  • Pattern:
    ```javascript
    function example() {
      return "code";
    }
    ```
    
  • Behavior: Preserve formatting, prevent WYSIWYG processing within
  • Language support: Syntax highlighting (future enhancement)

Code Block Newline Handling

  • Enter within code block adds newline (no markdown processing)
  • Preserve indentation and whitespace
  • Exit code block with proper delimiter handling

Smart Code Block Management

interface CodeBlockHandler {
  detectCodeBlock(content: string, cursorPosition: number): CodeBlockInfo | null;
  handleEnterInCodeBlock(content: string, cursorPosition: number): CodeBlockAction;
  formatCodeBlock(content: string, language?: string): FormattedCodeBlock;
}

type CodeBlockAction = 
  | { type: 'continue-code'; insertText: '\n' }
  | { type: 'end-code-block'; insertText: '\n```\n' }
  | { type: 'create-code-node'; content: string, language?: string }; // Future

Implementation Details

Block Detection Logic

class MultiLineBlockProcessor {
  detectBlockType(content: string, cursorPosition: number): BlockTypeInfo {
    // Check if cursor is within existing block
    const beforeCursor = content.substring(0, cursorPosition);
    const afterCursor = content.substring(cursorPosition);
    
    // Detect blockquote context
    if (this.isWithinBlockquote(beforeCursor, afterCursor)) {
      return { type: 'blockquote', ...this.analyzeQuoteBlock(content, cursorPosition) };
    }
    
    // Detect code block context
    if (this.isWithinCodeBlock(beforeCursor, afterCursor)) {
      return { type: 'codeblock', ...this.analyzeCodeBlock(content, cursorPosition) };
    }
    
    return { type: 'none' };
  }
  
  private isWithinBlockquote(before: string, after: string): boolean {
    // Check if cursor is within a blockquote context
    const lines = before.split('\n');
    const currentLine = lines[lines.length - 1];
    return /^\s*>/.test(currentLine) || this.hasActiveQuoteBlock(lines);
  }
  
  private isWithinCodeBlock(before: string, after: string): boolean {
    // Count backtick fence pairs to determine if inside code block
    const beforeFences = (before.match(/```/g) || []).length;
    return beforeFences % 2 === 1; // Odd number means inside block
  }
}

Keyboard Handler Integration

function handleKeyDown(event: KeyboardEvent) {
  if (event.key === 'Enter') {
    const blockInfo = blockProcessor.detectBlockType(content, getCurrentCursorPosition());
    
    switch (blockInfo.type) {
      case 'blockquote':
        event.preventDefault();
        handleEnterInBlockquote(blockInfo);
        return;
        
      case 'codeblock':
        event.preventDefault();
        handleEnterInCodeBlock(blockInfo);
        return;
        
      default:
        // Normal enter handling or soft newline detection
        break;
    }
  }
  
  // ... existing keyboard handling
}

function handleEnterInBlockquote(blockInfo: BlockTypeInfo) {
  const action = blockProcessor.determineQuoteAction(content, blockInfo);
  
  if (action.type === 'continue-quote') {
    insertTextAtCursor('\n> ');
  } else if (action.type === 'end-quote') {
    insertTextAtCursor('\n');
  }
  // Future: handle quote node creation
}

function handleEnterInCodeBlock(blockInfo: BlockTypeInfo) {
  // Always continue code block with plain newline
  insertTextAtCursor('\n');
  
  // Preserve indentation if applicable
  const currentLine = getCurrentLine(content, blockInfo.cursorPosition);
  const indentation = currentLine.match(/^\s*/)?.[0] || '';
  if (indentation) {
    insertTextAtCursor(indentation);
  }
}

WYSIWYG Integration

// Modify WYSIWYG processor to handle block types
class WYSIWYGProcessor {
  applyFormatting(element: HTMLElement, patterns: MarkdownPattern[]) {
    // ... existing formatting
    
    // Apply blockquote formatting
    this.applyBlockquoteFormatting(element, patterns);
    
    // Apply code block formatting (prevent other formatting within)
    this.applyCodeBlockFormatting(element, patterns);
  }
  
  private applyBlockquoteFormatting(element: HTMLElement, patterns: MarkdownPattern[]) {
    const quotePatterns = patterns.filter(p => p.type === 'blockquote');
    
    quotePatterns.forEach(pattern => {
      const quoteElement = this.createQuoteElement(pattern);
      this.replacePatternInDOM(element, pattern, quoteElement);
    });
  }
  
  private applyCodeBlockFormatting(element: HTMLElement, patterns: MarkdownPattern[]) {
    const codePatterns = patterns.filter(p => p.type === 'codeblock');
    
    codePatterns.forEach(pattern => {
      const codeElement = this.createCodeBlockElement(pattern);
      this.replacePatternInDOM(element, pattern, codeElement);
      
      // Prevent other formatting within code blocks
      this.disableFormattingWithin(codeElement);
    });
  }
}

User Experience Flows

Blockquote Creation and Continuation

  1. User types: > This is a quote
  2. Result: Blockquote formatting applied
  3. User presses Enter
  4. System response: Cursor positioned at \n> for quote continuation
  5. User continues typing or presses Enter again to exit quote

Code Block Creation

  1. User types: ````javascript`
  2. User presses Enter
  3. System response: Enters code block mode, no markdown processing
  4. User types code with preserved formatting
  5. User types: ````
  6. System response: Exits code block mode

Mixed Content Example

Meeting Notes

> Important quote from the discussion
> This continues the same quote
> Final line of the quote

Action items:
- Task 1
- Task 2

Code example:
```javascript
function example() {
  return "demo";
}

Follow up tomorrow.


## Acceptance Criteria

### Blockquote Functionality
- [ ] Single-line blockquotes (`> text`) formatted correctly
- [ ] Multi-line blockquotes maintain consistent formatting
- [ ] Enter within blockquote continues quote with `> ` prefix
- [ ] Empty Enter exits blockquote mode
- [ ] Blockquote visual styling matches design system

### Code Block Functionality
- [ ] Fenced code blocks (````code````) detected and formatted
- [ ] Language specification in code fences supported
- [ ] Enter within code block preserves plain newline
- [ ] Code block prevents other markdown formatting
- [ ] Proper code block exit handling

### Integration Behavior
- [ ] Blockquotes and code blocks work with WYSIWYG processing
- [ ] Multi-line blocks preserved during node operations
- [ ] Copy/paste maintains block formatting
- [ ] Undo/redo preserves block structure

### Edge Cases
- [ ] Nested blockquotes handled appropriately
- [ ] Empty blockquotes/code blocks don't cause errors
- [ ] Malformed block syntax handled gracefully
- [ ] Large multi-line blocks perform well

### Visual Consistency
- [ ] Blockquote styling matches NodeSpace design system
- [ ] Code block monospace font and background applied
- [ ] Block formatting distinguished from regular content
- [ ] Cursor visibility maintained within blocks

## Implementation Notes

### Block State Management
- Track current block context during editing
- Maintain block boundaries during text operations  
- Handle block transitions smoothly

### ContentEditable Considerations
- Prevent ContentEditable from interfering with block formatting
- Manage selection within formatted blocks
- Handle paste operations into blocks appropriately

### Future Node Type Preparation
- Structure block detection for future quote/code node types
- Design for potential block-to-node conversion
- Maintain compatibility with upcoming node type expansions

## Files to Create/Modify

### New Files:
- `src/lib/services/multiLineBlockProcessor.ts` - Core block handling logic
- `src/lib/services/blockquoteHandler.ts` - Blockquote-specific logic
- `src/lib/services/codeBlockHandler.ts` - Code block-specific logic
- `src/lib/services/multiLineBlockProcessor.test.ts` - Unit tests

### Modified Files:
- `src/lib/design/components/BaseNode.svelte` - Block-aware keyboard handling
- `src/lib/services/wysiwygProcessor.ts` - Block formatting integration
- `src/lib/services/markdownPatternDetector.ts` - Multi-line pattern support

## Related Issues

- **Parent Epic**: #54
- **Depends on**: #59
- **Integrates with**: #57
- **Prepares for**: Future specialized node types (quote nodes, code nodes)

---

This multi-line block support completes the core markdown editing experience while preparing the foundation for future specialized node types and advanced content structuring.

🤖 Generated with [Claude Code](https://claude.ai/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