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

[V3] Add generic to runtime event handlers #4042

Open
wants to merge 2 commits into
base: v3-alpha
Choose a base branch
from

Conversation

IanVS
Copy link

@IanVS IanVS commented Jan 30, 2025

Description

This strengthens the TypeScript types of @wailsio/runtime by adding a generic parameter to Events.On, Events.OnMultiple and Events.Once, and updates the templates to use the new format.

This was discussed in discord: https://discord.com/channels/1042734330029547630/1065600636294549514/1334267494491357204

Fixes # NA

Type of change

Please select the option that is relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How Has This Been Tested?

I copied the newly-generated events.d.ts into my own project, and verified that I was able to use the new generic without any type errors:

Code 2025-01-30 10 52 24
  • Windows
  • macOS
  • Linux

Test Configuration

 Wails (v3.0.0-alpha.9)  Wails Doctor

# System

┌──────────────────────────────────────────────────┐
| Name          | MacOS                            |
| Version       | 15.2                             |
| ID            | 24C101                           |
| Branding      | MacOS 15.2                       |
| Platform      | darwin                           |
| Architecture  | arm64                            |
| Apple Silicon | true                             |
| CPU           | Apple M2 Max                     |
| CPU 1         | Apple M2 Max                     |
| CPU 2         | Apple M2 Max                     |
| GPU           | 30 cores, Metal Support: Metal 3 |
| Memory        | 64 GB                            |
└──────────────────────────────────────────────────┘

# Build Environment

┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
| Wails CLI      | v3.0.0-alpha.9                                                                                                            |
| Go Version     | go1.23.5                                                                                                                  |
| -buildmode     | exe                                                                                                                       |
| -compiler      | gc                                                                                                                        |
| CGO_CFLAGS     |                                                                                                                           |
| CGO_CPPFLAGS   |                                                                                                                           |
| CGO_CXXFLAGS   |                                                                                                                           |
| CGO_ENABLED    | 1                                                                                                                         |
| CGO_LDFLAGS    |                                                                                                                           |
| DefaultGODEBUG | asynctimerchan=1,gotypesalias=0,httpservecontentkeepheaders=1,tls3des=1,tlskyber=0,x509keypairleaf=0,x509negativeserial=1 |
| GOARCH         | arm64                                                                                                                     |
| GOARM64        | v8.0                                                                                                                      |
| GOOS           | darwin                                                                                                                    |
└────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘

# Dependencies

┌───────────────────────────┐
| Xcode cli tools | 2409    |
| npm             | 10.9.2  |
| *NSIS           | v3.10   |
└─ * - Optional Dependency ─┘

# Diagnosis

 SUCCESS  Your system is ready for Wails development!

Checklist:

  • I have updated website/src/pages/changelog.mdx with details of this PR
  • My code follows the general coding style of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

Summary by CodeRabbit

  • Type Safety Improvements

    • Enhanced event handling system with more precise type definitions
    • Added generic type support for event callbacks across multiple frameworks
    • Improved type safety for event data handling
  • Event Handling Updates

    • Refined event callback type definitions
    • Updated event registration methods to support more flexible typing
    • Standardized event callback parameter handling across different templates
  • Framework Template Updates

    • Updated event listener type annotations in multiple frontend templates
    • Simplified event data type handling across various frameworks (React, Vue, Svelte, etc.)

Copy link
Contributor

coderabbitai bot commented Jan 30, 2025

Walkthrough

The pull request introduces significant improvements to the event handling system in the Wails runtime. The primary focus is on enhancing type safety and flexibility by adding generic type parameters to event-related functions and classes. The changes span multiple files, including the runtime implementation, type definitions, and various frontend template implementations across different frameworks. The modifications aim to provide more precise type checking and clearer event callback definitions while maintaining the existing functionality.

Changes

File Path Change Summary
v3/internal/runtime/desktop/@wailsio/runtime/src/events.js Added generic type WailsEventCallback, updated WailsEvent class with generic type parameter, modified event handling functions
v3/internal/runtime/desktop/@wailsio/runtime/types/events.d.ts Updated type definitions for OnMultiple, On, and Once functions, added WailsEventCallback type
Frontend Templates Updated event listener type annotations to use Events.On<string> in multiple framework-specific files (React, Vue, Svelte, Qwik, etc.)
v3/internal/templates/base/frontend/main.js Minor parameter name change from time to timeValue

Sequence Diagram

sequenceDiagram
    participant Client
    participant EventSystem
    participant Callback

    Client->>EventSystem: Register Event Listener
    Note over Client,EventSystem: Uses generic type WailsEventCallback<D>
    EventSystem-->>Client: Return Unregister Function
    Client->>EventSystem: Trigger Event
    EventSystem->>Callback: Invoke with Typed Event
    Callback->>Client: Process Event Data
Loading

Poem

🐰 Hop, hop, type safety springs!
Generic events now take their wings
Callbacks dance with type delight
No more any to cause a fright
CodeRabbit's magic makes types bright! 🎉

✨ 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.

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
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 (2)
v3/internal/templates/vanilla-ts/frontend/src/main.ts (1)

21-23: Consider renaming parameter for consistency.

While the generic type addition improves type safety, consider renaming the parameter from time to timeValue to maintain consistency with other templates and avoid confusion with the variable name.

-Events.On<string>('time', (time) => {
-    timeElement.innerText = time.data;
+Events.On<string>('time', (timeValue) => {
+    timeElement.innerText = timeValue.data;
v3/internal/runtime/desktop/@wailsio/runtime/src/events.js (1)

Line range hint 45-56: Consider adding type constraints for the generic parameter.

While the generic implementation looks good, consider adding type constraints to prevent potential misuse with incompatible types.

-/** 
- * @template [D=unknown] 
- */
+/** 
+ * @template [D=unknown]
+ * @template {object|string|number|boolean|null} D
+ */
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b3e81f5 and 265fbff.

📒 Files selected for processing (13)
  • v3/internal/runtime/desktop/@wailsio/runtime/src/events.js (4 hunks)
  • v3/internal/runtime/desktop/@wailsio/runtime/types/events.d.ts (2 hunks)
  • v3/internal/templates/base/frontend/main.js (1 hunks)
  • v3/internal/templates/lit-ts/frontend/src/my-element.ts (1 hunks)
  • v3/internal/templates/preact-ts/frontend/src/app.tsx (1 hunks)
  • v3/internal/templates/qwik-ts/frontend/src/app.tsx (1 hunks)
  • v3/internal/templates/react-swc-ts/frontend/src/App.tsx (1 hunks)
  • v3/internal/templates/react-ts/frontend/src/App.tsx (1 hunks)
  • v3/internal/templates/solid-ts/frontend/src/App.tsx (1 hunks)
  • v3/internal/templates/svelte-ts/frontend/src/App.svelte (1 hunks)
  • v3/internal/templates/vanilla-ts/frontend/src/main.ts (1 hunks)
  • v3/internal/templates/vanilla/frontend/main.js (1 hunks)
  • v3/internal/templates/vue-ts/frontend/src/components/HelloWorld.vue (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • v3/internal/templates/base/frontend/main.js
  • v3/internal/templates/vanilla/frontend/main.js
🔇 Additional comments (13)
v3/internal/templates/vue-ts/frontend/src/components/HelloWorld.vue (1)

25-27: LGTM! Clean implementation with proper type safety.

The implementation correctly uses the generic type parameter while maintaining Vue's best practices with lifecycle hooks and reactive refs.

v3/internal/templates/solid-ts/frontend/src/App.tsx (1)

23-25: LGTM! Well-implemented with proper type safety.

The implementation correctly uses the generic type parameter while following Solid.js best practices with lifecycle hooks and signals.

v3/internal/runtime/desktop/@wailsio/runtime/src/events.js (2)

13-19: LGTM! Well-structured type definition for event callbacks.

The new WailsEventCallback type definition with generic parameter D provides proper type safety for event handlers.


Line range hint 80-110: LGTM! Comprehensive documentation and type safety for event registration methods.

The event registration methods (OnMultiple, On, Once) are well documented with proper generic type parameters and return types.

v3/internal/templates/react-ts/frontend/src/App.tsx (1)

23-23: LGTM! Proper usage of generic type parameter.

The Events.On<string> correctly specifies the event data type, allowing TypeScript to infer the timeValue parameter type.

v3/internal/templates/react-swc-ts/frontend/src/App.tsx (1)

23-23: Implementation matches React template.

v3/internal/templates/preact-ts/frontend/src/app.tsx (1)

23-23: Implementation matches React template.

v3/internal/runtime/desktop/@wailsio/runtime/types/events.d.ts (4)

5-12: LGTM! Well-structured type definition for OnMultiple.

The generic type parameter and precise return type enhance type safety while maintaining flexibility with the default unknown type.


16-20: LGTM! Consistent type definition for On.

The changes maintain consistency with OnMultiple, providing the same level of type safety and flexibility.


24-29: LGTM! Consistent type definition for Once.

The changes maintain consistency with other event handlers, completing the set of typed event registration methods.


238-250: LGTM! Well-structured WailsEvent class and callback type.

The generic type parameter is properly implemented in both the class and callback type, providing a solid foundation for type-safe event handling.

v3/internal/templates/qwik-ts/frontend/src/app.tsx (1)

23-24: LGTM! Proper usage of generic type parameter.

The implementation correctly uses the new Events.On<string> syntax and properly accesses the event data.

v3/internal/templates/lit-ts/frontend/src/my-element.ts (1)

26-28: LGTM! Proper usage of generic type parameter.

The implementation correctly uses the new Events.On<string> syntax and properly accesses the event data.

Comment on lines +21 to 23
Events.On<string>('time', (timeValue) => {
time = timeValue.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

Consider wrapping event listener in onMount.

While the generic type addition is good, the event listener should be wrapped in Svelte's onMount lifecycle function to prevent potential memory leaks and ensure proper cleanup.

+import { onMount } from 'svelte';

-Events.On<string>('time', (timeValue) => {
-  time = timeValue.data;
-});
+onMount(() => {
+  Events.On<string>('time', (timeValue) => {
+    time = timeValue.data;
+  });
+});

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

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.

1 participant