Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JS to TS simulator/src/hotkey_binder/model/actions.ts #423

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

Conversation

ThatDeparted2061
Copy link
Contributor

@ThatDeparted2061 ThatDeparted2061 commented Jan 22, 2025

Fixes #414
Js to TS
@niladrix719 @JoshVarga @Arnabdaz @devartstar

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced enhanced key management for user interactions in the simulation.
    • Added functionality for custom key bindings with local storage support.
    • Implemented user feedback for key conflicts to improve user experience.
    • Expanded simulation area manipulation based on user input.
    • Added access to hotkey settings and documentation resources.
  • Refactor

    • Enhanced type safety for hotkey-related functions.
    • Improved code clarity with TypeScript annotations.
    • Added explicit return types to functions.
    • Standardized equality checks and error handling.
  • Style

    • Updated method signatures with more precise type definitions.

Copy link
Contributor

coderabbitai bot commented Jan 22, 2025

Walkthrough

The pull request introduces extensive modifications to the actions.ts file, enhancing key management and user interaction within a simulation environment. It adds several new functions and utility methods for managing user-defined and default key bindings, incorporating local storage for key configurations. The changes also include functions for checking key discrepancies, updating user keys, and providing user feedback to prevent conflicts. Additionally, methods for manipulating the simulation area based on user input are included, improving the overall functionality and type safety of the code.

Changes

File Change Summary
src/simulator/src/hotkey_binder/model/actions.ts - Added methods: addKeys, checkUpdate, setUserKeys, setDefault, warnOverride, elementDirection, labelDirection, insertLabel, moveElement, openHotkey, openDocumentation
- Updated method signature: updateSystem
- Improved local storage management and user feedback

Assessment against linked issues

Objective Addressed Explanation
Typescript integration in /simulator/src files (#414)

Poem

🐰 Hop, hop, through the code we go,
Types now dance in a safer flow!
Functions added, keys in line,
A rabbit's joy in design divine!
With every leap, our code does shine! 🌟

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

netlify bot commented Jan 22, 2025

Deploy Preview for circuitverse ready!

Name Link
🔨 Latest commit 55f3d80
🔍 Latest deploy log https://app.netlify.com/sites/circuitverse/deploys/67a072e1e0929700082fc20d
😎 Deploy Preview https://deploy-preview-423--circuitverse.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (4)
src/simulator/src/hotkey_binder/model/actions.ts (4)

15-17: Consider adding validation for key format in KeyMap.

The KeyMap interface allows any string value, which could lead to invalid key combinations being stored. Consider adding a more specific type or validation for the key format.

interface KeyMap {
    [key: string]: `${string}${' + ' | ''}${string}`  // Ensures format like "Ctrl + A" or "Meta"
}

19-28: Consider splitting SimulationArea interface.

The SimulationArea interface mixes positional properties with behavioral ones. Consider splitting it into smaller, focused interfaces for better maintainability.

interface Position {
    x: number
    y: number
}

interface LabelProperties {
    labelDirection: string
    labelDirectionFixed?: boolean
}

interface SimulationObject extends Position, LabelProperties {
    newDirection: (direction: string) => void
    helplink?: string
}

interface SimulationArea {
    lastSelected?: SimulationObject
}

Line range hint 194-213: Consider using an enum for DirectionType.

The direction handling could be more maintainable using an enum with associated values.

enum Direction {
    UP = 'up',
    DOWN = 'down',
    LEFT = 'left',
    RIGHT = 'right'
}

interface DirectionOffset {
    x: number
    y: number
}

const DIRECTION_OFFSETS: Record<Direction, DirectionOffset> = {
    [Direction.UP]: { x: 0, y: -10 },
    [Direction.DOWN]: { x: 0, y: 10 },
    [Direction.LEFT]: { x: -10, y: 0 },
    [Direction.RIGHT]: { x: 10, y: 0 }
}

export const moveElement = (direct: Direction) => (): void => {
    if (simulationArea.lastSelected) {
        const offset = DIRECTION_OFFSETS[direct]
        simulationArea.lastSelected.x += offset.x
        simulationArea.lastSelected.y += offset.y
        updateSystem()
    }
}

221-230: Add type guard for simulationArea.lastSelected.

The null checks could be more TypeScript-idiomatic using type guards.

export const openDocumentation = (): void => {
    const selected = simulationArea.lastSelected
    const defaultDocs = 'https://docs.circuitverse.org/'
    
    window.open(
        selected?.helplink ?? defaultDocs,
        '_blank'
    )
}
📜 Review details

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

📥 Commits

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

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

Line range hint 1-236: Overall good TypeScript conversion with room for improvement.

The conversion to TypeScript adds basic type safety and improves code maintainability. However, consider:

  1. Using more TypeScript features (enums, type guards, utility types)
  2. Adding proper type declarations for external functions
  3. Improving error handling for DOM and localStorage operations
  4. Breaking down complex interfaces into smaller, focused ones

The changes are a good foundation for further TypeScript enhancements.


232-236: Consider adding return types for imported functions.

The updateSystem function calls imported functions without clear type information. Consider adding type declarations for these imported functions.

src/simulator/src/hotkey_binder/model/actions.ts Outdated Show resolved Hide resolved
src/simulator/src/hotkey_binder/model/actions.ts Outdated Show resolved Hide resolved
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: 0

♻️ Duplicate comments (1)
src/simulator/src/hotkey_binder/model/actions.ts (1)

56-56: ⚠️ Potential issue

Use localStorage methods correctly ().
Checking localStorage.userKeys is invalid. Local storage only supports the standard getItem(), setItem(), and removeItem() methods. Replace:

-if (localStorage.userKeys) localStorage.removeItem('userKeys')
+if (localStorage.getItem('userKeys')) localStorage.removeItem('userKeys')

Also applies to: 131-131

🧹 Nitpick comments (3)
src/simulator/src/hotkey_binder/model/actions.ts (3)

49-49: Handle potential JSON parsing errors.
Directly using JSON.parse(...) on localStorage data can throw a runtime error if the stored string is not valid JSON. Consider adding a try/catch block or a guard to prevent the entire function from breaking if the data is malformed.

Also applies to: 57-57, 75-75


190-196: Avoid triple function nesting for clarity.
Returning a function that returns another function may complicate readability and type inference. Instead, consider a single function or partial application patterns that are clearer to maintain. For example:

-export const elementDirection = (direct: string) => (): void => {
+export const elementDirection = (direct: string): (() => void) => {
   return () => {
       // ...
   }
}

Also applies to: 198-207, 239-247


109-122: Consider unifying repeated DOM traversal logic.
Both getUserKeysFromUI and warnOverride traverse document.getElementById('preference') children. Extracting this repetitive logic into a helper function helps DRY up the code and improves readability.

Also applies to: 153-175

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3142e3a and 2f9e1dd.

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

48-49: Question the removal of default keys when fetching user keys.
Currently, the getUserKeys function removes the defaultKeys from localStorage every time user keys are fetched. If this is unintended, consider removing the removeItem('defaultKeys') call or clarifying why default keys must be cleared whenever user keys are requested.


252-259: Include a default or exhaustive check in the switch statement.
Because direct is a union type, ensure all cases are handled or use a default: clause for unforeseen values. Without it, TypeScript might not warn if new directions are added in the future but not handled.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (6)
src/simulator/src/hotkey_binder/model/actions.ts (6)

39-42: Reconsider removing all shortcuts on every key load
Removing all shortcuts (line 39) obliterates any other registered shortcuts, even those unrelated to userKeys or defaultKeys. Confirm if this blanket removal is intentional or if selective cleanup is preferable.


98-103: Watch out for concurrency with localStorage
Multiple browser tabs or windows could overwrite each other’s stored keys. If concurrent usage is expected, consider a more robust synchronization approach (e.g., broadcasting updates or using a storage event listener).


109-120: Ensure DOM structure consistency
The logic here assumes a specific DOM structure: child?.children[1]?.children[...]. If this structure changes, the code will break. Consider more defensive or flexible lookups (e.g. querySelector).


153-168: Clarify override flow
The code warns about conflicts but leaves the actual override handling to user intervention. Consider implementing a follow-up step to confirm/deny override, preventing user confusion.


218-224: Simplify nested arrow functions
Using export const elementDirection = (direct: string) => (): void => { ... } can be less readable. A single-level function returning void might suffice unless you need a factory of factories.

-export const elementDirection = (direct: string) => (): void => {
+export const elementDirection = (direct: string): void => {

306-308: Add fallback or checks for blocked popups
When opening documentation in a new tab/window, user browser settings or popup blockers may prevent it. Consider providing a fallback or a user message if the window fails to open.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2f9e1dd and 3a71291.

📒 Files selected for processing (1)
  • src/simulator/src/hotkey_binder/model/actions.ts (1 hunks)
🔇 Additional comments (4)
src/simulator/src/hotkey_binder/model/actions.ts (4)

48-49: Validate the unconditional removal of defaultKeys
Unconditionally removing defaultKeys might cause scenarios where a user cannot revert to default keys if they switch prematurely. Consider preserving the default keys for a more flexible workflow.


65-66: Evaluate the implication of stripping spaces
Joining all segments into a single string (line 65) can lead to collisions if multiple shortcuts differ only by spacing. Ensure this is intentional or consider a more robust normalization approach.


298-300: Handle potential missing elements
Calling document.getElementById('customShortcut')?.click() assumes the element is present. Confirm that a missing element is not a possible scenario or handle it gracefully.


313-317: Ensure update steps are robust
updateSystem calls broad updates but lacks error handling. If any step fails (e.g., scheduleUpdate or updateCanvasSet), the system state might remain partially updated.

src/simulator/src/hotkey_binder/model/actions.ts Outdated Show resolved Hide resolved
@ThatDeparted2061
Copy link
Contributor Author

merge this PR only after #425
for this file's interfaces are in #425's PR

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

🧹 Nitpick comments (1)
src/simulator/src/hotkey_binder/model/actions.ts (1)

224-230: Clarify higher-order function signature.

The function returns another function which returns yet another function of type (): void. This can be confusing to maintain. Consider whether a single function or a simpler function type would be more readable.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3a71291 and 5a6edb1.

📒 Files selected for processing (1)
  • src/simulator/src/hotkey_binder/model/actions.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/simulator/src/hotkey_binder/model/actions.ts

[error] 69-69: Do not access Object.prototype method 'hasOwnProperty' from target object.

It's recommended using Object.hasOwn() instead of using Object.hasOwnProperty().
See MDN web docs for more details.

(lint/suspicious/noPrototypeBuiltins)


[error] 77-77: Do not access Object.prototype method 'hasOwnProperty' from target object.

It's recommended using Object.hasOwn() instead of using Object.hasOwnProperty().
See MDN web docs for more details.

(lint/suspicious/noPrototypeBuiltins)

🔇 Additional comments (4)
src/simulator/src/hotkey_binder/model/actions.ts (4)

34-37: Verify removal of defaultKeys when retrieving userKeys.

Currently, getUserKeys() removes defaultKeys from localStorage unconditionally. Double-check whether this is intentional. If you need to preserve default keys for future reference or fallback, consider removing this call or making it conditional.

Would you like a script to search other parts of the codebase to confirm no features rely on persisting defaultKeys during user key retrieval?


43-44: Use getItem instead of direct property access on localStorage.

This is consistent with a past review comment. Accessing localStorage.userKeys is non-standard and may fail. Prefer:

-if (localStorage.userKeys) localStorage.removeItem('userKeys')
+if (localStorage.getItem('userKeys')) localStorage.removeItem('userKeys')

52-52: Clarify the removal of spaces from keys.

By invoking key.split(' ').join(''), all spaces in the key are stripped. Ensure this behavior is deliberate. If your application expects multi-word shortcuts, consider preserving them.

Do you want a script to scan the codebase for multispaced key definitions to confirm no unintended collisions will occur?


106-106: Use getItem rather than direct property access on localStorage.

Past comment also applies here. Replace:

-if (localStorage.defaultKeys) localStorage.removeItem('defaultKeys')
+if (localStorage.getItem('defaultKeys')) localStorage.removeItem('defaultKeys')

src/simulator/src/hotkey_binder/model/actions.ts Outdated Show resolved Hide resolved
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: 0

🧹 Nitpick comments (3)
src/simulator/src/hotkey_binder/model/actions.ts (3)

195-225: Consider simplifying iteration with a direct exit loop.

Using Array.from(...) + .reduce(...) to find a single match may be less intuitive. A simple for-of loop or an Array.find(...) approach could convey the intent more clearly:

-  return Array.from(preferenceChildren).reduce<string | undefined>((acc, child) => {
-      ...
-  }, undefined)

+  for (const child of preferenceChildren) {
+      const result = getAssigneeFromPreference(child, combo, target)
+      if (result) return result
+  }
+  return undefined

240-246: Clarify or simplify nested arrow function patterns.

Both elementDirection and labelDirection return double arrow functions. While this can be useful for higher-order bindings, consider making them single arrow functions returning void for clearer readability if there is no requirement for partial application.

Also applies to: 251-257


309-316: Avoid magic numbers in movement logic.

Using the hardcoded step of 10 for the x/y offsets can cause difficulty with future changes or customization. Consider extracting it into a named constant, e.g. const MOVE_STEP = 10;.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5a6edb1 and 55f3d80.

📒 Files selected for processing (1)
  • src/simulator/src/hotkey_binder/model/actions.ts (1 hunks)
🔇 Additional comments (3)
src/simulator/src/hotkey_binder/model/actions.ts (3)

43-43: Use getItem over direct property access on localStorage.

Referencing localStorage.userKeys or localStorage.defaultKeys is non-standard. For consistency, prefer the canonical getItem/removeItem methods:

-if (localStorage.userKeys) localStorage.removeItem('userKeys')
+if (localStorage.getItem('userKeys')) localStorage.removeItem('userKeys')

-if (localStorage.defaultKeys) localStorage.removeItem('defaultKeys')
+if (localStorage.getItem('defaultKeys')) localStorage.removeItem('defaultKeys')

Also applies to: 122-122


72-103: Sync logic thoroughly addresses key management.

Your implementation of syncKeys, addOrUpdateKeys, and removeObsoleteKeys is an apt solution for seamlessly handling changes in the default key map. This admirably addresses past feedback on cleaning up outdated user keys.


131-145: Good job with null checks and type guards for DOM elements.

Using optional chaining and verifying instance types for HTMLElement ensures robust DOM interaction. This prevents potential runtime errors caused by uninitialized elements.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Typescript Integration in /simulator/src files
1 participant