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: typescript integration : src/simulator/src/wire.ts #442

Merged
merged 8 commits into from
Jan 31, 2025

Conversation

ThatDeparted2061
Copy link
Contributor

@ThatDeparted2061 ThatDeparted2061 commented Jan 27, 2025

Fixes #414

@JoshVarga @Arnabdaz @niladrix719 @devartstar

Summary by CodeRabbit

  • Refactor

    • Enhanced functionality and type safety for the Wire class.
    • Introduced a new Scope interface to manage wire properties.
    • Updated methods to handle wire coordinates, connections, and interactions, including double-click event handling and visualization.
  • Chores

    • Improved code clarity without changing core functionality.

Copy link
Contributor

coderabbitai bot commented Jan 27, 2025

Warning

Rate limit exceeded

@ThatDeparted2061 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 19 minutes and 12 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between afc61e5 and 55ae1c6.

📒 Files selected for processing (1)
  • src/simulator/src/wire.ts (1 hunks)

Walkthrough

The pull request enhances the Wire class in the src/simulator/src/wire.ts file by introducing a new Scope interface and updating method signatures with TypeScript type annotations. The constructor now accepts a Scope type, and additional properties for node coordinates are declared. The changes improve type safety by specifying parameter and return types across several methods, while also introducing private helper methods for better management of wire behavior.

Changes

File Change Summary
src/simulator/src/wire.ts - Added Scope interface
- Updated class and method signatures with TypeScript type annotations
- Added type definitions for x1, y1, x2, y2 coordinates
- Enhanced type safety for constructor and method parameters

Assessment against linked issues

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

Poem

🔌 A wire's tale, now typed with care,
TypeScript's embrace, beyond compare!
Annotations dance, types so bright,
Bringing clarity to code's delight 🐰
Rabbit's code, now safe and sound! 🚀


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

Deploy Preview for circuitverse ready!

Name Link
🔨 Latest commit 55ae1c6
🔍 Latest deploy log https://app.netlify.com/sites/circuitverse/deploys/6798a655022cc000083974b8
😎 Deploy Preview https://deploy-preview-442--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: 2

🧹 Nitpick comments (3)
src/simulator/src/wire.ts (3)

9-13: Consider improving type safety of the Scope interface.

The root property is typed as any, which defeats TypeScript's type checking benefits. Consider defining a more specific type for the root property based on its actual structure and usage.

 interface Scope {
     wires: Wire[];
-    root: any; // Replace 'any' with the appropriate type if known
+    root: { [key: string]: unknown }; // Or a more specific interface/type
     timeStamp: number;
 }

69-70: Simplify optional chaining in checkConnections method.

The optional chaining and nullish coalescing operators could be simplified for better readability.

-            !(this.node1.connections?.includes(this.node2)) ||
-            !(this.node2.connections?.includes(this.node1) ?? false);
+            !this.node1.connections?.includes(this.node2) ||
+            !this.node2.connections?.includes(this.node1);

247-252: Simplify null checks in delete method.

The null checks for connections are redundant since the filter operation is safe on undefined/null arrays.

-        if (this.node1.connections) {
-            this.node1.connections = this.node1.connections.filter(x => x !== this.node2);
-        }
-        if (this.node2.connections) {
-            this.node2.connections = this.node2.connections.filter(x => x !== this.node1);
-        }
+        this.node1.connections = this.node1.connections?.filter(x => x !== this.node2) ?? [];
+        this.node2.connections = this.node2.connections?.filter(x => x !== this.node1) ?? [];
📜 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 823612d.

📒 Files selected for processing (1)
  • src/simulator/src/wire.ts (4 hunks)
🔇 Additional comments (2)
src/simulator/src/wire.ts (2)

25-47: Well-structured class properties and constructor implementation!

Good job on adding proper type annotations for all class properties and constructor parameters. The initialization logic is clear and type-safe.


196-198: Consider adding type constraints for Node parameters.

Methods checkConvergence and converge accept Node parameters, but there might be specific requirements for these nodes. Consider adding type constraints or validation.

Also applies to: 238-241

src/simulator/src/wire.ts Outdated Show resolved Hide resolved
src/simulator/src/wire.ts Show resolved Hide resolved
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: 0

♻️ Duplicate comments (2)
src/simulator/src/wire.ts (2)

70-71: ⚠️ Potential issue

Fix reference to undeclared globalScope variable
This usage of globalScope mirrors a past comment and can cause runtime errors if it's not defined or imported.

+import { globalScope } from './globalScope'; // Example import

- if (
-     this.node1.parent == globalScope.root &&
-     this.node2.parent == globalScope.root
- ) {
+ if (
+     this.node1.parent === globalScope.root &&
+     this.node2.parent === globalScope.root
+ ) {

81-81: ⚠️ Potential issue

Fix reference to undeclared embed variable
As with globalScope, the embed variable is used but not declared or imported, which can lead to runtime errors.

+import { embed } from './embed'; // Example import

 if (embed) return updated;
🧹 Nitpick comments (3)
src/simulator/src/wire.ts (3)

10-10: Replace 'any' with a known type for root property
If you know the concrete type of root, using a strongly-typed approach would improve maintainability and catch type errors at compile-time.

-    root: any; // Replace 'any' with the appropriate type if known
+    root: RootObject; // Example placeholder type: replace with the actual type

42-48: Use local variables to avoid repeatedly calling absX() and absY()
Storing absX() and absY() results in local variables reduces repeated calls, which can marginally improve code clarity and performance.

 updateData(): void {
-    this.x1 = this.node1.absX();
-    this.y1 = this.node1.absY();
-    this.x2 = this.node2.absX();
-    this.y2 = this.node2.absY();
-    if (this.x1 === this.x2) this.type = 'vertical';
+    const node1X = this.node1.absX();
+    const node1Y = this.node1.absY();
+    const node2X = this.node2.absX();
+    const node2Y = this.node2.absY();
+    
+    this.x1 = node1X;
+    this.y1 = node1Y;
+    this.x2 = node2X;
+    this.y2 = node2Y;
+    if (node1X === node2X) this.type = 'vertical';
 }

177-185: Consider support for diagonal wires
Currently, wires only switch between 'vertical' or 'horizontal'. If diagonal wires (or other angles) are needed in the future, you may need to extend this logic.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 823612d and fe9df14.

📒 Files selected for processing (1)
  • src/simulator/src/wire.ts (1 hunks)
🔇 Additional comments (1)
src/simulator/src/wire.ts (1)

1-265: Overall implementation aligns with PR objectives
The added TypeScript annotations, Scope interface introduction, and helper methods significantly improve readability and type safety. Aside from the flagged issues, everything else looks well-structured. Great job!

@ThatDeparted2061
Copy link
Contributor Author

@JoshVarga @niladrix719 having 24 functions really reduces the cognitive complexity wud you still want me to to fix the codeclimate issue ?

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

🧹 Nitpick comments (1)
src/simulator/src/wire.ts (1)

8-12: Refine the root property’s type instead of using any.
It’s best to replace any with a more appropriate type (or a union of types) to benefit from TypeScript’s compile-time checks.

 interface Scope {
    wires: Wire[];
-   root: any; // Replace 'any' with the appropriate type if known
+   root: HTMLElement | SomeOtherType; // Or a union type if needed
    timeStamp: number;
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fe9df14 and 2750985.

📒 Files selected for processing (1)
  • src/simulator/src/wire.ts (1 hunks)
🧰 Additional context used
📓 Learnings (1)
src/simulator/src/wire.ts (3)
Learnt from: ThatDeparted2061
PR: CircuitVerse/cv-frontend-vue#442
File: src/simulator/src/wire.ts:81-81
Timestamp: 2025-01-27T17:29:35.080Z
Learning: The `embed` variable in the CircuitVerse simulator is a boolean flag used to determine if the circuit is in embedded mode, defined in `src/simulator/src/embed.ts`.
Learnt from: ThatDeparted2061
PR: CircuitVerse/cv-frontend-vue#442
File: src/simulator/src/wire.ts:0-0
Timestamp: 2025-01-27T17:29:33.929Z
Learning: In the CircuitVerse frontend Vue project, globalScope is a global variable that should be typed by extending the Window interface in a TypeScript declaration file (global.d.ts), as it's initialized on the window object.
Learnt from: ThatDeparted2061
PR: CircuitVerse/cv-frontend-vue#442
File: src/simulator/src/wire.ts:0-0
Timestamp: 2025-01-27T17:29:33.929Z
Learning: In the CircuitVerse frontend Vue project, globalScope should be declared on the window object using TypeScript declaration files (.d.ts) rather than importing it as a module.
🔇 Additional comments (16)
src/simulator/src/wire.ts (16)

14-24: Overall class structure looks good.
The class-level fields and TypeScript conversions are consistent and well-organized.


25-39: Constructor logic is straightforward and well-initialized.
Nicely sets up wire object type, coordinates, and updates data.


41-48: Good practice to centralize coordinate updates in updateData().
This method ensures wire coordinates remain in sync as the simulation changes.


50-54: Scope update approach is acceptable.
Re-checking connections upon scope switch is logical.


56-65: Connection checks are concise and effective.
Deleting the wire immediately when nodes are invalid is a good approach.


67-76: Fix reference to undeclared globalScope.
This usage references globalScope.root, but the variable is not imported or declared in this file. Per your previous note, it should be declared globally via a .d.ts file (extending the Window interface) rather than imported.

// Example snippet for globalScope declaration in global.d.ts
declare global {
  interface Window {
    globalScope?: Scope;
  }
}
export {};

78-96: Fix reference to undeclared embed.
This usage of embed on line 81 will cause a runtime error unless it is declared or imported. You may need to define and export it from an embed.ts file, then import it here.

// Example snippet in embed.ts
export const embed: boolean = false;

// Then import it where needed:
import { embed } from './embed';

98-111: Drawing logic is nicely encapsulated.
Using drawLine from canvasApi keeps the wire rendering code concise.


113-137: Wire coordinate checks and geometry helpers look good.
The checkWithin and isBetween functions cleanly handle horizontal/vertical wire checks.


139-144: Intermediate node handling.
Converging on a new node before deleting the wire is a clear approach.


146-167: Deletion sequence is correct.
Properly updates the simulation sets, removes mutual connections, and updates timestamps.


169-183: Wire orientation logic is solid.
Automatically recalculating wire type based on node positions is helpful for a dynamic layout.


185-199: Mouse interaction handling is intuitive.
The approach of checking wire selection or drag keeps the code organized.


201-226: Selection and drag detection logic appears robust.
Creating an intermediate node upon drag is a nice user experience improvement.


228-237: Node alignment helpers are well written.
Breaking out alignment along the X or Y axis clarifies the logic.

Also applies to: 239-260, 262-279


281-297: Color determination method is well-structured.
Maintains consistent theming for wire states and bitwidths.

@ThatDeparted2061
Copy link
Contributor Author

@JoshVarga I dont think that the current code climate issues should result in refactoring , since the functions are enough in number for code understanding

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

♻️ Duplicate comments (2)
src/simulator/src/wire.ts (2)

49-54: ⚠️ Potential issue

Fix reference to undeclared global variable.

The globalScope variable is used but not imported or declared. This could cause runtime errors.

Based on previous discussions, this needs to be declared in a TypeScript declaration file. Create a new file src/types/global.d.ts:

import { Scope } from '../simulator/src/scope'

declare global {
  interface Window {
    globalScope: Scope
  }
}

export {}

56-58: ⚠️ Potential issue

Fix reference to undeclared variable.

The embed variable is used but not imported or declared. This could cause runtime errors.

Based on the learnings, import the embed variable from the embed module:

+import { embed } from './embed';
🧹 Nitpick comments (4)
src/simulator/src/wire.ts (4)

17-20: Initialize coordinate properties in the constructor instead of using non-null assertions.

The non-null assertion operator (!) should be avoided when possible. These properties can be safely initialized in the constructor.

-    x1!: number;
-    y1!: number;
-    x2!: number;
-    y2!: number;
+    x1: number;
+    y1: number;
+    x2: number;
+    y2: number;

Then initialize them in the constructor:

constructor(public node1: Node, public node2: Node, public scope: Scope) {
    this.x1 = this.node1.absX();
    this.y1 = this.node1.absY();
    this.x2 = this.node2.absX();
    this.y2 = this.node2.absY();
    this.updateData();
    this.scope.wires.push(this);
    forceResetNodesSet(true);
}

88-101: Simplify the checkWithin method using early returns.

The method can be simplified by using early returns and avoiding unnecessary variable declarations.

 checkWithin(x: number, y: number): boolean {
-    const isHorizontal = this.type === 'horizontal';
-    const isVertical = this.type === 'vertical';
-
-    if (isHorizontal) {
+    if (this.type === 'horizontal') {
         return y === this.node1.absY() && this.isBetween(x, this.node1.absX(), this.node2.absX());
     }
 
-    if (isVertical) {
+    if (this.type === 'vertical') {
         return x === this.node1.absX() && this.isBetween(y, this.node1.absY(), this.node2.absY());
     }
 
     return false;
 }

241-256: Improve readability of the getWireColor method.

The array access using magic numbers could be replaced with an enum or constant for better maintainability.

+const enum WireValue {
+    LOOSE = -1,
+    LOW = 0,
+    HIGH = 1
+}

 private getWireColor(): string {
     if (simulationArea.lastSelected === this) {
         return colors['color_wire_sel'];
     }
     if (this.node1.value === undefined || this.node2.value === undefined) {
         return colors['color_wire_lose'];
     }
     if (this.node1.bitWidth === 1) {
         return [
             colors['color_wire_lose'],
             colors['color_wire_con'],
             colors['color_wire_pow'],
-        ][this.node1.value + 1];
+        ][this.node1.value - WireValue.LOOSE];
     }
     return colors['color_wire'];
 }

222-229: Improve parameter names in checkAndCreateNode method.

The parameter names could be more descriptive to better convey their purpose.

 private checkAndCreateNode(
-    current1: number,
-    expected1: number,
+    currentPosition1: number,
+    expectedPosition1: number,
     createNode1: () => Node,
-    current2: number,
-    expected2: number,
+    currentPosition2: number,
+    expectedPosition2: number,
     createNode2: () => Node
 ): boolean {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2750985 and afc61e5.

📒 Files selected for processing (1)
  • src/simulator/src/wire.ts (1 hunks)
🧰 Additional context used
📓 Learnings (1)
src/simulator/src/wire.ts (1)
Learnt from: ThatDeparted2061
PR: CircuitVerse/cv-frontend-vue#442
File: src/simulator/src/wire.ts:81-81
Timestamp: 2025-01-27T17:29:35.080Z
Learning: The `embed` variable in the CircuitVerse simulator is a boolean flag used to determine if the circuit is in embedded mode, defined in `src/simulator/src/embed.ts`.

src/simulator/src/wire.ts Outdated Show resolved Hide resolved
@JoshVarga JoshVarga merged commit c0b26c9 into CircuitVerse:main Jan 31, 2025
9 checks passed
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
2 participants