LayTec-AG / Plotly.Blazor

This library packages the well-known charting library plotly.js into a razor component that can be used in a Blazor project.
MIT License
359 stars 52 forks source link

Animate feature workaround #441

Open melon-dog opened 2 months ago

melon-dog commented 2 months ago

I understand that the animation option isn't developed yet, but I was wondering if there’s a possible workaround to enable this feature via JavaScript.

Thanks in advance!

sean-mcl commented 2 months ago

You can write your own interop functions in a *.js file.

chart-helper.js

export function animate(id) {
    if (typeof Plotly === 'undefined') return false;

    var chart = document.getElementById(id);

    if (!chart) return false;

    // Custom logic, read the data from the current plotly instance and apply animations

    return true;
}

ChartHelper.cs


 public class ChartHelper
 {
     private const string InteropPath = "/_content/<ProjectName>/js/chart-helper.js";

     // Use lazy init
     private readonly Lazy<Task<IJSObjectReference>> moduleTask;

     public ChartHelper(IJSRuntime jsRuntime)
     {
         moduleTask = new(() =>
             jsRuntime.InvokeAsync<IJSObjectReference>("import", InteropPath).AsTask());
     }

     public async ValueTask Animate(string chartId, CancellationToken cancellationToken = default)
     {
         var success = await module.InvokeAsync<bool>("animate", cancellationToken, chartId);

         // TODO: Error handling
     }
 }

Component.razor


@inject IJSRuntime JsRuntime
private ChartHelper Helper { get; set; }

@code
{
   /// <inheritdoc />
   protected override async Task OnInitializedAsync()
   {
      Helper = new(JsRuntime);
   }
}
sean-mcl commented 2 months ago

Or just contribute to Plotly.Blazor with a correct wrapping method :)