Skip to content

Refactor Codebase: Replace jQuery with Vue.js in Key Components #465

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 7 commits into
base: main
Choose a base branch
from

Conversation

rxiddhi
Copy link

@rxiddhi rxiddhi commented Feb 9, 2025

Fixes # 433

Describe the changes you have made in this PR -

Migrated from jQuery to Vue.js Native Methods:

All jQuery selectors like $('.messageBox .v-card-text') have been replaced with Vue’s refs for direct DOM manipulation.
Replaced jQuery event handling methods (e.g., $('.button').on('click', ...)) with Vue’s @click, @input, and other event listeners that integrate with Vue’s reactivity system.
Refactored the truth table generation and Boolean function manipulation logic to use Vue's ref and reactive for managing the data, eliminating the need for jQuery.
Leveraged Vue’s Reactive System:

State management is now handled using Vue’s reactive data (ref and reactive), replacing the previous jQuery-based state handling.
The generation and display of the table content have been refactored to use Vue’s templating system and list rendering (v-for), making the code more efficient and easier to maintain.
Replaced jQuery’s Iteration Methods:

Instead of using jQuery's $.each for looping through arrays, I’ve switched to using JavaScript’s modern array methods like map, forEach, and join.
Improved Functionality:

The printBooleanTable function and the overall table creation process have been refactored to make better use of Vue's built-in features.
Instead of using jQuery for dynamic DOM updates, Vue’s v-if and v-for directives are now used to render table rows and headers based on the data.
Code Modernization:

Replaced traditional for loops with more modern for...of loops and used template literals for better readability and performance.
In ApplyThemes.vue, I’ve optimized the theme handling logic by removing jQuery's class manipulation methods and replacing them w

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 user input handling and improved printing functionality for Boolean logic tables.
    • Introduced a reactive theme selection mechanism for a more intuitive user experience.
  • Refactor

    • Streamlined logic for table generation and theme application, improving clarity and maintainability.

Copy link
Contributor

coderabbitai bot commented Feb 9, 2025

Walkthrough

The changes enhance the CombinationalAnalysis.vue component by improving user input handling and the printing functionality of Boolean logic tables. A new watch function manages alert visibility reactively, and the createBooleanPrompt method has been refactored for better clarity. In the ApplyThemes.vue component, the theme selection logic has been updated to use Vue's reactive references instead of jQuery, streamlining the application of themes and improving state management.

Changes

File(s) Change Summary
src/.../CombinationalAnalysis.vue Added a new watch function; refactored createBooleanPrompt(inputList, outputList) and printBooleanTable() for improved input handling, table generation, and printing functionality.
src/.../Themes/ApplyThemes.vue Introduced selectedThemeRef for theme state management; updated theme application logic to use object syntax for class binding instead of jQuery, enhancing clarity and maintainability.

Sequence Diagram(s)

sequenceDiagram
    participant User as User
    participant CA as CombinationalAnalysis Component
    participant Win as New Window

    User->>CA: Initiate print table operation
    CA->>CA: Generate table header and body
    CA->>Win: Open new window with generated HTML table
    Win->>User: Display table and trigger print dialog
Loading
sequenceDiagram
    participant User as User
    participant AT as ApplyThemes Component
    participant LS as LocalStorage

    User->>AT: Select theme
    AT->>AT: Update selectedThemeRef reactively
    AT->>AT: Apply 'selected' and 'set' classes using object syntax
    AT->>LS: Save updated theme setting
Loading

Poem

I'm a rabbit, hopping with delight,
Code refactored, everything's looking right.
Boolean tables now print with style,
Themes reactively change in just a while.
No more jQuery clutter in our den,
Clean and clear code makes me grin!
Happy hops and coding wins!


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 Feb 9, 2025

Deploy Preview for circuitverse ready!

Name Link
🔨 Latest commit 4bdaf63
🔍 Latest deploy log https://app.netlify.com/sites/circuitverse/deploys/67f2482db89c3e0008332cab
😎 Deploy Preview https://deploy-preview-465--circuitverse.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
Lighthouse
Lighthouse
1 paths audited
Performance: 30 (🔴 down 13 from production)
Accessibility: 72 (no change from production)
Best Practices: 92 (no change from production)
SEO: 80 (no change from production)
PWA: -
View the detailed breakdown and full score reports

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

🧹 Nitpick comments (6)
src/components/DialogBox/Themes/ApplyThemes.vue (3)

29-32: Consider consolidating theme state tracking.

The class binding uses two separate refs (selectedTheme and selectedThemeRef) to track theme state, which could lead to confusion. Consider consolidating these into a single reactive reference with an enum or string constant to represent different states (e.g., 'selected', 'applied').

-:class="{
-    selected: theme === selectedTheme,
-    set: theme === selectedThemeRef
-}"
+const ThemeState = {
+    SELECTED: 'selected',
+    APPLIED: 'applied'
+} as const
+
+:class="{
+    [ThemeState.SELECTED]: theme === currentTheme?.selected,
+    [ThemeState.APPLIED]: theme === currentTheme?.applied
+}"

216-226: Consolidate theme storage logic.

The theme storage logic is duplicated between applyTheme and applyCustomTheme. Consider extracting this into a reusable function.

+function saveThemeToStorage(theme: string, customThemeData?: object) {
+    try {
+        localStorage.setItem('theme', theme)
+        if (customThemeData) {
+            localStorage.setItem('Custom Theme', JSON.stringify(customThemeData))
+        }
+    } catch (error) {
+        console.error('Failed to save theme:', error)
+        // Handle the error appropriately
+    }
+}

 function applyCustomTheme() {
     iscustomTheme.value = true
     updateThemeForStyle(localStorage.getItem('theme'))
     updateBG()
-    localStorage.setItem('theme', 'Custom Theme')
-    localStorage.setItem(
-        'Custom Theme',
-        JSON.stringify(themeOptions['Custom Theme'])
-    )
+    saveThemeToStorage('Custom Theme', themeOptions['Custom Theme'])
     selectedThemeRef.value = selectedTheme.value
 }

1-297: Overall implementation successfully migrates from jQuery to Vue.js.

The changes effectively leverage Vue.js features like reactive refs and class binding, aligning well with the PR objectives. The removal of jQuery dependencies improves the codebase's consistency and maintainability.

However, consider these architectural improvements:

  1. Use Vue's computed properties for derived state
  2. Implement proper error boundaries
  3. Consider using Vue's Composition API features like provide/inject for theme management
src/components/DialogBox/CombinationalAnalysis.vue (3)

220-220: Remove unused 'index' parameter.

The index parameter in the map function is not being used.

Apply this diff:

-    tableContent.innerHTML = tableHeader.value.map((header, index) => `
+    tableContent.innerHTML = tableHeader.value.map(header => `
🧰 Tools
🪛 ESLint

[error] 220-220: 'index' is defined but never used.

(no-unused-vars)


262-262: Remove unused 'scope' parameter.

The scope parameter is assigned a default value but never used in the function.

Apply this diff:

-function createBooleanPrompt(inputList, outputList, scope = globalScope) {
+function createBooleanPrompt(inputList, outputList) {
🧰 Tools
🪛 ESLint

[error] 262-262: 'scope' is assigned a value but never used.

(no-unused-vars)


342-342: Remove commented CSS rule.

The commented out top: 50% rule should be removed as it's not being used.

Apply this diff:

.alertStyle {
    position: absolute;
-    /* top: 50%; */
    top: 100px;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0463a60 and 14d6645.

📒 Files selected for processing (2)
  • src/components/DialogBox/CombinationalAnalysis.vue (1 hunks)
  • src/components/DialogBox/Themes/ApplyThemes.vue (3 hunks)
🧰 Additional context used
🪛 ESLint
src/components/DialogBox/CombinationalAnalysis.vue

[error] 220-220: 'index' is defined but never used.

(no-unused-vars)


[error] 262-262: 'scope' is assigned a value but never used.

(no-unused-vars)

🔇 Additional comments (2)
src/components/DialogBox/CombinationalAnalysis.vue (2)

1-20: LGTM! Template section follows Vue.js best practices.

The template section properly utilizes Vue's reactivity system with v-model, event bindings, and conditional rendering.


263-323: LGTM! Modern JavaScript practices implemented.

The refactored code successfully:

  • Uses optional chaining for null safety
  • Implements modern array methods
  • Uses template literals
  • Follows Vue.js reactivity patterns

@ThatDeparted2061
Copy link
Member

Hey @rxiddhi,
Thanks for the PR but these Files have already been worked upon in #440 and #441
There is no point of raising PRs for the same files since that will just slow down the speed for the improvement i.e. transfer to Vue's reactive

@ThatDeparted2061
Copy link
Member

ThatDeparted2061 commented Feb 9, 2025

For future PRs try reducing the errors in the files
image
here in CombinationalAnalysis.vue you can see, you still need to work on a lot of issues

@rxiddhi
Copy link
Author

rxiddhi commented Feb 9, 2025

Hi @ThatDeparted2061 , The issue was already assigned to me on Slack before you raised the PR, and since I was already working on it, I submitted my PR.

@ThatDeparted2061
Copy link
Member

ThatDeparted2061 commented Feb 9, 2025

Hi @ThatDeparted2061 , The issue was already assigned to me on Slack before you raised the PR, and since I was already working on it, I submitted my PR.

Hey riddhi,
I do not intend to discourage you from raising PRs, this issue we are working on is too big and is supposed to be done together.
All I am saying is working on the same files would just make it cluttered for maintainers to review, as far as the timeline of my PRs is concerned, you can check the dates, its dated before the comments.

There is no assignment to this issue because this is intended to be done by everyone who wants, to speed things up.

@krushndayshmookh
Copy link

@rxiddhi @ThatDeparted2061 I think the simpler thing to do here would be to create two separate issues focusing on separate set of files and work on them.

@ThatDeparted2061
Copy link
Member

I dont think there is a need for that,
I dont want opensource to become a competetion. Here anyone can come and make meaningful contributions. I am just saying that if you solve a unique problem which hasnt been solved before then it would be more helpful

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

🧹 Nitpick comments (2)
src/components/DialogBox/CombinationalAnalysis.vue (2)

202-204: Consider using Vue's watchEffect for simpler alert handling.

The current implementation uses watch with a timeout option, but watchEffect would be more idiomatic for this use case.

-        watch(showAlert, () => {
-            showAlert.value = false
-        }, { timeout: 2000 })
+        watchEffect(() => {
+            if (showAlert.value) {
+                setTimeout(() => {
+                    showAlert.value = false
+                }, 2000)
+            }
+        })

Also applies to: 210-212


217-218: Improve null handling in prompt chains.

The optional chaining with fallback to empty array is good, but consider adding input validation.

-    inputListNames.value = inputList || prompt('Enter inputs separated by commas')?.split(',') || []
-    outputListNames.value = outputList || prompt('Enter outputs separated by commas')?.split(',') || []
+    const validateList = (list) => Array.isArray(list) ? list.filter(Boolean) : []
+    inputListNames.value = validateList(inputList || prompt('Enter inputs separated by commas')?.split(','))
+    outputListNames.value = validateList(outputList || prompt('Enter outputs separated by commas')?.split(','))
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 14d6645 and 5e544c0.

📒 Files selected for processing (1)
  • src/components/DialogBox/CombinationalAnalysis.vue (3 hunks)
🧰 Additional context used
🪛 ESLint
src/components/DialogBox/CombinationalAnalysis.vue

[error] 216-216: 'scope' is assigned a value but never used.

(no-unused-vars)

🔇 Additional comments (2)
src/components/DialogBox/CombinationalAnalysis.vue (2)

26-26: LGTM! Import statement aligns with Vue.js migration.

The addition of Vue's watch import aligns with the PR's objective of migrating from jQuery to Vue.js native methods.


231-276: LGTM! Excellent refactoring of table generation logic.

The table generation logic has been significantly improved:

  • Clear separation of concerns with decimal column handling
  • Modern array methods replacing loops
  • Improved readability with descriptive variable names

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

🧹 Nitpick comments (2)
src/components/DialogBox/CombinationalAnalysis.vue (2)

202-204: Standardize alert timeout values.

The alert timeout values are inconsistent across different alerts (2000ms vs 3000ms). Consider standardizing these values for consistency.

-        }, { timeout: 2000 })
+        }, { timeout: 3000 })

Also applies to: 210-212, 333-335


252-276: Extract table generation logic into separate functions.

The table generation logic is complex and could be more maintainable if split into smaller, focused functions.

+    function generateTableRow(rowIndex, columnOffset) {
+        const row = new Array(tableHeader.value.length).fill(null)
+        
+        if (columnOffset) {
+            row[0] = rowIndex
+        }
+
+        inputListNames.value.forEach((_, colIndex) => {
+            row[colIndex + columnOffset] = +((rowIndex & (1 << (inputListNames.value.length - colIndex - 1))) !== 0)
+        })
+
+        if (output.value == null) {
+            outputListNamesInteger.value.forEach((_, i) => {
+                row[inputListNames.value.length + columnOffset + i] = 'x'
+            })
+        } else {
+            row[inputListNames.value.length + columnOffset] = output.value[rowIndex]
+        }
+
+        return row
+    }
+
     // Generate table body
     const rowCount = 1 << inputListNames.value.length
-    tableBody.value = Array(rowCount).fill(null).map((_, rowIndex) => {
-        const row = new Array(tableHeader.value.length).fill(null)
-        
-        // Add decimal column if needed
-        if (columnOffset) {
-            row[0] = rowIndex
-        }
-
-        // Add input columns
-        inputListNames.value.forEach((_, colIndex) => {
-            row[colIndex + columnOffset] = +((rowIndex & (1 << (inputListNames.value.length - colIndex - 1))) !== 0)
-        })
-
-        // Add output columns
-        if (output.value == null) {
-            outputListNamesInteger.value.forEach((_, i) => {
-                row[inputListNames.value.length + columnOffset + i] = 'x'
-            })
-        } else {
-            row[inputListNames.value.length + columnOffset] = output.value[rowIndex]
-        }
-
-        return row
-    })
+    tableBody.value = Array(rowCount).fill(null).map((_, rowIndex) => 
+        generateTableRow(rowIndex, columnOffset)
+    )
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5e544c0 and a2e14d9.

📒 Files selected for processing (1)
  • src/components/DialogBox/CombinationalAnalysis.vue (3 hunks)
🔇 Additional comments (3)
src/components/DialogBox/CombinationalAnalysis.vue (3)

26-26: LGTM! Import statement updated to include Vue's watch function.

The import statement has been correctly updated to include the watch function from Vue.


293-336: Add error handling for DOM operations.

The print function needs better error handling for DOM operations and resource loading.


352-354: Verify and address the commented issues with output.value.

The comments indicate potential issues with output.value and output.value == null comparisons. These should be investigated and fixed.

❌ Verification inconclusive

🏁 Script executed:

#!/bin/bash
# Search for all usages of output.value to identify potential issues
rg -A 3 'output\.value' --type vue

Length of output: 64


#!/bin/bash
# Re-run the search for "output.value" in all Vue files using a glob pattern for the *.vue extension
rg -A 3 'output\.value' -g '*.vue'

# Display the context around the commented lines (348-360) in the target file to inspect the comment details
sed -n '348,360p' src/components/DialogBox/CombinationalAnalysis.vue

The previous command using --type vue failed because the file type wasn’t recognized by ripgrep. The above script re-runs the search using a glob (-g '*.vue') and also prints the relevant snippet from src/components/DialogBox/CombinationalAnalysis.vue so that you can manually verify if the issues regarding output.value (notably around lines 352–354) still apply or if they are outdated.

Please review the output of this script to determine whether any corrective action is needed for the handling of output.value.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

Update CombinationalAnalysis.vue

Update CombinationalAnalysis.vue
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.

4 participants