Custom Component ChartJS

Samples & Hints for the ABMaterial framework, which combines a tuned Materialize CSS with the free programming tool B4J.
rwblinn
Site Admin
Posts: 195
Joined: 07 Oct 2017, 12:16

Custom Component ChartJS

Postby rwblinn » 04 Dec 2017, 17:30

ABMaterial (ABM) Custom Component ChartJS
v1.0.0 (Build (20171204)

Objectives
Create an ABM custom component to display line and bar charts.

The custom component build, CustomChartJS, is a minimal solution based upon the Chart.js project (Many thanks to the author(s)).
Chart.js has many features, to handle them all would rather go beyond my requirement for simple charts.
For additional requirements, lookup the Chart.js documentation and make the according changes to the class CustomChartJS.

Image

Notes
  • The ABM sample project is part of the B4JHowTos and is called B4JHowToABMCustomChartJS.
  • A comprehensive tutorial on how to create an ABM Custom Component can be found here.
  • Not the full code is shared in the description below.
  • Software versions used B4J v6.00, ABM 4.03 (Dragonfly).

Download
B4J Source Code - Example application .
The archive does not contain the full ABM folder structure, but only what is required for the examples (in folder custom/js).

To test the application, copy first the www folder (and only that folder) from the ABM Template folder.

Build Steps
Below is outlined how to create an ABM application with a custom component ChartJS.
Recommend to read the source of the example in the zip file.

Prepare
Build a new ABM project MyChartJSEx.
Create folder <path>\MyChartJS.
Copy the ABM Template folder to folder <path>\MyChartJSEx.
Rename abmtemplate.b4j and abmtemplate.b4j.meta to MyChartJSEx.b4j and MyChartJSEx.b4j.meta.
Make the initial changes to the classes according ABM guidance ( see ABM Demo Project ).
Changed to port 51050 in MyChartJSEx.b4j Process_Globals. The application URL is http://localhost:51050/MyChartJSEx.

Important JavaScript Hint: ensure the case is right in the JavaScript, i.e. true and not True, if and not If, type and not Type.
The case can change when copy & paste in the B4J IDE.

Chart.JS
Review the documentation to understand how to use & configure Chart.js.
The latest version of Chart.JS is on GitHub. Go here to explore the depth of Chart.js.

In the archive b4jhowtoabmcustomchartjs.zip, the chart.min.js is located in ...\Objects\www\js\custom\. This file can be used.
Copy file chart.min.js to folder <path>\MyChartJS\Objects\www\js\custom\

Copy also CustomChartJS.bas to <path>\MyChartJS.

Open the B4J IDE and add CustomChartJS.bas to the project (option Copy to project folder).

For this example, use the page ABMPageTemplate to create the charts page.
Make changes:
Sub BuildPage
Add one row with two cells which will contain a line chart and a bar chart

Code: Select all

...
'R1 1x6 + 1x6 = [CustomChartJS Line][CustomChartJS Bar]
page.AddRows(1,True,"").AddCellsOS(1,0,0,0,6,6,6,"").AddCellsOS(1,0,0,0,6,6,6,"")
'IMPORTANT to load the complete grid AND before you start adding components
page.BuildGrid
' Extra javascript files and CSSfiles, to be added in the BuildPage() method!
page.AddExtraJavaScriptFile("custom/chart.min.js")
...

Sub ConnectPage[b]

Code: Select all

...
' R1C1 - Single Line Chart
Dim custChartJSLine1 As CustomChartJS
Dim ChartProperties As Map = CreateMap("type":"line", _
                        "min":0, "max":100, _
                        "xaxisdisplay":true, "legenddisplay":true, _
                        "fill":true, _
                        "datasets":1, _
                        "label1":"Line 1", "backgroundcolor1":"#FF000025", "bordercolor1":"#FF0000", _
                        "data": JSONSampleData1)
custChartJSLine1.Initialize(page, "custChartJSLine1", ChartProperties)
page.Cell(1,1).AddComponent(custChartJSLine1.ABMComp)

' R1C1 - Bar chart which data is loaded using UpdateDataPoints
Dim custChartJSBar1 As CustomChartJS
Dim ChartProperties As Map = CreateMap("type":"bar", _
                        "min":0, "max":100, _
                        "xaxisdisplay":true, "legenddisplay":false, _
                        "fill":true, _
                        "datasets":1, _
                        "label1":"Bar 1", "backgroundcolor1":"#00FFFF18", "bordercolor1":"#00FFFF", _
                        "data": Null)
custChartJSBar1.Initialize(page, "custChartJSBar1", ChartProperties)
page.Cell(1,2).AddComponent(custChartJSBar1.ABMComp)

' refresh the page
page.Refresh
   
' Tell the browser we finished loading
page.FinishedLoading

' restoring the navigation bar position
page.RestoreNavigationBarPosition

' After the page finished loading, add some data points to the Bar chart (as data had been set to Null
custChartJSBar1.UpdateDataSet(page, "custChartJSBar1", JSONSampleData1)
page.Refresh

[b]Helpers

Example helpers for creating JSON data to be displayed. The values are generated randomly.

' One Dataset - Build the JSON string holding the chart data. The JSON string is used by the CustomChartJS to update the chart.

Code: Select all

Sub JSONSampleData1 As String
   Dim label As String
   Dim value As Double
   Dim sb As StringBuilder
   Dim NrOfSamples As Int = Rnd(5, 10)
   sb.Initialize
   sb.Append("[")
   For i = 1 To NrOfSamples
      label = i
      value = Rnd(0, 100)
      Dim s As String = $"{ "label":"${label}", "value1":${value} },"$
      sb.Append(s)
   Next
   sb.Append("]")
   Return sb.tostring.Replace("},]", "}]")
End Sub

' Two Datasets - Build the JSON string holding the chart data. The JSON string is used by the CustomChartJS to update the chart.

Code: Select all

Sub JSONSampleData2 As String
   Dim label As String
   Dim value1, value2 As Double
   Dim sb As StringBuilder
   Dim NrOfSamples As Int = Rnd(5, 10)
   sb.Initialize
   sb.Append("[")
   For i = 1 To NrOfSamples
      label = i
      value1 = Rnd(0, 50)
      value2 = Rnd(51, 100)
      Dim s As String = $"{ "label":"${label}", "value1":${value1}, "value2":${value2} },"$
      sb.Append(s)
   Next
   sb.Append("]")
   Return sb.tostring.Replace("},]", "}]")
End Sub

Run
Run the application

Code: Select all

ipaddress:51050/template

CustomChartJS
The Custom Component is defined in the class CustomChartJS.
As mentioned, it is a minimal wrapper for Chart.js. There are no error checks implemented. Be strickt on using the properties to create a chart.
Properties
Define the chart properties (key:value). The key must be in lowercase. See previous examples.
  • type - string "line" or "bar".
  • label - string showing the chart label in the data point tooltips or at the bottom if option legenddisplay is true.
  • min - double for the min value of the yaxis.
  • max -: double for the max value of the yaxis.
  • xaxisdisplay - display the xaxis labels.
  • legenddisplay - display the legend at the bottom of the chart.
  • fill - fill the chart with the background color.
  • backgroundcolorN - string with hex RRGGBBAA or rgba value rgba(R,G,B,A) with RGB between 0-255 and A between 0 - 1. N is the dataset number.
  • bordercolorN -: string with hex RRGGBB or rgb value rgba(R,G,B) with RGB between 0-255. N is the dataset number.
  • dataset - define the number of datasets to be used. must be 1 or more.
  • labelN - define the label for dataset N, i.e. datasets:1 then label1, datasets:2 then label1, label2.
  • data - String in JSON format holding an array of maps with the keys label (in "") and valueN. N is the dataset number.

Data Property Examples
datasets:1

Code: Select all

[ {"label":"label 1", "value1":1}, {"label":"label 2", "value1":2} ]
datasets:2

Code: Select all

[ {"label":"label 1", "value1":1, "value2":10}, {"label":"label 2", "value1":2, "value2":20}]

Set property data to Null if want to use sub UpdateDataSet (see below).

Be strickt on using the dataset number for values, bordercolor,

UpdateDataSet
This sub handles updating all the data of a chart.
Data - String in JSON format holding an array of maps with the keys label (in "") and value.
The data is assigned to a JS array which length is reset to 0. The number of datapoints is determined by the length of the map.
When building real-time charts, use this sub to update the data.

Data Example One Dataset

Code: Select all

[ { "label":"1", "value1":55.4 },{ "label":"2", "value1":55.6 } ]

Data Example Two Datasets

Code: Select all

[ { "label":"1", "value1":55.4, "value2":73 },{ "label":"2", "value1":55.6, "value2":32.1 } ]

Example calling with CustChartJS object

Code: Select all

custChartJSBar1.UpdateDataSet(page, "custChartJSBar1", JSONSampleData1)
using the sample JSON data.

Additional Chart Property Examples
Single Line Chart:

Code: Select all

Dim ChartProperties As Map = CreateMap("type":"line", _
                        "min":0, "max":100, _
                        "xaxisdisplay":true, "legenddisplay":true, _
                        "fill":true, _
                        "datasets":1, _
                        "label1":"Line 1", "backgroundcolor1":"#FF000025", "bordercolor1":"#FF0000", _
                        "data": JSONSampleData1)


Multiple Line Chart:

Code: Select all

Dim ChartProperties As Map = CreateMap("type":"line", _
                        "min":0, "max":100, _
                        "xaxisdisplay":true, "legenddisplay":true, _
                        "fill":false, _
                        "datasets":2, _
                        "label1":"Line 1", "backgroundcolor1":"#008B0018", "bordercolor1":"#008B00", _
                        "label2":"Line 2", "backgroundcolor2":"#00008B18", "bordercolor2":"#00008B", _
                        "data": JSONSampleData2)


Bar chart which data is loaded using UpdateDataSet:

Code: Select all

Dim ChartProperties As Map = CreateMap("type":"bar", _
                        "min":0, "max":100, _
                        "xaxisdisplay":true, "legenddisplay":false, _
                        "fill":true, _
                        "datasets":1, _
                        "label1":"Bar 1", "backgroundcolor1":"#00FFFF18", "bordercolor1":"#00FFFF", _
                        "data": Null)


Bar chart which data given:

Code: Select all

Dim ChartProperties As Map = CreateMap("type":"bar", _
                        "min":0, "max":100, _
                        "xaxisdisplay":True, "legenddisplay":false, _
                        "fill":true, _
                        "datasets":2, _
                        "label1":"Bar 1", "backgroundcolor1":"#00FF0018", "bordercolor1":"#00FF00", _
                        "label2":"Bar 2", "backgroundcolor1":"#00000018", "bordercolor1":"#000000", _
                        "data": JSONSampleData2)

Return to “ABMaterial”

Who is online

Users browsing this forum: No registered users and 1 guest