Skip to content

Conversation

@ShinichiShi
Copy link

@ShinichiShi ShinichiShi commented Oct 20, 2025

Fixes #661

Describe the changes you have made in this PR -

modified setup.js to typescript while maintaining the logic

Summary by CodeRabbit

  • Refactor

    • Improved startup stability via stronger type safety, stricter element validation, and safer environment handling (display scale, embed/light mode).
  • Bug Fixes

    • More reliable project loading with guarded data handling and clearer routing when version info is missing.
    • Safer layout, canvas sizing and redraw flows to prevent rendering or empty-screen issues.
    • More robust tutorial/tour visibility and error handling during setup.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 20, 2025

Walkthrough

Converted JavaScript setup logic in src/simulator/src/setup.ts to TypeScript with explicit return types, stricter DOM and window property guards, and safer data/loading flows. Added global Window augmentation and a ProjectData interface in src/simulator/src/types/setup.types.ts.

Changes

Cohort / File(s) Summary
Setup logic (conversion + stricter guards)
src/simulator/src/setup.ts
Added explicit type annotations and return types (void, Promise<void>) to setup-related functions (resetup, setupEnvironment, fetchProjectData, loadProjectData, showTour, setup). Introduced a local PlotArea interface and imported ProjectData. Replaced direct global accesses with window-prefixed properties and added existence checks for critical DOM elements. Refactored layout/canvas sizing, guarded DOM manipulations, adjusted drawing/resize flow, expanded environment setup call signature, and added error handling around data loading and localStorage usage.
Type definitions (globals + ProjectData)
src/simulator/src/types/setup.types.ts
Added global Window augmentation with properties: projectId, data, logixProjectId, isUserLoggedIn, DPR, width, height, embed, lightMode. Exported ProjectData interface with optional timePeriod, optional simulatorVersion, optional name, and an index signature for additional keys.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • 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 pull request title "refactor setup.js to ts" directly and clearly summarizes the main change in the changeset, which is the conversion of the setup.js file from JavaScript to TypeScript. The title is concise, specific, and accurately reflects the primary objective of the PR. It avoids vague terminology and provides a teammate scanning the history with clear understanding of what was changed.
Linked Issues Check ✅ Passed The code changes align with the requirements specified in linked issue #661. The PR successfully converts setup.js to TypeScript by adding explicit return types to functions, introducing type annotations for parameters, and creating a new types file (setup.types.ts) with proper TypeScript interfaces and Window augmentation. The changes preserve existing runtime logic while improving type safety through proper type definitions, null/existence checks, and type guards—all core objectives of the JavaScript-to-TypeScript conversion feature request. The PR description confirms that existing functionality is maintained and only interfaces, data types, and type safety have been improved.
Out of Scope Changes Check ✅ Passed All code changes in this PR are directly related to the TypeScript conversion objectives outlined in issue #661. The modifications to setup.ts include type annotations, return type declarations, interface definitions, and type-safety improvements—all integral to the conversion process and explicitly permitted by the feature request. The new setup.types.ts file introduces TypeScript type definitions and Window augmentation, which directly support the goal of improving type safety. No unrelated refactoring, logic changes, or new features have been introduced beyond what is necessary for the JavaScript-to-TypeScript conversion.
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 e8decbe
🔍 Latest deploy log https://app.netlify.com/projects/circuitverse/deploys/68f6928582d186000869e99a
😎 Deploy Preview https://deploy-preview-666--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: 46 (🟢 up 1 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: 4

🧹 Nitpick comments (3)
src/simulator/src/types/setup.types.ts (2)

4-4: Consider a more specific type than any for the data property.

Using Record<string, any> weakens type safety. If the structure is unknown, consider using Record<string, unknown> which requires type guards before usage, or define a more specific interface based on how window.data is actually used in the codebase.

-    data: Record<string, any>;
+    data: Record<string, unknown>;

15-18: Strengthen type safety in ProjectData interface.

The index signature [key: string]: any significantly weakens type safety. Consider defining specific properties based on the actual project data structure, or use unknown instead of any to enforce type guards at usage sites.

 export interface ProjectData {
   timePeriod?: number;
-  [key: string]: any;
+  [key: string]: unknown;
 }
src/simulator/src/setup.ts (1)

136-137: Type cast to any defeats type safety.

Line 137 casts to any when calling the load function, which bypasses TypeScript's type checking. From the relevant code snippets, load.js is still a JavaScript file without type annotations.

Consider either:

  1. Converting load.js to TypeScript with proper typing, OR
  2. Creating a proper type definition file for the load function, OR
  3. At minimum, add a comment explaining why the cast is necessary
📜 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 b7ee90c.

📒 Files selected for processing (2)
  • src/simulator/src/setup.ts (7 hunks)
  • src/simulator/src/types/setup.types.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/simulator/src/setup.ts (5)
src/simulator/src/backgroundArea.ts (1)
  • backgroundArea (4-20)
src/simulator/src/interface/backgroundArea.ts (1)
  • BackgroundArea (1-6)
src/simulator/src/circuit.ts (1)
  • newCircuit (210-272)
src/simulator/src/types/setup.types.ts (1)
  • ProjectData (15-18)
src/simulator/src/data/load.js (1)
  • load (207-293)
🔇 Additional comments (2)
src/simulator/src/setup.ts (2)

70-85: Good defensive null checks.

These null checks are well-implemented and prevent potential runtime errors. This is the pattern that should be followed consistently throughout the function (see comments on lines 54 and 60).


162-169: Good null safety improvements.

The null checks before parsing localStorage items (lines 162-163) prevent potential runtime errors. This is a solid improvement over the previous implementation.

Note: Line 165 has the same as any cast issue mentioned in the comment for lines 136-137.

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

♻️ Duplicate comments (2)
src/simulator/src/setup.ts (2)

191-197: Use window.embed (bare embed will fail TS and is inconsistent).

Access the global via Window augmentation for consistency and to avoid TS compile errors.

-    if (!localStorage.getItem('tutorials_tour_done') && !embed) {
+    if (!localStorage.getItem('tutorials_tour_done') && !window.embed) {
@@
-    if (!embed) {
+    if (!window.embed) {

Run to confirm no bare globals remain:

#!/bin/bash
rg -nP -C1 '(?<!\.)\b(embed|DPR|width|height)\b' src/simulator/src/setup.ts

Also applies to: 205-214


45-61: Good: replaced non-null assertions with explicit null checks.

Safer, aligns with defensive patterns and avoids runtime crashes.

🧹 Nitpick comments (2)
src/simulator/src/setup.ts (2)

30-32: Avoid local interface + cast for plotArea; add a .d.ts or convert to TS.

The local cast hides API drift. Provide real types so you can call plotArea.setup() without assertions.

  • Create src/simulator/src/plotArea.d.ts:
declare const plotArea: {
  setup(): void
  reset(): void
}
export default plotArea
  • Then remove the local interface and cast:
-interface PlotArea {
-    setup: () => void
-}
@@
-        ;(plotArea as PlotArea).setup()
+        plotArea.setup()

Also applies to: 87-89


112-114: Type window.data to ProjectData for clarity.

Improves type-safety and self-documentation.

-    window.data = {}
+    window.data = {} as ProjectData
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b7ee90c and f84df4a.

📒 Files selected for processing (1)
  • src/simulator/src/setup.ts (7 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/simulator/src/setup.ts (5)
src/simulator/src/backgroundArea.ts (1)
  • backgroundArea (4-20)
src/simulator/src/canvasApi.js (1)
  • dots (122-203)
src/simulator/src/circuit.ts (1)
  • newCircuit (210-272)
src/simulator/src/types/setup.types.ts (1)
  • ProjectData (15-18)
src/simulator/src/data/load.js (1)
  • load (207-293)

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

🧹 Nitpick comments (1)
src/simulator/src/setup.ts (1)

174-208: Good error handling; simplify redundant cast.

The try-catch blocks appropriately handle errors during data loading and recovery. However, line 190 contains a redundant cast since JSON.parse() returns any by default.

Apply this diff to simplify the cast:

-                const data = JSON.parse(item) as unknown as ProjectData
+                const data = JSON.parse(item) as ProjectData

The as any cast on line 191 is acceptable technical debt while load.js remains untyped.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f84df4a and e8decbe.

📒 Files selected for processing (2)
  • src/simulator/src/setup.ts (7 hunks)
  • src/simulator/src/types/setup.types.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/simulator/src/types/setup.types.ts
🧰 Additional context used
🧬 Code graph analysis (1)
src/simulator/src/setup.ts (8)
src/simulator/src/backgroundArea.ts (1)
  • backgroundArea (4-20)
src/simulator/src/canvasApi.js (1)
  • dots (122-203)
src/simulator/src/moduleSetup.js (1)
  • setupModules (67-135)
src/simulator/src/utils.ts (2)
  • generateId (25-35)
  • showMessage (66-71)
src/simulator/src/engine.js (1)
  • updateSimulationSet (99-101)
src/simulator/src/circuit.ts (1)
  • newCircuit (210-272)
src/simulator/src/types/setup.types.ts (1)
  • ProjectData (15-20)
src/simulator/src/data/load.js (1)
  • load (207-293)
🔇 Additional comments (6)
src/simulator/src/setup.ts (6)

28-32: Good approach for typing untyped dependencies.

The local PlotArea interface is a clean workaround for typing the imported JavaScript plotArea module during incremental conversion.


40-94: Excellent defensive programming and type safety.

The function properly:

  • Guards all DOM element accesses with null checks
  • Throws clear errors when critical elements are missing
  • Guards optional elements before style updates
  • Uses window-prefixed global properties consistently

The cast on line 88 is appropriate for interacting with the untyped plotArea module.


107-117: LGTM!

The explicit arguments to newCircuit clearly convey intent and match the expected function signature.


124-167: Well-structured with proper error handling.

The function correctly:

  • Returns early after redirects to prevent further execution
  • Uses strict equality and URL encoding for project names
  • Handles errors gracefully with try-catch

The as any cast on line 156 is acceptable technical debt while load.js remains untyped during incremental conversion.


216-222: LGTM!

The localStorage check correctly identifies when the tour hasn't been completed, and the condition properly guards against showing the tour in embed mode.


230-239: Solid entry point for simulator initialization.

The function properly orchestrates the setup sequence with clear, logical steps. The TypeScript conversion preserves the original functionality while adding type safety.

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