Skip to content

JS to TS : simulator/src/tutorial.ts #438

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

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/components/Panels/ElementsPanel/ElementsPanel.vue
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
@mouseleave="tooltipText = 'null'"
>
<img :src="element.imgURL" :alt="element.name" />

</div>
</div>
<v-expansion-panels
Expand Down Expand Up @@ -77,6 +78,7 @@
:src="element.imgURL"
:alt="element.name"
/>

</div>
</div>
</v-expansion-panel-text>
Expand Down Expand Up @@ -123,6 +125,10 @@
:src="element.imgURL"
:alt="element.name"
/>
<div class="overflow-hidden text-nowrap position-relative">
<p class=" d-inline-block">{{ element.name }}</p>
</div>

</div>
</div>
</v-expansion-panel-text>
Expand Down
58 changes: 31 additions & 27 deletions src/simulator/src/data/project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,23 +120,23 @@ function checkToSave() {
* Prompt user to save data if unsaved
* @category data
*/
window.onbeforeunload = async function () {
if (projectSaved || embed) return
// 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'
// }
Comment on lines +123 to +139
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

🛠️ Refactor suggestion

Reconsider removing the page leave warning

While there is a recovery mechanism in place, removing the onbeforeunload handler eliminates the primary way to prevent accidental data loss. The current recovery system only helps after the fact, but doesn't prevent users from accidentally navigating away with unsaved changes.

  • Consider keeping or reimplementing the onbeforeunload handler to maintain better user experience
  • If removal is intentional, ensure users are clearly informed about the auto-recovery feature
  • The commented code should still be removed from the codebase, but the functionality should be preserved
🔗 Analysis chain

Remove commented code.

Instead of keeping commented code, consider removing it entirely and preserving it in version control history if needed.

Verify impact on user experience.

The removal of the onbeforeunload handler means users won't be warned about unsaved changes when leaving the page. Please confirm if this is intentional and if there are alternative measures to prevent data loss.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any other implementations of onbeforeunload or similar data loss prevention
rg -l "onbeforeunload|beforeunload|unload" --type ts --type vue

Length of output: 93


Script:

#!/bin/bash
# Search in TypeScript files
echo "Searching TypeScript files..."
rg -l "onbeforeunload|beforeunload|unload|unsaved|warning" --type ts

# Search in .vue files directly
echo "Searching Vue files..."
find . -name "*.vue" -type f -exec rg -l "onbeforeunload|beforeunload|unload|unsaved|warning" {} \;

# Search for save-related functionality
echo "Searching for save-related functionality..."
rg -l "saveProject|saveTo|autoSave" --type ts
find . -name "*.vue" -type f -exec rg -l "saveProject|saveTo|autoSave" {} \;

Length of output: 743


Script:

#!/bin/bash
# Check content of setup.ts for related functionality
echo "Content of setup.ts:"
rg -A 5 -B 5 "onbeforeunload|beforeunload|unload|unsaved|warning" src/simulator/src/setup.ts

# Also check the Vue components for context
echo "Content of relevant Vue components:"
find . -name "*.vue" -type f -exec rg -A 5 -B 5 "onbeforeunload|beforeunload|unload|unsaved|warning" {} \;

Length of output: 4640


/**
* Function to clear project
Expand All @@ -155,21 +155,25 @@ export async function clearProject() {
Function used to start a new project while prompting confirmation from the user
*/
export async function newProject(verify: boolean) {

if (
verify ||
projectSaved ||
!checkToSave() ||
(await confirmOption(
!verify &&
(!projectSaved && checkToSave()) &&
!(await confirmOption(
'What you like to start a new project? Any unsaved changes will be lost.'
))
) {
clearProject()
localStorage.removeItem('recover')
const baseUrl = window.location.origin !== 'null' ? window.location.origin : 'http://localhost:4000';
window.location.assign(`${baseUrl}/simulatorvue/`);

setProjectName(undefined)
projectId = generateId()
showMessage('New Project has been created!')
return
}

// Proceed to clear project and create a new one if confirmed or conditions met
await clearProject()
localStorage.removeItem('recover')

const baseUrl = window.location.origin !== 'null' ? window.location.origin : 'http://localhost:4000'
window.location.assign(`${baseUrl}/simulatorvue/`)

setProjectName(undefined)
projectId = generateId()
showMessage('New Project has been created!')
}
178 changes: 178 additions & 0 deletions src/simulator/src/setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
/* eslint-disable import/no-cycle */
/* eslint-disable no-restricted-syntax */
/* eslint-disable guard-for-in */
import { generateId, showMessage } from './utils';
import { backgroundArea } from './backgroundArea';
import plotArea from './plotArea';
import { simulationArea } from './simulationArea';
import { dots } from './canvasApi';
import { update, updateSimulationSet, updateCanvasSet } from './engine';
import { setupUI } from './ux';
import startMainListeners from './listeners';
import { newCircuit } from './circuit';
import load from './data/load';
import save from './data/save';
import { showTourGuide } from './tutorials';
import setupModules from './moduleSetup';
import 'codemirror/lib/codemirror.css';
import 'codemirror/addon/hint/show-hint.css';
import 'codemirror/mode/javascript/javascript'; // verilog.js from codemirror is not working because array prototype is changed.
import 'codemirror/addon/edit/closebrackets';
import 'codemirror/addon/hint/anyword-hint';
import 'codemirror/addon/hint/show-hint';
import { setupCodeMirrorEnvironment } from './Verilog2CV';
import '../vendor/jquery-ui.min.css';
import '../vendor/jquery-ui.min';
import { confirmSingleOption } from '#/components/helpers/confirmComponent/ConfirmComponent.vue';
import { getToken } from '#/pages/simulatorHandler.vue';

/**
* to resize window and setup things it
* sets up new width for the canvas variables.
* Also redraws the grid.
* @category setup
*/
export function resetup(): void {
const DPR = window.devicePixelRatio || 1;
if (lightMode) {
DPR = 1;
}
Comment on lines +36 to +39
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 const reassignment of DPR.

The DPR variable is declared as const but reassigned, which is incorrect:

-    const DPR = window.devicePixelRatio || 1;
-    if (lightMode) {
-        DPR = 1;
-    }
+    let DPR = lightMode ? 1 : (window.devicePixelRatio || 1);
📝 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
const DPR = window.devicePixelRatio || 1;
if (lightMode) {
DPR = 1;
}
let DPR = lightMode ? 1 : (window.devicePixelRatio || 1);
🧰 Tools
🪛 Biome (1.9.4)

[error] 38-38: Can't assign DPR because it's a constant

This is where the variable is defined as constant

Unsafe fix: Replace const with let if you assign it to a new value.

(lint/correctness/noConstAssign)

const width = document.getElementById('simulationArea')?.clientWidth! * DPR;
let height;
if (!embed) {
height =
(document.body.clientHeight -
document.getElementById('toolbar')?.clientHeight!) *
DPR;
} else {
height = document.getElementById('simulation')?.clientHeight! * DPR;
}
Comment on lines +40 to +49
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

Add null checks for DOM elements.

Replace non-null assertions with proper null checks:

-    const width = document.getElementById('simulationArea')?.clientWidth! * DPR;
+    const simulationArea = document.getElementById('simulationArea');
+    if (!simulationArea) {
+        console.error('Simulation area not found');
+        return;
+    }
+    const width = simulationArea.clientWidth * DPR;

Committable suggestion skipped: line range outside the PR's diff.

// setup simulationArea and backgroundArea variables used to make changes to canvas.
backgroundArea.setup();
simulationArea.setup();
// redraw grid
dots();
document.getElementById('backgroundArea')!.style.height =
height / DPR + 100 + 'px';
document.getElementById('backgroundArea')!.style.width =
width / DPR + 100 + 'px';
document.getElementById('canvasArea')!.style.height = height / DPR + 'px';
simulationArea.canvas.width = width;
simulationArea.canvas.height = height;
backgroundArea.canvas.width = width + 100 * DPR;
backgroundArea.canvas.height = height + 100 * DPR;
if (!embed) {
plotArea.setup();
}
updateCanvasSet(true);
update(); // INEFFICIENT, needs to be deprecated
simulationArea.prevScale = 0;
dots();
}

window.onresize = resetup; // listener
window.onorientationchange = resetup; // listener

// for mobiles
window.addEventListener('orientationchange', resetup); // listener

/**
* function to setup environment variables like projectId and DPR
* @category setup
*/
function setupEnvironment(): void {
setupModules();
const projectId = generateId();
(window as any).projectId = projectId;
updateSimulationSet(true);
newCircuit('Main');
(window as any).data = {};
resetup();
setupCodeMirrorEnvironment();
}

/**
* Fetches project data from API and loads it into the simulator.
* @param {number} projectId The ID of the project to fetch data for
* @category setup
*/
async function fetchProjectData(projectId: number): Promise<void> {
try {
const response = await fetch(
`/api/v1/projects/${projectId}/circuit_data`,
{
method: 'GET',
headers: {
Accept: 'application/json',
Authorization: `Token ${getToken('cvt')}`,
},
}
);
if (response.ok) {
const data = await response.json();
await load(data);
await simulationArea.changeClockTime(data.timePeriod || 500);
($('.loadingIcon') as any).fadeOut();
} else {
throw new Error('API call failed');
}
} catch (error) {
console.error(error);
confirmSingleOption('Error: Could not load.');
($('.loadingIcon') as any).fadeOut();
}
}

/**
* Load project data immediately when available.
* Improvement to eliminate delay caused by setTimeout in previous implementation revert if issues arise.
* @category setup
*/
async function loadProjectData(): Promise<void> {
(window as any).logixProjectId = (window as any).logixProjectId ?? 0;
if ((window as any).logixProjectId !== 0) {
($('.loadingIcon') as any).fadeIn();
await fetchProjectData((window as any).logixProjectId);
} else if (localStorage.getItem('recover_login') && (window as any).isUserLoggedIn) {
// Restore unsaved data and save
const data = JSON.parse(localStorage.getItem('recover_login')!);
await load(data);
localStorage.removeItem('recover');
localStorage.removeItem('recover_login');
await save();
} else if (localStorage.getItem('recover')) {
// Restore unsaved data which didn't get saved due to error
showMessage(
"We have detected that you did not save your last work. Don't worry we have recovered them. Access them using Project->Recover"
);
}
}

/**
* Show tour guide if it hasn't been completed yet.
* The tour is shown after a delay of 2 seconds.
* @category setup
*/
function showTour(): void {
if (!localStorage.tutorials_tour_done && !embed) {
setTimeout(() => {
showTourGuide();
}, 2000);
}
}
Comment on lines +156 to +162
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

Add cleanup for setTimeout.

The setTimeout should be cleaned up to prevent memory leaks:

 function showTour(): void {
     if (!localStorage.tutorials_tour_done && !embed) {
-        setTimeout(() => {
+        const timeoutId = setTimeout(() => {
             showTourGuide();
         }, 2000);
+        // Add cleanup method to clear timeout
+        return () => clearTimeout(timeoutId);
     }
 }

Committable suggestion skipped: line range outside the PR's diff.


/**
* The first function to be called to setup the whole simulator.
* This function sets up the simulator environment, the UI, the listeners,
* loads the project data, and shows the tour guide.
* @category setup
*/
export function setup(): void {
setupEnvironment();
if (!embed) {
setupUI();
startMainListeners();
}
loadProjectData();
showTour();
}
Loading