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

JS to TS : simulator/src/app.ts #426

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

Conversation

nickhil-verma
Copy link

@nickhil-verma nickhil-verma commented Jan 23, 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

Release Notes

  • New Features

    • Enhanced element display in the Elements Panel with improved name visibility and styling
    • Added TypeScript interfaces for better type safety in circuit simulation
  • Refactoring

    • Replaced JavaScript loading module with TypeScript implementation
    • Updated project management logic for handling new projects
  • Improvements

    • Streamlined circuit loading and initialization process
    • Simplified project creation workflow

Copy link
Contributor

coderabbitai bot commented Jan 23, 2025

Walkthrough

This pull request focuses on migrating simulator-related files from JavaScript to TypeScript and refactoring the project's data loading and management components. The changes include converting load.js to load.ts, adding new TypeScript interfaces in app.ts, and modifying project management logic in project.ts. Additionally, the ElementsPanel.vue component receives UI improvements for displaying element names more clearly.

Changes

File Change Summary
src/components/Panels/ElementsPanel/ElementsPanel.vue Added new <div> elements to display element names with improved styling in search results
src/simulator/src/app.ts Introduced new TypeScript interfaces: Device, Connector, and Circuit; converted js variable to a typed constant
src/simulator/src/data/load.js Deleted JavaScript file with loading-related functions
src/simulator/src/data/load.ts New TypeScript file replacing load.js with enhanced type safety and loading functions
src/simulator/src/data/project.ts Modified project creation logic and commented out onbeforeunload event handler

Assessment against linked issues

Objective Addressed Explanation
Typescript Integration in /simulator/src files [#414]

Possibly related PRs

Poem

🐰 In circuits and code, a rabbit's delight,
TypeScript weaves types with algorithmic might
Elements dance, interfaces gleam bright
From JavaScript's shadows to a type-safe height
A digital warren of logic takes flight! 🖥️

✨ 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 23, 2025

Deploy Preview for circuitverse ready!

Name Link
🔨 Latest commit aedba88
🔍 Latest deploy log https://app.netlify.com/sites/circuitverse/deploys/67920175a88257000890eae1
😎 Deploy Preview https://deploy-preview-426--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 (6)
src/simulator/src/data/project.ts (1)

158-178: Refactor: Improve error handling and separation of concerns.

The function mixes multiple responsibilities and lacks proper error handling for asynchronous operations.

Consider breaking down the function into smaller, focused functions:

async function confirmNewProject(verify: boolean): Promise<boolean> {
    if (!verify && !projectSaved && checkToSave()) {
        return confirmOption(
            'What you like to start a new project? Any unsaved changes will be lost.'
        )
    }
    return true
}

async function resetProjectState(): Promise<void> {
    await clearProject()
    localStorage.removeItem('recover')
    setProjectName(undefined)
    projectId = generateId()
}

async function navigateToNewProject(): Promise<void> {
    const baseUrl = window.location.origin !== 'null' ? window.location.origin : process.env.BASE_URL || 'http://localhost:4000'
    const url = new URL('/simulatorvue/', baseUrl)
    window.location.assign(url.toString())
}

export async function newProject(verify: boolean): Promise<void> {
    try {
        const confirmed = await confirmNewProject(verify)
        if (!confirmed) return

        await resetProjectState()
        await navigateToNewProject()
        showMessage('New Project has been created!')
    } catch (error) {
        showError('Failed to create new project')
        throw error
    }
}
src/simulator/src/data/load.ts (1)

25-27: Replace 'any' types with specific type definitions

Currently, the types CircuitElement and Scope are defined as any. To enhance type safety and leverage TypeScript's benefits, consider replacing any with specific type definitions.

src/simulator/src/app.ts (2)

5-5: Consider using an enum for 'type' in 'Device' interface

Currently, the type property in the Device interface is defined as a union of string literals 'Input' | 'Output' | 'Memory'. Consider using an enum to define device types for better scalability and maintenance.

Example:

enum DeviceType {
    Input = 'Input',
    Output = 'Output',
    Memory = 'Memory',
}

interface Device {
    type: DeviceType;
    // rest of the properties...
}

Line range hint 43-248: Variable 'js' is defined but not used

The constant js of type Circuit is defined but not used within this file. This may lead to unused variable warnings and indicates potential dead code.

If js is needed in future implementations, consider using it within this file. Otherwise, remove it to clean up the code.

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

43-43: Display element names in search results for consistency

In the search results, the element names are not displayed under the images. For consistency and better user experience, consider adding the element names similar to how it's done in the main panel.

Add the following code after the image tag in the search results section:

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

81-81: Display element names in search categories for consistency

In the expanded search categories, the element names are not displayed under the images. To maintain consistency across the UI, consider adding the element names.

Add the following code after the image tag in the search categories section:

<div class="overflow-hidden text-nowrap position-relative">
    <p class="d-inline-block">{{ element.name }}</p>
</div>
📜 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 aedba88.

📒 Files selected for processing (5)
  • src/components/Panels/ElementsPanel/ElementsPanel.vue (3 hunks)
  • src/simulator/src/app.ts (2 hunks)
  • src/simulator/src/data/load.js (0 hunks)
  • src/simulator/src/data/load.ts (1 hunks)
  • src/simulator/src/data/project.ts (2 hunks)
💤 Files with no reviewable changes (1)
  • src/simulator/src/data/load.js
🔇 Additional comments (1)
src/components/Panels/ElementsPanel/ElementsPanel.vue (1)

128-130: Great addition of element names in the main panel

Displaying the element names under the images in the main elements panel enhances usability and improves the user interface.

Comment on lines +173 to +174
const baseUrl = window.location.origin !== 'null' ? window.location.origin : 'http://localhost:4000'
window.location.assign(`${baseUrl}/simulatorvue/`)
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

Security & Reliability: Improve URL handling.

The URL construction has potential issues:

  1. Hardcoded localhost URL could cause problems in different environments
  2. Direct string concatenation for URLs is error-prone

Consider this safer approach:

- const baseUrl = window.location.origin !== 'null' ? window.location.origin : 'http://localhost:4000'
- window.location.assign(`${baseUrl}/simulatorvue/`)
+ const baseUrl = window.location.origin !== 'null' ? window.location.origin : process.env.BASE_URL || 'http://localhost:4000'
+ const url = new URL('/simulatorvue/', baseUrl)
+ window.location.assign(url.toString())

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.

⚠️ Potential issue

Critical: Restore unsaved changes protection mechanism.

Commenting out the window.onbeforeunload handler removes critical user experience safeguards:

  1. Users can now lose unsaved work without warning
  2. The automatic recovery mechanism is disabled
  3. This contradicts standard web practices for handling unsaved changes

Consider this improved implementation:

- // window.onbeforeunload = async function () {
+ window.onbeforeunload = function (e: BeforeUnloadEvent) {
+     if (projectSaved || embed) return undefined
+     
+     if (!checkToSave()) return undefined
+     
+     // Modern browsers require us to set returnValue
+     const message = 'You have unsaved changes. Are you sure you want to leave?'
+     e.returnValue = message
+     
+     // Asynchronously save recovery data
+     void (async () => {
+         const data = await generateSaveData('Untitled')
+         localStorage.setItem('recover', JSON.stringify(data))
+     })()
+     
+     return message
+ }

This implementation:

  • Uses TypeScript types
  • Follows modern browser standards
  • Handles async operations correctly
  • Preserves the recovery mechanism
📝 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
// 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'
// }
window.onbeforeunload = function (e: BeforeUnloadEvent) {
if (projectSaved || embed) return undefined
if (!checkToSave()) return undefined
// Modern browsers require us to set returnValue
const message = 'You have unsaved changes. Are you sure you want to leave?'
e.returnValue = message
// Asynchronously save recovery data
void (async () => {
const data = await generateSaveData('Untitled')
localStorage.setItem('recover', JSON.stringify(data))
})()
return message
}

Comment on lines +46 to +47
obj.labelDirection =
data.labelDirection || oppositeDirection[fixDirection[obj.direction]];
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

Undefined reference to 'fixDirection'

The variable fixDirection is not defined or imported, but it's used in oppositeDirection[fixDirection[obj.direction]]. This will cause a runtime error.

Ensure that fixDirection is defined or imported before using it. If it's meant to be a method, consider calling it appropriately.

Comment on lines +173 to +175
if (!data) {
setProjectName(__projectName);
return;
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

Undefined variable '__projectName'

The variable __projectName is used but not defined or imported in this file. This will lead to a runtime error when setProjectName(__projectName) is called.

Define or import __projectName before using it, or ensure it's available in the current scope.

Comment on lines +198 to +202
if (embed) {
globalScope.centerFocus(true);
} else {
globalScope.centerFocus(false);
}
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

Undefined variable 'embed'

The variable embed is used in the conditional statement but is not defined or imported in this file. This will cause a runtime error.

Define or import embed before using it, or check if it's intended to be a global variable accessible in this context.

data.x,
data.y,
scope,
...(data.customData.constructorParamaters || [])
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

Correct typo in 'constructorParamaters'

There's a typo in 'constructorParamaters'. It should be 'constructorParameters'.

Apply this diff to correct the typo:

-    ...(data.customData.constructorParamaters || [])
+    ...(data.customData.constructorParameters || [])
📝 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
...(data.customData.constructorParamaters || [])
...(data.customData.constructorParameters || [])

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