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: TS integration in modules.js #472

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

Conversation

ThatDeparted2061
Copy link
Member

@ThatDeparted2061 ThatDeparted2061 commented Feb 10, 2025

Fixes #414

@Arnabdaz @JoshVarga

Summary by CodeRabbit

  • New Features

    • Enhanced simulation element positioning and input sizing for a more robust layout experience.
    • Introduced comprehensive type definitions to improve consistency and reliability across module interactions.
  • Refactor

    • Replaced the previous module management implementation with an updated, TypeScript-based solution that streamlines element layout adjustments.

Copy link
Contributor

coderabbitai bot commented Feb 10, 2025

Walkthrough

The pull request refactors module management within the simulation by removing the JavaScript file and replacing it with a TypeScript implementation. The new TypeScript file introduces helper functions for marking occupied Y positions, finding the next available Y value, and updating element positions when layout changes occur. Additionally, a new TypeScript file provides type declarations for simulation layout, inputs/outputs, modules, and size-changing contexts, ensuring stricter type safety.

Changes

File(s) Change Summary
src/simulator/src/modules.js & src/simulator/src/modules.ts Removed the old JS file with getNextPosition and changeInputSize functions and an empty modules default export. Introduced a new TS file with re-implemented module management functions along with helper functions (markOccupiedYPositions, findNextAvailableY, updateElementPositions) and exported a typed modules constant.
src/simulator/src/types/modules.types.ts Added a new file defining interfaces for layout properties, input/output elements, simulation scopes, module constructors, module instances, module registry, and the size-change context.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant getNextPosition
    participant Helper
    Caller->>getNextPosition: call getNextPosition(x: number, scope: GlobalScope)
    getNextPosition->>Helper: markOccupiedYPositions(elements)
    getNextPosition->>Helper: findNextAvailableY(done, startY)
    getNextPosition->>getNextPosition: Check if newY exceeds layout.height
    alt Height exceeded
        getNextPosition->>Helper: updateElementPositions(oldHeight, newHeight)
    end
    getNextPosition->>Caller: return next available Y
Loading
sequenceDiagram
    participant Caller
    participant changeInputSize
    participant ModuleInstance
    Caller->>changeInputSize: call changeInputSize(size)
    changeInputSize->>changeInputSize: Validate new size (within 2 to 10)
    alt Valid & different size
        changeInputSize->>ModuleInstance: Create new module instance
        ModuleInstance-->>changeInputSize: new instance created
        changeInputSize->>Caller: return new ModuleInstance
    else Not valid/different
        changeInputSize->>Caller: perform no changes
    end
Loading

Possibly related PRs

  • CircuitVerse/cv-frontend-vue#463: Introduces similar functions in a new TypeScript file, indicating a direct code-level relationship with the refactored simulation module management.

Suggested reviewers

  • Arnabdaz
  • JoshVarga

Poem

I'm a little rabbit, hopping through the code,
Leaving old JS behind on a winding road.
With TypeScript tricks and types so bright,
I ensure each module finds its light.
Hoppy days for changes, neat and clear,
🐇✨ CodeRabbit cheers with every cheer!

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
  • @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 10, 2025

Deploy Preview for circuitverse ready!

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

netlify bot commented Feb 10, 2025

Deploy Preview for circuitverse ready!

Name Link
🔨 Latest commit 7b0c9e5
🔍 Latest deploy log https://app.netlify.com/sites/circuitverse/deploys/67d2f35dfaabf40008c51647
😎 Deploy Preview https://deploy-preview-472--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: 47
Accessibility: 72
Best Practices: 92
SEO: 80
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: 2

🧹 Nitpick comments (4)
src/simulator/src/types/modules.types.ts (3)

10-16: Consider extracting layout into its own interface

The Scope interface is well-structured, but for better maintainability, consider extracting the layout object into its own interface.

+interface Layout {
+    height: number;
+}

 interface Scope {
     Input: InputOutputElement[];
     Output: InputOutputElement[];
-    layout: {
-        height: number;
-    };
+    layout: Layout;
 }

22-31: Consider using enum for direction parameter

The direction parameter is typed as string, but it likely has a limited set of valid values. Consider using a string enum for better type safety.

+enum Direction {
+    LEFT = "LEFT",
+    RIGHT = "RIGHT",
+    UP = "UP",
+    DOWN = "DOWN"
+}

 interface Module {
     new (
         x: number,
         y: number,
         scope: GlobalScope,
-        direction: string,
+        direction: Direction,
         size: number,
         bitWidth: number
     ): ModuleInstance;
 }

41-50: Consider consistent direction typing with Module interface

If you implement a Direction enum as suggested earlier, ensure it's also used here for consistency.

 interface ChangeInputSizeContext {
     inputSize: number;
     objectType: string;
     x: number;
     y: number;
     scope: GlobalScope;
-    direction: string;
+    direction: Direction;
     bitWidth: number;
     delete(): void;
 }
src/simulator/src/modules.ts (1)

61-64: Improve comment for global modules object

The comment "Global" is not very descriptive. Consider improving it to better explain this object's purpose.

 /**
- * Global
+ * Dictionary of available module types that can be instantiated
  */
 export const modules: Modules = {};
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2a9f309 and 7b0c9e5.

📒 Files selected for processing (3)
  • src/simulator/src/modules.js (0 hunks)
  • src/simulator/src/modules.ts (1 hunks)
  • src/simulator/src/types/modules.types.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • src/simulator/src/modules.js
🧰 Additional context used
🪛 Biome (1.9.4)
src/simulator/src/modules.ts

[error] 66-66: void is confusing inside a union type.

Unsafe fix: Use undefined instead.

(lint/suspicious/noConfusingVoidType)

🔇 Additional comments (9)
src/simulator/src/types/modules.types.ts (5)

1-4: Clear and well-structured layout interface

The LayoutProperties interface provides a clean definition for coordinate positioning used throughout the module system.


6-8: Good abstraction for elements with positions

The InputOutputElement interface creates a good abstraction for elements that need positioning in the layout.


18-20: Future-proof GlobalScope extension

Using extension here provides a clean way to add global-specific properties in the future without modifying the base Scope interface.


37-39: Good dictionary type for modules collection

The Modules interface provides a clean way to define a dictionary of available module types.


33-35:

❓ Verification inconclusive

ModuleInstance interface appears minimal

The ModuleInstance interface only defines a delete method. Consider expanding it to include other properties and methods that module instances should have.


🏁 Script executed:

#!/bin/bash
# Check for additional properties/methods used with module instances
rg --type ts --type js "\.(?!delete\(\))([\w]+)(?:\s*=|\()" -A 1 -B 1

Length of output: 311


ModuleInstance Interface Minimality – Further Verification Required

The current implementation of the ModuleInstance interface at src/simulator/src/types/modules.types.ts (lines 33–35) includes only the delete method. An initial search for accesses to additional properties/methods (aside from delete) resulted in a regex error due to unsupported look-around.

To verify whether module instances are used with additional properties or methods elsewhere in the codebase, please run the following revised shell script using PCRE2 support:

#!/bin/bash
# Attempt a re-run using PCRE2 to check for additional properties/method usages on ModuleInstance instances
rg --pcre2 --type ts --type js "\.(?!delete\(\))([\w]+)(?:\s*=|\()" -A 1 -B 1

Manually verify the output of this command:

  • If additional properties or methods are referenced on module instances, consider expanding the ModuleInstance interface accordingly.
  • If no usage beyond delete is found, confirm that the minimal implementation is intentional.
src/simulator/src/modules.ts (4)

7-13: Well-implemented helper function

This helper function efficiently marks occupied positions in the coordinate system.


29-35: Clear element position update logic

This helper function provides clean logic for updating element positions when layout height changes.


37-59: Well-structured position calculation function

The getNextPosition function effectively uses helper functions to calculate positions and update the layout as needed.


1-3:

❓ Verification inconclusive

Address import cycle warning

The ESLint disable comment suggests there's a circular dependency between modules. Circular dependencies can lead to maintenance issues and initialization problems.


🏁 Script executed:

#!/bin/bash
# Check for import cycles
echo "Checking for import cycles..."
rg -l "import.*from.*simulationArea" | xargs -I{} rg -l "import.*from.*modules" {}
echo "Checking what simulationArea imports from modules..."
rg "import.*from.*modules" ./src/simulator/src/simulationArea.ts

Length of output: 3423


Circular Dependency Check – Manual Verification Required

Our investigation shows that while src/simulator/src/modules.ts imports simulationArea from ./simulationArea, a direct cycle isn’t evident—simulationArea.ts does not import any module from the modules directory. However, the search results were not conclusive regarding any indirect cycles elsewhere in the dependency graph. Please manually review the broader dependency chain to confirm that no circular dependency exists. If no cycle is found, the ESLint disable comment (/* eslint-disable import/no-cycle */) can be safely removed.

Comment on lines +18 to +24
function findNextAvailableY(done: { [key: number]: number }, startY: number): number {
let possibleY = startY;
while (done[possibleY] || done[possibleY + 10] || done[possibleY - 10]) {
possibleY += 10;
}
return possibleY;
}
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

Add safeguard against potential infinite loop

The findNextAvailableY function lacks a safeguard against infinite loops. If all positions are marked as occupied, this function would never terminate.

 function findNextAvailableY(done: { [key: number]: number }, startY: number): number {
     let possibleY = startY;
+    const maxIterations = 1000; // Prevent infinite loops
+    let iterations = 0;
     while (done[possibleY] || done[possibleY + 10] || done[possibleY - 10]) {
         possibleY += 10;
+        iterations++;
+        if (iterations > maxIterations) {
+            console.warn('Maximum iterations reached in findNextAvailableY');
+            break;
+        }
     }
     return possibleY;
 }
📝 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 findNextAvailableY(done: { [key: number]: number }, startY: number): number {
let possibleY = startY;
while (done[possibleY] || done[possibleY + 10] || done[possibleY - 10]) {
possibleY += 10;
}
return possibleY;
}
function findNextAvailableY(done: { [key: number]: number }, startY: number): number {
let possibleY = startY;
const maxIterations = 1000; // Prevent infinite loops
let iterations = 0;
while (done[possibleY] || done[possibleY + 10] || done[possibleY - 10]) {
possibleY += 10;
iterations++;
if (iterations > maxIterations) {
console.warn('Maximum iterations reached in findNextAvailableY');
break;
}
}
return possibleY;
}

Comment on lines +66 to +84
export function changeInputSize(this: ChangeInputSizeContext, size: number): ModuleInstance | void {
if (size === undefined || size < 2 || size > 10) return;
if (this.inputSize === size) return;

size = parseInt(size.toString(), 10);

const obj: ModuleInstance = new modules[this.objectType](
this.x,
this.y,
this.scope,
this.direction,
size,
this.bitWidth
);

this.delete();
simulationArea.lastSelected = obj;
return obj;
}
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

Fix return type and improve parameter handling

The function has a few issues to address:

  1. Using void in a union type is confusing (per static analysis)
  2. Modifying the input parameter directly
  3. Relying on this context which can be error-prone
-export function changeInputSize(this: ChangeInputSizeContext, size: number): ModuleInstance | void {
+export function changeInputSize(this: ChangeInputSizeContext, size: number): ModuleInstance | undefined {
     if (size === undefined || size < 2 || size > 10) return;
     if (this.inputSize === size) return;
 
-    size = parseInt(size.toString(), 10);
+    const parsedSize = parseInt(size.toString(), 10);
 
     const obj: ModuleInstance = new modules[this.objectType](
         this.x,
         this.y,
         this.scope,
         this.direction,
-        size,
+        parsedSize,
         this.bitWidth
     );
 
     this.delete();
     simulationArea.lastSelected = obj;
     return obj;
 }
📝 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
export function changeInputSize(this: ChangeInputSizeContext, size: number): ModuleInstance | void {
if (size === undefined || size < 2 || size > 10) return;
if (this.inputSize === size) return;
size = parseInt(size.toString(), 10);
const obj: ModuleInstance = new modules[this.objectType](
this.x,
this.y,
this.scope,
this.direction,
size,
this.bitWidth
);
this.delete();
simulationArea.lastSelected = obj;
return obj;
}
export function changeInputSize(this: ChangeInputSizeContext, size: number): ModuleInstance | undefined {
if (size === undefined || size < 2 || size > 10) return;
if (this.inputSize === size) return;
const parsedSize = parseInt(size.toString(), 10);
const obj: ModuleInstance = new modules[this.objectType](
this.x,
this.y,
this.scope,
this.direction,
parsedSize,
this.bitWidth
);
this.delete();
simulationArea.lastSelected = obj;
return obj;
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 66-66: void is confusing inside a union type.

Unsafe fix: Use undefined instead.

(lint/suspicious/noConfusingVoidType)

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