Skip to content

refactor: convert circuitElement.js to TypeScript#814

Open
pantha704 wants to merge 2 commits intoCircuitVerse:mainfrom
pantha704:ts-circuitElement#661
Open

refactor: convert circuitElement.js to TypeScript#814
pantha704 wants to merge 2 commits intoCircuitVerse:mainfrom
pantha704:ts-circuitElement#661

Conversation

@pantha704
Copy link
Contributor

@pantha704 pantha704 commented Jan 17, 2026

Part of #661 (1 file per PR rule)

Changes

Converted circuitElement.js to TypeScript in both src/ and v1/src/.

TypeScript Improvements

  • Added 40+ class property declarations with explicit types
  • Added method return type annotations for all 43 methods (: void, : boolean, : string, : number, : any)
  • Replaced var with const/let throughout
  • Added proper type casts (this as any) for subclass-specific methods (click, customDraw, subcircuitDraw, releaseClick)
  • Added JSDoc documentation for all methods
  • Constructor parameter types added

No Logic Changes

  • ✅ Same class structure: CircuitElement base class
  • ✅ Same 43 exported methods
  • ✅ Same prototype properties
  • ✅ Same behavior, only added type safety
  • ✅ Build passes (bun run build)

Code Understanding and AI Usage

  • I have reviewed every single line of the changes
  • I can explain the purpose of each type annotation
  • No logic was changed, only types added

Summary by CodeRabbit

  • Refactor
    • Internal overhaul for stronger type safety and clearer method contracts across core circuit elements, improving stability and reducing runtime issues.
    • Enhances reliability of circuit editing, layout interactions, drawing behavior and Verilog export, leading to a smoother, more predictable user experience.

✏️ Tip: You can customize this high-level summary in your review settings.

Part of CircuitVerse#661 (1 file per PR rule)

- Added 40+ class property declarations with explicit types
- Added method return type annotations for all 43 methods
- Replaced var with const/let throughout
- Added proper type casts (this as any) for subclass methods
- Added JSDoc documentation
- Applied same changes to v1/src

No logic changes - strictly TypeScript migration.
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 17, 2026

Walkthrough

This change refactors CircuitElement to TypeScript by adding explicit public properties (e.g., x, y, hover, label, bitWidth, direction, layout and verilog metadata) and formalizing the constructor signature (constructor(x: number, y: number, scope: any, dir: string, bitWidth: number)). Many previously untyped methods were converted to typed signatures with explicit parameter and return types, newOrientation was added as a public method, and calls to optional overrides were guarded using typed forms. Documentation comments were updated to match the new typings.

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title 'refactor: convert circuitElement.js to TypeScript' accurately and directly describes the main change in the changeset—converting a JavaScript file to TypeScript with type annotations.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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.

@netlify
Copy link

netlify bot commented Jan 17, 2026

Deploy Preview for circuitverse ready!

Name Link
🔨 Latest commit e7a4be1
🔍 Latest deploy log https://app.netlify.com/projects/circuitverse/deploys/696b5958709523000814813e
😎 Deploy Preview https://deploy-preview-814--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: 51 (🟢 up 7 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.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/simulator/src/circuitElement.ts (1)

847-855: Validate numeric inputs to avoid NaN state.

newBitWidth checks this.bitWidth instead of the incoming bitWidth, and changePropagationDelay can set propagationDelay = NaN if parsing fails. A small guard prevents invalid state.

🐛 Suggested validation
     newBitWidth(bitWidth: number): void {
         if (this.fixedBitWidth) return
         if (this.bitWidth === undefined) return
-        if (this.bitWidth < 1) return
+        if (!Number.isFinite(bitWidth) || bitWidth < 1) return
         this.bitWidth = bitWidth
@@
     changePropagationDelay(delay: any): void {
         if (this.propagationDelayFixed) return
         if (delay === undefined) return
         if (delay === '') return
-        const tmpDelay = parseInt(delay, 10)
-        if (tmpDelay < 0) return
+        const tmpDelay = Number.parseInt(delay, 10)
+        if (!Number.isFinite(tmpDelay) || tmpDelay < 0) return
         this.propagationDelay = tmpDelay
     }

Also applies to: 862-869

v1/src/simulator/src/circuitElement.ts (1)

847-855: Validate numeric inputs to avoid NaN state.

newBitWidth checks this.bitWidth instead of the incoming bitWidth, and changePropagationDelay can set propagationDelay = NaN if parsing fails. A small guard prevents invalid state.

🐛 Suggested validation
     newBitWidth(bitWidth: number): void {
         if (this.fixedBitWidth) return
         if (this.bitWidth === undefined) return
-        if (this.bitWidth < 1) return
+        if (!Number.isFinite(bitWidth) || bitWidth < 1) return
         this.bitWidth = bitWidth
@@
     changePropagationDelay(delay: any): void {
         if (this.propagationDelayFixed) return
         if (delay === undefined) return
         if (delay === '') return
-        const tmpDelay = parseInt(delay, 10)
-        if (tmpDelay < 0) return
+        const tmpDelay = Number.parseInt(delay, 10)
+        if (!Number.isFinite(tmpDelay) || tmpDelay < 0) return
         this.propagationDelay = tmpDelay
     }

Also applies to: 862-869

🤖 Fix all issues with AI agents
In `@v1/src/simulator/src/circuitElement.ts`:
- Around line 389-390: The code calls subcircuitDraw() unguarded which throws on
subclasses that don't implement it; update the call to only invoke
subcircuitDraw when it exists (e.g., check typeof this.subcircuitDraw ===
'function' or use optional chaining) similar to the existing guard for
releaseClick() that checks this.objectType === 'SubCircuit'; locate the
unguarded call to subcircuitDraw() in CircuitElement and wrap it with the
existence check so non-implementing subclasses won't raise a TypeError.
🧹 Nitpick comments (2)
v1/src/simulator/src/circuitElement.ts (1)

70-101: Align bitWidth type with the runtime fallback.

Line 70–101: the implementation clearly tolerates undefined and prompts for a value, but the signature requires number. While all current call sites pass this argument, making bitWidth optional would improve the API design and better reflect the implementation's behavior.

🛠️ Proposed adjustment
-    constructor(x: number, y: number, scope: any, dir: string, bitWidth: number) {
+    constructor(x: number, y: number, scope: any, dir: string, bitWidth?: number) {
@@
-        this.bitWidth = bitWidth || parseInt(prompt('Enter bitWidth') || '1', 10) || 1
+        const resolvedBitWidth =
+            bitWidth || parseInt(prompt('Enter bitWidth') || '1', 10) || 1
+        this.bitWidth = resolvedBitWidth
src/simulator/src/circuitElement.ts (1)

70-101: Consider making bitWidth optional for consistency with the defensive fallback logic.

Line 100 implements a fallback pattern (bitWidth || parseInt(prompt(...)) || 1) suggesting undefined is acceptable, but the signature requires bitWidth: number. While all current call sites pass a value explicitly, aligning the signature with the implementation pattern would improve consistency and clarify intent if future code needs to omit the parameter.

Proposed adjustment
-    constructor(x: number, y: number, scope: any, dir: string, bitWidth: number) {
+    constructor(x: number, y: number, scope: any, dir: string, bitWidth?: number) {
@@
-        this.bitWidth = bitWidth || parseInt(prompt('Enter bitWidth') || '1', 10) || 1
+        const resolvedBitWidth =
+            bitWidth || parseInt(prompt('Enter bitWidth') || '1', 10) || 1
+        this.bitWidth = resolvedBitWidth

Addresses CodeRabbit feedback - guard subcircuitDraw() call to prevent
runtime errors on subclasses that don't implement it. Similar to the
existing guard on releaseClick() (line 389).
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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
v1/src/simulator/src/circuitElement.ts (1)

880-918: Add TypeScript declarations for global constants used without imports.

NODE_OUTPUT and NODE_INPUT (lines 885, 893, 951, 997) are currently defined on window in node.js and used throughout circuitElement.ts without explicit imports. Similarly, width and height are defined on window in globalVariables.ts but lack type declarations. These globals should be declared in a TypeScript declaration file (.d.ts) to enable proper type checking and IDE support.

Create or update a declaration file (e.g., src/simulator/src/globals.d.ts) to declare:

declare global {
  var NODE_OUTPUT: number;
  var NODE_INPUT: number;
  var NODE_INTERMEDIATE: number;
  var width: number | undefined;
  var height: number | undefined;
}
src/simulator/src/circuitElement.ts (1)

880-918: Add TypeScript declarations for window globals in .d.ts file.

NODE_OUTPUT, NODE_INPUT, width, and height are assigned to the window object but lack proper TypeScript type declarations. With strict: true in tsconfig.json, extend the Window interface in a .d.ts file (e.g., src/env.d.ts) to declare these properties with their correct types:

interface Window {
    NODE_INPUT: number
    NODE_OUTPUT: number
    NODE_INTERMEDIATE: number
    width: number | undefined
    height: number | undefined
}

This ensures type safety in strict mode for both src/simulator/src/ and v1/src/simulator/src/ code paths.

🤖 Fix all issues with AI agents
In `@src/simulator/src/circuitElement.ts`:
- Around line 217-221: The JSDoc for the method checkHover() incorrectly states
"@return boolean" while the method signature returns void; update the JSDoc to
match by either removing the "@return" tag or replacing it with "@returns
{void}" (or an explanatory comment) so the comment for checkHover() accurately
reflects its void return type.

In `@v1/src/simulator/src/circuitElement.ts`:
- Around line 217-221: The JSDoc for the checkHover method is out of sync: it
declares "@return boolean" but the method signature is "checkHover(): void";
update the documentation to match the code by either removing the "@return" tag
or changing it to "@return void" (or "@returns void") to reflect that checkHover
does not return a value, and ensure the JSDoc sits immediately above the
checkHover() method declaration.
🧹 Nitpick comments (4)
v1/src/simulator/src/circuitElement.ts (3)

27-68: Well-structured TypeScript property declarations.

The explicit type declarations for all class properties provide good type safety. However, two properties assigned on the prototype (lines 1024, 1036) are missing from these declarations:

🔧 Add missing property declarations
     layoutProperties: any
     overrideDirectionRotation: boolean
+    tooltip: any
+    subcircuitMutableProperties: any

     constructor(x: number, y: number, scope: any, dir: string, bitWidth: number) {

100-100: Consider extracting the prompt fallback logic.

The prompt() call in the constructor is a blocking UI side-effect. While this is preserved behavior from the original JS, consider refactoring in a future PR to accept bitWidth as a required parameter or use a callback/event pattern for missing values.


1022-1047: Consider migrating prototype assignments to class-level declarations.

Prototype assignments after the class definition work but bypass TypeScript's type system for these properties. For future maintainability, consider moving these to static properties or initializing them in the constructor with proper class property declarations.

This is acceptable for the current migration scope but worth tracking for a future cleanup.

src/simulator/src/circuitElement.ts (1)

27-68: Same property declarations as v1 version - add missing properties.

As with the v1 version, tooltip and subcircuitMutableProperties are assigned on the prototype (lines 1024, 1036) but not declared as class properties. Add these declarations for consistency.

Comment on lines 217 to +221
/**
* check hover over the element
* @return {boolean}
* @return boolean
*/
checkHover() {
checkHover(): void {
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 | 🟡 Minor

Same JSDoc inconsistency - @return boolean on void method.

Update or remove the @return tag to match the void return type.

🤖 Prompt for AI Agents
In `@src/simulator/src/circuitElement.ts` around lines 217 - 221, The JSDoc for
the method checkHover() incorrectly states "@return boolean" while the method
signature returns void; update the JSDoc to match by either removing the
"@return" tag or replacing it with "@returns {void}" (or an explanatory comment)
so the comment for checkHover() accurately reflects its void return type.

Comment on lines 217 to +221
/**
* check hover over the element
* @return {boolean}
* @return boolean
*/
checkHover() {
checkHover(): void {
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 | 🟡 Minor

JSDoc @return is inconsistent with method signature.

The JSDoc says @return boolean but the method is typed as checkHover(): void. Either remove the @return tag or update it to match the actual return type.

🔧 Fix JSDoc
     /**
      * check hover over the element
-     * `@return` boolean
      */
     checkHover(): void {
📝 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
/**
* check hover over the element
* @return {boolean}
* @return boolean
*/
checkHover() {
checkHover(): void {
/**
* check hover over the element
*/
checkHover(): void {
🤖 Prompt for AI Agents
In `@v1/src/simulator/src/circuitElement.ts` around lines 217 - 221, The JSDoc for
the checkHover method is out of sync: it declares "@return boolean" but the
method signature is "checkHover(): void"; update the documentation to match the
code by either removing the "@return" tag or changing it to "@return void" (or
"@returns void") to reflect that checkHover does not return a value, and ensure
the JSDoc sits immediately above the checkHover() method declaration.

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.

1 participant