-
Notifications
You must be signed in to change notification settings - Fork 137
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/app.ts #426
base: main
Are you sure you want to change the base?
Conversation
WalkthroughThis pull request focuses on migrating simulator-related files from JavaScript to TypeScript and refactoring the project's data loading and management components. The changes include converting Changes
Assessment against linked issues
Possibly related PRs
Poem
✨ Finishing Touches
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
✅ Deploy Preview for circuitverse ready!
To edit notification comments on pull requests, go to your Netlify site configuration. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 6
🧹 Nitpick comments (6)
src/simulator/src/data/project.ts (1)
158-178
: Refactor: Improve error handling and separation of concerns.The function mixes multiple responsibilities and lacks proper error handling for asynchronous operations.
Consider breaking down the function into smaller, focused functions:
async function confirmNewProject(verify: boolean): Promise<boolean> { if (!verify && !projectSaved && checkToSave()) { return confirmOption( 'What you like to start a new project? Any unsaved changes will be lost.' ) } return true } async function resetProjectState(): Promise<void> { await clearProject() localStorage.removeItem('recover') setProjectName(undefined) projectId = generateId() } async function navigateToNewProject(): Promise<void> { const baseUrl = window.location.origin !== 'null' ? window.location.origin : process.env.BASE_URL || 'http://localhost:4000' const url = new URL('/simulatorvue/', baseUrl) window.location.assign(url.toString()) } export async function newProject(verify: boolean): Promise<void> { try { const confirmed = await confirmNewProject(verify) if (!confirmed) return await resetProjectState() await navigateToNewProject() showMessage('New Project has been created!') } catch (error) { showError('Failed to create new project') throw error } }src/simulator/src/data/load.ts (1)
25-27
: Replace 'any' types with specific type definitionsCurrently, the types
CircuitElement
andScope
are defined asany
. To enhance type safety and leverage TypeScript's benefits, consider replacingany
with specific type definitions.src/simulator/src/app.ts (2)
5-5
: Consider using an enum for 'type' in 'Device' interfaceCurrently, the
type
property in theDevice
interface is defined as a union of string literals'Input' | 'Output' | 'Memory'
. Consider using an enum to define device types for better scalability and maintenance.Example:
enum DeviceType { Input = 'Input', Output = 'Output', Memory = 'Memory', } interface Device { type: DeviceType; // rest of the properties... }
Line range hint
43-248
: Variable 'js' is defined but not usedThe constant
js
of typeCircuit
is defined but not used within this file. This may lead to unused variable warnings and indicates potential dead code.If
js
is needed in future implementations, consider using it within this file. Otherwise, remove it to clean up the code.src/components/Panels/ElementsPanel/ElementsPanel.vue (2)
43-43
: Display element names in search results for consistencyIn the search results, the element names are not displayed under the images. For consistency and better user experience, consider adding the element names similar to how it's done in the main panel.
Add the following code after the image tag in the search results section:
<div class="overflow-hidden text-nowrap position-relative"> <p class="d-inline-block">{{ element.name }}</p> </div>
81-81
: Display element names in search categories for consistencyIn the expanded search categories, the element names are not displayed under the images. To maintain consistency across the UI, consider adding the element names.
Add the following code after the image tag in the search categories section:
<div class="overflow-hidden text-nowrap position-relative"> <p class="d-inline-block">{{ element.name }}</p> </div>
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
src/components/Panels/ElementsPanel/ElementsPanel.vue
(3 hunks)src/simulator/src/app.ts
(2 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 (1)
src/components/Panels/ElementsPanel/ElementsPanel.vue (1)
128-130
: Great addition of element names in the main panelDisplaying the element names under the images in the main elements panel enhances usability and improves the user interface.
const baseUrl = window.location.origin !== 'null' ? window.location.origin : 'http://localhost:4000' | ||
window.location.assign(`${baseUrl}/simulatorvue/`) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Security & Reliability: Improve URL handling.
The URL construction has potential issues:
- Hardcoded localhost URL could cause problems in different environments
- Direct string concatenation for URLs is error-prone
Consider this safer approach:
- const baseUrl = window.location.origin !== 'null' ? window.location.origin : 'http://localhost:4000'
- window.location.assign(`${baseUrl}/simulatorvue/`)
+ const baseUrl = window.location.origin !== 'null' ? window.location.origin : process.env.BASE_URL || 'http://localhost:4000'
+ const url = new URL('/simulatorvue/', baseUrl)
+ window.location.assign(url.toString())
Committable suggestion skipped: line range outside the PR's diff.
// window.onbeforeunload = async function () { | ||
// if (projectSaved || embed) return | ||
|
||
if (!checkToSave()) return | ||
// if (!checkToSave()) return | ||
|
||
alert( | ||
'You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?' | ||
) | ||
// await confirmSingleOption( | ||
// 'You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?' | ||
// ) | ||
const data = await generateSaveData('Untitled') | ||
const stringData = JSON.stringify(data) | ||
localStorage.setItem('recover', stringData) | ||
// eslint-disable-next-line consistent-return | ||
return 'Are u sure u want to leave? Any unsaved changes may not be recoverable' | ||
} | ||
// alert( | ||
// 'You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?' | ||
// ) | ||
// // await confirmSingleOption( | ||
// // 'You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?' | ||
// // ) | ||
// const data = await generateSaveData('Untitled') | ||
// const stringData = JSON.stringify(data) | ||
// localStorage.setItem('recover', stringData) | ||
// // eslint-disable-next-line consistent-return | ||
// return 'Are u sure u want to leave? Any unsaved changes may not be recoverable' | ||
// } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Critical: Restore unsaved changes protection mechanism.
Commenting out the window.onbeforeunload
handler removes critical user experience safeguards:
- Users can now lose unsaved work without warning
- The automatic recovery mechanism is disabled
- This contradicts standard web practices for handling unsaved changes
Consider this improved implementation:
- // window.onbeforeunload = async function () {
+ window.onbeforeunload = function (e: BeforeUnloadEvent) {
+ if (projectSaved || embed) return undefined
+
+ if (!checkToSave()) return undefined
+
+ // Modern browsers require us to set returnValue
+ const message = 'You have unsaved changes. Are you sure you want to leave?'
+ e.returnValue = message
+
+ // Asynchronously save recovery data
+ void (async () => {
+ const data = await generateSaveData('Untitled')
+ localStorage.setItem('recover', JSON.stringify(data))
+ })()
+
+ return message
+ }
This implementation:
- Uses TypeScript types
- Follows modern browser standards
- Handles async operations correctly
- Preserves the recovery mechanism
📝 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.
// window.onbeforeunload = async function () { | |
// if (projectSaved || embed) return | |
if (!checkToSave()) return | |
// if (!checkToSave()) return | |
alert( | |
'You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?' | |
) | |
// await confirmSingleOption( | |
// 'You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?' | |
// ) | |
const data = await generateSaveData('Untitled') | |
const stringData = JSON.stringify(data) | |
localStorage.setItem('recover', stringData) | |
// eslint-disable-next-line consistent-return | |
return 'Are u sure u want to leave? Any unsaved changes may not be recoverable' | |
} | |
// alert( | |
// 'You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?' | |
// ) | |
// // await confirmSingleOption( | |
// // 'You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?' | |
// // ) | |
// const data = await generateSaveData('Untitled') | |
// const stringData = JSON.stringify(data) | |
// localStorage.setItem('recover', stringData) | |
// // eslint-disable-next-line consistent-return | |
// return 'Are u sure u want to leave? Any unsaved changes may not be recoverable' | |
// } | |
window.onbeforeunload = function (e: BeforeUnloadEvent) { | |
if (projectSaved || embed) return undefined | |
if (!checkToSave()) return undefined | |
// Modern browsers require us to set returnValue | |
const message = 'You have unsaved changes. Are you sure you want to leave?' | |
e.returnValue = message | |
// Asynchronously save recovery data | |
void (async () => { | |
const data = await generateSaveData('Untitled') | |
localStorage.setItem('recover', JSON.stringify(data)) | |
})() | |
return message | |
} |
obj.labelDirection = | ||
data.labelDirection || oppositeDirection[fixDirection[obj.direction]]; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Undefined reference to 'fixDirection'
The variable fixDirection
is not defined or imported, but it's used in oppositeDirection[fixDirection[obj.direction]]
. This will cause a runtime error.
Ensure that fixDirection
is defined or imported before using it. If it's meant to be a method, consider calling it appropriately.
if (!data) { | ||
setProjectName(__projectName); | ||
return; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Undefined variable '__projectName'
The variable __projectName
is used but not defined or imported in this file. This will lead to a runtime error when setProjectName(__projectName)
is called.
Define or import __projectName
before using it, or ensure it's available in the current scope.
if (embed) { | ||
globalScope.centerFocus(true); | ||
} else { | ||
globalScope.centerFocus(false); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Undefined variable 'embed'
The variable embed
is used in the conditional statement but is not defined or imported in this file. This will cause a runtime error.
Define or import embed
before using it, or check if it's intended to be a global variable accessible in this context.
data.x, | ||
data.y, | ||
scope, | ||
...(data.customData.constructorParamaters || []) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Correct typo in 'constructorParamaters'
There's a typo in 'constructorParamaters'
. It should be 'constructorParameters'
.
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.
...(data.customData.constructorParamaters || []) | |
...(data.customData.constructorParameters || []) |
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
Refactoring
Improvements