Repository navigation
Description
Refactor: Replace $effect blocks with $derived patterns in Node Components
Problem Statement
Following the successful refactoring in #311 where we moved to architectural patterns like FocusManager instead of scattered $effect blocks, we should apply the same principles to our node wrapper components (TextNode, HeaderNode, TaskNode, etc.).
Currently, these components use $effect blocks for reactive state synchronization that could be replaced with more declarative $derived patterns or better architectural solutions.
Current $effect Usage
TextNode (src/lib/components/text-node.svelte:33-35)
let internalContent = $state(content);
$effect(() => {
internalContent = content;
});Pattern: Prop-to-state synchronization
HeaderNode (src/lib/design/components/header-node.svelte)
Block 1 (lines 44-55): Prop sync + newline stripping
$effect(() => {
let cleanedContent = content;
if (cleanedContent.includes('\n')) {
cleanedContent = cleanedContent.replace(/\n+/g, ' ');
dispatch('contentChanged', { content: cleanedContent });
}
internalContent = cleanedContent;
});Block 2 (lines 61-66): Header level detection
let headerLevel = $state(parseHeaderLevel(content));
$effect(() => {
const newLevel = parseHeaderLevel(internalContent);
if (newLevel !== headerLevel) {
headerLevel = newLevel;
}
});Pattern: Derived computation with state tracking
TaskNode (src/lib/design/components/task-node.svelte)
Block 1 (lines 44-46): Prop sync
$effect(() => {
internalContent = content;
});Block 2 (lines 143-150): Task state detection
$effect(() => {
if (/^\s*-?\s*\[(x|X|~|o|\s)\]/i.test(content.trim())) {
const newState = parseTaskState(content);
if (newState !== taskState) {
taskState = newState;
}
}
});Pattern: Conditional state update based on content
Proposed Solutions
Pattern 1: Replace Prop Sync with bind:content
Current (TextNode, TaskNode):
let internalContent = $state(content);
$effect(() => {
internalContent = content;
});
// In template
<BaseNode content={internalContent} />
// In event handler
on:contentChanged={(e) => {
internalContent = e.detail.content;
dispatch('contentChanged', e.detail);
}}Proposed:
// Remove $effect and $state completely
// In template
<BaseNode bind:content />
// In event handler (if needed)
on:contentChangedBenefits:
- Eliminates
$effectblock - Removes
internalContentstate variable - Uses Svelte's built-in two-way binding
- Simpler, more declarative
Pattern 2: Replace State Tracking with $derived
Current (HeaderNode header level):
let headerLevel = $state(parseHeaderLevel(content));
$effect(() => {
const newLevel = parseHeaderLevel(internalContent);
if (newLevel !== headerLevel) {
headerLevel = newLevel;
}
});Proposed:
let headerLevel = $derived(parseHeaderLevel(internalContent));Benefits:
- Eliminates
$effectblock - Pure reactive computation
- Automatically updates when
internalContentchanges - No manual state synchronization needed
- More declarative and easier to understand
Pattern 3: Move Side Effects to Event Handlers
Current (HeaderNode newline stripping):
$effect(() => {
let cleanedContent = content;
if (cleanedContent.includes('\n')) {
cleanedContent = cleanedContent.replace(/\n+/g, ' ');
dispatch('contentChanged', { content: cleanedContent });
}
internalContent = cleanedContent;
});Proposed:
function handleContentChange(event: CustomEvent<{ content: string }>) {
let newContent = event.detail.content;
// Headers are single-line - strip newlines
if (newContent.includes('\n')) {
newContent = newContent.replace(/\n+/g, ' ');
}
internalContent = newContent;
dispatch('contentChanged', { content: newContent });
}Benefits:
- Side effects happen explicitly in response to events
- No reactive timing issues
- Easier to debug (clear call stack)
- Follows event-driven pattern
Pattern 4: Conditional Derived Values
Current (TaskNode state detection):
let taskState = $state(parseTaskState(content));
$effect(() => {
if (/regex/.test(content.trim())) {
const newState = parseTaskState(content);
if (newState !== taskState) {
taskState = newState;
}
}
});Proposed Option A - $derived with fallback:
let taskState = $derived.by(() => {
const hasTaskSyntax = /^\s*-?\s*\[(x|X|~|o|\s)\]/i.test(content.trim());
return hasTaskSyntax
? parseTaskState(content)
: (metadata.taskState as NodeState) || 'pending';
});Proposed Option B - Computed from metadata:
// Store taskState in metadata instead of local state
// Let metadata be the single source of truth
let taskState = $derived((metadata.taskState as NodeState) || parseTaskState(content));Lessons from FocusManager Pattern
The FocusManager refactor showed us that:
- Centralized state management > scattered
$effectblocks - Explicit state updates > reactive side effects
- Single source of truth > synchronized state copies
We should apply these same principles:
- Could we have a NodeStateManager for task states?
- Could we use metadata as single source instead of local state + sync?
- Can we use $derived for pure computations instead of
$effect?
Implementation Strategy
Phase 1: Low-Risk Replacements (Quick Wins)
- ✅ HeaderNode line 61-66: Replace with
$derived(parseHeaderLevel(internalContent)) - ✅ Replace prop sync with
bind:contentwhere possible
Phase 2: Higher-Risk Refactors (Needs Testing)
- HeaderNode newline stripping: Move to event handler
- TaskNode state detection: Evaluate
$derived.by()vs metadata approach
Phase 3: Architectural Consideration
- Consider NodeStateManager for task/header state coordination
- Evaluate making metadata the single source of truth for all node-specific state
Acceptance Criteria
- Zero
$effectblocks used for prop synchronization - Pure computations use
$derivedinstead of$effect - Side effects happen in event handlers, not reactive blocks
- All existing tests pass
- No behavioral regressions
- Code is more declarative and easier to understand
Related Issues
- Refactor: Remove header-specific logic from BaseNode and TextareaController #311: Removed header-specific logic from base components (established the separation of concerns pattern)
- Refactor cursor positioning to reactive action-based architecture #281: FocusManager refactor (established centralized state management pattern)
Benefits
- Better performance:
$derivedis optimized for pure computations - Fewer reactivity bugs: No timing issues with
$effectexecution order - More declarative: Intent is clearer with
$derived - Easier debugging: Explicit event handlers vs reactive side effects
- Consistent patterns: Matches FocusManager architectural approach
Priority: Medium
Effort: 2-4 hours
Risk: Low-Medium (needs thorough testing)
Architecture Impact: High (improves consistency and maintainability)
Activity
refactor: Replace $effect blocks with $derived patterns (Phase 1) (#316)
fix: Allow empty ordered-list placeholders ('1. ') to enable testing
refactor: Move HeaderNode newline stripping from $effect to event han…
docs: Address all code review recommendations for Issue #316
malibio commentedon Oct 21, 2025
✅ Issue Complete - Merged to Main
All work for this refactoring has been successfully completed and merged.
Summary
Phase 1 & 2 Implementation:
$effectblocks with$derivedpatterns in TextNode, HeaderNode, TaskNodebind:contentpattern where appropriateCode Review Follow-Up:
Results
Test Coverage: 1093/1094 tests passing (99.9%)
Code Quality: 0 lint errors, 0 warnings
Technical Debt: Net reduction through elimination of imperative reactive patterns
Maintainability: Significantly improved through comprehensive documentation
Phase 3 Status
Phase 3 (Architectural Consideration - NodeStateManager) is marked as "Consideration" and optional. It can be addressed in a future issue if needed.
Merged Commits:
8acaa28: Phase 1 - Replace $effect blocks with $derived patterns5f6b00c: Fix OrderedListNodeBehavior validation for placeholder support55bd087: Phase 2 - Move HeaderNode newline stripping to event handlere2b320d: Address all code review recommendations🎉 This refactoring establishes valuable architectural patterns for future Svelte 5 development.
refactor: Replace $effect blocks with $derived patterns (Phase 1) (#316)
fix: Allow empty ordered-list placeholders ('1. ') to enable testing
refactor: Move HeaderNode newline stripping from $effect to event han…
docs: Address all code review recommendations for Issue #316
refactor: Replace $effect blocks with $derived patterns (Phase 1) (#316)
fix: Allow empty ordered-list placeholders ('1. ') to enable testing
refactor: Move HeaderNode newline stripping from $effect to event han…
docs: Address all code review recommendations for Issue #316
refactor: Replace $effect blocks with $derived patterns (Phase 1) (#316)
fix: Allow empty ordered-list placeholders ('1. ') to enable testing
refactor: Move HeaderNode newline stripping from $effect to event han…
docs: Address all code review recommendations for Issue #316
Address review feedback: fix cancelled task status regression and cle…
Refactor UI components to be props-driven and Tauri-independent (#1391)
Refactor UI components to be props-driven and Tauri-independent (#1391)