### Build Playwright Project and Install Browser Assets Source: https://github.com/ipax77/pax.blazorchartjs/blob/main/tests/README.md Build the Playwright project and install its Chromium browser assets. This is a one-time setup step. ```powershell dotnet build .\tests\pax.BlazorChartJs.pwtests\pax.BlazorChartJs.pwtests.csproj pwsh .\tests\pax.BlazorChartJs.pwtests\bin\Debug\net10.0\playwright.ps1 install ``` -------------------------------- ### Scalar Dataset Example Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Getting-Started Illustrates how to define data for a scalar dataset, such as for a simple bar chart. ```csharp Data = [1, 2, 3] ``` -------------------------------- ### Add pax.BlazorChartJs Package Source: https://github.com/ipax77/pax.blazorchartjs/blob/main/README.md Install the pax.BlazorChartJs NuGet package using the .NET CLI. ```powershell dotnet add package pax.BlazorChartJs ``` -------------------------------- ### Scriptable Font Option Example Source: https://github.com/ipax77/pax.blazorchartjs/blob/main/README.md Demonstrates how to use `ChartJsFunction` for scriptable font options when `IndexableOption` is used. ```csharp Font = new ChartJsFunction("() => new Font { Size = 12 }") ``` -------------------------------- ### Minimal Bar Chart Example Source: https://github.com/ipax77/pax.blazorchartjs/blob/main/README.md A basic Blazor component demonstrating how to render a bar chart using ChartComponent and a typed ChartJsConfig. ```razor @using pax.BlazorChartJs
@code { private readonly ChartJsConfig chartJsConfig = new() { Type = ChartType.bar, Data = new ChartJsData() { Labels = ["Jan", "Feb", "Mar"], Datasets = [ new BarDataset() { Label = "Dataset 1", Data = [1, 2, 3] } ] } }; } ``` -------------------------------- ### Regenerate Chart.js Interop Bundle Source: https://github.com/ipax77/pax.blazorchartjs/blob/main/README.md Use this command to regenerate the bundled JavaScript interop file. Ensure Node.js and npm are installed. This command should be run from the `src/pax.BlazorChartJs` directory. ```powershell cd src\pax.BlazorChartJs npm install npm run bundle ``` -------------------------------- ### Minimal Bar Chart Component Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Getting-Started This Razor component demonstrates the basic setup for a bar chart. It requires a ChartJsConfig object to be provided to the ChartComponent. ```razor @using pax.BlazorChartJs
@code { private readonly ChartJsConfig chartJsConfig = new() { Type = ChartType.bar, Data = new ChartJsData { Labels = ["Jan", "Feb", "Mar"], Datasets = [ new BarDataset { Label = "Dataset 1", Data = [1, 2, 3] } ] } }; } ``` -------------------------------- ### Configure Chart.js Datalabels Plugin Source Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Data-Labels Configure the Chart.js Datalabels plugin script location using AddChartJs options. This example uses a CDN. ```csharp builder.Services.AddChartJs(options => { options.ChartJsPluginDatalabelsLocation = "https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2"; }); ``` -------------------------------- ### Configure App-Wide Chart.js Defaults Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Defaults-and-Helpers Set global Chart.js defaults, including callback module location and default chart options like colors, fonts, and dataset-specific settings. This configuration is applied during application setup. ```csharp builder.Services.AddChartJs(options => { options.ChartJsCallbacksModuleLocation = $"{builder.HostEnvironment.BaseAddress}_content/my-app/chartJsCallbacks.js"; options.Defaults = new ChartJsDefaultsOptions { Color = "#1f2937", BorderColor = "#d1d5db", Font = new Font { Family = "Inter, system-ui, sans-serif", Size = 12 }, Datasets = new ChartJsOptionsDatasets { Bar = new { barPercentage = 0.8 }, Line = new { tension = 0.25 } }, OnClick = ChartJsFunction.FromName("globalChartClick") }; }); ``` -------------------------------- ### Create Dataset Slot for Large Data Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Large-Data-Updates Initializes a Chart.js configuration with a stable ID for a large dataset, starting with an empty data collection. This ID is crucial for targeting binary updates. ```csharp var config = new ChartJsConfig { Type = ChartType.line, Data = new ChartJsData { Datasets = [ new LineDataset { Id = "large-dataset", Label = "Large Dataset", BorderWidth = 1, PointRadius = 0, Data = [] } ] } }; ``` -------------------------------- ### Render HTML Legend Items Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Events-and-HTML-Legends Render legend items as Razor markup within a custom component. This example iterates through LegendItems and attaches click, mouseover, and mouseleave handlers. ```razor @inherits LegendComponentBase @foreach (var item in LegendItems) { @item.Text } ``` -------------------------------- ### New Syntax for IndexableOption Initialization Source: https://github.com/ipax77/pax.blazorchartjs/blob/main/README.md Demonstrates the concise syntax for initializing IndexableOption with implicit operators. This syntax is available from v0.8.1 onwards. ```csharp BorderColor = new List() { "rgba(255, 99, 132, 1)", "rgba(54, 162, 235, 1)" }, BorderWidth = 1 ``` -------------------------------- ### Run Full Sample Gallery Coverage Source: https://github.com/ipax77/pax.blazorchartjs/blob/main/tests/README.md Execute the full sample coverage by selecting the 'FullSamples' NUnit category. This provides comprehensive regression coverage. ```powershell dotnet test .\tests\pax.BlazorChartJs.pwtests\pax.BlazorChartJs.pwtests.csproj -- NUnit.Where="cat == FullSamples" ``` -------------------------------- ### Build Core Library Source: https://github.com/ipax77/pax.blazorchartjs/blob/main/AGENTS.md Build the core library of the project. This command is used to compile the main library components. ```bash dotnet build src\pax.BlazorChartJs\pax.BlazorChartJs.csproj ``` -------------------------------- ### Old Syntax for IndexableOption Initialization Source: https://github.com/ipax77/pax.blazorchartjs/blob/main/README.md Shows the older, more verbose syntax for initializing IndexableOption, which is still supported. This syntax was relevant before v0.8.1. ```csharp BorderColor = new IndexableOption(new List() { "rgba(255, 99, 132, 1)", "rgba(54, 162, 235, 1)" }), BorderWidth = new IndexableOption(1) ``` -------------------------------- ### Configure Services with Local Chart.js Source: https://github.com/ipax77/pax.blazorchartjs/blob/main/README.md Configure Chart.js services to serve Chart.js locally by providing custom URLs for the JavaScript files. ```csharp builder.Services.AddChartJs(options => { var version = "4.5.1"; options.ChartJsLocation = $"/_content/dsstats.weblib/js/chart.umd.min.js?v={version}"; options.ChartJsPluginDatalabelsLocation = "/_content/dsstats.weblib/js/chartjs-plugin-datalabels.min.js"; }); ``` -------------------------------- ### Run Serialization Tests Source: https://github.com/ipax77/pax.blazorchartjs/blob/main/AGENTS.md Execute serialization tests for the project. This ensures that data serialization and deserialization work correctly. ```bash dotnet test tests\pax.BlazorChartJs.tests\pax.BlazorChartJs.tests.csproj ``` -------------------------------- ### Scriptable Font Option with Object Initialization Source: https://github.com/ipax77/pax.blazorchartjs/blob/main/README.md Shows the alternative method for setting scriptable font options using object initialization. ```csharp Font = new Font { Size = 12 } ``` -------------------------------- ### Build and Run ChartJsConfig Serialization Benchmarks Source: https://github.com/ipax77/pax.blazorchartjs/blob/main/benchmarks/README.md Builds the benchmark project and runs the ChartJsConfig serialization benchmarks. Reports are generated in BenchmarkDotNet.Artifacts/results. ```powershell dotnet build benchmarks\pax.BlazorChartJs.benchmarks\pax.BlazorChartJs.benchmarks.csproj -c Release dotnet run -c Release --project benchmarks\pax.BlazorChartJs.benchmarks\pax.BlazorChartJs.benchmarks.csproj -- --filter *ChartJsConfigSerializationBenchmarks* ``` -------------------------------- ### Configure Services with CDN Locations Source: https://github.com/ipax77/pax.blazorchartjs/blob/main/README.md Configure the Chart.js services in Program.cs, specifying CDN locations for Chart.js and its plugins. ```csharp builder.Services.AddChartJs(options => { // default options.ChartJsLocation = "https://cdn.jsdelivr.net/npm/chart.js"; options.ChartJsPluginDatalabelsLocation = "https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2"; }); ``` -------------------------------- ### Run ChartJsConfig Serialization Benchmarks with Custom Iterations Source: https://github.com/ipax77/pax.blazorchartjs/blob/main/benchmarks/README.md Runs the ChartJsConfig serialization benchmarks with a specified number of warmup and measured iterations for a quick harness check. Reports are generated in BenchmarkDotNet.Artifacts/results. ```powershell dotnet run -c Release --project benchmarks\pax.BlazorChartJs.benchmarks\pax.BlazorChartJs.benchmarks.csproj -- --filter *ChartJsConfigSerializationBenchmarks* --warmupCount 1 --iterationCount 1 ``` -------------------------------- ### Resize and Export Chart as Image Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Defaults-and-Helpers Implement methods to resize the chart canvas to specified dimensions and to export the chart as an image data URL. Ensure the `chartComponent` is not null before calling these methods. ```csharp private ChartComponent? chartComponent; private string? imageDataUrl; private async Task ResizeChart() { if (chartComponent is not null) { await chartComponent.ResizeChart(640, 360); } } private async Task MakeImage() { if (chartComponent is not null) { imageDataUrl = await chartComponent.GetChartImage(); } } ``` -------------------------------- ### Run Default Regression Suite Source: https://github.com/ipax77/pax.blazorchartjs/blob/main/tests/README.md Execute the default regression test suite from the repository root. This run excludes the large 'FullSamples' category. ```powershell dotnet test .\tests\pax.BlazorChartJs.pwtests\pax.BlazorChartJs.pwtests.csproj ``` -------------------------------- ### Registering Time Chart Plugin and Configuring X-Axis Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Time-Charts This C# method registers a JavaScript plugin and configures the chart's X-axis to use a 'time' type with daily units. Ensure the chart configuration is reinitialized after updating options. ```csharp private async Task RegisterPlugin() { var module = await moduleTask!.Value.ConfigureAwait(false); await module.InvokeVoidAsync("registerPlugin").ConfigureAwait(false); chartConfig.Options = new ChartJsOptions { Scales = new ChartJsOptionsScales { X = new TimeCartesianAxis { Type = "time", Time = new TimeCartesianAxisTime { Unit = "day" } } } }; chartConfig.ReinitializeChart(); } ``` -------------------------------- ### Indexable Option with Collection Expressions Source: https://github.com/ipax77/pax.blazorchartjs/blob/main/README.md Illustrates the use of collection expressions for `IndexableOption` properties like `BorderColor` and `BorderWidth`. ```csharp BorderColor = ["rgba(255, 99, 132, 1)", "rgba(54, 162, 235, 1)"], BorderWidth = [1, 2] ``` -------------------------------- ### C# Configuration for Icon Plugin Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Callbacks-and-Plugins Define C# classes to serialize plugin options for Chart.js. These classes map to the expected JSON structure for custom plugin configurations. ```csharp public class IconsChartJsConfig : ChartJsConfig { public new IconsChartJsOptions? Options { get; set; } } public record IconsChartJsOptions : ChartJsOptions { public new IconsPlugins? Plugins { get; set; } } public record IconsPlugins : Plugins { public ICollection? BarIcons { get; set; } } public record ChartIconsConfig { public int XWidth { get; set; } public int YWidth { get; set; } public int YOffset { get; set; } public string ImageSrc { get; set; } = null!; } ``` -------------------------------- ### Time-Shaped Data for Line Dataset Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Time-Charts Format your data as an array of objects with 'x' as a date string and 'y' as a number for time-series line charts. ```csharp new LineDataset { Label = "My First Dataset", Data = [ new { x = "2022-09-07", y = 20 }, new { x = "2022-09-08", y = 40 }, new { x = "2022-09-09", y = 20 } ] } ``` -------------------------------- ### Run Browser Behavior Tests Source: https://github.com/ipax77/pax.blazorchartjs/blob/main/AGENTS.md Execute browser behavior tests using Playwright. This verifies the application's behavior in a browser environment. ```bash dotnet test tests\pax.BlazorChartJs.pwtests\pax.BlazorChartJs.pwtests.csproj ``` -------------------------------- ### Configure Global Chart.js Defaults Source: https://github.com/ipax77/pax.blazorchartjs/blob/main/README.md Set app-wide Chart.js defaults using AddChartJs, including colors, fonts, dataset-specific options, and global event callbacks. These defaults are applied before the first chart is constructed. ```csharp builder.Services.AddChartJs(options => { options.ChartJsCallbacksModuleLocation = $"{builder.HostEnvironment.BaseAddress}_content/my-app/chartJsCallbacks.js"; options.Defaults = new ChartJsDefaultsOptions() { Color = "#1f2937", BorderColor = "#d1d5db", Font = new Font { Family = "Inter, system-ui, sans-serif", Size = 12 }, Datasets = new ChartJsOptionsDatasets() { Bar = new { barPercentage = 0.8, categoryPercentage = 0.9 }, Line = new { tension = 0.25 } }, OnClick = ChartJsFunction.FromName("globalChartClick") }; }); ``` -------------------------------- ### Send Large Data via Binary Payload Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Large-Data-Updates Handles chart initialization events by creating XY point data and sending it as a binary payload using ChartJsBinaryPayload.FromXY. This method is optimized for large datasets to avoid JSON expansion. ```csharp private Task ChartEventTriggered(ChartJsEvent chartEvent) { if (chartEvent is ChartJsInitEvent) { var points = CreatePointData(); config.SetDatasetBinaryData( ChartJsBinaryPayload.FromXY("large-dataset", points)); } return Task.CompletedTask; } ``` -------------------------------- ### Enable Chart.js Events Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Events-and-HTML-Legends Configure ChartJsOptions to opt-in to various chart events like click, hover, resize, and animation progress. Ensure the relevant event properties are set to true. ```csharp Options = new ChartJsOptions { OnClickEvent = true, OnHoverEvent = true, OnResizeEvent = true, Animation = new Animation { OnProgressEvent = true, OnCompleteEvent = true }, Plugins = new Plugins { Legend = new Legend { OnClickEvent = true, OnHoverEvent = true, OnLeaveEvent = true } } } ``` -------------------------------- ### Custom ChartJs Location Configuration Source: https://github.com/ipax77/pax.blazorchartjs/blob/main/README.md Shows how to specify a custom local JavaScript file for Chart.js instead of using CDN links. This is useful for offline or specific version requirements. ```csharp options.ChartJsLocation = "mychart.js" ``` -------------------------------- ### Chart Initialization Event Handler Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Updating-Charts This C# code defines an event handler to track when the Chart.js component has been initialized, setting a flag to enable further updates. ```csharp private bool chartReady; private void ChartEventTriggered(ChartJsEvent chartJsEvent) { if (chartJsEvent is ChartJsInitEvent) { chartReady = true; } } ``` -------------------------------- ### Explicit Object List Data Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Getting-Started Shows how to explicitly create a list of objects for dataset data, accommodating various Chart.js data shapes. ```csharp IList data = [1, 2, 3]; ``` -------------------------------- ### Importing and Invoking Time Chart JavaScript Module Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Time-Charts Asynchronously import a JavaScript module to handle time chart functionalities. This is typically done during component initialization. ```csharp moduleTask = new(() => jsRuntime.InvokeAsync( "import", "./_content/pax.BlazorChartJs.samplelib/timeChart.js").AsTask()); ``` -------------------------------- ### Override External Target URL for Testing Source: https://github.com/ipax77/pax.blazorchartjs/blob/main/tests/README.md Set the 'PWTESTS_SampleBaseUrl' environment variable to debug against an already running or deployed target instead of the self-hosted local WASM test app. ```powershell $env:PWTESTS_SampleBaseUrl = "https://localhost:7082" dotnet test .\tests\pax.BlazorChartJs.pwtests\pax.BlazorChartJs.pwtests.csproj ``` -------------------------------- ### Updating Chart Dataset Data Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Getting-Started This C# method demonstrates how to update the data for datasets in an initialized chart. It checks a `chartReady` flag and uses `UpdateDatasetsDataSmooth` to apply changes. ```csharp private void Randomize() { if (!chartReady) { return; } Dictionary> dataByDatasetId = []; foreach (var dataset in chartJsConfig.Data.Datasets) { if (dataset is BarDataset barDataset) { dataByDatasetId[barDataset.Id] = barDataset.Data.Select(_ => (object)Random.Shared.Next(1, 10)).ToList(); } } chartJsConfig.UpdateDatasetsDataSmooth(dataByDatasetId); } ``` -------------------------------- ### Registering a Custom Chart.js Plugin from Blazor Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Callbacks-and-Plugins Invoke a JavaScript function from Blazor to register a Chart.js plugin. This requires a JavaScript module that handles the actual import and registration of the plugin. ```csharp private async Task RegisterPlugin() { if (moduleTask is not null) { var module = await moduleTask.Value.ConfigureAwait(false); await module.InvokeVoidAsync("registerPlugin").ConfigureAwait(false); } } ``` -------------------------------- ### Define Tooltip Callbacks in C# Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Tooltip-Callbacks Defines static TooltipCallbacks sets for content and color formatting. These sets store Chart.js function names for various tooltip parts. ```csharp private static readonly TooltipCallbacks ContentCallbacks = new() { Title = ChartJsFunction.FromName("formatTooltipContentTitle"), Label = ChartJsFunction.FromName("formatTooltipContentLabel"), Footer = ChartJsFunction.FromName("formatTooltipContentFooter") }; private static readonly TooltipCallbacks ColorCallbacks = new() { Title = ChartJsFunction.FromName("formatTooltipColorTitle"), Label = ChartJsFunction.FromName("formatTooltipContentLabel"), LabelColor = ChartJsFunction.FromName("tooltipLabelColor"), LabelTextColor = ChartJsFunction.FromName("tooltipLabelTextColor") }; ``` -------------------------------- ### Smoothly Replace Dataset with IDs Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Updating-Charts This C# code demonstrates how to update, add, remove, or reorder datasets and labels in a Chart.js chart using the SetDatasetsSmooth method. Ensure datasets have stable IDs for proper matching. ```csharp if (chartReady) { chartJsConfig.SetDatasetsSmooth( datasets: [ new RadarDataset { Id = "tychus", Label = "Tychus", Data = [0.82, 0.73, 0.65, 0.88, 0.70] }, new RadarDataset { Id = "nova", Label = "Nova", Data = [0.69, 0.86, 0.74, 0.79, 0.91] } ], labels: ["Artanis", "Dehaka", "Kerrigan", "Stetmann", "Vorazun"]); } ``` -------------------------------- ### Derived C# Options for Plugin Configuration Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Callbacks-and-Plugins Define C# classes that derive from `ChartJsConfig`, `ChartJsOptions`, and `Plugins` to enable configuration of Chart.js plugins directly from C# code. This provides type safety and IntelliSense. ```csharp public class CustomChartJsConfig : ChartJsConfig { public new CustomChartJsOptions? Options { get; set; } } public record CustomChartJsOptions : ChartJsOptions { public new CustomPlugins? Plugins { get; set; } } public record CustomPlugins : Plugins { public AnnotationsSettings? Annotation { get; set; } } ``` -------------------------------- ### Smooth Dataset Updates with Labels and Options Source: https://github.com/ipax77/pax.blazorchartjs/blob/main/README.md Use SetDatasetsSmooth to update, add, remove, and reorder datasets by ID in a single smooth chart update. Labels and options can be applied simultaneously. ```csharp chartJsConfig.Options ??= new ChartJsOptions(); chartJsConfig.Options.Responsive = false; chartJsConfig.SetDatasetsSmooth( datasets: [ new BarDataset { Id = "dataset-2", Label = "Dataset 2", Data = [ 4, 5, 6 ] }, new BarDataset { Id = "dataset-1", Label = "Dataset 1", Data = [ 3, 2, 1 ] } ], labels: ["Apr", "May", "Jun"], updateOptions: true); ``` -------------------------------- ### Configure Chart-Level Data Labels Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Data-Labels Enable and style shared data labels for all chart elements. This sets properties like color, background, border, and alignment. ```csharp chartJsConfig.Options!.Plugins!.Datalabels = new DataLabelsConfig { Display = "auto", Color = "#0a050c", BackgroundColor = "#cdc7ce", BorderColor = "#491756", BorderRadius = 4, BorderWidth = 1, Anchor = "end", Align = "start", Clip = true, Formatter = ChartJsFunction.FromName("formatPercent") }; ``` -------------------------------- ### JavaScript Module for Registering Date Adapter Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Time-Charts A minimal JavaScript module that imports and registers the 'chartjs-adapter-date-fns' bundle. This is essential for Chart.js to parse and handle date values on time scales. ```javascript export async function registerPlugin() { await import('./chartjs-adapter-date-fns.bundle.min.js'); } ``` -------------------------------- ### Custom Dataset Metadata for Tooltips Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Tooltip-Callbacks Defines a custom LineDataset that includes tooltip-specific metadata. This metadata can be accessed by JavaScript callbacks for richer tooltip content. ```csharp private sealed record CustomTooltipDataset : LineDataset { public IReadOnlyList TooltipPoints { get; init; } = []; } ``` -------------------------------- ### Register Chart.js Callback Module Location Source: https://github.com/ipax77/pax.blazorchartjs/blob/main/README.md Configure the location of the JavaScript callback module using AddChartJs. This allows referencing JavaScript callbacks from C# without serializing raw JavaScript. ```csharp builder.Services.AddChartJs(options => { options.ChartJsCallbacksModuleLocation = $"{builder.HostEnvironment.BaseAddress}_content/pax.BlazorChartJs.samplelib/chartJsCallbacks.js"; }); ``` -------------------------------- ### Apply Tooltip Callbacks in Blazor Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Tooltip-Callbacks Applies a predefined TooltipCallbacks set to the chart's tooltip options. This enables custom formatting and styling for tooltips. ```csharp Plugins = new Plugins { Tooltip = new Tooltip { Enabled = true, Callbacks = ContentCallbacks, DisplayColors = true } } ``` -------------------------------- ### Configure External Tooltip Rendering Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Tooltip-Callbacks Configures Chart.js to use a custom JavaScript callback for rendering tooltips. This provides full control over the tooltip's appearance and behavior. ```csharp Tooltip = new Tooltip { Enabled = false, External = ChartJsFunction.FromName("renderExternalTooltip") } ``` -------------------------------- ### Handle Chart Events in C# Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Events-and-HTML-Legends Branch on the derived event type in C# to handle specific chart events like initialization or resize. Use StateHasChanged() to update the UI after handling events. ```csharp private void EventTriggered(ChartJsEvent chartJsEvent) { if (chartJsEvent is ChartJsInitEvent initEvent) { latestInitEvent = initEvent; } if (chartJsEvent is ChartJsResizeEvent resizeEvent) { latestResizeEvent = resizeEvent; } StateHasChanged(); } ``` -------------------------------- ### Apply Per-Dataset Data Labels Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Data-Labels Override shared data label styles for individual datasets. This allows different colors, borders, placement, or formatter behavior per dataset. ```csharp for (var i = 0; i < chartJsConfig.Data.Datasets.Count; i++) { var dataset = chartJsConfig.Data.Datasets[i]; dataset.Datalabels = GetDataLabelsConfig(i); } chartJsConfig.ReinitializeChart(); ``` -------------------------------- ### Update Dataset with Packed Binary Payload (XY Data) Source: https://github.com/ipax77/pax.blazorchartjs/blob/main/README.md Use SetDatasetBinaryData with ChartJsBinaryPayload.FromXY to update a dataset with XY points from a packed binary payload. Supports ChartJsPoint spans or interleaved doubles. ```csharp var points = new ChartJsPoint[] { new(1, 20), new(2, 21), new(3, 22) }; chartJsConfig.SetDatasetBinaryData( ChartJsBinaryPayload.FromXY("dataset-2", points)); ``` -------------------------------- ### Registering Chart.js Callbacks Module Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Callbacks-and-Plugins Configure the Blazor application services to include the JavaScript module that exports Chart.js callbacks. This sets the location for the callback script. ```csharp builder.Services.AddChartJs(options => { options.ChartJsCallbacksModuleLocation = $"{builder.HostEnvironment.BaseAddress}_content/pax.BlazorChartJs.samplelib/chartJsCallbacks.js"; }); ``` -------------------------------- ### JavaScript Module for Plugin Registration Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Callbacks-and-Plugins This JavaScript module imports and registers a Chart.js plugin, such as `chartjs-plugin-annotation`. It exports a function that Blazor can call to perform the registration. ```javascript import * as annotationPlugin from './chartjs-plugin-annotation.min.js'; export async function registerPlugin() { await import('./chartjs-plugin-annotation.min.js'); Chart.register(annotationPlugin); } ``` -------------------------------- ### Reference JavaScript Callback in Dataset Background Source: https://github.com/ipax77/pax.blazorchartjs/blob/main/README.md Reference a registered JavaScript callback, like 'createRepeatFillPattern', for dataset properties such as BackgroundColor using ChartJsFunction.FromName. ```csharp new BarDataset() { Label = "Dataset 1", Data = new List() { 1, 2, 3 }, BackgroundColor = ChartJsFunction.FromName("createRepeatFillPattern") } ``` -------------------------------- ### Update Dataset with Packed Binary Payload (Y Data) Source: https://github.com/ipax77/pax.blazorchartjs/blob/main/README.md Utilize SetDatasetBinaryData with ChartJsBinaryPayload.FromY to update a dataset from a packed binary payload, avoiding JSON serialization for large data arrays. ```csharp chartJsConfig.SetDatasetBinaryData( ChartJsBinaryPayload.FromY("dataset-1", new float[] { 10, 12, 14 })); ``` -------------------------------- ### Chart Component with Event Handler Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Getting-Started This Razor snippet shows how to attach the `ChartEventTriggered` handler to the `ChartComponent` to receive initialization events. ```razor ``` -------------------------------- ### Update Tooltip Options Dynamically Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Tooltip-Callbacks Updates the chart's tooltip options dynamically in response to design changes or user interactions. This allows for real-time adjustments to tooltip behavior. ```csharp tooltip.Callbacks = callbacks; tooltip.Enabled = enabled; tooltip.External = external; tooltip.UsePointStyle = usePointStyle; chartJsConfig.UpdateChartOptions(); ``` -------------------------------- ### Blazor Component Integration for Icon Plugin Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Callbacks-and-Plugins Integrate a custom JavaScript plugin into a Blazor component. This involves invoking a JavaScript module to register the plugin and configuring icon data for chart elements. ```csharp var module = await moduleTask.Value.ConfigureAwait(false); await module.InvokeVoidAsync("registerImagePlugin").ConfigureAwait(false); chartJsConfig.Options!.Plugins!.BarIcons = [ new ChartIconsConfig { XWidth = 30, YWidth = 30, ImageSrc = "_content/my-app/images/alpha.png" }, new ChartIconsConfig { XWidth = 30, YWidth = 30, ImageSrc = "_content/my-app/images/beta.png" } ]; chartJsConfig.ReinitializeChart(); ``` -------------------------------- ### Update HTML Legend After Initialization Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Events-and-HTML-Legends Refresh the HTML legend after the chart is initialized by calling UpdateLegend(). This ensures the legend accurately reflects the chart's initial state. ```csharp private async Task ChartEventTriggered(ChartJsEvent chartJsEvent) { if (chartJsEvent is ChartJsInitEvent) { await UpdateLegend().ConfigureAwait(false); } } ``` -------------------------------- ### Reference JavaScript Callback in Axis Tick Format Source: https://github.com/ipax77/pax.blazorchartjs/blob/main/README.md Apply a JavaScript callback, like 'formatCurrency', to the Callback property of a LinearAxisTick using ChartJsFunction.FromName for custom tick formatting. ```csharp new LinearAxisTick() { Callback = ChartJsFunction.FromName("formatCurrency") } ``` -------------------------------- ### Referencing JavaScript Callbacks in C# Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Callbacks-and-Plugins Use `ChartJsFunction.FromName` in C# to reference named JavaScript functions exported from the registered callback module. This allows dynamic configuration of chart elements. ```csharp new BarDataset { Label = "Dataset 1", Data = [1, 2, 3], BackgroundColor = ChartJsFunction.FromName("createRepeatFillPattern") } ``` ```csharp new Legend { Labels = new Labels { Filter = ChartJsFunction.FromName("showLegendItem") } } ``` ```csharp new LinearAxisTick { Callback = ChartJsFunction.FromName("formatCurrency") } ``` -------------------------------- ### JavaScript Image Plugin for Chart.js Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Callbacks-and-Plugins Implement a Chart.js plugin to draw images on bar chart elements. This JavaScript code defines the plugin's behavior, including image caching and drawing logic. ```javascript const iconCache = new Map(); function getIcon(chart, src) { let image = iconCache.get(src); if (image) { return image; } image = new Image(); image.onload = () => chart.draw(); image.src = src; iconCache.set(src, image); return image; } export function registerImagePlugin() { Chart.register({ id: 'barIcons', afterDatasetDraw(chart, _args, icons) { const { ctx, scales } = chart; const bars = chart.getDatasetMeta(0).data; icons.forEach((icon, index) => { const bar = bars[index]; const image = getIcon(chart, icon.imageSrc); if (!bar || !image.complete || image.naturalWidth === 0) { return; } const value = Number(bar.$context.raw); const x = bar.x - (icon.xWidth / 2); const barEndY = value < 0 ? scales.y.getPixelForValue(0) : bar.y; const y = barEndY - icon.yWidth + icon.yOffset; ctx.drawImage(image, x, y, icon.xWidth, icon.yWidth); }); } }); } ``` -------------------------------- ### JavaScript Callback Implementation Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Callbacks-and-Plugins Define JavaScript functions within a module to handle Chart.js callbacks for tasks like formatting data, filtering labels, or creating custom visual elements. Ensure functions are exported. ```javascript const fillPatternCache = new WeakMap(); function createFillPattern(chart) { let pattern = fillPatternCache.get(chart); if (pattern) { return pattern; } const patternCanvas = document.createElement('canvas'); patternCanvas.width = 8; patternCanvas.height = 8; const patternContext = patternCanvas.getContext('2d'); patternContext.fillStyle = '#2563eb'; patternContext.fillRect(0, 0, 8, 8); patternContext.fillStyle = '#facc15'; patternContext.fillRect(0, 0, 4, 4); patternContext.fillRect(4, 4, 4, 4); pattern = chart.ctx.createPattern(patternCanvas, 'repeat'); fillPatternCache.set(chart, pattern); return pattern; } export const chartJsCallbacks = Object.freeze({ formatCurrency(value) { return `$${value}`; }, showLegendItem() { return true; }, createRepeatFillPattern(context) { return createFillPattern(context.chart); } }); ``` -------------------------------- ### Update Dataset Values by ID Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Updating-Charts This C# code shows how to efficiently update only the data values for existing datasets using their IDs with the UpdateDatasetsDataSmooth method. This is useful when dataset identity and styling remain unchanged. ```csharp Dictionary> dataByDatasetId = new() { ["nova"] = [0.91, 0.67, 0.79, 0.82], ["raynor"] = [0.73, 0.77, 0.71, 0.86] }; chartJsConfig.UpdateDatasetsDataSmooth(dataByDatasetId); ``` -------------------------------- ### Integrate HTML Legend Component Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Events-and-HTML-Legends Integrate a custom HTML legend component by hiding the default Chart.js legend and placing a Blazor legend next to the chart. This component inherits from LegendComponentBase. ```razor ``` -------------------------------- ### Reference a Chart Component in Razor Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Defaults-and-Helpers Maintain a reference to the `ChartComponent` in your Razor file to enable interaction with the rendered chart. This reference is typically declared using `@ref`. ```razor ``` -------------------------------- ### Bind Chart Event Callback in Razor Source: https://github.com/ipax77/pax.blazorchartjs/wiki/Events-and-HTML-Legends Bind the chart event callback in your Blazor component's Razor markup to a C# method. This allows you to receive and handle events triggered by the chart. ```razor ``` -------------------------------- ### Reference JavaScript Callback in Legend Filter Source: https://github.com/ipax77/pax.blazorchartjs/blob/main/README.md Use ChartJsFunction.FromName to reference a JavaScript callback, such as 'showLegendItem', for legend properties like Filter. ```csharp new Legend() { Labels = new Labels() { Filter = ChartJsFunction.FromName("showLegendItem") } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.