Add a new `offset` option to scales to add extra space at edges and remove the `includeOffset` argument from `getPixelForValue()` and `getPixelForTick()`. The bar controller now automatically calculates the bar width to avoid overlaps. When `offsetGridLines` is true, grid lines move to the left by one half of the tick interval, and labels don't move.
The `bounds` option makes more sense directly under `scale` since it defines the scale limits strategy when no explicit min/max are specified. Also change the `bounds: 'labels'` option value for `bounds: 'ticks'` because it really means: "ensure ticks to be fully visible in the scale, whatever the ticks `source`.
Allow to create a chart on a canvas not yet attached to the DOM (detection based on CSS animations described in https://davidwalsh.name/detect-node-insertion). The resize element (IFRAME) is added only when the canvas receives a parent or when `style.display` changes from `none`. This change also allows to re-parent the canvas under a different node (the resizer element following). This is a preliminary work for the DIV based resizer.
Fix `ticks.mode` behavior when `ticks.source` is `auto`: the lookup table is now built from the data and not from the ticks, so data (and ticks) are correctly distributed along the scale. Rename the option to `distribution` (more explicit than `mode`) and since this option applies from now on the data, it seems better to have it under `scale` instead `scale.ticks`.
Internal ticks are now stored as objects in the PRIVATE this._ticks member and must not be accessed directly from outside this class. this.ticks is around for a long time and hasn't been marked as private, so we can't change its structure without unexpected breaking changes. If you need to access the scale ticks, use scale.getTicks() instead.
The original implementation tries to intercept events from the chart internal iframe, which ones failing on Chrome 60. Checking internals doesn't seem the best approach, instead we could consider that a chart has been resized after the resize method has been called and processed. So let's hook `Chart.resize` and callback once it's done.
`ticks.bounds` (`'data'`(default)|`'label'`): `data` preserves the data range while `labels` ensures that all labels are visible. This option is bypassed by the min/max time options.
Remove the useless time scale `_model` object containing private members: instead, make these members private (prefixed by `_`) part of the scale.
Move time helpers back into time scale, remove the `Chart.helpers.time namespace` and attempt to make the auto generation logic a bit simpler. The generate method doesn't anymore enforce min/max, the calling code needs to clamp timestamps if needed.
For time series charts it may make more sense to specify the horizontal axis using the variable `t`. This change will make it much easier to use the time scale with the financial chart, which takes in the data points `{t, o, h, l, c}`.
The title plugin and scale title now accept lineHeight specified using unitless value (1.4), length ('1.4em' or '12px'), percentage ('200%') or keyword ('normal' === 1.2). The line height parsing has been refactored under the 'Chart.helpers.options' namespace. Also fix incorrect text positioning in the title plugin.
https://developer.mozilla.org/en-US/docs/Web/CSS/line-height
`ticks.source` (`'auto'`(default)|`'labels'`): `auto` generates "optimal" ticks based on min, max and a few more options (current `time` implementation`). `labels` generates ticks from the user given `data.labels` values (two additional trailing and leading ticks can be added if min and max are provided).
`ticks.mode` (`'linear'`(default)|`series`): `series` displays ticks at the same distance from each other, whatever the time value they represent, while `linear` displays them linearly in time: the distance between each tick represent the amount of time between their time values.
The `clone` method now accepts any type of input but also recursively perform a deep copy of the array items. Rewrite the `configMerge` and `scaleMerge` helpers which now rely on a new generic and customizable `merge` method, that one accepts a target object in which multiple sources are deep copied. Note that the target (first argument) is not cloned and will be modified after calling `merge(target, sources)`. Add a `mergeIf` helper which merge the source properties only if they do not exist in the target object.
Raise the cyclomatic complexity to 10 which seems to better match the project coding style and still reasonable (6 being quite low). Also move unit tests specific eslint rules in the cascaded `./test/.eslintrc` file (previously in `gulp.js`).
Deprecate `addEvent` and `removeEvent`, and move implementation in `platform.dom.js`. Add 'options' feature detection to register event listeners as passive and prevent warning in Chrome.
For consistency with `valueOrDefault`, `valueAtIndexOrDefault` now returns null if `value` (expected array) is null. Also get rid of the superfluous `get` prefix in `getValueOrDefault` and `getValueAtIndexOrDefault`.
Move some of the "core" and "canvas" utils in `helpers.core.js` and `helpers.canvas.js` and introduce the new `isNullOrUndef` and `isObject` helpers. Deprecate `indexOf` and rename `drawRoundedRectangle` to `roundedRect` which now creates a simple `rect` path if radius is 0. Write missing unit tests for the moved helpers.
See discussion in the issue for context and possible approaches.
When invoking update() inside an event handler, such as onHover,
`options.hover.animationDuration` was not being respected. Given that
some use cases may require additional animation properties for the
manual update call, this commit changes that method signature to accept
a configuration object.
This object provides backwards compatibility with duration and lazy
properties, and also introduces the easing property so that the event
animation is different from the global one.
Add tests that guarantee that when update is called manually with
arguments, it properly builds the _bufferedRequest or calls render with
the proper arguments.
It includes test cases for when update is called with legacy arguments
(duration and lazy) instead of the config object.
.update() documentation was previously updated but .render() was left
out. Since the backwards compatible change was also made to render(),
this commit adds documentation for it.
Implemented alignment by major unit in the time scale. This allows showing the first tick of a larger unit like days in a special way and is part of the basis of the time series scale.
`instanceof HTMLCanvasElement/CanvasRenderingContext2D` fails when the item is inside an iframe or when running in a protected environment. We could guess the types from their toString() value but let's keep things flexible and assume it's a sufficient condition if the item has a context2D which has item as `canvas`.
* Adds step-after functionality, true defaults to step-before
* Update stepped line sample to include all variations of steppedLine configurations
* Update documentation on steppedLine values
* Add tests for new steppedLine values 'before' and 'after'
* Fixed different calculation of scale min and max when dataset contains no values
* Removed trailing spaces
* Added test for correct min/max calculation
* Removed trailing spaces
Merge most of the horizontalBar controller into the bar one but also fix stack groups and bar positioning when scales are stacked or when a min and/or max tick values are explicitly defined. Note that this is a breaking change for derived controllers that rely on the following removed methods: `calculateBarBase`, `calculateBarX`, `calculateBarY`, `calculateBarWidth` and `calculateBarHeight`.
* respect new scale option 'order' when ordering scales
* scale service - respect new weight scale option for axes ordering
* added test for scale ordering by weight
* removed trailing spaces from layout weight scale order test
* Make parseTime private
* start on fixing time scale
* Reimplement existing functionality
* Tidy tests
* Fix labels for non-linearly sized units
Months, quarters and years have non-constant numbers of seconds. A scale that's linear WRT milliseconds produces incorrect tick labels due to the label formatting losing precision (eg year labels lose month and day so a label of 2016-12-32 displays as 2016 instead of 2017).
* Re-implement tick generation
As in v2.5
Radar chart position is not center horizontally with v2.5.0.
Right and left of `furthestLimits` would be switched wrongly on
this refactoring commit.
e1606f88ed
* Undo fix for #3585 since it has broken the stacked bar charts when the axis has a user defined minimum value.
* When a value of 0 is requested for a vertical logarithmic axis, return the bottom point
The `fill` option now accepts the index of the target dataset (number) or a string starting by "+" or "-" followed by a number representing the dataset index relative to the current one (e.g. `fill: "-2"` on dataset at index 3 will fill to dataset at index 1). It's also possible to "propagate" the filling to the target of an hidden dataset (`options.plugins.filler.propagate`). Fill boundaries `zero`, `top` and `bottom` have been deprecated and replaced by `origin`, `start` and `end`.
Implementation has been moved out of the line element into a new plugin (`src/plugins/plugin.filler.js`) and does not rely anymore on the deprecated model `scaleTop`, `scaleBottom` and `scaleZero` values. Drawing Bézier splines has been refactored in the canvas helpers (note that `Chart.helpers.canvas` is now an alias of `Chart.canvasHelpers`).
Add 3 new examples and extend utils with a pseudo-random number generator that can be initialized with `srand`. That makes possible to design examples starting always with the same initial data.
Attempt to make easier the creation of unit tests that check the drawing output. Until now, this was done by checking calls on a 'fake' context, which is hard to maintain (need to update pixel values by hands) and also not reliable when optimizing code (i.e. different calls sequence but same result).
As of now, it's possible to define 'auto' tests based on JSON/PNG fixtures: chart is generated from the JSON file and compared to the associated PNG image. The image diff is done using `pixelmatch`. As an example (and in preparation of the `filler` plugin), add auto tests for the line element `fill` options.
`karma.conf.ci.js` has been merged into `karma.conf.js` for local testing consistency: `gulp unittestWatch` has been replaced by `gulp unittest --watch` and thus use exactly the same config file. Upgrade to latest jasmine and karma packages and remove deprecated `gulp-karma` dependency (directly use `karma.Server` in gulp).
Split `test/mockContext.js` into smaller `test/jasmine.*` modules to make easier unit tests maintenance and finally, move all `*.test.js` files under the `test/specs` folder.
gridLines.circular is a new option that toggles circular lines. This allows radar charts with circular lines #3082
pointLabels.display is a new option that toggles the display of point labels.
The existing angleLines.display is used with the new pointLabels.display setting is used to trigger the radar like settings.
This required changing the default polar area config.
Animation callbacks now receives `animationObject` directly with a reference on the associated chart (`animation.chart`), which deprecates `animation.animationObject` and `animation.chartInstance`. Also fix missing `onComplete` animation argument and make sure that an animation object is passed even when animations are disabled.
If a value is set on the model after `pivot()` has been called, the view wasn't initialized and the animation started from 0. Now, `_start` and incomplete `_view` are initialized to the model value during the transition (no initial implicit transition).
Also remove exception handling when animating a string (color), which is faster when string are not valid colors (e.g. tooltip position). It requires to update `chartjs-color` to version 2.1.0.
In order to take full advantage of the new plugin hooks called before and after a dataset is drawn, all drawing operations must happen on stable meta data, so make sure that transitions are performed before.
Chart data can now be entirely replaced using `chart.data = {...}` thanks to the new property setter (instead of using `chart.config.data = {}`). Also update the documentation, as suggested by @ldaguise and @kennethkalmer, with a note about versions prior 2.6.
Make all `before` hooks cancellable (except `beforeInit`), meaning that if any plugin return explicitly `false`, the current action is not performed. Ensure that `init` hooks are called before `update` hooks and add associated calling order unit tests. Deprecate `Chart.PluginBase` in favor of `IPlugin` (no more an inheritable class) and document plugin hooks (also rename `extension` by `hook`).
Move base platform definition and logic in src/platform/platform.js and simplify the browser -> Chart.js event mapping by listing only different naming then fallback to the native type.
Replace `createEvent` by `add/removeEventListener` methods which dispatch Chart.js IEvent objects instead of native events. Move `add/removeResizeListener` implementation into the DOM platform which is now accessible via `platform.add/removeEventListener(chart, 'resize', listener)`.
Finally, remove `bindEvent` and `unbindEvent` from the helpers since the implementation is specific to the chart controller (and should be private).
Refactoring to put browser specific code in a new class, BrowserPlatform.
BrowserPlatform implements IPlatform. Chart.Platform is the constructor for the platform object that is attached to the chart instance.
Plugins are notified about the event using the `onEvent` call. The legend plugin was converted to use onEvent instead of the older private `handleEvent` method.
Wrote test to check that plugins are notified about events
Fix bar draw issue.
1. `Chart.elements.Rectangle.draw` function supports both horizontal and vertical bar.
2. Corrected bar position at minus.
3. Adjust bar size when `borderWidth` is set.
4. Adjust bar size when `borderSkipped` is set.
5. Adjust `borderWidth` with value near 0(base).
6. Update test.
Plugins can now be declared in the chart `config.plugins` array and will only be applied to the associated chart(s), after the globally registered plugins. Plugin specific options are now scoped under the `config.options.plugins` options. Hooks now receive the chart instance as first argument and the plugin options as last argument.
added helper method to adjust the index
pass in chartConfig rather than access within method, make it easier to
test
added semi-colon at the end of helper method
added test for adjustIndex helper method
fixed lint issues
added integration test for the interaction of trigger an event over the
bar
.
.
moved adjustIndex into element helper
removed method from helper and adjusted method in core.interaction
added test for the element adjustIndex helper
added a skipIndexAdjustment method to handle when to skip the adjustment
along with test cases
fixed lint issues
removed the test for the helper method
When datasets.data contains a null value, the label displays incorrect
value.
code additions:
- unit tests for truthy label values (when data is null)
- checks to ensure handling of null value in getLabelByIndex method
added mock data sets from issue #3528 example
expect the return value from getLabelForIndex method to be valid (truthy)
added check for null of first data value in getLabelForIndex
fixed indentation and null comparison operator in code
fixed mistake in definition of firstData variable
changed testing for data on index 0 to using index variable
changed firstData to use value instead
condense the statments to use value variable
The retinaScale helper now enforces the display size to the correct values because if no style has been set on the canvas, the render size is used as display size, making the chart bigger (or smaller) when deviceAspectRatio is different of 1.
In many cases, the canvas render size is changed by the lib, causing the state stack to be discarded, meaning that we can't use save() and restore() to release the context with its initial state (i.e. before creating the chart). Since we don't need (want) to manually save / restore the context initial state, simply make sure to reset it to the default state to give a fresh context back to the user. That also means we don't need to revert the scale when the pixel device ratio is not 1.
When the iframe is attached to the DOM, its content is reloaded (invaliding the resize listener) so make sure to install the handler after the iframe is loaded. Optimize resize events by throttling resize process until the next animation frame. Rewrite the unit test "waitForResize" method, the previous one (timeout) was too weak and most tests was failing on FF.
Add support for creating a chart from the canvas id and prevent exceptions, at construction time, when the given item doesn't provide a valid CanvasRenderingContext2D or when the getContext API is not accessible (e.g. undefined by add-ons to prevent fingerprinting). New jasmine matcher to verify chart validity.
In order to simulate real-time chart updates (i.e. horizontal animation), it's necessary to distinguish a removed or added value from a simple update. The dataset controller now hooks array methods that alter the data array length to synchronize metadata accordingly. Also remove the duplicate calls of updateBezierControlPoints() for line and radar charts.
Responsiveness is currently based on the use of an iframe, however this method causes performance issues and could be troublesome when used with ad blockers. So make sure that the user is still able to create a chart without iframe when responsive is false.
For convenience, charts are now automatically released after each spec if they are not acquired using `persistent: true`. Also remove the confusing and error prone `chartInstance` global variable and make sure that chart instances are local to each spec.
Add "onHover" to the legend options that will hold a user defined function (default is null) and called when a "mousemove" event is registered on top of a label item, with same parameters as the "onClick" option.
Also introduced logic that determines if the type of event passed to the legend "handleEvent" function is one we can handle. Currently allowing "click" and "mousemove" events. If the event is not one of those we stop the function execution (this is for the sake of reusing the legend hitbox calculations).
When dealing with time-delineated datasets, often we have data for known
intervals of time. For example, we may have a dataset which represents number
of purchases per day:
```json
{
labels: ['2016-01-01', '2016-01-02', '2016-01-03']
datasets: [
{
data: [12, 87, 42]
}
],
'...': '...'
}
```
In this case, Chart.js will attempt to figure out the best interval to display
the data, and could pick `hours` as the unit. However, in this case, we would
prefer to just use the `days` interval since our data's granularity can not be
represented well with `hours`.
To remedy this, this commit adds the `minUnit` option which allows
users to (optionally) specify what the minimum unit they would like
to use.
Change the linter in gulp tasks to be consistent with Code Climate results which are based on ESLint using .eslintrc options. However, defaults Code Climate rules are too strict, so turn as warnings the 'complexity' and 'max-statements' rules (other errors has been fixed). Note that the Gulp task name has been changed for `gulp lint`.
Zooming in can cause the params `datasetIndex` and `index` to be null in method `getLabelMoment`. This happens when no ticks are visible on scale. It also throws an error and the chart becomes broken.
* Added borderDash support for grid lines (#3136)
* Save and restore context to prevent border dash being applied to other elements
* Adds support for borderDashOffset, checks for setLineDash (IE9/IE10)
* Fixes tests
Previously, calling getLabelMoment with an out of bound index would cause an
error such as this:
```
Uncaught TypeError: Cannot read property 'null' of undefined
```
This happens because there is not always guaranteed to be a labelMoment on
at the current datasetIndex.
One example of this is practice comes from a this function call:
```js
// since the are not always guaranteed to be at least two labelMoments
// \ / this index can be out of bounds
// |
var tickWidth = me.getPixelForTick(1) - me.getPixelForTick(0) - 6;
```
This patch simply ensures that the `labelMoments` for the `datasetIndex` are
defined before accessing properties on it.
* Category scale can now read from the xLabels and yLabels properties.
* Update docs with section regarding the data object.
* Add sample file with non numeric Y and fix animations
The plugins service now accepts an array of plugin instances to register or unregister (for consistency, renamed `Chart.plugins.remove` to `unregister`). Also added a few methods to manipulate registered plugins, such as `count`, `getAll` and `clear` (mainly used by our unit tests).
Change the plugin notification behavior: this method now returns false as soon as a plugin *explicitly* returns false, else returns true. Also, plugins are now called in their own scope (so remove the never used `scope` parameter).
Rename `Chart.pluginService` to `Chart.plugins` (so move the old Chart.plugins array as a private member of the service), and rename `notifyPlugins` to `notify` for consistency with other service methods.
Change tooltip font color options
this options changed in tooltip core
bodyColor -> bodyFontColor
titleColor -> titleFontColor
footerColor -> footerFontColor
When a hover background isn't specified in the config for a chart a modified version of the default color is used. If the background color is a CanvasPattern object an error is triggered.
With this change the default background color will no longer be modified if it is a CanvasPattern.
Since we changed the way how meta data are stores, now unit tests need to work on real Chart instances. This commit brings some helpers to inject/cleanup HTML canvas and it's wrapper into/from the DOM.
* Better default tick rotation and tick autoskip settings
* scale.time: Use ctx to measure label, and <= instead of < for unit fitting
* Test Changes
* Passing Tests with new defaults
Updated unit tests to use correct 'boxes' property of chart instance. Tests did not require numerical updates!
Added a test to cover placing a full width box.