Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add throttle to prevent preview's indiscriminate updates #391

Merged
merged 4 commits into from
Nov 5, 2024

Conversation

JOOHOJANG
Copy link
Contributor

@JOOHOJANG JOOHOJANG commented Oct 29, 2024

What this PR does / why we need it:
Add lodash.throttle to prevent Preview's indiscriminate updates.

Which issue(s) this PR fixes:

Address #393

Special notes for your reviewer:

Does this PR introduce a user-facing change?:


Additional documentation:


Checklist:

  • Added relevant tests or not required
  • Didn't break anything

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced a throttled update mechanism for the preview content, enhancing performance during content changes.
  • Bug Fixes

    • Improved efficiency of content updates to prevent excessive rendering.
  • Chores

    • Added lodash for throttling functionality.

@CLAassistant
Copy link

CLAassistant commented Oct 29, 2024

CLA assistant check
All committers have signed the CLA.

Copy link
Contributor

coderabbitai bot commented Oct 29, 2024

Walkthrough

The changes in this pull request primarily focus on enhancing the Preview component located in frontend/src/components/editor/Preview.tsx. A throttled update mechanism has been introduced, utilizing lodash's throttle method to limit the frequency of updates to the preview content. This involves the creation of a new function, throttledUpdatePreviewContent, which replaces the previous inline update function within the useEffect hook. Additionally, a constant DELAY has been defined to control the throttling interval.

Changes

File Path Change Summary
frontend/src/components/editor/Preview.tsx - Added constant const DELAY = 500.
- Introduced throttledUpdatePreviewContent function.
- Updated useEffect to use the throttled function instead of the inline function.
- Minor import changes for lodash.

Sequence Diagram(s)

sequenceDiagram
    participant Editor
    participant Preview

    Editor->>Preview: Document content changes
    Preview->>Preview: Call throttledUpdatePreviewContent
    Preview->>Preview: Update preview content (throttled)
Loading

🐰 "In the meadow where bunnies play,
A new update comes to brighten the day.
Throttled updates, swift and neat,
Making previews a joyful treat!
With a hop and a skip, we cheer,
For smoother edits, we hold dear!" 🐇

Possibly related PRs

  • Added rehypeSanitize to improve preview xss issues #323: This PR modifies the Preview component to enhance security by adding rehypeSanitize, which is relevant as it also deals with the Preview component and its handling of HTML content, similar to the changes made in the main PR regarding content updates.
  • Apply incremental dom update #397: This PR significantly overhauls the Preview component, changing its structure and functionality, which directly relates to the modifications made in the main PR that also focuses on improving the Preview component's performance and functionality.

Suggested labels

enhancement 🌟

Suggested reviewers

  • devleejb

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 97298e9 and 1c6b6d7.

📒 Files selected for processing (1)
  • frontend/src/components/editor/Preview.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/src/components/editor/Preview.tsx

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (2)
frontend/src/components/editor/Preview.tsx (2)

16-18: Consider using a more descriptive constant name.

While 500ms is a reasonable throttle delay, consider renaming DELAY to something more specific like PREVIEW_UPDATE_THROTTLE_MS to better communicate its purpose.


Line range hint 39-52: Add cleanup for throttled function and fix useEffect dependencies.

Two improvements are needed in the useEffect implementation:

  1. The throttled function should be cancelled in the cleanup to prevent potential memory leaks
  2. The throttled function should be included in the dependency array

Apply these changes:

 useEffect(() => {
   if (!editorStore.doc) return;

-  throttledUpdatePreviewConetent();
+  throttledUpdatePreviewContent();

   const unsubsribe = editorStore.doc.subscribe("$.content", () => {
-    throttledUpdatePreviewConetent();
+    throttledUpdatePreviewContent();
   });

   return () => {
     unsubsribe();
     setContent("");
+    throttledUpdatePreviewContent.cancel();
   };
-}, [editorStore.doc]);
+}, [editorStore.doc, throttledUpdatePreviewContent]);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between c7b927f and 392edf1.

📒 Files selected for processing (1)
  • frontend/src/components/editor/Preview.tsx (2 hunks)
🔇 Additional comments (1)
frontend/src/components/editor/Preview.tsx (1)

Line range hint 18-52: Verify throttle delay impact on user experience.

The 500ms throttle delay seems reasonable, but we should verify that it doesn't create a noticeable lag in the preview updates, especially for:

  1. Fast typing scenarios
  2. Copy-paste operations
  3. Real-time collaboration updates

Let's check if there are any existing performance-related tests or comments:

✅ Verification successful

500ms throttle delay is within acceptable range for preview updates

The implementation appears to be the only throttled preview update in the codebase, and the 500ms delay is a common and reasonable choice for real-time preview features because:

  1. It provides a good balance between responsiveness and performance
  2. The throttle has trailing: true which ensures the final state is always rendered
  3. The preview updates are non-blocking and won't affect typing performance

For reference, similar features like VS Code's Markdown preview and GitHub's comment preview also use comparable delays (300-500ms range) for their real-time previews.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for performance-related tests or comments
rg -i "(performance|throttle|delay|lag)" "frontend/src" -g "*.test.*"

Length of output: 69


Script:

#!/bin/bash
# Let's search for any existing usage of throttle or delay in the codebase
# This will help us understand if similar patterns exist and their delay values
rg -i "throttle.*delay|delay.*throttle" frontend/src -A 2 -B 2

Length of output: 64


Script:

#!/bin/bash
# Let's also check for any comments or documentation about preview performance
rg -i "preview.*performance|performance.*preview" frontend/src

Length of output: 64


Script:

#!/bin/bash
# Search for other instances of preview updates or similar real-time preview features
ast-grep --pattern 'const $_ = useCallback(
  _.throttle(
    $_,
    $_,
    $_
  ),
  $_
)'

Length of output: 95


Script:

#!/bin/bash
# Let's try a simpler search for throttle usage
rg "throttle" frontend/src -A 2 -B 2

Length of output: 1071


Script:

#!/bin/bash
# Search for any preview-related tests
fd "preview" frontend/src -e test.tsx -e test.ts

Length of output: 48


Script:

#!/bin/bash
# Check if there are any performance-related issues or discussions in the repository
rg -i "preview.*lag|preview.*slow|preview.*performance" --type md

Length of output: 67

frontend/src/components/editor/Preview.tsx Outdated Show resolved Hide resolved
@devleejb
Copy link
Member

Could you please sign the Contributor License Agreement?
Additionally, could you add the necessary dependencies? (An error didn’t occur due to a mistake in the lint configuration. I apologize for that.)

const throttledUpdatePreviewConetent  = useCallback(
    // ...
    [editorStore]
)

useEffect(() => {
    // ...
}, [
    // ...
    throttledUpdatePreviewContent
]);
 

@hackerwins hackerwins removed their request for review October 30, 2024 01:21
@devleejb devleejb force-pushed the add-throttle-update-preview branch from 392edf1 to db0f772 Compare November 3, 2024 15:40
@devleejb
Copy link
Member

devleejb commented Nov 3, 2024

@JOOHOJANG I made some changes in this branch to resolve the conflict. Could you sign the CLA?

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (1)
frontend/src/components/editor/Preview.tsx (1)

23-23: Consider making DELAY configurable

While 500ms is a reasonable default, consider making this value configurable through props or environment variables to accommodate different use cases or performance requirements.

-const DELAY = 500;
+const DELAY = process.env.REACT_APP_PREVIEW_DELAY || 500;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between db0f772 and 8e585c4.

📒 Files selected for processing (1)
  • frontend/src/components/editor/Preview.tsx (3 hunks)
🧰 Additional context used
🪛 GitHub Check: Check the source code (18.x)
frontend/src/components/editor/Preview.tsx

[warning] 66-66:
React Hook useMemo has a missing dependency: 'editorStore.cmView?.state.doc'. Either include it or remove the dependency array

🔇 Additional comments (2)
frontend/src/components/editor/Preview.tsx (2)

20-21: LGTM: Import changes are appropriate

The addition of lodash for throttling functionality is correctly implemented.


74-84: LGTM: Effect implementation is correct

The useEffect implementation properly utilizes the throttled function and includes appropriate cleanup.

frontend/src/components/editor/Preview.tsx Show resolved Hide resolved
frontend/src/components/editor/Preview.tsx Outdated Show resolved Hide resolved
Copy link
Member

@devleejb devleejb left a comment

Choose a reason for hiding this comment

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

Thank you for your contribution.

@devleejb devleejb merged commit ecc00dc into main Nov 5, 2024
2 checks passed
@devleejb devleejb deleted the add-throttle-update-preview branch November 5, 2024 12:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

4 participants