Giter Site home page Giter Site logo

sb-chart-block's Introduction

SB Chart block

banner

  • Contributors: bobbingwide
  • Tags: block, Chart, Line, Bar, Horizontal bar, Pie, stacked
  • Requires at least: 5.6.0
  • Tested up to: 6.5.3
  • Stable tag: 1.2.6
  • Requires PHP: 7.2.0
  • License: GPL-2.0-or-later
  • License URI: https://www.gnu.org/licenses/gpl-2.0.html

Displays a Chart for CSV content.

Description

Use the Chart block ( oik-sb/chart ) to display a chart.

Installation

  1. Upload the plugin files to the /wp-content/plugins/sb-chart-block directory, or install the plugin through the WordPress plugins screen directly.
  2. Activate the plugin through the 'Plugins' screen in WordPress

OR with the authority to install plugins

  1. In the block editor, open the block inserter.
  2. Search for the block by typing 'Chart'.
  3. Click on the 'Add block' button for the SB Chart block.
  4. The SB Chart block plugin will be installed and activated.
  5. And the block will be inserted into your content.

Frequently Asked Questions

What types of chart can I display?

So far...

  • Line and stacked line, with optional fill
  • Bar and stacked bar
  • Horizontal bar and stacked horizontal bar
  • Pie

How do I choose the chart colors?

There are 6 predefined color palettes: choose the color palette from a drop down list.

Use the Background color overrides and border color overrides fields to set custom color values.

What options are there?

Options to control the chart display are:

  • Stacked - Toggle on to stack line or bar charts
  • Begin Y axis at 0 toggle
  • Fill toggle for line charts
  • Time line toggle for a date based axis, with selectable Time unit (stepSize)
  • Y-axes for multi axis charts
  • Color palette dropdown
  • Background color overrides. Enter comma separated hex codes.
  • Border color overrides. Enter comma separated hex codes.
  • Opacity - set the opacity of the background colours.
  • Height of the chart, in pixels
  • Bar thickness in pixels
  • Tension - for curved line charts
  • Legend font size
  • X-axis font size

What Chart script does it use?

v1.2.6 delivers chartjs v4.4.2 and chartjs-adapter-date-fns v3.0.0

What do I need to search for to find the block?

Chart or SB Chart

What if my first language is not English?

If your first language is not English then you could try:

  • French - graphique
  • German - Diagramm
  • Dutch - grafiek
  • Italian - grafico
  • Spanish - gráfico

Do I need to build this block?

No. The plugin is delivered with the production version of the block. If you do wish to modify the code then you can find instructions in the src folder.

Are there shortcodes available?

Charts can be embedded with the shortcode chartjs. The general syntax is as follows:

[chartjs attribute="attribute value"]CSV content[/chartjs]

Several attributes can be added at the same time. Example:

[chartjs attribute1="attribute1 value" attribute2="attribute2 value"]CSV content[/chartjs]

Here's the list of supported attributes:

    • backgroundColors (string): list of custom background colors (separated by comma) to use for datasets. For example, if there are 3 datasets (d1, d2 and d3) and we want d1 to use the color #0000FF, d2 to use #FFFF00 and d3 to use #008000, the value of the attribute must be #0000FF,#FFFF00,#008000. If some colors are missing (ex.: #0000FF,,#008000), default colors from the theme (set with the attribute theme) are used as fallback (#0000FF,second theme color,#008000); default is no custom colors used
    • barThickness (int): thickness (in pixels) of a bar in bar charts; default is the default Chart.js thickness
    • beginYAxisAt0 (bool): make sure the Y axis begins at 0; default is false
    • borderColors (string): list of custom border colors (separated by comma) to use for datasets. See the description of the attribute backgroundColors for more details; default is the value of the attribute backgroundColors
    • class (string): class or classes to be added to the chart container; default is an empty string
    • fill (bool): fill the area under the line; default is false
    • height (int): chart height (in pixels); default is the default Chart.js height
    • indexAxis (string): axis to use as index; choices are x, y; note that y is automatically used for horizontal bar charts; default is x
    • max (float): maximum value for Y axes; default is no maximum value
    • opacity (float): opacity to apply to the lines or bars; it must be between 0 and 1; default is 0.8
    • showLine (bool): show (draw) lines; default is true
    • stacked (bool): enable stacking for line/bar charts; default is false
    • tension (float): add Bezier curve tension to lines; when set to 0, lines are straight; default is 0
    • theme (string): theme used for the chart colors; choices are Chart, Gutenberg, Rainbow, Tertiary, Visualizer, Wordpress; default is Chart
    • time (bool): add support for time line on the X axis; default is false
    • timeUnit (string): time unit to use if time line is enabled; choices are year, quarter, month, week, day, hour, minute, second, millisecond; default is hour
    • type (string): type of chart; choices are bar, horizontalbar, line, pie; default is line
    • yAxes (string): list of Y axes to which the datasets are bound. It allows to enable multi-axis charts. For example, if there are 3 datasets (d1, d2 and d3) and we want d1 to use the first Y axis, and d2 and d3 to use the second Y axis, the attribute value must be y,y1,y1; default is an empty string, so multi-axis feature is disabled and all datasets are automatically bound to the first (and only) Y axis y

Here's a fully functional example:

[chartjs backgroundColors="#008000" fill="true" opacity="0.35" tension="0.2" theme="Visualizer" time="true" timeUnit="month" yAxes="y,y1"]Year,Sales,Expenses
2020-08,5421.32,1151.21
2021-02,4823.99,887.23
2021-03,4945.32,958.00
2021-10,7086.65,1854.35
2022-05,7385.21,2009.01
[/chartjs]

Here's the result:

Chart rendered with settings from the shortcode example

Are there hooks available for developers?

The following filter hooks are available:

    • sb_chart_block_content: filter allowing to manipulate the content before it's processed
    • sb_chart_block_options: filter allowing to add custom Chart.js options

For example, to customize the legend, use the sb_chart_block_options filter in your functions.php theme file as follows:

function customize_legend($options, $atts, $series) {
	$custom_options = to_array($options);

	$custom_options['plugins']['legend']['labels']['font']['size'] = 16;
	$custom_options['plugins']['legend']['labels']['color'] = '#0000FF';

	return json_decode(json_encode($custom_options));
}
add_filter('sb_chart_block_options', 'customize_legend', 10, 3);

function to_array($data) {
	$array = [];

	if (is_array($data) || is_object($data)) {
		foreach ($data as $key => $value) {
* 			$array[$key] = (is_array($value) || is_object($value)) ? to_array($value) : $value;
		}
	} else {
		$array[] = $data;
	}

	return $array;
}

Here's another way (without array conversion):

function customize_legend($options, $atts, $series) {
	if (!isset($options->plugins)) $options->plugins = new stdClass();
	if (!isset($options->plugins->legend)) $options->plugins->legend = new stdClass();
	if (!isset($options->plugins->legend->labels)) $options->plugins->legend->labels = new stdClass();
	if (!isset($options->plugins->legend->labels->font)) $options->plugins->legend->labels->font = new stdClass();

	$options->plugins->legend->labels->font->size = 16;
	$options->plugins->legend->labels->color = '#0000FF';

	return $options;
}
add_filter('sb_chart_block_options', 'customize_legend', 10, 3);

Screenshots

  1. Line chart - Gutenberg theme colors
  2. Bar chart - Chart theme colors
  3. Horizontal bar chart - Tertiary theme colors
  4. Pie chart - Visualizer theme colors
  5. Chart type toolbar selection

Upgrade Notice

1.2.6

Upgrade for PHP 8.3 support. Now uses chart.js v4.4.2

Changelog

1.2.6

  • Changed: Update wp-script and chart.js #35
  • Tested: With WordPress 6.5.3 and WordPress Multisite
  • Tested: With PHP 8.3
  • Tested: With PHPUnit 9.6

sb-chart-block's People

Contributors

bobbingwide avatar misaki-web avatar

Stargazers

PS avatar Huub avatar  avatar Cory Birdsong avatar Reinhard Jung avatar

Watchers

 avatar  avatar  avatar

sb-chart-block's Issues

Notice: Undefined offset in libs\class-sb-chart-block.php on line 282

Notice: Undefined offset: 15 in C:\apache\htdocs\wordpress\wp-content\plugins\sb-chart-block\libs\class-sb-chart-block.php on line 282.

Explanation

This is produced on the front end when there are more data values than there are legends.

Solution

Use sb_chart_block_array_get() to set a default value of undefined when the legend is not defined.

Unwanted wpautop - do we need to use wp_add_inline_script() ?

Two problems here:

  1. How to deal with unwanted wpautop processing.
  2. Is using wp_add_inline_script the preferred method over hand cranking inline script tags?

In the prototyped implementation, if oik-css is activated, it's necessary to "Disable automatic paragraph creation" otherwise the <script> tag gets wrapped in an unwanted <p> tag.

Originally posted by @bobbingwide in #1 (comment)

Allow two decimal places for Opacity

In the block editor the Opacity setting doesn't allow numbers with two decimal places. The shortcode does.

See https://s.b/oikcom/block_example/chart-block-multiple-y-axis-scales/
where the opacity is set to 0.35 in the shortcode but can only be specified as 0.3 in the block editor.
As soon as you type 0.35 it gets trimmed to 0.3.

Requirement

  • Allow Opacity setting to be specified to 2 decimal places

Also. Check how Gutenberg range controls are supposed to appear.

The slider part is missing.
image

Chart.js adapter not included in admin pages

When adding a chart using the Gutenberg block, we get the following error if time line is enabled:

Error displaying chart. Please check your dates then choose Refresh, or change the Time unit. [...]
Message: This method is not implemented: Check that a complete date adapter is provided.

JavaScript error when `stacked` or `beginYAxisAt0` are false

I'm not quite sure when this started happening but the JavaScript code generated in the PHP code to set the y axis attributes stacked and beginAt0 were not setting values in my local development environment, leading to a JavaScript error.

The solution is to implement a simple boolstring() method to return a string literal of true or false depending on the value of the passed parameter. This makes the syntax of the generated JS valid.

Add support for charts used for performance reporting

In my perf routine I'm using the SB_Chart_Block to display performance scores taken over a period of time.
To make it look a bit nicer I want to be able to change the colours of the line points or bars to reflect the score.

  • <50 red
  • < 90 amber
  • <= 100 green

To achieve this, I need to be able to pass in a number of other attributes

  • max - to set the max to 100
  • backgroundColor - to set the colour for each item charted
  • borderColor - to set the border colour for each item charted
  • showLine - to turn of lines between points.

ie. Make it look something like this
image

Multi axis line chart

Here's an example of multi axis line chart in the Chart.js documentation:

multi-axis-line-chart

Scales settings must have y and y1, and each dataset must be linked to a specific axis. Here's a very quick and dirty way just to get an idea of what's needed:

# In the `functions.php` theme file:
function chartjs_filter($output, $tag, $atts) {
	if ($tag == 'chartjs') {
		$custom_scales = <<<SCALES
			scales: {
			  y: {
				type: 'linear',
				display: true,
				position: 'left',
			  },
			  y1: {
				type: 'linear',
				display: true,
				position: 'right',
			  },
			}
		SCALES;
		$output = str_replace('}} };', '}},' . $custom_scales . '};', $output);
		$output = str_replace('datasets:[{', 'datasets:[{"yAxisID": "y",', $output);
		$output = str_replace('"showLine":true}]};', '"showLine":true,"yAxisID":"y1"}]};', $output);
	}
	
	return $output;
}
add_filter('do_shortcode_tag', 'chartjs_filter', 10, 3);

The shortcode to test:

[chartjs type="line"]Year,Dataset1,Dataset2
2016,125,2451.32
2017,158,1878.00
2018,215,1256.32
2019,325,34521.32
2020,500,1896.32
2021,251.32,2725.32[/chartjs]

The result:

multi-axis-line-chart-demo

Fatal error due to call to bw_trace2()

Reported in an email.

I really like your SB chart block as a great chart tool but after the last update it is throwing a critical error on my site.
An error of type E_ERROR was caused in line 396 of the file

//wp-content/plugins/sb-chart-block/libs/class-sb-chart-block.php.
Error message: Uncaught Error: Call to undefined function bw_trace2() in wp-content/plugins/sb-chart-block/libs/class-sb-chart-block.php:396

Stack trace: 0 /wp-content/plugins/sb-chart-block/libs/class-sb-chart-block.php(298): SB_chart_block->transpose(Array) 
1 wp-content/plugins/sb-chart-block/libs/class-sb-chart-block.php(75): SB_chart_block->prepare_content(‘x,Suicides – Ag…’) 
2 wp-content/plugins/sb-chart-block/sb-chart-block.php(169): SB_chart_block->render(Array, ‘x,Suicides – Ag…’) 
3 wp-content/plugins/sb-chart-block/sb-chart-block.php(104): sb_chart_block_shortcode(Array, ‘x,Suicides – Ag…’, ‘chartjs’) 
4 wp-includes/class-wp-block.php(256): sb_chart_block_dynamic_block(Array, ‘\n Norm

Implement a Chart block using chart.js

In https://github.com/wppompey/pompey-chart we've developed a generic [chart] shortcode using chartist.js.
But there are were couple of problems with it.
I want to be able to deliver a Chart block, as a Single Block plugin.

Requirements

  • Chart block displaying Line, Bar and Pie charts
  • Uses content in the form of a CSV file
  • Source CSV content to have same structure as for the [chart] shortcode.
  • Similar display capabilities as Visualizer.

Proposed solution

  • Use current version of Chart.js - 2.9.4, even though there's been a few beta 3 versions.
  • Deliver [chartjs] shortcode.
  • Deliver server side rendered version of the Chart block.
  • Deliver interactive Chart block in the editor.
  • Chart block to be built as a single block plugin.
  • Code to not be dependent upon other plugins.

Chart types to be supported: see https://www.chartjs.org/samples/latest/

Type Subtypes Support
Line Stacked, Area, Dots only With multiple series
Bar Stacked With multiple series
Horizontal bar Stacked With multiple series - obviously
Pie Donut Multiple series - optional

Support chartjs v3.1.0 - now v3.6.2 - now 3.7.1 - now 3.9.1

When I started developing with chartjs, version 2.9.4 was the stable version and 3.0 was in beta.
In the April 2021 v3.0 was released.
When I started adding the timeline logic the latest version was 3.6.2.
Now the latest version is v3.7.1

Requirements

  • Switch to using v3.7.1

Proposed solution

  • Download v3.7.1 to replace both the production and debug versions
  • Apply any changes to the calling routines as mentioned in the Migration Guide
  • Test editor and front end versions

Test with

  • WordPress 5.9.1 and WordPress Multi Site
  • Gutenberg 12.6.0
  • PHP 8.0
  • PHPUnit 9

Warning: Use of undefined constant FILTER_VALIDATE_BOOL in PHP 7.4

FILTER_VALIDATE_BOOL was added for PHP 8.0 as an alias for FILTER_VALIDATE_BOOLEAN.
The preferred is now BOOL rather than BOOLEAN

We need to change the code to support PHP 7.4 to avoid multiple warnings.

Warning: Use of undefined constant FILTER_VALIDATE_BOOL - assumed 'FILTER_VALIDATE_BOOL'
(this will throw an Error in a future version of PHP) in
/home/customer/www/oik-plugins.com/public_html/wp-content/plugins/sb-chart-block/libs/class-sb-chart-block.php on line 196

per-row color control

Dear I started using this great plugin.
The only control I missing in my first chart would be more fine-tuned control over individual elements' color.

A desirable feature would be to support a _color_ "meta-column" within CSV data which would be ignored as data but be considered as the preferred color of a given line/pie/bar.

Extract utility functions into a library file

From a comment in #21 (comment)

I'm thinking of extracting the utility functions from the main plugin file into a library file.

I've got some non WordPress code that also creates charts.
Functions needed:

  • sb_chart_block_array_get
  • sb_chart_block_get_csv
  • sb_chart_block_array_replace
  • sb_chart_block_merge_objects

Submit the plugin to wordpress.org

I used the block plugin validator to check the plugin.

https://wordpress.org/plugins/developers/block-plugin-validator/

It had a couple of warnings

Please use a unique block namespace. Namespace oik-sb is already used by SB Children block.

Blocks should use a namespace that is unique to the plugin or its author. It appears this namespace is already in use by another author. If that’s not you then please ensure you choose a unique namespace for your blocks. The plugin slug is a good choice.

Found 18 KB of PHP code. This might not be a block plugin.
Block plugins should keep the PHP code to a minimum. If you need a lot of PHP code, your plugin probably belongs in the main Plugin Directory rather than the Block Directory.

No translations are loaded for the scripts.
Block plugins should use wp_set_script_translations to load translations for each script file. Learn more about internationalization.

I submitted the plugin anyway. sb-chart-block v0.1.1

https://wordpress.org/plugins/developers/add/

There were 73 plugins in the queue to be reviewed.

Create PHPUnit test cases for server code

Some not insignificant changes are currently being developed. It's about time we implemented some regression testing capability for the PHP code.

Requirements

  • Regression testing capability for PHP code.
  • Tests to cover expected settings for each attribute.
  • Tests to cover good and bad CSV data for the chart.
  • Tests to be developed before any new solutions are merged.

Proposed solution

  • Develop In Situ PHPUnit tests similar to those for other plugins oik plugins that deliver shortcodes / blocks.
  • But no need to implement tests for internationalization.
  • Generated .html test results files should be easy to validate against ChartJS.

Add support for charts with a proper time based axis

chartJS supports charts plotted with a proper timeline.

Requirements

  • To be able to plot charts with a time based x-axis
  • where the measurements are taken at a different time of the month, day etc
  • and where some measurements may be missing
  • to support a variety of date/time formats for the readings

Proposed solution

  • Upgrade to chart.js v3.6.2 - see #11
  • Implement chartjs-adapter-date-fns v2.0.0 from https://github.com/chartjs/chartjs-adapter-date-fns
  • Add some mechanism to indicate the use of type: 'time' on the x axis
  • Other changes as required to enable chart.js to work without too much hassle
  • Consider deprecation logic so that blocks don't break when new attributes are added.
  • Test with WordPress 5.9 - without Gutenberg

Improve parsing of the chart content in the block editor

In #23 server logic was added to improve the parsing of the CSV content so that

  1. missing values were treated as null
  2. commas in double quoted strings were not treated as separators.

The block editor needs to replicate this logic

Example 1.

Year,Dataset1,Dataset2,Dataset3
    2018,250
    2019,,175
    2020,350,125,75

should produce a chart like this.
image

Dataset 1 has two points: 250 and 350 but a gap for 2019
Dataset 2 has two points: 175 and 125 for 2019 and 2020 - so a line
Dataset 3 has only 1 point: 75

Example 2.

Year,"Dataset 1: Lorem ipsum, dolor sit","Dataset 2: id dapibus, dui rhoncus"
    2017,9,12
    2018,5,17
    2019,10,15
    2020,12,19
    2021,14,22
    2022,9,23

Labels for the legends should be:
image

Support chart.js v4.2.0

Chartjs v4.0.1 was released on 14th November 2022.

Requirements

  • sb-chart-block should be updated to support this version of chart.js
  • I don't yet know if there's going to be a new version of chartjs-adapter-date-fns.
  • that may need to be updated as well.

Proposed solution

  • Develop PHPUnit tests for sb-chart-block #25
  • Apply updates to chart.js v4.0.1
  • Re-run PHPUnit tests
  • Retest the example blocks in both the block editor and front end.

Be able to customize the chart font

The Chart.js documentation gives an example about font customization using the options object when creating a chart instance:

let chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        plugins: {
            legend: {
                labels: {
                    font: {
                        size: 14
                    }
                }
            }
        }
    }
});

SB Chart Block creates the instance here:

function get_newChart() {
$type = $this->atts['type'];
return "var myLineChart = new Chart(ctx, { type: '$type', data: data, options: options });";
}

@bobbingwide There are many ways to add font customization, if you are open to this new feature:

  1. in the Gutenberg block settings
  2. as new shortcode attributes (like labelFontSize="16")
  3. as a more generic way to set any option supported by Chart.js, for example a textarea in the Gutenberg block settings or a new shortcode attribute like moreOptions="...".

The third point could be done like that (brainstorming, so not tested):

Shortcode:

[chartjs ... moreOptions='...json...']data[/chartjs]

Example:

[chartjs ... moreOptions='{"plugins":{"legend":{"labels":{"font":{"size":14}}}}}']data[/chartjs]

PHP:

$this->atts['moreOptions'] = isset( $this->atts['moreOptions'] ) ? json_decode($this->atts['moreOptions'], true) : [];

json_decode returns null if the string can't be decoded, but it can also return any PHP type, so it may be a good idea to ensure we have an array:

$this->atts['moreOptions'] = $this->validate_moreoptions( $this->atts['moreOptions'] );
function validate_moreoptions( $data ) {
    return is_array($data) ? $data : [];
}

Then, we could merge $this->atts['moreOptions'] with the options used to create the chart instance.

Objects could be used instead of arrays. I see that $options is a string, but there's a TODO note about it:

* @TODO
* Convert to using objects and json_encode.
*
* @return string
*/
function get_options() {
$options_html='';
$options_html="var options = {";
$options = '';

Add options to control the chart display in the editor and front end

For a Minimum Viable Product we need to add a number of options to control the display of the charts.

  • Chart height
  • stacked line or bar chart
  • begin y Axis at 0 ?
  • area chart
  • Toolbar icons to choose the chart type
  • Option to disable redraw while entering data.

Proposed solution

Implement options as attributes in both the editor and the server side rendering logic.

Attribute Option setting Value Purpose
beginAtZero scales.yAxes.ticks.beginAtZero true Start the axis from 0
stacked scales.yAxes.stacked & scales.xAxes.stacked true Show a stacked line / bar chart.
maintainAspectRatio maintainAspectRatio bool false to allow the height to be set

Other attributes

Attribute Value Purpose
height nnnpx Set the chart height on the `
tag.
fill bool Convert line chart to area when true.

For documentation see:

https://www.chartjs.org/docs/latest/charts/line.html?h=stacked

Chart height

According to the documentation of chart.js you need CSS like this if you want limit the chart height in a responsive display.
You also need to set maintainAspectRatio: false.

.chartjs { width: 90%; position: relative; height: 250px;}

Workaround
With v0.0.3 I used custom CSS defined using oik-css's CSS block.

This CSS will no longer be necessary once this has been implemented.
It appears that it's not necessary to set the aspectRatio when maintainAspectRatio is false.

Register block using `apiVersion:2`, internationalize, translate and localize

The oik-sb/chart block is registered using v1 of the registerBlockType API.
It needs to be:

  • registered using apiVersion: 2
  • internationalized,
  • translated
  • and localized.

Requirements

  • Register the block using block.json
  • Ensure the block can be selected
  • Add some color and typography settings where applicable
  • Add text align capability where applicable
  • Internationalized and localized

Proposed solution

  • Update package.json
  • Change block.json for each block
  • Change index.js to register the block from the server registration
  • Add logic to support deprecated versions of the block
  • Change the server to register the block from block.json
  • Update node_modules and rebuild
  • (re) Internationalize and (re) localize
  • remove webpack.config.js - it's no longer necessary

The scope is the source code of the plugin, not the chart.js package

Process for updating node_modules

  1. Remove the existing node_modules folder
  2. npm install
  3. npm install @wordpress/scripts --save-dev

See https://developer.wordpress.org/block-editor/reference-guides/packages/packages-scripts/

Update chart.js, wp-scripts, rebuild and test with WordPress 6.3 & 6.4

sb-chart-block needs updating because:

  • Latest chart.js version is 4.3.3, ( Aug 2023)
  • Latest chartjs-adapter-date-fns is v3.0.0 ( Dec 11, 2022)
  • WordPress 6.3 was released on 8th August 2023.
  • WordPress 6.4-RC1 was released on 17th October 2023. Final release due 7th Nov
  • wp-scripts latest version is v26.9.0

Proposed solution

  • Update wp-scripts to the latest version
  • Rebuild
  • Test with WordPress 6.3
  • Update chart.js to the latest version - see #26
  • Rebuild ?
  • Test with WordPress 6.3
  • Update chartjs-adapter-date-fns to the latest version - see #26
  • Test with WordPress 6.4

Gutenberg no longer delivers chartLine in the icons package

As of version 4.0.0 (2021-05-20) the icon package no longer includes the chartLine icon.
This was a breaking change.

Removed icons: camera, chartLine, closeCircleFilled, controlsRepeat, expand, as they all have better existing alternatives, and were unused by the block editor. Instead of camera, use capturePhoto. Instead of chartLine, use chartBar or trendingUp or trendingDown, instead of closeCircleFilled, use close, instead of controlsRepeat which was used for Reusable Blocks, consider reusableBlock, and instead of expand, use fullscreen.

See https://github.com/WordPress/gutenberg/blob/41e1ca829be98fd04d1fc859447b1ec769790b66/packages/icons/CHANGELOG.md

We can't use chartBar since we're already using that.
Either try trendingUp or extract chartLine into our own source.

Choose a nice set or sets of Colours for up to 16 series

Over a number of Slack conversations with @AndrewMLeonard we created 4 different colour themes ( or palettes) to use in the charts.

  • Initially I've named them based on the source of the colours called these: Gutenberg, Chart, Chartist or Tertiary, and Visualizer.
  • They have varying numbers of colours.
  • The Chart theme has different opacities for the border and background
  • This is obvious in the bar chart but not in the line chart when filled.
  • I've also noted that Chart.js comes with a predefined set of colours.

Here's a screen capture showing examples of each chart type currently implemented and each colour palette.
image

Requirements

  • Ability to choose the colour palette to use per chart
  • Ability to define your own colours
  • Ability to set the opacity for the chart
  • Ability to use the Chart.js default colours for the chart palette.
  • Better names for the palettes
  • Same colours to be used in the editor as in the server rendered charts.

Proposed solution

  • Investigate a few more chart color options: Google charts, Excel
  • Implement as many palettes as deemed necessary
  • Allow the user to set a start index
  • Allow the user to define the opacity
  • Display the palette colours in a Palette panel body

Add support for stacked with automatic calculation of the differences

The stacked toggle option currently stacks the values on top of each other

eg
Key,A,B,C
X,1,2,3
Y,4,5,6

Would produce a chart for X going up to 6, and Y would go up to 15.

But sometimes we want to have the system display the stacked values by working out the difference automatically.
So X would go to 3, and Y would go to 6.

What would the toggles be?

  • stacked
  • calculate differences

How to display the chart in the block editor?

I asked this question on the UK WP Community Slack #gutenberg channel, and also on the WordPress #core-editor channel.

Question about block development. I have a block that's server side rendered. The rendered content includes inline JavaScript... to display a chart using chart.js. Is there any documentation that explains how to get the block editor to run this Javascript so that I can see the chart in the editor?

Requirements

  • Server Side Render the chart
  • Display the chart in the block
  • When the CSV content is changed the chart should be updated

Expected result

  • Server side rendered content is "run" once it's been loaded into the editor.

Actual result

  • The HTML and JavaScript is returned to the block and can be inspected.
  • The containing div ( class chartjs ) can be styled.
  • The JavaScript is not run.
  • The Chart.js JavaScript has been enqueued from the CDN.

Attempts to get it to work

HTML block

  • I tried copying the returned HTML and JavaScript into an HTML block and Previewing the block.
  • This produced Uncaught ReferenceError: Chart is not defined at :11:19.
  • I think this is due to the Sandbox control.

Rerun button

  • Maybe a button to cause the JavaScript to be rerun.

Eliminate render-blocking resources - chart.js

When running Google's PageSpeed Insights against a WordPress website you often get told about the following opportunity to improve the website's performance.

Eliminate render-blocking resources

Resources are blocking the first paint of your page. Consider delivering critical JS/CSS inline and deferring all non-critical JS/styles. Learn more

WordPress
There are a number of WordPress plugins that can help you inline critical assets or defer less important resources.

Beware that optimizations provided by these plugins may break features of your theme or plugins, so you will likely need to make code changes.

Requirement

  • Front end - Only enqueue the chart.js script when it's needed
  • Front end - Enqueue in the footer
  • Front end - Run the Chart.js script when the page has loaded.
  • Editor - doesn't matter so much

Proposed solution

Wrap the inline JavaScript written by the server side rendering with:

$script .= 'document.addEventListener( "DOMContentLoaded", function() {';

and

$script .= '}, false );';

This part of the solution uses JavaScript that is identical to the code used by people fiddling with Gravity forms JavaScript.
It's a lot easier to implement though.

The other change is to ensure the script is enqueued in the footer.

wp_register_script( "chartjs-script", 'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js', null, null, true );

simplify the enqueue_script call

wp_enqueue_script( "chartjs-script" );
//'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js', null, null, true );

and to remove the hook that enqueues the script willy-nilly.

//add_action( 'wp_enqueue_scripts', 'sb_chart_block_enqueue_scripts' );

In this explanation I've just commented out the code that's not necessary any more.

Chart block example doesn't show a chart

I can't find any evidence to prove it but I'm sure that the example used to work.
It doesn't work with the latest build of the code (v0.4.0 ), nor does it work with the version released to wordpress.org
image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.