Skip to content

Conversation

@ShinichiShi
Copy link

@ShinichiShi ShinichiShi commented Oct 24, 2025

Fixes #661

Describe the changes you have made in this PR -

refactored andGate.js to typescript

Summary by CodeRabbit

  • New Features
    • AND gate component added to the circuit simulator with enhanced capabilities:
      • Support for configurable multiple inputs to accommodate diverse circuit requirements and designs
      • Verilog code generation for seamless hardware description and design export workflows
      • Interactive visual representation featuring responsive hover and selection feedback states
      • Automatic configuration persistence enabling reliable saved circuit recovery

@netlify
Copy link

netlify bot commented Oct 24, 2025

Deploy Preview for circuitverse ready!

Name Link
🔨 Latest commit 0cbcff2
🔍 Latest deploy log https://app.netlify.com/projects/circuitverse/deploys/68fb1eb40b135b000911549e
😎 Deploy Preview https://deploy-preview-670--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: 43 (🔴 down 2 from production)
Accessibility: 73 (no change from production)
Best Practices: 92 (no change from production)
SEO: 82 (no change from production)
PWA: -
View the detailed breakdown and full score reports

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 24, 2025

Walkthrough

A new TypeScript AndGate class is introduced extending CircuitElement. It implements multi-input AND gate functionality with configurable input length and bit width, including methods for serialization, simulation resolution, canvas rendering, and Verilog code generation.

Changes

Cohort / File(s) Summary
New AndGate Implementation
v0/src/simulator/src/modules/AndGate.ts
Adds new AndGate class with constructor for gate configuration, customSave for state persistence, resolve for logical AND computation across inputs, customDraw for canvas rendering with directional styling, and generateVerilog for Verilog output. Includes prototype properties for UI metadata and gate configuration.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

The change adds a single, self-contained new gate class following established CircuitElement patterns. While multiple method implementations require review, the logic is straightforward and consistent with similar gate modules. No refactoring or multi-file structural changes introduce complexity.

Suggested reviewers

  • Arnabdaz

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The PR title "Re: AndGate.js to ts" directly and clearly describes the primary change: converting the AndGate module from JavaScript to TypeScript. The title is concise, specific, and immediately communicates the main objective of the PR to a reviewer scanning the commit history. The phrasing matches the actual changeset, which introduces a new AndGate.ts file in TypeScript format.
Linked Issues Check ✅ Passed The PR satisfies the core requirements from linked issue #661: it converts a single JavaScript file (AndGate.js) to TypeScript, which is the primary objective of the feature request. The changeset is scoped to one file as mandated by the issue guidelines. The summary indicates the existing functionality is preserved through the class structure and method implementations (customSave, resolve, customDraw, generateVerilog), which aligns with the requirement to not change existing logic while improving type safety. The change is appropriately related to the Vue simulator as specified in the issue.
Out of Scope Changes Check ✅ Passed The changeset contains only the AndGate.ts file with the class definition and methods necessary for the JavaScript-to-TypeScript conversion. All modifications are directly related to the conversion objective specified in issue #661, including the class structure, public method signatures, and prototype properties that define the gate's behavior. No additional features, refactoring beyond type conversion, or unrelated modifications are evident in the summary. The scope remains focused on the single-file conversion requirement.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

Comment @coderabbitai help to get the list of available commands and usage tips.

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 (5)
v0/src/simulator/src/modules/AndGate.ts (5)

9-9: Consider typing globalScope instead of using any.

The use of any defeats TypeScript's type safety benefits. Consider creating a proper interface or type for globalScope to improve type safety across the codebase. This can be a follow-up task if proper types don't exist yet.


50-70: Consider refactoring input node creation logic for clarity.

The current implementation uses floating-point arithmetic in loop conditions (e.g., inputLength / 2 - 1, inputLength / 2 + 1), which makes the code difficult to understand and maintain. While the logic is mathematically correct, integer-based arithmetic would be clearer.

Example refactor using integer arithmetic:

// Calculate spacing for symmetrical node placement
const halfSize = Math.floor(inputLength / 2)
const isOdd = inputLength % 2 === 1

// Create top half nodes
for (let i = 0; i < halfSize; i++) {
    const a = new Node(-10, -10 * (halfSize - i), 0, this)
    this.inp.push(a)
}

// Create center node for odd input counts
if (isOdd) {
    const a = new Node(-10, 0, 0, this)
    this.inp.push(a)
}

// Create bottom half nodes
for (let i = 0; i < halfSize; i++) {
    const a = new Node(-10, 10 * (i + 1), 0, this)
    this.inp.push(a)
}

100-100: Consider using nullish coalescing operator for clarity.

Using || 0 works but treats falsy values (0, false, null, undefined, '') all as 0. The nullish coalescing operator ?? 0 would be more explicit about only defaulting null/undefined values, which is likely the intent for bitwise operations.

Example:

-        let result = this.inp[0].value || 0
+        let result = this.inp[0].value ?? 0
         if (this.isResolvable() === false) {
             return
         }
         for (let i = 1; i < this.inputSize; i++)
-            result &= this.inp[i].value || 0
+            result &= this.inp[i].value ?? 0

Also applies to: 105-105


107-107: Avoid type casting with as any for simulationQueue.

The as any cast bypasses TypeScript's type safety. Consider properly typing simulationArea.simulationQueue.add() or creating a type assertion that's more specific than any.


147-154: Consider defining prototype properties with proper types.

Using (AndGate.prototype as any) for all property assignments bypasses TypeScript's type safety. Consider one of these approaches:

  1. Define these as class properties with proper types
  2. Create an interface that extends the class with these properties
  3. Use a more specific type than any

Example approach:

export default class AndGate extends CircuitElement {
    rectangleObject: boolean
    inputSize: number
    inp: Node[]
    output1: Node
    
    // Prototype-like properties
    static readonly tooltipText = 'And Gate ToolTip : Implements logical conjunction'
    static readonly verilogType = 'and'
    static readonly helplink = 'https://docs.circuitverse.org/#/chapter4/4gates?id=and-gate'
    static readonly objectType = 'AndGate'
    
    readonly alwaysResolve = true
    changeInputSize = changeInputSize

    // ... rest of class
}

Note: This may require adjustments based on how these properties are accessed elsewhere in the codebase.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0921d26 and 0cbcff2.

📒 Files selected for processing (1)
  • v0/src/simulator/src/modules/AndGate.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
v0/src/simulator/src/modules/AndGate.ts (7)
src/simulator/src/restrictedElementDiv.js (1)
  • globalScope (4-4)
src/simulator/src/circuitElement.js (1)
  • CircuitElement (27-993)
src/simulator/src/node.js (2)
  • Node (150-1034)
  • findNode (87-89)
src/simulator/src/canvasApi.js (4)
  • correctWidth (401-403)
  • moveTo (235-255)
  • lineTo (257-271)
  • arc (273-296)
src/simulator/src/themer/themer.ts (1)
  • colors (47-47)
src/simulator/src/utils.ts (1)
  • gateGenerateVerilog (93-120)
src/simulator/src/modules.js (1)
  • changeInputSize (45-60)
🔇 Additional comments (3)
v0/src/simulator/src/modules/AndGate.ts (3)

114-140: LGTM!

The drawing logic correctly handles null context, uses canvas API helpers appropriately, and implements proper hover/selection styling.


142-144: LGTM!

The Verilog generation correctly delegates to the utility function with the appropriate AND operator.


82-82: No action needed—preserve the typo for serialization compatibility.

The typo constructorParamaters originates from the original codebase and is consistently used across all versions (v0, v1, src) in both serialization and deserialization logic (see data/load.js). Changing this key name would break backward compatibility with existing saved circuit files. The spelling must remain as-is.

Comment on lines +41 to +43
/* this is done in this.baseSetup() now
this.scope['AndGate'].push(this);
*/
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 | 🟠 Major

Remove commented code.

The commented code referencing baseSetup() should be removed to improve code cleanliness. Based on the comment, this functionality is now handled elsewhere.

Apply this diff:

-        /* this is done in this.baseSetup() now
-        this.scope['AndGate'].push(this);
-        */
📝 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
/* this is done in this.baseSetup() now
this.scope['AndGate'].push(this);
*/
🤖 Prompt for AI Agents
In v0/src/simulator/src/modules/AndGate.ts around lines 41 to 43, remove the
commented-out block that references this.scope['AndGate'].push(this) and the
surrounding comment about baseSetup(); delete those lines entirely (and any
leftover blank line) since the functionality is now handled in baseSetup(),
leaving no commented dead code.

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.

Feature: Javascript to Typescript conversion in the src folder

1 participant