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

Combining Vue Simulator Versioning PRs #337

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

Conversation

aryanndwi123
Copy link
Contributor

@aryanndwi123 aryanndwi123 commented Jul 16, 2024

Fixes #372

Describe the changes you have made in this PR -

Combining all the PRs related to Vue simulator versioning

Screenshots of the changes (If any) -

#332 - Enable the Main simulator to dynamically load the Vue simulator.

#327 - build: script modification for different builds.

#327 - chore: adding versioned directory(v0 and v1).

Key Achievements:

  • Versioning Directories:

    • Implemented separate version-specific directories (v0, v1, etc.) to manage multiple versions of the Vue simulator, allowing for independent development and maintenance of each version.
  • Modifying the Build Script:

    • Customized the build process by creating version-specific Vite configuration files (vite.config.v0.ts, vite.config.v1.ts) to ensure proper building and output management for each simulator version.
  • Bash Script for Multi-Version Builds:

    • Developed a bash script to automate the building of multiple simulator versions, making it easier to manage and deploy all versions simultaneously.
  • Hot-Swapping Vue Simulator Versions:

    • Enabled dynamic version switching of the Vue simulator from the main CircuitVerse repository based on the simver query parameter, allowing users to seamlessly switch between different versions.
  • Dynamic Script Injection:

    • Implemented an HTML script injection mechanism using createHtmlPlugin in Vite, ensuring that the correct version-specific script tags are dynamically inserted into the index.html during the build process.
  • Storing Simulator Version in Circuit Data:

    • Added a field in the circuit_data to store the simulator version, enabling circuits to be loaded with the appropriate simulator version based on their creation version.
  • Redirecting to Correct Simulator Version:

    • Implemented logic to redirect users to the correct simulator version based on the stored simulatorVersion in circuit_data, ensuring compatibility and functionality.
  • Creation of index-cv.html:

    • Created a separate index-cv.html to serve as the entry point for the main repository, while the default index.html continues to serve the cv-frontend-vue repository, maintaining stability during development.
  • Setting v0 as Default Simulator:

    • Configured the development environment to use v0 as the default simulator version, ensuring consistency during the development process.
  • Fixing Circuit Preview Image Issue:

    • Resolved the bug where circuit preview images were not displaying in the Vue simulator by adding image attachment functionality during the circuit creation process.
  • Version-Specific Links for Launching Circuits:

    • Updated the launch button links to dynamically include the correct simulator version, ensuring users are directed to the appropriate version of the simulator when accessing a circuit.

Future Work:

  • Writing comprehensive tests for all Ruby on Rails code.
  • Designing and implementing UI/UX for version switching.
  • Creating a dialog box to appear when switching versions.
  • Enabling embed mode for circuits of different versions.
  • Automatically configuring Netlify deployments to point to /simulatorvue

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

Summary by CodeRabbit

  • New Features

    • Introduced a dialog component for opening offline projects, allowing users to select from a list and delete projects.
    • Added functionality to handle version mismatches when opening projects, providing users with clear options to continue or cancel.
  • Bug Fixes

    • Resolved issues related to project selection and version compatibility notifications.
  • Documentation

    • Updated documentation to include the new offline project management features.
  • Style

    • Enhanced styling for the new dialog components to improve user interaction.

Copy link

netlify bot commented Jul 16, 2024

Deploy Preview for circuitverse ready!

Name Link
🔨 Latest commit e56653d
🔍 Latest deploy log https://app.netlify.com/sites/circuitverse/deploys/671bb22216a125000834fb0b
😎 Deploy Preview https://deploy-preview-337--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

@github-advanced-security github-advanced-security bot left a comment

Choose a reason for hiding this comment

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

ESLint found more than 20 potential problems in the proposed changes. Check the Files changed tab for more details.

// const { activeCircuit } = toRefs(simulatorStore)
name = name || 'Untitled'
name = stripTags(name)
scopeList[id].name = name

Check warning

Code scanning / CodeQL

Prototype-polluting assignment Medium

This assignment may alter Object.prototype if a malicious '__proto__' string is injected from
user controlled input
.
scope.backups[scope.backups.length - 1] !== backup
) {
scope.backups.push(backup)
scope.history = []

Check warning

Code scanning / CodeQL

Prototype-polluting assignment Medium

This assignment may alter Object.prototype if a malicious '__proto__' string is injected from
user controlled input
.
) {
scope.backups.push(backup)
scope.history = []
scope.timeStamp = new Date().getTime()

Check warning

Code scanning / CodeQL

Prototype-polluting assignment Medium

This assignment may alter Object.prototype if a malicious '__proto__' string is injected from
user controlled input
.
*/
function loadModule(data, scope) {
// Create circuit element
var obj = new modules[rectifyObjectType(data.objectType)](

Check failure

Code scanning / CodeQL

Unvalidated dynamic method call High

Invocation of method with
user-controlled
name may dispatch to unexpected target and cause an exception.
@JoshVarga JoshVarga added the GSOC'24 PR's for GSoC'24 label Jul 28, 2024
Copy link
Contributor

coderabbitai bot commented Sep 1, 2024

Walkthrough

The changes introduce a new Vue component, OpenOffline.vue, which provides a dialog for managing offline projects within a simulator application. This component features two main dialogs: one for selecting offline projects and another for handling version mismatches. It integrates Vue's reactivity with state management through a SimulatorState object, allowing users to select, delete, and open projects while addressing compatibility issues related to project versions.

Changes

Files Change Summary
v0/src/components/DialogBox/OpenOffline.vue New dialog component for managing offline projects, including project selection and version mismatch handling. Functions added for project management and state management.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant OpenOffline
    participant SimulatorState

    User->>OpenOffline: Opens offline project dialog
    OpenOffline->>SimulatorState: Fetches project list
    SimulatorState-->>OpenOffline: Returns project list
    User->>OpenOffline: Selects a project
    OpenOffline->>OpenOffline: Checks project version
    alt Version mismatch
        OpenOffline-->>User: Displays version mismatch dialog
        User->>OpenOffline: Chooses to continue or cancel
    else No mismatch
        OpenOffline-->>User: Loads selected project
    end
Loading

🐰 In the meadow where projects lay,
A new dialog hops into play.
With options to choose and versions to check,
Managing offline dreams, what the heck!
So gather 'round, let's cheer and sing,
For the joy of coding, our hearts take wing! 🎉


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

🧹 Outside diff range and nitpick comments (3)
v0/src/components/DialogBox/OpenOffline.vue (3)

33-35: Prevent click event on delete icon from selecting the radio button

Clicking the delete icon inside the label may inadvertently select the radio button due to event propagation. To prevent this, use the .stop modifier on the @click event.

Apply this change:

Line 35~:

- @click="deleteOfflineProject(projectId)"
+ @click.stop="deleteOfflineProject(projectId)"

This ensures that clicking the delete icon does not affect the radio button selection.


45-60: Use a computed property to check if projectList is empty

Comparing JSON.stringify(projectList) to '{}' is inefficient and may lead to unexpected results. Instead, use a computed property to check if projectList is empty.

In your script, add the computed property:

+ import { computed } from '@vue/runtime-core'
+ const isProjectListEmpty = computed(() => {
+     return Object.keys(projectList.value).length === 0
+ })

Update the template to use this computed property:

Lines 37~:

- <p v-if="JSON.stringify(projectList) == '{}'">
+ <p v-if="isProjectListEmpty">

Lines 45~ to 60~:

<v-btn
-   v-if="JSON.stringify(projectList) != '{}'"
+   v-if="!isProjectListEmpty"
    class="messageBtn"
    block
    @click="openProjectOffline()"
>
    open project
</v-btn>
<v-btn
-   v-else
+   v-if="isProjectListEmpty"
    class="messageBtn"
    block
    @click.stop="OpenImportProjectDialog"
>
    open CV file
</v-btn>

This approach is cleaner and enhances readability.


101-101: Use const instead of var for variable declaration

Using const for variable declarations that are not reassigned promotes better coding practices and prevents accidental reassignment.

Line 101~:

- var data = localStorage.getItem('projectList')
+ const data = localStorage.getItem('projectList')
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e92d95b and e56653d.

📒 Files selected for processing (1)
  • v0/src/components/DialogBox/OpenOffline.vue (1 hunks)

Comment on lines +113 to +117
function openProjectOffline() {
SimulatorState.dialogBox.open_project_dialog = false
let ele = $('input[name=projectId]:checked')
if (!ele.val()) return
const projectData = JSON.parse(localStorage.getItem(ele.val()))
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

Avoid using jQuery in Vue components; utilize Vue's reactivity system instead

Using jQuery inside Vue components is not recommended as it can lead to unpredictable state management and makes the code harder to maintain. Instead, leverage Vue's reactivity to handle user inputs.

You can bind the selected project ID to a reactive variable using v-model.

First, declare a reactive variable for the selected project ID:

+ const selectedProjectId = ref('')

Update the radio input to use v-model:

Lines 26~ to 30~:

< input
    type="radio"
    name="projectId"
    :value="projectId"
+   v-model="selectedProjectId"
  />

Modify the openProjectOffline function to use the reactive variable:

Lines 115~ to 117~:

- let ele = $('input[name=projectId]:checked')
- if (!ele.val()) return
- const projectData = JSON.parse(localStorage.getItem(ele.val()))
+ if (!selectedProjectId.value) return
+ const projectData = JSON.parse(localStorage.getItem(selectedProjectId.value))

Committable suggestion was skipped due to low confidence.

Comment on lines +100 to +103
onUpdated(() => {
var data = localStorage.getItem('projectList')
projectList.value = JSON.parse(localStorage.getItem('projectList')) || {}
})
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

Avoid using onUpdated for initialization; use onMounted instead

Using onUpdated to initialize projectList can cause unnecessary executions every time the component updates, impacting performance. Since you need to load projectList when the component mounts, it's better to use onMounted.

Move the initialization code to onMounted:

Lines 96~ to 98~:

onMounted(() => {
    SimulatorState.dialogBox.open_project_dialog = false
+   projectList.value = JSON.parse(localStorage.getItem('projectList')) || {}
})

Remove the onUpdated hook:

Lines 100~ to 103~:

- onUpdated(() => {
-     var data = localStorage.getItem('projectList')
-     projectList.value = JSON.parse(localStorage.getItem('projectList')) || {}
- })
📝 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
onUpdated(() => {
var data = localStorage.getItem('projectList')
projectList.value = JSON.parse(localStorage.getItem('projectList')) || {}
})
onMounted(() => {
SimulatorState.dialogBox.open_project_dialog = false
projectList.value = JSON.parse(localStorage.getItem('projectList')) || {}
})

Comment on lines +137 to +146
function confirmOpenProject() {
SimulatorState.dialogBox.version_mismatch_dialog = false
// Redirect to the appropriate version after confirmation
if(targetVersion.value == "Legacy"){
window.location.href = `/simulator/edit/${projectName}`
}else{
window.location.href = `/simulatorvue/edit/${projectName}?simver=${targetVersion.value}`
}

}
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

Validate targetVersion.value before using it in the redirect URL

Using variables from local storage directly in URLs can pose security risks if manipulated maliciously. Ensure that targetVersion.value contains only expected values before redirecting.

You can validate targetVersion.value against a whitelist of allowed versions:

function confirmOpenProject() {
    SimulatorState.dialogBox.version_mismatch_dialog = false
+   const allowedVersions = ['v0', 'v1', 'Legacy']; // Add all allowed versions
+   if (!allowedVersions.includes(targetVersion.value)) {
+       alert('Invalid simulator version.');
+       return;
+   }
    // Redirect to the appropriate version after confirmation
    if(targetVersion.value == "Legacy"){
        window.location.href = `/simulator/edit/${projectName}`  
    }else{
        window.location.href = `/simulatorvue/edit/${projectName}?simver=${targetVersion.value}`
    }
}

This ensures that only valid versions are used in the redirect URL.

📝 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
function confirmOpenProject() {
SimulatorState.dialogBox.version_mismatch_dialog = false
// Redirect to the appropriate version after confirmation
if(targetVersion.value == "Legacy"){
window.location.href = `/simulator/edit/${projectName}`
}else{
window.location.href = `/simulatorvue/edit/${projectName}?simver=${targetVersion.value}`
}
}
function confirmOpenProject() {
SimulatorState.dialogBox.version_mismatch_dialog = false
const allowedVersions = ['v0', 'v1', 'Legacy']; // Add all allowed versions
if (!allowedVersions.includes(targetVersion.value)) {
alert('Invalid simulator version.');
return;
}
// Redirect to the appropriate version after confirmation
if(targetVersion.value == "Legacy"){
window.location.href = `/simulator/edit/${projectName}`
}else{
window.location.href = `/simulatorvue/edit/${projectName}?simver=${targetVersion.value}`
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
GSOC'24 PR's for GSoC'24
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Combining all the PRs into one for running tests
2 participants