Skip to content

Conversation

@ArgoZhang
Copy link
Member

@ArgoZhang ArgoZhang commented May 16, 2025

Link issues

fixes #6038

Summary By Copilot

This pull request refactors the Toast.razor.js file to improve code maintainability and fix issues related to the toast progress bar and event handling. Key changes include centralizing the progressElement logic, updating event handlers, and enhancing the handling of the autohide configuration.

Refactoring and code improvements:

  • Centralized the progressElement logic by moving its initialization to the init function and ensuring consistent usage across methods. This eliminates redundant queries for the .toast-progress element.
  • Simplified event handler setup by directly using el (the toast element) instead of repeatedly referencing toast.element. This improves readability and reduces potential errors.

Functional enhancements:

  • Added a new event handler for the transitionend event on the progressElement to automatically hide the toast when the progress bar animation completes.
  • Improved update function to handle cases where autohide is disabled by removing the progress bar's width and transition properties. This ensures proper behavior for non-autohiding toasts.

Cleanup and disposal:

  • Updated the dispose function to cleanly remove all associated event handlers, including the new transitionend event on the `progressElement

Regression?

  • Yes
  • No

Risk

  • High
  • Medium
  • Low

Verification

  • Manual (required)
  • Automated

Packaging changes reviewed?

  • Yes
  • No
  • N/A

☑️ Self Check before Merge

⚠️ Please check all items below before review. ⚠️

  • Doc is updated/provided or not needed
  • Demo is updated/provided or not needed
  • Merge the latest code from the main branch

Summary by Sourcery

Refactor toast component to improve auto-hide logic by centralizing progress bar handling, adding a transitionend listener to trigger hide on animation completion, handling disabled autohide by clearing styles, and ensuring proper cleanup of event listeners

Bug Fixes:

  • Ensure toast hides correctly after progress animation by handling transitionend

Enhancements:

  • Centralize progress bar element initialization in init() to avoid redundant queries
  • Simplify event handler setup by referencing the toast element directly
  • Update autohide logic in update() to reset progress bar styles when disabled
  • Clean up all related event listeners including transitionend in dispose()

@bb-auto bb-auto bot added the enhancement New feature or request label May 16, 2025
@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented May 16, 2025

Reviewer's Guide

Refactored Toast.razor.js to centralize progress element management, streamline event handling, introduce a transitionend auto-hide trigger, refine autohide update behavior, and ensure complete cleanup in dispose.

Sequence Diagram: Toast Auto-Hide on Progress Transition End

sequenceDiagram
    participant Caller
    participant ToastModule as "Toast.razor.js init()"
    participant BootstrapToast as "bootstrap.Toast"
    participant ProgressElement as "progressElement"
    participant EventHandler

    Caller->>ToastModule: init(id, invoke, callback)
    ToastModule->>ToastModule: Get progressElement from DOM
    ToastModule->>ToastModule: Create toastObject (now includes progressElement reference)
    alt autohide is true
        ToastModule->>ProgressElement: style.transition = `width linear ${delay}s`
    end
    ToastModule->>EventHandler: on(el, 'shown.bs.toast', ...)
    ToastModule->>EventHandler: on(el, 'hidden.bs.toast', ...)
    ToastModule->>EventHandler: on(progressElement, 'transitionend', handleTransitionEndCallback)
    ToastModule->>BootstrapToast: show()

    EventHandler-->>ToastModule: 'shown.bs.toast' event received
    alt autohide is true
        ToastModule->>ProgressElement: style.width = '100%' (progress animation starts)
    end

    Note over ProgressElement: Progress bar animates to 100%
    EventHandler-->>ToastModule: 'transitionend' event received (from progressElement)
    ToastModule->>BootstrapToast: hide()  // Toast hiding is triggered by progress completion

    EventHandler-->>ToastModule: 'hidden.bs.toast' event received
    ToastModule->>Caller: invoke.invokeMethodAsync(callback) // Notify .NET about closure
Loading

Sequence Diagram: Toast Update Logic for AutoHide Configuration

sequenceDiagram
    participant Caller
    participant ToastModuleUpdate as "Toast.razor.js update()"
    participant ToastObject
    participant BootstrapToastConfig as "bootstrap.Toast._config"
    participant ProgressElementStyle as "progressElement.style"

    Caller->>ToastModuleUpdate: update(id)
    ToastModuleUpdate->>ToastObject: Get toast data (element, toast, progressElement)
    ToastModuleUpdate->>ToastObject: Read autohide & delay from element attributes
    alt autohide is true (based on element attributes)
        ToastModuleUpdate->>BootstrapToastConfig: toast._config.autohide = true
        ToastModuleUpdate->>BootstrapToastConfig: toast._config.delay = newDelay
        ToastModuleUpdate->>ProgressElementStyle: progressElement.style.width = '100%'
        ToastModuleUpdate->>ProgressElementStyle: progressElement.style.transition = `width linear ${newDelay / 1000}s`
    else autohide is false (based on element attributes)
        ToastModuleUpdate->>BootstrapToastConfig: toast._config.autohide = false
        ToastModuleUpdate->>ProgressElementStyle: progressElement.style.removeProperty('width')
        ToastModuleUpdate->>ProgressElementStyle: progressElement.style.removeProperty('transition')
    end
Loading

Class Diagram: Structure of the Internal Toast Object

classDiagram
    class ToastObject {
      +element: HTMLElement
      +invoke: DotNetObjectReference
      +callback: string
      +toast: BootstrapToast
      +progressElement: HTMLElement  // Centralized property
      +showProgress(): boolean
    }
    note for ToastObject "Internal object created by Toast.razor.js#init() to manage a toast instance. `progressElement` is now a direct and centralized property, simplifying its access and management."

    class BootstrapToast {
      <<External Library>>
      _config: object
      show()
      hide()
      dispose()
    }

    class EventHandler {
      <<Utility Module>>
      static on(element, eventName, handler)
      static off(element, eventName, handler)
    }

    namespace ToastRazorJs {
        class Functions {
            <<JavaScript Module Functions>>
            init(id, invoke, callback): ToastObject
            update(id): void
            dispose(id): void
        }
    }
    note for Functions "Exported functions in Toast.razor.js that operate on ToastObject instances stored in a Data cache."

    Functions ..> ToastObject : Creates & Manages
    ToastObject "1" *-- "1" BootstrapToast : aggregates via `toast` property
    ToastObject "1" *-- "1" HTMLElement : holds `element` (the main toast DOM element)
    ToastObject "1" *-- "1" HTMLElement : holds `progressElement` (the progress bar DOM element)
    Functions ..> EventHandler : Uses for event binding and unbinding
Loading

File-Level Changes

Change Details Files
Centralized progress element initialization
  • Moved query selector for .toast-progress into init
  • Attached progressElement to the toast object
  • Removed duplicate queries in subsequent methods
src/BootstrapBlazor/Components/Toast/Toast.razor.js
Simplified event handler references and invocation
  • Replaced toast.element references with local el variable
  • Directly used invoke.invokeMethodAsync instead of toast.invoke.invokeMethodAsync
src/BootstrapBlazor/Components/Toast/Toast.razor.js
Added transitionend event to auto-hide toast
  • Bound transitionend on progressElement to call toast.hide()
  • Removed redundant transitionend binding in update()
src/BootstrapBlazor/Components/Toast/Toast.razor.js
Refined update logic for autohide configuration
  • Destructured progressElement in update()
  • Applied width and transition only when autohide is true
  • Cleared width and transition styles when autohide is disabled
src/BootstrapBlazor/Components/Toast/Toast.razor.js
Enhanced disposal cleanup
  • Destructured element and progressElement in dispose()
  • Unbound transitionend handler alongside shown/hidden events
  • Ensured toast instance is properly disposed
src/BootstrapBlazor/Components/Toast/Toast.razor.js

Assessment against linked issues

Issue Objective Addressed Explanation
#6038 Perfect the AutoHide logic of the Toast component.

Possibly linked issues

  • #0: PR refactors Toast AutoHide logic, progress bar, and event handling as described in the issue.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@bb-auto bb-auto bot added this to the v9.6.0 milestone May 16, 2025
@ArgoZhang ArgoZhang merged commit ab6c3c1 into main May 16, 2025
3 checks passed
@ArgoZhang ArgoZhang deleted the refactor-toast branch May 16, 2025 14:09
Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @ArgoZhang - I've reviewed your changes and they look great!

Here's what I looked at during the review
  • 🟡 General issues: 2 issues found
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.


toast._config.autohide = autoHide;
toast._config.delay = delay;

Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (bug_risk): Specify radix in parseInt

Include a radix of 10 (parseInt(..., 10)) to ensure decimal parsing; without it, leading zeros can cause unexpected results.

Suggested change
const delay = parseInt(element.getAttribute('data-bs-delay'), 10);

Comment on lines +32 to +34
EventHandler.on(progressElement, 'transitionend', e => {
toast.toast.hide();
});
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (bug_risk): Filter transitionend by property name

Guard with if (e.propertyName !== 'width') return; so only the width transition triggers hide and other transitions won’t call it.

Suggested change
EventHandler.on(progressElement, 'transitionend', e => {
toast.toast.hide();
});
EventHandler.on(progressElement, 'transitionend', e => {
if (e.propertyName !== 'width') return;
toast.toast.hide();
});

@codecov
Copy link

codecov bot commented May 16, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (bd404f7) to head (573d652).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #6039   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files          701       701           
  Lines        30955     30955           
  Branches      4377      4377           
=========================================
  Hits         30955     30955           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

refactor(Toast): perfect AutoHide logic

2 participants