Skip to content

refactor: typescript defined addShortcit.ts, model.types.ts and plugins #488

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

Closed
wants to merge 1 commit into from

Conversation

gitsofaryan
Copy link
Contributor

@gitsofaryan gitsofaryan commented Feb 21, 2025

Describe the changes you have made in this PR -

  1. TypeScript Conversion:
  • Converted addShortcut.ts, model.types.ts, and normalizer.plugin.js to TypeScript (.ts).
  • Added type annotations and interfaces for improved type safety.
  1. Type Definitions:
  • Introduced ActionType in model.types.ts to define valid shortcut actions.
  • Defined interfaces for key events and current key states in normalizer.plugin.ts.
  1. Code Improvements:
  • Refactored addShortcut.ts to use imported types and options for shortcut configuration.
  • Enhanced readability and maintainability by using TypeScript features.

Files Affected:

  • src/simulator/src/hotkey_binder/model/addShortcut.ts
  • src/simulator/src/hotkey_binder/model/model.types.ts
  • src/simulator/src/hotkey_binder/model/normalize/normalizer.plugin.ts

Summary by CodeRabbit

  • New Features
    • Enhanced keyboard shortcut management now supports a broader range of actions.
  • Refactor
    • Updated shortcut handling with explicit type definitions for improved reliability.
  • Chore
    • Removed outdated keyboard normalization logic to streamline event processing and ensure consistent behavior.

Copy link
Contributor

coderabbitai bot commented Feb 21, 2025

Walkthrough

This PR updates the hotkey binder module by refining the addShortcut function and related type definitions. The function signature now uses a default export with explicit TypeScript type annotations. Import statements have been updated to include the .js extension. A new union type, ActionType, has been added to enhance hotkey action typing. In addition, the legacy JavaScript-based normalizer has been removed in favor of a new TypeScript implementation that exports a strongly-typed KeyCode object along with supporting interfaces.

Changes

File(s) Change Summary
src/…/hotkey_binder/model/addShortcut.ts Changed from named to default export; added explicit parameter (keys: string, action: ActionType) and callback type annotations; updated import paths to include .js, and defined shortcut options with an explicit type.
src/…/hotkey_binder/model/model.types.ts Introduced new ActionType as a union of hotkey-related string literals; existing interfaces remain unchanged.
src/…/hotkey_binder/model/normalize/normalizer.plugin.js Removed the entire JavaScript file that provided key normalization logic and browser key code mapping.
src/…/hotkey_binder/model/normalize/normalizer.plugin.ts Added a new TypeScript file defining interfaces (KeyCodeType, KeyEvent, CurrentKeys) and exporting a KeyCode object with methods for key translation, event handling, and mapping.

Sequence Diagram(s)

sequenceDiagram
    participant U as User/Caller
    participant A as addShortcut
    participant SH as Shortcut Plugin

    U->>A: call addShortcut(keys, action)
    A->>A: Determine callback based on action
    A->>SH: Register shortcut with callback and options
    SH-->>A: Confirm registration
    A-->>U: Return void
Loading
sequenceDiagram
    participant U as User
    participant E as Key Event
    participant K as KeyCode (Normalizer)

    U->>E: Trigger keydown event
    E->>K: translate_event(event)
    K-->>E: Return standardized key data
    E->>K: Process key state (key_down, is_down)
Loading

Possibly related PRs

Suggested reviewers

  • JoshVarga
  • Arnabdaz

Poem

Hop, hop, the code is fresh and new,
I nibble on changes while typing through.
Shortcuts refined and keys aligned,
In TypeScript fields, clarity we find.
With each update, my joy leaps high,
Celebrating clean code as I hop by! 🐇

✨ 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 Feb 21, 2025

Deploy Preview for circuitverse ready!

Name Link
🔨 Latest commit 8e34105
🔍 Latest deploy log https://app.netlify.com/sites/circuitverse/deploys/67b809a503f9a60008710e93
😎 Deploy Preview https://deploy-preview-488--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 (3)
src/simulator/src/hotkey_binder/model/model.types.ts (1)

28-34: Consider making some ShortcutOptions properties required.

Properties like disable_in_input and propagate seem to have consistent usage patterns in addShortcut.ts. Consider making them required if they're always needed.

 export interface ShortcutOptions {
     type?: string
-    propagate?: boolean
-    disable_in_input?: boolean
+    propagate: boolean
+    disable_in_input: boolean
     target?: Document | string
     keycode?: number | false
 }
src/simulator/src/hotkey_binder/model/addShortcut.ts (1)

25-91: Consider using an action map instead of a switch statement.

The switch statement, while exhaustive, could be replaced with an object map for better maintainability.

+const actionMap: Record<ActionType, () => void> = {
+    'New Circuit': logixFunction.createNewCircuitScope,
+    'Save Online': save,
+    'Save Offline': saveOffline,
+    // ... other actions
+};

 export default function addShortcut(keys: string, action: ActionType): void {
-    let callback: () => void = () => console.error('No shortcut found..')
-    
-    switch (action) {
-        case 'New Circuit':
-            callback = logixFunction.createNewCircuitScope
-            break
-        // ... other cases
-    }
+    const callback = actionMap[action] ?? (() => console.error('No shortcut found..'));
src/simulator/src/hotkey_binder/model/normalize/normalizer.plugin.ts (1)

237-244: Add type guard for better type safety.

The is_down function could benefit from a type guard to ensure type safety when checking modifiers.

+function isModifierKey(code: number): boolean {
+    return code === KeyCode.CTRL || code === KeyCode.ALT || code === KeyCode.SHIFT;
+}

 is_down: function(key: KeyEvent): boolean {
     const code = key.code;
-    if (code == KeyCode.CTRL) return current_keys.ctrl;
-    if (code == KeyCode.ALT) return current_keys.alt;
-    if (code == KeyCode.SHIFT) return current_keys.shift;
+    if (isModifierKey(code)) {
+        return current_keys[key_names[code].toLowerCase() as keyof CurrentKeys];
+    }

     return current_keys.codes[code] !== undefined && same_modifiers(key, current_keys);
 },
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1ea73f2 and 8e34105.

📒 Files selected for processing (4)
  • src/simulator/src/hotkey_binder/model/addShortcut.ts (2 hunks)
  • src/simulator/src/hotkey_binder/model/model.types.ts (1 hunks)
  • src/simulator/src/hotkey_binder/model/normalize/normalizer.plugin.js (0 hunks)
  • src/simulator/src/hotkey_binder/model/normalize/normalizer.plugin.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • src/simulator/src/hotkey_binder/model/normalize/normalizer.plugin.js
🔇 Additional comments (3)
src/simulator/src/hotkey_binder/model/model.types.ts (1)

4-26: LGTM! Well-structured union type for actions.

The ActionType union type provides a comprehensive and type-safe way to define valid shortcut actions. The string literals are descriptive and follow a consistent naming pattern.

src/simulator/src/hotkey_binder/model/addShortcut.ts (1)

21-23: LGTM! Well-typed function signature with proper error handling.

The function signature is properly typed with TypeScript, and the default error callback is a good practice.

src/simulator/src/hotkey_binder/model/normalize/normalizer.plugin.ts (1)

1-14: LGTM! Well-structured KeyCodeType interface.

The interface provides a comprehensive type-safe API for key code operations.

Comment on lines +68 to +74
const is_gecko = navigator.userAgent.indexOf('Gecko') != -1;
const is_ie = navigator.userAgent.indexOf('MSIE') != -1;
const is_windows = navigator.platform.indexOf('Win') != -1;
const is_opera = window.opera && (window.opera as any).version() < 9.5;
const is_konqueror = navigator.vendor && navigator.vendor.indexOf('KDE') != -1;
const is_icab = navigator.vendor && navigator.vendor.indexOf('iCab') != -1;

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

Modernize browser detection logic.

The current browser detection approach using userAgent and vendor is outdated. Consider using feature detection instead.

-const is_gecko = navigator.userAgent.indexOf('Gecko') != -1;
-const is_ie = navigator.userAgent.indexOf('MSIE') != -1;
-const is_windows = navigator.platform.indexOf('Win') != -1;
-const is_opera = window.opera && (window.opera as any).version() < 9.5;
-const is_konqueror = navigator.vendor && navigator.vendor.indexOf('KDE') != -1;
-const is_icab = navigator.vendor && navigator.vendor.indexOf('iCab') != -1;
+const getKeyboardAPI = () => {
+    if ('KeyboardEvent' in window && 'code' in KeyboardEvent.prototype) {
+        return 'modern';
+    }
+    return 'legacy';
+};
📝 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 is_gecko = navigator.userAgent.indexOf('Gecko') != -1;
const is_ie = navigator.userAgent.indexOf('MSIE') != -1;
const is_windows = navigator.platform.indexOf('Win') != -1;
const is_opera = window.opera && (window.opera as any).version() < 9.5;
const is_konqueror = navigator.vendor && navigator.vendor.indexOf('KDE') != -1;
const is_icab = navigator.vendor && navigator.vendor.indexOf('iCab') != -1;
const getKeyboardAPI = () => {
if ('KeyboardEvent' in window && 'code' in KeyboardEvent.prototype) {
return 'modern';
}
return 'legacy';
};

Comment on lines +214 to +223
translate_event: function(e: KeyboardEvent): KeyEvent {
const code = e.which || e.keyCode;
return {
code: KeyCode.translate_key_code(code),
shift: e.shiftKey,
alt: e.altKey,
ctrl: e.ctrlKey,
meta: e.metaKey,
};
},
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

Consider using KeyboardEvent.code for more reliable key identification.

The current implementation uses which (deprecated) or keyCode. Consider using the more modern code property.

 translate_event: function(e: KeyboardEvent): KeyEvent {
-    const code = e.which || e.keyCode;
+    const code = e.code ? KeyCode.translate_key_code(e.code.charCodeAt(0)) : e.keyCode;
     return {
         code: KeyCode.translate_key_code(code),
         shift: e.shiftKey,
         alt: e.altKey,
         ctrl: e.ctrlKey,
         meta: e.metaKey,
     };
 },

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

@gitsofaryan
Copy link
Contributor Author

@vedant-jain03 please review my changes.

@ThatDeparted2061
Copy link
Member

#424 and #458
@gitsofaryan There are many other files in js that you can convert to ts , why do you always raise PR for the same files which have been previously worked upon, If you feel like a file the previous work has some fatal issue then you should comment and if it needs a total revamp then you should very well raise a PR for the same file, but that is not the case here.

@gitsofaryan
Copy link
Contributor Author

Hey @ThatDeparted2061 I'm sorry for the misunderstanding, I was not aware that you have worked on this. I'm closing this PR.

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.

2 participants