Repository navigation
Description
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
patternDetectionconfig - Integration:
TextareaController.detectNodeTypeConversion()usespluginRegistry.detectPatternInContent()
How They Work Together (Currently)
-
User Types Content:
TextareaControllercallsdetectPatterns()on every content changedetectNodeTypeConversion()checks plugin patterns viapluginRegistry.detectPatternInContent()- If pattern matches (e.g.,
#), dispatchesnodeTypeChangedevent
-
User Presses Enter:
CreateNodeCommandusessplitMarkdownContent()to split at cursormarkdown-splitter.tshas hardcoded checks for headers, ordered-list, quote-block- Split result determines
beforeContent,afterContent, and cursor position
-
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.tshas 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.tsexists
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:
- Pattern definitions (from plugins)
- Pattern detection (for node type conversion)
- Content splitting (markdown-aware)
- 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:
-
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; }
-
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 { /* ... */ } }
-
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)
-
Validation: Tests pass, no production code changes yet
Phase 2: Implement Splitting Strategies (PR #2)
Goal: Create strategy classes that replicate existing behavior
Steps:
-
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 }; } }
-
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 }; } }
-
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
- Move
-
Write comprehensive unit tests for each strategy:
- Test against existing
markdown-splittertest cases - Verify exact output match with legacy implementation
- Test edge cases (empty content, position at boundaries, etc.)
- Test against existing
-
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:
-
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); } }
-
Write integration tests:
- Test all node types (header, ordered-list, quote-block, text, task)
- Compare output with legacy
splitMarkdownContent() - Test pattern detection + splitting pipeline
-
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:
-
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 } };
-
DELETE old
patternDetectionfield from all plugins -
Register patterns with
PatternRegistryon plugin initialization -
Write tests: Verify plugin registration populates pattern registry correctly
-
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:
-
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);
-
DELETE
/src/lib/utils/markdown-splitter.tsentirely -
Update all imports across codebase
-
Remove legacy tests (migrate to new test files if needed)
-
Write integration tests:
- Test Enter key behavior for all node types
- Verify cursor positioning matches legacy behavior
- Test edge cases (empty content, position boundaries)
-
Manual testing checklist:
- Headers: Type
# Test, press Enter → splits correctly - Ordered lists: Type
1. Item, press Enter → inherits1. - 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
- Headers: Type
-
Validation: All integration tests pass, manual tests pass
Phase 6: Documentation & Performance (PR #6)
Goal: Document new system and optimize if needed
Steps:
-
Create
/docs/architecture/pattern-system.md:- Explain pattern template system
- Document splitting strategies
- Provide examples for plugin authors
-
Update plugin development guide with pattern template examples
-
Performance testing:
- Benchmark pattern detection vs legacy
- Benchmark splitting vs legacy
- Optimize hot paths if needed
-
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
-
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)
-
Nested Formatting:
- Mixed inline formats:
***bold-italic*** - Nested markers:
**bold *italic* bold** - Overlapping formats:
**bold** and *italic*
- Mixed inline formats:
-
Pattern Priority:
- Multiple patterns match (e.g.,
#for header vs text) - Pattern precedence (block patterns vs inline patterns)
- Conflicting cursor placement rules
- Multiple patterns match (e.g.,
-
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:
CreateNodeCommand(keyboard Enter handling) ✅TextareaController(pattern detection for node type conversion) ✅SharedNodeStore(pattern validation) - No changes neededBaseNodeViewer(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, verify1.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:
-
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)
-
Testability:
- 90%+ code coverage on pattern system
- Unit tests for all strategies
- Integration tests for full pipeline
-
Performance:
- Within 5% of legacy performance (measured via benchmarks)
- No observable UI lag
-
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:
-
WYSIWYG Integration:
- Use pattern templates for WYSIWYG rendering
- Consolidate
MarkdownPatternDetectorwith new system
-
Advanced Splitting Strategies:
- Wrapper split for code blocks
- Table split for future table nodes
- Custom split logic per plugin
-
Pattern Composition:
- Support multiple patterns per node type
- Pattern modifiers (case-insensitive, multiline, etc.)
-
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
refactor(#317): Phases 1-2 - Pattern types, registry, and splitting s…
refactor(#317): Phase 3 - Unified PatternSplitter interface with inte…
refactor(#317): Phase 4 - Register patterns with PatternRegistry from…
docs(#317): Update pattern system documentation with new PatternTempl…
refactor: Migrate CreateNodeCommand to PatternSplitter and delete leg…
fix: Implement all code review recommendations from #317
Refactor: Extract markdown pattern detection and splitting into unifi…
Refactor: Extract markdown pattern detection and splitting into unifi…
Refactor: Extract markdown pattern detection and splitting into unifi…
Refactor: Extract markdown pattern detection and splitting into unifi…