Skip to content

JS to TS : simulator/src/tutorial.ts #438

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

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

nickhil-verma
Copy link

@nickhil-verma nickhil-verma commented Jan 25, 2025

Fixes #414

Describe the changes you have made in this PR -

Screenshots of the changes (If any) -

Note: Please check Allow edits from maintainers. if you would like us to assist in the PR.

Summary by CodeRabbit

  • New Features

    • Enhanced element panel display with improved name visibility
    • Added new setup and tutorial system for the simulator
    • Introduced comprehensive project management functions
  • Improvements

    • Refined user interface for element search and display
    • Streamlined project creation and loading processes
    • Implemented tutorial guide for new users
  • Changes

    • Removed unsaved changes warning when navigating away from the page
    • Added canvas resizing and environment setup functionality

Copy link
Contributor

coderabbitai bot commented Jan 25, 2025

Walkthrough

The pull request introduces TypeScript files to the simulator source directory, focusing on enhancing the project setup, tutorial system, and project management. New files like setup.ts and tutorials.ts are added to provide structured initialization, environment configuration, and a guided user tutorial experience. The changes include functions for canvas resizing, project data fetching, tutorial management, and environment setup, while also modifying the project creation logic in the existing project.ts file.

Changes

File Change Summary
src/components/Panels/ElementsPanel/ElementsPanel.vue Added <div> elements to display element names in search results and expansion panels with inline styling
src/simulator/src/data/project.ts Modified newProject function logic and commented out window.onbeforeunload event listener
src/simulator/src/setup.ts New file with setup functions for simulator environment, canvas resizing, and project data management
src/simulator/src/tutorials.ts New file implementing tutorial system with Driver library, defining tour steps and tutorial interactions

Assessment against linked issues

Objective Addressed Explanation
Typescript Integration [#414] Multiple TypeScript files added in /simulator/src directory

Sequence Diagram

sequenceDiagram
    participant User
    participant Setup
    participant ProjectData
    participant Tutorial
    
    User->>Setup: Initiate Application
    Setup->>ProjectData: Fetch Project Data
    Setup->>Setup: Configure Environment
    Setup->>Setup: Resize Canvas
    Setup->>Tutorial: Check Tutorial Status
    Tutorial-->>User: Show Tour Guide
Loading

Poem

🐰 Code hops, TypeScript springs to life,
Simulator's heart beats with new might!
Tutorials dance, projects take flight,
A rabbit's code, pure and bright!
Leap forward, technology's delight! 🚀

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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

netlify bot commented Jan 25, 2025

Deploy Preview for circuitverse ready!

Name Link
🔨 Latest commit a8f036b
🔍 Latest deploy log https://app.netlify.com/sites/circuitverse/deploys/679551328ea3310008b62c21
😎 Deploy Preview https://deploy-preview-438--circuitverse.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

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: 6

🧹 Nitpick comments (3)
src/simulator/src/tutorials.ts (1)

17-100: Consider standardizing element selectors.

The tour steps use a mix of ID selectors (#guide_1, #tabsBar) and class selectors (.guide_2, .quick-btn). Consider standardizing the approach to use either IDs or classes consistently for better maintainability.

src/simulator/src/data/project.ts (1)

173-174: Use URL constructor for better URL handling.

The URL construction could be improved using the URL API for better robustness:

-    const baseUrl = window.location.origin !== 'null' ? window.location.origin : 'http://localhost:4000'
-    window.location.assign(`${baseUrl}/simulatorvue/`)
+    const baseUrl = new URL(window.location.origin !== 'null' ? window.location.origin : 'http://localhost:4000');
+    baseUrl.pathname = '/simulatorvue/';
+    window.location.assign(baseUrl.toString());
src/simulator/src/setup.ts (1)

99-124: Modernize jQuery usage.

Consider replacing jQuery fade effects with native JavaScript or CSS transitions:

-            ($('.loadingIcon') as any).fadeOut();
+            const loadingIcon = document.querySelector('.loadingIcon');
+            if (loadingIcon) {
+                loadingIcon.classList.add('fade-out');
+                loadingIcon.addEventListener('transitionend', () => {
+                    loadingIcon.style.display = 'none';
+                });
+            }

Add corresponding CSS:

.fade-out {
    opacity: 0;
    transition: opacity 0.3s ease-out;
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6eae6ed and a8f036b.

📒 Files selected for processing (4)
  • src/components/Panels/ElementsPanel/ElementsPanel.vue (3 hunks)
  • src/simulator/src/data/project.ts (2 hunks)
  • src/simulator/src/setup.ts (1 hunks)
  • src/simulator/src/tutorials.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/simulator/src/setup.ts

[error] 38-38: Can't assign DPR because it's a constant

This is where the variable is defined as constant

Unsafe fix: Replace const with let if you assign it to a new value.

(lint/correctness/noConstAssign)

🔇 Additional comments (2)
src/simulator/src/tutorials.ts (1)

3-15: LGTM! Well-structured interfaces.

The interfaces Popover and TourStep are well-defined with clear types and optional properties.

src/components/Panels/ElementsPanel/ElementsPanel.vue (1)

128-131: Verify styling dependencies.

The code uses Bootstrap-like classes (overflow-hidden, text-nowrap, d-inline-block). Please ensure these classes are properly defined in your styling system or consider using Vue's native class bindings:

Alternative approach using Vue's native class bindings:

-                                <div class="overflow-hidden text-nowrap position-relative">
-                                    <p class=" d-inline-block">{{ element.name }}</p>
+                                <div :class="$style.elementName">
+                                    <p>{{ element.name }}</p>

Add scoped styles:

<style module>
.elementName {
    overflow: hidden;
    white-space: nowrap;
    position: relative;
}
.elementName p {
    display: inline-block;
}
</style>
✅ Verification successful

Bootstrap utility classes are properly configured ✓

The codebase has Bootstrap v4.6.1 properly installed as a dependency, so the utility classes used in the component are valid and will work as expected.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for Bootstrap or similar CSS framework dependencies
rg -l "bootstrap|tailwind" --type=json package.json

Length of output: 66


Script:

#!/bin/bash
# Display package.json content to check actual dependencies
cat package.json

Length of output: 2288

Comment on lines +142 to +147
export function showTourGuide(): void {
document.querySelector('.draggable-panel .maximize')?.dispatchEvent(new Event('click'));
animatedTourDriver.defineSteps(tour);
animatedTourDriver.start();
localStorage.setItem('tutorials_tour_done', 'true');
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for panel maximization.

The showTourGuide function should handle cases where the panel element is not found or the click event fails.

 export function showTourGuide(): void {
-    document.querySelector('.draggable-panel .maximize')?.dispatchEvent(new Event('click'));
+    const panel = document.querySelector('.draggable-panel .maximize');
+    if (!panel) {
+        console.error('Panel maximize button not found');
+        return;
+    }
+    try {
+        panel.dispatchEvent(new Event('click'));
+    } catch (error) {
+        console.error('Failed to maximize panel:', error);
+        return;
+    }
     animatedTourDriver.defineSteps(tour);
     animatedTourDriver.start();
     localStorage.setItem('tutorials_tour_done', 'true');
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export function showTourGuide(): void {
document.querySelector('.draggable-panel .maximize')?.dispatchEvent(new Event('click'));
animatedTourDriver.defineSteps(tour);
animatedTourDriver.start();
localStorage.setItem('tutorials_tour_done', 'true');
}
export function showTourGuide(): void {
const panel = document.querySelector('.draggable-panel .maximize');
if (!panel) {
console.error('Panel maximize button not found');
return;
}
try {
panel.dispatchEvent(new Event('click'));
} catch (error) {
console.error('Failed to maximize panel:', error);
return;
}
animatedTourDriver.defineSteps(tour);
animatedTourDriver.start();
localStorage.setItem('tutorials_tour_done', 'true');
}

Comment on lines +102 to +133
// Not used currently
export const tutorialWrapper = (): void => {
const panelHighlight = new Driver();
document.querySelector('.panelHeader')?.addEventListener(
'click',
(e: MouseEvent) => {
if (localStorage.getItem('tutorials') === 'next') {
panelHighlight.highlight({
element: '#guide_1',
showButtons: false,
popover: {
title: 'Here are the elements',
description:
'Select any element by clicking on it & then click anywhere on the grid to place the element.',
position: 'right',
offset:
(e.target as HTMLElement).nextElementSibling?.clientHeight! +
(e.target as HTMLElement).offsetTop -
45,
},
});
localStorage.setItem('tutorials', 'done');
}
},
{
once: true,
}
);
document.querySelector('.icon')?.addEventListener('click', () => {
panelHighlight.reset(true);
});
};
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove unused code.

The tutorialWrapper function is marked as "Not used currently". Consider removing it to maintain code cleanliness.

Simplify offset calculation.

The offset calculation is complex and hard to maintain:

-                    offset:
-                        (e.target as HTMLElement).nextElementSibling?.clientHeight! +
-                        (e.target as HTMLElement).offsetTop -
-                        45,
+                    offset: calculateOffset(e.target as HTMLElement),

Consider extracting it into a separate helper function for better readability and maintainability.

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +123 to +139
// window.onbeforeunload = async function () {
// if (projectSaved || embed) return

if (!checkToSave()) return
// if (!checkToSave()) return

alert(
'You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?'
)
// await confirmSingleOption(
// 'You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?'
// )
const data = await generateSaveData('Untitled')
const stringData = JSON.stringify(data)
localStorage.setItem('recover', stringData)
// eslint-disable-next-line consistent-return
return 'Are u sure u want to leave? Any unsaved changes may not be recoverable'
}
// alert(
// 'You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?'
// )
// // await confirmSingleOption(
// // 'You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?'
// // )
// const data = await generateSaveData('Untitled')
// const stringData = JSON.stringify(data)
// localStorage.setItem('recover', stringData)
// // eslint-disable-next-line consistent-return
// return 'Are u sure u want to leave? Any unsaved changes may not be recoverable'
// }
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

🛠️ Refactor suggestion

Reconsider removing the page leave warning

While there is a recovery mechanism in place, removing the onbeforeunload handler eliminates the primary way to prevent accidental data loss. The current recovery system only helps after the fact, but doesn't prevent users from accidentally navigating away with unsaved changes.

  • Consider keeping or reimplementing the onbeforeunload handler to maintain better user experience
  • If removal is intentional, ensure users are clearly informed about the auto-recovery feature
  • The commented code should still be removed from the codebase, but the functionality should be preserved
🔗 Analysis chain

Remove commented code.

Instead of keeping commented code, consider removing it entirely and preserving it in version control history if needed.

Verify impact on user experience.

The removal of the onbeforeunload handler means users won't be warned about unsaved changes when leaving the page. Please confirm if this is intentional and if there are alternative measures to prevent data loss.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any other implementations of onbeforeunload or similar data loss prevention
rg -l "onbeforeunload|beforeunload|unload" --type ts --type vue

Length of output: 93


Script:

#!/bin/bash
# Search in TypeScript files
echo "Searching TypeScript files..."
rg -l "onbeforeunload|beforeunload|unload|unsaved|warning" --type ts

# Search in .vue files directly
echo "Searching Vue files..."
find . -name "*.vue" -type f -exec rg -l "onbeforeunload|beforeunload|unload|unsaved|warning" {} \;

# Search for save-related functionality
echo "Searching for save-related functionality..."
rg -l "saveProject|saveTo|autoSave" --type ts
find . -name "*.vue" -type f -exec rg -l "saveProject|saveTo|autoSave" {} \;

Length of output: 743


Script:

#!/bin/bash
# Check content of setup.ts for related functionality
echo "Content of setup.ts:"
rg -A 5 -B 5 "onbeforeunload|beforeunload|unload|unsaved|warning" src/simulator/src/setup.ts

# Also check the Vue components for context
echo "Content of relevant Vue components:"
find . -name "*.vue" -type f -exec rg -A 5 -B 5 "onbeforeunload|beforeunload|unload|unsaved|warning" {} \;

Length of output: 4640

Comment on lines +36 to +39
const DPR = window.devicePixelRatio || 1;
if (lightMode) {
DPR = 1;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix const reassignment of DPR.

The DPR variable is declared as const but reassigned, which is incorrect:

-    const DPR = window.devicePixelRatio || 1;
-    if (lightMode) {
-        DPR = 1;
-    }
+    let DPR = lightMode ? 1 : (window.devicePixelRatio || 1);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const DPR = window.devicePixelRatio || 1;
if (lightMode) {
DPR = 1;
}
let DPR = lightMode ? 1 : (window.devicePixelRatio || 1);
🧰 Tools
🪛 Biome (1.9.4)

[error] 38-38: Can't assign DPR because it's a constant

This is where the variable is defined as constant

Unsafe fix: Replace const with let if you assign it to a new value.

(lint/correctness/noConstAssign)

Comment on lines +156 to +162
function showTour(): void {
if (!localStorage.tutorials_tour_done && !embed) {
setTimeout(() => {
showTourGuide();
}, 2000);
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add cleanup for setTimeout.

The setTimeout should be cleaned up to prevent memory leaks:

 function showTour(): void {
     if (!localStorage.tutorials_tour_done && !embed) {
-        setTimeout(() => {
+        const timeoutId = setTimeout(() => {
             showTourGuide();
         }, 2000);
+        // Add cleanup method to clear timeout
+        return () => clearTimeout(timeoutId);
     }
 }

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +40 to +49
const width = document.getElementById('simulationArea')?.clientWidth! * DPR;
let height;
if (!embed) {
height =
(document.body.clientHeight -
document.getElementById('toolbar')?.clientHeight!) *
DPR;
} else {
height = document.getElementById('simulation')?.clientHeight! * DPR;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add null checks for DOM elements.

Replace non-null assertions with proper null checks:

-    const width = document.getElementById('simulationArea')?.clientWidth! * DPR;
+    const simulationArea = document.getElementById('simulationArea');
+    if (!simulationArea) {
+        console.error('Simulation area not found');
+        return;
+    }
+    const width = simulationArea.clientWidth * DPR;

Committable suggestion skipped: line range outside the PR's diff.

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.

Typescript Integration in /simulator/src files
1 participant