Skip to content

Refactor Keyboard Event Handling with Command Pattern #94

Closed

Description

@malibio

Overview

Based on architectural analysis and extensive debugging, the keyboard handling system needs refactoring to improve maintainability and extensibility. This issue implements a complete Command Pattern refactoring for all keyboard operations.

Background

The current keyboard handling is distributed across multiple components:

  • ContentEditableController: Handles raw keyboard events and text manipulation
  • BaseNode.svelte: Manages component-level event routing
  • BaseNodeViewer.svelte: Processes node creation/modification events

While functional, this approach has maintenance challenges as the system scales and we add more keyboard shortcuts.

Proposed Solution: Command Pattern Implementation

Architecture Decision: Separate KeyboardCommandRegistry Service

Implement a separate service (Option B) following the existing SlashCommandService pattern:

// keyboard-command-registry.ts
interface KeyboardCommand {
  execute(context: KeyboardContext): Promise<boolean>;
  canExecute(context: KeyboardContext): boolean;
  description: string;
}

class KeyboardCommandRegistry {
  private static instance: KeyboardCommandRegistry;
  private commands = new Map<string, KeyboardCommand>();
  
  static getInstance(): KeyboardCommandRegistry { ... }
  register(key: string, command: KeyboardCommand): void { ... }
  execute(key: string, context: KeyboardContext): Promise<boolean> { ... }
}

Why separate service?

  • ✅ Consistency with existing SlashCommandService pattern
  • ✅ Better testability (commands tested in isolation)
  • ✅ Future plugin support (plugins can register custom keyboard shortcuts)
  • ✅ Separation of concerns (ContentEditableController stays focused on DOM)

KeyboardContext Interface

interface KeyboardContext {
  event: KeyboardEvent;
  controller: ContentEditableController;
  currentNode: Node;
  cursorPosition: number;
  selection: Selection | null;
  // Additional context as needed
}

Implementation Plan

Phase 1: Command Infrastructure (Week 1)

  • Create KeyboardCommand interface and KeyboardContext type
  • Implement KeyboardCommandRegistry service (singleton pattern)
  • Add unit tests for registry (registration, execution, context building)
  • Integrate with ContentEditableController (parallel execution with fallback)
  • Add centralized error handling and logging

Parallel Execution Strategy:

async handleKeyPress(event: KeyboardEvent) {
  const context = this.buildContext(event);
  
  // Try new command pattern first
  const handled = await KeyboardCommandRegistry.getInstance().execute(event.key, context);
  
  // Fall back to old code if command not implemented yet
  if (!handled) {
    this.handleKeyPressOldWay(event);
  }
}

Phase 2: Core Commands (Week 1-2)

  • CreateNodeCommand - Enter key functionality
    • Unit tests: node creation, content splitting, cursor positioning
    • Integration tests: with ContentEditableController
  • IndentNodeCommand - Tab key functionality
    • Unit tests: hierarchy changes, validation
    • Integration tests: multi-node indentation
  • OutdentNodeCommand - Shift+Tab functionality
    • Unit tests: hierarchy changes, root-level handling
    • Integration tests: multi-level outdentation
  • MergeNodesCommand - Unified Backspace/Delete functionality
    • Architecture Note: Single command with direction parameter
    • new MergeNodesCommand('up') for Backspace (merge with above)
    • new MergeNodesCommand('down') for Delete (merge with below)
    • Unit tests: both directions, edge cases (first/last node)
    • Integration tests: content preservation, cursor positioning

Phase 3: Advanced Commands (Week 2-3)

  • NavigateUpCommand / NavigateDownCommand - Arrow key navigation
    • Unit tests: focus management, boundary handling
    • Integration tests: multi-node navigation workflows
  • FormatTextCommand - Cmd+B/I/U formatting
    • Unit tests: markdown syntax insertion, selection handling
    • Integration tests: with content processor
  • Custom shortcuts as needed (extensibility demonstration)

Phase 4: Migration & Cleanup (Week 3)

  • Remove old keyboard handling code from ContentEditableController
  • Update BaseNode.svelte and BaseNodeViewer.svelte (if needed)
  • Performance validation using existing perf test infrastructure
  • Documentation: "Adding Custom Keyboard Shortcuts" guide
  • Final integration test sweep

Key Decisions & Clarifications

1. Blocking Issues Status

2. Migration Strategy

Incremental with parallel execution:

  1. Build full infrastructure first (registry, interfaces, tests)
  2. Migrate commands one at a time (Enter → Tab → Backspace → Navigation → Formatting)
  3. Run new command pattern alongside old handlers during transition
  4. Remove old code only after all commands migrated and tested

Why incremental?

  • Zero user-facing breakage during refactoring
  • Each command can be tested thoroughly before moving to next
  • Easy rollback if issues discovered
  • Aligns with "self-contained implementation" philosophy

3. Test Coverage Requirements

For each command:

  • ✅ Unit tests - Command logic in isolation (business logic)
  • ✅ Integration tests - Command within ContentEditableController (workflow)
  • ❌ Skip E2E - Existing integration tests already cover full workflows

Leverage existing test infrastructure:

  • /src/tests/component/content-editable-controller.test.ts
  • /src/tests/integration/node-workflow.test.ts
  • /src/tests/performance/event-bus-performance.test.ts

4. Performance Validation

Target: Performance equivalent or better than current implementation

Approach:

  • Reuse existing performance test infrastructure (event-bus-performance.test.ts)
  • Keyboard operations should complete in <16ms (single frame)
  • Add benchmarks for command execution overhead
  • Compare before/after metrics

5. Backward Compatibility

"Full backward compatibility during transition" means:

  • All existing keyboard functionality works exactly as before while migrating
  • Parallel execution allows old code to handle keys not yet migrated
  • Once migration complete, old code is removed (no permanent dual systems)

6. Future Extensibility

Design supports (but doesn't implement in this issue):

  • ✅ Plugin-based keyboard shortcuts - Interface designed for external registration
  • ✅ Context-aware commands - Commands can check node type, selection state, etc.
  • ⏳ User-configurable key bindings - Future enhancement (separate issue)

Acceptance Criteria

  • All keyboard operations use Command Pattern via KeyboardCommandRegistry
  • Separate service following SlashCommandService pattern
  • Unified MergeNodesCommand handles both Backspace and Delete
  • Comprehensive unit tests for each command (business logic)
  • Integration tests for command workflows
  • Performance equivalent or better (validated with existing perf tests)
  • Zero user-facing breakage during migration (parallel execution)
  • Documentation for adding custom keyboard shortcuts
  • All old keyboard handling code removed after migration complete

Scope

All phases (1-4) implemented in this issue for complete keyboard handling refactor.

Estimated Effort

  • Phase 1 (Infrastructure): 4-6 hours
  • Phase 2 (Core Commands): 8-12 hours
  • Phase 3 (Advanced Commands): 6-10 hours
  • Phase 4 (Cleanup): 2-4 hours
  • Total: 20-32 hours (2.5-4 working days)

Priority

High - Unblocks future keyboard shortcut additions and improves maintainability for scaling the system.

Related Issues

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions