Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initial implementation of onclick on bar chart. #25

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
129 changes: 80 additions & 49 deletions samples/TestApplication/Pages/Index.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,34 @@
<div class="row">
<button class="btn btn-primary" onclick="@UpdateChart">Update Chart </button>
</div>
<ChartJsBarChart ref="barChartJs" Chart="@blazorBarChartJS" Width="600" Height="300" />
<ChartJsBarChart ref="barChartJs" Chart="@blazorBarChartJS" Width="600" Height="300" ProcessClickEventResult="ProcessEvent" />
<div class="row">
Clicked Value: @clickedValue
</div>
</div>


@functions {

public ChartJSBarChart blazorBarChartJS { get; set; } = new ChartJSBarChart();
ChartJsBarChart barChartJs;
public string clickedValue = "";

protected override void OnInit()
{


blazorBarChartJS = new ChartJSBarChart()
{
ChartType = "bar",
CanvasId = "myFirstBarChart",
Options = new ChartJsOptions()
Options = new ChartJsBarChartOptions()
{
Text = "Sample chart from Blazor",
BorderWidth = 1,
Display = true,
BarPercentage = 0.5,
CategoryPercentage = 0.5,
// Title of the chart
Title = new ChartJsTitle()
{
Expand All @@ -46,40 +53,40 @@
}
},
// move the legend
Legend = new ChartJsLegend()
Legend = new ChartJsLegend()
{
Position = "top",
Display = true // set to false for hiding legend
},
Scales = new ChartJsScale()
{
XAxes = new List<ChartJsXAxes>()
Scales = new ChartJsScale()
{
XAxes = new List<ChartJsXAxes>()
{
new ChartJsXAxes()
{
new ChartJsXAxes()
Ticks = new ChartJsTicks()
{
Ticks = new ChartJsTicks()
{
BeginAtZero = true,
FontSize = 20
},
Position = "top"
}
},
YAxes = new List<ChartJsYAxes>()
BeginAtZero = true,
FontSize = 20
},
Position = "top"
}
},
YAxes = new List<ChartJsYAxes>()
{
new ChartJsYAxes()
{
new ChartJsYAxes()
Ticks = new ChartJsTicks()
{
Ticks = new ChartJsTicks()
{
BeginAtZero = true,
FontSize = 20,
Max = 50 // set a maxmimum value for this axis
}
BeginAtZero = true,
FontSize = 20,
Max = 50 // set a maxmimum value for this axis
}
}
},
Plugins = new ChartJsPlugins()
{
}
},
Plugins = new ChartJsPlugins()
{
// if you have enabled the plugin you can use these parameters, otherwise it will be ignored
Datalabels = new ChartJsDataLabels()
{
Expand All @@ -98,35 +105,59 @@
{
Labels = new List<string>() { "Red", "Blue", "Yellow", "Green", "Purple", "Orange" },
Datasets = new List<ChartJsBarDataset>()
{
new ChartJsBarDataset()
{
new ChartJsBarDataset()
{
Label = "# of Votes from blazor",
BackgroundColor = new List<string>(){"#cc65fe" },
BorderColor = "#cc65fe",
PointHoverRadius = 2,
Data = new List<double>(){ 19.187,12.2253,5.5,3,3,2}
},
new ChartJsBarDataset()
{
Label = "# of Likes from blazor",
BackgroundColor = new List<string>() {
"#a4cef0",
"#3498db",
"#95a5a6",
"#9b59b6",
"#f1c40f",
"#e74c3c",
"#34495e" },
BorderColor = "#36a2eb",
PointHoverRadius = 2,
Data = new List<int>(){ 30,10,15,13,13,12}.Select<int,double>(i=> i).ToList()
}
Label = "# of Votes from blazor",
BackgroundColor = new List<string>(){"#cc65fe" },
BorderColor = "#cc65fe",
PointHoverRadius = 2,
Data = new List<double>(){ 19.187,12.2253,5.5,3,3,2}
},
new ChartJsBarDataset()
{
Label = "# of Likes from blazor",
BackgroundColor = new List<string>() {
"#a4cef0",
"#3498db",
"#95a5a6",
"#9b59b6",
"#f1c40f",
"#e74c3c",
"#34495e" },
BorderColor = "#36a2eb",
PointHoverRadius = 2,
Data = new List<int>(){ 30,10,15,13,13,12}.Select<int,double>(i=> i).ToList()
}
}
},
//OnClick = (eventResult) =>
//{
// if (eventResult.First().DatasetIndex != -1)
// {
// foreach (var item in eventResult)
// {
// _clickedValue += $"Dataset Index: {item.DatasetIndex}, Index: {item.Index} ";
// }
// }
//}
};
}

public async Task ProcessEvent(List<ChartJsEventResult> result)
{
clickedValue = "";
if (result.First().DatasetIndex != -1)
{
foreach (var item in result)
{
clickedValue += $"Dataset Index: {item.DatasetIndex}, Index: {item.Index} ";
}
}
StateHasChanged();
Copy link
Owner Author

Choose a reason for hiding this comment

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

StateHasChanged() is necessary at this point. Took an hour to figure it out. 😃

return;
}

public async Task<bool> UpdateChart()
{
//Update existing dataset
Expand Down
3 changes: 2 additions & 1 deletion samples/TestApplication/Pages/_ViewImports.cshtml
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
@layout MainLayout
@using System.Collections.Generic;
Copy link
Owner Author

Choose a reason for hiding this comment

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

I think I don't need this. This was part of a frantic "Why isn't this working?" 1 hour

@layout MainLayout
1 change: 1 addition & 0 deletions samples/TestApplication/TestApplication.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<BlazorLinkOnBuild>true</BlazorLinkOnBuild>
<RunCommand>dotnet</RunCommand>
<RunArguments>blazor serve</RunArguments>
<LangVersion>7.3</LangVersion>
Expand Down
1 change: 1 addition & 0 deletions samples/TestApplication/_ViewImports.cshtml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
@using System.Net.Http
@using System.Collections.Generic;
@using Microsoft.AspNetCore.Blazor
@using Microsoft.AspNetCore.Blazor.Components
@using Microsoft.AspNetCore.Blazor.Layouts
Expand Down
3 changes: 2 additions & 1 deletion samples/TestApplication/wwwroot/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
<app>Loading...</app>

<!--<script src="css/bootstrap/bootstrap-native.min.js"></script>-->
<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<!--<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>
<!-- If you wanto to use the data labels plugin for ChartJS, NOTE: Plugin handling will change in the future (only an example for current use cases)-->
Expand Down
1 change: 1 addition & 0 deletions src/BlazorComponents/ChartJS/ChartJSBarChart.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;

namespace BlazorComponents.ChartJS
{
Expand Down
8 changes: 7 additions & 1 deletion src/BlazorComponents/ChartJS/ChartJSInterop.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using Microsoft.JSInterop;
using Microsoft.AspNetCore.Blazor;
using Microsoft.JSInterop;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace BlazorComponents.ChartJS
Expand Down Expand Up @@ -49,6 +51,10 @@ public static Task<bool> UpdatePieChart(ChartJSPieChart pieChart)
{
return JSRuntime.Current.InvokeAsync<bool>("BlazorComponents.ChartJSInterop.UpdatePieChart", new[] { pieChart });
}
public static Task<IEnumerable<ChartJsEventResult>> GetElementsAtEvent(string canvasId, UIMouseEventArgs evt)
{
return JSRuntime.Current.InvokeAsync<IEnumerable<ChartJsEventResult>>("BlazorComponents.ChartJSInterop.GetElementsAtEvent", new object[] { canvasId,evt});
}

}
}
21 changes: 21 additions & 0 deletions src/BlazorComponents/ChartJS/ChartJsBarChartOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BlazorComponents.ChartJS
{
public class ChartJsBarChartOptions : ChartJsOptions
{
/// <summary>
/// Percent (0-1) of the available width each bar should be within the category width. 1.0 will take the whole category width and put the bars right next to each other.
/// Default value 0.9
/// </summary>
public double BarPercentage { get; set; } = 0.9;
/// <summary>
/// Percent(0-1) of the available width each category should be within the sample width.
/// Default value 0.8
/// </summary>
public double CategoryPercentage { get; set; } = 0.8;
}
}
13 changes: 13 additions & 0 deletions src/BlazorComponents/ChartJS/ChartJsEventResult.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BlazorComponents.ChartJS
{
public class ChartJsEventResult
{
public int DatasetIndex { get; set; }
public int Index { get; set; }
}
}
1 change: 0 additions & 1 deletion src/BlazorComponents/Shared/ChartBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,5 @@ public void UpdateSize(int newWidth, int newHeight)
{
ChartJSInterop.UpdateSize(GetChart().CanvasId, newWidth, newHeight);
}

}
}
11 changes: 10 additions & 1 deletion src/BlazorComponents/Shared/ChartJsBarChart.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,22 @@

<div class="row">
<div class="container">
<canvas id="@Chart.CanvasId" width="@Width" height="@Height"></canvas>
<canvas id="@Chart.CanvasId" width="@Width" height="@Height" onclick="@GetEventInformation"> </canvas>
</div>
</div>

@functions {

[Parameter]
ChartJSBarChart Chart { get; set; }
[Parameter]
Func<List<ChartJsEventResult>, Task> ProcessClickEventResult { get; set; }

private async Task GetEventInformation(UIMouseEventArgs e)
{
var result = await ChartJS.ChartJSInterop.GetElementsAtEvent(Chart.CanvasId, e);
await ProcessClickEventResult(result.ToList());
}

protected override void OnAfterRender()
{
Expand Down
19 changes: 19 additions & 0 deletions src/BlazorComponents/dist/BlazorComponents.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,25 @@ window.BlazorComponents.ChartJSInterop = {
}

return true;
},
GetElementsAtEvent: function (canvasId,evt) {
let ctx = document.getElementById(canvasId);
evt.target = ctx;
let myChart = window.BlazorComponents.BlazorCharts.find(currentChart => currentChart.id === canvasId);
var result = [];
if (myChart) {
var values = myChart.chart.getElementsAtEvent(evt);
values.map(function (item) { result.push({ datasetIndex: item._datasetIndex, index: item._index })});
if (result.length < 1) {
result.push({ datasetIndex: -1, index: -1 });
}
return result;
}
else {
result.push({ datasetIndex: -1, index: -1 });
}
return result;

}
//UpdateLineChart: function (data) {

Expand Down