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

feat(frontend):add-loading-bar-when-intialize-project #193

Merged
merged 2 commits into from
Mar 22, 2025

Conversation

PengyuChen01
Copy link
Collaborator

@PengyuChen01 PengyuChen01 commented Mar 17, 2025

Summary by CodeRabbit

  • New Features
    • Enhanced the project loading experience with a dynamic progress indicator and a smooth success animation for when the project is ready.
    • Improved state handling ensures a seamless, responsive transition by automatically reflecting the current project status without delay.

Copy link
Contributor

coderabbitai bot commented Mar 17, 2025

Walkthrough

The changes in this pull request enhance the CodeEngine component by introducing new state variables and effects. These modifications manage project progress and completion, integrate a timer for progress updates, and utilize local storage to recall the project's completion status. Additionally, the component logic is refactored to conditionally skip polling when the project is complete and to render a success animation once project loading completes.

Changes

File Path Change Summary
frontend/src/components/chat/code-engine/code-engine.tsx Added new state variables (progress, estimateTime, timerActive, projectCompleted, isCompleting) and a reference (isProjectLoadedRef); modified and added useEffect hooks to check local storage for a saved project completion state and manage polling; refactored logic using useMemo for loader rendering and progress updates.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant CE as CodeEngine
    participant LS as LocalStorage
    U->>CE: Load Component
    CE->>LS: Check project completion flag
    LS-->>CE: Return completion status
    alt Project Completed
        CE->>CE: Update state to completed 
        CE->>U: Display success animation
    else Not Completed
        loop Polling Timer
            CE->>CE: Update progress and timer effects
        end
        CE->>U: Render loading indicator
    end
Loading

Poem

I'm a little rabbit with a techy beat,
Hopping through code with nimble feet!
New states and timers make my heart sing,
As the project loads, watch the progress swing.
With each update, success is neat—
A joyful hop in every byte so sweet!
🐰✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

frontend/src/components/chat/code-engine/code-engine.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the config "next/core-web-vitals" to extend from. Please check that the name of the config is correct.

The config "next/core-web-vitals" was referenced from the config file in "/frontend/.eslintrc.json".

If you still have problems, please stop by https://eslint.org/chat/help to chat with the team.

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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 generate docstrings to generate docstrings for this 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: 0

🧹 Nitpick comments (6)
frontend/src/components/chat/code-engine/code-engine.tsx (6)

42-50: New state variables for progress tracking look good

The state variables for tracking project loading progress are well-structured and serve a clear purpose in enhancing user experience during initialization.

A small improvement suggestion: consider translating the Chinese comments to English to maintain consistency with the rest of the codebase.

-  const [progress, setProgress] = useState(0); // 从0%开始
+  const [progress, setProgress] = useState(0); // Starting from 0%
-  const [estimateTime, setEstimateTime] = useState(6 * 60); // 保留估计时间
+  const [estimateTime, setEstimateTime] = useState(6 * 60); // Store estimated time
-  const initialTime = 6 * 60; // 初始总时间(6分钟)
+  const initialTime = 6 * 60; // Initial total time (6 minutes)
-  // 添加一个状态来跟踪完成动画
+  // Add a state to track completion animation
-  // 添加一个ref来持久跟踪项目状态,避免重新渲染时丢失
+  // Add a ref to persistently track project status, avoiding loss during re-renders

52-66: Good use of localStorage for persistence

Using localStorage to remember if a project has been completed is a good approach for improving user experience across sessions. The implementation handles potential localStorage errors gracefully.

One minor improvement: consider extracting the localStorage key to a constant for reusability.

+  // Create constant for localStorage key
+  const PROJECT_COMPLETED_KEY = `project-completed-${chatId}`;
+
   // 在组件挂载时从localStorage检查项目是否已完成
   useEffect(() => {
     try {
-      const savedCompletion = localStorage.getItem(
-        `project-completed-${chatId}`
-      );
+      const savedCompletion = localStorage.getItem(PROJECT_COMPLETED_KEY);
       if (savedCompletion === 'true') {
         setProjectCompleted(true);
         isProjectLoadedRef.current = true;

And then use this constant in the other places where this key is used.


335-370: Animation handling looks good, but consider refactoring timeout chaining

The implementation of the completion animation workflow is functional, but the nested setTimeout calls could be improved for better readability and maintenance.

Consider refactoring the nested timeouts using a more structured approach:

  useEffect(() => {
    if (!showLoader && timerActive) {
      setIsCompleting(true);
      setProgress(99);
-      const completionTimer = setTimeout(() => {
-        setProgress(100);
-        setTimeout(() => {
-          setTimerActive(false);
-          setIsCompleting(false);
-          setProjectCompleted(true);
-          // 同时更新ref以持久记住完成状态
-          isProjectLoadedRef.current = true;
-
-          // 可选:在完成时将状态保存到localStorage
-          try {
-            localStorage.setItem(`project-completed-${chatId}`, 'true');
-          } catch (e) {
-            // 忽略localStorage错误
-          }
-        }, 800);
-      }, 500);
+      // Stage 1: Show 99% progress
+      const stage1Timer = setTimeout(() => {
+        setProgress(100);
+      }, 500);
+      
+      // Stage 2: Complete the process
+      const stage2Timer = setTimeout(() => {
+        setTimerActive(false);
+        setIsCompleting(false);
+        setProjectCompleted(true);
+        isProjectLoadedRef.current = true;
+        
+        // Save completion status to localStorage
+        try {
+          localStorage.setItem(`project-completed-${chatId}`, 'true');
+        } catch (e) {
+          // Ignore localStorage errors
+        }
+      }, 1300); // 500ms + 800ms
-      return () => clearTimeout(completionTimer);
+      return () => {
+        clearTimeout(stage1Timer);
+        clearTimeout(stage2Timer);
+      };

348-353: Use the constant for localStorage key here as well

If you implement the suggested constant for the localStorage key, use it here too for consistency.

          // 可选:在完成时将状态保存到localStorage
          try {
-            localStorage.setItem(`project-completed-${chatId}`, 'true');
+            localStorage.setItem(PROJECT_COMPLETED_KEY, 'true');
          } catch (e) {
            // 忽略localStorage错误
          }

372-396: Good implementation of the timer logic

The timer logic is well-implemented. It calculates progress based on elapsed time and ensures the progress never exceeds 99% (reserving 100% for completion).

One minor optimization: consider using a callback ref for the interval to avoid creating a new interval on each render.

  useEffect(() => {
    let interval;

    if (timerActive) {
      interval = setInterval(() => {
        setEstimateTime((prevTime) => {
          if (prevTime <= 1) {
            return initialTime;
          }
          const elapsedTime = initialTime - prevTime + 1;
          const newProgress = Math.min(
            Math.floor((elapsedTime / initialTime) * 100),
            99
          );
          setProgress(newProgress);

          return prevTime - 1;
        });
      }, 1000);
    }

    return () => {
      if (interval) clearInterval(interval);
    };
-  }, [timerActive]);
+  }, [timerActive, initialTime]);

414-478: Loading UI enhancements look great

The loading UI has been significantly enhanced with:

  1. A progress bar showing completion percentage
  2. A success animation when the project is ready
  3. Different messages based on the loading state

These changes provide a much better user experience during project initialization.

The only minor issue is that the empty motion.p element at lines 471-477 doesn't seem to serve a purpose since it doesn't contain any text.

-              {/* 添加不同阶段的消息 */}
-              <motion.p
-                initial={{ opacity: 0 }}
-                animate={{ opacity: 1 }}
-                exit={{ opacity: 0 }}
-                transition={{ delay: 0.2 }}
-                className="text-sm text-center max-w-xs text-muted-foreground"
-              ></motion.p>
+              {/* If you want to show stage messages, uncomment and add content:
+              <motion.p
+                initial={{ opacity: 0 }}
+                animate={{ opacity: 1 }}
+                exit={{ opacity: 0 }}
+                transition={{ delay: 0.2 }}
+                className="text-sm text-center max-w-xs text-muted-foreground"
+              >
+                {progress < 30 ? "Setting up environment..." : 
+                 progress < 60 ? "Loading dependencies..." : 
+                 progress < 90 ? "Preparing workspace..." :
+                 progress === 100 ? "Ready to code!" : "Almost there..."}
+              </motion.p>
+              */}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 17ea0df and 3466687.

📒 Files selected for processing (1)
  • frontend/src/components/chat/code-engine/code-engine.tsx (5 hunks)
🔇 Additional comments (5)
frontend/src/components/chat/code-engine/code-engine.tsx (5)

70-73: Optimization to skip polling when project is completed

Good optimization to skip the polling operation when the project is already completed. This reduces unnecessary network requests and improves performance.

Don't forget to add projectCompleted to the dependency array of the useEffect hook, which you correctly did.

Also applies to: 99-99


83-86: Project completion detection looks good

The code correctly identifies when a project is successfully loaded by checking for the existence of project.projectPath and updates the state accordingly.


317-333: Well-structured showLoader logic

Moving the showLoader logic to a useMemo hook is a good refactoring choice. It properly considers the project completion state and will only recompute when its dependencies change.


398-402: Utility function for time formatting looks good

The formatTime function is well-implemented and properly formats seconds into a readable minutes:seconds format.


446-468: Progress bar implementation is well-done

The progress bar implementation using motion.div for animations is excellent. It provides a smooth visual feedback to users during loading and changes color when complete.

@Sma1lboy Sma1lboy merged commit 21b54ef into main Mar 22, 2025
3 of 4 checks passed
@Sma1lboy Sma1lboy deleted the feat-frontend-add-estimate-time-when-generate-proj branch March 22, 2025 21:36
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.

3 participants