Skip to content

Conversation

@ShinichiShi
Copy link

@ShinichiShi ShinichiShi commented Oct 20, 2025

Fixes #661

Describe the changes you have made in this PR -

converting the canvas.js to typescript while maintaining the logic and rendering same

Note: Please check Allow edits from maintainers. if you would like us to assist in the PR.

Summary by CodeRabbit

  • Refactor
    • Strengthened the canvas rendering system with enhanced TypeScript type safety and comprehensive validation. Implemented explicit type definitions and detailed type annotations across all drawing functions and parameters. These foundational improvements significantly increase code quality and reliability while enabling better error detection and developer tooling support throughout the development process.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 20, 2025

Walkthrough

TypeScript migration of canvas API code introducing explicit type definitions and function signatures. A new types file defines Direction, DirectionFix, SimulationObject, and Scope interfaces. The main canvasApi.ts file adds type annotations to 20+ exported functions and public constants without altering underlying logic.

Changes

Cohort / File(s) Summary
New Canvas API Type Definitions
src/simulator/src/types/canvasApi.types.ts
Introduces TypeScript type definitions: Direction union ('RIGHT' | 'LEFT' | 'UP' | 'DOWN'), DirectionFix type, SimulationObject interface with dimension properties and methods, Scope interface with scale/offset fields, and global declarations for runtime scope access.
Canvas API Type Safety
src/simulator/src/canvasApi.ts
Adds explicit type annotations to all exported functions (bezierCurveTo, moveTo, lineTo, arc, arc2, drawCircle2, rect, drawImage, rect2, rotate, correctWidth, rotateAngle, drawLine, validColor, colorToRGBA, drawCircle, canvasMessage, fillText, fillText2, fillText3, fillText4); updates public constants oppositeDirection and fixDirection with Record type mappings; strengthens findDimensions, changeScale, and dots signatures with explicit parameter and return types.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

High homogeneity in changes (consistent pattern of adding type annotations across multiple functions), but substantial scope with 20+ function signatures and new type definitions requiring validation against usage patterns throughout the codebase.

Suggested reviewers

  • JoshVarga

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 "Refactor: canvas migration from js to ts" accurately and concisely describes the primary change in the pull request. The changeset focuses on converting the canvas API from JavaScript to TypeScript, introducing explicit type annotations, type definitions, and modernizing the code structure while preserving existing logic. The title is clear, specific enough to convey the intent to a teammate scanning the repository history, and directly reflects what was accomplished in this PR.
Linked Issues Check ✅ Passed The pull request successfully addresses the objectives outlined in linked issue #661. The changeset converts canvasApi.ts from JavaScript to TypeScript with preserved logic, improves type safety through explicit type annotations and new type definitions (Scope, SimulationObject, Direction, DirectionFix), and updates method signatures with proper parameter and return types. The creation of canvasApi.types.ts provides a clean interface layer for these type definitions, and all changes align with the requirement to modernize the code with TypeScript without altering the program's rendering and simulator functionality.
Out of Scope Changes Check ✅ Passed The changes in this PR appear to be consistently in-scope for a TypeScript migration effort. All modifications relate to adding type annotations, updating function signatures with explicit types, creating type definitions, and minor code quality improvements like converting var to let/const and adding null safety guards. These improvements align with the objectives to improve type safety and modernize the codebase during the JavaScript-to-TypeScript conversion. No evidence of unrelated feature additions or significant scope expansion beyond the stated goal of canvas API TypeScript migration is apparent in the summary.
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.

@netlify
Copy link

netlify bot commented Oct 20, 2025

Deploy Preview for circuitverse ready!

Name Link
🔨 Latest commit 2841fa3
🔍 Latest deploy log https://app.netlify.com/projects/circuitverse/deploys/68f635ddce3338000854dce3
😎 Deploy Preview https://deploy-preview-662--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: 45 (no change 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.

@ShinichiShi ShinichiShi reopened this Oct 20, 2025
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

Caution

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

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

86-149: Unsafe type assertions could cause runtime errors.

Lines 125-126 use type assertions (as number) that assume xx and yy are always numbers at that point. However, there are code paths where they might remain 'zoomButton' or undefined:

  1. If method is not 1, 2, or 3
  2. AND the conditions at line 99 don't trigger (i.e., xx and yy are not undefined or 'zoomButton')
  3. OR if they do trigger but there's no valid lastSelected and method is not 1 or 2

In these cases, the type assertions hide potential runtime errors where non-numeric values would be used in arithmetic operations.

Consider adding explicit validation before the type assertions:

+    if (typeof xx !== 'number' || typeof yy !== 'number') {
+        console.warn('Invalid zoom coordinates, using screen center');
+        xx = (width / 2 - globalScope.ox) / globalScope.scale;
+        yy = (height / 2 - globalScope.oy) / globalScope.scale;
+    }
+
     const focusX = xx as number
     const focusY = yy as number

Alternatively, refactor to ensure all code paths assign numeric values or throw an error for invalid cases.

🧹 Nitpick comments (1)
src/simulator/src/types/canvasApi.types.ts (1)

25-32: Consider using var instead of let for global variable declarations.

In TypeScript's declare global blocks, global variables are typically declared with var since let implies block scope. For better TypeScript practices, consider either using var or extending the Window interface.

Apply this diff if you want to use the more idiomatic approach:

 declare global {
-    let globalScope: Scope;
-    let width: number;
-    let height: number;
-    let DPR: number;
-    let embed: boolean;
-    let lightMode: boolean;
+    var globalScope: Scope;
+    var width: number;
+    var height: number;
+    var DPR: number;
+    var embed: boolean;
+    var lightMode: 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 0921d26 and 2841fa3.

📒 Files selected for processing (2)
  • src/simulator/src/canvasApi.ts (23 hunks)
  • src/simulator/src/types/canvasApi.types.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
src/simulator/src/types/canvasApi.types.ts (1)
src/simulator/src/restrictedElementDiv.js (1)
  • globalScope (4-4)
src/simulator/src/canvasApi.ts (4)
src/simulator/src/types/canvasApi.types.ts (4)
  • Scope (18-23)
  • SimulationObject (5-16)
  • Direction (2-2)
  • DirectionFix (3-3)
src/simulator/src/metadata.ts (1)
  • updateOrder (67-72)
src/simulator/src/minimap.js (2)
  • updatelastMinimapShown (175-177)
  • removeMiniMap (178-194)
src/simulator/src/backgroundArea.ts (1)
  • backgroundArea (4-20)
🔇 Additional comments (12)
src/simulator/src/types/canvasApi.types.ts (2)

2-3: LGTM! Direction types are well-defined.

The Direction and DirectionFix types provide good type safety for direction handling throughout the canvas API, with DirectionFix accommodating both upper and lowercase variants.


5-16: SimulationObject interface looks good.

The interface appropriately captures the dimensional properties and methods needed for canvas simulation objects. The index signature [key: string]: any provides flexibility for the migration while the explicitly typed properties ensure type safety for critical fields.

src/simulator/src/canvasApi.ts (10)

7-14: LGTM! Clean imports and constant declaration.

The imports from the new types file are well-organized, and the unit constant is properly typed.


20-77: LGTM! Well-typed dimension finding logic.

The function signature properly types the scope parameter with a default value, and the SimulationObject type provides good type safety for the iteration logic. The function correctly preserves the original behavior while adding type safety.


159-239: LGTM! Properly typed with good defensive checks.

The function signature is well-typed with appropriate default parameters, and the guard check at line 169 prevents null reference errors. The canvas drawing logic correctly preserves the original behavior.


259-505: LGTM! Drawing helpers are well-typed.

The drawing helper functions (bezierCurveTo, moveTo, lineTo, arc, arc2, drawCircle2) have clean type signatures using CanvasRenderingContext2D and Direction types. The bezierCurveTo function adds a defensive null check at line 285, though other helpers rely on callers to provide valid contexts. The logic is correctly preserved from the JavaScript version.


515-602: LGTM! Rectangle and image drawing functions are well-typed.

The rect, drawImage, and rect2 functions use appropriate TypeScript types including CanvasImageSource for the image parameter and Direction with a sensible default value of 'RIGHT' for rect2. Logic is correctly preserved.


611-659: LGTM! Utility functions with correct tuple return types.

The rotate, correctWidth, and rotateAngle functions are properly typed with appropriate return types, including tuple types [number, number] and [number, number, boolean] that accurately represent the multi-value returns. The logic is correctly preserved.


671-761: LGTM! Drawing and color utilities are well-typed.

The drawLine, validColor, colorToRGBA, and drawCircle functions are properly typed. Note that line 725 uses a non-null assertion operator (!) when getting the 2D context, which is generally safe for regular canvas elements but assumes the context will never be null.


771-966: LGTM! Text rendering functions are comprehensively typed.

The text rendering functions (canvasMessage, fillText, fillText2, fillText3, fillText4) are well-typed with appropriate use of CanvasTextAlign, Record<Direction, number> for angle mappings, and sensible default parameters. The functions correctly preserve the original rendering logic while adding type safety.


968-973: LGTM! Opposite direction mapping is correct.

The oppositeDirection constant correctly maps each Direction to its opposite with proper typing using Record<Direction, Direction>.


975-984: Behavior verified as intentional; consider adding clarification comment.

The fixDirection mapping logic is confirmed to be correct and consistent with the original JavaScript implementation across all versions. The dual behavior—normalizing lowercase directions to uppercase while reversing them—is used during data loading and element initialization to handle mixed-format direction values.

The current implementation matches v0 and v1 identically, confirming this is intentional design. Your optional suggestion to add an explanatory comment remains valid for clarity:

export const fixDirection: Record<DirectionFix, Direction> = {
    // Normalize lowercase directions to uppercase and reverse them (for backward compatibility)
    right: 'LEFT',
    left: 'RIGHT',
    down: 'UP',
    up: 'DOWN',
    // Uppercase directions pass through unchanged
    LEFT: 'LEFT',
    RIGHT: 'RIGHT',
    UP: 'UP',
    DOWN: 'DOWN',
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature: Javascript to Typescript conversion in the src folder

2 participants