Skip to content

chore: Sync src to v0/src and v1/src #599

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 3 commits into
base: main
Choose a base branch
from

Conversation

ThatDeparted2061
Copy link
Member

@ThatDeparted2061 ThatDeparted2061 commented Jun 14, 2025

Fixes #595 #596

Synced src to v0/src and v1/src

Summary by CodeRabbit

  • New Features

    • Introduced mobile-optimized panels and dialogs for elements, properties, timing diagrams, and Verilog editing, enhancing simulator usability on mobile devices.
    • Added Bengali language support and expanded localization for layout features.
    • Implemented a user menu with avatar, authentication, and locale selection.
    • Added new test bench creation and validation dialogs with CSV import/export.
    • Provided layout elements panel and improved layout editing controls.
    • Added quick action toolbars for both desktop and mobile.
    • Added a new right-side hamburger navigation drawer with project info and user menu.
    • Introduced combinational analysis functionality with improved circuit generation and boolean solving.
    • Added a mobile-optimized elements panel and layout elements panel with drag-and-drop support.
  • Enhancements

    • Refactored theme management and selection, including custom theme import/export, removing jQuery dependencies.
    • Improved conditional rendering and responsive UI for mobile and embedded views.
    • Streamlined navigation with a new hamburger menu and dropdowns.
    • Enhanced properties panel with centralized state management and layout mode support.
    • Improved testbench and timing diagram panels with modular components and better controls.
    • Centralized quick button action logic for consistency across desktop and mobile.
    • Refined circuit and array management with explicit typings and standard JavaScript methods.
    • Updated Verilog mode toggling with safer DOM checks and reactive store synchronization.
    • Simplified project and circuit name handling with improved input focus and null safety.
    • Replaced jQuery DOM manipulations with native DOM APIs and Vue reactivity throughout the codebase.
    • Externalized event handling and UI logic for better maintainability.
  • Bug Fixes

    • Fixed input focus and null safety in project and circuit name handling.
    • Improved error handling and type safety across dialogs and panels.
    • Addressed UI issues for element selection and tooltips.
    • Corrected boolean function solving validation with user-friendly alerts.
  • Refactor

    • Migrated internal logic to external modules for better maintainability.
    • Updated array prototype extensions removal and replaced with standard methods.
    • Modularized and externalized event handling for panels and dialogs.
    • Removed deprecated files and replaced legacy canvas-to-SVG conversion with updated implementations.
    • Enhanced circuit and scope classes with explicit typings and safer method implementations.
  • Tests

    • Added comprehensive test suites for combinational, sequential, subcircuit, and miscellaneous circuit elements.
    • Introduced new JSON test data files for various circuit components.
    • Migrated test suites to Vitest with improved mocking and Vue 3 integration.
  • Chores

    • Cleaned up unused imports and deprecated files.
    • Improved project save, load, and offline storage logic.
    • Updated codebase to TypeScript in key modules for better type safety.
    • Replaced jQuery with native DOM APIs in save and load modules.
    • Added global test environment setup for consistent testing.
  • Documentation

    • Enhanced JSDoc comments and localization files for new features and UI elements.
    • Added Bengali locale and updated English and Hindi locales with layout-related strings.

Copy link
Contributor

coderabbitai bot commented Jun 14, 2025

Walkthrough

This update introduces a comprehensive synchronization and refactor of the simulator's source code, including migration to TypeScript, modularization of UI and logic, introduction of mobile-optimized components, improved state management, and enhanced localization. Numerous new test suites, UI panels, and utility modules are added, while legacy JavaScript files and jQuery dependencies are removed or replaced.

Changes

Files/Groups Change Summary
src/assets/constants/theme.ts Added TypeScript module for theme constants and types.
src/components/DialogBox/*.vue Refactored imports, improved type safety, removed jQuery, updated file handling, and simplified logic for dialogs.
src/components/Extra.vue Introduced mobile/desktop conditional rendering, added mobile controls, and modularized panels.
src/components/Logo/Logo.vue Replaced router-link with anchor tag for navigation.
src/components/Navbar/, src/components/NavbarLinks/ Added new hamburger and user menu components, replaced legacy sidebar logic, improved responsiveness, modularized quick button logic, and updated imports.
src/components/Panels/ElementsPanel/* Modularized element creation logic, introduced mobile panel, improved typing, and removed direct global assignments.
src/components/Panels/LayoutElementsPanel/LayoutElementsPanel.vue Added new draggable panel for layout elements.
src/components/Panels/PropertiesPanel/* Centralized properties panel state in store, refactored layout logic, added mobile panel, and improved reactivity.
src/components/Panels/TestBenchPanel/* Added test bench creator, validator, and main panel components with CSV import/export and error handling.
src/components/Panels/TimingDiagramPanel/* Modularized timing diagram logic, added mobile panel, refactored event handling, and improved responsive design.
src/components/Panels/VerilogEditorPanel/VerilogEditorPanelMobile.vue Added mobile dialog for Verilog code editing and theme selection.
src/components/ReportIssue/ReportIssueButton.vue Dynamically adjusted button position based on mobile panel state.
src/components/TabsBar/TabsBar.vue Added circuit name click handler, removed type declaration, minor CSS changes.
src/components/helpers/deleteCircuit/DeleteCircuit.vue Safely accessed active circuit ID with optional chaining.
src/env.d.ts Declared array prototype method signatures for clean, extend, and contains.
src/globalVariables.ts Removed global assignments for Array and elementHierarchy.
src/locales/*.json, src/locales/i18n.ts Added Bengali locale, updated English and Hindi locales, exported i18n instance and available locales.
src/main.ts Removed unused import.
src/pages/embed.vue Added conditional rendering of UI based on query params, theme selection, and improved imports.
src/pages/simulatorHandler.vue Added mobile view toggle based on window size.
src/router/index.ts Exported routes array.
src/simulator/spec/, src/simulator/spec/testData/, src/simulator/spec/circuits/* Added and reformatted test suites and test data for combinational, sequential, and complex circuits.
src/simulator/src/Verilog2CV.js Enhanced Verilog mode handling, updated mobile store, improved DOM checks.
src/simulator/src/VerilogClasses.js Removed unused imports; no functional changes.
src/simulator/src/app.ts Updated imports, removed global Array assignment.
src/simulator/src/arrayHelpers.js Deleted file; removed custom Array prototype extensions.
src/simulator/src/backgroundArea.js, src/simulator/src/backgroundArea.ts Migrated background area logic to TypeScript.
src/simulator/src/canvas2svg.js Deleted file; removed Canvas-to-SVG mock context implementation.
src/simulator/src/canvasApi.js Refactored to use native DOM APIs, removed jQuery, rounded coordinates.
src/simulator/src/circuit.ts Refactored for type safety, removed jQuery, improved state management, added mobile integration.
src/simulator/src/circuitElement.js Replaced non-standard array methods with standard ones, improved touch support, fixed JSDoc types.
src/simulator/src/combinationalAnalysis.js Refactored to remove UI dependencies, modularized logic, improved function signatures.
src/simulator/src/contention.ts Added new TypeScript class for contention management.
src/simulator/src/data.js Updated function assignments for circuit creation, removed unused imports.
src/simulator/src/data/backupCircuit.js Added imports for module list and order.
src/simulator/src/data/load.js Updated imports, removed testbench UI update, added module list import.
src/simulator/src/data/project.ts Improved type safety, safe parsing of localStorage, updated navigation logic.
src/simulator/src/data/redo.js, src/simulator/src/data/redo.ts Migrated redo logic to TypeScript, improved state handling.
src/simulator/src/data/save.js Refactored to remove jQuery, updated image generation, improved subcircuit update logic.
src/simulator/src/data/saveImage.js, src/simulator/src/data/saveImage.ts Migrated save image prompt logic to TypeScript.

Assessment against linked issues

Objective (Issue #) Addressed Explanation
Synchronize and refactor src to v0/src and v1/src (#595)
Migrate legacy JavaScript files to TypeScript modules (#595)
Modularize and improve UI components, including mobile support (#595)
Enhance localization and add new language support (#595)

Assessment against linked issues: Out-of-scope changes

Code Change (file_path) Explanation
No out-of-scope changes found All code changes align with the objectives of syncing, refactoring, modularizing, and improving the simulator codebase as described in the linked issue.

Possibly related PRs

  • CircuitVerse/cv-frontend-vue#434: Introduces the same ContentionPendingData class and interface for managing node contentions, indicating direct code-level overlap.
  • CircuitVerse/cv-frontend-vue#419: Migrates the saveImage helper to TypeScript, directly replacing the deleted JavaScript version—showing a clear code migration connection.

Suggested labels

GSOC'24

Suggested reviewers

  • Arnabdaz
  • niladrix719
  • JoshVarga

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-06-26T19_42_34_201Z-debug-0.log

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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 Jun 14, 2025

Deploy Preview for circuitverse ready!

Name Link
🔨 Latest commit 3290047
🔍 Latest deploy log https://app.netlify.com/projects/circuitverse/deploys/685da24dc0bc460008b42edf
😎 Deploy Preview https://deploy-preview-599--circuitverse.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
Lighthouse
Lighthouse
1 paths audited
Performance: 32 (🔴 down 15 from production)
Accessibility: 73 (🟢 up 1 from production)
Best Practices: 92 (no change from production)
SEO: 82 (🟢 up 2 from production)
PWA: -
View the detailed breakdown and full score reports

To edit notification comments on pull requests, go to your Netlify project configuration.

@ThatDeparted2061
Copy link
Member Author

@aryanndwi123 @Arnabdaz
The extra features of vo have been added in src and then syncing has been done

Copy link

@github-advanced-security github-advanced-security bot left a comment

Choose a reason for hiding this comment

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

ESLint found more than 20 potential problems in the proposed changes. Check the Files changed tab for more details.

@@ -207,16 +165,16 @@
this.downDimensionY = subcircuitScope.layout.height
}

this.nodeList.extend(this.inputNodes)
this.nodeList.extend(this.outputNodes)
this.nodeList.push(...this.inputNodes)

Check warning

Code scanning / CodeQL

Prototype-polluting assignment Medium

This assignment may alter Object.prototype if a malicious '__proto__' string is injected from
user controlled input
.
this.nodeList.extend(this.inputNodes)
this.nodeList.extend(this.outputNodes)
this.nodeList.push(...this.inputNodes)
this.nodeList.push(...this.outputNodes)

Check warning

Code scanning / CodeQL

Prototype-polluting assignment Medium

This assignment may alter Object.prototype if a malicious '__proto__' string is injected from
user controlled input
.
@@ -207,16 +165,16 @@
this.downDimensionY = subcircuitScope.layout.height
}

this.nodeList.extend(this.inputNodes)
this.nodeList.extend(this.outputNodes)
this.nodeList.push(...this.inputNodes)

Check warning

Code scanning / CodeQL

Prototype-polluting assignment Medium

This assignment may alter Object.prototype if a malicious '__proto__' string is injected from
user controlled input
.
this.nodeList.extend(this.inputNodes)
this.nodeList.extend(this.outputNodes)
this.nodeList.push(...this.inputNodes)
this.nodeList.push(...this.outputNodes)

Check warning

Code scanning / CodeQL

Prototype-polluting assignment Medium

This assignment may alter Object.prototype if a malicious '__proto__' string is injected from
user controlled input
.
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: 59

🔭 Outside diff range comments (5)
v0/src/components/Panels/Shared/InputGroups.vue (1)

52-60: ⚠️ Potential issue

Illegal prop mutation (props.propertyValue = …) will throw in Vue 3

defineProps() returns a read-only object; attempting to assign to props.propertyValue (and likewise in decreaseValue) throws “attempting to mutate prop” at runtime.

Emit an update instead:

-    props.propertyValue = value
+    emit('update:propertyValue', value)

and expose a v-model:propertyValue binding in the parent.
Same applies to min/max comparisons: convert strings with Number(props.valueMax) to avoid silent coercion bugs.

Also applies to: 67-76

v0/src/components/Navbar/NavbarLinks/NavbarLinks.vue (1)

2-9: ⚠️ Potential issue

Duplicate id="toolbar" inside a v-for violates HTML spec

The id must be unique, but the loop renders one <ul> per item, all carrying the same id.

-    <ul
-        v-for="navbarItem in navbarData"
-        id="toolbar"
+    <ul
+        v-for="navbarItem in navbarData"
+        :id="`toolbar-${navbarItem.id}`"

Browsers will pick the first match, breaking querySelector('#toolbar') calls and CSS anchors.

v0/src/simulator/spec/circuits/sequential-circuitdata.json (1)

1506-1545: 🛠️ Refactor suggestion

Duplicate ForceGate objects

Two consecutive ForceGate entries share identical coordinates and node mappings.
This inflates the fixture and may lead to double-instantiation during simulation.

Consider removing the duplicate block (lines 1506-1545).

v0/src/components/DialogBox/CombinationalAnalysis.vue (1)

196-198: ⚠️ Potential issue

Incorrect zero-length check

booleanInputVariables == 0 compares an array to a number and is always false. Use .length.

-        (inputList.length == 0 || outputList.length == 0) && booleanInputVariables == 0
+        (inputList.length === 0 || outputList.length === 0) && booleanInputVariables.length === 0
v0/src/components/DialogBox/Themes/ApplyThemes.vue (1)

198-201: ⚠️ Potential issue

Remove remaining jQuery dependencies.

The component still uses jQuery for DOM manipulation, which should be replaced with Vue's reactive approach.

-if ($('.selected label').text()) {
-    localStorage.removeItem('Custom Theme')
-    localStorage.setItem('theme', $('.selected label').text())
-}
+if (selectedTheme.value) {
+    localStorage.removeItem('Custom Theme')
+    localStorage.setItem('theme', selectedTheme.value)
+}

-$('.set').removeClass('set')
-$('.selected').addClass('set')
+// Use Vue's reactive data instead of manipulating DOM classes directly

Also applies to: 211-212, 226-227

♻️ Duplicate comments (3)
v0/src/simulator/spec/sequential.spec.js (1)

26-75: Same test-setup duplication as flagged in subCircuit.spec.js

Refer to earlier comment about extracting a shared helper.

v0/src/simulator/spec/decoders-plexers.spec.js (1)

45-63: Factor out document.createRange mock

Same duplication comment as in bitConvertor.spec.js.

v0/src/simulator/spec/combinationalAnalysis.spec.js (1)

13-24: Same Vitest global issue as in misc.spec.js

Import testing globals explicitly to satisfy ESLint and avoid potential shadowing.

-import { setup } from '../src/setup';
+import { vi, describe, beforeAll, test, expect } from 'vitest';
+import { setup } from '../src/setup';
🧰 Tools
🪛 GitHub Check: ESLint

[failure] 13-13: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 17-17: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 21-21: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 22-22: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.

🧹 Nitpick comments (70)
v0/src/components/Panels/PropertiesPanel/ModuleProperty/ModuleProperty.vue (1)

33-34: Consolidate and clean up Vue imports

Importing ref, toRefs, and onMounted from vue is the right approach, but currently ref and onMounted aren’t used in this component. You can merge the two statements into one and remove unused symbols:

- import { ref, toRefs } from 'vue'
- import { onMounted } from 'vue'
+ import { toRefs } from 'vue'

If you plan to leverage ref or onMounted in future logic, combine them in a single line:

import { ref, toRefs, onMounted } from 'vue'
v0/src/simulator/src/app.ts (1)

6-210: Consider externalising the static simulator preset

The 180-line literal makes app.ts noisy and couples UI bootstrapping with sample data. Moving it to ./presets/memory-demo.ts (or JSON) improves readability and lets you tree-shake / lazy-load presets later.

No functional change required now, but it will pay off in maintainability.

v0/src/components/DialogBox/ExportProject.vue (1)

44-45: Consolidate imports from utils
These two imports come from the same module; consider merging them for brevity and clarity:

-import { downloadFile } from '#/simulator/src/utils'
-import { escapeHtml } from '#/simulator/src/utils'
+import { downloadFile, escapeHtml } from '#/simulator/src/utils'
v0/src/components/DialogBox/ExportVerilog.vue (1)

84-86: Sanitize exported filename for Verilog
The raw project name may contain spaces or special characters that lead to invalid filenames. Mirror the sanitization used in ExportProject.vue:

+import { escapeHtml } from '#/simulator/src/utils'
 
 function downloadVerilog() {
-  let fileName = getProjectName() || 'Untitled'
-  downloadFile(fileName + '.v', code.value)
+  const base = escapeHtml(getProjectName() || 'Untitled')
+  const fileName = `${base.replace(/[^a-z0-9]/gi, '_')}.v`
+  downloadFile(fileName, code.value)
   SimulatorState.dialogBox.exportverilog_dialog = false
 }
v0/src/components/Panels/Shared/InputGroups.vue (2)

83-90: Minor: stray apostrophe in CSS comment

-/* Hide spinners for numeric input' */
+/* Hide spinners for numeric inputs */

92-94: Firefox rule loses specificity without input[type="number"] spacing

Some browsers ignore the selector when = is not quoted:

-input[type=number]{
+input[type="number"] {
     -moz-appearance: textfield;
 }
v0/src/assets/constants/theme.ts (1)

1-8: Use a union & Record to avoid manual key duplication

Manually repeating the keys in both the type and the object invites drift. Let TS infer:

-export type ThemeType = {
-  'default': string;
-  ...
-};
-
-export const THEME: ThemeType = {
+export const THEME = {
   'default': 'Default Theme',
   ...
-};
+} as const;
+
+export type ThemeKey = keyof typeof THEME;

Gives strong typing with one source of truth.

v0/src/locales/bn.json (1)

41-43: Unescaped newline may render literally

The \n inside "নতুন ভেরিলোগ\nমডিউল" is fine for plain text, but many UI components render HTML; consider replacing with <br/> or splitting label logicically.

v0/src/components/Navbar/Navbar.css (1)

1-1: Root-relative @import may break depending on build tooling

/src/styles/color_theme.scss assumes the bundler resolves URLs from the project root.
If the app is deployed from a sub-folder or the Vite / Webpack publicPath is non-root, the sheet will 404.
Consider a tilde / alias or a relative path instead, e.g.

-@import url('/src/styles/color_theme.scss');
+@import url('~@/styles/color_theme.scss');   /* Vite / Vue-CLI default alias */
v0/src/simulator/src/data/backupCircuit.js (2)

17-21: Edge case: updateOrder must stay in sync with scope fields

checkIfBackup now iterates over updateOrder. If new element arrays are added to Scope but updateOrder is not updated, backups silently miss data.
Consider adding a runtime assert or automated test that validates every scope array in moduleList is also in updateOrder.


49-53: Potential performance micro-optimisation

The inside-loop map(extract) executes for every module type even when the outer array is empty.
Minor, but you can avoid the extra allocation:

-    for (let i = 0; i < moduleList.length; i++) {
-        if (scope[moduleList[i]].length) {
-            data[moduleList[i]] = scope[moduleList[i]].map(extract)
-        }
-    }
+    for (const key of moduleList) {
+        const arr = scope[key]
+        if (arr && arr.length) data[key] = arr.map(extract)
+    }
v0/src/components/Panels/VerilogEditorPanel/VerilogEditorPanel.vue (1)

97-103: Un-scoped style may bleed into other selects

Removing the scoped attribute makes .applyTheme global. Any <select class="applyTheme"> elsewhere will now inherit these white borders and padding.

If the intent is truly global theming, keep it. Otherwise re-add scoped or namespace the class:

-<style>
+<style scoped>

—or—

.verilog-editor-panel .applyTheme { ... }
v0/src/simulator/src/data/load.js (2)

24-25: moduleList copy unnecessary

moduleList.slice() allocates every load. Unless ML is mutated later (it isn't), iterate over moduleList directly to save GC churn.

-const ML = moduleList.slice()
+const ML = moduleList        // or iterate directly

263-265: Magic default clock period

data.timePeriod || 500 hard-codes 500 ms when the saved file lacks timePeriod. Consider exposing this default as a constant so UI and documentation stay consistent.

v0/src/router/index.ts (1)

5-35: Nice – exporting routes increases re-usability

Making the array public will let unit tests and storybook instances reuse the same config. No functional issues spotted.
Tiny nit: the TODO paths (/simulatorvue) are still hard-coded; confirm you indeed want those in production before merging.

v0/src/components/ReportIssue/ReportIssueButton.vue (1)

8-22: Reactive position works, but consider CSS class instead of inline style

Inline styles hinder theming and dark-mode tweaks. A computed class tied to showElementsPanel (e.g. .bottom--large/.bottom--small) would keep markup cleaner and avoid !important wars later.

v0/src/simulator/spec/testData/gates-testdata.json (1)

222-255: Minor casing inconsistencies in titles

"NOT GAte" / "XNOR GAte" differ from the usual “Gate” capitalisation. Purely cosmetic, but could confuse string-matching tests.

v0/src/locales/en.json (1)

12-15: Key naming consistency

"layout_elements" duplicates the wording already present under panel_header.layout_elements.
Unless the panel header and sidebar strings differ intentionally, de-duplicate to keep translators’ workload low.

v0/src/simulator/spec/vitestSetup.ts (2)

3-5: Accidental shadowing of common globals

global.width / global.height are very generic and may collide with libraries that rely on Node’s process.stdout.columns workaround or browser APIs.
Namespace these flags (e.g., global.__SIM_TEST_WIDTH__) or attach them to window only.


9-11: Missing cleanup for test globals

Shared mutable globals (restrictedElements, userSignedIn, embed) persist between test files and can create hidden couplings.
Provide a beforeEach/afterEach hook resetting them or move them to Vitest’s setupFiles that re-runs per worker.

v0/src/pages/simulatorHandler.vue (2)

102-104: Boolean expression can be simplified & renamed

simulatorMobileStore.showMobileView = window.innerWidth < simulatorMobileStore.minWidthToShowMobile ? true : false
can just be:

-simulatorMobileStore.showMobileView = window.innerWidth < simulatorMobileStore.minWidthToShowMobile ? true : false
+simulatorMobileStore.showMobileView =
+  window.innerWidth < simulatorMobileStore.minWidthToShowMobile

Also, checkShowSidebar now toggles mobile mode; rename to updateMobileViewState for clarity.


85-97: Race condition when projectId is undefined

getLoginData() is fired but its async promise isn’t awaited before isLoading.value = false, which causes a brief flash of “Loading…” followed by a possible re-render when login data resolves.

Consider:

async function openBlankSimulator() {
  isLoading.value = true
  await getLoginData()
  isLoading.value = false
}
v0/src/simulator/spec/testData/subCircuit-testdata.json (1)

4-6: Nit: type field can be inferred

If downstream code already distinguishes combinational vs sequential using groups[*].n, keeping "type": "comb" is harmless but redundant.
Consider removing to reduce duplication across datasets.

v0/src/simulator/spec/testData/alu-testdata.json (1)

4-5: Provide meaningful title for easier test diagnostics

"title": "Untitled" makes CI failure logs harder to trace when multiple datasets fail.
Rename to "ALU" or similar.

v0/src/components/TabsBar/TabsBar.vue (2)

82-83: Duplicate import from the same module – merge into one statement

circuitNameClicked is imported in a second standalone line while several functions are already imported from the same path above (l. 73 – 78). Reduce churn / tree-shaking cost:

-import {
-    createNewCircuitScope,
-    // …,
-    switchCircuit,
-} from '#/simulator/src/circuit'
+import {
+    createNewCircuitScope,
+    // …,
+    switchCircuit,
+    circuitNameClicked,
+} from '#/simulator/src/circuit'
-
-import { circuitNameClicked } from '#/simulator/src/circuit'

336-339: Toolbar height magic number

height: 22px is another hard-coded pixel value; prefer using the CSS var already driving other toolbar dimensions (if available) to avoid mismatch when theming.

v0/src/locales/i18n.ts (1)

6-17: Named and default export of the same i18n instance

Having both is legal but can confuse import style consistency across the code-base. Decide on one (prefer export default) and align usage.

v0/src/simulator/src/data/saveImage.ts (1)

1-15: Store accessor naming inconsistent with rest of codebase

Other modules use useState()/useSimulatorStore() pattern; introducing SimulatorStore() here creates cognitive churn. For uniformity export one canonical getter from the store module and reuse it.

v0/src/simulator/spec/subCircuit.spec.js (1)

26-75: Heavy setup duplicated across specs – extract to a shared helper

The boiler-plate (Pinia + router + CodeMirror mocks + createRange stub + component mount) is repeated verbatim in every simulator spec, bloating test code and slowing execution.

Consider moving this into test/utils/setupSimulator.ts and invoking it with:

const { pinia, router, wrapper } = await setupSimulator();

This yields:

  • DRY test files
  • Single maintenance point for future changes
  • Easier addition of teardown (wrapper.unmount(), restoring globals)
v0/src/components/Panels/TimingDiagramPanel/TimingDiagramButtons.vue (1)

26-33: Inconsistent padding keys

When isMobileView is false you return {}, but Vue may keep the previous
inline style. Safer to always return all keys with explicit values.

-    return isMobileView ? { padding, paddingTop, paddingBottom } : {}
+    return { padding: isMobileView ? padding : '', paddingTop, paddingBottom }
v0/src/simulator/spec/bitConvertor.spec.js (4)

1-3: ES-Lint globals missing – add test-environment header

vi, describe, beforeAll, test, expect are reported as undefined by ESLint.
Insert a single header comment to declare the Vitest env instead of sprinkling /* global … */ everywhere.

+/* eslint-env vitest */

Place it on the very first line (above all imports) to silence the warnings cleanly.


11-17: Mock callback signature can be simplified

You don’t need the callback parameter; Vitest already exposes vi.importActual.
The current pattern works but is harder to read.

-vi.mock('codemirror', async (importOriginal) => {
-    const actual = await importOriginal();
+vi.mock('codemirror', async () => {
+    const actual = await vi.importActual('codemirror');
🧰 Tools
🪛 GitHub Check: ESLint

[failure] 11-11: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 15-15: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


42-60: Duplicate document.createRange stub – extract to shared test util

Exactly the same stub appears in several spec files. Move it to a dedicated helper (e.g. tests/setupDomMocks.ts) and call it from beforeAll to avoid copy-paste maintenance.

🧰 Tools
🪛 GitHub Check: ESLint

[failure] 42-42: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 43-43: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 44-44: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 45-45: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 55-55: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 56-56: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 58-58: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


84-86: Remove noisy console output in test

console.log('Testing for Base Value --> ', randomBaseValue); pollutes test output and CI logs without adding assertion value.

-        console.log('Testing for Base Value --> ', randomBaseValue);
🧰 Tools
🪛 GitHub Check: ESLint

[failure] 86-86: disallow the use of undeclared variables unless mentioned in /*global */ comments
'expect' is not defined.

v0/src/simulator/spec/testData/sequential-testdata.json (1)

1-250: File is big but valid – consider schema validation in CI

Nothing blocking here, but adding a JSON-schema and hooking it into lint-stage would prevent accidental format errors in future edits.

v0/src/simulator/spec/decoders-plexers.spec.js (1)

1-3: Missing Vitest env header (same as other spec)

Add /* eslint-env vitest */ at the top to silence ESLint for globals.

v0/src/components/Navbar/Navbar.vue (2)

18-22: Class name typo

Template uses class="useMenuBtn"; CSS also defines .useMenuBtn. If the intention was userMenuBtn, rename for clarity or leave a comment.


2-8: Redundant v-if duplication

The <nav> and inner <div> both check !simulatorMobileStore.showMobileView. The inner check is redundant because the outer guards it already.

-        <div
-            v-if="!simulatorMobileStore.showMobileView"
+        <div
v0/src/simulator/src/data.js (2)

42-58: Wrapper naming is confusing

createNewCircuit() merely forwards to createNewCircuitScope(), yet the exported property is still called createNewCircuitScope. Consider:

-logixFunction.createNewCircuitScope = createNewCircuit
+logixFunction.createNewCircuit = createNewCircuit

This keeps names consistent and avoids misleading downstream code.


55-58: Tiny nit – add return for clarity

The helper doesn’t need to be void; returning the underlying result makes chaining possible.

-function createNewCircuit() {
-    createNewCircuitScope()
+function createNewCircuit() {
+    return createNewCircuitScope()
 }
v0/src/simulator/src/data/redo.ts (1)

20-23: Consider improving global variable management

Instead of using declare var for global variables, consider importing them from a dedicated module or using a global type definition file (.d.ts) to centralize global declarations.

Create a globals.d.ts file:

declare global {
  var globalScope: ExtendedScope;
  var loading: boolean;
}
v0/src/components/Panels/TimingDiagramPanel/TimingDiagramPanel.vue (1)

61-65: Consider keeping styles scoped

Changing from scoped to global styles could cause CSS conflicts with other components. If global styles are necessary, consider using a more specific selector or CSS modules.

-<style>
+<style scoped>
 .timing-diagram-panel-button {
     margin-right: 5px;
 }
 </style>
v0/src/simulator/src/canvasApi.js (1)

111-115: Remove duplicate display assignment

Line 114 duplicates the display assignment from line 112.

         let miniMap = document.querySelector('#miniMap');
         miniMap.style.display = 'block';
         updatelastMinimapShown()
-        miniMap.style.display = 'block';
         setTimeout(removeMiniMap, 2000)
v0/src/components/Navbar/NavbarLinks/NavbarLink/NavbarLink2.vue (1)

4-8: Hard-coded element id risks duplicates

id="navbarMenuButton" will be rendered for every NavbarLink2 instance, violating DOM uniqueness.
Either compute a unique id (:id="navbarItem.text + '-btn'`") or drop the id attribute unless it is required for tests.

v0/src/components/Panels/PropertiesPanel/LayoutProperty/LayoutProperty.vue (1)

128-133: Watcher could use immediate:true to reflect initial state

If titleEnable is already true on mount, the watcher will never fire and the title won’t sync until toggled.

 watch(
   () => propertiesPanelStore.titleEnable,
-  () => { layoutFunction('toggleLayoutTitle') }
+  () => layoutFunction('toggleLayoutTitle'),
+  { immediate: true }
 )

Optional but improves first-render consistency.

v0/src/simulator/spec/gates.spec.js (1)

30-44: Router navigation not awaited; tests may race

mount() is executed before the router finishes initialisation.
While the current tests pass by chance, a route-dependent component would fail.

 router = createRouter({ … })
 await router.isReady()   // ensure async hook chain completes
 mount(simulator, { … })

Adds negligible cost and future-proofs the suite.

v0/src/components/Panels/PropertiesPanel/PropertiesPanel.ts (3)

14-16: Avoid redundant getter calls

layoutModeGet() is invoked twice consecutively. Cache the result once to prevent unnecessary work:

- if (propertiesPanelStore.inLayoutMode.value != layoutModeGet())
-     propertiesPanelStore.inLayoutMode.value = layoutModeGet()
+const inLayout = layoutModeGet()
+if (propertiesPanelStore.inLayoutMode.value !== inLayout)
+    propertiesPanelStore.inLayoutMode.value = inLayout

20-22: Optional-chain for defensive access

simulationArea.lastSelected can be undefined; optional chaining removes the need for the leading guard and silences linter noise:

-if(simulationArea.lastSelected && simulationArea.lastSelected.newElement) {
-    simulationArea.lastSelected.label = ""
-}
+if (simulationArea.lastSelected?.newElement) {
+    simulationArea.lastSelected.label = ''
+}
🧰 Tools
🪛 Biome (1.9.4)

[error] 20-20: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


11-58: Poll-driven update may be wasteful

showPropertiesPanel is designed to be polled every 100 ms from several components. Consider replacing the interval with:

  • a watch on simulationArea.lastSelected
  • a watch on layoutModeGet() via a reactive wrapper

to cut CPU usage and duplicated timers.

🧰 Tools
🪛 Biome (1.9.4)

[error] 20-20: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

v0/src/components/Navbar/QuickButton/QuickButtonMobile.vue (1)

85-96: Slider lacks reactive binding

The range input and <span id="slider_value"> are raw DOM elements; without a v-model or ref they won’t reflect decrement/increment changes, making tests and SSR harder. Bind the value to a reactive ref:

<input type="range" v-model="zoomLevel" ... />
<span>{{ zoomLevel }}</span>

and update zoomLevel inside the imported helpers.

v0/src/components/Panels/TestBenchPanel/TestBenchPanel.vue (1)

32-38: Key collisions in v-for

key="button.title" is not unique if two buttons share a title.
Use a stable id, e.g. :key="button.id || button.title" to avoid patching issues.

v0/src/components/Panels/TimingDiagramPanel/TimingDiagramMobile.vue (2)

13-16: Avoid recreating closures in every render

@click="() => { handleButtonClick(button.click) }" allocates a new function each render.
Simpler & cheaper:

-@click="() => { handleButtonClick(button.click) }"
+@click="handleButtonClick(button.click)"

34-35: _plotArea import is unused

If the import is only for side-effects, remove the leading underscore to silence linters or use:

import '#/simulator/src/plotArea';

[nitpick]

v0/src/components/Panels/LayoutElementsPanel/LayoutElementsPanel.vue (1)

76-82: getImgUrl builds path at runtime for every render

Cache the result or compute once per element to avoid redundant new URL allocations inside loops.

v0/src/components/Panels/VerilogEditorPanel/VerilogEditorPanelMobile.vue (1)

90-92: Persist the chosen theme

applyVerilogTheme runs but the new value is not saved back to localStorage, so the choice is lost on reload.

watch(selectedTheme, (newTheme) => {
  applyVerilogTheme(newTheme);
+ localStorage.setItem('verilog-theme', newTheme);
});
v0/src/components/DialogBox/OpenOffline.vue (2)

37-40: Prefer Object.keys().length over string comparison

JSON.stringify(projectList) == '{}' incurs unnecessary serialization every render and ignores key ordering differences.

- <p v-if="JSON.stringify(projectList) == '{}'">
+ <p v-if="Object.keys(projectList).length === 0">

82-89: deleteOfflineProject should also clear a deleted selection

If the user deletes the project that is currently selected, selectedProjectId keeps pointing to a now-missing id, making the subsequent “open project” a no-op.
Add a guard:

   delete temp[id]
+  if (selectedProjectId.value === id) selectedProjectId.value = null
v0/src/components/Navbar/Hamburger/Hamburger2.vue (2)

88-89: userMenuState ref declared but never initialised

An empty ref is spread with v-bind="userMenuState" resulting in { "value": undefined } props leaking into UserMenu.
Either remove the binding or set it to a proper reactive object.


90-94: Avoid raw DOM queries – use Vue refs

Directly querying .avatar-btn breaks SSR and component encapsulation.
Emit an event from UserMenu instead or expose the button through a ref:

const avatarBtn = ref<HTMLButtonElement>()
// in template of UserMenu: <button ref="avatarBtn" …>
v0/src/simulator/spec/circuits/misc-circuitdata.json (1)

1506-1545: Redundant ForceGate definition duplicated

Same issue as in the sequential fixture – the second object adds no value and should be deleted to keep the JSON minimal and deterministic.

v0/src/components/Panels/TestBenchPanel/TestBenchCreator.vue (2)

25-26: style attribute is mis-used

<v-card-text style="testCard"> assigns a string that is neither a CSS declaration block nor a binding.
Replace with class="testCard" or a valid inline style.

-<v-card-text style="testCard">
+<v-card-text class="testCard">

171-195: Duplicate deep watch – consider consolidating

Two watch blocks observe exactly the same source (testBenchStore.testbenchData.testData.groups).
Merge them to avoid double execution and make intent clearer.

v0/src/simulator/src/data/save.js (1)

369-371: Consider extracting loading icon manipulation into helper functions.

While the jQuery removal is correct, there's repeated code for showing/hiding the loading icon. Consider extracting these into reusable functions.

+function showLoadingIcon() {
+    const loadingIcon = document.querySelector('.loadingIcon');
+    if (loadingIcon) {
+        loadingIcon.style.transition = 'opacity 0.5s linear';
+        loadingIcon.style.opacity = '1';
+    }
+}
+
+function hideLoadingIcon() {
+    const loadingIcon = document.querySelector('.loadingIcon');
+    if (loadingIcon) {
+        loadingIcon.style.transition = 'opacity 0.2s';
+        loadingIcon.style.opacity = '0';
+    }
+}

 export default async function save() {
     // ... existing code ...
-    let loadingIcon = document.querySelector('.loadingIcon');
-    loadingIcon.style.transition = 'opacity 0.5s linear';
-    loadingIcon.style.opacity = '1';
+    showLoadingIcon();

Also applies to: 393-396, 450-452, 523-525

v0/src/pages/embed.vue (1)

243-251: Consider combining lifecycle hooks.

Having multiple onMounted hooks can make the code harder to follow. Consider combining them.

-onMounted(() => {
-    const themeValue = theme?.value as string;
-    updateThemeForStyle(THEME[themeValue as keyof ThemeType]);
-})
-
-onMounted(() => {
-    startListeners()
-    setup()
-})
+onMounted(() => {
+    // Apply theme from query parameter
+    const themeValue = theme?.value as string;
+    if (themeValue && themeValue in THEME) {
+        updateThemeForStyle(THEME[themeValue as keyof ThemeType]);
+    }
+    
+    // Initialize simulator
+    startListeners()
+    setup()
+})
v0/src/components/DialogBox/Themes/ApplyThemes.vue (1)

291-294: Good defensive localStorage handling.

The fallback to default theme is a good safety measure. Consider adding explicit error handling for the JSON.parse.

 const customTheme = localStorage.getItem('Custom Theme')
 if (customTheme) {
-    themeOptions['Custom Theme'] = JSON.parse(customTheme) || themeOptions['Default Theme']
+    try {
+        themeOptions['Custom Theme'] = JSON.parse(customTheme)
+    } catch {
+        themeOptions['Custom Theme'] = themeOptions['Default Theme']
+    }
 }
v0/src/components/Extra.vue (1)

296-305: Consider using modern Clipboard API.

The execCommand API is deprecated. Consider using the modern Clipboard API for better browser support.

-const copyBtnClick = () => {
-    window.document.execCommand('copy')
-    simulationArea.shiftDown = false
-    simulatorMobileStore.isCopy = true
-}
+const copyBtnClick = async () => {
+    try {
+        // Assuming the copy logic is handled elsewhere and data is in clipboard
+        await navigator.clipboard.writeText(localStorage.getItem('clipboardData') || '');
+        simulationArea.shiftDown = false;
+        simulatorMobileStore.isCopy = true;
+    } catch (err) {
+        console.error('Failed to copy:', err);
+    }
+}
v0/src/simulator/spec/circuits/subCircuit-circuitdata.json (4)

20-25: Remove placeholder Verilog code or supply actual implementations
Each scope’s verilogMetadata.code field currently contains "// Write Some Verilog Code Here!". This stub will appear in Verilog exports or dialogs even if unused. Replace it with real code snippets or clear the field if Verilog integration is out of scope.

Also applies to: 344-349


26-173: Avoid overlapping node coordinates in Half-adder scope
In the allNodes list, nodes at indices 2 and 5 share the same position (x: 20, y: 0), leading to UI overlap. Consider offsetting one of these nodes slightly to improve visual clarity.


350-609: Avoid overlapping node coordinates in Main scope
Multiple entries in the Main scope’s allNodes array use identical (x, y) values (e.g., several nodes at 10, 0). These overlaps can confuse users in the circuit editor. Please stagger or adjust coordinates for distinct placement.


1-815: Add JSON schema validation as part of CI
Since this file is critical for simulator integrity and is being synced across versions (v0/src and v1/src), include a JSON schema check in your pipeline to catch missing fields or type mismatches early. Consider adding a lightweight ajv or jsonschema validation step against a committed schema.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8d8ca00 and ab30ade.

📒 Files selected for processing (94)
  • v0/src/assets/constants/theme.ts (1 hunks)
  • v0/src/components/DialogBox/CombinationalAnalysis.vue (5 hunks)
  • v0/src/components/DialogBox/ExportProject.vue (2 hunks)
  • v0/src/components/DialogBox/ExportVerilog.vue (3 hunks)
  • v0/src/components/DialogBox/InsertSubcircuit.vue (1 hunks)
  • v0/src/components/DialogBox/OpenOffline.vue (2 hunks)
  • v0/src/components/DialogBox/Themes/ApplyThemes.vue (7 hunks)
  • v0/src/components/Extra.vue (6 hunks)
  • v0/src/components/Logo/Logo.vue (1 hunks)
  • v0/src/components/Navbar/Hamburger/Hamburger2.vue (1 hunks)
  • v0/src/components/Navbar/Navbar.css (1 hunks)
  • v0/src/components/Navbar/Navbar.vue (2 hunks)
  • v0/src/components/Navbar/NavbarLinks/NavbarLink/NavbarLink2.vue (1 hunks)
  • v0/src/components/Navbar/NavbarLinks/NavbarLinks.vue (1 hunks)
  • v0/src/components/Navbar/QuickButton/QuickButton.ts (1 hunks)
  • v0/src/components/Navbar/QuickButton/QuickButton.vue (5 hunks)
  • v0/src/components/Navbar/QuickButton/QuickButtonMobile.vue (1 hunks)
  • v0/src/components/Navbar/User/UserMenu.vue (1 hunks)
  • v0/src/components/Panels/ElementsPanel/ElementsPanel.ts (1 hunks)
  • v0/src/components/Panels/ElementsPanel/ElementsPanel.vue (4 hunks)
  • v0/src/components/Panels/ElementsPanel/ElementsPanelMobile.vue (1 hunks)
  • v0/src/components/Panels/LayoutElementsPanel/LayoutElementsPanel.vue (1 hunks)
  • v0/src/components/Panels/PropertiesPanel/LayoutProperty/LayoutProperty.vue (3 hunks)
  • v0/src/components/Panels/PropertiesPanel/ModuleProperty/ModuleProperty.vue (1 hunks)
  • v0/src/components/Panels/PropertiesPanel/ModuleProperty/ProjectProperty/ProjectProperty.vue (5 hunks)
  • v0/src/components/Panels/PropertiesPanel/PropertiesPanel.ts (1 hunks)
  • v0/src/components/Panels/PropertiesPanel/PropertiesPanel.vue (1 hunks)
  • v0/src/components/Panels/PropertiesPanel/PropertiesPanelMobile.vue (1 hunks)
  • v0/src/components/Panels/Shared/InputGroups.vue (1 hunks)
  • v0/src/components/Panels/TestBenchPanel/TestBenchCreator.vue (1 hunks)
  • v0/src/components/Panels/TestBenchPanel/TestBenchPanel.vue (1 hunks)
  • v0/src/components/Panels/TestBenchPanel/TestBenchValidator.vue (1 hunks)
  • v0/src/components/Panels/TimingDiagramPanel/TimingDiagramButtons.vue (1 hunks)
  • v0/src/components/Panels/TimingDiagramPanel/TimingDiagramMobile.vue (1 hunks)
  • v0/src/components/Panels/TimingDiagramPanel/TimingDiagramPanel.ts (1 hunks)
  • v0/src/components/Panels/TimingDiagramPanel/TimingDiagramPanel.vue (3 hunks)
  • v0/src/components/Panels/VerilogEditorPanel/VerilogEditorPanel.vue (1 hunks)
  • v0/src/components/Panels/VerilogEditorPanel/VerilogEditorPanelMobile.vue (1 hunks)
  • v0/src/components/ReportIssue/ReportIssueButton.vue (2 hunks)
  • v0/src/components/TabsBar/TabsBar.vue (6 hunks)
  • v0/src/components/helpers/deleteCircuit/DeleteCircuit.vue (2 hunks)
  • v0/src/env.d.ts (1 hunks)
  • v0/src/globalVariables.ts (0 hunks)
  • v0/src/locales/bn.json (1 hunks)
  • v0/src/locales/en.json (1 hunks)
  • v0/src/locales/hi.json (1 hunks)
  • v0/src/locales/i18n.ts (1 hunks)
  • v0/src/main.ts (0 hunks)
  • v0/src/pages/embed.vue (8 hunks)
  • v0/src/pages/simulatorHandler.vue (2 hunks)
  • v0/src/router/index.ts (1 hunks)
  • v0/src/simulator/spec/bitConvertor.spec.js (1 hunks)
  • v0/src/simulator/spec/circuits/Decoders-plexers-circuitdata.json (1 hunks)
  • v0/src/simulator/spec/circuits/gates-circuitdata.json (1 hunks)
  • v0/src/simulator/spec/circuits/misc-circuitdata.json (1 hunks)
  • v0/src/simulator/spec/circuits/sequential-circuitdata.json (1 hunks)
  • v0/src/simulator/spec/circuits/subCircuit-circuitdata.json (1 hunks)
  • v0/src/simulator/spec/combinationalAnalysis.spec.js (1 hunks)
  • v0/src/simulator/spec/complexCircuit.spec.js (1 hunks)
  • v0/src/simulator/spec/data.spec.js (1 hunks)
  • v0/src/simulator/spec/decoders-plexers.spec.js (1 hunks)
  • v0/src/simulator/spec/gates.spec.js (1 hunks)
  • v0/src/simulator/spec/misc.spec.js (1 hunks)
  • v0/src/simulator/spec/sequential.spec.js (1 hunks)
  • v0/src/simulator/spec/subCircuit.spec.js (1 hunks)
  • v0/src/simulator/spec/testData/alu-testdata.json (1 hunks)
  • v0/src/simulator/spec/testData/decoders-plexers.json (1 hunks)
  • v0/src/simulator/spec/testData/gates-testdata.json (1 hunks)
  • v0/src/simulator/spec/testData/misc-testdata.json (1 hunks)
  • v0/src/simulator/spec/testData/ripple-carry-adder.json (1 hunks)
  • v0/src/simulator/spec/testData/sequential-testdata.json (1 hunks)
  • v0/src/simulator/spec/testData/subCircuit-testdata.json (1 hunks)
  • v0/src/simulator/spec/vitestSetup.ts (1 hunks)
  • v0/src/simulator/src/Verilog2CV.js (4 hunks)
  • v0/src/simulator/src/VerilogClasses.js (0 hunks)
  • v0/src/simulator/src/app.ts (2 hunks)
  • v0/src/simulator/src/arrayHelpers.js (0 hunks)
  • v0/src/simulator/src/backgroundArea.js (0 hunks)
  • v0/src/simulator/src/backgroundArea.ts (1 hunks)
  • v0/src/simulator/src/canvas2svg.js (0 hunks)
  • v0/src/simulator/src/canvasApi.js (4 hunks)
  • v0/src/simulator/src/circuit.ts (14 hunks)
  • v0/src/simulator/src/circuitElement.js (13 hunks)
  • v0/src/simulator/src/combinationalAnalysis.js (1 hunks)
  • v0/src/simulator/src/contention.ts (1 hunks)
  • v0/src/simulator/src/data.js (3 hunks)
  • v0/src/simulator/src/data/backupCircuit.js (1 hunks)
  • v0/src/simulator/src/data/load.js (2 hunks)
  • v0/src/simulator/src/data/project.ts (7 hunks)
  • v0/src/simulator/src/data/redo.js (0 hunks)
  • v0/src/simulator/src/data/redo.ts (1 hunks)
  • v0/src/simulator/src/data/save.js (10 hunks)
  • v0/src/simulator/src/data/saveImage.js (0 hunks)
  • v0/src/simulator/src/data/saveImage.ts (1 hunks)
💤 Files with no reviewable changes (8)
  • v0/src/main.ts
  • v0/src/globalVariables.ts
  • v0/src/simulator/src/backgroundArea.js
  • v0/src/simulator/src/data/saveImage.js
  • v0/src/simulator/src/data/redo.js
  • v0/src/simulator/src/arrayHelpers.js
  • v0/src/simulator/src/VerilogClasses.js
  • v0/src/simulator/src/canvas2svg.js
🧰 Additional context used
🪛 GitHub Check: ESLint
v0/src/simulator/spec/bitConvertor.spec.js

[failure] 11-11: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 15-15: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 19-19: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 20-20: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 23-23: disallow the use of undeclared variables unless mentioned in /*global */ comments
'describe' is not defined.


[failure] 27-27: disallow the use of undeclared variables unless mentioned in /*global */ comments
'beforeAll' is not defined.


[failure] 42-42: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 43-43: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 44-44: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 45-45: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 55-55: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 56-56: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 58-58: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 75-75: disallow the use of undeclared variables unless mentioned in /*global */ comments
'test' is not defined.


[failure] 76-76: disallow the use of undeclared variables unless mentioned in /*global */ comments
'expect' is not defined.


[failure] 79-79: disallow the use of undeclared variables unless mentioned in /*global */ comments
'test' is not defined.


[failure] 80-80: disallow the use of undeclared variables unless mentioned in /*global */ comments
'expect' is not defined.


[failure] 83-83: disallow the use of undeclared variables unless mentioned in /*global */ comments
'test' is not defined.


[failure] 86-86: disallow the use of undeclared variables unless mentioned in /*global */ comments
'expect' is not defined.

v0/src/simulator/spec/combinationalAnalysis.spec.js

[failure] 13-13: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 17-17: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 21-21: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 22-22: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 25-25: disallow the use of undeclared variables unless mentioned in /*global */ comments
'describe' is not defined.


[failure] 29-29: disallow the use of undeclared variables unless mentioned in /*global */ comments
'beforeAll' is not defined.


[failure] 44-44: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 45-45: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 46-46: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 47-47: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.


[failure] 57-57: disallow the use of undeclared variables unless mentioned in /*global */ comments
'vi' is not defined.

🪛 Biome (1.9.4)
v0/src/components/Panels/PropertiesPanel/PropertiesPanel.ts

[error] 20-20: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

v0/src/simulator/src/combinationalAnalysis.js

[error] 136-136: Shouldn't redeclare 'i'. Consider to delete it or rename it.

'i' is defined here:

(lint/suspicious/noRedeclare)


[error] 165-165: Shouldn't redeclare 'i'. Consider to delete it or rename it.

'i' is defined here:

(lint/suspicious/noRedeclare)


[error] 182-182: Shouldn't redeclare 'k'. Consider to delete it or rename it.

'k' is defined here:

(lint/suspicious/noRedeclare)


[error] 184-184: Shouldn't redeclare 'index'. Consider to delete it or rename it.

'index' is defined here:

(lint/suspicious/noRedeclare)


[error] 186-186: Shouldn't redeclare 'v'. Consider to delete it or rename it.

'v' is defined here:

(lint/suspicious/noRedeclare)


[error] 203-203: Shouldn't redeclare 'j'. Consider to delete it or rename it.

'j' is defined here:

(lint/suspicious/noRedeclare)


[error] 204-204: Shouldn't redeclare 'v'. Consider to delete it or rename it.

'v' is defined here:

(lint/suspicious/noRedeclare)


[error] 205-205: This variable is used before its declaration.

The variable is declared here:

(lint/correctness/noInvalidUseBeforeDeclaration)


[error] 206-206: Shouldn't redeclare 'v2'. Consider to delete it or rename it.

'v2' is defined here:

(lint/suspicious/noRedeclare)


[error] 207-207: This variable is used before its declaration.

The variable is declared here:

(lint/correctness/noInvalidUseBeforeDeclaration)


[error] 207-207: This variable is used before its declaration.

The variable is declared here:

(lint/correctness/noInvalidUseBeforeDeclaration)


[error] 208-208: This variable is used before its declaration.

The variable is declared here:

(lint/correctness/noInvalidUseBeforeDeclaration)


[error] 210-210: Shouldn't redeclare 'v'. Consider to delete it or rename it.

'v' is defined here:

(lint/suspicious/noRedeclare)


[error] 212-212: Shouldn't redeclare 'v2'. Consider to delete it or rename it.

'v2' is defined here:

(lint/suspicious/noRedeclare)


[error] 219-219: Shouldn't redeclare 'out'. Consider to delete it or rename it.

'out' is defined here:

(lint/suspicious/noRedeclare)


[error] 225-225: Shouldn't redeclare 'i'. Consider to delete it or rename it.

'i' is defined here:

(lint/suspicious/noRedeclare)


[error] 227-227: Shouldn't redeclare 'v'. Consider to delete it or rename it.

'v' is defined here:

(lint/suspicious/noRedeclare)


[error] 315-315: eval() exposes to security risks and performance issues.

See the MDN web docs for more details.
Refactor the code so that it doesn't need to call eval().

(lint/security/noGlobalEval)

v0/src/simulator/src/circuit.ts

[error] 309-309: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (51)
v0/src/simulator/src/app.ts (1)

1-2: Array-polyfill removal is a welcome cleanup

Dropping the arrayHelpers side-effect import avoids polluting the global Array prototype and aligns with TS best practices. Nice catch.

v0/src/components/DialogBox/ExportProject.vue (1)

76-76: Updated invocation to downloadFile
This correctly replaces the old download call with the new API, ensuring consistent file-download behavior.

v0/src/components/DialogBox/ExportVerilog.vue (2)

46-46: Correct source for Vue APIs
Importing onMounted and ref from 'vue' is the recommended entry point in Vue 3. LGTM.


60-64: Standardized download utility import
Renaming download to downloadFile aligns with other components and reduces ambiguity.

v0/src/components/Logo/Logo.vue (1)

2-4:

❌ Incorrect review comment

Replacing <router-link> with <a> breaks SPA navigation & lacks accessibility labelling

  1. Switching from client-side <router-link> to a plain anchor triggers a full page reload, defeating SPA benefits (state preservation, faster nav).
  2. The anchor has no aria-label or textual content for screen-readers, so the brand link will be announced as empty.
-    <a href="/">
+    <!-- keep SPA nav & add a11y label -->
+    <router-link to="/" aria-label="Home">
         <span :class="cvlogo"></span>
-    </a>
+    </router-link>

If a hard reload is intentional, at least add aria-label="Home".



🏁 Script executed:

#!/bin/bash
# Search for <router-link> usage in the codebase
rg "<router-link" -n .

# Check for Vue Router setup (Vue 3 & Vue 2)
rg "createRouter" -n .
rg "new Router" -n .

Length of output: 5455


🏁 Script executed:

#!/bin/bash
# Locate Logo.vue file
fd Logo.vue

# Display the first 20 lines of the Logo.vue in v0 branch
sed -n '1,20p' v0/src/components/Logo/Logo.vue

Length of output: 439


No <router-link> in Logo.vue – review comment is incorrect

The Logo.vue component in both v0 and v1 branches has always used a plain <a href="/">, not a <router-link>. Nothing was replaced, so there is no SPA navigation break introduced here.

You can safely disregard the suggestion to switch back to <router-link>.

Likely an incorrect or invalid review comment.

v0/src/components/DialogBox/InsertSubcircuit.vue (1)

69-69: Confirm simulationArea is exported as named

Import was switched to a named import:

import { simulationArea } from '#/simulator/src/simulationArea'

Ensure the module now exports simulationArea (not default) everywhere, or this will be undefined.

v0/src/simulator/src/data/backupCircuit.js (1)

2-2: 👍 Explicit import removes hidden global dependency

Importing moduleList and updateOrder makes the dependency graph clearer and prevents accidental reliance on globals.
Looks good.

v0/src/components/Navbar/NavbarLinks/NavbarLinks.vue (1)

13-13: Confirm import path

Make sure ./NavbarLink/NavbarLink2.vue exists; the previous component sat beside this file. If the folder move was accidental the build will fail.

v0/src/simulator/src/data/load.js (1)

11-11: Named import assumes simulationArea is now exported explicitly

If simulationArea is still a default export, this change will import undefined and crash at runtime (simulationArea.changeClockTime).
Double-check simulationArea/index.ts (or .js) exports.

// simulationArea.js
export const simulationArea = { ... }   // ✅ required
v0/src/locales/hi.json (1)

12-17: Good localisation coverage

New keys match the English source and follow existing style. LGTM.

v0/src/locales/en.json (1)

12-16: Ensure locale-key parity across all languages

New keys (simulator.layout.*, simulator.unlabeled) are only added to the English bundle.
If other locale files are not updated, users will see raw keys instead of translations.

Action:

  1. Add the same keys to every *.json locale file (with at least an empty string as value).
  2. Consider adding a unit test that scans locale folders for missing keys to avoid future drift.
v0/src/components/TabsBar/TabsBar.vue (2)

282-288: Lowering #tabsBar z-index from 100 → 1 may break overlap ordering

z-index: 1 puts the tab bar beneath any element that still uses the default of auto but sits inside a stacking context with z-index ≥ 2. Please re-check dialogs/tooltips introduced in this PR – tabs might disappear behind them.


311-314: Hard-coding font-size: 1rem on toolbar buttons

If the rest of the toolbar scales with the root font this is fine; otherwise consider inheriting or using em to remain consistent with surrounding typography.

v0/src/simulator/spec/circuits/gates-circuitdata.json (1)

1-880: Formatting change only – no semantic impact

Indentation and ordering look good; no further comments.

v0/src/simulator/spec/testData/ripple-carry-adder.json (1)

10-24:

❓ Verification inconclusive

Input vectors shorter than declared bitWidth 16

Values like "0" are a single bit; parsers that expect fixed-width strings may mis-align. Pad to 16 chars ("0000000000000000") or document that variable-length tokens are accepted.


🏁 Script executed:

#!/bin/bash
set -eux

# 1. List all simulator source files to locate relevant modules
fd . -t f v0/src/simulator

# 2. Search for any binary parsing routines (e.g., parseBinary, parseValue)
rg -n "parseBinary" -n v0/src/simulator || true
rg -n "parseValue" -n v0/src/simulator || true

# 3. Look for where JSON testData is loaded and values are mapped
rg -n "ripple-carry-adder.json" -n v0/src/simulator -A3

# 4. Check usage of bitWidth in mapping logic
rg -n "bitWidth" -n v0/src/simulator -A5

Length of output: 96011


Verify JSON bit-string parsing against declared bitWidth
It isn’t obvious from the code how the "values" strings in ripple-carry-adder.json (e.g. "0") are interpreted versus each pin’s 16-bit declaration. If the test harness simply does a parseInt(value, 2) into a Number, then variable-length tokens pose no alignment issue; otherwise, MSBs may shift unexpectedly.

• Review input mapping in

  • v0/src/simulator/src/testbench/testbenchInput.js
  • or v0/src/simulator/src/testbench.ts
    to see if bit-strings are zero-padded/truncated to bitWidth.
    • If padding isn’t already handled, either
  • zero-pad all JSON bit-strings to the declared width, or
  • document that variable-length tokens are accepted and normalized.
v0/src/simulator/spec/subCircuit.spec.js (1)

67-74: Leaking mounted component

mount() returns a wrapper that is never unmounted, which can leave
Vue instances dangling between suites. Capture and dispose it in afterAll.

let wrapper;
beforeAll(() => {
    wrapper = mount(...);
});
afterAll(() => wrapper?.unmount());
v0/src/components/Panels/ElementsPanel/ElementsPanel.ts (1)

17-25: LGTM!

Good error handling and use of import.meta.url for module-relative asset paths.

v0/src/simulator/src/Verilog2CV.js (1)

87-132: Good addition of null safety checks

The null checks before DOM manipulations improve robustness and prevent runtime errors. This is a good defensive programming practice.

v0/src/simulator/src/canvasApi.js (2)

245-248: Good addition of coordinate rounding

Adding Math.round() when bypass is true ensures pixel-perfect positioning and prevents sub-pixel rendering issues.


444-448: Excellent jQuery removal

The native DOM implementation is cleaner and removes an unnecessary dependency while maintaining the same validation logic.

v0/src/components/Navbar/QuickButton/QuickButtonMobile.vue (1)

1-100: Multiple root elements fine, but IDs must stay unique

id="customRange1" and id="exitView" are hard-coded. If multiple instances of this component render (e.g., split-screen), duplicated IDs break accessibility and CSS selectors. Replace with :id="uniqueId" generated per-instance.

v0/src/simulator/spec/testData/decoders-plexers.json (1)

1-401: Looks good

Test-vector JSON is well-structured and consistent with other suites.

v0/src/simulator/spec/data.spec.js (1)

57-75: Stub cleans-up are missing

global.document.createRange is overwritten, yet never restored.
Add afterAll(() => delete global.document.createRange) to prevent bleed-through into unrelated tests.

v0/src/components/Navbar/QuickButton/QuickButton.vue (2)

90-92: 👍 Centralising quick-button actions looks clean

Importing the handlers from a dedicated module greatly improves reuse between desktop and mobile components.


102-318: Non-scoped styles may bleed into other components

The previous file used scoped styles; dropping scoped means every .quick-btn-save class elsewhere now inherits these rules.
If this is intentional for a global design system – fine. Otherwise re-add scoped or use CSS modules.

v0/src/simulator/src/contention.ts (1)

14-122: Nice, concise contention-tracking implementation

The class cleanly prevents duplicates, keeps O(1) operations and exposes useful helpers. No issues spotted.

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

3-3: Good refactoring for improved modularity!

The extraction of createElement and getImgUrl functions to a separate module and storing the panel ref in the layout store improves code organization and enables better cross-component communication.

Also applies to: 145-145, 151-151, 153-153, 171-172

v0/src/components/Panels/PropertiesPanel/PropertiesPanelMobile.vue (1)

163-163:

❓ Verification inconclusive

Verify the existence of layoutDialogRef in the properties panel store.

The assignment references propertiesPanelStore.layoutDialogRef, but it's unclear where this property is defined or initialized.

Run the following script to verify the layoutDialogRef property:


🏁 Script executed:

#!/bin/bash
# Description: Check for layoutDialogRef definition in the properties panel store

# Search for layoutDialogRef in store files
rg -A 3 "layoutDialogRef" --glob "**/*store*"

# Search for layoutDialogRef definition in PropertiesPanel related files
fd "PropertiesPanel" --type f --exec rg -l "layoutDialogRef" {}

Length of output: 462


🏁 Script executed:

#!/usr/bin/env bash
set -e

# 1. Locate the store definition for "propertiesPanel"
echo "Searching for defineStore('propertiesPanel') in .ts/.js files..."
STORE_FILES=$(rg -l "defineStore\\(['\"]propertiesPanel['\"]" -g "**/*.{ts,js}")

if [ -z "$STORE_FILES" ]; then
  echo "No store definition for 'propertiesPanel' found."
else
  echo "Found store file(s):"
  echo "$STORE_FILES"
  echo
  # 2. Check each store file for layoutDialogRef
  for file in $STORE_FILES; do
    echo "Inspecting $file for layoutDialogRef..."
    rg -n "layoutDialogRef" "$file" || echo "  → layoutDialogRef not defined in $file"
    echo
  done
fi

# 3. As a fallback, search for any layoutDialogRef in TS/JS/Vue files
echo "Searching entire codebase for layoutDialogRef references..."
rg -n "layoutDialogRef" -g "**/*.{ts,js,vue}" || echo "No layoutDialogRef references found anywhere."

Length of output: 240


Verify layoutDialogRef definition & add cleanup for setInterval

I wasn’t able to locate a layoutDialogRef property on the propertiesPanelStore. Please confirm that the store:

  • Defines and initializes layoutDialogRef before it’s assigned here.
  • Or update the import/usage to reference the correct reactive ref.

Additionally, the setInterval created around line 175 is never cleared. To prevent memory leaks:

  • Capture the interval ID.
  • Call clearInterval (for example in onBeforeUnmount) when the component is destroyed.
v0/src/simulator/src/data/project.ts (1)

19-25: Excellent improvements to type safety and error handling!

The changes enhance code robustness through:

  • Safe JSON parsing with null checks
  • Proper type annotations
  • Logical operators instead of bitwise for boolean operations
  • Fallback URL for development environments

Also applies to: 84-100, 113-117, 135-139, 168-172

v0/src/simulator/src/circuitElement.js (2)

336-336: Good migration from custom array methods to standard JavaScript!

Replacing .contains() with .includes() and .clean() with .filter() removes the dependency on custom Array prototype extensions, making the code more maintainable and standards-compliant.

Also applies to: 352-352, 380-383, 582-582, 738-738, 887-887


483-484: Touch support implementation looks correct.

Using mouseDownX/Y coordinates when simulationArea.touch is true appropriately handles touch interactions.

v0/src/simulator/src/data/save.js (7)

3-3: LGTM! Clean import structure.

The refactoring to use named imports instead of global variables improves modularity and makes dependencies explicit.

Also applies to: 6-7, 14-14, 20-20


72-72: Good defensive programming with optional chaining.

Using optional chaining prevents potential runtime errors if tabs is null or undefined.


125-131: Critical fix for subcircuit integrity.

Excellent addition of updateSubcircuitSet(true) with clear documentation explaining why it's needed. This ensures subcircuits remain consistent when inputs/outputs change.


196-196: Correct usage of imported canvasToSvg.

The instantiation correctly matches the imported module's API.


248-252: Proper use of renderOrder for drawing circuits.

The refactoring correctly uses the imported renderOrder array to iterate through and draw circuit elements.


319-328: Clean jQuery removal with native DOM APIs.

The conversion from jQuery to native DOM methods is correct:

  • window.getComputedStyle() properly replaces jQuery's CSS getter
  • Direct style property assignments correctly replace jQuery's .css() setter

378-378: Safe CSRF token retrieval with optional chaining.

Excellent use of optional chaining to safely retrieve the CSRF token from the meta tag.

v0/src/pages/embed.vue (2)

51-51: Well-implemented embed configuration system.

The use of computed properties with query parameters provides a clean way to customize the embed interface. Good default values are provided for each option.

Also applies to: 88-88, 95-95, 107-107, 138-138, 197-201


169-169: Correct use of named imports.

The change to named imports improves code clarity and aligns with the module's export structure.

v0/src/components/DialogBox/Themes/ApplyThemes.vue (2)

35-36: Clean refactoring of theme selection.

The simplified changeTheme function and updated checkbox logic improve code clarity.

Also applies to: 75-75


160-162: Excellent TypeScript type safety improvements.

The refactoring to use a reactive object with proper typing for custom themes improves type safety and code maintainability.

Also applies to: 170-174, 183-194

v0/src/components/Extra.vue (2)

2-2: Well-structured mobile/desktop view separation.

The conditional rendering based on showMobileView provides a clean separation between mobile and desktop interfaces. Good use of dedicated mobile components.

Also applies to: 4-4, 16-16, 26-26, 31-33, 46-46, 51-51, 56-56, 244-245


106-130: Proper touch event handling implementation.

Good approach to handle both touch and mouse events with the touch flag to distinguish between them. This enables proper mobile interaction support.

v0/src/simulator/spec/circuits/Decoders-plexers-circuitdata.json (1)

1-1337: Well-structured test circuit data

The JSON circuit data is properly formatted and follows a consistent structure throughout. The comprehensive updates to support decoder and multiplexer testing align well with the new test specifications.

v0/src/simulator/src/circuit.ts (4)

14-56: Clean separation of concerns with the new imports and wrapper function

The addition of Vue reactive state imports and the changeClockTime wrapper function properly encapsulates the clock time management while maintaining clean module boundaries.


202-204: Good addition for Vue integration

The circuitNameClicked function provides a clean interface for the Vue components to interact with the circuit selection logic.


76-100: Proper synchronization with mobile store

The integration with simulatorMobileStore ensures consistent Verilog mode state across desktop and mobile interfaces.


378-477: Excellent defensive programming with null checks

The addition of null checks throughout the Scope class methods prevents potential runtime errors and makes the code more robust. This is particularly important for arrays that might not be initialized in all scenarios.

v0/src/simulator/spec/circuits/subCircuit-circuitdata.json (2)

6-6: Verify spelling of focussedCircuit key
This property uses British spelling (focussedCircuit), but the rest of the code may refer to focusedCircuit. Confirm the codebase aligns with this key name to avoid undefined references.


1-10:

❓ Verification inconclusive

Ensure consistent ID types for orderedTabs and scopes[].id
The orderedTabs array lists scope IDs as strings, while each scope’s id is numeric. If the UI or lookup logic uses strict comparisons, this mismatch will break tab ordering.

Proposed diff to unify to numeric IDs:

 "orderedTabs": [
-    "69980799589",
-    "98622262167"
+    69980799589,
+    98622262167
 ]

To verify after merging:


🏁 Script executed:

#!/bin/bash
# Check that orderedTabs entries match scopes[].id exactly
jq -r '
  (.orderedTabs         | map(tostring) | sort) as $tabs |
  ([.scopes[].id | tostring] | sort) as $ids   |
  if $tabs != $ids then "❌ ID mismatch" else "✅ All IDs match" end
' v0/src/simulator/spec/circuits/subCircuit-circuitdata.json

Length of output: 261


Verify type consistency for orderedTabs vs. scopes[].id
The value check passes (✅ All IDs match), but orderedTabs entries are still strings while your scopes’ id fields are numbers. If any lookup or comparison uses strict equality (===), this will break tab ordering.

Please choose one of the following:

  • Convert orderedTabs entries to numbers in v0/src/simulator/spec/circuits/subCircuit-circuitdata.json
     "orderedTabs": [
    -    "69980799589",
    -    "98622262167"
    +    69980799589,
    +    98622262167
     ]
  • Or update your tab-lookup code to coerce types (e.g. use ==, String(id), or Number(tabId)) so string vs. number mismatches are handled.

Comment on lines +5 to 7
setup();
const js: JsConfig = {
devices: {
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

js is declared but never used – will fail noUnusedLocals and wastes memory

The large JsConfig object is created but not referenced, so TypeScript (or ESLint) will emit an error and the bundle ships an unused ~200-line literal.

-    setup();
-    const js: JsConfig = {
+    const js: JsConfig = {
       /* … */
-    };
+    };
+    setup(js);          // or remove the constant if it’s really unused

If setup doesn’t currently accept a config, either:

  1. Extend its signature to receive JsConfig, or
  2. Delete the constant and its import entirely.

Failing to address this will break CI in strict builds.

📝 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
setup();
const js: JsConfig = {
devices: {
const js: JsConfig = {
devices: {
/* … */
}
};
setup(js);
🤖 Prompt for AI Agents
In v0/src/simulator/src/app.ts around lines 5 to 7, the JsConfig object named
'js' is declared but never used, causing a noUnusedLocals error and unnecessary
memory usage. To fix this, either modify the setup function to accept a JsConfig
parameter and pass 'js' to it, or remove the 'js' constant declaration and any
related imports if it is not needed. This will prevent the unused variable error
and reduce bundle size.

Comment on lines +3 to +7
interface Array<T> {
clean(deleteValue: T): T[]
extend(otherArray: T[]): void
contains(value: T): boolean
}
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

⚠️ Potential issue

Declared Array extensions are not implemented → runtime will throw TypeError

You have kept the type declarations for Array.prototype.clean, extend, and contains, but the implementation file (simulator/src/arrayHelpers.js) was deleted in this PR.
Type-checking will happily compile, yet every call site will now reach vanilla Array instances that miss those members:

myArr.clean(0)   // -> TypeError: myArr.clean is not a function

Either ship a polyfill or delete the declarations.

Example quick fix – re-add a minimal, tree-shakable helper once and avoid global pollution:

- interface Array<T> {
-     clean(deleteValue: T): T[]
-     extend(otherArray: T[]): void
-     contains(value: T): boolean
- }
+ declare global {
+     interface Array<T> {
+         clean?(deleteValue: T): T[]
+         extend?(otherArray: T[]): void
+         contains?(value: T): boolean
+     }
+ }

…and provide explicit utility functions that callers import, then purge all prototype calls in follow-up PRs.

Failing to address this will break every runtime path that relied on those helpers.

🤖 Prompt for AI Agents
In v0/src/env.d.ts around lines 3 to 7, the Array interface extensions clean,
extend, and contains are declared but their implementations were removed,
causing runtime TypeErrors. To fix this, either reintroduce the implementations
of these methods as polyfills on Array.prototype or remove these declarations
entirely. A better approach is to create explicit utility functions that perform
these operations and have callers import them, then remove all prototype method
calls in a future PR to avoid global pollution.

Comment on lines +1 to +5
global.window = window;
global.jQuery = require('jquery');
global.DPR = true;
global.width = true;
global.height = true;
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

Global pollution & fragile window stub

Assigning global.window = window assumes window already exists (jsdom).
When Vitest is run with environment: "node" this throws ReferenceError: window is not defined.

- global.window = window;
+if (typeof window !== 'undefined') {
+  global.window = window;
+}
📝 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
global.window = window;
global.jQuery = require('jquery');
global.DPR = true;
global.width = true;
global.height = true;
// v0/src/simulator/spec/vitestSetup.ts
if (typeof window !== 'undefined') {
global.window = window;
}
global.jQuery = require('jquery');
global.DPR = true;
global.width = true;
global.height = true;
🤖 Prompt for AI Agents
In v0/src/simulator/spec/vitestSetup.ts at lines 1 to 5, the code assigns
global.window to window without checking if window is defined, causing a
ReferenceError in node environment. Fix this by adding a conditional check to
ensure window exists before assigning it to global.window, preventing errors
when running Vitest with environment set to "node".

Comment on lines +2 to +9
global.jQuery = require('jquery');
global.DPR = true;
global.width = true;
global.height = true;

window.Jquery = require('jquery');
window.$ = require('jquery');
window.restrictedElements = [];
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

Duplicate / miss-spelled jQuery bindings

require('jquery') is invoked three times and bound to window.Jquery (note the capital “J”) in addition to window.jQuery/window.$.
This increases bundle size in CJS mode and the typo introduces a fourth alias that will never be referenced.

-global.jQuery = require('jquery');
-window.Jquery = require('jquery');
-window.$ = require('jquery');
+import jQuery from 'jquery';
+global.jQuery = jQuery;
+global.$ = jQuery;
+if (typeof window !== 'undefined') {
+  window.jQuery = jQuery;
+  window.$ = jQuery;
+}
📝 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
global.jQuery = require('jquery');
global.DPR = true;
global.width = true;
global.height = true;
window.Jquery = require('jquery');
window.$ = require('jquery');
window.restrictedElements = [];
import jQuery from 'jquery';
global.jQuery = jQuery;
global.$ = jQuery;
if (typeof window !== 'undefined') {
window.jQuery = jQuery;
window.$ = jQuery;
}
global.DPR = true;
global.width = true;
global.height = true;
window.restrictedElements = [];
🤖 Prompt for AI Agents
In v0/src/simulator/spec/vitestSetup.ts around lines 2 to 9, the code requires
'jquery' three times and assigns it to window.Jquery with a capital "J", which
is a typo and unused. To fix this, require 'jquery' only once, assign it to
window.jQuery and window.$ with the correct casing, and remove the redundant
window.Jquery assignment to avoid increasing bundle size and eliminate the
misspelled alias.

Comment on lines +99 to +104
onMounted(() => {
window.addEventListener('resize', checkShowSidebar)
})
function checkShowSidebar() {
simulatorMobileStore.showMobileView = window.innerWidth < simulatorMobileStore.minWidthToShowMobile ? true : false
}
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

Memory leak: resize listener never removed

window.addEventListener('resize', checkShowSidebar) is registered but not cleaned up.
On hot-reload or when the component is destroyed in tests, multiple listeners accumulate.

 onMounted(() => {
   window.addEventListener('resize', checkShowSidebar)
+  checkShowSidebar() // initialise once
 })
+onUnmounted(() => {
+  window.removeEventListener('resize', checkShowSidebar)
+})
📝 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
onMounted(() => {
window.addEventListener('resize', checkShowSidebar)
})
function checkShowSidebar() {
simulatorMobileStore.showMobileView = window.innerWidth < simulatorMobileStore.minWidthToShowMobile ? true : false
}
onMounted(() => {
window.addEventListener('resize', checkShowSidebar)
checkShowSidebar() // initialise once
})
onUnmounted(() => {
window.removeEventListener('resize', checkShowSidebar)
})
function checkShowSidebar() {
simulatorMobileStore.showMobileView = window.innerWidth < simulatorMobileStore.minWidthToShowMobile ? true : false
}
🤖 Prompt for AI Agents
In v0/src/pages/simulatorHandler.vue around lines 99 to 104, the resize event
listener added in onMounted is never removed, causing a memory leak. Fix this by
adding a corresponding window.removeEventListener call inside an onUnmounted
lifecycle hook to clean up the listener when the component is destroyed.

Comment on lines +26 to +32
vi.mock('codemirror', async (importOriginal) => {
const actual = await importOriginal();
return {
...actual,
fromTextArea: vi.fn(() => ({ setValue: () => {} })),
};
});
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

Use the recommended vi.importActual API for partial mocks

vi.mock('codemirror', async (importOriginal) => { … }) relies on an undocumented callback arg.
Safer/forward-compatible pattern:

-vi.mock('codemirror', async (importOriginal) => {
-    const actual = await importOriginal();
+vi.mock('codemirror', async () => {
+    const actual = await vi.importActual<any>('codemirror');

This avoids breaking when Vitest drops the extra parameter.

📝 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
vi.mock('codemirror', async (importOriginal) => {
const actual = await importOriginal();
return {
...actual,
fromTextArea: vi.fn(() => ({ setValue: () => {} })),
};
});
vi.mock('codemirror', async () => {
const actual = await vi.importActual<any>('codemirror');
return {
...actual,
fromTextArea: vi.fn(() => ({ setValue: () => {} })),
};
});
🤖 Prompt for AI Agents
In v0/src/simulator/spec/data.spec.js around lines 26 to 32, the mock for
'codemirror' uses an undocumented callback argument for partial mocking. Replace
the current async callback with the recommended pattern using vi.importActual to
import the actual module, then return the partial mock by spreading the actual
module and overriding fromTextArea. This ensures compatibility with future
Vitest versions by avoiding reliance on undocumented parameters.

Comment on lines 98 to 103
globalScope.Input.forEach((input) => {
input.state = input.state === 1 ? 0 : 1
expect(() => scheduleBackup()).not.toThrow()
})
})
input.state = input.state === 1 ? 0 : 1;
expect(() => scheduleBackup()).not.toThrow();
});
});

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

Guard against missing globalScope.Input

If setup() failed to populate globalScope.Input, this loop throws.
Add a nullish check:

-if (globalScope.Input)
-  globalScope.Input.forEach(…)
+globalScope.Input?.forEach(…)

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

🤖 Prompt for AI Agents
In v0/src/simulator/spec/data.spec.js around lines 98 to 103, the code assumes
globalScope.Input is always defined, but if setup() fails to populate it, the
forEach loop will throw an error. Add a nullish check before the loop to ensure
globalScope.Input exists and is iterable, such as using an if statement or
optional chaining, to guard against this scenario.

Comment on lines +124 to +134
const combinedIO = computed(() => {
const group = testData.value.groups[0];
return group.inputs.concat(group.outputs);
});

const currentGroup = computed(() => testBenchStore.testbenchData.currentGroup);
const currentCase = computed(() => testBenchStore.testbenchData.currentCase);

const inputs = computed(() => testData.value.groups[currentGroup.value].inputs);
const outputs = computed(() => testData.value.groups[currentGroup.value].outputs);
</script>
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

Computed chains can crash when testData is undefined

testData.value.groups[0] and subsequent deep accesses will throw on an empty/undefined testData.
Defensive version:

-const combinedIO = computed(() => {
-  const group = testData.value.groups[0];
-  return group.inputs.concat(group.outputs);
-});
+const combinedIO = computed(() => {
+  const group = testData.value?.groups?.[0];
+  return group ? [...group.inputs, ...group.outputs] : [];
+});

Apply similar optional chaining to inputs and outputs.

📝 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 combinedIO = computed(() => {
const group = testData.value.groups[0];
return group.inputs.concat(group.outputs);
});
const currentGroup = computed(() => testBenchStore.testbenchData.currentGroup);
const currentCase = computed(() => testBenchStore.testbenchData.currentCase);
const inputs = computed(() => testData.value.groups[currentGroup.value].inputs);
const outputs = computed(() => testData.value.groups[currentGroup.value].outputs);
</script>
const combinedIO = computed(() => {
const group = testData.value?.groups?.[0];
return group ? [...group.inputs, ...group.outputs] : [];
});
const currentGroup = computed(() => testBenchStore.testbenchData.currentGroup);
const currentCase = computed(() => testBenchStore.testbenchData.currentCase);
const inputs = computed(() => testData.value.groups[currentGroup.value].inputs);
const outputs = computed(() => testData.value.groups[currentGroup.value].outputs);
</script>
🤖 Prompt for AI Agents
In v0/src/components/Panels/TestBenchPanel/TestBenchPanel.vue around lines 124
to 134, the computed properties access nested properties of testData without
checking if testData or its groups array is defined, which can cause runtime
errors. Update the computed properties combinedIO, inputs, and outputs to use
optional chaining and nullish coalescing to safely handle cases where testData
or groups might be undefined or empty, returning empty arrays or default values
instead of throwing errors.

Comment on lines +52 to +74
const dragElement = (groupType: string, element: any, index: number) => {
element.subcircuitMetadata.showInSubcircuit = true
element.newElement = true
simulationArea.lastSelected = element

// Remove the element from subCircuitElementList
SimulatorState.subCircuitElementList.forEach((typeGroup) => {
typeGroup.elements = typeGroup.elements.filter(
(_, elementIndex) => {
if(typeGroup.type === groupType && index === elementIndex)
return false

return true;
}
)
})

// Remove the type group if its elements array is empty
SimulatorState.subCircuitElementList =
SimulatorState.subCircuitElementList.filter(
(typeGroup) => typeGroup.elements.length > 0
)
}
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

Inefficient in-place mutation & double iteration

forEach + filter causes two passes; also reassigning the full list mid-mutation can confuse reactivity.

const dragElement = (groupType, element, index) => {
  element.subcircuitMetadata.showInSubcircuit = true;
  element.newElement = true;
  simulationArea.lastSelected = element;

- // current two-pass removal
- SimulatorState.subCircuitElementList.forEach((typeGroup) => {
-   typeGroup.elements = typeGroup.elements.filter((_, i) =>
-     !(typeGroup.type === groupType && i === index));
- });
- SimulatorState.subCircuitElementList =
-   SimulatorState.subCircuitElementList.filter(g => g.elements.length);
+
+ const grp = SimulatorState.subCircuitElementList.find(g => g.type === groupType);
+ if (grp) {
+   grp.elements.splice(index, 1);          // O(1) removal, keeps reactivity
+   if (!grp.elements.length) {
+     SimulatorState.subCircuitElementList =
+       SimulatorState.subCircuitElementList.filter(g => g !== grp);
+   }
+ }
}
📝 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 dragElement = (groupType: string, element: any, index: number) => {
element.subcircuitMetadata.showInSubcircuit = true
element.newElement = true
simulationArea.lastSelected = element
// Remove the element from subCircuitElementList
SimulatorState.subCircuitElementList.forEach((typeGroup) => {
typeGroup.elements = typeGroup.elements.filter(
(_, elementIndex) => {
if(typeGroup.type === groupType && index === elementIndex)
return false
return true;
}
)
})
// Remove the type group if its elements array is empty
SimulatorState.subCircuitElementList =
SimulatorState.subCircuitElementList.filter(
(typeGroup) => typeGroup.elements.length > 0
)
}
const dragElement = (groupType: string, element: any, index: number) => {
element.subcircuitMetadata.showInSubcircuit = true;
element.newElement = true;
simulationArea.lastSelected = element;
const grp = SimulatorState.subCircuitElementList.find(
g => g.type === groupType
);
if (grp) {
grp.elements.splice(index, 1); // O(1) removal, keeps reactivity
if (!grp.elements.length) {
SimulatorState.subCircuitElementList =
SimulatorState.subCircuitElementList.filter(g => g !== grp);
}
}
}
🤖 Prompt for AI Agents
In v0/src/components/Panels/LayoutElementsPanel/LayoutElementsPanel.vue between
lines 52 and 74, the current code uses forEach combined with filter to remove an
element, causing two iterations and potential reactivity issues due to in-place
mutation and reassignment. Refactor by using a single filter operation on
SimulatorState.subCircuitElementList to remove the element directly without
mutating in place, and avoid reassigning the entire list mid-mutation to
maintain reactivity clarity.

Comment on lines +68 to 80
import { onMounted, onUpdated, ref } from '@vue/runtime-core'
const SimulatorState = useState()
const projectList = ref({})
const targetVersion = ref('')
let projectName = ''
const projectList = ref<{ [key: string]: string }>({})
const selectedProjectId = ref<string | null>(null)

onMounted(() => {
SimulatorState.dialogBox.open_project_dialog = false
})

onUpdated(() => {
var data = localStorage.getItem('projectList')
projectList.value = JSON.parse(localStorage.getItem('projectList')) || {}
const data = localStorage.getItem('projectList')
projectList.value = data ? JSON.parse(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

Avoid reading localStorage on every component update

onUpdated fires after any reactive change, causing repeated synchronous localStorage reads and JSON parses.
Move the fetch to onMounted and update projectList only when the dialog actually opens (or via a dedicated refresh method).
This prevents jank on highly-interactive pages.

🤖 Prompt for AI Agents
In v0/src/components/DialogBox/OpenOffline.vue around lines 68 to 80, avoid
reading localStorage inside the onUpdated hook because it triggers on every
reactive update causing performance issues. Instead, move the localStorage fetch
and JSON parse logic into the onMounted hook and create a dedicated method to
refresh projectList only when the dialog opens or when explicitly needed.
Replace the onUpdated hook with this approach to prevent unnecessary repeated
synchronous reads.

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.

Review continued from previous batch...

Comment on lines 91 to 99
function openProjectOffline() {
SimulatorState.dialogBox.open_project_dialog = false
let ele = $('input[name=projectId]:checked')
if (!ele.val()) return
const projectData = JSON.parse(localStorage.getItem(ele.val()))
const simulatorVersion = projectData.simulatorVersion
projectName = projectData.name

// Handle version mismatch logic
if (!simulatorVersion) {
// If no version, proceed directly
targetVersion.value = "Legacy"
SimulatorState.dialogBox.version_mismatch_dialog = true
} else if (simulatorVersion && simulatorVersion != "v0") {
// Set the targetVersion and show the version mismatch dialog
targetVersion.value = simulatorVersion
SimulatorState.dialogBox.version_mismatch_dialog = true
} else {
// For other cases, proceed normally
load(projectData)
window.projectId = ele.val()
}
}

function confirmOpenProject() {
SimulatorState.dialogBox.version_mismatch_dialog = false
// Redirect to the appropriate version after confirmation
if(targetVersion.value == "Legacy"){
window.location.href = `/simulator/edit/${projectName}`
}else{
window.location.href = `/simulatorvue/edit/${projectName}?simver=${targetVersion.value}`
if (!selectedProjectId.value) return
const projectData = localStorage.getItem(selectedProjectId.value)
if (projectData) {
load(JSON.parse(projectData))
window.projectId = selectedProjectId.value
}

}

function cancelOpenProject() {
SimulatorState.dialogBox.version_mismatch_dialog = false
}
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

Wrap JSON parsing in a safe try/catch

A corrupted entry in localStorage will currently throw and break the whole UI.

- const projectData = localStorage.getItem(selectedProjectId.value)
- if (projectData) {
-     load(JSON.parse(projectData))
+ const raw = localStorage.getItem(selectedProjectId.value)
+ if (!raw) return
+ try {
+     load(JSON.parse(raw))
+ } catch (e) {
+     console.error('Invalid project data', e)
+     return
+ }

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

🤖 Prompt for AI Agents
In v0/src/components/DialogBox/OpenOffline.vue around lines 91 to 99, the
JSON.parse call on localStorage data can throw an error if the data is
corrupted, breaking the UI. Wrap the JSON.parse call inside a try/catch block to
safely handle parsing errors. In the catch block, handle the error gracefully,
such as logging it or ignoring the corrupted data, to prevent the UI from
breaking.

Comment on lines +1 to +3
<template v-else>
<UserMenu :style="{width: 0}" class="userMenuHamBurger" v-bind="userMenuState" />
<v-card id="toolbar" color="transparent" variant="outlined">
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

<template v-else> is illegal without a preceding v-if

Vue requires v-else to be immediately adjacent to a sibling with v-if.
Drop the modifier or wrap this template inside a conditional wrapper component.
Compilation will fail otherwise.

🤖 Prompt for AI Agents
In v0/src/components/Navbar/Hamburger/Hamburger2.vue at lines 1 to 3, the
<template> tag uses v-else without a preceding sibling element with v-if, which
is invalid in Vue. To fix this, either remove the v-else directive or ensure it
directly follows a sibling element with v-if. Alternatively, wrap this template
block inside a parent element that conditionally renders based on the intended
condition.

@@ -1,5 +1,5 @@
<template>
<div class="quick-btn" @ondragover="dragover">
<div class="quick-btn" id='quick-btn-id' @ondragover="dragover">
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

Use @dragover, not @ondragover

Vue listens to DOM events via @event; the on* prefix registers a prop, not a handler.

- <div class="quick-btn" id='quick-btn-id' @ondragover="dragover">
+ <div class="quick-btn" id="quick-btn-id" @dragover="dragover">
🤖 Prompt for AI Agents
In v0/src/components/Navbar/QuickButton/QuickButton.vue at line 2, the event
listener is incorrectly using @ondragover instead of @dragover. Change the
attribute from @ondragover="dragover" to @dragover="dragover" to correctly
register the dragover event handler in Vue.

Comment on lines +6 to +12
interface PlotArea {
resize: () => void
[key: string]: () => void
}

export const plotArea: PlotArea = _plotArea

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

Type definition mismatch – cycleUnit missing in PlotArea interface

handleUnitsChange() assigns plotArea.cycleUnit, but cycleUnit is not declared in the PlotArea interface and the index signature only allows functions. This will fail TypeScript compilation.

 interface PlotArea {
   resize: () => void
-  [key: string]: () => void
+  /* arbitrary callable actions  */
+  [key: string]: (...args: any[]) => any
+  /** unit (in cycles) used by the plot-area grid */
+  cycleUnit?: number
 }

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

🤖 Prompt for AI Agents
In v0/src/components/Panels/TimingDiagramPanel/TimingDiagramPanel.ts between
lines 6 and 12, the PlotArea interface lacks a declaration for the cycleUnit
property, which is assigned in handleUnitsChange(). To fix this, explicitly add
cycleUnit with the correct type to the PlotArea interface, and adjust or remove
the index signature if necessary to allow non-function properties like
cycleUnit.

Comment on lines +20 to +23
export function zoomToFit(): void {
globalScope.centerFocus(false)
}
export function undoit(): void {
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

globalScope is used without a declaration

globalScope.centerFocus(false) will raise “cannot find name ‘globalScope’” unless an ambient declaration exists.
Add an explicit import or declare it in a globals.d.ts to keep the TS compiler happy.

// e.g. globals.d.ts
declare const globalScope: { centerFocus: (animate?: boolean) => void }
🤖 Prompt for AI Agents
In v0/src/components/Navbar/QuickButton/QuickButton.ts around lines 20 to 23,
the variable globalScope is used without being declared or imported, causing a
TypeScript error. To fix this, either add an explicit import statement for
globalScope if it is exported from another module, or declare it globally by
creating a globals.d.ts file with a declaration like "declare const globalScope:
{ centerFocus: (animate?: boolean) => void }" to inform the TypeScript compiler
about its existence and type.

booleanInputVariables.sort();
if (inputList.length > 0 && outputList.length > 0 && booleanInputVariables.length == 0) {
createBooleanPrompt(inputList, outputList, null, scope);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify createBooleanPrompt function exists.

The function createBooleanPrompt is called but not defined in this file.

Also applies to: 48-48


🏁 Script executed:

#!/bin/bash
# Search for createBooleanPrompt function definition
ast-grep --pattern 'function createBooleanPrompt($$$) { $$$ }'
ast-grep --pattern 'const createBooleanPrompt = $$$'
ast-grep --pattern 'export $$ function createBooleanPrompt'

Length of output: 181


Let’s broaden the search across the repo to be sure:


🏁 Script executed:

#!/bin/bash
# Find any references or definitions of createBooleanPrompt
rg -n "createBooleanPrompt"

Length of output: 1911


🏁 Script executed:

#!/bin/bash
# Display the top of the file to check imports
sed -n '1,50p' v0/src/simulator/src/combinationalAnalysis.js

Length of output: 2319


Missing createBooleanPrompt definition or import

The calls to createBooleanPrompt (at lines 43 and 48) in v0/src/simulator/src/combinationalAnalysis.js have no matching definition or import in this file. That helper is only defined (but not exported) in v0/src/components/DialogBox/CombinationalAnalysis.vue.

• Extract createBooleanPrompt into a shared module (e.g. src/utils/combinationalAnalysisUtils.js) and export it.
• In v0/src/simulator/src/combinationalAnalysis.js, add at the top:

import { createBooleanPrompt } from '#/utils/combinationalAnalysisUtils';

• Update CombinationalAnalysis.vue to import the shared function instead of defining it inline.

🤖 Prompt for AI Agents
In v0/src/simulator/src/combinationalAnalysis.js around lines 43 to 48, the
function createBooleanPrompt is called but neither defined nor imported, causing
unresolved reference errors. To fix this, extract the createBooleanPrompt
function from v0/src/components/DialogBox/CombinationalAnalysis.vue into a new
shared module, for example src/utils/combinationalAnalysisUtils.js, and export
it from there. Then, add an import statement at the top of
combinationalAnalysis.js to import createBooleanPrompt from the new shared
module. Finally, update CombinationalAnalysis.vue to import createBooleanPrompt
from the shared module instead of defining it inline.

Comment on lines +230 to +234
function receivedText(e: ProgressEvent<FileReader>) {
let lines = []
if(typeof e.target?.result === 'string') {
lines = JSON.parse(e.target.result)
}
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 error handling for JSON parsing.

While the type checking is good, JSON parsing can still throw errors.

 function receivedText(e: ProgressEvent<FileReader>) {
     let lines = []
-    if(typeof e.target?.result === 'string') {
-        lines = JSON.parse(e.target.result)
-    }
+    if(typeof e.target?.result === 'string') {
+        try {
+            lines = JSON.parse(e.target.result)
+        } catch (error) {
+            confirmSingleOption('Invalid theme file format!');
+            return;
+        }
+    }
📝 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
function receivedText(e: ProgressEvent<FileReader>) {
let lines = []
if(typeof e.target?.result === 'string') {
lines = JSON.parse(e.target.result)
}
function receivedText(e: ProgressEvent<FileReader>) {
let lines = []
if (typeof e.target?.result === 'string') {
try {
lines = JSON.parse(e.target.result)
} catch (error) {
confirmSingleOption('Invalid theme file format!');
return;
}
}
🤖 Prompt for AI Agents
In v0/src/components/DialogBox/Themes/ApplyThemes.vue around lines 230 to 234,
the JSON.parse call can throw an error if the input is malformed. Wrap the
JSON.parse call in a try-catch block to handle any parsing errors gracefully. In
the catch block, log or handle the error appropriately to avoid unhandled
exceptions and improve robustness.

Comment on lines +192 to +202
@mousedown="(e: React.MouseEvent) => {
if(simulationArea.shiftDown == false) {
simulationArea.shiftDown = true;
selectMultiple = true;
}
else {
simulationArea.shiftDown = false;
selectMultiple = false;
e.preventDefault();
}
}"
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 TypeScript type and simplify event handler.

The event type should be MouseEvent, not React.MouseEvent. Also, consider extracting the complex logic to a method.

-@mousedown="(e: React.MouseEvent) => {
-  if(simulationArea.shiftDown == false) {
-      simulationArea.shiftDown = true;
-      selectMultiple = true;
-  }
-  else {
-      simulationArea.shiftDown = false;
-      selectMultiple = false;
-      e.preventDefault();
-  }
-}"
+@mousedown="toggleMultiSelect"

// In the script section:
+const toggleMultiSelect = (e: MouseEvent) => {
+    simulationArea.shiftDown = !simulationArea.shiftDown;
+    selectMultiple.value = simulationArea.shiftDown;
+    if (!simulationArea.shiftDown) {
+        e.preventDefault();
+    }
+}
🤖 Prompt for AI Agents
In v0/src/components/Extra.vue around lines 192 to 202, the event handler uses
the incorrect type React.MouseEvent instead of the standard MouseEvent. Change
the event parameter type to MouseEvent. Additionally, move the logic inside the
mousedown handler into a separate method in the component to simplify the
template and improve readability, then call that method from the template.

scale: number;
stack: any[];
layout: { width: number; height: number; title_x: number; title_y: number; titleEnabled: boolean; };
tunnelList?: {};
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 generic object type with proper interface

The static analysis correctly identifies that {} is too generic. Define a proper type for the tunnel list.

-    tunnelList?: {};
+    tunnelList?: Record<string, any>;

If you know the structure of tunnel objects, consider creating a more specific interface:

interface Tunnel {
    // Define tunnel properties here
}
tunnelList?: Record<string, Tunnel>;
🧰 Tools
🪛 Biome (1.9.4)

[error] 309-309: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)

🤖 Prompt for AI Agents
In v0/src/simulator/src/circuit.ts at line 309, the tunnelList property is
currently typed as a generic empty object {}, which is too broad. Define a
specific interface representing the structure of a tunnel object, then update
tunnelList to use a Record type mapping string keys to Tunnel objects. This will
provide proper typing and improve code clarity.

Comment on lines +128 to 140
export function getDependenciesList(scopeId: string | number) {
let scope = scopeList[scopeId]
if (scope == undefined) scope = scopeList[globalScope.id]

let dependencies = ''
for (id in scopeList) {
if (id != scope.id && scopeList[id].checkDependency(scope.id)) {
for (let id in scopeList) {
let formattedId;
if (typeof scopeId === 'number')
formattedId = scopeId;
else
formattedId = parseInt(scopeId);
if (id != scope.id && scopeList[id].checkDependency(formattedId)) {
if (dependencies === '') {
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 incorrect variable reference in type checking

There's a bug in the type checking logic - you're checking the type of scopeId instead of id in the loop.

-        if (typeof scopeId === 'number')
-            formattedId = scopeId;
+        if (typeof id === 'number')
+            formattedId = parseInt(id);
         else
-            formattedId = parseInt(scopeId);
+            formattedId = id;

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

🤖 Prompt for AI Agents
In v0/src/simulator/src/circuit.ts around lines 128 to 140, the type checking
inside the loop incorrectly checks the type of scopeId instead of id. Update the
type check to use the variable id to correctly determine its type before parsing
or assigning it. This will fix the logic that formats the id for dependency
checking.

@@ -60,93 +60,42 @@
</v-card-actions>
</v-card>
</v-dialog>
Copy link
Contributor

Choose a reason for hiding this comment

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

Version mismatch dialog got removed during v0-src sync

@@ -60,93 +60,44 @@
</v-card-actions>
</v-card>
</v-dialog>
Copy link
Contributor

Choose a reason for hiding this comment

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

Version mismatch dialog got removed during v1-src sync

Copy link
Contributor

@aryanndwi123 aryanndwi123 left a comment

Choose a reason for hiding this comment

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

File names like Hamburger and NavbarLink were renamed to Hamburger2 and NavbarLink2. Compare with the original files, resolve conflicts, and merge into one file.

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.

Week 2- Sync src to v0/src and v1/src
2 participants