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

Refactor: Optimize ContextMenu.vue by replacing timers with Vue lifecycle methods #486

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

Conversation

Jay2006sawant
Copy link

@Jay2006sawant Jay2006sawant commented Feb 17, 2025

Fixes #469

Describe the changes you have made in this PR -

This PR refactors ContextMenu.vue to replace setTimeout with Vue lifecycle hooks, improving performance and reducing unnecessary browser resource usage.


Why this change?

  • Reduces the load on the browser by eliminating unnecessary timers.
  • Improves maintainability by using Vue’s recommended lifecycle methods.

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

Summary by CodeRabbit

  • New Features

    • The context menu now features dynamic visual feedback with refined transition effects for showing and hiding, providing smoother animations and enhanced clarity during interactions.
    • A new method, showContextMenu, has been added to control the visibility of the context menu.
  • Refactor

    • The interaction process for selecting menu options has been streamlined, resulting in a more intuitive and responsive user experience. The method for handling menu item clicks has been updated for better clarity and maintainability.

Copy link
Contributor

coderabbitai bot commented Feb 17, 2025

Walkthrough

The pull request refactors the context menu component in ContextMenu.vue. It removes the x and y properties from the ctxPos data structure, retaining only the visible state. A new computed property, contextMenuStyle, dynamically adjusts the menu's presentation. The component now includes a new showContextMenu method while simplifying the hideContextMenu method. Additionally, the menuItemClicked method has been refactored to accept an index for selecting an action from an array, streamlining event handling.

Changes

File Changes Summary
src/.../ContextMenu.vue • Removed x and y properties from ctxPos, keeping only visible.
• Added contextMenuStyle computed property for dynamic styling.
• Simplified hideContextMenu to directly set visibility.
• Introduced showContextMenu for explicit control.
• Refactored menuItemClicked to accept an index and invoke actions from an array.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant CM as ContextMenu Component
    participant AA as Action Array

    U->>CM: Trigger context menu (e.g., right-click)
    CM->>CM: Call showContextMenu()
    CM-->>U: Render menu with contextMenuStyle changes

    U->>CM: Click menu item (pass index)
    CM->>AA: Invoke action at index
    AA-->>CM: Return action response
Loading

Possibly related PRs

Poem

I'm a rabbit, hopping with glee,
In code gardens, what a sight to see!
Context menus now dance so light,
With clean actions, oh what a delight.
Bugs go bye, as my whiskers twitch,
Celebrating changes with a playful glitch!
🐇✨


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 17, 2025

Deploy Preview for circuitverse ready!

Name Link
🔨 Latest commit dac3bd3
🔍 Latest deploy log https://app.netlify.com/sites/circuitverse/deploys/67bccee916b9ce0008765134
😎 Deploy Preview https://deploy-preview-486--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: 1

🧹 Nitpick comments (1)
src/components/ContextMenu/ContextMenu.vue (1)

42-50: Consider extracting transition duration to CSS.

The computed property effectively handles the menu's visibility state. However, the transition timing could be moved to CSS for better maintainability.

Consider this approach:

 computed: {
     contextMenuStyle() {
         return {
             opacity: this.ctxPos.visible ? '1' : '0',
             visibility: this.ctxPos.visible ? 'visible' : 'hidden',
-            transition: 'opacity 0.2s ease-in-out',
         };
     },
 },

Add to your component's style section:

<style>
#contextMenu {
    transition: opacity 0.2s ease-in-out;
}
</style>
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1ea73f2 and c740ca2.

📒 Files selected for processing (1)
  • src/components/ContextMenu/ContextMenu.vue (2 hunks)
🔇 Additional comments (2)
src/components/ContextMenu/ContextMenu.vue (2)

2-2: LGTM! Template changes align with Vue best practices.

The changes improve the code by:

  • Using Vue's reactivity system with v-show and computed styles instead of manual DOM manipulation
  • Simplifying the click handler by passing the index directly

Also applies to: 8-8


57-62: LGTM! Methods are now simpler and more focused.

The visibility methods are now cleaner and more maintainable.

@Jay2006sawant
Copy link
Author

@JoshVarga @Arnabdaz PTAL

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 (1)
src/components/ContextMenu/ContextMenu.vue (1)

42-50: Consider making transition duration configurable.

The computed property effectively handles menu visibility with smooth transitions.

Consider extracting the hardcoded transition duration to a prop or constant:

 contextMenuStyle() {
     return {
         opacity: this.ctxPos.visible ? '1' : '0',
         visibility: this.ctxPos.visible ? 'visible' : 'hidden',
-        transition: 'opacity 0.2s ease-in-out',
+        transition: `opacity ${this.transitionDuration}s ease-in-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 c740ca2 and dac3bd3.

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

2-2: LGTM! Vue-idiomatic template changes.

The changes improve the component by:

  • Using v-show with computed styles for better reactivity
  • Passing the index directly to the click handler for improved type safety

Also applies to: 8-8


37-39: Verify context menu positioning logic.

The x,y coordinates have been removed from ctxPos, but there's no visible logic for positioning the context menu relative to the click location.

Please confirm how the context menu is positioned on the screen. You might need to:

  1. Add CSS positioning (fixed/absolute)
  2. Add logic to update menu position on right-click

57-62: LGTM! Clean visibility management.

The simplified visibility methods align well with Vue's reactivity system and eliminate the need for timers.

Comment on lines +63 to +112
async menuItemClicked(index) {
this.hideContextMenu()
const id = event.target.dataset.index
if (id == 0) {
document.execCommand('copy')
} else if (id == 1) {
document.execCommand('cut')
} else if (id == 2) {
// document.execCommand('paste'); it is restricted to sove this problem we use dataPasted variable
paste(localStorage.getItem('clipboardData'))
} else if (id == 3) {
deleteSelected()
} else if (id == 4) {
undo()
} else if (id == 5) {
createNewCircuitScope()
} else if (id == 6) {
logixFunction.createSubCircuitPrompt()
} else if (id == 7) {
globalScope.centerFocus(false)
}
try {
switch (index) {
case 0: // Copy
if (navigator.clipboard) {
const text = window.getSelection().toString();
if (text) {
await navigator.clipboard.writeText(text);
console.log("Copied:", text);
} else {
console.warn("No text selected for copying.");
}
} else {
console.error("Clipboard API not available.");
}
break;

case 1: // Cut
if (navigator.clipboard) {
const text = window.getSelection().toString();
if (text) {
await navigator.clipboard.writeText(text);
document.execCommand('delete');
console.log("Cut:", text);
} else {
console.warn("No text selected for cutting.");
}
} else {
console.error("Clipboard API not available.");
}
break;

case 2: // Paste
const clipboardData = await navigator.clipboard.readText();
if (clipboardData) {
paste(clipboardData);
console.log("Pasted:", clipboardData);
} else {
console.warn("No clipboard data available.");
}
break;

default:
console.warn("No action defined for this menu option.");
}
} catch (error) {
console.error("Error executing menu action:", error);
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

⚠️ Potential issue

🧩 Analysis chain

Implement missing menu actions.

The switch statement only handles Copy/Cut/Paste (cases 0-2) but ignores:

  • Delete (case 3)
  • Undo (case 4)
  • New Circuit (case 5)
  • Insert Subcircuit (case 6)
  • Center Focus (case 7)

Add the missing cases:

 switch (index) {
     case 0: // Copy
         // ... existing code ...
     case 1: // Cut
         // ... existing code ...
     case 2: // Paste
         // ... existing code ...
+    case 3: // Delete
+        deleteSelected();
+        break;
+    case 4: // Undo
+        undo();
+        break;
+    case 5: // New Circuit
+        createNewCircuitScope();
+        break;
+    case 6: // Insert Subcircuit
+        logixFunction.createSubCircuitPrompt();
+        break;
+    case 7: // Center Focus
+        if (typeof globalScope === 'undefined') {
+            console.error('globalScope is not defined');
+            return;
+        }
+        globalScope.centerFocus(false);
+        break;
     default:
         console.warn("No action defined for this menu option.");
 }

Let's verify the globalScope reference:


🏁 Script executed:

#!/bin/bash
# Search for globalScope definition
echo "Searching for globalScope in JavaScript files:"
rg "globalScope" --type js
echo "Searching for globalScope in Vue files:"
rg "globalScope" -g "*.vue"

Length of output: 66190


Action Required: Implement Missing Menu Cases in ContextMenu.vue

The globalScope reference is valid and widely used throughout the codebase, so the check in case 7 is appropriate. However, the switch statement currently only supports Copy (0), Cut (1), and Paste (2). Please add the missing actions as follows:

  • Case 3 – Delete: Call deleteSelected().
  • Case 4 – Undo: Invoke undo().
  • Case 5 – New Circuit: Trigger createNewCircuitScope().
  • Case 6 – Insert Subcircuit: Use logixFunction.createSubCircuitPrompt().
  • Case 7 – Center Focus: Confirm globalScope is defined before calling globalScope.centerFocus(false).
 switch (index) {
     case 0: // Copy
         // ... existing code ...
     case 1: // Cut
         // ... existing code ...
     case 2: // Paste
         // ... existing code ...
+    case 3: // Delete
+        deleteSelected();
+        break;
+    case 4: // Undo
+        undo();
+        break;
+    case 5: // New Circuit
+        createNewCircuitScope();
+        break;
+    case 6: // Insert Subcircuit
+        logixFunction.createSubCircuitPrompt();
+        break;
+    case 7: // Center Focus
+        if (typeof globalScope === 'undefined') {
+            console.error('globalScope is not defined');
+            return;
+        }
+        globalScope.centerFocus(false);
+        break;
     default:
         console.warn("No action defined for this menu option.");
 }
📝 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
async menuItemClicked(index) {
this.hideContextMenu()
const id = event.target.dataset.index
if (id == 0) {
document.execCommand('copy')
} else if (id == 1) {
document.execCommand('cut')
} else if (id == 2) {
// document.execCommand('paste'); it is restricted to sove this problem we use dataPasted variable
paste(localStorage.getItem('clipboardData'))
} else if (id == 3) {
deleteSelected()
} else if (id == 4) {
undo()
} else if (id == 5) {
createNewCircuitScope()
} else if (id == 6) {
logixFunction.createSubCircuitPrompt()
} else if (id == 7) {
globalScope.centerFocus(false)
}
try {
switch (index) {
case 0: // Copy
if (navigator.clipboard) {
const text = window.getSelection().toString();
if (text) {
await navigator.clipboard.writeText(text);
console.log("Copied:", text);
} else {
console.warn("No text selected for copying.");
}
} else {
console.error("Clipboard API not available.");
}
break;
case 1: // Cut
if (navigator.clipboard) {
const text = window.getSelection().toString();
if (text) {
await navigator.clipboard.writeText(text);
document.execCommand('delete');
console.log("Cut:", text);
} else {
console.warn("No text selected for cutting.");
}
} else {
console.error("Clipboard API not available.");
}
break;
case 2: // Paste
const clipboardData = await navigator.clipboard.readText();
if (clipboardData) {
paste(clipboardData);
console.log("Pasted:", clipboardData);
} else {
console.warn("No clipboard data available.");
}
break;
default:
console.warn("No action defined for this menu option.");
}
} catch (error) {
console.error("Error executing menu action:", error);
}
}
async menuItemClicked(index) {
this.hideContextMenu()
try {
switch (index) {
case 0: // Copy
if (navigator.clipboard) {
const text = window.getSelection().toString();
if (text) {
await navigator.clipboard.writeText(text);
console.log("Copied:", text);
} else {
console.warn("No text selected for copying.");
}
} else {
console.error("Clipboard API not available.");
}
break;
case 1: // Cut
if (navigator.clipboard) {
const text = window.getSelection().toString();
if (text) {
await navigator.clipboard.writeText(text);
document.execCommand('delete');
console.log("Cut:", text);
} else {
console.warn("No text selected for cutting.");
}
} else {
console.error("Clipboard API not available.");
}
break;
case 2: // Paste
const clipboardData = await navigator.clipboard.readText();
if (clipboardData) {
paste(clipboardData);
console.log("Pasted:", clipboardData);
} else {
console.warn("No clipboard data available.");
}
break;
case 3: // Delete
deleteSelected();
break;
case 4: // Undo
undo();
break;
case 5: // New Circuit
createNewCircuitScope();
break;
case 6: // Insert Subcircuit
logixFunction.createSubCircuitPrompt();
break;
case 7: // Center Focus
if (typeof globalScope === 'undefined') {
console.error('globalScope is not defined');
return;
}
globalScope.centerFocus(false);
break;
default:
console.warn("No action defined for this menu option.");
}
} catch (error) {
console.error("Error executing menu action:", error);
}
}

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.

Chore: Reduce usage of set timout and set interval
1 participant