Skip to content

Conversation

@senutpal
Copy link

@senutpal senutpal commented Dec 12, 2025

Description

Migrates canvasApi.js to TypeScript (canvasApi.ts) as part of the ongoing JS-to-TS migration in src/simulator/src/.

Fixes #661

Changes Made

Type Definitions

  • Added Direction type ('RIGHT' | 'LEFT' | 'UP' | 'DOWN') for element orientation
  • Added CanvasContext type alias for CanvasRenderingContext2D
  • Added MiniMapArea interface with TODO for unmigrated minimap.js dependency
  • Added DirectionAngleMap interface for text rotation angles
  • Exported Direction type for use by other modules

Improvements

  • Replaced all var with const/let throughout
  • Added explicit type annotations for all 31 functions:
    • Canvas path functions: moveTo, lineTo, bezierCurveTo
    • Arc/circle functions: arc, arc2, drawCircle, drawCircle2
    • Rectangle functions: rect, rect2
    • Text functions: fillText, fillText2, fillText3, fillText4, canvasMessage
    • Utility functions: rotate, rotateAngle, correctWidth, validColor, colorToRGBA
    • Core functions: findDimensions, changeScale, dots, drawLine, drawImage
  • Added typed constants with Readonly<Record<...>> and as const:
    • oppositeDirection: Maps directions to their opposites
    • fixDirection: Normalizes direction input strings
  • Added comprehensive JSDoc documentation with @param, @returns, @example, and @category tags
  • Added TODO comments for future migration tracking (globalScope, MiniMapArea)
  • Added proper null checks for canvas contexts

Testing

  • TypeScript compiles without errors specific to canvasApi.ts (verified via tsc --noEmit)
  • Existing circuit functionality works as expected

Summary by CodeRabbit

  • Refactor
    • Modernized canvas rendering utilities with improved type safety and structure. Drawing functionality remains unchanged, with better maintainability and code organization.

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

@netlify
Copy link

netlify bot commented Dec 12, 2025

Deploy Preview for circuitverse ready!

Name Link
🔨 Latest commit e8a01b8
🔍 Latest deploy log https://app.netlify.com/projects/circuitverse/deploys/693c0f68334c540008f2ae30
😎 Deploy Preview https://deploy-preview-694--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: 40 (🔴 down 4 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 Dec 12, 2025

Walkthrough

Converts the canvasApi drawing utilities module from JavaScript to TypeScript, adding type annotations and type safety improvements. Introduces Direction type, function parameter types, return type declarations, and type aliases. Logic and functionality remain unchanged; this is a pure migration with type layer additions.

Changes

Cohort / File(s) Change Summary
TypeScript Migration
src/simulator/src/canvasApi.jssrc/simulator/src/canvasApi.ts
Removed JavaScript implementation of canvas drawing utilities module with 25+ exported functions and helpers (findDimensions, changeScale, dots, shape primitives, text rendering, direction mappings). Added TypeScript version with identical logic and full type annotations: Direction enum-like type, CanvasContext alias, typed function signatures, and typed constants (oppositeDirection, fixDirection). No functional changes.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Type annotation accuracy: Verify that all 25+ function signatures (shape drawing, text rendering, transformations) have correct parameter and return types
  • Direction type usage: Ensure the new Direction type ('RIGHT'|'LEFT'|'UP'|'DOWN') is consistently applied across all direction-dependent functions (arc, arc2, rotate, fillText2, fillText4, etc.)
  • Global variable declarations: Confirm type declarations for globalScope, width, height, DPR, embed, and lightMode are properly declared or match expected runtime environment types
  • Type imports and interfaces: Verify CanvasRenderingContext2D and CanvasImageSource types are correctly imported/available and MiniMapArea interface aligns with actual minimap module
  • Constant exports: Validate that oppositeDirection and fixDirection mappings retain correct structure and values from the original JavaScript

Suggested reviewers

  • JoshVarga
  • vedant-jain03
  • Arnabdaz

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: migrating canvasApi.js to TypeScript, which matches the primary objective of the PR.
Linked Issues check ✅ Passed The PR fulfills all coding requirements from issue #661: converts a single JavaScript file to TypeScript, preserves existing logic, adds type safety through explicit type annotations, Direction type, and CanvasContext alias, without changing core functionality.
Out of Scope Changes check ✅ Passed All changes are directly related to the TypeScript migration objective; no unrelated modifications or refactoring of functionality outside the scope of type conversion and type safety improvements were introduced.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ 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: 2

🧹 Nitpick comments (4)
src/simulator/src/canvasApi.ts (4)

36-37: Export CanvasContext if it’s intended as part of the public API.
Right now CanvasContext is file-local (type CanvasContext = ...). If other modules are expected to import it, change to export type CanvasContext = CanvasRenderingContext2D;.


193-198: Narrow xx/yy types to prevent invalid strings being cast to numbers.
xx?: number | string + focalX = xx as number will happily accept any string at runtime. If the only sentinel is 'zoomButton', prefer: xx?: number | 'zoomButton' (same for yy).

Also applies to: 209-238


250-260: Minor: duplicated miniMap.style.display = 'block'.
Line 255 and Line 257 both set the same value; one can be removed.


982-1011: Simplify/verify the baseline offset math in fillText2 (currently a no-op).
Math.round(4 * globalScope.scale) * (1 - 0 * +(dir === 'DOWN')) always evaluates to Math.round(4 * globalScope.scale). If DOWN-specific behavior is intended, make it explicit; otherwise simplify.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 11b4883 and e8a01b8.

📒 Files selected for processing (2)
  • src/simulator/src/canvasApi.js (0 hunks)
  • src/simulator/src/canvasApi.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • src/simulator/src/canvasApi.js

Comment on lines +122 to +128
export function findDimensions(scope: any = globalScope): void {
let totalObjects = 0;
simulationArea.minWidth = undefined as unknown as number;
simulationArea.maxWidth = undefined as unknown as number;
simulationArea.minHeight = undefined as unknown as number;
simulationArea.maxHeight = undefined as unknown as number;

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

Avoid undefined as unknown as number for min/max bounds—this defeats type safety.
This pattern can propagate invalid numeric states. Prefer typing simulationArea.minWidth/etc as number | undefined (or initialize to Infinity/-Infinity and handle the “no objects” case explicitly).

Also applies to: 171-172

🤖 Prompt for AI Agents
In src/simulator/src/canvasApi.ts around lines 122-128 (and also apply to
171-172), do not use "undefined as unknown as number" to set min/max bounds;
instead change the types of simulationArea.minWidth/minHeight/maxWidth/maxHeight
to number | undefined or initialize them to safe numeric sentinels (e.g.,
Infinity for mins and -Infinity for maxes) and update the logic that computes
and checks these values to handle the "no objects" case explicitly; ensure
assignments and comparisons use the chosen approach consistently and remove the
unsafe type cast.

Comment on lines +1114 to +1123
export const fixDirection: Readonly<Record<string, Direction>> = {
right: 'LEFT',
left: 'RIGHT',
down: 'UP',
up: 'DOWN',
LEFT: 'LEFT',
RIGHT: 'RIGHT',
UP: 'UP',
DOWN: 'DOWN',
} as const;
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 | 🔴 Critical

fixDirection appears inverted (likely breaks rotation/orientation).
The mapping claims to “normalize direction values”, but currently maps right -> 'LEFT', down -> 'UP', etc. That’s the opposite of normalization and is very likely a functional regression.

Proposed fix:

 export const fixDirection: Readonly<Record<string, Direction>> = {
-    right: 'LEFT',
-    left: 'RIGHT',
-    down: 'UP',
-    up: 'DOWN',
+    right: 'RIGHT',
+    left: 'LEFT',
+    down: 'DOWN',
+    up: 'UP',
     LEFT: 'LEFT',
     RIGHT: 'RIGHT',
     UP: 'UP',
     DOWN: 'DOWN',
 } as const;
📝 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 const fixDirection: Readonly<Record<string, Direction>> = {
right: 'LEFT',
left: 'RIGHT',
down: 'UP',
up: 'DOWN',
LEFT: 'LEFT',
RIGHT: 'RIGHT',
UP: 'UP',
DOWN: 'DOWN',
} as const;
export const fixDirection: Readonly<Record<string, Direction>> = {
right: 'RIGHT',
left: 'LEFT',
down: 'DOWN',
up: 'UP',
LEFT: 'LEFT',
RIGHT: 'RIGHT',
UP: 'UP',
DOWN: 'DOWN',
} as const;
🤖 Prompt for AI Agents
In src/simulator/src/canvasApi.ts around lines 1114 to 1123, the fixDirection
mapping is inverted (e.g., right -> 'LEFT', down -> 'UP'), which reverses
intended normalization; update the object so each lowercase key maps to the
corresponding uppercase direction (right -> 'RIGHT', left -> 'LEFT', up -> 'UP',
down -> 'DOWN') while keeping the existing uppercase entries unchanged, ensuring
the mapping returns the canonical Direction for each input.

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