Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: ts in plotArea.js #478

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

gitsofaryan
Copy link

@gitsofaryan gitsofaryan commented Feb 12, 2025

Fixes: #414


Description

  • Centralized functions and components into a single object plotArea, improving organization and maintainability.
  • Defined an interface PlotArea for type safety and consistency.
  • Added helper functions and event listeners for additional logic and interactivity.

Summary by CodeRabbit

  • Refactor
    • Streamlined simulation rendering components to improve robustness and reliability.
    • Enhanced code practices to ensure consistent performance and smoother interactions during simulations.

These internal improvements help deliver a more stable experience while maintaining the same user interface.

Copy link
Contributor

coderabbitai bot commented Feb 12, 2025

Walkthrough

This update refactors the plotArea.ts file to enhance type safety and modernize coding practices. Key changes include converting mutable variables from var to const or let, adding explicit type annotations to function parameters and return values, and defining interfaces for both PlotArea and TimingDiagramButtonActions. Method implementations now include proper type checks and non-null assertions for canvas elements and context usage. These modifications ensure that the codebase adheres to strict TypeScript standards and improves overall clarity.

Changes

File Change Summary
src/simulator/.../plotArea.ts - Converted DPR from var to const and loop variables from var to let for better scoping.
- Added explicit type annotations to functions (sh, getFullHeight, getFlagStartY, getCycleStartX, getPlotTime, getCurrentTime).
- Transformed plotArea object into a PlotArea interface and instantiated accordingly.
- Updated methods (reset, download, resize, etc.) to include type checks and non-null assertions.
- Defined and applied TimingDiagramButtonActions interface for button actions.

Poem

I'm a bunny coder with ears so keen,
Hopping through refactors in a TypeScript scene.
With const and let, my code now sings,
Interfaces and safety give my soul its wings.
In PlotArea’s garden, bugs are out of sight—
A rabbit’s delight in code so bright!

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

netlify bot commented Feb 12, 2025

Deploy Preview for circuitverse ready!

Name Link
🔨 Latest commit d71464f
🔍 Latest deploy log https://app.netlify.com/sites/circuitverse/deploys/67ac3e08622527000894ef44
😎 Deploy Preview https://deploy-preview-478--circuitverse.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site 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: 0

🔭 Outside diff range comments (1)
src/simulator/src/plotArea.ts (1)

451-479: 🛠️ Refactor suggestion

Improve event listener management and mouse event handling.

  1. Add cleanup for event listeners to prevent memory leaks
  2. Add error handling for mouse events
  3. Consider using a debounce for mousemove events
 export function setupTimingListeners() {
+    const plotAreaElement = document.getElementById('plotArea')
+    if (!plotAreaElement) {
+        console.error('Plot area element not found')
+        return
+    }
+
+    const handleMouseDown = (e: MouseEvent) => {
         const rect = plotArea.canvas!.getBoundingClientRect()
         const x = sh(e.clientX - rect.left)
         // ... rest of the mousedown logic
-    })
+    }
+
+    plotAreaElement.addEventListener('mousedown', handleMouseDown)
     // ... similar for other event listeners
+
+    // Return cleanup function
+    return () => {
+        plotAreaElement.removeEventListener('mousedown', handleMouseDown)
+        // ... remove other listeners
+    }
 }
🧹 Nitpick comments (4)
src/simulator/src/plotArea.ts (4)

23-28: Convert mutable variables to constants.

These variables don't appear to be modified after initialization. Consider converting them to const for better immutability and code safety.

-let timeLineHeight = sh(20)
-let padding = sh(2)
-let plotHeight = sh(20)
-let waveFormPadding = sh(5)
-let waveFormHeight = plotHeight - 2 * waveFormPadding
-let flagLabelWidth = sh(75)
+const timeLineHeight = sh(20)
+const padding = sh(2)
+const plotHeight = sh(20)
+const waveFormPadding = sh(5)
+const waveFormHeight = plotHeight - 2 * waveFormPadding
+const flagLabelWidth = sh(75)

50-86: Add JSDoc comments to the PlotArea interface.

Consider adding JSDoc comments to document the purpose and usage of each property and method in the interface. This will improve code maintainability and developer experience.

+/**
+ * Interface representing the plot area for timing diagrams.
+ */
 interface PlotArea {
+  /** Current cycle offset for scrolling */
   cycleOffset: number
+  /** Device pixel ratio */
   DPR: number
+  /** Canvas element reference */
   canvas: HTMLCanvasElement | null
   // ... add comments for other properties and methods
 }

139-146: Add error handling to the download method.

The method could fail silently if the canvas is null or if there are issues with creating/downloading the image.

 download() {
-    if (!this.canvas) return
+    if (!this.canvas) {
+        console.warn('Cannot download: Canvas is not initialized')
+        return
+    }
     const img = this.canvas.toDataURL('image/png')
     const anchor = document.createElement('a')
     anchor.href = img
     anchor.download = 'waveform.png'
-    anchor.click()
+    try {
+        anchor.click()
+    } catch (error) {
+        console.error('Failed to download waveform:', error)
+    }
 }

191-217: Extract magic numbers into named constants.

The utilization thresholds (90, 10) and the recommended unit multiplier (3) should be extracted into named constants for better maintainability.

+const UTILIZATION_HIGH_THRESHOLD = 90
+const UTILIZATION_LOW_THRESHOLD = 10
+const MIN_RECOMMENDED_UNITS = 20
+const RECOMMENDED_UNIT_MULTIPLIER = 3

 update() {
     // ...
-    if (utilization >= 90 || utilization <= 10) {
-        const recommendedUnit = Math.max(20, Math.round(unitUsed * 3))
+    if (utilization >= UTILIZATION_HIGH_THRESHOLD || utilization <= UTILIZATION_LOW_THRESHOLD) {
+        const recommendedUnit = Math.max(MIN_RECOMMENDED_UNITS, Math.round(unitUsed * RECOMMENDED_UNIT_MULTIPLIER))
     // ...
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1ea73f2 and d71464f.

📒 Files selected for processing (1)
  • src/simulator/src/plotArea.ts (11 hunks)

@gitsofaryan
Copy link
Author

@vedant-jain03 @Arnabdaz Please review changes!!

@@ -1,12 +1,13 @@
import { simulationArea } from './simulationArea'
import { globalScope } from './globalScope'
Copy link
Member

@ThatDeparted2061 ThatDeparted2061 Feb 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no such file as globalscope
Why have you done this ?

Comment on lines +23 to +29
let timeLineHeight = sh(20)
let padding = sh(2)
let plotHeight = sh(20)
let waveFormPadding = sh(5)
let waveFormHeight = plotHeight - 2 * waveFormPadding
let flagLabelWidth = sh(75)
let cycleWidth = sh(30)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using let reduces the type-safety, this defeats the purpose of TS

@ThatDeparted2061
Copy link
Member

ThatDeparted2061 commented Feb 12, 2025

@gitsofaryan Have you used AI tools for converting to TS files ?, since AI would work well on singleton files but the code will break when we try to combine all the files, You should review it first
JS vs TS : The difference - Refer to this, this will help

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.

Typescript Integration in /simulator/src files
2 participants