Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<DemoContainer>
<ApexChart TItem="SupportIncident"
Title="Incident Severity"
Options="options">

@foreach (var source in incidents.GroupBy(e => e.Source).OrderBy(e => e.Key))
{
<ApexPointSeries TItem="SupportIncident"
Items="source.OrderBy(e=>e.WeekNumber)"
Name="@source.Key.ToString()"
SeriesType="SeriesType.Heatmap"
Color="@GetColor(source.Key)"
ShowDataLabels="true"
XValue="@(e => e.WeekName)"
YAggregate="@(e => (int)e.Average(a=>a.Severity))" />
}

</ApexChart>
</DemoContainer>

@code {
private List<SupportIncident> incidents { get; set; } = SampleData.GetSupportIncidents();
private ApexChartOptions<SupportIncident> options = new ApexChartOptions<SupportIncident>
{
DataLabels = new DataLabels
{
Style = new DataLabelsStyle
{
Colors = ["function(opts) { return (opts.series[opts.seriesIndex][opts.dataPointIndex] < 30) ? '#00f' : '#f00'; }"],
},
},
};

private string GetColor(IncidentSource source)
{
switch (source)
{
case IncidentSource.Internal:
return "#FF0000";
case IncidentSource.ThirdParty:
return "#0000FF";
case IncidentSource.Integration:
return "#FF00FF";
default:
return "#008FFB";
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@
</Snippet>
</CodeSnippet>

<CodeSnippet Title="Data Labels Colors" ClassName=@typeof(Colors).ToString()>
<Snippet>
<DataLabelColors />
</Snippet>
</CodeSnippet>

<CodeSnippet Title=NoShade ClassName=@typeof(NoShade).ToString()>
<Snippet>
<NoShade />
Expand Down
65 changes: 65 additions & 0 deletions src/Blazor-ApexCharts/Internal/ChartUtilities.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
using System;
using System.Text.RegularExpressions;

namespace ApexCharts.Internal;

/// <summary>
/// Provides JavaScript related helper utilities for ApexCharts internal processing.
/// </summary>
internal static class ChartUtilities
{
/// <summary>
/// Regex that matches the beginning of a JavaScript function or arrow function (including optional leading comments).
/// </summary>
private static readonly Regex JsFunctionStartRegex = new(
@"^\s*(?:/\*[\s\S]*?\*/\s*|//[^\n]*\n\s*)*(?:async\s+)?(?:
function\b
| \([^)]*\)\s*=> # (args) =>
| [A-Za-z_$][\w$]*\s*=> # identifier =>
)",
RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace);

/// <summary>
/// Regex that matches immediately-invoked function expressions (IIFE) using the traditional function keyword.
/// </summary>
private static readonly Regex IifeFunctionRegex = new(
@"^\s*\(\s*(?:async\s+)?function\b",
RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.CultureInvariant);

/// <summary>
/// Regex that matches immediately-invoked arrow function expressions.
/// </summary>
private static readonly Regex IifeArrowRegex = new(
@"^\s*\(\s*(?:async\s+)?\([^)]*\)\s*=>",
RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.CultureInvariant);

/// <summary>
/// Determines whether the provided string appears to represent a JavaScript function
/// (standard function declaration, arrow function, or IIFE).
/// </summary>
/// <param name="candidate">The string to inspect.</param>
/// <returns>
/// <see langword="true"/> if the string structurally resembles a JavaScript function;
/// otherwise, <see langword="false"/>.
/// </returns>
internal static bool IsJavaScriptFunction(string candidate)
{
if (string.IsNullOrWhiteSpace(candidate))
return false;

// Quick cheap pre-filter: avoid regex if no plausible tokens
if (!(candidate.Contains("function", StringComparison.OrdinalIgnoreCase) ||
candidate.Contains("=>", StringComparison.Ordinal)))
return false;

// Direct structural check at start
if (JsFunctionStartRegex.IsMatch(candidate))
return true;

// IIFE patterns: (function(...) {...})(), (() => {...})(), etc.
if (IifeFunctionRegex.IsMatch(candidate) || IifeArrowRegex.IsMatch(candidate))
return true;

return false;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace ApexCharts.Internal;

/// <summary>
/// Converter for lists of strings that detects entries containing a JavaScript function definition
/// (case-insensitive search for the word "function") and serializes those as an object with the "@eval" key
/// so that ApexCharts interprets them as executable functions instead of plain strings.
///
/// Output behavior:
/// - Normal strings are written as JSON string elements inside the array.
/// - Strings representing functions are written as:
/// { "@eval": "function(x) { return x; }" }
///
/// Example:
/// C# input:
/// <code>
/// new List&lt;string&gt;
/// {
/// "Label 1",
/// "function(w) { return w; }",
/// "Another label"
/// };
/// </code>
///
/// JSON output:
/// <code>
/// [
/// "Label 1",
/// { "@eval": "function(w) { return w; }" },
/// "Another label"
/// ]
/// </code>
///
/// Note: Deserialization (Read) is not implemented because this converter is intended only for outgoing
/// serialization to the client.
/// </summary>
internal class ListStringOrFunctionConverter : JsonConverter<List<string>>
{
public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(List<string>);

public override List<string> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotImplementedException();
}

public override void Write(Utf8JsonWriter writer, List<string> value, JsonSerializerOptions options)
{
writer.WriteStartArray();

foreach (var item in value)
{
if (ChartUtilities.IsJavaScriptFunction(item))
{
writer.WriteStartObject();
writer.WritePropertyName("@eval");
JsonSerializer.Serialize(writer, item, options);
writer.WriteEndObject();
}
else
{
writer.WriteStringValue(item);
}
}

writer.WriteEndArray();
}
}
30 changes: 29 additions & 1 deletion src/Blazor-ApexCharts/Models/ApexChartOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1856,8 +1856,36 @@ public class DataLabelsBackground
public class DataLabelsStyle
{
/// <summary>
/// Fore colors for the dataLabels. Accepts an array of string colors (['#333', '#999']) or an array of functions ([function(opts) { return '#333' }]) (Each index in the array corresponds to the series).
/// Fore colors for the dataLabels (each index in the array corresponds to the series).
/// </summary>
/// <remarks>
/// Accepts:
/// <list type="bullet">
/// <item><description>An array of string colors (e.g. <c>{ "#333", "#999" }</c>)</description></item>
/// <item><description>An array of JavaScript functions serialized as strings (e.g. <c>{ "function(opts) { return '#333' }" }</c>)</description></item>
/// </list>
/// Each index in the array corresponds to the series index.
/// <para>Examples:</para>
/// <code>
/// // Using static colors
/// var style = new DataLabelsStyle
/// {
/// Colors = new List&lt;string&gt; { "#333", "#999" }
/// };
///
/// // Using JavaScript functions (strings will be passed through the converter)
/// var styleWithFunctions = new DataLabelsStyle
/// {
/// Colors = new List&lt;string&gt;
/// {
/// "function(opts) { return '#333'; }",
/// "function(opts) { return opts.seriesIndex % 2 ? '#999' : '#555'; }"
/// }
/// };
/// </code>
/// For short inline snippets use the inline code tag, e.g. <c>"#333"</c>.
/// </remarks>
[JsonConverter(typeof(ListStringOrFunctionConverter))]
public List<string> Colors { get; set; }

/// <summary>
Expand Down