Skip to content

refactor(dev): modularize Preview architecture and enhance persistence for Preview & StreamPreview - #185

Merged
Aarebecca merged 7 commits into
antvis:mainfrom
xxMudCloudxx:refactor/dev-preview-state-persistence
Jan 27, 2026
Merged

Aarebecca merged 7 commits into
antvis:mainfrom
xxMudCloudxx:refactor/dev-preview-state-persistence

Conversation

@xxMudCloudxx

Copy link
Copy Markdown
Contributor

📝 Description

Motivation:

During the process of development or debugging, while observing the rendered SVG results in these two components, any local code modification triggers a page refresh or Hot Module Replacement (HMR). This previously caused all test data—especially manually edited JSON in the editor—to be reset to defaults. Developers were forced to re-input or re-paste their test cases repeatedly just to verify a small visual change in the SVG.

Key Changes:

  1. Enhanced Persistence :

    • Added logic to persist the raw JSON string from the editor to localStorage.
    • Implemented a hydration check to restore this custom content upon mounting, ensuring your test data survives refreshes.
  2. Architectural Refactor :

    The Preview.tsx has been decomposed into four specialized hooks to separate concerns:

    • usePreviewSettings (Configuration):
      • Role: Encapsulates the state management for form controls (Template selector, Theme, Primary Color, Palette).
      • Change: Moved the existing localStorage logic for these settings into this hook and added a hydration barrier to ensure SSR safety.
    • usePreviewData (Data & Editor):
      • Role: Manages the JSON editor's state.
      • Change: New capability. Unlike the original code which only tracked the selected DataKey, this hook now tracks the actual text content. It implements debouncing (to prevent render lag) and manages the specific storage for custom user input.
    • usePreviewInteractions (Coordination):
      • Role: The "Brain" that connects Settings and Data.
      • Change: Handles the business logic that was previously mixed in the main component, such as "When Template changes -> Reset Data" or "When Preset changes -> Update Editor". It ensures the new persistence logic works smoothly with the existing preset logic.
    • useKeyboardNavigation (UX):
      • Role: Handles the arrow-key shortcuts.
      • Change: Extracted the existing useEffect event listener logic into a standalone hook to declutter the main component.

the result:

Preview
StreamPreview

- Fix Hydration Mismatch: move localStorage read from useState init to useEffect
- Add isHydrated state to ensure consistent server/client initial render
- Fix state initialization order dependency in Preview.tsx
- Remove unused 'data' dependency from templateConfig useMemo
- Add preset key validation in StreamPreview to prevent crashes from tampered localStorage
- Improve reset button defensive code with nullish coalescing fallback

Files:
- dev/src/Preview.tsx
- dev/src/StreamPreview.tsx
Move form state initialization (template, data, theme, etc.) from
direct localStorage read to useEffect hydration pattern, ensuring
SSR/CSR consistency.
- Extract configuration state to usePreviewSettings
- Extract data editor state to usePreviewData
- Extract coordination logic to usePreviewInteractions
- Refactor Preview.tsx to use separate hooks instead of monolithic logic
- Remove complex useEffect based hydration from main component
- Improve code readability and separation of concerns
… logic

- fix(hooks): ensure data resets when switching templates even if data key remains unchanged
- refactor(preview): extract keyboard navigation logic to useKeyboardNavigation hook
- refactor(hooks): remove silent DATASET fallback from usePreviewData to expose parse errors
- chore(preview): replace inline useEffect with useKeyboardNavigation in Preview.tsx
- Fix keyboard navigation hook to ignore arrow key events when focusing on inputs or editors
- Add missing dependencies to usePreviewInteractions initialization effect to prevent stale closures
- Improve interaction stability between Monaco Editor and global shortcuts
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @xxMudCloudxx, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the developer experience and maintainability of the preview components. By modularizing the Preview component's logic into dedicated hooks and implementing robust persistence mechanisms for user-defined data and settings in both Preview and StreamPreview, it addresses the frustration of losing work during development cycles. The changes ensure that user configurations and custom inputs are retained across page reloads, making the development process smoother and more efficient.

Highlights

  • Modular Architecture: The Preview.tsx component has been refactored into four specialized custom hooks (usePreviewSettings, usePreviewData, usePreviewInteractions, useKeyboardNavigation) to separate concerns and improve maintainability.
  • Enhanced Persistence: Both Preview and StreamPreview components now persist user-edited data (JSON string, code) and settings (template, theme, colors) to localStorage, preventing data loss on page refreshes or Hot Module Replacement (HMR).
  • Improved Developer Experience: Developers no longer need to repeatedly re-input or re-paste test data after code modifications, significantly streamlining the development and debugging workflow.
  • SSR Safety: All localStorage operations are now guarded with typeof window === 'undefined' checks to ensure Server-Side Rendering (SSR) compatibility.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This is an excellent refactoring that greatly improves the architecture of the preview pages. By modularizing the logic into well-defined custom hooks (usePreviewSettings, usePreviewData, usePreviewInteractions, useKeyboardNavigation), the Preview component has become much cleaner and easier to maintain. The introduction of state persistence using localStorage is a significant enhancement to the developer experience, directly addressing the motivation for this change. The implementation is robust, handling SSR safety, debouncing for performance, and providing clear user feedback through 'dirty' and 'saved' states. I have one suggestion for StreamPreview.tsx to further improve consistency and performance by extracting inline event handlers. Overall, this is a high-quality contribution.

Comment thread dev/src/StreamPreview.tsx Resolved
…llback at the top level of the StreamPreview component.
@Aarebecca
Aarebecca merged commit 15c3ee2 into antvis:main Jan 27, 2026
@Aarebecca

Copy link
Copy Markdown
Contributor

@xxMudCloudxx You did a great job, that will be very helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants