Skip to content

JS to TS: simulator/src/setup.ts #437

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 4 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'
// }

/**
* 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

Prevent constant re-assignment of DPR.

Currently, DPR is declared as a constant, but re-assigned inside the if (lightMode) conditional, which will throw an error in TypeScript. If you need to override DPR, switch to using a let variable or create another variable for the adjusted value.

Proposed fix:

- const DPR = window.devicePixelRatio || 1;
+ let DPR = 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 = window.devicePixelRatio || 1;
if (lightMode) {
DPR = 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;
}
// 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);
}
}

/**
* 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();
}