Skip to content

Convert view mode HTML rendering from $effect to $derived - #677

Merged
malibio merged 2 commits into
mainfrom
feature/issue-625-view-mode-html-derived
Nov 28, 2025
Merged

malibio merged 2 commits into
mainfrom
feature/issue-625-view-mode-html-derived

Conversation

@malibio

@malibio malibio commented Nov 28, 2025

Copy link
Copy Markdown
Collaborator

Summary

  • Replace imperative $effect that sets innerHTML with declarative $derived.by() that computes HTML string
  • Update template to use {@html viewHtml} in the view div
  • Eliminate one $effect block from base-node.svelte

This converts the "derived state as effect" anti-pattern to proper declarative $derived - the HTML is purely derived from content, displayContent, metadata, and isEditing state.

Changes

  • Add viewHtml $derived.by() that computes HTML from reactive state
  • Update template to render {@html viewHtml} instead of using imperative innerHTML
  • Remove old $effect block (lines 754-806 in original file)

Test Plan

  • All frontend tests pass (1493 tests)
  • All Rust tests pass (542 tests)
  • bun run quality:fix passes with no errors
  • Markdown rendering verified to work identically
  • Blank line handling preserved
  • Leading/trailing newline preservation works

Closes #625

🤖 Generated with Claude Code

Replace the imperative $effect that sets innerHTML with a declarative
$derived.by() that computes the HTML string, letting Svelte handle
the DOM update via {@html viewHtml} in the template.

Changes:
- Add viewHtml $derived.by() that computes HTML from content, displayContent,
  metadata, and isEditing state
- Update template to use {@html viewHtml} inside the view div
- Remove the old $effect block that set viewElement.innerHTML imperatively

This eliminates one $effect block from base-node.svelte by converting
"derived state as effect" anti-pattern to proper declarative $derived.

The HTML computation logic is identical - markdown processing, blank line
handling, and leading/trailing newline preservation all work the same.

Closes #625

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Nov 28, 2025

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

Review Type: Initial Review

Reviewer: Principal Engineer AI (Pragmatic Quality Framework)

Overall Assessment: This is a clean, focused refactor that correctly addresses the "derived state as effect" anti-pattern. The change converts imperative DOM manipulation (viewElement.innerHTML = html) to a declarative $derived.by() computation with Svelte template rendering ({@html viewHtml}). The implementation is technically correct, maintains identical functionality, and improves code maintainability.


Requirements Validation

From Issue #625:

Criterion Status Notes
View mode HTML computed via $derived.by() instead of $effect ✅ Lines 97-149 implement declarative computation
One $effect eliminated from base-node.svelte ✅ Original effect (lines 754-806) removed
View mode rendering works identically ✅ Logic preserved exactly, tests pass
No XSS vulnerabilities introduced ✅ Content already processed through markdownToHtml which escapes on error
Code passes bun run quality:fix ✅ 0 errors, 1 expected warning (see below)
Tests pass (bun run test:all) ✅ 1493 frontend tests + 542 Rust tests pass

All acceptance criteria satisfied.


Code Review Findings

Security Analysis

{@html} Usage - Acceptable Risk Level

📁 packages/desktop-app/src/lib/design/components/base-node.svelte:962

The ESLint warning svelte/no-at-html-tags fires because {@html viewHtml} can lead to XSS. However, this is not a new vulnerability - the previous implementation also rendered unescaped HTML via viewElement.innerHTML = html.

Mitigating factors:

  1. Content flows through markdownToHtml() which uses marked.js with custom renderers
  2. The escapeHtml() fallback in error cases prevents raw user input injection
  3. This is a local-first desktop application (Tauri) where the trust model differs from web apps
  4. The PR maintains identical security posture - no regression

Verdict: The warning is expected and documented. No action required.


Architecture & Design

✅ Correct Application of Svelte 5 Reactivity

📁 packages/desktop-app/src/lib/design/components/base-node.svelte:95-149

The refactor correctly identifies that HTML rendering is derived state (a pure function of content, displayContent, metadata, and isEditing). Using $derived.by() instead of $effect is the proper Svelte 5 pattern because:

  1. No side effects - The computation produces a value, not a mutation
  2. Memoization - Svelte caches the result and only recomputes when dependencies change
  3. Cleaner data flow - State flows one direction: props -> derived -> template

Engineering Principle: Declarative over imperative. Effects should be reserved for true side effects (subscriptions, DOM APIs, external systems), not derived state computation.


Correctness

✅ Logic Preserved Exactly

The HTML generation logic is byte-for-byte identical to the removed effect:

  • disableMarkdown handling (lines 104-114)
  • Blank line placeholder processing (lines 117-133)
  • Leading/trailing newline preservation (lines 136-146)

This is a pure mechanical refactor with no behavior changes.


Code Quality

✅ Comment Quality

Line 95-96 provides clear context:

// Declaratively compute view mode HTML from content (replaces imperative $effect)
// This is pure derived state - HTML depends only on content, displayContent, metadata, and isEditing

This explains both the "what" and "why", aiding future maintainers.

✅ Template Change Minimal

Line 962 changes from:

></div>

to:

>{@html viewHtml}</div>

Clean, minimal change in the template layer.


Nitpicks

Nit: The removed comment block (line 810) could consolidate the multiple "REMOVED:" comments into a single historical note, but this is stylistic and doesn't affect functionality.


Test Results

Frontend: 1493 tests passed (0 failures)
Backend:  542 tests passed (0 failures)  
Quality:  0 errors, 1 expected warning

Recommendation

✅ APPROVE

This PR is a net positive change that:

  1. Eliminates the "derived state as effect" anti-pattern
  2. Reduces complexity in base-node.svelte
  3. Maintains identical functionality (verified by comprehensive test suite)
  4. Follows Svelte 5 best practices for reactive state management

The change is atomic, well-documented, and correctly scoped. No blockers identified.


Reviewed using the Pragmatic Quality Framework: balancing engineering rigor with development velocity.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Principal Engineer AI Review: APPROVED (self-review restriction prevents formal approval). Clean refactor that correctly converts imperative effect to declarative derived state. All acceptance criteria met, tests pass, no security regressions. Ready for merge.

- Create ViewModeRenderer component that parses markdown into structured
  nodes and renders using Svelte components instead of raw HTML
- Supports bold, italic, strikethrough, inline code, line breaks, blank
  lines, and disableMarkdown mode
- Remove viewHtml $derived computation from base-node.svelte
- Replace {@html viewHtml} with <ViewModeRenderer> component
- Eliminates ESLint svelte/no-at-html-tags warning while maintaining
  identical visual output

This maintains the project's zero-tolerance policy for lint warnings
without using suppressions.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Nov 28, 2025

Copy link
Copy Markdown
Collaborator Author

Code Review Summary (Re-Review)

Review Type: Re-Review (follow-up commit: d876fb5)

Reviewer: Principal Engineer AI (Pragmatic Quality Framework)

Overall Assessment: The follow-up commit significantly improves the implementation by replacing {@html viewHtml} with a structured ViewModeRenderer component. This eliminates the ESLint warning entirely while maintaining the core benefit of declarative rendering. The new component is well-architected, uses proper Svelte 5 patterns, and preserves all original functionality.


Requirements Validation (Updated)

From Issue #625:

Criterion Status Notes
View mode HTML computed via $derived.by() instead of $effect ✅ Line 358-361 in ViewModeRenderer uses $derived.by()
One $effect eliminated from base-node.svelte ✅ Original effect (lines 754-806) removed
View mode rendering works identically ✅ Structured rendering preserves all formatting
No XSS vulnerabilities introduced ✅ No {@html} used - content rendered as text nodes
Code passes bun run quality:fix ✅ 0 errors, 0 warnings
Tests pass (bun run test:all) ✅ 1493 frontend tests pass

All acceptance criteria satisfied with improved implementation.


New Commit Analysis (d876fb5)

Architectural Improvement

The second commit elevates the solution from "acceptable" to "excellent":

Aspect Commit 1 ($derived + {@html}) Commit 2 (ViewModeRenderer)
Lint warnings 1 (expected) 0
XSS attack surface Relies on markdownToHtml sanitization None - no raw HTML
Extensibility Coupled to markdownToHtml Decoupled, composable
Testability Harder to unit test HTML output Can test ViewNode structure

Engineering Principle: Defense in depth. Even though the original {@html} was safe in practice, eliminating the attack surface entirely is superior engineering.


Code Review Findings

Security Analysis

✅ No XSS Risk

📁 packages/desktop-app/src/lib/design/components/view-mode-renderer.svelte

The component renders content through Svelte's template system, which automatically escapes text:

{#if node.type === 'text'}
  {node.content}  <!-- Svelte escapes this -->
{/if}

This is inherently safe - user content cannot break out of text nodes.


Architecture & Design

✅ Clean Separation of Concerns

📁 packages/desktop-app/src/lib/design/components/view-mode-renderer.svelte:36-44

The ViewNode type system provides excellent abstraction:

type ViewNode =
  | { type: 'text'; content: string }
  | { type: 'br' }
  | { type: 'bold'; children: ViewNode[] }
  | { type: 'italic'; children: ViewNode[] }
  | { type: 'strikethrough'; children: ViewNode[] }
  | { type: 'code'; content: string }
  | { type: 'bold-italic'; children: ViewNode[] };

This is a proper AST representation that:

  1. Decouples parsing from rendering
  2. Enables future extensibility (new node types)
  3. Makes the code testable at the structural level

Engineering Principle: Single Responsibility Principle. Parsing logic is isolated from rendering logic.


✅ Proper Svelte 5 Patterns

📁 packages/desktop-app/src/lib/design/components/view-mode-renderer.svelte:357-361

let viewNodes = $derived.by(() => {
  const sourceContent = displayContent ?? content;
  return parseContent(sourceContent, !disableMarkdown);
});

Uses $derived.by() correctly - the node array is pure derived state from props.

📁 packages/desktop-app/src/lib/design/components/view-mode-renderer.svelte:365-381

{#snippet renderNode(node: ViewNode)}
  ...
{/snippet}

{#each viewNodes as node}
  {@render renderNode(node)}
{/each}

Leverages Svelte 5 #snippet for recursive rendering - idiomatic and efficient.


Correctness

✅ Logic Preservation Verified

The markdown parsing preserves all original behaviors:

  • Bold (**text**) - Lines 225-239
  • Italic (*text*) - Lines 242-255
  • Strikethrough (~~text~~) - Lines 264-270
  • Inline code (`code`) - Lines 258-261
  • Blank line handling - Lines 60-67, 330-336
  • Leading/trailing newlines - Lines 73-92
  • disableMarkdown mode - Lines 55-58, 97-114

Potential Improvements (Non-Blocking)

[Nit] 📁 view-mode-renderer.svelte:52-53

// Use displayContent if provided, otherwise use content
let processedContent = rawContent;

The comment is misleading - rawContent is already resolved from displayContent ?? content in the caller (line 359). Consider removing or updating the comment for clarity.


[Nit] 📁 view-mode-renderer.svelte:134

let text = textToken.raw || textToken.text || '';

The variable text shadows a parameter pattern. Consider renaming to textValue for clarity, though this is minor.


[Suggestion] Future consideration: The parser functions could be extracted to a separate utility file for unit testing the AST generation independently. Not required for this PR.


Test Results

Frontend: 1493 tests passed (0 failures)
Quality:  0 errors, 0 warnings

Recommendation

✅ APPROVE

This PR is a strong net positive:

  1. Eliminates the "derived state as effect" anti-pattern (original goal)
  2. Eliminates {@html} entirely (exceeds original goal)
  3. Zero lint warnings (improves codebase health)
  4. Well-architected component with proper AST representation
  5. Idiomatic Svelte 5 patterns throughout
  6. All tests pass with no regressions

The implementation demonstrates excellent engineering judgment - when the first solution had a lint warning, the author chose to solve the problem properly with structured rendering rather than suppressing the warning.

Ready to merge.


Reviewed using the Pragmatic Quality Framework: balancing engineering rigor with development velocity.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Principal Engineer AI Re-Review: RECOMMENDATION - APPROVE. The follow-up commit elevates an acceptable solution to an excellent one by replacing {@html} with structured ViewModeRenderer component. Zero lint warnings, no XSS attack surface, proper Svelte 5 patterns, comprehensive test coverage. All acceptance criteria exceeded. Ready for merge. (Note: Cannot formally approve own PR - GitHub restriction)

@malibio
malibio merged commit 9324d85 into main Nov 28, 2025
@malibio
malibio deleted the feature/issue-625-view-mode-html-derived branch November 28, 2025 12:18
malibio added a commit that referenced this pull request Feb 4, 2026
* Convert view mode HTML rendering from $effect to $derived

Replace the imperative $effect that sets innerHTML with a declarative
$derived.by() that computes the HTML string, letting Svelte handle
the DOM update via {@html viewHtml} in the template.

Changes:
- Add viewHtml $derived.by() that computes HTML from content, displayContent,
  metadata, and isEditing state
- Update template to use {@html viewHtml} inside the view div
- Remove the old $effect block that set viewElement.innerHTML imperatively

This eliminates one $effect block from base-node.svelte by converting
"derived state as effect" anti-pattern to proper declarative $derived.

The HTML computation logic is identical - markdown processing, blank line
handling, and leading/trailing newline preservation all work the same.

Closes #625

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Replace {@html} with ViewModeRenderer component for lint compliance

- Create ViewModeRenderer component that parses markdown into structured
  nodes and renders using Svelte components instead of raw HTML
- Supports bold, italic, strikethrough, inline code, line breaks, blank
  lines, and disableMarkdown mode
- Remove viewHtml $derived computation from base-node.svelte
- Replace {@html viewHtml} with <ViewModeRenderer> component
- Eliminates ESLint svelte/no-at-html-tags warning while maintaining
  identical visual output

This maintains the project's zero-tolerance policy for lint warnings
without using suppressions.

🤖 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
* Convert view mode HTML rendering from $effect to $derived

Replace the imperative $effect that sets innerHTML with a declarative
$derived.by() that computes the HTML string, letting Svelte handle
the DOM update via {@html viewHtml} in the template.

Changes:
- Add viewHtml $derived.by() that computes HTML from content, displayContent,
  metadata, and isEditing state
- Update template to use {@html viewHtml} inside the view div
- Remove the old $effect block that set viewElement.innerHTML imperatively

This eliminates one $effect block from base-node.svelte by converting
"derived state as effect" anti-pattern to proper declarative $derived.

The HTML computation logic is identical - markdown processing, blank line
handling, and leading/trailing newline preservation all work the same.

Closes #625

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Replace {@html} with ViewModeRenderer component for lint compliance

- Create ViewModeRenderer component that parses markdown into structured
  nodes and renders using Svelte components instead of raw HTML
- Supports bold, italic, strikethrough, inline code, line breaks, blank
  lines, and disableMarkdown mode
- Remove viewHtml $derived computation from base-node.svelte
- Replace {@html viewHtml} with <ViewModeRenderer> component
- Eliminates ESLint svelte/no-at-html-tags warning while maintaining
  identical visual output

This maintains the project's zero-tolerance policy for lint warnings
without using suppressions.

🤖 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
* Convert view mode HTML rendering from $effect to $derived

Replace the imperative $effect that sets innerHTML with a declarative
$derived.by() that computes the HTML string, letting Svelte handle
the DOM update via {@html viewHtml} in the template.

Changes:
- Add viewHtml $derived.by() that computes HTML from content, displayContent,
  metadata, and isEditing state
- Update template to use {@html viewHtml} inside the view div
- Remove the old $effect block that set viewElement.innerHTML imperatively

This eliminates one $effect block from base-node.svelte by converting
"derived state as effect" anti-pattern to proper declarative $derived.

The HTML computation logic is identical - markdown processing, blank line
handling, and leading/trailing newline preservation all work the same.

Closes #625

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Replace {@html} with ViewModeRenderer component for lint compliance

- Create ViewModeRenderer component that parses markdown into structured
  nodes and renders using Svelte components instead of raw HTML
- Supports bold, italic, strikethrough, inline code, line breaks, blank
  lines, and disableMarkdown mode
- Remove viewHtml $derived computation from base-node.svelte
- Replace {@html viewHtml} with <ViewModeRenderer> component
- Eliminates ESLint svelte/no-at-html-tags warning while maintaining
  identical visual output

This maintains the project's zero-tolerance policy for lint warnings
without using suppressions.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Convert view mode HTML rendering from $effect to $derived

1 participant