Repository navigation
Viewer Coordination: Focus, Scroll, and Cursor Management - #373
Merged
Merged
Conversation
Implemented pane-aware keyboard command execution to prevent inactive panes from responding to keyboard shortcuts. This is the first phase of viewer coordination for split-pane layouts. ## ✅ ACCEPTANCE CRITERIA STATUS (from Issue #301) - ✅ **Keyboard shortcuts routed to active viewer only** - IMPLEMENTED (this commit) - ✅ **Visual indicator shows which viewer is active** - ALREADY EXISTS (#300) - ❌ **Scroll position independent per viewer** - NOT IMPLEMENTED (Phase 2) - ✅ **Cursor position preserved during external updates** - ALREADY EXISTS (FocusManager) - ✅ **Clicking into viewer activates it** - ALREADY EXISTS (#300) - ✅ **Tab switch updates active viewer automatically** - ALREADY EXISTS (#300) ## 📊 INVESTIGATION FINDINGS **What Already Existed from #300:** - Pane context (paneId) available in BaseNode via Svelte context - Active pane tracking in tabState.activePaneId - FocusManager already tracks editingPaneId for cursor preservation - Visual indicators for active pane (box-shadow) - Click-to-activate functionality - Comprehensive cursor positioning system with semantic anchoring **What Was Missing:** - Keyboard commands executed in ALL panes simultaneously - No check to prevent inactive panes from handling shortcuts **Root Cause:** - TextareaController had no paneId parameter - KeyboardCommandRegistry had no pane-awareness check - KeyboardContext interface missing paneId field ## 🔧 CHANGES MADE ### 1. TextareaController Pane-Awareness **File:** `src/lib/design/components/textarea-controller.ts` **Lines:** 120, 164-171, 617-636 - Added `paneId: string` parameter to constructor (4th parameter) - Store paneId as instance variable - Import `tabState` from `$lib/stores/navigation` - Import `get` from `svelte/store` - In `buildKeyboardContext()`: Get activePaneId from tabState - Include `{ activePaneId }` in metadata for command execution **Key Code:** ```typescript constructor( element: HTMLTextAreaElement, nodeId: string, nodeType: string, paneId: string, // NEW PARAMETER events: TextareaControllerEvents, config: TextareaControllerConfig = {} ) private buildKeyboardContext(event: KeyboardEvent): Record<string, unknown> { const currentTabState = get(tabState); const activePaneId = currentTabState.activePaneId; return { // ... other fields paneId: this.paneId, metadata: { activePaneId } }; } ``` ### 2. KeyboardCommandRegistry Pane Check **File:** `src/lib/services/keyboard-command-registry.ts` **Lines:** 14-44 (interface), 138-161 (execute), 234-253 (buildContext) - Added `paneId: string` to `KeyboardContext` interface - Added pane-awareness check in `execute()` method before command execution - Updated `buildContext()` to include paneId with 'default' fallback **Key Code:** ```typescript // In execute() method, after building context: // MULTI-PANE COORDINATION: Only execute if this pane is active if (context.paneId && context.metadata.activePaneId) { if (context.paneId !== context.metadata.activePaneId) { return false; // Not the active pane, ignore the command } } ``` ### 3. BaseNode Integration **File:** `src/lib/design/components/base-node.svelte` **Line:** 686-693 - Pass `paneId` from context to TextareaController constructor **Key Code:** ```typescript controller = new TextareaController( element, nodeId, nodeType, paneId, // NEW - from context controllerEvents, editableConfig ); ``` ### 4. Test Updates **Files Modified:** - `src/tests/components/textarea-controller.test.ts` (3 occurrences) - `src/tests/components/textarea-bidirectional-conversion.test.ts` (multiple) - `src/tests/actions/position-cursor.test.ts` (1 occurrence) - All keyboard command tests (7 files): Added `paneId: "default"` to KeyboardContext objects **Pattern:** ```typescript // OLD: new TextareaController(element, 'node-id', 'text', mockEvents) // NEW: new TextareaController(element, 'node-id', 'text', 'default', mockEvents) ``` ## 🧪 TESTING RESULTS - ✅ TypeScript: svelte-check found 0 errors, 0 warnings - ✅ Linting: oxlint (0 warnings, 0 errors) - ✅ Formatting: prettier (all files unchanged) - ✅ Rust: cargo clippy (no warnings) - ✅ Unit Tests: 1351 passing, 16 failed (unrelated network failures in integration tests) ## 📝 WHAT'S NEXT - PHASE 2 IMPLEMENTATION GUIDE ### Task 1: Investigate Scroll Position Management **Goal:** Determine if scroll position tracking already exists or needs implementation **Steps:** 1. Check if BaseNodeViewer or any parent components track scroll position 2. Search for scroll event listeners in the codebase 3. Look for scroll restoration logic when switching tabs/panes 4. Test manually: Create split panes, scroll one pane, switch tabs, return - does scroll restore? **Files to Check:** - `src/lib/design/components/base-node-viewer.svelte` (lines 1385-1651 mention scroll) - `src/lib/components/layout/pane-manager.svelte` - `src/lib/components/layout/pane-content.svelte` - `src/lib/stores/navigation.ts` (check if tab/pane state includes scroll) **Expected Outcome:** Either: - Scroll tracking already works → Document and close issue - Scroll tracking missing → Implement scroll position store per viewer ID ### Task 2: Implement Scroll Position Tracking (If Needed) **Goal:** Store and restore scroll position per viewer instance **Implementation Plan:** 1. **Create scroll state store** (new file or extend navigation.ts): ```typescript // Map<viewerId, scrollPosition> const scrollPositions = new Map<string, number>(); export function saveScrollPosition(viewerId: string, position: number) { scrollPositions.set(viewerId, position); } export function getScrollPosition(viewerId: string): number { return scrollPositions.get(viewerId) ?? 0; } ``` 2. **Add scroll listener to BaseNodeViewer**: ```typescript let scrollContainer: HTMLElement; $effect(() => { if (scrollContainer) { const handleScroll = () => { saveScrollPosition(nodeId || 'default', scrollContainer.scrollTop); }; scrollContainer.addEventListener('scroll', handleScroll); return () => scrollContainer.removeEventListener('scroll', handleScroll); } }); ``` 3. **Restore scroll on mount**: ```typescript $effect(() => { if (scrollContainer && nodeId) { const savedPosition = getScrollPosition(nodeId); scrollContainer.scrollTop = savedPosition; } }); ``` **Files to Modify:** - `src/lib/design/components/base-node-viewer.svelte` (add scroll tracking) - `src/lib/stores/navigation.ts` OR create `src/lib/stores/scroll-state.ts` ### Task 3: Manual Browser Testing **Goal:** Verify all acceptance criteria work in actual browser **Test Plan:** 1. **Keyboard Shortcuts Test:** - Open dev server: `bun run dev` - Create 2 panes with Cmd+Shift+Click - Click into left pane - Press Cmd+B - verify only left pane gets bold formatting - Click into right pane - Press Cmd+B - verify only right pane gets bold formatting - Expected: ✅ Only active pane responds 2. **Scroll Position Test:** - Create 2 panes, scroll left pane to middle - Switch to different tab - Return to original tab - Expected: ✅ Left pane scroll position restored 3. **Cursor Preservation Test:** - Type in left pane, position cursor mid-text - External update triggers (simulate with DevTools) - Expected: ✅ Cursor stays at same semantic position 4. **Visual Indicator Test:** - Click between panes - Expected: ✅ Active pane shows box-shadow highlight 5. **Tab Switch Test:** - Switch tabs with multiple panes open - Expected: ✅ Active pane tracked per tab ### Task 4: Create Pull Request **Goal:** Submit completed work for review **Steps:** 1. Run final quality checks: `bun run quality:fix` 2. Push branch: `git push -u origin feature/issue-301-viewer-coordination` 3. Create PR: `bun run gh:pr 301` 4. Update status: PR creation does this automatically **PR Description Should Include:** - Link to this commit for Phase 1 details - Manual testing results from Phase 2 - Screenshots/video of split-pane keyboard shortcuts working - Any remaining issues or follow-up work ## 🎯 ESTIMATED REMAINING EFFORT - Scroll position investigation: 30 minutes - Scroll position implementation (if needed): 1-2 hours - Manual browser testing: 30 minutes - PR creation and documentation: 15 minutes **Total: 2.25-3.25 hours** ## 🔍 DEBUGGING TIPS FOR NEXT AGENT 1. **If keyboard shortcuts still affect both panes:** - Check browser console for `[KeyboardCommandRegistry]` debug logs (DEV mode) - Verify `paneId` is correctly passed from BaseNode context - Verify `activePaneId` matches the clicked pane - Add console.log in `keyboard-command-registry.ts:157-160` to see pane check 2. **If scroll doesn't persist:** - Check if BaseNodeViewer has `overflow: auto` or `overflow: scroll` - Verify scroll container element has proper ref binding - Check if scroll state is cleared on navigation 3. **If cursor jumps during updates:** - FocusManager should already handle this - Check `focus-manager.svelte.ts:72-85` for pane-aware editing state - Verify `editingPaneId` matches the active pane ## 📚 ARCHITECTURE REFERENCE **Pane Context Flow:** ``` PaneContent (sets paneId context) └─> BaseNodeViewer (receives from context) └─> BaseNode (receives from context: line 78) └─> TextareaController (receives as param: line 690) └─> KeyboardCommandRegistry (checks in execute: line 157-160) ``` **Active Pane State:** ``` User clicks pane └─> pane-manager.svelte onclick (line 132) └─> setActivePane(pane.id) └─> tabState.activePaneId updated └─> KeyboardCommandRegistry checks this value ``` ## 🔗 RELATED ISSUES - Issue #301: Viewer Coordination (this issue) - Issue #300: Split-Pane Layout System (complete) - Issue #297: Link Navigation (complete) ## 📄 RELEVANT DOCUMENTATION - [Development Process](docs/architecture/development/overview.md) - [Startup Sequence](docs/architecture/development/process/startup-sequence.md) - [Component Architecture](docs/architecture/components/component-architecture-guide.md) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
Implemented scroll position preservation for each viewer instance in split-pane layouts. Each viewer (identified by tabId + paneId) now maintains independent scroll state that persists when switching tabs or panes. ## ✅ ACCEPTANCE CRITERIA STATUS (from Issue #301) All acceptance criteria now COMPLETED: - ✅ **Keyboard shortcuts routed to active viewer only** - COMPLETE (Phase 1) - ✅ **Visual indicator shows which viewer is active** - COMPLETE (existed from #300) - ✅ **Scroll position independent per viewer** - COMPLETE (this commit) - ✅ **Cursor position preserved during external updates** - COMPLETE (FocusManager) - ✅ **Clicking into viewer activates it** - COMPLETE (existed from #300) - ✅ **Tab switch updates active viewer automatically** - COMPLETE (existed from #300) ## 📊 IMPLEMENTATION ### 1. Created Scroll State Store **File:** `src/lib/stores/scroll-state.ts` (NEW) - Centralized scroll position tracking using Map<viewerId, scrollPosition> - Viewer ID combines tabId + paneId: `${tabId}-${paneId}` - API functions: - `getViewerId(tabId, paneId)` - Generate unique viewer identifier - `saveScrollPosition(viewerId, position)` - Save scroll position - `getScrollPosition(viewerId)` - Retrieve saved position (0 if none) - `clearScrollPosition(viewerId)` - Clean up on tab close - `clearPaneScrollPositions(paneId)` - Clean up on pane close **Why this approach:** - Each viewer instance (tab + pane combination) gets independent scroll state - Same node in different tabs/panes maintains separate scroll positions - Memory efficient with automatic cleanup on close ### 2. Updated PaneContent to Pass tabId **File:** `src/lib/components/layout/pane-content.svelte` **Line:** 72 - Added `tabId={activeTabId}` prop to ViewerComponent - Provides tabId context needed for scroll tracking ### 3. Updated BaseNodeViewer for Scroll Tracking **File:** `src/lib/design/components/base-node-viewer.svelte` **Changes:** - **Line 32:** Added `tabId` prop (default: 'default') - **Line 24-28:** Import scroll state functions - **Line 80-82:** Initialize scroll container ref and viewerId - **Line 1452:** Bind scroll container element with `bind:this={scrollContainer}` - **Lines 1352-1369:** $effect for scroll event listener (saves on scroll) - **Lines 1371-1385:** $effect for scroll restoration (restores on mount/activation) **Scroll Save Logic:** ```typescript // Attach scroll listener when container becomes available $effect(() => { if (!scrollContainer) return; const handleScroll = () => { if (scrollContainer) { saveScrollPosition(viewerId, scrollContainer.scrollTop); } }; scrollContainer.addEventListener('scroll', handleScroll, { passive: true }); return () => { if (scrollContainer) { scrollContainer.removeEventListener('scroll', handleScroll); } }; }); ``` **Scroll Restore Logic:** ```typescript // Restore scroll position when viewer becomes active $effect(() => { if (scrollContainer && viewerId) { const savedPosition = getScrollPosition(viewerId); // Use requestAnimationFrame to ensure DOM is ready requestAnimationFrame(() => { if (scrollContainer) { scrollContainer.scrollTop = savedPosition; } }); } }); ``` ### 4. Updated Navigation Store for Cleanup **File:** `src/lib/stores/navigation.ts` **Line 3:** Import cleanup functions **Line 145:** Call `clearPaneScrollPositions(paneId)` in `closePane()` **Lines 277-282:** Call `clearScrollPosition(viewerId)` for all panes in `closeTab()` **Why cleanup matters:** - Prevents memory leaks from orphaned scroll positions - Ensures fresh state for new viewers with same IDs ## 🧪 TESTING **TypeScript:** ✅ svelte-check found 0 errors, 0 warnings **Linting:** ✅ oxlint (0 warnings, 0 errors) **Formatting:** ✅ prettier (all files unchanged) **Rust:** ✅ cargo clippy (no warnings) ## 📝 MANUAL TESTING CHECKLIST To verify all acceptance criteria work in browser: ### Test 1: Independent Scroll Positions 1. Create 2 panes (Cmd+Shift+Click) 2. Add content to left pane, scroll to middle 3. Switch to right pane, scroll to different position 4. Click back to left pane - **Expected:** ✅ Left pane scroll position restored ### Test 2: Scroll Persistence Across Tab Switches 1. Create content with multiple screens of nodes 2. Scroll to middle of content 3. Switch to different tab 4. Return to original tab - **Expected:** ✅ Scroll position restored exactly ### Test 3: Keyboard Shortcuts (Phase 1) 1. Create 2 panes 2. Click into left pane, press Cmd+B 3. Click into right pane, press Cmd+B - **Expected:** ✅ Only active pane responds to shortcuts ### Test 4: Visual Indicators (from #300) 1. Click between different panes - **Expected:** ✅ Active pane shows box-shadow highlight ### Test 5: Cursor Preservation (FocusManager) 1. Type in a node, position cursor mid-text 2. Trigger external update - **Expected:** ✅ Cursor stays at semantic position ## 🔧 ARCHITECTURE DECISIONS **1. Why Map instead of Svelte Store?** - Scroll positions are ephemeral UI state, not application state - No need for reactivity - only save/restore operations - Simpler implementation with direct Map access **2. Why composite viewerId (tabId-paneId)?** - Same nodeId can appear in multiple tabs/panes simultaneously - Each instance needs independent scroll state - Ensures no conflicts or shared state between viewers **3. Why requestAnimationFrame for restoration?** - Ensures DOM has fully rendered before setting scrollTop - Prevents race conditions with Svelte's reactive updates - Smoother restoration experience **4. Why passive event listener?** - Scroll events fire very frequently - Passive flag improves scroll performance - We don't need to preventDefault() on scroll events ## 🔍 DEBUGGING TIPS **If scroll doesn't persist:** - Check if `scrollContainer` is properly bound (inspect in DevTools) - Verify `viewerId` is unique per viewer instance - Check if cleanup is being called prematurely **If scroll jumps unexpectedly:** - Check if multiple effects are fighting over scrollTop - Verify requestAnimationFrame timing - Look for parent components forcing scroll reset ## 📚 RELATED COMMITS - Phase 1 (67e0bc1): Keyboard shortcut routing to active pane - Issue #300: Split-Pane Layout System - Issue #297: Link Navigation 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
Enhanced the scroll experience by implementing an autohide scrollbar that only
appears when hovering over the content area or actively scrolling. This provides
a cleaner, more modern interface while maintaining full scroll functionality.
## Changes
**File Modified:**
`src/lib/design/components/base-node-viewer.svelte` (lines 1700-1733)
## Implementation Details
**Autohide Scrollbar Styling:**
- **Default State**: Completely transparent scrollbar (hidden)
- **Hover State**: Scrollbar appears when hovering over `.node-content-area`
- **Active State**: Scrollbar visible while actively scrolling
- **Cross-Browser Support**:
- Firefox: `scrollbar-width: thin` + `scrollbar-color` properties
- WebKit (Chrome/Safari/Edge): `::-webkit-scrollbar-*` pseudo-elements
**CSS Structure:**
```css
.node-content-area {
scrollbar-width: thin;
scrollbar-color: transparent transparent; /* Hidden by default */
}
.node-content-area:hover,
.node-content-area:active {
scrollbar-color: hsl(var(--muted-foreground) / 0.3) transparent;
}
/* WebKit browsers */
.node-content-area::-webkit-scrollbar-thumb {
background: transparent; /* Hidden by default */
}
.node-content-area:hover::-webkit-scrollbar-thumb {
background: hsl(var(--muted-foreground) / 0.3); /* Visible on hover */
}
```
## Benefits
1. **Cleaner Interface**: No persistent scrollbar clutter
2. **Better Focus**: Content takes visual priority
3. **Modern UX**: Follows patterns from macOS, VS Code, etc.
4. **Accessible**: Scrollbar still appears when needed
5. **Performance**: Uses passive event listeners (from Phase 2)
## Browser Compatibility
- ✅ Chrome/Edge: Full support via `::-webkit-scrollbar`
- ✅ Firefox: Full support via `scrollbar-color`
- ✅ Safari: Full support via `::-webkit-scrollbar`
## Testing
Manually tested in browser:
- Scrollbar hidden by default ✅
- Appears on hover ✅
- Visible while scrolling ✅
- Works across different panes ✅
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <[email protected]>
Implemented all reviewer recommendations from the pragmatic code review,
including must-haves, improvements, and nitpicks. This commit enhances
code quality, test coverage, and documentation across the viewer coordination
implementation.
## Changes Made
### 1. Unit Tests for Scroll State Store (Must-Have)
**Files:** `src/tests/stores/scroll-state.test.ts` (NEW)
- Added comprehensive test suite with 22 tests covering all scroll state functions
- Tests for `getViewerId`, `saveScrollPosition`, `getScrollPosition`, `clearScrollPosition`
- Tests for `clearPaneScrollPositions` including edge cases (pane-1 vs pane-10, pane-11)
- Real-world usage scenario tests (multi-pane workflows, split views, tab cleanup)
- All tests pass (22/22)
### 2. Race Condition Fix in Scroll Restoration (Improvement)
**File:** `src/lib/design/components/base-node-viewer.svelte:1376-1383`
- Captured `scrollContainer` reference before `requestAnimationFrame`
- Added validation check to prevent stale scroll restoration
- Prevents flickering if viewer changes during RAF callback
**Before:**
```typescript
requestAnimationFrame(() => {
if (scrollContainer) {
scrollContainer.scrollTop = savedPosition;
}
});
```
**After:**
```typescript
const currentContainer = scrollContainer;
requestAnimationFrame(() => {
if (scrollContainer === currentContainer) {
scrollContainer.scrollTop = savedPosition;
}
});
```
### 3. Integration Tests for Multi-Pane Keyboard Coordination (Improvement)
**File:** `src/tests/integration/multi-pane-keyboard.test.ts` (NEW)
- Added 5 end-to-end tests verifying keyboard coordination behavior
- Tests verify only active pane executes keyboard shortcuts
- Tests verify pane switching updates command routing
- Tests verify fallback behavior when activePaneId is missing
- Tests verify multiple panes with same command
- All tests pass (5/5)
### 4. Scroll State Monitoring Utilities (Improvement)
**File:** `src/lib/stores/scroll-state.ts:68-92`
- Added `getScrollStateSize()` for memory leak detection
- Added `getScrollStateKeys()` for debugging (DEV mode only)
- Added `clearAllScrollPositions()` for test isolation
- Updated unit tests to verify monitoring utilities (4 new tests)
### 5. Standardized Viewer/Pane Terminology with JSDoc (Nitpick)
**File:** `src/lib/stores/scroll-state.ts:1-45`
- Added comprehensive module-level JSDoc explaining terminology:
- **Pane**: Split-pane container
- **Tab**: Document/node being viewed
- **Viewer**: BaseNodeViewer component instance
- **Viewer ID**: Unique identifier `${tabId}-${paneId}`
- Enhanced `getViewerId()` JSDoc with usage examples
- Clarifies relationship between concepts
### 6. Replaced Magic 'default' String with Constant (Nitpick)
**File:** `src/lib/services/keyboard-command-registry.ts:9,247`
- Imported `DEFAULT_PANE_ID` from navigation store
- Replaced hardcoded `'default'` string with constant
- Single source of truth for default values
- Prevents typos and eases refactoring
### 7. Added JSDoc for New tabId Prop (Nitpick)
**File:** `src/lib/design/components/base-node-viewer.svelte:33-40`
- Added comprehensive JSDoc comment for `tabId` prop
- Explains purpose: combined with paneId for scroll position tracking
- Documents that each tab+pane combo maintains independent scroll state
- Includes @default annotation
## Skipped Recommendations (Analysis)
**NOT IMPLEMENTED: Autohide Scrollbar CSS Extraction**
- **Reasoning:** The autohide scrollbar styling is specific to BaseNodeViewer context
- **Current approach:** Inline styles maintain component encapsulation
- **Future consideration:** Extract if pattern is reused elsewhere
- **Decision:** Keep as-is (acceptable per reviewer's counterpoint)
**NOT IMPLEMENTED: LRU Eviction for Scroll State Map**
- **Reasoning:** Scroll positions are tiny primitives (numbers)
- **Memory footprint:** Even 1000 entries = ~8KB (negligible)
- **Cleanup:** Proper cleanup on tab/pane close prevents unbounded growth
- **Decision:** `getScrollStateSize()` utility sufficient for monitoring
## Testing Results
**Unit Tests:**
- ✅ scroll-state.test.ts: 22 passing
- ✅ multi-pane-keyboard.test.ts: 5 passing
**Quality Checks:**
- ✅ TypeScript: svelte-check 0 errors, 0 warnings
- ✅ Linting: oxlint 0 warnings, 0 errors
- ✅ Linting: eslint 0 warnings, 0 errors
- ✅ Formatting: prettier all files unchanged
- ✅ Rust: cargo clippy no warnings
## Impact
**Code Quality:** +27 comprehensive tests, defensive programming patterns
**Documentation:** Improved terminology clarity, JSDoc coverage
**Maintainability:** Consistent constants, monitoring utilities for debugging
**Memory Safety:** Test isolation, leak detection tooling
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <[email protected]>
malibio
added a commit
that referenced
this pull request
Feb 4, 2026
* feat: Phase 1 - Keyboard shortcut routing to active pane (#301) Implemented pane-aware keyboard command execution to prevent inactive panes from responding to keyboard shortcuts. This is the first phase of viewer coordination for split-pane layouts. ## ✅ ACCEPTANCE CRITERIA STATUS (from Issue #301) - ✅ **Keyboard shortcuts routed to active viewer only** - IMPLEMENTED (this commit) - ✅ **Visual indicator shows which viewer is active** - ALREADY EXISTS (#300) - ❌ **Scroll position independent per viewer** - NOT IMPLEMENTED (Phase 2) - ✅ **Cursor position preserved during external updates** - ALREADY EXISTS (FocusManager) - ✅ **Clicking into viewer activates it** - ALREADY EXISTS (#300) - ✅ **Tab switch updates active viewer automatically** - ALREADY EXISTS (#300) ## 📊 INVESTIGATION FINDINGS **What Already Existed from #300:** - Pane context (paneId) available in BaseNode via Svelte context - Active pane tracking in tabState.activePaneId - FocusManager already tracks editingPaneId for cursor preservation - Visual indicators for active pane (box-shadow) - Click-to-activate functionality - Comprehensive cursor positioning system with semantic anchoring **What Was Missing:** - Keyboard commands executed in ALL panes simultaneously - No check to prevent inactive panes from handling shortcuts **Root Cause:** - TextareaController had no paneId parameter - KeyboardCommandRegistry had no pane-awareness check - KeyboardContext interface missing paneId field ## 🔧 CHANGES MADE ### 1. TextareaController Pane-Awareness **File:** `src/lib/design/components/textarea-controller.ts` **Lines:** 120, 164-171, 617-636 - Added `paneId: string` parameter to constructor (4th parameter) - Store paneId as instance variable - Import `tabState` from `$lib/stores/navigation` - Import `get` from `svelte/store` - In `buildKeyboardContext()`: Get activePaneId from tabState - Include `{ activePaneId }` in metadata for command execution **Key Code:** ```typescript constructor( element: HTMLTextAreaElement, nodeId: string, nodeType: string, paneId: string, // NEW PARAMETER events: TextareaControllerEvents, config: TextareaControllerConfig = {} ) private buildKeyboardContext(event: KeyboardEvent): Record<string, unknown> { const currentTabState = get(tabState); const activePaneId = currentTabState.activePaneId; return { // ... other fields paneId: this.paneId, metadata: { activePaneId } }; } ``` ### 2. KeyboardCommandRegistry Pane Check **File:** `src/lib/services/keyboard-command-registry.ts` **Lines:** 14-44 (interface), 138-161 (execute), 234-253 (buildContext) - Added `paneId: string` to `KeyboardContext` interface - Added pane-awareness check in `execute()` method before command execution - Updated `buildContext()` to include paneId with 'default' fallback **Key Code:** ```typescript // In execute() method, after building context: // MULTI-PANE COORDINATION: Only execute if this pane is active if (context.paneId && context.metadata.activePaneId) { if (context.paneId !== context.metadata.activePaneId) { return false; // Not the active pane, ignore the command } } ``` ### 3. BaseNode Integration **File:** `src/lib/design/components/base-node.svelte` **Line:** 686-693 - Pass `paneId` from context to TextareaController constructor **Key Code:** ```typescript controller = new TextareaController( element, nodeId, nodeType, paneId, // NEW - from context controllerEvents, editableConfig ); ``` ### 4. Test Updates **Files Modified:** - `src/tests/components/textarea-controller.test.ts` (3 occurrences) - `src/tests/components/textarea-bidirectional-conversion.test.ts` (multiple) - `src/tests/actions/position-cursor.test.ts` (1 occurrence) - All keyboard command tests (7 files): Added `paneId: "default"` to KeyboardContext objects **Pattern:** ```typescript // OLD: new TextareaController(element, 'node-id', 'text', mockEvents) // NEW: new TextareaController(element, 'node-id', 'text', 'default', mockEvents) ``` ## 🧪 TESTING RESULTS - ✅ TypeScript: svelte-check found 0 errors, 0 warnings - ✅ Linting: oxlint (0 warnings, 0 errors) - ✅ Formatting: prettier (all files unchanged) - ✅ Rust: cargo clippy (no warnings) - ✅ Unit Tests: 1351 passing, 16 failed (unrelated network failures in integration tests) ## 📝 WHAT'S NEXT - PHASE 2 IMPLEMENTATION GUIDE ### Task 1: Investigate Scroll Position Management **Goal:** Determine if scroll position tracking already exists or needs implementation **Steps:** 1. Check if BaseNodeViewer or any parent components track scroll position 2. Search for scroll event listeners in the codebase 3. Look for scroll restoration logic when switching tabs/panes 4. Test manually: Create split panes, scroll one pane, switch tabs, return - does scroll restore? **Files to Check:** - `src/lib/design/components/base-node-viewer.svelte` (lines 1385-1651 mention scroll) - `src/lib/components/layout/pane-manager.svelte` - `src/lib/components/layout/pane-content.svelte` - `src/lib/stores/navigation.ts` (check if tab/pane state includes scroll) **Expected Outcome:** Either: - Scroll tracking already works → Document and close issue - Scroll tracking missing → Implement scroll position store per viewer ID ### Task 2: Implement Scroll Position Tracking (If Needed) **Goal:** Store and restore scroll position per viewer instance **Implementation Plan:** 1. **Create scroll state store** (new file or extend navigation.ts): ```typescript // Map<viewerId, scrollPosition> const scrollPositions = new Map<string, number>(); export function saveScrollPosition(viewerId: string, position: number) { scrollPositions.set(viewerId, position); } export function getScrollPosition(viewerId: string): number { return scrollPositions.get(viewerId) ?? 0; } ``` 2. **Add scroll listener to BaseNodeViewer**: ```typescript let scrollContainer: HTMLElement; $effect(() => { if (scrollContainer) { const handleScroll = () => { saveScrollPosition(nodeId || 'default', scrollContainer.scrollTop); }; scrollContainer.addEventListener('scroll', handleScroll); return () => scrollContainer.removeEventListener('scroll', handleScroll); } }); ``` 3. **Restore scroll on mount**: ```typescript $effect(() => { if (scrollContainer && nodeId) { const savedPosition = getScrollPosition(nodeId); scrollContainer.scrollTop = savedPosition; } }); ``` **Files to Modify:** - `src/lib/design/components/base-node-viewer.svelte` (add scroll tracking) - `src/lib/stores/navigation.ts` OR create `src/lib/stores/scroll-state.ts` ### Task 3: Manual Browser Testing **Goal:** Verify all acceptance criteria work in actual browser **Test Plan:** 1. **Keyboard Shortcuts Test:** - Open dev server: `bun run dev` - Create 2 panes with Cmd+Shift+Click - Click into left pane - Press Cmd+B - verify only left pane gets bold formatting - Click into right pane - Press Cmd+B - verify only right pane gets bold formatting - Expected: ✅ Only active pane responds 2. **Scroll Position Test:** - Create 2 panes, scroll left pane to middle - Switch to different tab - Return to original tab - Expected: ✅ Left pane scroll position restored 3. **Cursor Preservation Test:** - Type in left pane, position cursor mid-text - External update triggers (simulate with DevTools) - Expected: ✅ Cursor stays at same semantic position 4. **Visual Indicator Test:** - Click between panes - Expected: ✅ Active pane shows box-shadow highlight 5. **Tab Switch Test:** - Switch tabs with multiple panes open - Expected: ✅ Active pane tracked per tab ### Task 4: Create Pull Request **Goal:** Submit completed work for review **Steps:** 1. Run final quality checks: `bun run quality:fix` 2. Push branch: `git push -u origin feature/issue-301-viewer-coordination` 3. Create PR: `bun run gh:pr 301` 4. Update status: PR creation does this automatically **PR Description Should Include:** - Link to this commit for Phase 1 details - Manual testing results from Phase 2 - Screenshots/video of split-pane keyboard shortcuts working - Any remaining issues or follow-up work ## 🎯 ESTIMATED REMAINING EFFORT - Scroll position investigation: 30 minutes - Scroll position implementation (if needed): 1-2 hours - Manual browser testing: 30 minutes - PR creation and documentation: 15 minutes **Total: 2.25-3.25 hours** ## 🔍 DEBUGGING TIPS FOR NEXT AGENT 1. **If keyboard shortcuts still affect both panes:** - Check browser console for `[KeyboardCommandRegistry]` debug logs (DEV mode) - Verify `paneId` is correctly passed from BaseNode context - Verify `activePaneId` matches the clicked pane - Add console.log in `keyboard-command-registry.ts:157-160` to see pane check 2. **If scroll doesn't persist:** - Check if BaseNodeViewer has `overflow: auto` or `overflow: scroll` - Verify scroll container element has proper ref binding - Check if scroll state is cleared on navigation 3. **If cursor jumps during updates:** - FocusManager should already handle this - Check `focus-manager.svelte.ts:72-85` for pane-aware editing state - Verify `editingPaneId` matches the active pane ## 📚 ARCHITECTURE REFERENCE **Pane Context Flow:** ``` PaneContent (sets paneId context) └─> BaseNodeViewer (receives from context) └─> BaseNode (receives from context: line 78) └─> TextareaController (receives as param: line 690) └─> KeyboardCommandRegistry (checks in execute: line 157-160) ``` **Active Pane State:** ``` User clicks pane └─> pane-manager.svelte onclick (line 132) └─> setActivePane(pane.id) └─> tabState.activePaneId updated └─> KeyboardCommandRegistry checks this value ``` ## 🔗 RELATED ISSUES - Issue #301: Viewer Coordination (this issue) - Issue #300: Split-Pane Layout System (complete) - Issue #297: Link Navigation (complete) ## 📄 RELEVANT DOCUMENTATION - [Development Process](docs/architecture/development/overview.md) - [Startup Sequence](docs/architecture/development/process/startup-sequence.md) - [Component Architecture](docs/architecture/components/component-architecture-guide.md) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * feat: Phase 2 - Independent scroll position tracking per viewer (#301) Implemented scroll position preservation for each viewer instance in split-pane layouts. Each viewer (identified by tabId + paneId) now maintains independent scroll state that persists when switching tabs or panes. ## ✅ ACCEPTANCE CRITERIA STATUS (from Issue #301) All acceptance criteria now COMPLETED: - ✅ **Keyboard shortcuts routed to active viewer only** - COMPLETE (Phase 1) - ✅ **Visual indicator shows which viewer is active** - COMPLETE (existed from #300) - ✅ **Scroll position independent per viewer** - COMPLETE (this commit) - ✅ **Cursor position preserved during external updates** - COMPLETE (FocusManager) - ✅ **Clicking into viewer activates it** - COMPLETE (existed from #300) - ✅ **Tab switch updates active viewer automatically** - COMPLETE (existed from #300) ## 📊 IMPLEMENTATION ### 1. Created Scroll State Store **File:** `src/lib/stores/scroll-state.ts` (NEW) - Centralized scroll position tracking using Map<viewerId, scrollPosition> - Viewer ID combines tabId + paneId: `${tabId}-${paneId}` - API functions: - `getViewerId(tabId, paneId)` - Generate unique viewer identifier - `saveScrollPosition(viewerId, position)` - Save scroll position - `getScrollPosition(viewerId)` - Retrieve saved position (0 if none) - `clearScrollPosition(viewerId)` - Clean up on tab close - `clearPaneScrollPositions(paneId)` - Clean up on pane close **Why this approach:** - Each viewer instance (tab + pane combination) gets independent scroll state - Same node in different tabs/panes maintains separate scroll positions - Memory efficient with automatic cleanup on close ### 2. Updated PaneContent to Pass tabId **File:** `src/lib/components/layout/pane-content.svelte` **Line:** 72 - Added `tabId={activeTabId}` prop to ViewerComponent - Provides tabId context needed for scroll tracking ### 3. Updated BaseNodeViewer for Scroll Tracking **File:** `src/lib/design/components/base-node-viewer.svelte` **Changes:** - **Line 32:** Added `tabId` prop (default: 'default') - **Line 24-28:** Import scroll state functions - **Line 80-82:** Initialize scroll container ref and viewerId - **Line 1452:** Bind scroll container element with `bind:this={scrollContainer}` - **Lines 1352-1369:** $effect for scroll event listener (saves on scroll) - **Lines 1371-1385:** $effect for scroll restoration (restores on mount/activation) **Scroll Save Logic:** ```typescript // Attach scroll listener when container becomes available $effect(() => { if (!scrollContainer) return; const handleScroll = () => { if (scrollContainer) { saveScrollPosition(viewerId, scrollContainer.scrollTop); } }; scrollContainer.addEventListener('scroll', handleScroll, { passive: true }); return () => { if (scrollContainer) { scrollContainer.removeEventListener('scroll', handleScroll); } }; }); ``` **Scroll Restore Logic:** ```typescript // Restore scroll position when viewer becomes active $effect(() => { if (scrollContainer && viewerId) { const savedPosition = getScrollPosition(viewerId); // Use requestAnimationFrame to ensure DOM is ready requestAnimationFrame(() => { if (scrollContainer) { scrollContainer.scrollTop = savedPosition; } }); } }); ``` ### 4. Updated Navigation Store for Cleanup **File:** `src/lib/stores/navigation.ts` **Line 3:** Import cleanup functions **Line 145:** Call `clearPaneScrollPositions(paneId)` in `closePane()` **Lines 277-282:** Call `clearScrollPosition(viewerId)` for all panes in `closeTab()` **Why cleanup matters:** - Prevents memory leaks from orphaned scroll positions - Ensures fresh state for new viewers with same IDs ## 🧪 TESTING **TypeScript:** ✅ svelte-check found 0 errors, 0 warnings **Linting:** ✅ oxlint (0 warnings, 0 errors) **Formatting:** ✅ prettier (all files unchanged) **Rust:** ✅ cargo clippy (no warnings) ## 📝 MANUAL TESTING CHECKLIST To verify all acceptance criteria work in browser: ### Test 1: Independent Scroll Positions 1. Create 2 panes (Cmd+Shift+Click) 2. Add content to left pane, scroll to middle 3. Switch to right pane, scroll to different position 4. Click back to left pane - **Expected:** ✅ Left pane scroll position restored ### Test 2: Scroll Persistence Across Tab Switches 1. Create content with multiple screens of nodes 2. Scroll to middle of content 3. Switch to different tab 4. Return to original tab - **Expected:** ✅ Scroll position restored exactly ### Test 3: Keyboard Shortcuts (Phase 1) 1. Create 2 panes 2. Click into left pane, press Cmd+B 3. Click into right pane, press Cmd+B - **Expected:** ✅ Only active pane responds to shortcuts ### Test 4: Visual Indicators (from #300) 1. Click between different panes - **Expected:** ✅ Active pane shows box-shadow highlight ### Test 5: Cursor Preservation (FocusManager) 1. Type in a node, position cursor mid-text 2. Trigger external update - **Expected:** ✅ Cursor stays at semantic position ## 🔧 ARCHITECTURE DECISIONS **1. Why Map instead of Svelte Store?** - Scroll positions are ephemeral UI state, not application state - No need for reactivity - only save/restore operations - Simpler implementation with direct Map access **2. Why composite viewerId (tabId-paneId)?** - Same nodeId can appear in multiple tabs/panes simultaneously - Each instance needs independent scroll state - Ensures no conflicts or shared state between viewers **3. Why requestAnimationFrame for restoration?** - Ensures DOM has fully rendered before setting scrollTop - Prevents race conditions with Svelte's reactive updates - Smoother restoration experience **4. Why passive event listener?** - Scroll events fire very frequently - Passive flag improves scroll performance - We don't need to preventDefault() on scroll events ## 🔍 DEBUGGING TIPS **If scroll doesn't persist:** - Check if `scrollContainer` is properly bound (inspect in DevTools) - Verify `viewerId` is unique per viewer instance - Check if cleanup is being called prematurely **If scroll jumps unexpectedly:** - Check if multiple effects are fighting over scrollTop - Verify requestAnimationFrame timing - Look for parent components forcing scroll reset ## 📚 RELATED COMMITS - Phase 1 (67e0bc1): Keyboard shortcut routing to active pane - Issue #300: Split-Pane Layout System - Issue #297: Link Navigation 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * style: Add autohide scrollbar for cleaner viewer UX (#301) Enhanced the scroll experience by implementing an autohide scrollbar that only appears when hovering over the content area or actively scrolling. This provides a cleaner, more modern interface while maintaining full scroll functionality. ## Changes **File Modified:** `src/lib/design/components/base-node-viewer.svelte` (lines 1700-1733) ## Implementation Details **Autohide Scrollbar Styling:** - **Default State**: Completely transparent scrollbar (hidden) - **Hover State**: Scrollbar appears when hovering over `.node-content-area` - **Active State**: Scrollbar visible while actively scrolling - **Cross-Browser Support**: - Firefox: `scrollbar-width: thin` + `scrollbar-color` properties - WebKit (Chrome/Safari/Edge): `::-webkit-scrollbar-*` pseudo-elements **CSS Structure:** ```css .node-content-area { scrollbar-width: thin; scrollbar-color: transparent transparent; /* Hidden by default */ } .node-content-area:hover, .node-content-area:active { scrollbar-color: hsl(var(--muted-foreground) / 0.3) transparent; } /* WebKit browsers */ .node-content-area::-webkit-scrollbar-thumb { background: transparent; /* Hidden by default */ } .node-content-area:hover::-webkit-scrollbar-thumb { background: hsl(var(--muted-foreground) / 0.3); /* Visible on hover */ } ``` ## Benefits 1. **Cleaner Interface**: No persistent scrollbar clutter 2. **Better Focus**: Content takes visual priority 3. **Modern UX**: Follows patterns from macOS, VS Code, etc. 4. **Accessible**: Scrollbar still appears when needed 5. **Performance**: Uses passive event listeners (from Phase 2) ## Browser Compatibility - ✅ Chrome/Edge: Full support via `::-webkit-scrollbar` - ✅ Firefox: Full support via `scrollbar-color` - ✅ Safari: Full support via `::-webkit-scrollbar` ## Testing Manually tested in browser: - Scrollbar hidden by default ✅ - Appears on hover ✅ - Visible while scrolling ✅ - Works across different panes ✅ 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * refactor: Address all code review recommendations for issue #301 Implemented all reviewer recommendations from the pragmatic code review, including must-haves, improvements, and nitpicks. This commit enhances code quality, test coverage, and documentation across the viewer coordination implementation. ## Changes Made ### 1. Unit Tests for Scroll State Store (Must-Have) **Files:** `src/tests/stores/scroll-state.test.ts` (NEW) - Added comprehensive test suite with 22 tests covering all scroll state functions - Tests for `getViewerId`, `saveScrollPosition`, `getScrollPosition`, `clearScrollPosition` - Tests for `clearPaneScrollPositions` including edge cases (pane-1 vs pane-10, pane-11) - Real-world usage scenario tests (multi-pane workflows, split views, tab cleanup) - All tests pass (22/22) ### 2. Race Condition Fix in Scroll Restoration (Improvement) **File:** `src/lib/design/components/base-node-viewer.svelte:1376-1383` - Captured `scrollContainer` reference before `requestAnimationFrame` - Added validation check to prevent stale scroll restoration - Prevents flickering if viewer changes during RAF callback **Before:** ```typescript requestAnimationFrame(() => { if (scrollContainer) { scrollContainer.scrollTop = savedPosition; } }); ``` **After:** ```typescript const currentContainer = scrollContainer; requestAnimationFrame(() => { if (scrollContainer === currentContainer) { scrollContainer.scrollTop = savedPosition; } }); ``` ### 3. Integration Tests for Multi-Pane Keyboard Coordination (Improvement) **File:** `src/tests/integration/multi-pane-keyboard.test.ts` (NEW) - Added 5 end-to-end tests verifying keyboard coordination behavior - Tests verify only active pane executes keyboard shortcuts - Tests verify pane switching updates command routing - Tests verify fallback behavior when activePaneId is missing - Tests verify multiple panes with same command - All tests pass (5/5) ### 4. Scroll State Monitoring Utilities (Improvement) **File:** `src/lib/stores/scroll-state.ts:68-92` - Added `getScrollStateSize()` for memory leak detection - Added `getScrollStateKeys()` for debugging (DEV mode only) - Added `clearAllScrollPositions()` for test isolation - Updated unit tests to verify monitoring utilities (4 new tests) ### 5. Standardized Viewer/Pane Terminology with JSDoc (Nitpick) **File:** `src/lib/stores/scroll-state.ts:1-45` - Added comprehensive module-level JSDoc explaining terminology: - **Pane**: Split-pane container - **Tab**: Document/node being viewed - **Viewer**: BaseNodeViewer component instance - **Viewer ID**: Unique identifier `${tabId}-${paneId}` - Enhanced `getViewerId()` JSDoc with usage examples - Clarifies relationship between concepts ### 6. Replaced Magic 'default' String with Constant (Nitpick) **File:** `src/lib/services/keyboard-command-registry.ts:9,247` - Imported `DEFAULT_PANE_ID` from navigation store - Replaced hardcoded `'default'` string with constant - Single source of truth for default values - Prevents typos and eases refactoring ### 7. Added JSDoc for New tabId Prop (Nitpick) **File:** `src/lib/design/components/base-node-viewer.svelte:33-40` - Added comprehensive JSDoc comment for `tabId` prop - Explains purpose: combined with paneId for scroll position tracking - Documents that each tab+pane combo maintains independent scroll state - Includes @default annotation ## Skipped Recommendations (Analysis) **NOT IMPLEMENTED: Autohide Scrollbar CSS Extraction** - **Reasoning:** The autohide scrollbar styling is specific to BaseNodeViewer context - **Current approach:** Inline styles maintain component encapsulation - **Future consideration:** Extract if pattern is reused elsewhere - **Decision:** Keep as-is (acceptable per reviewer's counterpoint) **NOT IMPLEMENTED: LRU Eviction for Scroll State Map** - **Reasoning:** Scroll positions are tiny primitives (numbers) - **Memory footprint:** Even 1000 entries = ~8KB (negligible) - **Cleanup:** Proper cleanup on tab/pane close prevents unbounded growth - **Decision:** `getScrollStateSize()` utility sufficient for monitoring ## Testing Results **Unit Tests:** - ✅ scroll-state.test.ts: 22 passing - ✅ multi-pane-keyboard.test.ts: 5 passing **Quality Checks:** - ✅ TypeScript: svelte-check 0 errors, 0 warnings - ✅ Linting: oxlint 0 warnings, 0 errors - ✅ Linting: eslint 0 warnings, 0 errors - ✅ Formatting: prettier all files unchanged - ✅ Rust: cargo clippy no warnings ## Impact **Code Quality:** +27 comprehensive tests, defensive programming patterns **Documentation:** Improved terminology clarity, JSDoc coverage **Maintainability:** Consistent constants, monitoring utilities for debugging **Memory Safety:** Test isolation, leak detection tooling 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> --------- Co-authored-by: Claude <[email protected]>
malibio
added a commit
that referenced
this pull request
Feb 5, 2026
* feat: Phase 1 - Keyboard shortcut routing to active pane (#301) Implemented pane-aware keyboard command execution to prevent inactive panes from responding to keyboard shortcuts. This is the first phase of viewer coordination for split-pane layouts. ## ✅ ACCEPTANCE CRITERIA STATUS (from Issue #301) - ✅ **Keyboard shortcuts routed to active viewer only** - IMPLEMENTED (this commit) - ✅ **Visual indicator shows which viewer is active** - ALREADY EXISTS (#300) - ❌ **Scroll position independent per viewer** - NOT IMPLEMENTED (Phase 2) - ✅ **Cursor position preserved during external updates** - ALREADY EXISTS (FocusManager) - ✅ **Clicking into viewer activates it** - ALREADY EXISTS (#300) - ✅ **Tab switch updates active viewer automatically** - ALREADY EXISTS (#300) ## 📊 INVESTIGATION FINDINGS **What Already Existed from #300:** - Pane context (paneId) available in BaseNode via Svelte context - Active pane tracking in tabState.activePaneId - FocusManager already tracks editingPaneId for cursor preservation - Visual indicators for active pane (box-shadow) - Click-to-activate functionality - Comprehensive cursor positioning system with semantic anchoring **What Was Missing:** - Keyboard commands executed in ALL panes simultaneously - No check to prevent inactive panes from handling shortcuts **Root Cause:** - TextareaController had no paneId parameter - KeyboardCommandRegistry had no pane-awareness check - KeyboardContext interface missing paneId field ## 🔧 CHANGES MADE ### 1. TextareaController Pane-Awareness **File:** `src/lib/design/components/textarea-controller.ts` **Lines:** 120, 164-171, 617-636 - Added `paneId: string` parameter to constructor (4th parameter) - Store paneId as instance variable - Import `tabState` from `$lib/stores/navigation` - Import `get` from `svelte/store` - In `buildKeyboardContext()`: Get activePaneId from tabState - Include `{ activePaneId }` in metadata for command execution **Key Code:** ```typescript constructor( element: HTMLTextAreaElement, nodeId: string, nodeType: string, paneId: string, // NEW PARAMETER events: TextareaControllerEvents, config: TextareaControllerConfig = {} ) private buildKeyboardContext(event: KeyboardEvent): Record<string, unknown> { const currentTabState = get(tabState); const activePaneId = currentTabState.activePaneId; return { // ... other fields paneId: this.paneId, metadata: { activePaneId } }; } ``` ### 2. KeyboardCommandRegistry Pane Check **File:** `src/lib/services/keyboard-command-registry.ts` **Lines:** 14-44 (interface), 138-161 (execute), 234-253 (buildContext) - Added `paneId: string` to `KeyboardContext` interface - Added pane-awareness check in `execute()` method before command execution - Updated `buildContext()` to include paneId with 'default' fallback **Key Code:** ```typescript // In execute() method, after building context: // MULTI-PANE COORDINATION: Only execute if this pane is active if (context.paneId && context.metadata.activePaneId) { if (context.paneId !== context.metadata.activePaneId) { return false; // Not the active pane, ignore the command } } ``` ### 3. BaseNode Integration **File:** `src/lib/design/components/base-node.svelte` **Line:** 686-693 - Pass `paneId` from context to TextareaController constructor **Key Code:** ```typescript controller = new TextareaController( element, nodeId, nodeType, paneId, // NEW - from context controllerEvents, editableConfig ); ``` ### 4. Test Updates **Files Modified:** - `src/tests/components/textarea-controller.test.ts` (3 occurrences) - `src/tests/components/textarea-bidirectional-conversion.test.ts` (multiple) - `src/tests/actions/position-cursor.test.ts` (1 occurrence) - All keyboard command tests (7 files): Added `paneId: "default"` to KeyboardContext objects **Pattern:** ```typescript // OLD: new TextareaController(element, 'node-id', 'text', mockEvents) // NEW: new TextareaController(element, 'node-id', 'text', 'default', mockEvents) ``` ## 🧪 TESTING RESULTS - ✅ TypeScript: svelte-check found 0 errors, 0 warnings - ✅ Linting: oxlint (0 warnings, 0 errors) - ✅ Formatting: prettier (all files unchanged) - ✅ Rust: cargo clippy (no warnings) - ✅ Unit Tests: 1351 passing, 16 failed (unrelated network failures in integration tests) ## 📝 WHAT'S NEXT - PHASE 2 IMPLEMENTATION GUIDE ### Task 1: Investigate Scroll Position Management **Goal:** Determine if scroll position tracking already exists or needs implementation **Steps:** 1. Check if BaseNodeViewer or any parent components track scroll position 2. Search for scroll event listeners in the codebase 3. Look for scroll restoration logic when switching tabs/panes 4. Test manually: Create split panes, scroll one pane, switch tabs, return - does scroll restore? **Files to Check:** - `src/lib/design/components/base-node-viewer.svelte` (lines 1385-1651 mention scroll) - `src/lib/components/layout/pane-manager.svelte` - `src/lib/components/layout/pane-content.svelte` - `src/lib/stores/navigation.ts` (check if tab/pane state includes scroll) **Expected Outcome:** Either: - Scroll tracking already works → Document and close issue - Scroll tracking missing → Implement scroll position store per viewer ID ### Task 2: Implement Scroll Position Tracking (If Needed) **Goal:** Store and restore scroll position per viewer instance **Implementation Plan:** 1. **Create scroll state store** (new file or extend navigation.ts): ```typescript // Map<viewerId, scrollPosition> const scrollPositions = new Map<string, number>(); export function saveScrollPosition(viewerId: string, position: number) { scrollPositions.set(viewerId, position); } export function getScrollPosition(viewerId: string): number { return scrollPositions.get(viewerId) ?? 0; } ``` 2. **Add scroll listener to BaseNodeViewer**: ```typescript let scrollContainer: HTMLElement; $effect(() => { if (scrollContainer) { const handleScroll = () => { saveScrollPosition(nodeId || 'default', scrollContainer.scrollTop); }; scrollContainer.addEventListener('scroll', handleScroll); return () => scrollContainer.removeEventListener('scroll', handleScroll); } }); ``` 3. **Restore scroll on mount**: ```typescript $effect(() => { if (scrollContainer && nodeId) { const savedPosition = getScrollPosition(nodeId); scrollContainer.scrollTop = savedPosition; } }); ``` **Files to Modify:** - `src/lib/design/components/base-node-viewer.svelte` (add scroll tracking) - `src/lib/stores/navigation.ts` OR create `src/lib/stores/scroll-state.ts` ### Task 3: Manual Browser Testing **Goal:** Verify all acceptance criteria work in actual browser **Test Plan:** 1. **Keyboard Shortcuts Test:** - Open dev server: `bun run dev` - Create 2 panes with Cmd+Shift+Click - Click into left pane - Press Cmd+B - verify only left pane gets bold formatting - Click into right pane - Press Cmd+B - verify only right pane gets bold formatting - Expected: ✅ Only active pane responds 2. **Scroll Position Test:** - Create 2 panes, scroll left pane to middle - Switch to different tab - Return to original tab - Expected: ✅ Left pane scroll position restored 3. **Cursor Preservation Test:** - Type in left pane, position cursor mid-text - External update triggers (simulate with DevTools) - Expected: ✅ Cursor stays at same semantic position 4. **Visual Indicator Test:** - Click between panes - Expected: ✅ Active pane shows box-shadow highlight 5. **Tab Switch Test:** - Switch tabs with multiple panes open - Expected: ✅ Active pane tracked per tab ### Task 4: Create Pull Request **Goal:** Submit completed work for review **Steps:** 1. Run final quality checks: `bun run quality:fix` 2. Push branch: `git push -u origin feature/issue-301-viewer-coordination` 3. Create PR: `bun run gh:pr 301` 4. Update status: PR creation does this automatically **PR Description Should Include:** - Link to this commit for Phase 1 details - Manual testing results from Phase 2 - Screenshots/video of split-pane keyboard shortcuts working - Any remaining issues or follow-up work ## 🎯 ESTIMATED REMAINING EFFORT - Scroll position investigation: 30 minutes - Scroll position implementation (if needed): 1-2 hours - Manual browser testing: 30 minutes - PR creation and documentation: 15 minutes **Total: 2.25-3.25 hours** ## 🔍 DEBUGGING TIPS FOR NEXT AGENT 1. **If keyboard shortcuts still affect both panes:** - Check browser console for `[KeyboardCommandRegistry]` debug logs (DEV mode) - Verify `paneId` is correctly passed from BaseNode context - Verify `activePaneId` matches the clicked pane - Add console.log in `keyboard-command-registry.ts:157-160` to see pane check 2. **If scroll doesn't persist:** - Check if BaseNodeViewer has `overflow: auto` or `overflow: scroll` - Verify scroll container element has proper ref binding - Check if scroll state is cleared on navigation 3. **If cursor jumps during updates:** - FocusManager should already handle this - Check `focus-manager.svelte.ts:72-85` for pane-aware editing state - Verify `editingPaneId` matches the active pane ## 📚 ARCHITECTURE REFERENCE **Pane Context Flow:** ``` PaneContent (sets paneId context) └─> BaseNodeViewer (receives from context) └─> BaseNode (receives from context: line 78) └─> TextareaController (receives as param: line 690) └─> KeyboardCommandRegistry (checks in execute: line 157-160) ``` **Active Pane State:** ``` User clicks pane └─> pane-manager.svelte onclick (line 132) └─> setActivePane(pane.id) └─> tabState.activePaneId updated └─> KeyboardCommandRegistry checks this value ``` ## 🔗 RELATED ISSUES - Issue #301: Viewer Coordination (this issue) - Issue #300: Split-Pane Layout System (complete) - Issue #297: Link Navigation (complete) ## 📄 RELEVANT DOCUMENTATION - [Development Process](docs/architecture/development/overview.md) - [Startup Sequence](docs/architecture/development/process/startup-sequence.md) - [Component Architecture](docs/architecture/components/component-architecture-guide.md) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * feat: Phase 2 - Independent scroll position tracking per viewer (#301) Implemented scroll position preservation for each viewer instance in split-pane layouts. Each viewer (identified by tabId + paneId) now maintains independent scroll state that persists when switching tabs or panes. ## ✅ ACCEPTANCE CRITERIA STATUS (from Issue #301) All acceptance criteria now COMPLETED: - ✅ **Keyboard shortcuts routed to active viewer only** - COMPLETE (Phase 1) - ✅ **Visual indicator shows which viewer is active** - COMPLETE (existed from #300) - ✅ **Scroll position independent per viewer** - COMPLETE (this commit) - ✅ **Cursor position preserved during external updates** - COMPLETE (FocusManager) - ✅ **Clicking into viewer activates it** - COMPLETE (existed from #300) - ✅ **Tab switch updates active viewer automatically** - COMPLETE (existed from #300) ## 📊 IMPLEMENTATION ### 1. Created Scroll State Store **File:** `src/lib/stores/scroll-state.ts` (NEW) - Centralized scroll position tracking using Map<viewerId, scrollPosition> - Viewer ID combines tabId + paneId: `${tabId}-${paneId}` - API functions: - `getViewerId(tabId, paneId)` - Generate unique viewer identifier - `saveScrollPosition(viewerId, position)` - Save scroll position - `getScrollPosition(viewerId)` - Retrieve saved position (0 if none) - `clearScrollPosition(viewerId)` - Clean up on tab close - `clearPaneScrollPositions(paneId)` - Clean up on pane close **Why this approach:** - Each viewer instance (tab + pane combination) gets independent scroll state - Same node in different tabs/panes maintains separate scroll positions - Memory efficient with automatic cleanup on close ### 2. Updated PaneContent to Pass tabId **File:** `src/lib/components/layout/pane-content.svelte` **Line:** 72 - Added `tabId={activeTabId}` prop to ViewerComponent - Provides tabId context needed for scroll tracking ### 3. Updated BaseNodeViewer for Scroll Tracking **File:** `src/lib/design/components/base-node-viewer.svelte` **Changes:** - **Line 32:** Added `tabId` prop (default: 'default') - **Line 24-28:** Import scroll state functions - **Line 80-82:** Initialize scroll container ref and viewerId - **Line 1452:** Bind scroll container element with `bind:this={scrollContainer}` - **Lines 1352-1369:** $effect for scroll event listener (saves on scroll) - **Lines 1371-1385:** $effect for scroll restoration (restores on mount/activation) **Scroll Save Logic:** ```typescript // Attach scroll listener when container becomes available $effect(() => { if (!scrollContainer) return; const handleScroll = () => { if (scrollContainer) { saveScrollPosition(viewerId, scrollContainer.scrollTop); } }; scrollContainer.addEventListener('scroll', handleScroll, { passive: true }); return () => { if (scrollContainer) { scrollContainer.removeEventListener('scroll', handleScroll); } }; }); ``` **Scroll Restore Logic:** ```typescript // Restore scroll position when viewer becomes active $effect(() => { if (scrollContainer && viewerId) { const savedPosition = getScrollPosition(viewerId); // Use requestAnimationFrame to ensure DOM is ready requestAnimationFrame(() => { if (scrollContainer) { scrollContainer.scrollTop = savedPosition; } }); } }); ``` ### 4. Updated Navigation Store for Cleanup **File:** `src/lib/stores/navigation.ts` **Line 3:** Import cleanup functions **Line 145:** Call `clearPaneScrollPositions(paneId)` in `closePane()` **Lines 277-282:** Call `clearScrollPosition(viewerId)` for all panes in `closeTab()` **Why cleanup matters:** - Prevents memory leaks from orphaned scroll positions - Ensures fresh state for new viewers with same IDs ## 🧪 TESTING **TypeScript:** ✅ svelte-check found 0 errors, 0 warnings **Linting:** ✅ oxlint (0 warnings, 0 errors) **Formatting:** ✅ prettier (all files unchanged) **Rust:** ✅ cargo clippy (no warnings) ## 📝 MANUAL TESTING CHECKLIST To verify all acceptance criteria work in browser: ### Test 1: Independent Scroll Positions 1. Create 2 panes (Cmd+Shift+Click) 2. Add content to left pane, scroll to middle 3. Switch to right pane, scroll to different position 4. Click back to left pane - **Expected:** ✅ Left pane scroll position restored ### Test 2: Scroll Persistence Across Tab Switches 1. Create content with multiple screens of nodes 2. Scroll to middle of content 3. Switch to different tab 4. Return to original tab - **Expected:** ✅ Scroll position restored exactly ### Test 3: Keyboard Shortcuts (Phase 1) 1. Create 2 panes 2. Click into left pane, press Cmd+B 3. Click into right pane, press Cmd+B - **Expected:** ✅ Only active pane responds to shortcuts ### Test 4: Visual Indicators (from #300) 1. Click between different panes - **Expected:** ✅ Active pane shows box-shadow highlight ### Test 5: Cursor Preservation (FocusManager) 1. Type in a node, position cursor mid-text 2. Trigger external update - **Expected:** ✅ Cursor stays at semantic position ## 🔧 ARCHITECTURE DECISIONS **1. Why Map instead of Svelte Store?** - Scroll positions are ephemeral UI state, not application state - No need for reactivity - only save/restore operations - Simpler implementation with direct Map access **2. Why composite viewerId (tabId-paneId)?** - Same nodeId can appear in multiple tabs/panes simultaneously - Each instance needs independent scroll state - Ensures no conflicts or shared state between viewers **3. Why requestAnimationFrame for restoration?** - Ensures DOM has fully rendered before setting scrollTop - Prevents race conditions with Svelte's reactive updates - Smoother restoration experience **4. Why passive event listener?** - Scroll events fire very frequently - Passive flag improves scroll performance - We don't need to preventDefault() on scroll events ## 🔍 DEBUGGING TIPS **If scroll doesn't persist:** - Check if `scrollContainer` is properly bound (inspect in DevTools) - Verify `viewerId` is unique per viewer instance - Check if cleanup is being called prematurely **If scroll jumps unexpectedly:** - Check if multiple effects are fighting over scrollTop - Verify requestAnimationFrame timing - Look for parent components forcing scroll reset ## 📚 RELATED COMMITS - Phase 1 (67e0bc1): Keyboard shortcut routing to active pane - Issue #300: Split-Pane Layout System - Issue #297: Link Navigation 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * style: Add autohide scrollbar for cleaner viewer UX (#301) Enhanced the scroll experience by implementing an autohide scrollbar that only appears when hovering over the content area or actively scrolling. This provides a cleaner, more modern interface while maintaining full scroll functionality. ## Changes **File Modified:** `src/lib/design/components/base-node-viewer.svelte` (lines 1700-1733) ## Implementation Details **Autohide Scrollbar Styling:** - **Default State**: Completely transparent scrollbar (hidden) - **Hover State**: Scrollbar appears when hovering over `.node-content-area` - **Active State**: Scrollbar visible while actively scrolling - **Cross-Browser Support**: - Firefox: `scrollbar-width: thin` + `scrollbar-color` properties - WebKit (Chrome/Safari/Edge): `::-webkit-scrollbar-*` pseudo-elements **CSS Structure:** ```css .node-content-area { scrollbar-width: thin; scrollbar-color: transparent transparent; /* Hidden by default */ } .node-content-area:hover, .node-content-area:active { scrollbar-color: hsl(var(--muted-foreground) / 0.3) transparent; } /* WebKit browsers */ .node-content-area::-webkit-scrollbar-thumb { background: transparent; /* Hidden by default */ } .node-content-area:hover::-webkit-scrollbar-thumb { background: hsl(var(--muted-foreground) / 0.3); /* Visible on hover */ } ``` ## Benefits 1. **Cleaner Interface**: No persistent scrollbar clutter 2. **Better Focus**: Content takes visual priority 3. **Modern UX**: Follows patterns from macOS, VS Code, etc. 4. **Accessible**: Scrollbar still appears when needed 5. **Performance**: Uses passive event listeners (from Phase 2) ## Browser Compatibility - ✅ Chrome/Edge: Full support via `::-webkit-scrollbar` - ✅ Firefox: Full support via `scrollbar-color` - ✅ Safari: Full support via `::-webkit-scrollbar` ## Testing Manually tested in browser: - Scrollbar hidden by default ✅ - Appears on hover ✅ - Visible while scrolling ✅ - Works across different panes ✅ 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * refactor: Address all code review recommendations for issue #301 Implemented all reviewer recommendations from the pragmatic code review, including must-haves, improvements, and nitpicks. This commit enhances code quality, test coverage, and documentation across the viewer coordination implementation. ## Changes Made ### 1. Unit Tests for Scroll State Store (Must-Have) **Files:** `src/tests/stores/scroll-state.test.ts` (NEW) - Added comprehensive test suite with 22 tests covering all scroll state functions - Tests for `getViewerId`, `saveScrollPosition`, `getScrollPosition`, `clearScrollPosition` - Tests for `clearPaneScrollPositions` including edge cases (pane-1 vs pane-10, pane-11) - Real-world usage scenario tests (multi-pane workflows, split views, tab cleanup) - All tests pass (22/22) ### 2. Race Condition Fix in Scroll Restoration (Improvement) **File:** `src/lib/design/components/base-node-viewer.svelte:1376-1383` - Captured `scrollContainer` reference before `requestAnimationFrame` - Added validation check to prevent stale scroll restoration - Prevents flickering if viewer changes during RAF callback **Before:** ```typescript requestAnimationFrame(() => { if (scrollContainer) { scrollContainer.scrollTop = savedPosition; } }); ``` **After:** ```typescript const currentContainer = scrollContainer; requestAnimationFrame(() => { if (scrollContainer === currentContainer) { scrollContainer.scrollTop = savedPosition; } }); ``` ### 3. Integration Tests for Multi-Pane Keyboard Coordination (Improvement) **File:** `src/tests/integration/multi-pane-keyboard.test.ts` (NEW) - Added 5 end-to-end tests verifying keyboard coordination behavior - Tests verify only active pane executes keyboard shortcuts - Tests verify pane switching updates command routing - Tests verify fallback behavior when activePaneId is missing - Tests verify multiple panes with same command - All tests pass (5/5) ### 4. Scroll State Monitoring Utilities (Improvement) **File:** `src/lib/stores/scroll-state.ts:68-92` - Added `getScrollStateSize()` for memory leak detection - Added `getScrollStateKeys()` for debugging (DEV mode only) - Added `clearAllScrollPositions()` for test isolation - Updated unit tests to verify monitoring utilities (4 new tests) ### 5. Standardized Viewer/Pane Terminology with JSDoc (Nitpick) **File:** `src/lib/stores/scroll-state.ts:1-45` - Added comprehensive module-level JSDoc explaining terminology: - **Pane**: Split-pane container - **Tab**: Document/node being viewed - **Viewer**: BaseNodeViewer component instance - **Viewer ID**: Unique identifier `${tabId}-${paneId}` - Enhanced `getViewerId()` JSDoc with usage examples - Clarifies relationship between concepts ### 6. Replaced Magic 'default' String with Constant (Nitpick) **File:** `src/lib/services/keyboard-command-registry.ts:9,247` - Imported `DEFAULT_PANE_ID` from navigation store - Replaced hardcoded `'default'` string with constant - Single source of truth for default values - Prevents typos and eases refactoring ### 7. Added JSDoc for New tabId Prop (Nitpick) **File:** `src/lib/design/components/base-node-viewer.svelte:33-40` - Added comprehensive JSDoc comment for `tabId` prop - Explains purpose: combined with paneId for scroll position tracking - Documents that each tab+pane combo maintains independent scroll state - Includes @default annotation ## Skipped Recommendations (Analysis) **NOT IMPLEMENTED: Autohide Scrollbar CSS Extraction** - **Reasoning:** The autohide scrollbar styling is specific to BaseNodeViewer context - **Current approach:** Inline styles maintain component encapsulation - **Future consideration:** Extract if pattern is reused elsewhere - **Decision:** Keep as-is (acceptable per reviewer's counterpoint) **NOT IMPLEMENTED: LRU Eviction for Scroll State Map** - **Reasoning:** Scroll positions are tiny primitives (numbers) - **Memory footprint:** Even 1000 entries = ~8KB (negligible) - **Cleanup:** Proper cleanup on tab/pane close prevents unbounded growth - **Decision:** `getScrollStateSize()` utility sufficient for monitoring ## Testing Results **Unit Tests:** - ✅ scroll-state.test.ts: 22 passing - ✅ multi-pane-keyboard.test.ts: 5 passing **Quality Checks:** - ✅ TypeScript: svelte-check 0 errors, 0 warnings - ✅ Linting: oxlint 0 warnings, 0 errors - ✅ Linting: eslint 0 warnings, 0 errors - ✅ Formatting: prettier all files unchanged - ✅ Rust: cargo clippy no warnings ## Impact **Code Quality:** +27 comprehensive tests, defensive programming patterns **Documentation:** Improved terminology clarity, JSDoc coverage **Maintainability:** Consistent constants, monitoring utilities for debugging **Memory Safety:** Test isolation, leak detection tooling 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> --------- Co-authored-by: Claude <[email protected]>
malibio
added a commit
that referenced
this pull request
Feb 26, 2026
* feat: Phase 1 - Keyboard shortcut routing to active pane (#301) Implemented pane-aware keyboard command execution to prevent inactive panes from responding to keyboard shortcuts. This is the first phase of viewer coordination for split-pane layouts. ## ✅ ACCEPTANCE CRITERIA STATUS (from Issue #301) - ✅ **Keyboard shortcuts routed to active viewer only** - IMPLEMENTED (this commit) - ✅ **Visual indicator shows which viewer is active** - ALREADY EXISTS (#300) - ❌ **Scroll position independent per viewer** - NOT IMPLEMENTED (Phase 2) - ✅ **Cursor position preserved during external updates** - ALREADY EXISTS (FocusManager) - ✅ **Clicking into viewer activates it** - ALREADY EXISTS (#300) - ✅ **Tab switch updates active viewer automatically** - ALREADY EXISTS (#300) ## 📊 INVESTIGATION FINDINGS **What Already Existed from #300:** - Pane context (paneId) available in BaseNode via Svelte context - Active pane tracking in tabState.activePaneId - FocusManager already tracks editingPaneId for cursor preservation - Visual indicators for active pane (box-shadow) - Click-to-activate functionality - Comprehensive cursor positioning system with semantic anchoring **What Was Missing:** - Keyboard commands executed in ALL panes simultaneously - No check to prevent inactive panes from handling shortcuts **Root Cause:** - TextareaController had no paneId parameter - KeyboardCommandRegistry had no pane-awareness check - KeyboardContext interface missing paneId field ## 🔧 CHANGES MADE ### 1. TextareaController Pane-Awareness **File:** `src/lib/design/components/textarea-controller.ts` **Lines:** 120, 164-171, 617-636 - Added `paneId: string` parameter to constructor (4th parameter) - Store paneId as instance variable - Import `tabState` from `$lib/stores/navigation` - Import `get` from `svelte/store` - In `buildKeyboardContext()`: Get activePaneId from tabState - Include `{ activePaneId }` in metadata for command execution **Key Code:** ```typescript constructor( element: HTMLTextAreaElement, nodeId: string, nodeType: string, paneId: string, // NEW PARAMETER events: TextareaControllerEvents, config: TextareaControllerConfig = {} ) private buildKeyboardContext(event: KeyboardEvent): Record<string, unknown> { const currentTabState = get(tabState); const activePaneId = currentTabState.activePaneId; return { // ... other fields paneId: this.paneId, metadata: { activePaneId } }; } ``` ### 2. KeyboardCommandRegistry Pane Check **File:** `src/lib/services/keyboard-command-registry.ts` **Lines:** 14-44 (interface), 138-161 (execute), 234-253 (buildContext) - Added `paneId: string` to `KeyboardContext` interface - Added pane-awareness check in `execute()` method before command execution - Updated `buildContext()` to include paneId with 'default' fallback **Key Code:** ```typescript // In execute() method, after building context: // MULTI-PANE COORDINATION: Only execute if this pane is active if (context.paneId && context.metadata.activePaneId) { if (context.paneId !== context.metadata.activePaneId) { return false; // Not the active pane, ignore the command } } ``` ### 3. BaseNode Integration **File:** `src/lib/design/components/base-node.svelte` **Line:** 686-693 - Pass `paneId` from context to TextareaController constructor **Key Code:** ```typescript controller = new TextareaController( element, nodeId, nodeType, paneId, // NEW - from context controllerEvents, editableConfig ); ``` ### 4. Test Updates **Files Modified:** - `src/tests/components/textarea-controller.test.ts` (3 occurrences) - `src/tests/components/textarea-bidirectional-conversion.test.ts` (multiple) - `src/tests/actions/position-cursor.test.ts` (1 occurrence) - All keyboard command tests (7 files): Added `paneId: "default"` to KeyboardContext objects **Pattern:** ```typescript // OLD: new TextareaController(element, 'node-id', 'text', mockEvents) // NEW: new TextareaController(element, 'node-id', 'text', 'default', mockEvents) ``` ## 🧪 TESTING RESULTS - ✅ TypeScript: svelte-check found 0 errors, 0 warnings - ✅ Linting: oxlint (0 warnings, 0 errors) - ✅ Formatting: prettier (all files unchanged) - ✅ Rust: cargo clippy (no warnings) - ✅ Unit Tests: 1351 passing, 16 failed (unrelated network failures in integration tests) ## 📝 WHAT'S NEXT - PHASE 2 IMPLEMENTATION GUIDE ### Task 1: Investigate Scroll Position Management **Goal:** Determine if scroll position tracking already exists or needs implementation **Steps:** 1. Check if BaseNodeViewer or any parent components track scroll position 2. Search for scroll event listeners in the codebase 3. Look for scroll restoration logic when switching tabs/panes 4. Test manually: Create split panes, scroll one pane, switch tabs, return - does scroll restore? **Files to Check:** - `src/lib/design/components/base-node-viewer.svelte` (lines 1385-1651 mention scroll) - `src/lib/components/layout/pane-manager.svelte` - `src/lib/components/layout/pane-content.svelte` - `src/lib/stores/navigation.ts` (check if tab/pane state includes scroll) **Expected Outcome:** Either: - Scroll tracking already works → Document and close issue - Scroll tracking missing → Implement scroll position store per viewer ID ### Task 2: Implement Scroll Position Tracking (If Needed) **Goal:** Store and restore scroll position per viewer instance **Implementation Plan:** 1. **Create scroll state store** (new file or extend navigation.ts): ```typescript // Map<viewerId, scrollPosition> const scrollPositions = new Map<string, number>(); export function saveScrollPosition(viewerId: string, position: number) { scrollPositions.set(viewerId, position); } export function getScrollPosition(viewerId: string): number { return scrollPositions.get(viewerId) ?? 0; } ``` 2. **Add scroll listener to BaseNodeViewer**: ```typescript let scrollContainer: HTMLElement; $effect(() => { if (scrollContainer) { const handleScroll = () => { saveScrollPosition(nodeId || 'default', scrollContainer.scrollTop); }; scrollContainer.addEventListener('scroll', handleScroll); return () => scrollContainer.removeEventListener('scroll', handleScroll); } }); ``` 3. **Restore scroll on mount**: ```typescript $effect(() => { if (scrollContainer && nodeId) { const savedPosition = getScrollPosition(nodeId); scrollContainer.scrollTop = savedPosition; } }); ``` **Files to Modify:** - `src/lib/design/components/base-node-viewer.svelte` (add scroll tracking) - `src/lib/stores/navigation.ts` OR create `src/lib/stores/scroll-state.ts` ### Task 3: Manual Browser Testing **Goal:** Verify all acceptance criteria work in actual browser **Test Plan:** 1. **Keyboard Shortcuts Test:** - Open dev server: `bun run dev` - Create 2 panes with Cmd+Shift+Click - Click into left pane - Press Cmd+B - verify only left pane gets bold formatting - Click into right pane - Press Cmd+B - verify only right pane gets bold formatting - Expected: ✅ Only active pane responds 2. **Scroll Position Test:** - Create 2 panes, scroll left pane to middle - Switch to different tab - Return to original tab - Expected: ✅ Left pane scroll position restored 3. **Cursor Preservation Test:** - Type in left pane, position cursor mid-text - External update triggers (simulate with DevTools) - Expected: ✅ Cursor stays at same semantic position 4. **Visual Indicator Test:** - Click between panes - Expected: ✅ Active pane shows box-shadow highlight 5. **Tab Switch Test:** - Switch tabs with multiple panes open - Expected: ✅ Active pane tracked per tab ### Task 4: Create Pull Request **Goal:** Submit completed work for review **Steps:** 1. Run final quality checks: `bun run quality:fix` 2. Push branch: `git push -u origin feature/issue-301-viewer-coordination` 3. Create PR: `bun run gh:pr 301` 4. Update status: PR creation does this automatically **PR Description Should Include:** - Link to this commit for Phase 1 details - Manual testing results from Phase 2 - Screenshots/video of split-pane keyboard shortcuts working - Any remaining issues or follow-up work ## 🎯 ESTIMATED REMAINING EFFORT - Scroll position investigation: 30 minutes - Scroll position implementation (if needed): 1-2 hours - Manual browser testing: 30 minutes - PR creation and documentation: 15 minutes **Total: 2.25-3.25 hours** ## 🔍 DEBUGGING TIPS FOR NEXT AGENT 1. **If keyboard shortcuts still affect both panes:** - Check browser console for `[KeyboardCommandRegistry]` debug logs (DEV mode) - Verify `paneId` is correctly passed from BaseNode context - Verify `activePaneId` matches the clicked pane - Add console.log in `keyboard-command-registry.ts:157-160` to see pane check 2. **If scroll doesn't persist:** - Check if BaseNodeViewer has `overflow: auto` or `overflow: scroll` - Verify scroll container element has proper ref binding - Check if scroll state is cleared on navigation 3. **If cursor jumps during updates:** - FocusManager should already handle this - Check `focus-manager.svelte.ts:72-85` for pane-aware editing state - Verify `editingPaneId` matches the active pane ## 📚 ARCHITECTURE REFERENCE **Pane Context Flow:** ``` PaneContent (sets paneId context) └─> BaseNodeViewer (receives from context) └─> BaseNode (receives from context: line 78) └─> TextareaController (receives as param: line 690) └─> KeyboardCommandRegistry (checks in execute: line 157-160) ``` **Active Pane State:** ``` User clicks pane └─> pane-manager.svelte onclick (line 132) └─> setActivePane(pane.id) └─> tabState.activePaneId updated └─> KeyboardCommandRegistry checks this value ``` ## 🔗 RELATED ISSUES - Issue #301: Viewer Coordination (this issue) - Issue #300: Split-Pane Layout System (complete) - Issue #297: Link Navigation (complete) ## 📄 RELEVANT DOCUMENTATION - [Development Process](docs/architecture/development/overview.md) - [Startup Sequence](docs/architecture/development/process/startup-sequence.md) - [Component Architecture](docs/architecture/components/component-architecture-guide.md) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * feat: Phase 2 - Independent scroll position tracking per viewer (#301) Implemented scroll position preservation for each viewer instance in split-pane layouts. Each viewer (identified by tabId + paneId) now maintains independent scroll state that persists when switching tabs or panes. ## ✅ ACCEPTANCE CRITERIA STATUS (from Issue #301) All acceptance criteria now COMPLETED: - ✅ **Keyboard shortcuts routed to active viewer only** - COMPLETE (Phase 1) - ✅ **Visual indicator shows which viewer is active** - COMPLETE (existed from #300) - ✅ **Scroll position independent per viewer** - COMPLETE (this commit) - ✅ **Cursor position preserved during external updates** - COMPLETE (FocusManager) - ✅ **Clicking into viewer activates it** - COMPLETE (existed from #300) - ✅ **Tab switch updates active viewer automatically** - COMPLETE (existed from #300) ## 📊 IMPLEMENTATION ### 1. Created Scroll State Store **File:** `src/lib/stores/scroll-state.ts` (NEW) - Centralized scroll position tracking using Map<viewerId, scrollPosition> - Viewer ID combines tabId + paneId: `${tabId}-${paneId}` - API functions: - `getViewerId(tabId, paneId)` - Generate unique viewer identifier - `saveScrollPosition(viewerId, position)` - Save scroll position - `getScrollPosition(viewerId)` - Retrieve saved position (0 if none) - `clearScrollPosition(viewerId)` - Clean up on tab close - `clearPaneScrollPositions(paneId)` - Clean up on pane close **Why this approach:** - Each viewer instance (tab + pane combination) gets independent scroll state - Same node in different tabs/panes maintains separate scroll positions - Memory efficient with automatic cleanup on close ### 2. Updated PaneContent to Pass tabId **File:** `src/lib/components/layout/pane-content.svelte` **Line:** 72 - Added `tabId={activeTabId}` prop to ViewerComponent - Provides tabId context needed for scroll tracking ### 3. Updated BaseNodeViewer for Scroll Tracking **File:** `src/lib/design/components/base-node-viewer.svelte` **Changes:** - **Line 32:** Added `tabId` prop (default: 'default') - **Line 24-28:** Import scroll state functions - **Line 80-82:** Initialize scroll container ref and viewerId - **Line 1452:** Bind scroll container element with `bind:this={scrollContainer}` - **Lines 1352-1369:** $effect for scroll event listener (saves on scroll) - **Lines 1371-1385:** $effect for scroll restoration (restores on mount/activation) **Scroll Save Logic:** ```typescript // Attach scroll listener when container becomes available $effect(() => { if (!scrollContainer) return; const handleScroll = () => { if (scrollContainer) { saveScrollPosition(viewerId, scrollContainer.scrollTop); } }; scrollContainer.addEventListener('scroll', handleScroll, { passive: true }); return () => { if (scrollContainer) { scrollContainer.removeEventListener('scroll', handleScroll); } }; }); ``` **Scroll Restore Logic:** ```typescript // Restore scroll position when viewer becomes active $effect(() => { if (scrollContainer && viewerId) { const savedPosition = getScrollPosition(viewerId); // Use requestAnimationFrame to ensure DOM is ready requestAnimationFrame(() => { if (scrollContainer) { scrollContainer.scrollTop = savedPosition; } }); } }); ``` ### 4. Updated Navigation Store for Cleanup **File:** `src/lib/stores/navigation.ts` **Line 3:** Import cleanup functions **Line 145:** Call `clearPaneScrollPositions(paneId)` in `closePane()` **Lines 277-282:** Call `clearScrollPosition(viewerId)` for all panes in `closeTab()` **Why cleanup matters:** - Prevents memory leaks from orphaned scroll positions - Ensures fresh state for new viewers with same IDs ## 🧪 TESTING **TypeScript:** ✅ svelte-check found 0 errors, 0 warnings **Linting:** ✅ oxlint (0 warnings, 0 errors) **Formatting:** ✅ prettier (all files unchanged) **Rust:** ✅ cargo clippy (no warnings) ## 📝 MANUAL TESTING CHECKLIST To verify all acceptance criteria work in browser: ### Test 1: Independent Scroll Positions 1. Create 2 panes (Cmd+Shift+Click) 2. Add content to left pane, scroll to middle 3. Switch to right pane, scroll to different position 4. Click back to left pane - **Expected:** ✅ Left pane scroll position restored ### Test 2: Scroll Persistence Across Tab Switches 1. Create content with multiple screens of nodes 2. Scroll to middle of content 3. Switch to different tab 4. Return to original tab - **Expected:** ✅ Scroll position restored exactly ### Test 3: Keyboard Shortcuts (Phase 1) 1. Create 2 panes 2. Click into left pane, press Cmd+B 3. Click into right pane, press Cmd+B - **Expected:** ✅ Only active pane responds to shortcuts ### Test 4: Visual Indicators (from #300) 1. Click between different panes - **Expected:** ✅ Active pane shows box-shadow highlight ### Test 5: Cursor Preservation (FocusManager) 1. Type in a node, position cursor mid-text 2. Trigger external update - **Expected:** ✅ Cursor stays at semantic position ## 🔧 ARCHITECTURE DECISIONS **1. Why Map instead of Svelte Store?** - Scroll positions are ephemeral UI state, not application state - No need for reactivity - only save/restore operations - Simpler implementation with direct Map access **2. Why composite viewerId (tabId-paneId)?** - Same nodeId can appear in multiple tabs/panes simultaneously - Each instance needs independent scroll state - Ensures no conflicts or shared state between viewers **3. Why requestAnimationFrame for restoration?** - Ensures DOM has fully rendered before setting scrollTop - Prevents race conditions with Svelte's reactive updates - Smoother restoration experience **4. Why passive event listener?** - Scroll events fire very frequently - Passive flag improves scroll performance - We don't need to preventDefault() on scroll events ## 🔍 DEBUGGING TIPS **If scroll doesn't persist:** - Check if `scrollContainer` is properly bound (inspect in DevTools) - Verify `viewerId` is unique per viewer instance - Check if cleanup is being called prematurely **If scroll jumps unexpectedly:** - Check if multiple effects are fighting over scrollTop - Verify requestAnimationFrame timing - Look for parent components forcing scroll reset ## 📚 RELATED COMMITS - Phase 1 (67e0bc1): Keyboard shortcut routing to active pane - Issue #300: Split-Pane Layout System - Issue #297: Link Navigation 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * style: Add autohide scrollbar for cleaner viewer UX (#301) Enhanced the scroll experience by implementing an autohide scrollbar that only appears when hovering over the content area or actively scrolling. This provides a cleaner, more modern interface while maintaining full scroll functionality. ## Changes **File Modified:** `src/lib/design/components/base-node-viewer.svelte` (lines 1700-1733) ## Implementation Details **Autohide Scrollbar Styling:** - **Default State**: Completely transparent scrollbar (hidden) - **Hover State**: Scrollbar appears when hovering over `.node-content-area` - **Active State**: Scrollbar visible while actively scrolling - **Cross-Browser Support**: - Firefox: `scrollbar-width: thin` + `scrollbar-color` properties - WebKit (Chrome/Safari/Edge): `::-webkit-scrollbar-*` pseudo-elements **CSS Structure:** ```css .node-content-area { scrollbar-width: thin; scrollbar-color: transparent transparent; /* Hidden by default */ } .node-content-area:hover, .node-content-area:active { scrollbar-color: hsl(var(--muted-foreground) / 0.3) transparent; } /* WebKit browsers */ .node-content-area::-webkit-scrollbar-thumb { background: transparent; /* Hidden by default */ } .node-content-area:hover::-webkit-scrollbar-thumb { background: hsl(var(--muted-foreground) / 0.3); /* Visible on hover */ } ``` ## Benefits 1. **Cleaner Interface**: No persistent scrollbar clutter 2. **Better Focus**: Content takes visual priority 3. **Modern UX**: Follows patterns from macOS, VS Code, etc. 4. **Accessible**: Scrollbar still appears when needed 5. **Performance**: Uses passive event listeners (from Phase 2) ## Browser Compatibility - ✅ Chrome/Edge: Full support via `::-webkit-scrollbar` - ✅ Firefox: Full support via `scrollbar-color` - ✅ Safari: Full support via `::-webkit-scrollbar` ## Testing Manually tested in browser: - Scrollbar hidden by default ✅ - Appears on hover ✅ - Visible while scrolling ✅ - Works across different panes ✅ 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * refactor: Address all code review recommendations for issue #301 Implemented all reviewer recommendations from the pragmatic code review, including must-haves, improvements, and nitpicks. This commit enhances code quality, test coverage, and documentation across the viewer coordination implementation. ## Changes Made ### 1. Unit Tests for Scroll State Store (Must-Have) **Files:** `src/tests/stores/scroll-state.test.ts` (NEW) - Added comprehensive test suite with 22 tests covering all scroll state functions - Tests for `getViewerId`, `saveScrollPosition`, `getScrollPosition`, `clearScrollPosition` - Tests for `clearPaneScrollPositions` including edge cases (pane-1 vs pane-10, pane-11) - Real-world usage scenario tests (multi-pane workflows, split views, tab cleanup) - All tests pass (22/22) ### 2. Race Condition Fix in Scroll Restoration (Improvement) **File:** `src/lib/design/components/base-node-viewer.svelte:1376-1383` - Captured `scrollContainer` reference before `requestAnimationFrame` - Added validation check to prevent stale scroll restoration - Prevents flickering if viewer changes during RAF callback **Before:** ```typescript requestAnimationFrame(() => { if (scrollContainer) { scrollContainer.scrollTop = savedPosition; } }); ``` **After:** ```typescript const currentContainer = scrollContainer; requestAnimationFrame(() => { if (scrollContainer === currentContainer) { scrollContainer.scrollTop = savedPosition; } }); ``` ### 3. Integration Tests for Multi-Pane Keyboard Coordination (Improvement) **File:** `src/tests/integration/multi-pane-keyboard.test.ts` (NEW) - Added 5 end-to-end tests verifying keyboard coordination behavior - Tests verify only active pane executes keyboard shortcuts - Tests verify pane switching updates command routing - Tests verify fallback behavior when activePaneId is missing - Tests verify multiple panes with same command - All tests pass (5/5) ### 4. Scroll State Monitoring Utilities (Improvement) **File:** `src/lib/stores/scroll-state.ts:68-92` - Added `getScrollStateSize()` for memory leak detection - Added `getScrollStateKeys()` for debugging (DEV mode only) - Added `clearAllScrollPositions()` for test isolation - Updated unit tests to verify monitoring utilities (4 new tests) ### 5. Standardized Viewer/Pane Terminology with JSDoc (Nitpick) **File:** `src/lib/stores/scroll-state.ts:1-45` - Added comprehensive module-level JSDoc explaining terminology: - **Pane**: Split-pane container - **Tab**: Document/node being viewed - **Viewer**: BaseNodeViewer component instance - **Viewer ID**: Unique identifier `${tabId}-${paneId}` - Enhanced `getViewerId()` JSDoc with usage examples - Clarifies relationship between concepts ### 6. Replaced Magic 'default' String with Constant (Nitpick) **File:** `src/lib/services/keyboard-command-registry.ts:9,247` - Imported `DEFAULT_PANE_ID` from navigation store - Replaced hardcoded `'default'` string with constant - Single source of truth for default values - Prevents typos and eases refactoring ### 7. Added JSDoc for New tabId Prop (Nitpick) **File:** `src/lib/design/components/base-node-viewer.svelte:33-40` - Added comprehensive JSDoc comment for `tabId` prop - Explains purpose: combined with paneId for scroll position tracking - Documents that each tab+pane combo maintains independent scroll state - Includes @default annotation ## Skipped Recommendations (Analysis) **NOT IMPLEMENTED: Autohide Scrollbar CSS Extraction** - **Reasoning:** The autohide scrollbar styling is specific to BaseNodeViewer context - **Current approach:** Inline styles maintain component encapsulation - **Future consideration:** Extract if pattern is reused elsewhere - **Decision:** Keep as-is (acceptable per reviewer's counterpoint) **NOT IMPLEMENTED: LRU Eviction for Scroll State Map** - **Reasoning:** Scroll positions are tiny primitives (numbers) - **Memory footprint:** Even 1000 entries = ~8KB (negligible) - **Cleanup:** Proper cleanup on tab/pane close prevents unbounded growth - **Decision:** `getScrollStateSize()` utility sufficient for monitoring ## Testing Results **Unit Tests:** - ✅ scroll-state.test.ts: 22 passing - ✅ multi-pane-keyboard.test.ts: 5 passing **Quality Checks:** - ✅ TypeScript: svelte-check 0 errors, 0 warnings - ✅ Linting: oxlint 0 warnings, 0 errors - ✅ Linting: eslint 0 warnings, 0 errors - ✅ Formatting: prettier all files unchanged - ✅ Rust: cargo clippy no warnings ## Impact **Code Quality:** +27 comprehensive tests, defensive programming patterns **Documentation:** Improved terminology clarity, JSDoc coverage **Maintainability:** Consistent constants, monitoring utilities for debugging **Memory Safety:** Test isolation, leak detection tooling 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> --------- Co-authored-by: Claude <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #301