# ChartJS4 Integration

## Introduction

A modern Chart.js 4.x integration for Wisej.NET, featuring a fully redesigned architecture with improved serialization, inline JavaScript scripting, automatic plugin discovery, and an extensible options model — built to replace the limitations of previous ChartJS implementations.

## Technical Highlights

### Modern Serialization

Every options and dataset class exposes an `ExtensionData` dictionary that is serialized alongside all other properties. Any Chart.js option — including those from third-party plugins — can be passed through without modifying the library or subclassing anything.

```csharp
// Pass any Chart.js option not yet covered by a first-class property
chart.ChartOptions.ExtensionData = new Dictionary<string, object>
{
    ["interaction"] = new { mode = "nearest", intersect = false },
    ["parsing"] = new { xAxisKey = "date", yAxisKey = "value" }
};
```

#### Inline Scripting & Widget Functions

Supports server-defined JavaScript functions that are resolved client-side and bound to the Wisej widget context. Scriptable Chart.js options (per-point colors, dynamic labels, conditional formatting) can be expressed as named `WidgetFunction` references using the `(ctx)=>functionName` pattern, or as raw inline function strings assigned directly to any option.

```csharp
// Named function — define once, reference anywhere
chart.WidgetFunctions = new[]
{
    new ChartJS4.WidgetFunction
    {
        Name = "barColor",
        Source = "function(ctx) { return ctx.parsed.y > 100 ? 'crimson' : 'steelblue'; }"
    }
};

ds.ExtensionData = new Dictionary<string, object>
{
    ["backgroundColor"] = "(ctx)=>barColor"
};

// Or just assign an inline function string directly — no registration needed
ds.ExtensionData = new Dictionary<string, object>
{
    ["borderColor"] = "ctx => ctx.dataIndex % 2 === 0 ? 'red' : 'blue'"
};
```

#### Automatic Plugin Discovery

Scans all loaded assemblies at startup for embedded resources located in a folder named `ChartJsPlugins`. Any `.js` file placed there with **Build Action → Embedded Resource** is automatically registered and loaded — no code changes, no registration calls required.

```
MyApp/
├── ChartJsPlugins/
│   ├── chartjs-plugin-zoom.js        ← loaded automatically
│   └── chartjs-plugin-annotation.js  ← loaded automatically
```

#### Strongly-Typed Options Model

Provides dedicated C# classes for all major Chart.js options: scales, axes, plugins, legend, tooltip, animation, data labels, and all dataset types. `[DefaultValue]` attributes keep serialized payloads lean and the Visual Studio designer clean.

```csharp
chart.ChartOptions.Plugins.Legend.Position = "bottom";
chart.ChartOptions.Plugins.Title.Display = true;
chart.ChartOptions.Plugins.Title.Text = "Monthly Revenue";
chart.ChartOptions.Scales.Y.BeginAtZero = true;
chart.ChartOptions.Scales.Y.Title.Display = true;
chart.ChartOptions.Scales.Y.Title.Text = "USD";
```

#### Full Chart.js API Surface

Exposes the complete Chart.js runtime API as C# methods: `UpdateData`, `UpdateChart`, `SetDatasetVisibility`, `Hide`, `Show`, `SetActiveElements`, `ToBase64Image`, `GetImageAsync`, `Resize`, `Destroy`, and more.

```csharp
// Smooth animated data refresh without re-rendering the whole chart
chart.UpdateData(duration: 400);

// Export the chart as a PNG image
var image = await chart.GetImageAsync();
image.Save("export.png");

// Hide a dataset and show it again
chart.Hide(datasetIndex: 1);
chart.Show(datasetIndex: 1);
```

#### Design-Time Support

Renders a live preview chart in the Visual Studio designer with animations disabled, using a hardcoded sample dataset. All properties support full designer serialization and reset.

***

## ChartValue.NaN

`ChartValue.NaN` is a convenience value you can place into a dataset when you want Chart.js to **treat a data point as “missing / not-a-number”**.

In Chart.js (and therefore in **Wisej.Ext.Web.ChartJS4**), **`NaN` values are skipped**:

* The point is **not rendered**.
* For line charts, a `NaN` can **create a gap (break) in the line**, depending on the dataset option **`SpanGaps`**.

### When to use it

Use `ChartValue.NaN` when you need to:

* represent **missing measurements** in a time series,
* intentionally **break** a line between two sections,
* hide individual points without changing the number of labels.

***

### Example: Create a gap in a line chart

The example below shows a line dataset with a gap at the 4th point by using `ChartValue.NaN`. With `SpanGaps = false`, Chart.js will break the line at that point.

```csharp
// Example usage inside a Wisej form/page that contains a ChartJS4 control named "chartJS4".

// Labels (x-axis)
chartJS4.Data.Labels = new[] { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };

// Dataset with a missing value on "Thu"
var data = new object[]
{
	10,
	14,
	12,
	ChartValue.NaN, // <-- gap here
	18,
	16,
	20
};

// Configure dataset
var ds = new LineDataSet()
{
	Label = "Visitors",
	Data = data,
	SpanGaps = false, // <-- important: NaN will create a break in the line
};

// Apply
chartJS4.Data.Datasets.Clear();
chartJS4.Data.Datasets.Add(ds);
chartJS4.Type = ChartType.Line;
```

#### What you should see

* Points for **Mon, Tue, Wed** are connected.
* **Thu** is skipped.
* A new segment starts at **Fri** and continues to **Sun**.

***

### Use Cases

* Business dashboards with dynamic, data-driven charts
* Per-point conditional formatting using scriptable options
* Embedding third-party Chart.js plugins without rebuilding the library
* Real-time data visualization with smooth animated updates
* Exporting charts as PNG images server-side

***

This extension provides a production-ready, maintainable foundation for Chart.js 4.x in Wisej.NET applications, significantly reducing the friction of advanced chart customization while integrating natively into the Wisej component model.

## Live Demo

See diagrams powered by our ChartJS4 extension here: <https://demo.wisej.net/#Preview/ChartJS4/Features>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.wisej.com/docs/whats-new-in-4.1/chartjs4-integration.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
