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

JS to TS : simulator/src/data/load.ts #422 #422

Open
wants to merge 7 commits into
base: main
Choose a base branch
from

Conversation

nickhil-verma
Copy link

@nickhil-verma nickhil-verma commented Jan 22, 2025

Fixes #414

Describe the changes you have made in this PR -

Screenshots of the changes (If any) -

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

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced element display in search results and expansion panels with improved name visibility
  • Refactor

    • Replaced JavaScript loading logic with TypeScript implementation for circuit data management
    • Introduced structured interfaces for devices and connections to improve code clarity and maintainability
    • Updated project management functionality to streamline user experience
  • Chores

    • Removed legacy loading and project recovery mechanisms
    • Simplified project initialization process

Copy link
Contributor

coderabbitai bot commented Jan 22, 2025

Walkthrough

The pull request introduces TypeScript migration for the simulator's data loading and project management modules. The changes involve converting the load.js file to load.ts, adding type definitions, and modifying the project management logic. Additionally, there are UI improvements in the ElementsPanel.vue component, enhancing the display of element names in search results and expansion panels.

Changes

File Change Summary
src/components/Panels/ElementsPanel/ElementsPanel.vue Added new <div> elements to improve element name display in search results and expansion panels
src/simulator/src/data/load.js Deleted JavaScript file for loading circuit data
src/simulator/src/data/load.ts New TypeScript file replacing load.js with type-safe implementations of loading functions
src/simulator/src/data/project.ts Modified project management logic, removed unsaved changes prompt

Assessment against linked issues

Objective Addressed Explanation
Typescript Integration [#414]

Possibly related PRs

  • Fix Clock Settings Functionality and Improve UI #384: The changes in this PR involve modifications to Vue components, specifically enhancing the UI and functionality of the ProjectProperty.vue file, which is related to the user interface improvements made in the ElementsPanel.vue component of the main PR. Both PRs focus on improving the presentation and interaction of elements within the Vue components.

Suggested reviewers

  • Arnabdaz

Poem

🐰 Circuits dance in TypeScript's light,
Bits and bytes now typed just right!
Elements panel, crisp and clear,
Code migration brings us cheer!
Rabbit's code hops with delight! 🚀

✨ 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 Jan 22, 2025

Deploy Preview for circuitverse ready!

Name Link
🔨 Latest commit aedba88
🔍 Latest deploy log https://app.netlify.com/sites/circuitverse/deploys/6792007ea6a6370008c34e79
😎 Deploy Preview https://deploy-preview-422--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.

@nickhil-verma
Copy link
Author

CC:- @niladrix719

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: 3

🧹 Nitpick comments (4)
src/simulator/src/data/load.ts (3)

132-162: Initialize layout properties only when necessary

The layout initialization code can be optimized by checking if data.layout is undefined before setting default values. This avoids unnecessary computations when layout data is provided.

Consider wrapping the default layout initialization within an else block to ensure it's only executed when data.layout is not provided.


173-175: Simplify base URL determination

The logic for determining baseUrl can be simplified. The current check for 'null' may be unnecessary and could be error-prone.

Simplify the URL assignment as follows:

- const baseUrl = window.location.origin !== 'null' ? window.location.origin : 'http://localhost:4000'
+ const baseUrl = window.location.origin || 'http://localhost:4000'

181-182: Avoid setting globalScope to undefined before reset

Setting globalScope to undefined before calling resetScopeList() may not be necessary, as resetScopeList() should handle scope resets internally.

Consider removing the line or ensuring that resetScopeList() accounts for the globalScope reset.

src/components/Panels/ElementsPanel/ElementsPanel.vue (1)

Line range hint 148-148: Consider localization for element names

If element names are subject to localization, ensure that the displayed names are wrapped with localization functions.

Modify the code to accommodate localization if necessary.

- <p class="d-inline-block">{{ element.name }}</p>
+ <p class="d-inline-block">{{ $t('element_names.' + element.name) }}</p>
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6eae6ed and f3cb84d.

📒 Files selected for processing (4)
  • src/components/Panels/ElementsPanel/ElementsPanel.vue (3 hunks)
  • src/simulator/src/data/load.js (0 hunks)
  • src/simulator/src/data/load.ts (1 hunks)
  • src/simulator/src/data/project.ts (2 hunks)
💤 Files with no reviewable changes (1)
  • src/simulator/src/data/load.js
🔇 Additional comments (5)
src/simulator/src/data/project.ts (2)

123-139: Confirm removal of unsaved changes prompt

The code block that prompts users about unsaved changes has been commented out. Confirm that this behavior is intentionally removed, as it may lead to loss of unsaved work without warning.

If the removal is intentional, ensure that users are informed through other means to prevent accidental data loss.


158-178: ⚠️ Potential issue

Review logic change in newProject function

The condition in the newProject function has been altered, which might affect how new projects are initiated when unsaved changes exist.

Ensure that the new logic correctly handles cases where verification is required and when unsaved changes are present.

Consider revising the condition:

- if (verify || projectSaved || !checkToSave()) {
+ if (!verify && !projectSaved && checkToSave() && !(await confirmOption(...))) {

Please confirm that this change aligns with the intended behavior.

✅ Verification successful

Logic change in newProject function is correct and improved

The new implementation is logically equivalent to the original but more explicit in its intent. The function correctly:

  • Skips confirmation when verification is required (verify=true)
  • Prompts for confirmation only when necessary (unsaved changes exist and verify=false)
  • Maintains the same behavior while being more readable
🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Find the complete newProject function implementation
ast-grep --pattern 'async function newProject($_) {
  $$$
}'

# Find checkToSave function implementation
ast-grep --pattern 'function checkToSave() {
  $$$
}'

# Search for verify parameter usage
rg "verify" "src/simulator/src/data/project.ts" -A 2 -B 2

Length of output: 2695

src/components/Panels/ElementsPanel/ElementsPanel.vue (3)

43-43: Add element name display in search results

Displaying the element names alongside their icons improves usability by helping users identify elements more easily.


81-81: Add element name display in expansion panels

Consistently displaying element names in both search results and expansion panels enhances the user interface and experience.


128-131: Ensure text overflow is handled properly

The added <div> for element names should handle text overflow to maintain layout integrity.

Test with longer element names to ensure that the text does not overflow or cause layout issues.

Comment on lines +25 to +27
type CircuitElement = any; // Replace with proper type
type Scope = any; // Replace with proper type
type JSONData = Record<string, any>; // Generic type for JSON data
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

Replace 'any' types with specific type definitions

Using any reduces the benefits of TypeScript's type safety. Defining specific types for CircuitElement, Scope, and JSONData will enhance code reliability and maintainability.

Please replace the any types with appropriate interfaces or classes that reflect the actual structures used.


obj.label = data.label;
obj.labelDirection =
data.labelDirection || oppositeDirection[fixDirection[obj.direction]];
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

Undefined 'fixDirection' variable

The variable fixDirection is used but not defined or imported, which will cause a runtime error.

Ensure that fixDirection is properly defined or imported before using it. If it's meant to adjust the direction, consider importing it from its module.

data.x,
data.y,
scope,
...(data.customData.constructorParamaters || [])
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

Fix typo in 'constructorParamaters'

There's a typo in data.customData.constructorParamaters; it should be constructorParameters. This might lead to undefined behavior or errors during object construction.

Apply this diff to correct the typo:

- ...(data.customData.constructorParamaters || [])
+ ...(data.customData.constructorParameters || [])
📝 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
...(data.customData.constructorParamaters || [])
...(data.customData.constructorParameters || [])

@nickhil-verma nickhil-verma changed the title JS to TS : simulator/src/data/undo.ts #422 JS to TS : simulator/src/data/load.ts #422 Jan 22, 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: 2

🧹 Nitpick comments (3)
src/simulator/src/app.ts (3)

22-32: Add port name validation.

The Connector interface allows any string for port names. Consider adding validation for allowed port names.

+type PortName = 'in' | 'out' | 'rd0data' | 'rd1data' | 'rd0addr' | 'rd1addr' | 'wr0addr' | 'wr1addr' | 'wr0data' | 'wr1data' | 'rd1clk' | 'wr0clk' | 'wr1clk';

 interface Connector {
     to: {
         id: string;
-        port: string;
+        port: PortName;
     };
     from: {
         id: string;
-        port: string;
+        port: PortName;
     };
     name: string;
 }

Line range hint 43-247: Refactor large initialization block.

The circuit initialization block is quite large and could benefit from being split into smaller, more manageable functions.

+const createMemoryDevice = (): Device => ({
+    label: 'mem',
+    type: 'Memory',
+    bits: 5,
+    abits: 4,
+    words: 16,
+    offset: 0,
+    rdports: [
+        {},
+        { clock_polarity: true }
+    ],
+    wrports: [
+        { clock_polarity: true },
+        { clock_polarity: true }
+    ],
+    memdata: [13, '00001', 3, '11111']
+});
+
+const createInputDevices = (): Record<string, Device> => ({
+    dev0: { type: 'Input', net: 'clk', order: 0, bits: 1 },
+    dev1: { type: 'Input', net: 'addr', order: 1, bits: 4 },
+    // ... other input devices
+});
+
+const createOutputDevices = (): Record<string, Device> => ({
+    dev2: { type: 'Output', net: 'data', order: 2, bits: 5 },
+    dev4: { type: 'Output', net: 'data2', order: 4, bits: 5 }
+});
+
+const createConnectors = (): Connector[] => ([
+    // ... connectors array
+]);

 const js: Circuit = {
-    devices: {
-        dev0: { ... },
-        // ... other devices
-    },
-    connectors: [ ... ],
+    devices: {
+        ...createInputDevices(),
+        ...createOutputDevices(),
+        dev9: createMemoryDevice()
+    },
+    connectors: createConnectors(),
     subcircuits: {}
 };

40-42: Consider moving event listener to a separate file.

The event listener and setup logic could be moved to a separate file to improve modularity.

+// circuitInitializer.ts
+import { setup } from './setup';
+import { initializeCircuit } from './circuitConfig';
+
+export const initializeApp = () => {
+    document.addEventListener('DOMContentLoaded', () => {
+        setup();
+        initializeCircuit();
+    });
+};
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f3cb84d and aedba88.

📒 Files selected for processing (1)
  • src/simulator/src/app.ts (2 hunks)
🔇 Additional comments (1)
src/simulator/src/app.ts (1)

4-6: Verify device types coverage.

Let's ensure that all device types used in the codebase are covered by the Device interface.

✅ Verification successful

Device interface types are correctly defined

The Device interface correctly covers all device types ('Input', 'Output', 'Memory') used in the codebase. All other type assignments found are unrelated and used in different contexts.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for device type assignments in the codebase
echo "Searching for device type assignments..."
rg -g '*.{ts,js,vue}' "type:\s*['\"](\w+)['\"]" --only-matching --replace '$1' | sort -u

# Search for type property access
echo "Searching for type property access..."
ast-grep --pattern 'device.type' -l ts,js,vue

Length of output: 2725

Comment on lines +34 to +38
interface Circuit {
devices: Record<string, Device>;
connectors: Connector[];
subcircuits: Record<string, unknown>;
}
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

Avoid using unknown type.

The subcircuits field uses the unknown type, which bypasses TypeScript's type checking. Consider defining a proper type for subcircuits.

 interface Circuit {
     devices: Record<string, Device>;
     connectors: Connector[];
-    subcircuits: Record<string, unknown>;
+    subcircuits: Record<string, Circuit>;
 }
📝 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
interface Circuit {
devices: Record<string, Device>;
connectors: Connector[];
subcircuits: Record<string, unknown>;
}
interface Circuit {
devices: Record<string, Device>;
connectors: Connector[];
subcircuits: Record<string, Circuit>;
}

Comment on lines +4 to +20
interface Device {
type: 'Input' | 'Output' | 'Memory';
net: string;
order?: number;
bits: number;
label?: string;
abits?: number;
words?: number;
offset?: number;
rdports?: Array<{
clock_polarity?: boolean;
}>;
wrports?: Array<{
clock_polarity?: boolean;
}>;
memdata?: (number | string)[];
}
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

Expand device types and add JSDoc documentation.

The Device interface has a limited set of device types and lacks documentation for complex fields.

+/**
+ * Represents a device in the circuit simulator.
+ * @property type - The type of the device
+ * @property net - Network identifier
+ * @property order - Optional display order
+ * @property bits - Number of bits
+ * @property label - Optional device label
+ * @property abits - Optional address bits for memory devices
+ * @property words - Optional word count for memory devices
+ * @property memdata - Optional memory initialization data
+ */
 interface Device {
-    type: 'Input' | 'Output' | 'Memory';
+    type: 'Input' | 'Output' | 'Memory' | 'Register' | 'Counter' | 'Clock' | 'AndGate' | 'OrGate' | 'NotGate' | 'XorGate';
     // ... rest of the interface
 }
📝 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
interface Device {
type: 'Input' | 'Output' | 'Memory';
net: string;
order?: number;
bits: number;
label?: string;
abits?: number;
words?: number;
offset?: number;
rdports?: Array<{
clock_polarity?: boolean;
}>;
wrports?: Array<{
clock_polarity?: boolean;
}>;
memdata?: (number | string)[];
}
/**
* Represents a device in the circuit simulator.
* @property type - The type of the device
* @property net - Network identifier
* @property order - Optional display order
* @property bits - Number of bits
* @property label - Optional device label
* @property abits - Optional address bits for memory devices
* @property words - Optional word count for memory devices
* @property memdata - Optional memory initialization data
*/
interface Device {
type: 'Input' | 'Output' | 'Memory' | 'Register' | 'Counter' | 'Clock' | 'AndGate' | 'OrGate' | 'NotGate' | 'XorGate';
net: string;
order?: number;
bits: number;
label?: string;
abits?: number;
words?: number;
offset?: number;
rdports?: Array<{
clock_polarity?: boolean;
}>;
wrports?: Array<{
clock_polarity?: boolean;
}>;
memdata?: (number | string)[];
}

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
1 participant