language
stringclasses
1 value
owner
stringlengths
2
15
repo
stringlengths
2
21
sha
stringlengths
45
45
message
stringlengths
7
36.3k
path
stringlengths
1
199
patch
stringlengths
15
102k
is_multipart
bool
2 classes
Other
chartjs
Chart.js
6a250de81dd0ebcd66014911460d3076d41e8737.json
Add chart, p0.raw, p1.raw to segment context (#9761) * Add chart, p0.raw, p1.raw to segment context * Types
src/core/core.datasetController.js
@@ -2,7 +2,7 @@ import Animations from './core.animations'; import defaults from './core.defaults'; import {isArray, isFinite, isObject, valueOrDefault, resolveObjectKey, defined} from '../helpers/helpers.core'; import {listenArrayEvents, unlistenArrayEvents} from '../helpers/helpers.collection'; -import {sign} from '../helpers/helpers.math'; +import {createContext, sign} from '../helpers'; /** * @typedef { import("./core.controller").default } Chart @@ -167,7 +167,7 @@ function getFirstScaleId(chart, axis) { } function createDatasetContext(parent, index) { - return Object.assign(Object.create(parent), + return createContext(parent, { active: false, dataset: undefined, @@ -180,7 +180,7 @@ function createDatasetContext(parent, index) { } function createDataContext(parent, index, element) { - return Object.assign(Object.create(parent), { + return createContext(parent, { active: false, dataIndex: index, parsed: undefined,
true
Other
chartjs
Chart.js
6a250de81dd0ebcd66014911460d3076d41e8737.json
Add chart, p0.raw, p1.raw to segment context (#9761) * Add chart, p0.raw, p1.raw to segment context * Types
src/core/core.scale.js
@@ -3,7 +3,7 @@ import {_alignPixel, _measureText, renderText, clipArea, unclipArea} from '../he import {callback as call, each, finiteOrDefault, isArray, isFinite, isNullOrUndef, isObject, valueOrDefault} from '../helpers/helpers.core'; import {toDegrees, toRadians, _int16Range, _limitValue, HALF_PI} from '../helpers/helpers.math'; import {_alignStartEnd, _toLeftRightCenter} from '../helpers/helpers.extras'; -import {toFont, toPadding, _addGrace} from '../helpers/helpers.options'; +import {createContext, toFont, toPadding, _addGrace} from '../helpers/helpers.options'; import './core.scale.defaults'; @@ -109,14 +109,14 @@ function getTitleHeight(options, fallback) { } function createScaleContext(parent, scale) { - return Object.assign(Object.create(parent), { + return createContext(parent, { scale, type: 'scale' }); } function createTickContext(parent, index, tick) { - return Object.assign(Object.create(parent), { + return createContext(parent, { tick, index, type: 'tick'
true
Other
chartjs
Chart.js
6a250de81dd0ebcd66014911460d3076d41e8737.json
Add chart, p0.raw, p1.raw to segment context (#9761) * Add chart, p0.raw, p1.raw to segment context * Types
src/elements/element.line.js
@@ -244,6 +244,7 @@ export default class LineElement extends Element { this.animated = true; this.options = undefined; + this._chart = undefined; this._loop = undefined; this._fullLoop = undefined; this._path = undefined;
true
Other
chartjs
Chart.js
6a250de81dd0ebcd66014911460d3076d41e8737.json
Add chart, p0.raw, p1.raw to segment context (#9761) * Add chart, p0.raw, p1.raw to segment context * Types
src/helpers/helpers.options.js
@@ -184,3 +184,13 @@ export function _addGrace(minmax, grace, beginAtZero) { max: keepZero(max, change) }; } + +/** + * Create a context inheriting parentContext + * @param {object|null} parentContext + * @param {object} context + * @returns {object} + */ +export function createContext(parentContext, context) { + return Object.assign(Object.create(parentContext), context); +}
true
Other
chartjs
Chart.js
6a250de81dd0ebcd66014911460d3076d41e8737.json
Add chart, p0.raw, p1.raw to segment context (#9761) * Add chart, p0.raw, p1.raw to segment context * Types
src/helpers/helpers.segment.js
@@ -1,4 +1,5 @@ import {_angleBetween, _angleDiff, _normalizeAngle} from './helpers.math'; +import {createContext} from './helpers.options'; /** * @typedef { import("../elements/element.line").default } LineElement @@ -275,6 +276,7 @@ function splitByStyles(line, segments, points, segmentOptions) { * @return {Segment[]} */ function doSplitByStyles(line, segments, points, segmentOptions) { + const chartContext = line._chart.getContext(); const baseStyle = readStyle(line.options); const {_datasetIndex: datasetIndex, options: {spanGaps}} = line; const count = points.length; @@ -309,14 +311,14 @@ function doSplitByStyles(line, segments, points, segmentOptions) { let style; for (i = start + 1; i <= segment.end; i++) { const pt = points[i % count]; - style = readStyle(segmentOptions.setContext({ + style = readStyle(segmentOptions.setContext(createContext(chartContext, { type: 'segment', p0: prev, p1: pt, p0DataIndex: (i - 1) % count, p1DataIndex: i % count, datasetIndex - })); + }))); if (styleChanged(style, prevStyle)) { addStyle(start, i - 1, segment.loop, prevStyle); }
true
Other
chartjs
Chart.js
6a250de81dd0ebcd66014911460d3076d41e8737.json
Add chart, p0.raw, p1.raw to segment context (#9761) * Add chart, p0.raw, p1.raw to segment context * Types
src/plugins/plugin.tooltip.js
@@ -5,7 +5,7 @@ import {each, noop, isNullOrUndef, isArray, _elementsEqual} from '../helpers/hel import {toFont, toPadding, toTRBLCorners} from '../helpers/helpers.options'; import {getRtlAdapter, overrideTextDirection, restoreTextDirection} from '../helpers/helpers.rtl'; import {distanceBetweenPoints, _limitValue} from '../helpers/helpers.math'; -import {drawPoint} from '../helpers'; +import {createContext, drawPoint} from '../helpers'; /** * @typedef { import("../platform/platform.base").ChartEvent } ChartEvent @@ -335,7 +335,7 @@ function getBeforeAfterBodyLines(callback) { } function createTooltipContext(parent, tooltip, tooltipItems) { - return Object.assign(Object.create(parent), { + return createContext(parent, { tooltip, tooltipItems, type: 'tooltip'
true
Other
chartjs
Chart.js
6a250de81dd0ebcd66014911460d3076d41e8737.json
Add chart, p0.raw, p1.raw to segment context (#9761) * Add chart, p0.raw, p1.raw to segment context * Types
src/scales/scale.radialLinear.js
@@ -4,7 +4,7 @@ import {HALF_PI, isNumber, TAU, toDegrees, toRadians, _normalizeAngle} from '../ import LinearScaleBase from './scale.linearbase'; import Ticks from '../core/core.ticks'; import {valueOrDefault, isArray, isFinite, callback as callCallback, isNullOrUndef} from '../helpers/helpers.core'; -import {toFont, toPadding} from '../helpers/helpers.options'; +import {createContext, toFont, toPadding} from '../helpers/helpers.options'; function getTickBackdropHeight(opts) { const tickOpts = opts.ticks; @@ -265,7 +265,7 @@ function numberOrZero(param) { } function createPointLabelContext(parent, index, label) { - return Object.assign(Object.create(parent), { + return createContext(parent, { label, index, type: 'pointLabel'
true
Other
chartjs
Chart.js
6a250de81dd0ebcd66014911460d3076d41e8737.json
Add chart, p0.raw, p1.raw to segment context (#9761) * Add chart, p0.raw, p1.raw to segment context * Types
types/helpers/helpers.options.d.ts
@@ -52,3 +52,10 @@ export function resolve<T, C>( index?: number, info?: { cacheable?: boolean } ): T | undefined; + + +/** + * Create a context inheriting parentContext + * @since 3.6.0 + */ +export function createContext<P, T>(parentContext: P, context: T): P extends null ? T : P & T;
true
Other
chartjs
Chart.js
6a250de81dd0ebcd66014911460d3076d41e8737.json
Add chart, p0.raw, p1.raw to segment context (#9761) * Add chart, p0.raw, p1.raw to segment context * Types
types/tests/helpers/options.ts
@@ -0,0 +1,10 @@ +import { createContext } from '../../helpers/helpers.options'; + +const context1 = createContext(null, { type: 'test1', parent: true }); +const context2 = createContext(context1, { type: 'test2' }); + +const sSest: string = context1.type + context2.type; +const bTest: boolean = context1.parent && context2.parent; + +// @ts-expect-error Property 'notThere' does not exist on type '{ type: string; parent: boolean; } & { type: string; }' +context2.notThere = '';
true
Other
chartjs
Chart.js
7993fc95dcea17edf1050283580078423d63a82d.json
Types: Move tooltip methods to model from plugin (#9729)
types/index.esm.d.ts
@@ -2427,15 +2427,15 @@ export interface TooltipModel<TType extends ChartType> { // tooltip options options: TooltipOptions<TType>; + + getActiveElements(): ActiveElement[]; + setActiveElements(active: ActiveDataPoint[], eventPosition: { x: number, y: number }): void; } export const Tooltip: Plugin & { readonly positioners: { [key: string]: (items: readonly ActiveElement[], eventPosition: { x: number; y: number }) => { x: number; y: number } | false; }; - - getActiveElements(): ActiveElement[]; - setActiveElements(active: ActiveDataPoint[], eventPosition: { x: number, y: number }): void; }; export interface TooltipCallbacks<
true
Other
chartjs
Chart.js
7993fc95dcea17edf1050283580078423d63a82d.json
Types: Move tooltip methods to model from plugin (#9729)
types/tests/plugins/plugin.tooltip/chart.tooltip.ts
@@ -11,3 +11,5 @@ const chart = new Chart('id', { }); const tooltip = chart.tooltip; + +const active = tooltip && tooltip.getActiveElements();
true
Other
chartjs
Chart.js
28de4b00dcea3fc54366e0e12ea4b2e9a0c0cb43.json
docs: fix small error (#9724)
docs/general/options.md
@@ -32,7 +32,7 @@ Options are resolved from top to bottom, using a context dependent route. ### Dataset element level options -Each scope is looked up with `elementType` prefix in the option name first, then wihtout the prefix. For example, `radius` for `point` element is looked up using `pointRadius` and if that does not hit, then `radius`. +Each scope is looked up with `elementType` prefix in the option name first, then without the prefix. For example, `radius` for `point` element is looked up using `pointRadius` and if that does not hit, then `radius`. * dataset * options.datasets[`dataset.type`]
false
Other
chartjs
Chart.js
990a2890d5d04a82bff329a263ac0231585ddb25.json
Fix some typings issues (#9680) * Types: Add scope to ticks.callback * Fix some typings issues
docs/samples/advanced/linear-gradient.md
@@ -47,7 +47,7 @@ let width, height, gradient; function getGradient(ctx, chartArea) { const chartWidth = chartArea.right - chartArea.left; const chartHeight = chartArea.bottom - chartArea.top; - if (gradient === null || width !== chartWidth || height !== chartHeight) { + if (!gradient || width !== chartWidth || height !== chartHeight) { // Create the gradient because this is either the first render // or the size of the chart has changed width = chartWidth; @@ -79,7 +79,7 @@ const data = { if (!chartArea) { // This case happens on initial chart load - return null; + return; } return getGradient(ctx, chartArea); },
true
Other
chartjs
Chart.js
990a2890d5d04a82bff329a263ac0231585ddb25.json
Fix some typings issues (#9680) * Types: Add scope to ticks.callback * Fix some typings issues
docs/samples/advanced/radial-gradient.md
@@ -30,7 +30,7 @@ function createRadialGradient3(context, c1, c2, c3) { const chartArea = context.chart.chartArea; if (!chartArea) { // This case happens on initial chart load - return null; + return; } const chartWidth = chartArea.right - chartArea.left;
true
Other
chartjs
Chart.js
990a2890d5d04a82bff329a263ac0231585ddb25.json
Fix some typings issues (#9680) * Types: Add scope to ticks.callback * Fix some typings issues
types/index.esm.d.ts
@@ -34,7 +34,7 @@ export interface ScriptableLineSegmentContext { datasetIndex: number } -export type Scriptable<T, TContext> = T | ((ctx: TContext, options: AnyObject) => T); +export type Scriptable<T, TContext> = T | ((ctx: TContext, options: AnyObject) => T | undefined); export type ScriptableOptions<T, TContext> = { [P in keyof T]: Scriptable<T[P], TContext> }; export type ScriptableAndArray<T, TContext> = readonly T[] | Scriptable<T, TContext>; export type ScriptableAndArrayOptions<T, TContext> = { [P in keyof T]: ScriptableAndArray<T[P], TContext> }; @@ -1402,22 +1402,22 @@ export interface CoreChartOptions<TType extends ChartType> extends ParsingOption * base color * @see Defaults.color */ - color: Color; + color: Scriptable<Color, ScriptableContext<TType>>; /** * base background color * @see Defaults.backgroundColor */ - backgroundColor: Color; + backgroundColor: Scriptable<Color, ScriptableContext<TType>>; /** * base border color * @see Defaults.borderColor */ - borderColor: Color; + borderColor: Scriptable<Color, ScriptableContext<TType>>; /** * base font * @see Defaults.font */ - font: FontSpec; + font: Scriptable<Partial<FontSpec>, ScriptableContext<TType>>; /** * Resizes the chart canvas when its container does (important note...). * @default true @@ -2805,7 +2805,7 @@ export interface TickOptions { /** * Returns the string representation of the tick value as it should be displayed on the chart. See callback. */ - callback: (tickValue: number | string, index: number, ticks: Tick[]) => string | number | null | undefined; + callback: (this: Scale, tickValue: number | string, index: number, ticks: Tick[]) => string | number | null | undefined; /** * If true, show tick labels. * @default true
true
Other
chartjs
Chart.js
990a2890d5d04a82bff329a263ac0231585ddb25.json
Fix some typings issues (#9680) * Types: Add scope to ticks.callback * Fix some typings issues
types/tests/scales/options.ts
@@ -26,6 +26,14 @@ const chart = new Chart('test', { // @ts-expect-error Type 'string' is not assignable to type 'false | "millisecond" | "second" | "minute" | "hour" | "day" | "week" | "month" | "quarter" | "year" | undefined'. unit: 'year' } + }, + y: { + ticks: { + callback(tickValue) { + const value = this.getLabelForValue(tickValue as number); + return '$' + value; + } + } } } }
true
Other
chartjs
Chart.js
990a2890d5d04a82bff329a263ac0231585ddb25.json
Fix some typings issues (#9680) * Types: Add scope to ticks.callback * Fix some typings issues
types/tests/scriptable_core_chart_options.ts
@@ -0,0 +1,15 @@ +import { ChartConfiguration } from '../index.esm'; + +const getConfig = (): ChartConfiguration<'bar'> => { + return { + type: 'bar', + data: { + datasets: [] + }, + options: { + backgroundColor: (context) => context.active ? '#fff' : undefined, + font: (context) => context.datasetIndex === 1 ? { size: 10 } : { size: 12, family: 'arial' } + } + }; +}; +
true
Other
chartjs
Chart.js
5587738fa4cf86bcd89de09da04a5d245a092bef.json
Add sanity check for stepSize (#9679)
src/scales/scale.linearbase.js
@@ -222,6 +222,10 @@ export default class LinearScaleBase extends Scale { if (stepSize) { maxTicks = Math.ceil(this.max / stepSize) - Math.floor(this.min / stepSize) + 1; + if (maxTicks > 1000) { + console.warn(`scales.${this.id}.ticks.stepSize: ${stepSize} would result generating up to ${maxTicks} ticks. Limiting to 1000.`); + maxTicks = 1000; + } } else { maxTicks = this.computeTickLimit(); maxTicksLimit = maxTicksLimit || 11;
true
Other
chartjs
Chart.js
5587738fa4cf86bcd89de09da04a5d245a092bef.json
Add sanity check for stepSize (#9679)
test/specs/scale.linear.tests.js
@@ -639,6 +639,29 @@ describe('Linear Scale', function() { expect(getLabels(chart.scales.y)).toEqual(['1', '3', '5', '7', '9', '11']); }); + it('Should not generate insane amounts of ticks with small stepSize and large range', function() { + var chart = window.acquireChart({ + type: 'bar', + options: { + scales: { + y: { + type: 'linear', + min: 1, + max: 1E10, + ticks: { + stepSize: 2, + autoSkip: false + } + } + } + } + }); + + expect(chart.scales.y.min).toBe(1); + expect(chart.scales.y.max).toBe(1E10); + expect(chart.scales.y.ticks.length).toBeLessThanOrEqual(1000); + }); + it('Should create decimal steps if stepSize is a decimal number', function() { var chart = window.acquireChart({ type: 'bar',
true
Other
chartjs
Chart.js
0e64e53a59df1e0ba8ab6bd429334badb0a2afbc.json
Add align to interface of scale title config (#9634)
types/index.esm.d.ts
@@ -2905,6 +2905,7 @@ export interface CartesianScaleOptions extends CoreScaleOptions { title: { display: boolean; + align: 'start' | 'center' | 'end'; text: string | string[]; color: Color; font: FontSpec;
false
Other
chartjs
Chart.js
3f23aaba9a18c6ff70eee9ec1ce51cc4b6e62634.json
Add sanity checks for scale options (#9624)
src/core/core.config.js
@@ -48,6 +48,12 @@ function mergeScaleConfig(config, options) { // First figure out first scale id's per axis. Object.keys(configScales).forEach(id => { const scaleConf = configScales[id]; + if (!isObject(scaleConf)) { + return console.error(`Invalid scale configuration for scale: ${id}`); + } + if (scaleConf._proxy) { + return console.warn(`Ignoring resolver passed as options for scale: ${id}`); + } const axis = determineAxis(id, scaleConf); const defaultId = getDefaultScaleIDFromAxis(axis, chartIndexAxis); const defaultScaleOptions = chartDefaults.scales || {};
true
Other
chartjs
Chart.js
3f23aaba9a18c6ff70eee9ec1ce51cc4b6e62634.json
Add sanity checks for scale options (#9624)
test/specs/core.controller.tests.js
@@ -498,6 +498,49 @@ describe('Chart', function() { expect(Chart.defaults.scales.linear._jasmineCheck).not.toBeDefined(); expect(Chart.defaults.scales.category._jasmineCheck).not.toBeDefined(); }); + + it('should ignore proxy passed as scale options', function() { + let failure = false; + const chart = acquireChart({ + type: 'line', + data: [], + options: { + scales: { + x: { + grid: { + color: ctx => { + if (!ctx.tick) { + failure = true; + } + } + } + } + } + } + }); + chart.options.scales = { + x: chart.options.scales.x, + y: { + type: 'linear', + position: 'right' + } + }; + chart.update(); + expect(failure).toEqual(false); + }); + + it('should ignore array passed as scale options', function() { + const chart = acquireChart({ + type: 'line', + data: [], + options: { + scales: { + xAxes: [{id: 'xAxes', type: 'category'}] + } + } + }); + expect(chart.scales.xAxes).not.toBeDefined(); + }); }); describe('Updating options', function() {
true
Other
chartjs
Chart.js
6c47a984b0b417e793ed3ef3e0dd7ca36e6eed4c.json
Remove offscreen canvas (#9617)
types/index.esm.d.ts
@@ -537,11 +537,9 @@ export const registerables: readonly ChartComponentLike[]; export declare type ChartItem = | string | CanvasRenderingContext2D - | OffscreenCanvasRenderingContext2D | HTMLCanvasElement - | OffscreenCanvas - | { canvas: HTMLCanvasElement | OffscreenCanvas } - | ArrayLike<CanvasRenderingContext2D | HTMLCanvasElement | OffscreenCanvas>; + | { canvas: HTMLCanvasElement } + | ArrayLike<CanvasRenderingContext2D | HTMLCanvasElement>; export declare enum UpdateModeEnum { resize = 'resize',
false
Other
chartjs
Chart.js
eb1e82c9813fbfccd86f4e4b424e768332654bd9.json
Update old codepen links to ones for v3 (#9619)
.github/ISSUE_TEMPLATE/DOCS.md
@@ -21,5 +21,5 @@ Documentation Is: ### Example <!-- Provide a link to a live example demonstrating the issue or feature to be documented: - https://codepen.io/pen?template=JXVYzq + https://codepen.io/pen?template=wvezeOq -->
true
Other
chartjs
Chart.js
eb1e82c9813fbfccd86f4e4b424e768332654bd9.json
Update old codepen links to ones for v3 (#9619)
.github/PULL_REQUEST_TEMPLATE.md
@@ -7,5 +7,5 @@ Example of changes on an interactive website such as the following: - https://jsbin.com/ - https://jsfiddle.net/ - https://codepen.io/pen/ -- Premade template: https://codepen.io/pen?template=JXVYzq +- Premade template: https://codepen.io/pen?template=wvezeOq -->
true
Other
chartjs
Chart.js
eb1e82c9813fbfccd86f4e4b424e768332654bd9.json
Update old codepen links to ones for v3 (#9619)
docs/developers/contributing.md
@@ -74,6 +74,6 @@ Guidelines for reporting bugs: - Check the issue search to see if it has already been reported - Isolate the problem to a simple test case -- Please include a demonstration of the bug on a website such as [JS Bin](https://jsbin.com/), [JS Fiddle](https://jsfiddle.net/), or [Codepen](https://codepen.io/pen/). ([Template](https://codepen.io/pen?template=JXVYzq)). If filing a bug against `master`, you may reference the latest code via <https://www.chartjs.org/dist/master/chart.min.js> (changing the filename to point at the file you need as appropriate). Do not rely on these files for production purposes as they may be removed at any time. +- Please include a demonstration of the bug on a website such as [JS Bin](https://jsbin.com/), [JS Fiddle](https://jsfiddle.net/), or [Codepen](https://codepen.io/pen/). ([Template](https://codepen.io/pen?template=wvezeOq)). If filing a bug against `master`, you may reference the latest code via <https://www.chartjs.org/dist/master/chart.min.js> (changing the filename to point at the file you need as appropriate). Do not rely on these files for production purposes as they may be removed at any time. Please provide any additional details associated with the bug, if it's browser or screen density specific, or only happens with a certain configuration or data.
true
Other
chartjs
Chart.js
fca030922360a1a2d1292f6936276ad11a7cf7d9.json
Detect attach/detach from any level (#9557)
src/core/core.controller.js
@@ -123,7 +123,7 @@ class Chart { this.attached = false; this._animationsDisabled = undefined; this.$context = undefined; - this._doResize = debounce(() => this.update('resize'), options.resizeDelay || 0); + this._doResize = debounce(mode => this.update(mode), options.resizeDelay || 0); // Add the chart instance to the global namespace instances[me.id] = me; @@ -231,6 +231,7 @@ class Chart { const aspectRatio = options.maintainAspectRatio && me.aspectRatio; const newSize = me.platform.getMaximumSize(canvas, width, height, aspectRatio); const newRatio = options.devicePixelRatio || me.platform.getDevicePixelRatio(); + const mode = me.width ? 'resize' : 'attach'; me.width = newSize.width; me.height = newSize.height; @@ -244,7 +245,7 @@ class Chart { callCallback(options.onResize, [me, newSize], me); if (me.attached) { - if (me._doResize()) { + if (me._doResize(mode)) { // The resize update is delayed, only draw without updating. me.render(); } @@ -831,19 +832,22 @@ class Chart { } } - destroy() { + _stop() { const me = this; - const {canvas, ctx} = me; let i, ilen; - me.stop(); animator.remove(me); - // dataset controllers need to cleanup associated data for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) { me._destroyDatasetMeta(i); } + } + + destroy() { + const me = this; + const {canvas, ctx} = me; + me._stop(); me.config.clearCache(); if (canvas) { @@ -940,6 +944,11 @@ class Chart { me.attached = false; _remove('resize', listener); + + // Stop animating and remove metasets, so when re-attached, the animations start from begining. + me._stop(); + me._resize(0, 0); + _add('attach', attached); };
true
Other
chartjs
Chart.js
fca030922360a1a2d1292f6936276ad11a7cf7d9.json
Detect attach/detach from any level (#9557)
src/helpers/helpers.extras.js
@@ -42,24 +42,23 @@ export function throttled(fn, thisArg, updateFn) { /** * Debounces calling `fn` for `delay` ms - * @param {function} fn - Function to call. No arguments are passed. + * @param {function} fn - Function to call. * @param {number} delay - Delay in ms. 0 = immediate invocation. * @returns {function} */ export function debounce(fn, delay) { let timeout; - return function() { + return function(...args) { if (delay) { clearTimeout(timeout); - timeout = setTimeout(fn, delay); + timeout = setTimeout(fn, delay, args); } else { - fn(); + fn.apply(this, args); } return delay; }; } - /** * Converts 'start' to 'left', 'end' to 'right' and others to 'center' * @param {string} align start, end, center
true
Other
chartjs
Chart.js
fca030922360a1a2d1292f6936276ad11a7cf7d9.json
Detect attach/detach from any level (#9557)
src/platform/platform.dom.js
@@ -116,40 +116,31 @@ function fromNativeEvent(event, chart) { function createAttachObserver(chart, type, listener) { const canvas = chart.canvas; - const container = canvas && _getParentNode(canvas); - const element = container || canvas; const observer = new MutationObserver(entries => { - const parent = _getParentNode(element); - entries.forEach(entry => { - for (let i = 0; i < entry.addedNodes.length; i++) { - const added = entry.addedNodes[i]; - if (added === element || added === parent) { - listener(entry.target); + for (const entry of entries) { + for (const node of entry.addedNodes) { + if (node === canvas || node.contains(canvas)) { + return listener(); } } - }); + } }); observer.observe(document, {childList: true, subtree: true}); return observer; } function createDetachObserver(chart, type, listener) { const canvas = chart.canvas; - const container = canvas && _getParentNode(canvas); - if (!container) { - return; - } const observer = new MutationObserver(entries => { - entries.forEach(entry => { - for (let i = 0; i < entry.removedNodes.length; i++) { - if (entry.removedNodes[i] === canvas) { - listener(); - break; + for (const entry of entries) { + for (const node of entry.removedNodes) { + if (node === canvas || node.contains(canvas)) { + return listener(); } } - }); + } }); - observer.observe(container, {childList: true}); + observer.observe(document, {childList: true, subtree: true}); return observer; }
true
Other
chartjs
Chart.js
fca030922360a1a2d1292f6936276ad11a7cf7d9.json
Detect attach/detach from any level (#9557)
test/specs/core.controller.tests.js
@@ -1029,8 +1029,10 @@ describe('Chart', function() { }); parent.removeChild(wrapper); - parent.appendChild(wrapper); - wrapper.style.height = '355px'; + setTimeout(() => { + parent.appendChild(wrapper); + wrapper.style.height = '355px'; + }, 0); }); // https://github.com/chartjs/Chart.js/issues/4737 @@ -1075,6 +1077,47 @@ describe('Chart', function() { canvas.parentNode.style.width = '455px'; }); }); + + it('should resize the canvas if attached to the DOM after construction with mutiple parents', function(done) { + var canvas = document.createElement('canvas'); + var wrapper = document.createElement('div'); + var wrapper2 = document.createElement('div'); + var wrapper3 = document.createElement('div'); + var body = window.document.body; + + var chart = new Chart(canvas, { + type: 'line', + options: { + responsive: true, + maintainAspectRatio: false + } + }); + + expect(chart).toBeChartOfSize({ + dw: 0, dh: 0, + rw: 0, rh: 0, + }); + expect(chart.chartArea).toBeUndefined(); + + waitForResize(chart, function() { + expect(chart).toBeChartOfSize({ + dw: 455, dh: 355, + rw: 455, rh: 355, + }); + + expect(chart.chartArea).not.toBeUndefined(); + + body.removeChild(wrapper3); + chart.destroy(); + done(); + }); + + wrapper3.appendChild(wrapper2); + wrapper2.appendChild(wrapper); + wrapper.style.cssText = 'width: 455px; height: 355px'; + wrapper.appendChild(canvas); + body.appendChild(wrapper3); + }); }); describe('config.options.responsive: true (maintainAspectRatio: true)', function() {
true
Other
chartjs
Chart.js
4d99658155cdf3d504749b43cdc3ab71ab1d18d6.json
Remove chart.scale property (always undefined) (#9556)
src/core/core.controller.js
@@ -117,7 +117,6 @@ class Chart { this._responsiveListeners = undefined; this._sortedMetasets = []; this.scales = {}; - this.scale = undefined; this._plugins = new PluginService(); this.$proxies = {}; this._hiddenIndices = {};
false
Other
chartjs
Chart.js
fdd3ede6aa8e3678d3034d8b4e347819de7707ee.json
Fix broken link. (#9555) Fix broken link from Creating Custom Tick Formats section to the Tick API page.
docs/axes/labelling.md
@@ -24,7 +24,7 @@ The method receives 3 arguments: * `value` - the tick value in the **internal data format** of the associated scale. * `index` - the tick index in the ticks array. -* `ticks` - the array containing all of the [tick objects](../api/interfaces/tick). +* `ticks` - the array containing all of the [tick objects](../api/interfaces/Tick). The call to the method is scoped to the scale. `this` inside the method is the scale object.
false
Other
chartjs
Chart.js
567baad09dbb27055c0ea1b7ad0c61e4bdfca6d3.json
Update eslint settings for readable errors (#9534)
.eslintrc.yml
@@ -1,15 +1,19 @@ extends: - chartjs - - plugin:es/no-new-in-es2019 + - plugin:es/restrict-to-es2018 - plugin:markdown/recommended +settings: + es: + aggressive: true + env: es6: true browser: true node: true parserOptions: - ecmaVersion: 2018 + ecmaVersion: 2021 sourceType: module ecmaFeatures: impliedStrict: true
false
Other
chartjs
Chart.js
148114b03ba8eef45c07e8c987992aa2abeef1cb.json
Add more details on legend sort function (#9524)
docs/configuration/legend.md
@@ -58,7 +58,7 @@ Namespace: `options.plugins.legend.labels` | `padding` | `number` | `10` | Padding between rows of colored boxes. | `generateLabels` | `function` | | Generates legend items for each thing in the legend. Default implementation returns the text + styling for the color box. See [Legend Item](#legend-item-interface) for details. | `filter` | `function` | `null` | Filters legend items out of the legend. Receives 2 parameters, a [Legend Item](#legend-item-interface) and the chart data. -| `sort` | `function` | `null` | Sorts legend items. Receives 3 parameters, two [Legend Items](#legend-item-interface) and the chart data. +| `sort` | `function` | `null` | Sorts legend items. Type is : `sort(a: LegendItem, b: LegendItem, data: ChartData): number;`. Receives 3 parameters, two [Legend Items](#legend-item-interface) and the chart data. The return value of the function is a number that indicates the order of the two legend item parameters. The ordering matches the [return value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#description) of `Array.prototype.sort()` | [`pointStyle`](elements.md#point-styles) | [`pointStyle`](elements.md#types) | `'circle'` | If specified, this style of point is used for the legend. Only used if `usePointStyle` is true. | `textAlign` | `string` | `'center'` | Horizontal alignment of the label text. Options are: `'left'`, `'right'` or `'center'`. | `usePointStyle` | `boolean` | `false` | Label style will match corresponding point style (size is based on the minimum value between boxWidth and font.size).
false
Other
chartjs
Chart.js
1c837a9c12ec4fa7c519a170830a4adbb9898d09.json
Fix _isPointInArea helper when no area is provided (#9489)
src/helpers/helpers.canvas.js
@@ -251,8 +251,8 @@ export function drawPoint(ctx, options, x, y) { export function _isPointInArea(point, area, margin) { margin = margin || 0.5; // margin - default is to match rounded decimals - return point && area && point.x > area.left - margin && point.x < area.right + margin && - point.y > area.top - margin && point.y < area.bottom + margin; + return !area || (point && point.x > area.left - margin && point.x < area.right + margin && + point.y > area.top - margin && point.y < area.bottom + margin); } export function clipArea(ctx, area) {
true
Other
chartjs
Chart.js
1c837a9c12ec4fa7c519a170830a4adbb9898d09.json
Fix _isPointInArea helper when no area is provided (#9489)
test/specs/helpers.canvas.tests.js
@@ -24,6 +24,9 @@ describe('Chart.helpers.canvas', function() { }); describe('isPointInArea', function() { + it('should return true when no area is provided', function() { + expect(helpers._isPointInArea({x: 1, y: 1})).toBe(true); + }); it('should determine if a point is in the area', function() { var isPointInArea = helpers._isPointInArea; var area = {left: 0, top: 0, right: 512, bottom: 256};
true
Other
chartjs
Chart.js
1c837a9c12ec4fa7c519a170830a4adbb9898d09.json
Fix _isPointInArea helper when no area is provided (#9489)
types/index.esm.d.ts
@@ -1629,7 +1629,7 @@ export interface FontSpec { export type TextAlign = 'left' | 'center' | 'right'; export interface VisualElement { - draw(ctx: CanvasRenderingContext2D): void; + draw(ctx: CanvasRenderingContext2D, area?: ChartArea): void; inRange(mouseX: number, mouseY: number, useFinalPosition?: boolean): boolean; inXRange(mouseX: number, useFinalPosition?: boolean): boolean; inYRange(mouseY: number, useFinalPosition?: boolean): boolean;
true
Other
chartjs
Chart.js
281ad204524f6ad9943902a6a909bb56bfc3d06b.json
Fix copy typo
docs/06-Polar-Area-Chart.md
@@ -29,7 +29,7 @@ Some properties are specified as arrays. The first value applies to the first ba Property | Type | Usage --- | --- | --- -data | `Array<Number>` | The data to plot as bars +data | `Array<Number>` | The data to plot as arcs label | `String` | The label for the dataset which appears in the legend and tooltips backgroundColor | `Array<Color>` | The fill color of the arcs. See [Colors](#chart-configuration-colors) borderColor | `Array<Color>` | Arc border color
false
Other
chartjs
Chart.js
8226f3432b9a71f2f9c0c616161de328378985da.json
Fix JSHint warnings and remove commented code
src/controllers/controller.bar.js
@@ -446,26 +446,10 @@ module.exports = function(Chart) { var base = 0; if (xScale.options.stacked) { + var chart = me.chart; + var datasets = chart.data.datasets; + var value = Number(datasets[datasetIndex].data[index]); - var value = Number(me.chart.data.datasets[datasetIndex].data[index]); - - /*if (value < 0) { - for (var i = 0; i < datasetIndex; i++) { - var negDS = me.chart.data.datasets[i]; - var negDSMeta = me.chart.getDatasetMeta(i); - if (negDSMeta.bar && negDSMeta.xAxisID === xScale.id && me.chart.isDatasetVisible(i)) { - base += negDS.data[index] < 0 ? negDS.data[index] : 0; - } - } - } else { - for (var j = 0; j < datasetIndex; j++) { - var posDS = me.chart.data.datasets[j]; - var posDSMeta = me.chart.getDatasetMeta(j); - if (posDSMeta.bar && posDSMeta.xAxisID === xScale.id && me.chart.isDatasetVisible(j)) { - base += posDS.data[index] > 0 ? posDS.data[index] : 0; - } - } - }*/ for (var i = 0; i < datasetIndex; i++) { var currentDs = datasets[i]; var currentDsMeta = chart.getDatasetMeta(i);
false
Other
chartjs
Chart.js
a452094f5d1637b99b01bacd06a78b5ab4666cfa.json
Add polar area start angle setting
docs/06-Polar-Area-Chart.md
@@ -76,6 +76,7 @@ These are the customisation options specific to Polar Area charts. These options Name | Type | Default | Description --- | --- | --- | --- +startAngle | Number | -0.5 * Math.PI | Sets the starting angle for the first item in a dataset scale | Object | [See Scales](#scales) and [Defaults for Radial Linear Scale](#scales-radial-linear-scale) | Options for the one scale used on the chart. Use this to style the ticks, labels, and grid. *scale*.type | String |"radialLinear" | As defined in ["Radial Linear"](#scales-radial-linear-scale). *scale*.lineArc | Boolean | true | When true, lines are circular.
true
Other
chartjs
Chart.js
a452094f5d1637b99b01bacd06a78b5ab4666cfa.json
Add polar area start angle setting
src/controllers/controller.polarArea.js
@@ -20,6 +20,7 @@ module.exports = function(Chart) { animateScale: true }, + startAngle: -0.5 * Math.PI, aspectRatio: 1, legendCallback: function(chart) { var text = []; @@ -154,9 +155,10 @@ module.exports = function(Chart) { } } - var negHalfPI = -0.5 * Math.PI; + //var negHalfPI = -0.5 * Math.PI; + var datasetStartAngle = opts.startAngle; var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]); - var startAngle = (negHalfPI) + (circumference * visibleCount); + var startAngle = datasetStartAngle + (circumference * visibleCount); var endAngle = startAngle + (arc.hidden ? 0 : circumference); var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]); @@ -173,8 +175,8 @@ module.exports = function(Chart) { y: centerY, innerRadius: 0, outerRadius: reset ? resetRadius : distance, - startAngle: reset && animationOpts.animateRotate ? negHalfPI : startAngle, - endAngle: reset && animationOpts.animateRotate ? negHalfPI : endAngle, + startAngle: reset && animationOpts.animateRotate ? datasetStartAngle : startAngle, + endAngle: reset && animationOpts.animateRotate ? datasetStartAngle : endAngle, label: getValueAtIndexOrDefault(labels, index, labels[index]) } });
true
Other
chartjs
Chart.js
a452094f5d1637b99b01bacd06a78b5ab4666cfa.json
Add polar area start angle setting
test/controller.polarArea.tests.js
@@ -159,6 +159,52 @@ describe('Polar area controller tests', function() { })); }); + it('should update elements with start angle from options', function() { + var chart = window.acquireChart({ + type: 'polarArea', + data: { + datasets: [{ + data: [10, 15, 0, -4], + label: 'dataset2' + }], + labels: ['label1', 'label2', 'label3', 'label4'] + }, + options: { + showLines: true, + startAngle: 0, // default is -0.5 * Math.PI + elements: { + arc: { + backgroundColor: 'rgb(255, 0, 0)', + borderColor: 'rgb(0, 255, 0)', + borderWidth: 1.2 + } + } + } + }); + + var meta = chart.getDatasetMeta(0); + expect(meta.data.length).toBe(4); + + [ { o: 156, s: 0, e: 0.5 * Math.PI }, + { o: 211, s: 0.5 * Math.PI, e: Math.PI }, + { o: 45, s: Math.PI, e: 1.5 * Math.PI }, + { o: 0, s: 1.5 * Math.PI, e: 2.0 * Math.PI } + ].forEach(function(expected, i) { + expect(meta.data[i]._model.x).toBeCloseToPixel(256); + expect(meta.data[i]._model.y).toBeCloseToPixel(272); + expect(meta.data[i]._model.innerRadius).toBeCloseToPixel(0); + expect(meta.data[i]._model.outerRadius).toBeCloseToPixel(expected.o); + expect(meta.data[i]._model.startAngle).toBe(expected.s); + expect(meta.data[i]._model.endAngle).toBe(expected.e); + expect(meta.data[i]._model).toEqual(jasmine.objectContaining({ + backgroundColor: 'rgb(255, 0, 0)', + borderColor: 'rgb(0, 255, 0)', + borderWidth: 1.2, + label: chart.data.labels[i] + })); + }); + }); + it('should handle number of data point changes in update', function() { var chart = window.acquireChart({ type: 'polarArea',
true
Other
chartjs
Chart.js
ff9e9f1d7c32b8c1ec36f9eb8a0ace5d20748818.json
add wikipedia link for DRY explanation DRY is a short term for Don't Repeat yourself, maybe it is not so well known by front-end developers, but it is well known among back end developers
docs/01-Chart-Configuration.md
@@ -21,7 +21,7 @@ var chartInstance = new Chart(ctx, { ### Global Configuration -This concept was introduced in Chart.js 1.0 to keep configuration DRY, and allow for changing options globally across chart types, avoiding the need to specify options for each instance, or the default for a particular chart type. +This concept was introduced in Chart.js 1.0 to keep configuration [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself), and allow for changing options globally across chart types, avoiding the need to specify options for each instance, or the default for a particular chart type. Chart.js merges the options object passed to the chart with the global configuration using chart type defaults and scales defaults appropriately. This way you can be as specific as you would like in your individual chart configuration, while still changing the defaults for all chart types where applicable. The global general options are defined in `Chart.defaults.global`. The defaults for each chart type are discussed in the documentation for that chart type. @@ -408,4 +408,4 @@ img.onload = function() { }) } -``` \ No newline at end of file +```
false
Other
chartjs
Chart.js
aed3d40263b77aa5014d8c3734e2dcbc9ca5122d.json
add id property to common configuration
docs/02-Scales.md
@@ -19,6 +19,7 @@ Name | Type | Default | Description type | String | Chart specific. | Type of scale being employed. Custom scales can be created and registered with a string key. Options: ["category"](#scales-category-scale), ["linear"](#scales-linear-scale), ["logarithmic"](#scales-logarithmic-scale), ["time"](#scales-time-scale), ["radialLinear"](#scales-radial-linear-scale) display | Boolean | true | If true, show the scale including gridlines, ticks, and labels. Overrides *gridLines.display*, *scaleLabel.display*, and *ticks.display*. position | String | "left" | Position of the scale. Possible values are 'top', 'left', 'bottom' and 'right'. +id | String | | The ID is used to link datasets and scale axes together. The properties `datasets.xAxisID` or `datasets.yAxisID` have to match the scale properties `scales.xAxes.id` or `scales.yAxes.id`. This is especially needed if multi-axes charts are used. beforeUpdate | Function | undefined | Callback called before the update process starts. Passed a single argument, the scale instance. beforeSetDimensions | Function | undefined | Callback that runs before dimensions are set. Passed a single argument, the scale instance. afterSetDimensions | Function | undefined | Callback that runs after dimensions are set. Passed a single argument, the scale instance.
false
Other
chartjs
Chart.js
2feebb1cd29e89479194ffe66488b223e75a0c50.json
remove redundant option entry
docs/02-Scales.md
@@ -52,7 +52,7 @@ drawTicks | Boolean | true | If true, draw lines beside the ticks in the axis a tickMarkLength | Number | 10 | Length in pixels that the grid lines will draw into the axis area. zeroLineWidth | Number | 1 | Stroke width of the grid line for the first index (index 0). zeroLineColor | Color | "rgba(0, 0, 0, 0.25)" | Stroke color of the grid line for the first index (index 0). -offsetGridLines | Boolean | false | If true, offset labels from grid lines. +offsetGridLines | Boolean | false | If true, labels are shifted to be between grid lines. This is used in the bar chart. #### Scale Title Configuration @@ -124,8 +124,6 @@ Name | Type | Default | Description --- | --- | --- | --- ticks.min | String | - | The minimum item to display. Must be a value in the `labels` array ticks.max | String | - | The maximum item to display. Must be a value in the `labels` array -gridLines.offsetGridLines | Boolean | - | If true, labels are shifted to be between grid lines. This is used in the bar chart. - ### Linear Scale
false
Other
chartjs
Chart.js
900e1062ba57331f6c44535bace125e10a0e8bf1.json
Fix typo in docs
docs/01-Chart-Configuration.md
@@ -373,7 +373,7 @@ hoverBorderWidth | Number | 1 | Default stroke width when hovered #### Rectangle Configuration -Rectangle elements are used to represent the bars in a bar chart. The global rectangle options are stored in `Chart.defaults.global.elements.rectange`. +Rectangle elements are used to represent the bars in a bar chart. The global rectangle options are stored in `Chart.defaults.global.elements.rectangle`. Name | Type | Default | Description --- | --- | --- | ---
false
Other
chartjs
Chart.js
e1a1d9cd6dc16b3291f45b57dd0c13a69694f41f.json
Change ID links for scales objects
docs/02-Scales.md
@@ -33,9 +33,9 @@ afterCalculateTickRotation | Function | undefined | Callback that runs after tic beforeFit | Function | undefined | Callback that runs before the scale fits to the canvas. Passed a single argument, the scale instance. afterFit | Function | undefined | Callback that runs after the scale fits to the canvas. Passed a single argument, the scale instance. afterUpdate | Function | undefined | Callback that runs at the end of the update process. Passed a single argument, the scale instance. -**gridLines** | Object | - | See [grid line configuration](#scales-grid-line-configuration) section. -**scaleLabel** | Object | | See [scale title configuration](#scales-scale-title-configuration) section. -**ticks** | Object | | See [ticks configuration](#scales-ticks-configuration) section. +**gridLines** | Object | - | See [grid line configuration](#grid-line-configuration) section. +**scaleLabel** | Object | | See [scale title configuration](#scale-title-configuration) section. +**ticks** | Object | | See [ticks configuration](#ticks-configuration) section. #### Grid Line Configuration @@ -222,7 +222,7 @@ parser | String or Function | - | If defined as a string, it is interpreted as a round | String | - | If defined, dates will be rounded to the start of this unit. See [Time Units](#scales-time-units) below for the allowed units. tooltipFormat | String | '' | The moment js format string to use for the tooltip. unit | String | - | If defined, will force the unit to be a certain type. See [Time Units](#scales-time-units) section below for details. -unitStepSize | Number | 1 | The number of units between grid lines. +unitStepSize | Number | 1 | The number of units between grid lines. #### Date Formats @@ -232,8 +232,8 @@ When providing data for the time scale, Chart.js supports all of the formats tha The following display formats are used to configure how different time units are formed into strings for the axis tick marks. See [moment.js](http://momentjs.com/docs/#/displaying/format/) for the allowable format strings. -Name | Default ---- | --- +Name | Default +--- | --- millisecond | 'SSS [ms]' second | 'h:mm:ss a' minute | 'h:mm:ss a' @@ -318,7 +318,7 @@ The following options are used to configure angled lines that radiate from the c Name | Type | Default | Description --- | --- | --- | --- -display | Boolean | true | If true, angle lines are shown. +display | Boolean | true | If true, angle lines are shown. color | Color | 'rgba(0, 0, 0, 0.1)' | Color of angled lines lineWidth | Number | 1 | Width of angled lines
false
Other
chartjs
Chart.js
5c36e0de652af1912b0e5de262f3e9758677e05c.json
Fix typo in tooltip docs
docs/01-Chart-Configuration.md
@@ -189,7 +189,7 @@ var chartInstance = new Chart(ctx, { ### Tooltip Configuration -The title configuration is passed into the `options.tooltips` namespace. The global options for the chart tooltips is defined in `Chart.defaults.global.tooltips`. +The tooltip configuration is passed into the `options.tooltips` namespace. The global options for the chart tooltips is defined in `Chart.defaults.global.tooltips`. Name | Type | Default | Description --- | --- | --- | ---
false
Other
chartjs
Chart.js
3cf1cfa3de538f13f64f31e5071a4fb40a8482ad.json
Fix JSHint warning
src/controllers/controller.polarArea.js
@@ -130,7 +130,6 @@ module.exports = function(Chart) { updateElement: function(arc, index, reset) { var me = this; var chart = me.chart; - var chartArea = chart.chartArea; var dataset = me.getDataset(); var opts = chart.options; var animationOpts = opts.animation;
false
Other
chartjs
Chart.js
7ea36aead33d90803027d668a15d0f698fb3d4b2.json
Add a way to know when a resize occurs.
docs/01-Chart-Configuration.md
@@ -72,6 +72,7 @@ maintainAspectRatio | Boolean | true | Maintain the original canvas aspect ratio events | Array[String] | `["mousemove", "mouseout", "click", "touchstart", "touchmove", "touchend"]` | Events that the chart should listen to for tooltips and hovering onClick | Function | null | Called if the event is of type 'mouseup' or 'click'. Called in the context of the chart and passed an array of active elements legendCallback | Function | ` function (chart) { }` | Function to generate a legend. Receives the chart object to generate a legend from. Default implementation returns an HTML string. +onResize | Function | null | Called when a resize occurs. Gets passed two arguemnts: the chart instance and the new size. ### Title Configuration
true
Other
chartjs
Chart.js
7ea36aead33d90803027d668a15d0f698fb3d4b2.json
Add a way to know when a resize occurs.
docs/09-Advanced.md
@@ -381,6 +381,9 @@ Plugins will be called at the following times * End of update (before render occurs) * Start of draw * End of draw +* Before datasets draw +* After datasets draw +* Resize * Before an animation is started Plugins should derive from Chart.PluginBase and implement the following interface @@ -389,6 +392,8 @@ Plugins should derive from Chart.PluginBase and implement the following interfac beforeInit: function(chartInstance) { }, afterInit: function(chartInstance) { }, + resize: function(chartInstance, newChartSize) { }, + beforeUpdate: function(chartInstance) { }, afterScaleUpdate: function(chartInstance) { } afterUpdate: function(chartInstance) { },
true
Other
chartjs
Chart.js
7ea36aead33d90803027d668a15d0f698fb3d4b2.json
Add a way to know when a resize occurs.
src/core/core.controller.js
@@ -76,26 +76,39 @@ module.exports = function(Chart) { }, resize: function resize(silent) { - var canvas = this.chart.canvas; - var newWidth = helpers.getMaximumWidth(this.chart.canvas); - var newHeight = (this.options.maintainAspectRatio && isNaN(this.chart.aspectRatio) === false && isFinite(this.chart.aspectRatio) && this.chart.aspectRatio !== 0) ? newWidth / this.chart.aspectRatio : helpers.getMaximumHeight(this.chart.canvas); + var me = this; + var chart = me.chart; + var canvas = chart.canvas; + var newWidth = helpers.getMaximumWidth(canvas); + var aspectRatio = chart.aspectRatio; + var newHeight = (me.options.maintainAspectRatio && isNaN(aspectRatio) === false && isFinite(aspectRatio) && aspectRatio !== 0) ? newWidth / aspectRatio : helpers.getMaximumHeight(canvas); + + var sizeChanged = chart.width !== newWidth || chart.height !== newHeight; + + if (!sizeChanged) { + return me; + } - var sizeChanged = this.chart.width !== newWidth || this.chart.height !== newHeight; + canvas.width = chart.width = newWidth; + canvas.height = chart.height = newHeight; - if (!sizeChanged) - return this; + helpers.retinaScale(chart); - canvas.width = this.chart.width = newWidth; - canvas.height = this.chart.height = newHeight; + // Notify any plugins about the resize + var newSize = { width: newWidth, height: newHeight }; + Chart.pluginService.notifyPlugins('resize', [me, newSize]); - helpers.retinaScale(this.chart); + // Notify of resize + if (me.options.onResize) { + me.options.onResize(me, newSize); + } if (!silent) { - this.stop(); - this.update(this.options.responsiveAnimationDuration); + me.stop(); + me.update(me.options.responsiveAnimationDuration); } - return this; + return me; }, ensureScalesHaveIDs: function ensureScalesHaveIDs() {
true
Other
chartjs
Chart.js
016c2d8267f0d7c5a25caa858611ed804c18f8e4.json
Update Contributing Guidelines
CONTRIBUTING.md
@@ -25,7 +25,7 @@ Guidlines for reporting bugs: - Check the issue search to see if it has already been reported - Isolate the problem to a simple test case - - Provide a demonstration of the problem on [JS Bin](http://jsbin.com) or similar + - Please include a demonstration of the bug on a website such as [JS Bin](http://jsbin.com/), [JS Fiddle](http://jsfiddle.net/), or [Codepen](http://codepen.io/pen/). ([Template](http://codepen.io/pen?template=JXVYzq)) Please provide any additional details associated with the bug, if it's browser or screen density specific, or only happens with a certain configuration or data. @@ -45,7 +45,7 @@ Be advised that **Chart.js 1.0.2 is in feature-complete status**. Pull requests Guidelines: - - Please create an issue first: + - Please create an issue first and/or talk with a team member: - For bugs, we can discuss the fixing approach - For enhancements, we can discuss if it is within the project scope and avoid duplicate effort - Please make changes to the files in [`/src`](https://github.com/chartjs/Chart.js/tree/master/src), not `Chart.js` or `Chart.min.js` in the repo root directory, this avoids merge conflicts
false
Other
chartjs
Chart.js
10f01088e43f6632c0fbb977c43dfae4996c7dcc.json
add afterDatasetDraw in correct place
src/core/core.controller.js
@@ -297,12 +297,12 @@ module.exports = function(Chart) { } }, this, true); - Chart.pluginService.notifyPlugins('afterElementDraw', [this, easingDecimal]); + Chart.pluginService.notifyPlugins('afterDatasetDraw', [this, easingDecimal]); // Finally draw the tooltip this.tooltip.transition(easingDecimal).draw(); - Chart.pluginService.notifyPlugins('afterDatasetDraw', [this, easingDecimal]); + Chart.pluginService.notifyPlugins('afterDraw', [this, easingDecimal]); }, // Get the single element that was clicked on
false
Other
chartjs
Chart.js
0997cf71ccd711afe956d0d40e1a7053d698fff2.json
Fix doc syntax (#2673)
docs/02-Scales.md
@@ -190,14 +190,16 @@ var chartInstance = new Chart(ctx, { type: 'line', data: data, options: { - xAxes: [{ - type: 'logarithmic', - position: 'bottom', - ticks: { - min: 1, - max: 1000 - } - }] + scales: { + xAxes: [{ + type: 'logarithmic', + position: 'bottom', + ticks: { + min: 1, + max: 1000 + } + }] + } } }) ```
false
Other
chartjs
Chart.js
9d7a0fb93ef23fd76ee41596b36235aaf988dcf4.json
Fix links to 09-Advanced.md (was 07-Advanced.md)
CONTRIBUTING.md
@@ -9,7 +9,7 @@ Using issues The [issue tracker](https://github.com/chartjs/Chart.js/issues) is the preferred channel for reporting bugs, requesting new features and submitting pull requests. -If you're suggesting a new chart type, please take a look at [writing new chart types](https://github.com/chartjs/Chart.js/blob/master/docs/07-Advanced.md#writing-new-chart-types) in the documentation or consider [creating a plugin](https://github.com/chartjs/Chart.js/blob/master/docs/07-Advanced.md#creating-plugins). +If you're suggesting a new chart type, please take a look at [writing new chart types](https://github.com/chartjs/Chart.js/blob/master/docs/09-Advanced.md#writing-new-chart-types) in the documentation or consider [creating a plugin](https://github.com/chartjs/Chart.js/blob/master/docs/09-Advanced.md#creating-plugins). To keep the library lightweight for everyone, it's unlikely we'll add many more chart types to the core of Chart.js, but issues are a good medium to design and spec out how new chart types could work and look.
false
Other
chartjs
Chart.js
a5167cc42d397491247e406253afd006ba6b33b5.json
Reduce duplicated code in doughnut controller
src/controllers/controller.doughnut.js
@@ -220,10 +220,8 @@ module.exports = function(Chart) { }); var model = arc._model; - model.backgroundColor = custom.backgroundColor ? custom.backgroundColor : valueAtIndexOrDefault(dataset.backgroundColor, index, arcOpts.backgroundColor); - model.hoverBackgroundColor = custom.hoverBackgroundColor ? custom.hoverBackgroundColor : valueAtIndexOrDefault(dataset.hoverBackgroundColor, index, arcOpts.hoverBackgroundColor); - model.borderWidth = custom.borderWidth ? custom.borderWidth : valueAtIndexOrDefault(dataset.borderWidth, index, arcOpts.borderWidth); - model.borderColor = custom.borderColor ? custom.borderColor : valueAtIndexOrDefault(dataset.borderColor, index, arcOpts.borderColor); + // Resets the visual styles + this.removeHoverStyle(arc); // Set correct angles if not resetting if (!reset || !animationOpts.animateRotate) {
true
Other
chartjs
Chart.js
a5167cc42d397491247e406253afd006ba6b33b5.json
Reduce duplicated code in doughnut controller
test/controller.doughnut.tests.js
@@ -75,8 +75,7 @@ describe('Doughnut controller tests', function() { arc: { backgroundColor: 'rgb(255, 0, 0)', borderColor: 'rgb(0, 0, 255)', - borderWidth: 2, - hoverBackgroundColor: 'rgb(255, 255, 255)' + borderWidth: 2 } } } @@ -102,7 +101,6 @@ describe('Doughnut controller tests', function() { startAngle: Math.PI * -0.5, endAngle: Math.PI * -0.5, label: chart.data.labels[i], - hoverBackgroundColor: 'rgb(255, 255, 255)', backgroundColor: 'rgb(255, 0, 0)', borderColor: 'rgb(0, 0, 255)', borderWidth: 2 @@ -125,7 +123,6 @@ describe('Doughnut controller tests', function() { expect(meta.data[i]._model.endAngle).toBeCloseTo(expected.e, 8); expect(meta.data[i]._model).toEqual(jasmine.objectContaining({ label: chart.data.labels[i], - hoverBackgroundColor: 'rgb(255, 255, 255)', backgroundColor: 'rgb(255, 0, 0)', borderColor: 'rgb(0, 0, 255)', borderWidth: 2 @@ -173,8 +170,7 @@ describe('Doughnut controller tests', function() { arc: { backgroundColor: 'rgb(255, 0, 0)', borderColor: 'rgb(0, 0, 255)', - borderWidth: 2, - hoverBackgroundColor: 'rgb(255, 255, 255)' + borderWidth: 2 } } }
true
Other
chartjs
Chart.js
bd6c4870af3ce2e6ed85b030907835a694b08619.json
Update colors for chart that is created
docs/04-Bar-Chart.md
@@ -58,11 +58,23 @@ var data = { datasets: [ { label: "My First dataset", - backgroundColor: "rgba(255,99,132,0.2)", - borderColor: "rgba(255,99,132,1)", - borderWidth: 1, - hoverBackgroundColor: "rgba(255,99,132,0.4)", - hoverBorderColor: "rgba(255,99,132,1)", + backgroundColor: [ + 'rgba(255, 99, 132, 0.2)', + 'rgba(54, 162, 235, 0.2)', + 'rgba(255, 206, 86, 0.2)', + 'rgba(75, 192, 192, 0.2)', + 'rgba(153, 102, 255, 0.2)', + 'rgba(255, 159, 64, 0.2)' + ], + borderColor: [ + 'rgba(255,99,132,1)', + 'rgba(54, 162, 235, 1)', + 'rgba(255, 206, 86, 1)', + 'rgba(75, 192, 192, 1)', + 'rgba(153, 102, 255, 1)', + 'rgba(255, 159, 64, 1)' + ], + borderWidth: 1 data: [65, 59, 80, 81, 56, 55, 40], } ]
false
Other
chartjs
Chart.js
876ddc89313cef693771a70b571d844b062e7fc4.json
Update radial linear scale docs
docs/02-Scales.md
@@ -340,8 +340,15 @@ Name | Type | Default | Description backdropColor | Color | 'rgba(255, 255, 255, 0.75)' | Color of label backdrops backdropPaddingX | Number | 2 | Horizontal padding of label backdrop backdropPaddingY | Number | 2 | Vertical padding of label backdrop +beginAtZero | Boolean | - | if true, scale will inclulde 0 if it is not already included. +min | Number | - | User defined minimum number for the scale, overrides minimum value from data. +max | Number | - | User defined maximum number for the scale, overrides maximum value from data. maxTicksLimit | Number | 11 | Maximum number of ticks and gridlines to show. If not defined, it will limit to 11 ticks but will show all gridlines. showLabelBackdrop | Boolean | true | If true, draw a background behind the tick labels +stepSize | Number | - | User defined fixed step size for the scale. If set, the scale ticks will be enumerated by multiple of stepSize, having one tick per increment. If not set, the ticks are labeled automatically using the nice numbers algorithm. +stepSize | Number | - | if defined, it can be used along with the min and the max to give a custom number of steps. See the example below. +suggestedMax | Number | - | User defined maximum number for the scale, overrides maximum value *except for if* it is lower than the maximum value. +suggestedMin | Number | - | User defined minimum number for the scale, overrides minimum value *except for if* it is higher than the minimum value. ### Update Default Scale config
false
Other
chartjs
Chart.js
6bc917c8e3168aee488f1b716bc1dbd174c52b95.json
Improve testing on the CI
src/core/core.tooltip.js
@@ -282,10 +282,10 @@ module.exports = function(Chart) { model.opacity = 1; var labelColors = [], - tooltipPosition = tooltipPosition = getAveragePosition(active); + tooltipPosition = getAveragePosition(active); var tooltipItems = []; - for (var i = 0, len = active.length; i < len; ++i) { + for (i = 0, len = active.length; i < len; ++i) { tooltipItems.push(createTooltipItem(active[i])); } @@ -601,7 +601,7 @@ module.exports = function(Chart) { var bodyColor = helpers.color(vm.bodyColor); var textColor = bodyColor.alpha(opacity * bodyColor.alpha()).rgbString(); - ctx.fillStyle = textColor + ctx.fillStyle = textColor; ctx.font = helpers.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily); // Before Body @@ -615,7 +615,7 @@ module.exports = function(Chart) { helpers.each(vm.beforeBody, fillLineOfText); var drawColorBoxes = body.length > 1; - xLinePadding = drawColorBoxes ? (bodyFontSize + 2) : 0 + xLinePadding = drawColorBoxes ? (bodyFontSize + 2) : 0; // Draw body lines now helpers.each(body, function(bodyItem, i) {
true
Other
chartjs
Chart.js
6bc917c8e3168aee488f1b716bc1dbd174c52b95.json
Improve testing on the CI
test/core.tooltip.tests.js
@@ -109,8 +109,6 @@ describe('tooltip tests', function() { }], afterBody: [], footer: [], - x: 269, - y: 155, caretPadding: 2, labelColors: [{ borderColor: 'rgb(255, 0, 0)', @@ -120,6 +118,9 @@ describe('tooltip tests', function() { backgroundColor: 'rgb(0, 255, 255)' }] })); + + expect(tooltip._view.x).toBeCloseToPixel(269); + expect(tooltip._view.y).toBeCloseToPixel(155); }); it('Should display in single mode', function() { @@ -218,11 +219,12 @@ describe('tooltip tests', function() { }], afterBody: [], footer: [], - x: 269, - y: 312, caretPadding: 2, labelColors: [] })); + + expect(tooltip._view.x).toBeCloseToPixel(269); + expect(tooltip._view.y).toBeCloseToPixel(312); }); it('Should display information from user callbacks', function() { @@ -360,8 +362,6 @@ describe('tooltip tests', function() { }], afterBody: ['afterBody'], footer: ['beforeFooter', 'footer', 'afterFooter'], - x: 216, - y: 190, caretPadding: 2, labelColors: [{ borderColor: 'rgb(255, 0, 0)', @@ -371,6 +371,9 @@ describe('tooltip tests', function() { backgroundColor: 'rgb(0, 255, 255)' }] })); + + expect(tooltip._view.x).toBeCloseToPixel(216); + expect(tooltip._view.y).toBeCloseToPixel(190); }); it('Should display information from user callbacks', function() { @@ -443,8 +446,6 @@ describe('tooltip tests', function() { }], afterBody: [], footer: [], - x: 269, - y: 155, labelColors: [{ borderColor: 'rgb(0, 0, 255)', backgroundColor: 'rgb(0, 255, 255)' @@ -453,5 +454,8 @@ describe('tooltip tests', function() { backgroundColor: 'rgb(0, 255, 0)' }] })); + + expect(tooltip._view.x).toBeCloseToPixel(269); + expect(tooltip._view.y).toBeCloseToPixel(155); }); });
true
Other
chartjs
Chart.js
da1c51f1492c48ba8738896d4256bc2d77302777.json
Improve testing on CI
test/core.tooltip.tests.js
@@ -109,8 +109,6 @@ describe('tooltip tests', function() { }], afterBody: [], footer: [], - x: 269, - y: 155, caretPadding: 2, labelColors: [{ borderColor: 'rgb(255, 0, 0)', @@ -120,6 +118,9 @@ describe('tooltip tests', function() { backgroundColor: 'rgb(0, 255, 255)' }] })); + + expect(tooltip._view.x).toBeCloseTo(269, 1); + expect(tooltip._view.y).toBeCloseTo(155, 1); }); it('Should display in single mode', function() { @@ -218,11 +219,12 @@ describe('tooltip tests', function() { }], afterBody: [], footer: [], - x: 269, - y: 312, caretPadding: 2, labelColors: [] })); + + expect(tooltip._view.x).toBeCloseTo(269, 1); + expect(tooltip._view.y).toBeCloseTo(312, 1); }); it('Should display information from user callbacks', function() { @@ -360,8 +362,6 @@ describe('tooltip tests', function() { }], afterBody: ['afterBody'], footer: ['beforeFooter', 'footer', 'afterFooter'], - x: 216, - y: 190, caretPadding: 2, labelColors: [{ borderColor: 'rgb(255, 0, 0)', @@ -371,6 +371,9 @@ describe('tooltip tests', function() { backgroundColor: 'rgb(0, 255, 255)' }] })); + + expect(tooltip._view.x).toBeCloseTo(216, 1); + expect(tooltip._view.y).toBeCloseTo(190, 1); }); it('Should display information from user callbacks', function() { @@ -443,8 +446,6 @@ describe('tooltip tests', function() { }], afterBody: [], footer: [], - x: 269, - y: 155, labelColors: [{ borderColor: 'rgb(0, 0, 255)', backgroundColor: 'rgb(0, 255, 255)' @@ -453,5 +454,8 @@ describe('tooltip tests', function() { backgroundColor: 'rgb(0, 255, 0)' }] })); + + expect(tooltip._view.x).toBeCloseTo(269, 1); + expect(tooltip._view.y).toBeCloseTo(155, 1); }); });
false
Other
chartjs
Chart.js
af5344462e64f40c96741bf937f2bffa1fc39a72.json
Improve tooltip minification
src/core/core.helpers.js
@@ -953,17 +953,6 @@ module.exports = function(Chart) { return true; }; - helpers.pushAllIfDefined = function(element, array) { - if (typeof element === "undefined") { - return; - } - - if (helpers.isArray(element)) { - array.push.apply(array, element); - } else { - array.push(element); - } - }; helpers.callCallback = function(fn, args, _tArg) { if (fn && typeof fn.call === 'function') { fn.apply(_tArg, args);
true
Other
chartjs
Chart.js
af5344462e64f40c96741bf937f2bffa1fc39a72.json
Improve tooltip minification
src/core/core.tooltip.js
@@ -35,12 +35,16 @@ module.exports = function(Chart) { title: function(tooltipItems, data) { // Pick first xLabel for now var title = ''; + var labels = data.labels; + var labelCount = labels ? labels.length : 0; if (tooltipItems.length > 0) { - if (tooltipItems[0].xLabel) { - title = tooltipItems[0].xLabel; - } else if (data.labels.length > 0 && tooltipItems[0].index < data.labels.length) { - title = data.labels[tooltipItems[0].index]; + var item = tooltipItems[0]; + + if (item.xLabel) { + title = item.xLabel; + } else if (labelCount > 0 && item.index < labelCount) { + title = labels[item.index]; } } @@ -91,12 +95,62 @@ module.exports = function(Chart) { return base; } + function getAveragePosition(elements) { + if (!elements.length) { + return false; + } + + var i, len; + var xPositions = []; + var yPositions = []; + + for (i = 0, len = elements.length; i < len; ++i) { + var el = elements[i]; + if (el && el.hasValue()){ + var pos = el.tooltipPosition(); + xPositions.push(pos.x); + yPositions.push(pos.y); + } + } + + var x = 0, + y = 0; + for (i = 0, len - xPositions.length; i < len; ++i) { + x += xPositions[i]; + y += yPositions[i]; + } + + return { + x: Math.round(x / xPositions.length), + y: Math.round(y / xPositions.length) + }; + } + + // Private helper to create a tooltip iteam model + // @param element : the chart element (point, arc, bar) to create the tooltip item for + // @return : new tooltip item + function createTooltipItem(element) { + var xScale = element._xScale; + var yScale = element._yScale || element._scale; // handle radar || polarArea charts + var index = element._index, + datasetIndex = element._datasetIndex; + + return { + xLabel: xScale ? xScale.getLabelForIndex(index, datasetIndex) : '', + yLabel: yScale ? yScale.getLabelForIndex(index, datasetIndex) : '', + index: index, + datasetIndex: datasetIndex + }; + } + Chart.Tooltip = Chart.Element.extend({ initialize: function() { + var me = this; var globalDefaults = Chart.defaults.global; - var tooltipOpts = this._options; + var tooltipOpts = me._options; + var getValueOrDefault = helpers.getValueOrDefault; - helpers.extend(this, { + helpers.extend(me, { _model: { // Positioning xPadding: tooltipOpts.xPadding, @@ -106,26 +160,26 @@ module.exports = function(Chart) { // Body bodyColor: tooltipOpts.bodyColor, - _bodyFontFamily: helpers.getValueOrDefault(tooltipOpts.bodyFontFamily, globalDefaults.defaultFontFamily), - _bodyFontStyle: helpers.getValueOrDefault(tooltipOpts.bodyFontStyle, globalDefaults.defaultFontStyle), + _bodyFontFamily: getValueOrDefault(tooltipOpts.bodyFontFamily, globalDefaults.defaultFontFamily), + _bodyFontStyle: getValueOrDefault(tooltipOpts.bodyFontStyle, globalDefaults.defaultFontStyle), _bodyAlign: tooltipOpts.bodyAlign, - bodyFontSize: helpers.getValueOrDefault(tooltipOpts.bodyFontSize, globalDefaults.defaultFontSize), + bodyFontSize: getValueOrDefault(tooltipOpts.bodyFontSize, globalDefaults.defaultFontSize), bodySpacing: tooltipOpts.bodySpacing, // Title titleColor: tooltipOpts.titleColor, - _titleFontFamily: helpers.getValueOrDefault(tooltipOpts.titleFontFamily, globalDefaults.defaultFontFamily), - _titleFontStyle: helpers.getValueOrDefault(tooltipOpts.titleFontStyle, globalDefaults.defaultFontStyle), - titleFontSize: helpers.getValueOrDefault(tooltipOpts.titleFontSize, globalDefaults.defaultFontSize), + _titleFontFamily: getValueOrDefault(tooltipOpts.titleFontFamily, globalDefaults.defaultFontFamily), + _titleFontStyle: getValueOrDefault(tooltipOpts.titleFontStyle, globalDefaults.defaultFontStyle), + titleFontSize: getValueOrDefault(tooltipOpts.titleFontSize, globalDefaults.defaultFontSize), _titleAlign: tooltipOpts.titleAlign, titleSpacing: tooltipOpts.titleSpacing, titleMarginBottom: tooltipOpts.titleMarginBottom, // Footer footerColor: tooltipOpts.footerColor, - _footerFontFamily: helpers.getValueOrDefault(tooltipOpts.footerFontFamily, globalDefaults.defaultFontFamily), - _footerFontStyle: helpers.getValueOrDefault(tooltipOpts.footerFontStyle, globalDefaults.defaultFontStyle), - footerFontSize: helpers.getValueOrDefault(tooltipOpts.footerFontSize, globalDefaults.defaultFontSize), + _footerFontFamily: getValueOrDefault(tooltipOpts.footerFontFamily, globalDefaults.defaultFontFamily), + _footerFontStyle: getValueOrDefault(tooltipOpts.footerFontStyle, globalDefaults.defaultFontStyle), + footerFontSize: getValueOrDefault(tooltipOpts.footerFontSize, globalDefaults.defaultFontSize), _footerAlign: tooltipOpts.footerAlign, footerSpacing: tooltipOpts.footerSpacing, footerMarginTop: tooltipOpts.footerMarginTop, @@ -143,9 +197,13 @@ module.exports = function(Chart) { // Get the title // Args are: (tooltipItem, data) getTitle: function() { - var beforeTitle = this._options.callbacks.beforeTitle.apply(this, arguments), - title = this._options.callbacks.title.apply(this, arguments), - afterTitle = this._options.callbacks.afterTitle.apply(this, arguments); + var me = this; + var opts = me._options; + var callbacks = opts.callbacks; + + var beforeTitle = callbacks.beforeTitle.apply(me, arguments), + title = callbacks.title.apply(me, arguments), + afterTitle = callbacks.afterTitle.apply(me, arguments); var lines = []; lines = pushOrConcat(lines, beforeTitle); @@ -157,12 +215,15 @@ module.exports = function(Chart) { // Args are: (tooltipItem, data) getBeforeBody: function() { - var lines = this._options.callbacks.beforeBody.apply(this, arguments); + var me = this; + var lines = me._options.callbacks.beforeBody.apply(me, arguments); return helpers.isArray(lines) ? lines : lines !== undefined ? [lines] : []; }, // Args are: (tooltipItem, data) getBody: function(tooltipItems, data) { + var me = this; + var callbacks = me._options.callbacks; var bodyItems = []; helpers.each(tooltipItems, function(tooltipItem) { @@ -171,28 +232,32 @@ module.exports = function(Chart) { lines: [], after: [] }; - helpers.pushAllIfDefined(this._options.callbacks.beforeLabel.call(this, tooltipItem, data), bodyItem.before); - helpers.pushAllIfDefined(this._options.callbacks.label.call(this, tooltipItem, data), bodyItem.lines); - helpers.pushAllIfDefined(this._options.callbacks.afterLabel.call(this, tooltipItem, data), bodyItem.after); + pushOrConcat(bodyItem.before, callbacks.beforeLabel.call(me, tooltipItem, data)); + pushOrConcat(bodyItem.lines, callbacks.label.call(me, tooltipItem, data)); + pushOrConcat(bodyItem.after, callbacks.afterLabel.call(me, tooltipItem, data)); bodyItems.push(bodyItem); - }, this); + }); return bodyItems; }, // Args are: (tooltipItem, data) getAfterBody: function() { - var lines = this._options.callbacks.afterBody.apply(this, arguments); + var me = this; + var lines = me._options.callbacks.afterBody.apply(me, arguments); return helpers.isArray(lines) ? lines : lines !== undefined ? [lines] : []; }, // Get the footer and beforeFooter and afterFooter lines // Args are: (tooltipItem, data) getFooter: function() { - var beforeFooter = this._options.callbacks.beforeFooter.apply(this, arguments); - var footer = this._options.callbacks.footer.apply(this, arguments); - var afterFooter = this._options.callbacks.afterFooter.apply(this, arguments); + var me = this; + var callbacks = me._options.callbacks; + + var beforeFooter = callbacks.beforeFooter.apply(me, arguments); + var footer = callbacks.footer.apply(me, arguments); + var afterFooter = callbacks.afterFooter.apply(me, arguments); var lines = []; lines = pushOrConcat(lines, beforeFooter); @@ -202,179 +267,146 @@ module.exports = function(Chart) { return lines; }, - getAveragePosition: function(elements) { - - if (!elements.length) { - return false; - } - - var xPositions = []; - var yPositions = []; - - helpers.each(elements, function(el) { - if (el && el.hasValue()){ - var pos = el.tooltipPosition(); - xPositions.push(pos.x); - yPositions.push(pos.y); - } - }); - - var x = 0, - y = 0; - for (var i = 0; i < xPositions.length; i++) { - x += xPositions[i]; - y += yPositions[i]; - } + update: function(changed) { + var me = this; + var opts = me._options; + var model = me._model; + var active = me._active; + var data = me._data; + var chartInstance = me._chartInstance; - return { - x: Math.round(x / xPositions.length), - y: Math.round(y / xPositions.length) - }; + var i, len; - }, + if (active.length) { + model.opacity = 1; - update: function(changed) { - if (this._active.length) { - this._model.opacity = 1; - - var element = this._active[0], + var element = active[0], labelColors = [], - tooltipPosition; + tooltipPosition = tooltipPosition = getAveragePosition(active); var tooltipItems = []; + for (var i = 0, len = active.length; i < len; ++i) { + tooltipItems.push(createTooltipItem(active[i])); + } - if (this._options.mode === 'single') { - var yScale = element._yScale || element._scale; // handle radar || polarArea charts - tooltipItems.push({ - xLabel: element._xScale ? element._xScale.getLabelForIndex(element._index, element._datasetIndex) : '', - yLabel: yScale ? yScale.getLabelForIndex(element._index, element._datasetIndex) : '', - index: element._index, - datasetIndex: element._datasetIndex - }); - tooltipPosition = this.getAveragePosition(this._active); - } else { - helpers.each(this._data.datasets, function(dataset, datasetIndex) { - if (!this._chartInstance.isDatasetVisible(datasetIndex)) { - return; - } - - var meta = this._chartInstance.getDatasetMeta(datasetIndex); - var currentElement = meta.data[element._index]; - if (currentElement) { - var yScale = element._yScale || element._scale; // handle radar || polarArea charts - - tooltipItems.push({ - xLabel: currentElement._xScale ? currentElement._xScale.getLabelForIndex(currentElement._index, currentElement._datasetIndex) : '', - yLabel: yScale ? yScale.getLabelForIndex(currentElement._index, currentElement._datasetIndex) : '', - index: element._index, - datasetIndex: datasetIndex - }); - } - }, this); - + // If there is more than one item, show color items + if (active.length > 1) { helpers.each(tooltipItems, function(tooltipItem) { - labelColors.push(this._options.callbacks.labelColor.call(this, tooltipItem, this._chartInstance)); - }, this); - - tooltipPosition = this.getAveragePosition(this._active); + labelColors.push(opts.callbacks.labelColor.call(me, tooltipItem, chartInstance)); + }); } // Build the Text Lines - helpers.extend(this._model, { - title: this.getTitle(tooltipItems, this._data), - beforeBody: this.getBeforeBody(tooltipItems, this._data), - body: this.getBody(tooltipItems, this._data), - afterBody: this.getAfterBody(tooltipItems, this._data), - footer: this.getFooter(tooltipItems, this._data), + helpers.extend(model, { + title: me.getTitle(tooltipItems, data), + beforeBody: me.getBeforeBody(tooltipItems, data), + body: me.getBody(tooltipItems, data), + afterBody: me.getAfterBody(tooltipItems, data), + footer: me.getFooter(tooltipItems, data), x: Math.round(tooltipPosition.x), y: Math.round(tooltipPosition.y), caretPadding: helpers.getValueOrDefault(tooltipPosition.padding, 2), labelColors: labelColors }); // We need to determine alignment of - var tooltipSize = this.getTooltipSize(this._model); - this.determineAlignment(tooltipSize); // Smart Tooltip placement to stay on the canvas + var tooltipSize = me.getTooltipSize(model); + me.determineAlignment(tooltipSize); // Smart Tooltip placement to stay on the canvas - helpers.extend(this._model, this.getBackgroundPoint(this._model, tooltipSize)); + helpers.extend(model, me.getBackgroundPoint(model, tooltipSize)); } else { - this._model.opacity = 0; + me._model.opacity = 0; } - if (changed && this._options.custom) { - this._options.custom.call(this, this._model); + if (changed && opts.custom) { + opts.custom.call(me, model); } - return this; + return me; }, getTooltipSize: function getTooltipSize(vm) { - var ctx = this._chart.ctx; + var me = this; + var ctx = me._chart.ctx; var size = { height: vm.yPadding * 2, // Tooltip Padding width: 0 }; - - var combinedBodyLength = vm.body.reduce(function(count, bodyItem) { + // Count of all lines in the body + var body = vm.body; + var combinedBodyLength = body.reduce(function(count, bodyItem) { return count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length; }, 0); - // Count in before and after body sections combinedBodyLength += vm.beforeBody.length + vm.afterBody.length; - size.height += vm.title.length * vm.titleFontSize; // Title Lines - size.height += (vm.title.length - 1) * vm.titleSpacing; // Title Line Spacing - size.height += vm.title.length ? vm.titleMarginBottom : 0; // Title's bottom Margin - size.height += combinedBodyLength * vm.bodyFontSize; // Body Lines + var titleLineCount = vm.title.length; + var footerLineCount = vm.footer.length; + var titleFontSize = vm.titleFontSize, + bodyFontSize = vm.bodyFontSize, + footerFontSize = vm.footerFontSize; + + size.height += titleLineCount * titleFontSize; // Title Lines + size.height += (titleLineCount - 1) * vm.titleSpacing; // Title Line Spacing + size.height += titleLineCount ? vm.titleMarginBottom : 0; // Title's bottom Margin + size.height += combinedBodyLength * bodyFontSize; // Body Lines size.height += combinedBodyLength ? (combinedBodyLength - 1) * vm.bodySpacing : 0; // Body Line Spacing - size.height += vm.footer.length ? vm.footerMarginTop : 0; // Footer Margin - size.height += vm.footer.length * (vm.footerFontSize); // Footer Lines - size.height += vm.footer.length ? (vm.footer.length - 1) * vm.footerSpacing : 0; // Footer Line Spacing - - // Width - ctx.font = helpers.fontString(vm.titleFontSize, vm._titleFontStyle, vm._titleFontFamily); - helpers.each(vm.title, function(line) { - size.width = Math.max(size.width, ctx.measureText(line).width); - }); + size.height += footerLineCount ? vm.footerMarginTop : 0; // Footer Margin + size.height += footerLineCount * (footerFontSize); // Footer Lines + size.height += footerLineCount ? (footerLineCount - 1) * vm.footerSpacing : 0; // Footer Line Spacing + + // Title width + var widthPadding = 0; + var maxLineWidth = function(line) { + size.width = Math.max(size.width, ctx.measureText(line).width + widthPadding); + }; - ctx.font = helpers.fontString(vm.bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily); - helpers.each(vm.beforeBody.concat(vm.afterBody), function(line) { - size.width = Math.max(size.width, ctx.measureText(line).width); - }); + ctx.font = helpers.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily); + helpers.each(vm.title, maxLineWidth); - var _this = this; - var maxBodyWidth = function(line) { - size.width = Math.max(size.width, ctx.measureText(line).width + (_this._options.mode !== 'single' ? (vm.bodyFontSize + 2) : 0)); - }; - helpers.each(vm.body, function(bodyItem) { - helpers.each(bodyItem.before, maxBodyWidth); - helpers.each(bodyItem.lines, maxBodyWidth); - helpers.each(bodyItem.after, maxBodyWidth); - }); + // Body width + ctx.font = helpers.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily); + helpers.each(vm.beforeBody.concat(vm.afterBody), maxLineWidth); - ctx.font = helpers.fontString(vm.footerFontSize, vm._footerFontStyle, vm._footerFontFamily); - helpers.each(vm.footer, function(line) { - size.width = Math.max(size.width, ctx.measureText(line).width); + // Body lines may include some extra width due to the color box + widthPadding = body.length > 1 ? (bodyFontSize + 2) : 0; + helpers.each(body, function(bodyItem) { + helpers.each(bodyItem.before, maxLineWidth); + helpers.each(bodyItem.lines, maxLineWidth); + helpers.each(bodyItem.after, maxLineWidth); }); + + // Reset back to 0 + widthPadding = 0; + + // Footer width + ctx.font = helpers.fontString(footerFontSize, vm._footerFontStyle, vm._footerFontFamily); + helpers.each(vm.footer, maxLineWidth); + + // Add padding size.width += 2 * vm.xPadding; return size; }, determineAlignment: function determineAlignment(size) { - if (this._model.y < size.height) { - this._model.yAlign = 'top'; - } else if (this._model.y > (this._chart.height - size.height)) { - this._model.yAlign = 'bottom'; + var me = this; + var model = me._model; + var chart = me._chart; + var chartArea = me._chartInstance.chartArea; + + if (model.y < size.height) { + model.yAlign = 'top'; + } else if (model.y > (chart.height - size.height)) { + model.yAlign = 'bottom'; } var lf, rf; // functions to determine left, right alignment var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges - var _this = this; - var midX = (this._chartInstance.chartArea.left + this._chartInstance.chartArea.right) / 2; - var midY = (this._chartInstance.chartArea.top + this._chartInstance.chartArea.bottom) / 2; + var midX = (chartArea.left + chartArea.right) / 2; + var midY = (chartArea.top + chartArea.bottom) / 2; - if (this._model.yAlign === 'center') { + if (model.yAlign === 'center') { lf = function(x) { return x <= midX; }; @@ -386,12 +418,12 @@ module.exports = function(Chart) { return x <= (size.width / 2); }; rf = function(x) { - return x >= (_this._chart.width - (size.width / 2)); + return x >= (chart.width - (size.width / 2)); }; } olf = function(x) { - return x + size.width > _this._chart.width; + return x + size.width > chart.width; }; orf = function(x) { return x - size.width < 0; @@ -400,21 +432,21 @@ module.exports = function(Chart) { return y <= midY ? 'top' : 'bottom'; }; - if (lf(this._model.x)) { - this._model.xAlign = 'left'; + if (lf(model.x)) { + model.xAlign = 'left'; // Is tooltip too wide and goes over the right side of the chart.? - if (olf(this._model.x)) { - this._model.xAlign = 'center'; - this._model.yAlign = yf(this._model.y); + if (olf(model.x)) { + model.xAlign = 'center'; + model.yAlign = yf(model.y); } - } else if (rf(this._model.x)) { - this._model.xAlign = 'right'; + } else if (rf(model.x)) { + model.xAlign = 'right'; // Is tooltip too wide and goes outside left edge of canvas? - if (orf(this._model.x)) { - this._model.xAlign = 'center'; - this._model.yAlign = yf(this._model.y); + if (orf(model.x)) { + model.xAlign = 'center'; + model.yAlign = yf(model.y); } } }, @@ -425,79 +457,96 @@ module.exports = function(Chart) { y: vm.y }; - if (vm.xAlign === 'right') { + var caretSize = vm.caretSize, + caretPadding = vm.caretPadding, + cornerRadius = vm.cornerRadius, + xAlign = vm.xAlign, + yAlign = vm.yAlign, + paddingAndSize = caretSize + caretPadding, + radiusAndPadding = cornerRadius + caretPadding; + + if (xAlign === 'right') { pt.x -= size.width; - } else if (vm.xAlign === 'center') { + } else if (xAlign === 'center') { pt.x -= (size.width / 2); } - if (vm.yAlign === 'top') { - pt.y += vm.caretPadding + vm.caretSize; - } else if (vm.yAlign === 'bottom') { - pt.y -= size.height + vm.caretPadding + vm.caretSize; + if (yAlign === 'top') { + pt.y += paddingAndSize; + } else if (yAlign === 'bottom') { + pt.y -= size.height + paddingAndSize; } else { pt.y -= (size.height / 2); } - if (vm.yAlign === 'center') { - if (vm.xAlign === 'left') { - pt.x += vm.caretPadding + vm.caretSize; - } else if (vm.xAlign === 'right') { - pt.x -= vm.caretPadding + vm.caretSize; + if (yAlign === 'center') { + if (xAlign === 'left') { + pt.x += paddingAndSize; + } else if (xAlign === 'right') { + pt.x -= paddingAndSize; } } else { - if (vm.xAlign === 'left') { - pt.x -= vm.cornerRadius + vm.caretPadding; - } else if (vm.xAlign === 'right') { - pt.x += vm.cornerRadius + vm.caretPadding; + if (xAlign === 'left') { + pt.x -= radiusAndPadding; + } else if (xAlign === 'right') { + pt.x += radiusAndPadding; } } return pt; }, drawCaret: function drawCaret(tooltipPoint, size, opacity, caretPadding) { - var vm = this._view; - var ctx = this._chart.ctx; + var me = this; + var vm = me._view; + var ctx = me._chart.ctx; var x1, x2, x3; var y1, y2, y3; - - if (vm.yAlign === 'center') { + var caretSize = vm.caretSize; + var cornerRadius = vm.cornerRadius; + var xAlign = vm.xAlign, + yAlign = vm.yAlign; + var ptX = tooltipPoint.x, + ptY = tooltipPoint.y; + var width = size.width, + height = size.height; + + if (yAlign === 'center') { // Left or right side - if (vm.xAlign === 'left') { - x1 = tooltipPoint.x; - x2 = x1 - vm.caretSize; + if (xAlign === 'left') { + x1 = ptX; + x2 = x1 - caretSize; x3 = x1; } else { - x1 = tooltipPoint.x + size.width; - x2 = x1 + vm.caretSize; + x1 = ptX + width; + x2 = x1 + caretSize; x3 = x1; } - y2 = tooltipPoint.y + (size.height / 2); - y1 = y2 - vm.caretSize; - y3 = y2 + vm.caretSize; + y2 = ptY + (height / 2); + y1 = y2 - caretSize; + y3 = y2 + caretSize; } else { - if (vm.xAlign === 'left') { - x1 = tooltipPoint.x + vm.cornerRadius; - x2 = x1 + vm.caretSize; - x3 = x2 + vm.caretSize; - } else if (vm.xAlign === 'right') { - x1 = tooltipPoint.x + size.width - vm.cornerRadius; - x2 = x1 - vm.caretSize; - x3 = x2 - vm.caretSize; + if (xAlign === 'left') { + x1 = ptX + cornerRadius; + x2 = x1 + caretSize; + x3 = x2 + caretSize; + } else if (xAlign === 'right') { + x1 = ptX + width - cornerRadius; + x2 = x1 - caretSize; + x3 = x2 - caretSize; } else { - x2 = tooltipPoint.x + (size.width / 2); - x1 = x2 - vm.caretSize; - x3 = x2 + vm.caretSize; + x2 = ptX + (width / 2); + x1 = x2 - caretSize; + x3 = x2 + caretSize; } - if (vm.yAlign === 'top') { - y1 = tooltipPoint.y; - y2 = y1 - vm.caretSize; + if (yAlign === 'top') { + y1 = ptY; + y2 = y1 - caretSize; y3 = y1; } else { - y1 = tooltipPoint.y + size.height; - y2 = y1 + vm.caretSize; + y1 = ptY + height; + y2 = y1 + caretSize; y3 = y1; } } @@ -512,82 +561,96 @@ module.exports = function(Chart) { ctx.fill(); }, drawTitle: function drawTitle(pt, vm, ctx, opacity) { - if (vm.title.length) { + var title = vm.title; + + if (title.length) { ctx.textAlign = vm._titleAlign; ctx.textBaseline = "top"; + var titleFontSize = vm.titleFontSize, + titleSpacing = vm.titleSpacing; + var titleColor = helpers.color(vm.titleColor); ctx.fillStyle = titleColor.alpha(opacity * titleColor.alpha()).rgbString(); - ctx.font = helpers.fontString(vm.titleFontSize, vm._titleFontStyle, vm._titleFontFamily); + ctx.font = helpers.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily); - helpers.each(vm.title, function(title, i) { - ctx.fillText(title, pt.x, pt.y); - pt.y += vm.titleFontSize + vm.titleSpacing; // Line Height and spacing + var i, len; + for (i = 0, len = title.length; i < len; ++i) { + ctx.fillText(title[i], pt.x, pt.y); + pt.y += titleFontSize + titleSpacing; // Line Height and spacing - if (i + 1 === vm.title.length) { - pt.y += vm.titleMarginBottom - vm.titleSpacing; // If Last, add margin, remove spacing + if (i + 1 === title.length) { + pt.y += vm.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing } - }); + } } }, drawBody: function drawBody(pt, vm, ctx, opacity) { + var me = this; + var bodyFontSize = vm.bodyFontSize; + var bodySpacing = vm.bodySpacing; + var body = vm.body; + ctx.textAlign = vm._bodyAlign; ctx.textBaseline = "top"; var bodyColor = helpers.color(vm.bodyColor); - ctx.fillStyle = bodyColor.alpha(opacity * bodyColor.alpha()).rgbString(); - ctx.font = helpers.fontString(vm.bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily); + var textColor = bodyColor.alpha(opacity * bodyColor.alpha()).rgbString(); + ctx.fillStyle = textColor + ctx.font = helpers.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily); // Before Body - helpers.each(vm.beforeBody, function(beforeBody) { - ctx.fillText(beforeBody, pt.x, pt.y); - pt.y += vm.bodyFontSize + vm.bodySpacing; - }); + var xLinePadding = 0; + var fillLineOfText = function(line) { + ctx.fillText(line, pt.x + xLinePadding, pt.y); + pt.y += bodyFontSize + bodySpacing; + }; - helpers.each(vm.body, function(bodyItem, i) { - var _this = this; - var fillLine = function(line) { - // Body Line - ctx.fillText(line, pt.x + (_this._options.mode !== 'single' ? (vm.bodyFontSize + 2) : 0), pt.y); - pt.y += vm.bodyFontSize + vm.bodySpacing; - }; + // Before body lines + helpers.each(vm.beforeBody, fillLineOfText); - helpers.each(bodyItem.before, fillLine); + var drawColorBoxes = body.length > 1; + xLinePadding = drawColorBoxes ? (bodyFontSize + 2) : 0 + + // Draw body lines now + helpers.each(body, function(bodyItem, i) { + helpers.each(bodyItem.before, fillLineOfText); helpers.each(bodyItem.lines, function(line) { // Draw Legend-like boxes if needed - if (this._options.mode !== 'single') { + if (drawColorBoxes) { // Fill a white rect so that colours merge nicely if the opacity is < 1 ctx.fillStyle = helpers.color(vm.legendColorBackground).alpha(opacity).rgbaString(); - ctx.fillRect(pt.x, pt.y, vm.bodyFontSize, vm.bodyFontSize); + ctx.fillRect(pt.x, pt.y, bodyFontSize, bodyFontSize); // Border ctx.strokeStyle = helpers.color(vm.labelColors[i].borderColor).alpha(opacity).rgbaString(); - ctx.strokeRect(pt.x, pt.y, vm.bodyFontSize, vm.bodyFontSize); + ctx.strokeRect(pt.x, pt.y, bodyFontSize, bodyFontSize); // Inner square ctx.fillStyle = helpers.color(vm.labelColors[i].backgroundColor).alpha(opacity).rgbaString(); - ctx.fillRect(pt.x + 1, pt.y + 1, vm.bodyFontSize - 2, vm.bodyFontSize - 2); + ctx.fillRect(pt.x + 1, pt.y + 1, bodyFontSize - 2, bodyFontSize - 2); - ctx.fillStyle = helpers.color(vm.bodyColor).alpha(opacity).rgbaString(); // Return fill style for text + ctx.fillStyle = textColor; } - fillLine(line); - }, this); + fillLineOfText(line); + }); - helpers.each(bodyItem.after, fillLine); - }, this); - - // After Body - helpers.each(vm.afterBody, function(afterBody) { - ctx.fillText(afterBody, pt.x, pt.y); - pt.y += vm.bodyFontSize; + helpers.each(bodyItem.after, fillLineOfText); }); - pt.y -= vm.bodySpacing; // Remove last body spacing + // Reset back to 0 for after body + xLinePadding = 0; + + // After body lines + helpers.each(vm.afterBody, fillLineOfText); + pt.y -= bodySpacing; // Remove last body spacing }, drawFooter: function drawFooter(pt, vm, ctx, opacity) { - if (vm.footer.length) { + var footer = vm.footer; + + if (footer.length) { pt.y += vm.footerMarginTop; ctx.textAlign = vm._footerAlign; @@ -597,8 +660,8 @@ module.exports = function(Chart) { ctx.fillStyle = footerColor.alpha(opacity * footerColor.alpha()).rgbString(); ctx.font = helpers.fontString(vm.footerFontSize, vm._footerFontStyle, vm._footerFontFamily); - helpers.each(vm.footer, function(footer) { - ctx.fillText(footer, pt.x, pt.y); + helpers.each(footer, function(line) { + ctx.fillText(line, pt.x, pt.y); pt.y += vm.footerFontSize + vm.footerSpacing; }); } @@ -611,7 +674,6 @@ module.exports = function(Chart) { return; } - var caretPadding = vm.caretPadding; var tooltipSize = this.getTooltipSize(vm); var pt = { x: vm.x, @@ -629,7 +691,7 @@ module.exports = function(Chart) { ctx.fill(); // Draw Caret - this.drawCaret(pt, tooltipSize, opacity, caretPadding); + this.drawCaret(pt, tooltipSize, opacity, vm.caretPadding); // Draw Title, Body, and Footer pt.x += vm.xPadding;
true
Other
chartjs
Chart.js
1b277a71e4af83d19a87d09ffeb06841c275fce9.json
Fix pie custom tooltip sample
samples/pie-customTooltips.html
@@ -13,160 +13,142 @@ text-align: center; } #chartjs-tooltip { - opacity: 1; - position: absolute; - background: rgba(0, 0, 0, .7); - color: white; - padding: 3px; - border-radius: 3px; - -webkit-transition: all .1s ease; - transition: all .1s ease; - pointer-events: none; - -webkit-transform: translate(-50%, 0); - transform: translate(-50%, 0); + opacity: 1; + position: absolute; + background: rgba(0, 0, 0, .7); + color: white; + border-radius: 3px; + -webkit-transition: all .1s ease; + transition: all .1s ease; + pointer-events: none; + -webkit-transform: translate(-50%, 0); + transform: translate(-50%, 0); } - #chartjs-tooltip.below { - -webkit-transform: translate(-50%, 0); - transform: translate(-50%, 0); - } - #chartjs-tooltip.below:before { - border: solid; - border-color: #111 transparent; - border-color: rgba(0, 0, 0, .8) transparent; - border-width: 0 8px 8px 8px; - bottom: 1em; - content: ""; - display: block; - left: 50%; - position: absolute; - z-index: 99; - -webkit-transform: translate(-50%, -100%); - transform: translate(-50%, -100%); - } - #chartjs-tooltip.above { - -webkit-transform: translate(-50%, -100%); - transform: translate(-50%, -100%); - } - #chartjs-tooltip.above:before { - border: solid; - border-color: #111 transparent; - border-color: rgba(0, 0, 0, .8) transparent; - border-width: 8px 8px 0 8px; - bottom: 1em; - content: ""; - display: block; - left: 50%; - top: 100%; - position: absolute; - z-index: 99; - -webkit-transform: translate(-50%, 0); - transform: translate(-50%, 0); + + .chartjs-tooltip-key { + display: inline-block; + width: 10px; + height: 10px; } </style> </head> <body> - <div id="canvas-holder"> + <div id="canvas-holder" style="width: 50px;"> <canvas id="chart-area1" width="50" height="50" /> </div> - <div id="canvas-holder"> + <div id="canvas-holder" style="width: 300px;"> <canvas id="chart-area2" width="300" height="300" /> </div> <div id="chartjs-tooltip"></div> <script> - Chart.defaults.global.customTooltips = function(tooltip) { + Chart.defaults.global.tooltips.custom = function(tooltip) { // Tooltip Element - var tooltipEl = $('#chartjs-tooltip'); - - // Hide if no tooltip - if (!tooltip) { - tooltipEl.css({ - opacity: 0 - }); - return; - } - - // Set caret Position - tooltipEl.removeClass('above below'); - tooltipEl.addClass(tooltip.yAlign); + var tooltipEl = $('#chartjs-tooltip'); - // Set Text - tooltipEl.html(tooltip.text); + if (!tooltipEl[0]) { + $('body').append('<div id="chartjs-tooltip"></div>'); + tooltipEl = $('#chartjs-tooltip'); + } - // Find Y Location on page - var top; + // Hide if no tooltip + if (!tooltip.opacity) { + tooltipEl.css({ + opacity: 0 + }); + $('.chartjs-wrap canvas') + .each(function(index, el) { + $(el).css('cursor', 'default'); + }); + return; + } + + $(this._chart.canvas).css('cursor', 'pointer'); + + // Set caret Position + tooltipEl.removeClass('above below no-transform'); + if (tooltip.yAlign) { + tooltipEl.addClass(tooltip.yAlign); + } else { + tooltipEl.addClass('no-transform'); + } + + // Set Text + if (tooltip.body) { + var innerHtml = [ + (tooltip.beforeTitle || []).join('\n'), (tooltip.title || []).join('\n'), (tooltip.afterTitle || []).join('\n'), (tooltip.beforeBody || []).join('\n'), (tooltip.body || []).join('\n'), (tooltip.afterBody || []).join('\n'), (tooltip.beforeFooter || []) + .join('\n'), (tooltip.footer || []).join('\n'), (tooltip.afterFooter || []).join('\n') + ]; + tooltipEl.html(innerHtml.join('\n')); + } + + // Find Y Location on page + var top = 0; + if (tooltip.yAlign) { if (tooltip.yAlign == 'above') { - top = tooltip.y - tooltip.caretHeight - tooltip.caretPadding; + top = tooltip.y - tooltip.caretHeight - tooltip.caretPadding; } else { - top = tooltip.y + tooltip.caretHeight + tooltip.caretPadding; + top = tooltip.y + tooltip.caretHeight + tooltip.caretPadding; } - - //Function to find absolution position of the element and not just it's relative position - function getPosition (element) { - var top = 0, left = 0; - do { - top += element.offsetTop || 0; - left += element.offsetLeft || 0; - element = element.offsetParent; - } while (element); - - return { - top: top, - left: left - }; - }; - - //Finding absolute position of the chart canvas - var position = getPosition(tooltip.chart.canvas) - - // Display, position, and set styles for font - tooltipEl.css({ - opacity: 1, - left: position.left + tooltip.x + 'px', - top: position.top + top + 'px', - fontFamily: tooltip.fontFamily, - fontSize: tooltip.fontSize, - fontStyle: tooltip.fontStyle, - }); + } + + var position = $(this._chart.canvas)[0].getBoundingClientRect(); + + // Display, position, and set styles for font + tooltipEl.css({ + opacity: 1, + width: tooltip.width ? (tooltip.width + 'px') : 'auto', + left: position.left + tooltip.x + 'px', + top: position.top + top + 'px', + fontFamily: tooltip._fontFamily, + fontSize: tooltip.fontSize, + fontStyle: tooltip._fontStyle, + padding: tooltip.yPadding + 'px ' + tooltip.xPadding + 'px', + }); }; - var pieData = [{ - value: 300, - color: "#F7464A", - highlight: "#FF5A5E", - label: "Red" - }, { - value: 50, - color: "#46BFBD", - highlight: "#5AD3D1", - label: "Green" - }, { - value: 100, - color: "#FDB45C", - highlight: "#FFC870", - label: "Yellow" - }, { - value: 40, - color: "#949FB1", - highlight: "#A8B3C5", - label: "Grey" - }, { - value: 120, - color: "#4D5360", - highlight: "#616774", - label: "Dark Grey" - }]; + var config = { + type: 'pie', + data: { + datasets: [{ + data: [300, 50, 100, 40, 10], + backgroundColor: [ + "#F7464A", + "#46BFBD", + "#FDB45C", + "#949FB1", + "#4D5360", + ], + }], + labels: [ + "Red", + "Green", + "Yellow", + "Grey", + "Dark Grey" + ] + }, + options: { + responsive: true, + legend: { + display: false + }, + tooltips: { + enabled: false, + } + } + }; window.onload = function() { var ctx1 = document.getElementById("chart-area1").getContext("2d"); - window.myPie = new Chart(ctx1).Pie(pieData); + window.myPie = new Chart(ctx1, config); var ctx2 = document.getElementById("chart-area2").getContext("2d"); - window.myPie = new Chart(ctx2).Pie(pieData); + window.myPie = new Chart(ctx2, config); }; </script> </body>
false
Other
chartjs
Chart.js
46fc96bf4d97989096aa1024be3d0ee2c9a6a789.json
Remove unused code from core controller.
src/core/core.controller.js
@@ -53,7 +53,6 @@ module.exports = function(Chart) { this.ensureScalesHaveIDs(); this.buildOrUpdateControllers(); this.buildScales(); - this.buildSurroundingItems(); this.updateLayout(); this.resetElements(); this.initToolTip(); @@ -166,18 +165,6 @@ module.exports = function(Chart) { Chart.scaleService.addScalesToLayout(this); }, - buildSurroundingItems: function() { - /*if (this.options.title) { - this.titleBlock = new Chart.Title({ - ctx: this.chart.ctx, - options: this.options.title, - chart: this - }); - - Chart.layoutService.addBox(this, this.titleBlock); - }*/ - }, - updateLayout: function() { Chart.layoutService.update(this, this.chart.width, this.chart.height); },
false
Other
chartjs
Chart.js
d6289c6129f1222980ea571f6c6f675182d78f35.json
Convert title block to a plugin
src/chart.js
@@ -8,9 +8,9 @@ require('./core/core.datasetController')(Chart); require('./core/core.layoutService')(Chart); require('./core/core.scaleService')(Chart); require('./core/core.plugin.js')(Chart); -require('./core/core.legend')(Chart); require('./core/core.scale')(Chart); require('./core/core.title')(Chart); +require('./core/core.legend')(Chart); require('./core/core.tooltip')(Chart); require('./elements/element.arc')(Chart);
true
Other
chartjs
Chart.js
d6289c6129f1222980ea571f6c6f675182d78f35.json
Convert title block to a plugin
src/core/core.controller.js
@@ -167,15 +167,15 @@ module.exports = function(Chart) { }, buildSurroundingItems: function() { - if (this.options.title) { + /*if (this.options.title) { this.titleBlock = new Chart.Title({ ctx: this.chart.ctx, options: this.options.title, chart: this }); Chart.layoutService.addBox(this, this.titleBlock); - } + }*/ }, updateLayout: function() {
true
Other
chartjs
Chart.js
d6289c6129f1222980ea571f6c6f675182d78f35.json
Convert title block to a plugin
src/core/core.legend.js
@@ -363,5 +363,5 @@ module.exports = function(Chart) { Chart.layoutService.addBox(chartInstance, chartInstance.legend); } } - }) + }); };
true
Other
chartjs
Chart.js
d6289c6129f1222980ea571f6c6f675182d78f35.json
Convert title block to a plugin
src/core/core.title.js
@@ -177,4 +177,22 @@ module.exports = function(Chart) { } } }); + + // Register the title plugin + Chart.pluginService.register({ + beforeInit: function(chartInstance) { + var opts = chartInstance.options; + var titleOpts = opts.title; + + if (titleOpts) { + chartInstance.titleBlock = new Chart.Title({ + ctx: chartInstance.chart.ctx, + options: titleOpts, + chart: chartInstance + }); + + Chart.layoutService.addBox(chartInstance, chartInstance.titleBlock); + } + } + }); }; \ No newline at end of file
true
Other
chartjs
Chart.js
e81299ded4b7a6af9f2bf52e31129d9d96f51a3f.json
Improve line chart docs
docs/03-Line-Chart.md
@@ -3,9 +3,7 @@ title: Line Chart anchor: line-chart --- ### Introduction -A line chart is a way of plotting data points on a line. - -Often, it is used to show trend data, and the comparison of two data sets. +A line chart is a way of plotting data points on a line. Often, it is used to show trend data, and the comparison of two data sets. <div class="canvas-holder"> <canvas width="250" height="125"></canvas> @@ -27,6 +25,7 @@ var myLineChart = Chart.Line(ctx, { options: options }); ``` + ### Data Structure The following options can be included in a line chart dataset to configure options for that specific dataset. @@ -35,7 +34,7 @@ All point* properties can be specified as an array. If these are set to an array Property | Type | Usage --- | --- | --- -data | `Array<Number>` | The data to plot in a line +data | See [data point](#line-chart-data-points) section | The data to plot in a line label | `String` | The label for the dataset which appears in the legend and tooltips xAxisID | `String` | The ID of the x axis to plot this dataset on yAxisID | `String` | The ID of the y axis to plot this dataset on @@ -57,7 +56,7 @@ pointHitRadius | `Number or Array<Number>` | The pixel size of the non-displayed pointHoverBackgroundColor | `Color or Array<Color>` | Point background color when hovered pointHoverBorderColor | `Color or Array<Color>` | Point border color when hovered pointHoverBorderWidth | `Number or Array<Number>` | Border width of point when hovered -pointStyle | `String or Array<String>` | The style of point. Options include 'circle', 'triangle', 'rect', 'rectRot', 'cross', 'crossRot', 'star', 'line', and 'dash' +pointStyle | `String, Array<String>, Image, Array<Image>` | The style of point. Options are 'circle', 'triangle', 'rect', 'rectRot', 'cross', 'crossRot', 'star', 'line', and 'dash'. If the option is an image, that image is drawn on the canvas using `drawImage`. An example data object using these attributes is shown below. ```javascript @@ -89,39 +88,61 @@ var data = { }; ``` -The line chart requires an array of labels. This labels are shown on the X axis. There must be one label for each data point. More labels than datapoints are allowed, in which case the line ends at the last data point. +The line chart usually requires an array of labels. This labels are shown on the X axis. There must be one label for each data point. More labels than datapoints are allowed, in which case the line ends at the last data point. The data for line charts is broken up into an array of datasets. Each dataset has a colour for the fill, a colour for the line and colours for the points and strokes of the points. These colours are strings just like CSS. You can use RGBA, RGB, HEX or HSL notation. The label key on each dataset is optional, and can be used when generating a scale for the chart. -### Chart Options +### Data Points + +The data passed to the chart can be passed in two formats. The most common method is to pass the data array as an array of numbers. In this case, the `data.labels` array must be specified and must contain a label for each point. + +The alternate is used for sparse datasets. Data is specified using an object containing `x` and `y` properties. This is used for scatter charts as documented below. + +### Scatter Line Charts + +Scatter line charts can be created by changing the X axis to a linear axis. To use a scatter chart, data must be passed as objects containing X and Y properties. The example below creates a scatter chart with 3 points. + +```javascript +var scatterChart = new Chart(ctx, { + type: 'line', + data: { + datasets: [{ + label: 'Scatter Dataset', + data: [{ + x: -10, + y: 0 + }, { + x: 0, + y: 10 + }, { + x: 10, + y: 5 + }] + }] + }, + options: { + scales: { + xAxes: [{ + type: 'linear', + position: 'bottom' + }] + } + } +}); +``` -These are the customisation options specific to Line charts. These options are merged with the [global chart configuration options](#global-chart-configuration), and form the options of the chart. +### Chart Options -The default options for line chart are defined in `Chart.defaults.line`. +These are the customisation options specific to Line charts. These options are merged with the [global chart configuration options](#chart-configuration-global-configuration), and form the options of the chart. Name | Type | Default | Description --- | --- | --- | --- showLines | Boolean | true | If false, the lines between points are not drawn -stacked | Boolean | false | If true, lines stack on top of each other along the y axis. -*hover*.mode | String | "label" | Label's hover mode. "label" is used since the x axis displays data by the index in the dataset. -elements | Object | - | - -*elements*.point | Object | - | - -*elements.point*.radius | Number | `3` | Defines the size of the Point shape. Can be set to zero to skip rendering a point. -scales | Object | - | - -*scales*.xAxes | Array | `[{type:"category","id":"x-axis-0"}]` | Defines all of the x axes used in the chart. See the [scale documentation](#scales) for details on the available options. -*Options for xAxes* | | | -type | String | "category" | As defined in ["Category"](#scales-category-scale). -id | String | "x-axis-0" | Id of the axis so that data can bind to it. - | | | - *scales*.yAxes | Array | `[{type:"linear","id":"y-axis-0"}]` | Defines all of the y axes used in the chart. See the [scale documentation](#scales) for details on the available options. - *Options for yAxes* | | | - type | String | "linear" | As defined in ["Linear"](#scales-linear-scale). - id | String | "y-axis-0" | Id of the axis so that data can bind to it. You can override these for your `Chart` instance by passing a member `options` into the `Line` method. -For example, we could have a line chart display without an x axis by doing the following. The config merge is smart enough to handle arrays so that you do not need to specify all axis settings to change one thing. +For example, we could have a line chart display without an X axis by doing the following. The config merge is smart enough to handle arrays so that you do not need to specify all axis settings to change one thing. ```javascript new Chart(ctx, { @@ -133,8 +154,24 @@ new Chart(ctx, { }] } }); -// This will create a chart with all of the default options, merged from the global config, -// and the Line chart defaults, but this particular instance will have the x axis not displaying. ``` We can also change these defaults values for each Line type that is created, this object is available at `Chart.defaults.line`. + +### Stacked Charts + +Stacked area charts can be created by setting the Y axis to a stacked configuration. The following example would have stacked lines. + +```javascript +var stackedLine = new Chart(ctx, { + type: 'line', + data: data, + options: { + scales: { + yAxes: [{ + stacked: true + }] + } + } +}); +```
false
Other
chartjs
Chart.js
f4ef56993d94ad5379ebd82331f05f16d89df987.json
Add full description text for scales.
docs/01-Scales.md
@@ -14,39 +14,39 @@ Every scale extends a core scale class with the following options: Name | Type | Default | Description --- |:---:| --- | --- -display | Boolean | true | If true, show the scale. -reverse | Boolean | false | If true, reverses the scales. -gridLines | Array | | +type | String | Chart specific. | Type of scale being employed. Custom scales can be created. Options: ["category"](#scales-category-scale), ["linear"](#scales-linear-scale), ["logarithmic"](#scales-logarithmic-scale), ["time"](#scales-time-scale), ["radialLinear"](#scales-radial-linear-scale) +display | Boolean | true | If true, show the scale including gridlines, ticks, and labels. Overrides *gridLines.show*, *scaleLabel.show*, and *ticks.show*. +**gridLines** | Array | - | Options for the grid lines that run perpendicular to the axis. *gridLines*.show | Boolean | true | If true, show the grid lines. *gridLines*.color | Color | "rgba(0, 0, 0, 0.1)" | Color of the grid lines. *gridLines*.lineWidth | Number | 1 | Width of the grid lines in number of pixels. -*gridLines*.drawOnChartArea | Boolean | true | If true draw lines on the chart area, if false... -*gridLines*.drawTicks | Boolean | true | If true draw ticks in the axis area, if false... +*gridLines*.drawOnChartArea | Boolean | true | If true, draw lines on the chart area inside the axis lines. +*gridLines*.drawTicks | Boolean | true | If true, draw lines beside the ticks in the axis area beside the chart. *gridLines*.zeroLineWidth | Number | 1 | Width of the grid line for the first index (index 0). *gridLines*.zeroLineColor | Color | "rgba(0, 0, 0, 0.25)" | Color of the grid line for the first index (index 0). *gridLines*.offsetGridLines | Boolean | false | If true, offset labels from grid lines. -scaleLabel | Array | | Label for the axis. -*scaleLabel*.show | Boolean | false | Whether the label is displayed. -*scaleLabel*.labelString | String | "" | The text for the label. -*scaleLabel*.fontColor | Color | "#666" | -*scaleLabel*.fontFamily| String | "Helvetica Neue" | -*scaleLabel*.fontSize | Number | 12 | -*scaleLabel*.fontStyle | String | "normal" | -ticks | Array | | Settings for the ticks along the axis. +**scaleLabel** | Array | | Label for the entire axis. +*scaleLabel*.show | Boolean | false | If true, show the scale label. +*scaleLabel*.labelString | String | "" | The text for the label. (i.e. "# of People", "Response Choices") +*scaleLabel*.fontColor | Color | "#666" | Font color for the scale label. +*scaleLabel*.fontFamily| String | "Helvetica Neue" | Font family for the scale label, follows CSS font-family options. +*scaleLabel*.fontSize | Number | 12 | Font size for the scale label. +*scaleLabel*.fontStyle | String | "normal" | Font style for the scale label, follows CSS font-style options (i.e. normal, italic, oblique, initial, inherit). +**ticks** | Array | | Settings for the labels that run along the axis. *ticks*.beginAtZero | Boolean | false | If true the scale will be begin at 0, if false the ticks will begin at your smallest data value. -*ticks*.fontSize | Number | 12 | -*ticks*.fontStyle | String | "normal" | -*ticks*.fontColor | Color | "#666" | -*ticks*.fontFamily | String | "Helvetica Neue" | -*ticks*.maxRotation | Number | 90 | -*ticks*.minRotation | Number | 20 | -*ticks*.mirror | Boolean | false | -*ticks*.padding | Number | 10 | -*ticks*.reverse | Boolean | false | -*ticks*.show | Boolean | true | +*ticks*.fontColor | Color | "#666" | Font color for the tick labels. +*ticks*.fontFamily | String | "Helvetica Neue" | Font family for the tick labels, follows CSS font-family options. +*ticks*.fontSize | Number | 12 | Font size for the tick labels. +*ticks*.fontStyle | String | "normal" | Font style for the tick labels, follows CSS font-style options (i.e. normal, italic, oblique, initial, inherit). +*ticks*.maxRotation | Number | 90 | Maximum rotation for tick labels when rotating to condense labels. Note: Rotation doesn't occur until necessary. *Note: Only applicable to horizontal scales.* +*ticks*.minRotation | Number | 20 | *currently not-implemented* Minimum rotation for tick labels when condensing is necessary. *Note: Only applicable to horizontal scales.* +*ticks*.padding | Number | 10 | Padding between the tick label and the axis. *Note: Only applicable to horizontal scales.* +*ticks*.mirror | Boolean | false | Flips tick labels around axis, displaying the labels inside the chart instead of outside. *Note: Only applicable to vertical scales.* +*ticks*.reverse | Boolean | false | Reverses order of tick labels. +*ticks*.show | Boolean | true | If true, show the ticks. *ticks*.suggestedMin | Number | - | User defined minimum number for the scale, overrides minimum value *except for if* it is higher than the minimum value. *ticks*.suggestedMax | Number | - | User defined maximum number for the scale, overrides maximum value *except for if* it is lower than the maximum value. -*ticks*.callback | Function | `function(value) { return '' + value; } ` | +*ticks*.callback | Function | `function(value) { return '' + value; } ` | Returns the string representation of the tick value as it should be displayed on the chart. The `userCallback` method may be used for advanced tick customization. The following callback would display every label in scientific notation ```javascript
false
Other
chartjs
Chart.js
ea15aaaec23485c5c257617c3ece3e178729e870.json
Fix draw issue
src/core/core.legend.js
@@ -285,6 +285,7 @@ if (dataset.hidden) { // Strikethrough the text if hidden + ctx.beginPath(); ctx.moveTo(this.options.labels.boxWidth + (this.options.labels.fontSize / 2) + cursor.x, cursor.y + (this.options.labels.fontSize / 2)); ctx.lineTo(this.options.labels.boxWidth + (this.options.labels.fontSize / 2) + cursor.x + textWidth, cursor.y + (this.options.labels.fontSize / 2)); ctx.stroke();
false
Other
chartjs
Chart.js
f32d62722a8b64bc2d198796d8bd64db6c5a3666.json
Update initializer documentation for Bar.
docs/03-Bar-Chart.md
@@ -14,8 +14,9 @@ It is sometimes used to show trend data, and the comparison of multiple data set ### Example usage ```javascript -var myBarChart = new Chart(ctx).Bar({ - data: data, +var myBarChart = new Chart(ctx,{ + type: 'bar', + data: data, options: options }); ``` @@ -83,7 +84,7 @@ These are the customisation options specific to Bar charts. These options are me }, scales: { - // The bar chart officially supports only 1 x-axis but uses an array to keep the API consistent. Use a scatter chart if you need multiple x axes. + // The bar chart officially supports only 1 x-axis but uses an array to keep the API consistent. Use a scatter chart if you need multiple x axes. xAxes: [{ // String - type of axis to use. Should not be changed from 'dataset'. scaleType: "dataset", // scatter should not use a dataset axis @@ -226,7 +227,7 @@ For example, we could have a bar chart without a stroke on each bar by doing the ```javascript new Chart(ctx).Bar({ - data: data, + data: data, options: { barShowStroke: false }
false
Other
chartjs
Chart.js
7edcc0659bf3295532974d1d3569f3454290e8e7.json
Fix polar area legends
src/charts/Chart.PolarArea.js
@@ -7,7 +7,23 @@ var defaultConfig = { aspectRatio: 1, - legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i = 0; i < data.datasets[0].data.length; i++){%><li><span style=\"background-color:<%=data.datasets[0].backgroundColor[i]%>\"><%if(data.labels && i < data.labels.length){%><%=data.labels[i]%><%}%></span></li><%}%></ul>", + legendCallback: function(chart) { + var text = []; + text.push('<ul class="' + chart.id + '-legend">'); + + if (chart.data.datasets.length) { + for (var i = 0; i < chart.data.datasets[0].data.length; ++i) { + text.push('<li><span style="background-color:' + chart.data.datasets[0].backgroundColor[i] + '">'); + if (chart.data.labels[i]) { + text.push(chart.data.labels[i]); + } + text.push('</span></li>'); + } + } + + text.push('</ul>'); + return text.join(""); + } }; Chart.PolarArea = function(context, config) {
false
Other
chartjs
Chart.js
8398d26d10ee030339cafb77519a98857ce9dd66.json
Remove Tooltip opacity from core-controller
src/core/core.controller.js
@@ -458,20 +458,7 @@ // The usual updates this.tooltip.initialize(); - - // Active - if (this.tooltipActive.length) { - this.tooltip._model.opacity = 1; - - helpers.extend(this.tooltip, { - _active: this.tooltipActive, - }); - - } else { - // Inactive - this.tooltip._model.opacity = 0; - } - this.tooltip.update(); + this.tooltip._active = this.tooltipActive; } // Hover animations
false
Other
chartjs
Chart.js
0fa03fad24040d83b713727f2158919f223387b4.json
Handle opacity in the tooltip update method
src/core/core.tooltip.js
@@ -197,63 +197,70 @@ var ctx = this._chart.ctx; - var element = this._active[0], - labelColors = [], - tooltipPosition; - - var tooltipItems = []; - - if (this._options.tooltips.mode == 'single') { - var yScale = element._yScale || element._scale; // handle radar || polarArea charts - tooltipItems.push({ - xLabel: element._xScale ? element._xScale.getLabelForIndex(element._index, element._datasetIndex) : '', - yLabel: yScale ? yScale.getLabelForIndex(element._index, element._datasetIndex) : '', - index: element._index, - datasetIndex: element._datasetIndex, - }); - tooltipPosition = this._active[0].tooltipPosition(); - } else { - helpers.each(this._data.datasets, function(dataset, datasetIndex) { - if (!helpers.isDatasetVisible(dataset)) { - return; - } - var currentElement = dataset.metaData[element._index]; - var yScale = element._yScale || element._scale; // handle radar || polarArea charts + if(this._active.length){ + this._model.opacity = 1; + + var element = this._active[0], + labelColors = [], + tooltipPosition; + + var tooltipItems = []; + if (this._options.tooltips.mode == 'single') { + var yScale = element._yScale || element._scale; // handle radar || polarArea charts tooltipItems.push({ - xLabel: currentElement._xScale ? currentElement._xScale.getLabelForIndex(currentElement._index, currentElement._datasetIndex) : '', - yLabel: yScale ? yScale.getLabelForIndex(currentElement._index, currentElement._datasetIndex) : '', + xLabel: element._xScale ? element._xScale.getLabelForIndex(element._index, element._datasetIndex) : '', + yLabel: yScale ? yScale.getLabelForIndex(element._index, element._datasetIndex) : '', index: element._index, - datasetIndex: datasetIndex, + datasetIndex: element._datasetIndex, }); - }); - - helpers.each(this._active, function(active, i) { - labelColors.push({ - borderColor: active._view.borderColor, - backgroundColor: active._view.backgroundColor + tooltipPosition = this._active[0].tooltipPosition(); + } else { + helpers.each(this._data.datasets, function(dataset, datasetIndex) { + if (!helpers.isDatasetVisible(dataset)) { + return; + } + var currentElement = dataset.metaData[element._index]; + var yScale = element._yScale || element._scale; // handle radar || polarArea charts + + tooltipItems.push({ + xLabel: currentElement._xScale ? currentElement._xScale.getLabelForIndex(currentElement._index, currentElement._datasetIndex) : '', + yLabel: yScale ? yScale.getLabelForIndex(currentElement._index, currentElement._datasetIndex) : '', + index: element._index, + datasetIndex: datasetIndex, + }); }); - }, this); - tooltipPosition = this._active[0].tooltipPosition(); - tooltipPosition.y = this._active[0]._yScale.getPixelForDecimal(0.5); - } + helpers.each(this._active, function(active, i) { + labelColors.push({ + borderColor: active._view.borderColor, + backgroundColor: active._view.backgroundColor + }); + }, this); - // Build the Text Lines - helpers.extend(this._model, { - title: this.getTitle(tooltipItems, this._data), - beforeBody: this.getBeforeBody(tooltipItems, this._data), - body: this.getBody(tooltipItems, this._data), - afterBody: this.getAfterBody(tooltipItems, this._data), - footer: this.getFooter(tooltipItems, this._data), - }); + tooltipPosition = this._active[0].tooltipPosition(); + tooltipPosition.y = this._active[0]._yScale.getPixelForDecimal(0.5); + } - helpers.extend(this._model, { - x: Math.round(tooltipPosition.x), - y: Math.round(tooltipPosition.y), - caretPadding: tooltipPosition.padding, - labelColors: labelColors, - }); + // Build the Text Lines + helpers.extend(this._model, { + title: this.getTitle(tooltipItems, this._data), + beforeBody: this.getBeforeBody(tooltipItems, this._data), + body: this.getBody(tooltipItems, this._data), + afterBody: this.getAfterBody(tooltipItems, this._data), + footer: this.getFooter(tooltipItems, this._data), + }); + + helpers.extend(this._model, { + x: Math.round(tooltipPosition.x), + y: Math.round(tooltipPosition.y), + caretPadding: tooltipPosition.padding, + labelColors: labelColors, + }); + } + else{ + this._model.opacity = 0; + } if (this._options.tooltips.custom) { this._options.tooltips.custom.call(this, this._model);
false
Other
chartjs
Chart.js
ecf5801787abefaa6a47b17cb8b4180c35948437.json
call the custom callback in tooltip options
src/core/core.tooltip.js
@@ -136,7 +136,7 @@ }); }, - // Get the title + // Get the title // Args are: (tooltipItem, data) getTitle: function() { var beforeTitle = this._options.tooltips.callbacks.beforeTitle.apply(this, arguments), @@ -197,7 +197,7 @@ var ctx = this._chart.ctx; - var element = this._active[0], + var element = this._active[0], labelColors = [], tooltipPosition; @@ -255,6 +255,10 @@ labelColors: labelColors, }); + if (this._options.tooltips.custom) { + this._options.tooltips.custom.call(this, this._model); + } + return this; }, draw: function() {
false
Other
chartjs
Chart.js
682545e1e37e16d32e55f9b34dfda867ac1fd8ec.json
Change license link The link to the license now points to the direct license that applies for chart.js, rather than a generic MIT license
README.md
@@ -58,4 +58,4 @@ For support using Chart.js, please post questions with the [`chartjs` tag on Sta ## License -Chart.js is available under the [MIT license](http://opensource.org/licenses/MIT). +Chart.js is available under the [MIT license](https://github.com/nnnick/Chart.js/blob/master/LICENSE.md).
false
Other
chartjs
Chart.js
b87106c1817d380576fbd6fc1ae1e7928d38b6ba.json
Add npm info to getting started doc.
docs/00-Getting-Started.md
@@ -31,6 +31,12 @@ You can also grab Chart.js using bower: bower install Chart.js --save ``` +or NPM: + +```bash +npm install chart.js --save +``` + Also, Chart.js is available from CDN: https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js
false
Other
chartjs
Chart.js
4d009d116dfd405e183fc44658909e013dfa88fc.json
Use the new travis CI docker framework (hopefully)
.travis.yml
@@ -15,3 +15,5 @@ script: notifications: slack: chartjs:pcfCZR6ugg5TEcaLtmIfQYuA + +sudo: false \ No newline at end of file
false
Other
chartjs
Chart.js
57979a22708364d16eb58373910de374d736ecb0.json
Fix similar typos in core.controller & element
src/core/core.controller.js
@@ -4,7 +4,7 @@ //Declare root variable - window in the browser, global on the server var root = this, - previous = root.Chart, + Chart = root.Chart, helpers = Chart.helpers;
true
Other
chartjs
Chart.js
57979a22708364d16eb58373910de374d736ecb0.json
Fix similar typos in core.controller & element
src/core/core.element.js
@@ -4,7 +4,7 @@ //Declare root variable - window in the browser, global on the server var root = this, - previous = root.Chart, + Chart = root.Chart, helpers = Chart.helpers; Chart.elements = {};
true
Other
chartjs
Chart.js
ef1c4fb0cbd7c35f0affaa27bf589b6f3302fd8c.json
Fix typo in core.helpers.js
src/core/core.helpers.js
@@ -4,7 +4,7 @@ //Declare root variable - window in the browser, global on the server var root = this, - previous = root.Chart; + Chart = root.Chart; //Global Chart helpers object for utility methods and classes var helpers = Chart.helpers = {};
false
Other
chartjs
Chart.js
fe5ef1584b7e10b4d584e553ecb949d7c8ccc5ec.json
Add Line chart with time scale sample
samples/line-time-scale.html
@@ -0,0 +1,162 @@ +<!doctype html> +<html> + +<head> + <title>Line Chart</title> + <script src="../Chart.js"></script> + <script src="../node_modules/jquery/dist/jquery.min.js"></script> + <style> + canvas { + -webkit-box-shadow: 0 0 20px 0 rgba(0, 0, 0, .5); + } + </style> +</head> + +<body> + <div style="width:100%;"> + <canvas id="canvas" style="width:100%;height:100%"></canvas> + </div> + <br> + <br> + <button id="randomizeData">Randomize Data</button> + <button id="addDataset">Add Dataset</button> + <button id="removeDataset">Remove Dataset</button> + <button id="addData">Add Data</button> + <button id="removeData">Remove Data</button> + <div> + <h3>Legend</h3> + <div id="legendContainer"> + </div> + </div> + <script> + var randomScalingFactor = function() { + return Math.round(Math.random() * 100 * (Math.random() > 0.5 ? -1 : 1)); + }; + var randomColorFactor = function() { + return Math.round(Math.random() * 255); + }; + var randomColor = function(opacity) { + return 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',' + (opacity || '.3') + ')'; + }; + + var config = { + type: 'line', + data: { + // labels: ["01/01/2015 20:00", "01/02/2015 21:00", "01/03/2015 22:00", "01/06/2015 23:00", "01/15/2015 03:00", "01/17/2015 10:00", "01/30/2015 11:00"], // Hours + labels: ["01/01/2015", "01/02/2015", "01/03/2015", "01/06/2015", "01/15/2015", "01/17/2015", "01/30/2015"], // Days + // labels: ["12/25/2014", "01/08/2015", "01/15/2015", "01/22/2015", "01/29/2015", "02/05/2015", "02/12/2015"], // Weeks + datasets: [{ + label: "My First dataset", + data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()], + fill: false, + borderDash: [5, 5], + }, { + label: "My Second dataset", + data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()], + }] + }, + options: { + responsive: true, + scales: { + xAxes: [{ + type: "time", + display: true, + time: { + format: 'MM/DD/YYYY HH:mm', + } + }, ], + yAxes: [{ + display: true + }] + } + } + }; + + $.each(config.data.datasets, function(i, dataset) { + dataset.borderColor = randomColor(0.4); + dataset.backgroundColor = randomColor(0.5); + dataset.pointBorderColor = randomColor(0.7); + dataset.pointBackgroundColor = randomColor(0.5); + dataset.pointBorderWidth = 1; + }); + + console.log(config.data); + + window.onload = function() { + var ctx = document.getElementById("canvas").getContext("2d"); + window.myLine = new Chart(ctx, config); + + updateLegend(); + }; + + function updateLegend() { + $legendContainer = $('#legendContainer'); + $legendContainer.empty(); + $legendContainer.append(window.myLine.generateLegend()); + } + + $('#randomizeData').click(function() { + $.each(config.data.datasets, function(i, dataset) { + dataset.data = dataset.data.map(function() { + return randomScalingFactor(); + }); + }); + + window.myLine.update(); + updateLegend(); + }); + + $('#addDataset').click(function() { + var newDataset = { + label: 'Dataset ' + config.data.datasets.length, + borderColor: randomColor(0.4), + backgroundColor: randomColor(0.5), + pointBorderColor: randomColor(0.7), + pointBackgroundColor: randomColor(0.5), + pointBorderWidth: 1, + data: [], + }; + + for (var index = 0; index < config.data.labels.length; ++index) { + newDataset.data.push(randomScalingFactor()); + } + + window.myLine.addDataset(newDataset); + updateLegend(); + }); + + $('#addData').click(function() { + if (config.data.datasets.length > 0) { + config.data.labels.push( + moment( + config.data.labels[config.data.labels.length - 1], config.options.scales.xAxes[0].time.format + ).add(1, 'day') + .format('MM/DD/YYYY') + ); + + for (var index = 0; index < config.data.datasets.length; ++index) { + window.myLine.addData(randomScalingFactor(), index); + } + + updateLegend(); + } + }); + + $('#removeDataset').click(function() { + window.myLine.removeDataset(0); + updateLegend(); + }); + + $('#removeData').click(function() { + config.data.labels.splice(-1, 1); // remove the label first + + config.data.datasets.forEach(function(dataset, datasetIndex) { + window.myLine.removeData(datasetIndex, -1); + }); + + updateLegend(); + }); + </script> +</body> + +</html>
false
Other
chartjs
Chart.js
8762ae2f2806d7784b1b716e273827544abc53eb.json
Add moment.js as dependency
gulpfile.js
@@ -33,7 +33,8 @@ var srcFiles = [ './src/scales/**', './src/elements/**', './src/charts/**', - './node_modules/color/dist/color.min.js' + './node_modules/color/dist/color.min.js', + './node_modules/moment/min/moment.min.js' ];
true
Other
chartjs
Chart.js
8762ae2f2806d7784b1b716e273827544abc53eb.json
Add moment.js as dependency
package.json
@@ -31,6 +31,7 @@ "karma-firefox-launcher": "^0.1.6", "karma-jasmine": "^0.3.6", "karma-jasmine-html-reporter": "^0.1.8", + "moment": "^2.10.6", "onecolor": "^2.5.0", "semver": "^3.0.1" },
true
Other
chartjs
Chart.js
26684b6371cca9db250edc9e7c0a056fb8081d4d.json
Rectangle element tests
src/elements/element.rectangle.js
@@ -55,15 +55,26 @@ }, inRange: function(mouseX, mouseY) { var vm = this._view; - if (vm.y < vm.base) { - return (mouseX >= vm.x - vm.width / 2 && mouseX <= vm.x + vm.width / 2) && (mouseY >= vm.y && mouseY <= vm.base); - } else { - return (mouseX >= vm.x - vm.width / 2 && mouseX <= vm.x + vm.width / 2) && (mouseY >= vm.base && mouseY <= vm.y); - } + var inRange = false; + + if (vm) { + if (vm.y < vm.base) { + inRange = (mouseX >= vm.x - vm.width / 2 && mouseX <= vm.x + vm.width / 2) && (mouseY >= vm.y && mouseY <= vm.base); + } else { + inRange = (mouseX >= vm.x - vm.width / 2 && mouseX <= vm.x + vm.width / 2) && (mouseY >= vm.base && mouseY <= vm.y); + } + } + + return inRange; }, inLabelRange: function(mouseX) { var vm = this._view; - return (mouseX >= vm.x - vm.width / 2 && mouseX <= vm.x + vm.width / 2); + + if (vm) { + return (mouseX >= vm.x - vm.width / 2 && mouseX <= vm.x + vm.width / 2); + } else { + return false; + } }, tooltipPosition: function() { var vm = this._view;
true
Other
chartjs
Chart.js
26684b6371cca9db250edc9e7c0a056fb8081d4d.json
Rectangle element tests
test/element.rectangle.tests.js
@@ -0,0 +1,246 @@ +// Test the rectangle element + +describe('Rectangle element tests', function() { + it ('Should be constructed', function() { + var rectangle = new Chart.elements.Rectangle({ + _datasetIndex: 2, + _index: 1 + }); + + expect(rectangle).not.toBe(undefined); + expect(rectangle._datasetIndex).toBe(2); + expect(rectangle._index).toBe(1); + }); + + it ('Should correctly identify as in range', function() { + var rectangle = new Chart.elements.Rectangle({ + _datasetIndex: 2, + _index: 1 + }); + + // Safely handles if these are called before the viewmodel is instantiated + expect(rectangle.inRange(5)).toBe(false); + expect(rectangle.inLabelRange(5)).toBe(false); + + // Attach a view object as if we were the controller + rectangle._view = { + base: 0, + width: 4, + x: 10, + y: 15 + }; + + expect(rectangle.inRange(10, 15)).toBe(true); + expect(rectangle.inRange(10, 10)).toBe(true); + expect(rectangle.inRange(10, 16)).toBe(false); + expect(rectangle.inRange(5, 5)).toBe(false); + + expect(rectangle.inLabelRange(5)).toBe(false); + expect(rectangle.inLabelRange(7)).toBe(false); + expect(rectangle.inLabelRange(10)).toBe(true); + expect(rectangle.inLabelRange(12)).toBe(true); + expect(rectangle.inLabelRange(15)).toBe(false); + expect(rectangle.inLabelRange(20)).toBe(false); + + // Test when the y is below the base (negative bar) + var negativeRectangle = new Chart.elements.Rectangle({ + _datasetIndex: 2, + _index: 1 + }); + + // Attach a view object as if we were the controller + negativeRectangle._view = { + base: 0, + width: 4, + x: 10, + y: -15 + }; + + expect(negativeRectangle.inRange(10, -16)).toBe(false); + expect(negativeRectangle.inRange(10, 1)).toBe(false); + expect(negativeRectangle.inRange(10, -5)).toBe(true); + }); + + it ('should get the correct height', function() { + var rectangle = new Chart.elements.Rectangle({ + _datasetIndex: 2, + _index: 1 + }); + + // Attach a view object as if we were the controller + rectangle._view = { + base: 0, + width: 4, + x: 10, + y: 15 + }; + + expect(rectangle.height()).toBe(-15); + + // Test when the y is below the base (negative bar) + var negativeRectangle = new Chart.elements.Rectangle({ + _datasetIndex: 2, + _index: 1 + }); + + // Attach a view object as if we were the controller + negativeRectangle._view = { + base: -10, + width: 4, + x: 10, + y: -15 + }; + expect(negativeRectangle.height()).toBe(5); + }); + + it ('should get the correct tooltip position', function() { + var rectangle = new Chart.elements.Rectangle({ + _datasetIndex: 2, + _index: 1 + }); + + // Attach a view object as if we were the controller + rectangle._view = { + base: 0, + width: 4, + x: 10, + y: 15 + }; + + expect(rectangle.tooltipPosition()).toEqual({ + x: 10, + y: 0, + }); + + // Test when the y is below the base (negative bar) + var negativeRectangle = new Chart.elements.Rectangle({ + _datasetIndex: 2, + _index: 1 + }); + + // Attach a view object as if we were the controller + negativeRectangle._view = { + base: -10, + width: 4, + x: 10, + y: -15 + }; + + expect(negativeRectangle.tooltipPosition()).toEqual({ + x: 10, + y: -15, + }); + }); + + it ('should draw correctly', function() { + var mockContext = window.createMockContext(); + var rectangle = new Chart.elements.Rectangle({ + _datasetIndex: 2, + _index: 1, + _chart: { + ctx: mockContext, + } + }); + + // Attach a view object as if we were the controller + rectangle._view = { + backgroundColor: 'rgb(255, 0, 0)', + base: 0, + borderColor: 'rgb(0, 0, 255)', + borderWidth: 1, + ctx: mockContext, + width: 4, + x: 10, + y: 15, + }; + + rectangle.draw(); + + expect(mockContext.getCalls()).toEqual([{ + name: 'beginPath', + args: [], + }, { + name: 'setFillStyle', + args: ['rgb(255, 0, 0)'] + }, { + name: 'setStrokeStyle', + args: ['rgb(0, 0, 255)'], + }, { + name: 'setLineWidth', + args: [1] + }, { + name: 'moveTo', + args: [8.5, 0] + }, { + name: 'lineTo', + args: [8.5, 15.5] + }, { + name: 'lineTo', + args: [11.5, 15.5] + }, { + name: 'lineTo', + args: [11.5, 0] + }, { + name: 'fill', + args: [], + }, { + name: 'stroke', + args: [] + }]); + }); + + it ('should draw correctly with no stroke', function() { + var mockContext = window.createMockContext(); + var rectangle = new Chart.elements.Rectangle({ + _datasetIndex: 2, + _index: 1, + _chart: { + ctx: mockContext, + } + }); + + // Attach a view object as if we were the controller + rectangle._view = { + backgroundColor: 'rgb(255, 0, 0)', + base: 0, + borderColor: 'rgb(0, 0, 255)', + ctx: mockContext, + width: 4, + x: 10, + y: 15, + }; + + rectangle.draw(); + + expect(mockContext.getCalls()).toEqual([{ + name: 'beginPath', + args: [], + }, { + name: 'setFillStyle', + args: ['rgb(255, 0, 0)'] + }, { + name: 'setStrokeStyle', + args: ['rgb(0, 0, 255)'], + }, { + name: 'setLineWidth', + args: [undefined] + }, { + name: 'moveTo', + args: [8, 0] + }, { + name: 'lineTo', + args: [8, 15] + }, { + name: 'lineTo', + args: [12, 15] + }, { + name: 'lineTo', + args: [12, 0] + }, { + name: 'fill', + args: [], + }]); + }); + + +}); \ No newline at end of file
true
Other
chartjs
Chart.js
b4b3bf60b81e898fac41afc716b5885e928caebc.json
Remove wrong addition of padding
src/scales/scale.linear.js
@@ -173,7 +173,6 @@ // Bottom - top since pixels increase downard on a screen var innerHeight = this.height - (this.paddingTop + this.paddingBottom); pixel = (this.bottom - this.paddingBottom) - (innerHeight / range * (value - this.start)); - pixel += this.paddingTop; } return pixel;
false
Other
chartjs
Chart.js
572b1c737ee20ad9e144976e60b2bb33444d74d0.json
Move register/unregister to core.controller (#7626)
src/core/core.controller.js
@@ -1181,4 +1181,16 @@ Chart.instances = {}; Chart.registry = registry; +// @ts-ignore +const invalidatePlugins = () => each(Chart.instances, (chart) => chart._plugins.invalidate()); + +Chart.register = (...items) => { + registry.add(...items); + invalidatePlugins(); +}; +Chart.unregister = (...items) => { + registry.remove(...items); + invalidatePlugins(); +}; + export default Chart;
true
Other
chartjs
Chart.js
572b1c737ee20ad9e144976e60b2bb33444d74d0.json
Move register/unregister to core.controller (#7626)
src/index.js
@@ -23,21 +23,9 @@ import registry from './core/core.registry'; import Scale from './core/core.scale'; import * as scales from './scales'; import Ticks from './core/core.ticks'; -import {each} from './helpers/helpers.core'; - -// @ts-ignore -const invalidatePlugins = () => each(Chart.instances, (chart) => chart._plugins.invalidate()); - -Chart.register = (...items) => { - registry.add(...items); - invalidatePlugins(); -}; -Chart.unregister = (...items) => { - registry.remove(...items); - invalidatePlugins(); -}; // Register built-ins +// @ts-ignore Chart.register(controllers, scales, elements, plugins); Chart.helpers = helpers;
true
Other
chartjs
Chart.js
4f6d9d844072e6e1cbac49f483a231e1ab4969fb.json
Fix links to fonts.md (#7623)
docs/docs/axes/labelling.md
@@ -13,7 +13,7 @@ The scale label configuration is nested under the scale configuration in the `sc | `display` | `boolean` | `false` | If true, display the axis title. | `align` | `string` | `'center'` | Alignment of the axis title. Possible options are `'start'`, `'center'` and `'end'` | `labelString` | `string` | `''` | The text for the title. (i.e. "# of People" or "Response Choices"). -| `font` | `Font` | `defaults.font` | See [Fonts](fonts.md) +| `font` | `Font` | `defaults.font` | See [Fonts](../general/fonts.md) | `padding` | `number`\|`object` | `4` | Padding to apply around scale labels. Only `top` and `bottom` are implemented. ## Creating Custom Tick Formats
true
Other
chartjs
Chart.js
4f6d9d844072e6e1cbac49f483a231e1ab4969fb.json
Fix links to fonts.md (#7623)
docs/docs/axes/radial/linear.md
@@ -133,7 +133,7 @@ The following options are used to configure the point labels that are shown on t | ---- | ---- | ------- | ------- | ----------- | `display` | `boolean` | | `true` | if true, point labels are shown. | `callback` | `function` | | | Callback function to transform data labels to point labels. The default implementation simply returns the current string. -| `font` | `Font` | Yes | `defaults.font` | See [Fonts](fonts.md) +| `font` | `Font` | Yes | `defaults.font` | See [Fonts](../general/fonts.md) The scriptable context is the same as for the [Angle Line Options](#angle-line-options).
true
Other
chartjs
Chart.js
4f6d9d844072e6e1cbac49f483a231e1ab4969fb.json
Fix links to fonts.md (#7623)
docs/docs/axes/styling.md
@@ -44,7 +44,7 @@ The tick configuration is nested under the scale configuration in the `ticks` ke | ---- | ---- | :-------------------------------: | ------- | ----------- | `callback` | `function` | | | Returns the string representation of the tick value as it should be displayed on the chart. See [callback](../axes/labelling.md#creating-custom-tick-formats). | `display` | `boolean` | | `true` | If true, show tick labels. -| `font` | `Font` | Yes | `defaults.font` | See [Fonts](fonts.md) +| `font` | `Font` | Yes | `defaults.font` | See [Fonts](../general/fonts.md) | `major` | `object` | | `{}` | [Major ticks configuration](#major-tick-configuration). | `padding` | `number` | | `0` | Sets the offset of the tick labels from the axis | `reverse` | `boolean` | | `false` | Reverses order of tick labels.
true
Other
chartjs
Chart.js
4f6d9d844072e6e1cbac49f483a231e1ab4969fb.json
Fix links to fonts.md (#7623)
docs/docs/configuration/title.md
@@ -13,7 +13,7 @@ The title configuration is passed into the `options.title` namespace. The global | `align` | `string` | `'center'` | Alignment of the title. [more...](#align) | `display` | `boolean` | `false` | Is the title shown? | `position` | `string` | `'top'` | Position of title. [more...](#position) -| `font` | `Font` | `defaults.font` | See [Fonts](fonts.md) +| `font` | `Font` | `defaults.font` | See [Fonts](../general/fonts.md) | `padding` | <code>number&#124;{top: number, bottom: number}</code> | `10` | Adds padding above and below the title text if a single number is specified. It is also possible to change top and bottom padding separately. | `lineHeight` | <code>number&#124;string</code> | `1.2` | Height of an individual line of text. See [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height). | `text` | <code>string&#124;string[]</code> | `''` | Title text to display. If specified as an array, text is rendered on multiple lines.
true
Other
chartjs
Chart.js
4f6d9d844072e6e1cbac49f483a231e1ab4969fb.json
Fix links to fonts.md (#7623)
docs/docs/configuration/tooltip.md
@@ -17,14 +17,14 @@ The tooltip configuration is passed into the `options.tooltips` namespace. The g | `itemSort` | `function` | | Sort tooltip items. [more...](#sort-callback) | `filter` | `function` | | Filter tooltip items. [more...](#filter-callback) | `backgroundColor` | `Color` | `'rgba(0, 0, 0, 0.8)'` | Background color of the tooltip. -| `titleFont` | `Font` | `{style: 'bold', color: '#fff'}` | See [Fonts](fonts.md). +| `titleFont` | `Font` | `{style: 'bold', color: '#fff'}` | See [Fonts](../general/fonts.md). | `titleAlign` | `string` | `'left'` | Horizontal alignment of the title text lines. [more...](#alignment) | `titleSpacing` | `number` | `2` | Spacing to add to top and bottom of each title line. | `titleMarginBottom` | `number` | `6` | Margin to add on bottom of title section. -| `bodyFont` | `Font` | `{color: '#fff'}` | See [Fonts](fonts.md). +| `bodyFont` | `Font` | `{color: '#fff'}` | See [Fonts](../general/fonts.md). | `bodyAlign` | `string` | `'left'` | Horizontal alignment of the body text lines. [more...](#alignment) | `bodySpacing` | `number` | `2` | Spacing to add to top and bottom of each tooltip item. -| `footerFont` | `Font` | `{style: 'bold', color: '#fff'}` | See [Fonts](fonts.md). +| `footerFont` | `Font` | `{style: 'bold', color: '#fff'}` | See [Fonts](../general/fonts.md). | `footerAlign` | `string` | `'left'` | Horizontal alignment of the footer text lines. [more...](#alignment) | `footerSpacing` | `number` | `2` | Spacing to add to top and bottom of each footer line. | `footerMarginTop` | `number` | `6` | Margin to add before drawing the footer.
true
Other
chartjs
Chart.js
fb68e91312ad632fcefad0d5883d1d04c13e32ec.json
Fix errors in custom tooltip samples (#7595)
samples/tooltips/custom-line.html
@@ -40,24 +40,26 @@ <script> Chart.defaults.pointHitDetectionRadius = 1; - var getOrCreateTooltip = function() { + var getOrCreateTooltip = function(chart) { var tooltipEl = document.getElementById('chartjs-tooltip'); if (!tooltipEl) { tooltipEl = document.createElement('div'); tooltipEl.id = 'chartjs-tooltip'; tooltipEl.innerHTML = '<table></table>'; - this._chart.canvas.parentNode.appendChild(tooltipEl); + chart.canvas.parentNode.appendChild(tooltipEl); } return tooltipEl; }; - var customTooltips = function(tooltip) { + var customTooltips = function(context) { // Tooltip Element - var tooltipEl = getOrCreateTooltip(); + var chart = context.chart; + var tooltipEl = getOrCreateTooltip(chart); // Hide if no tooltip + var tooltip = context.tooltip; if (tooltip.opacity === 0) { tooltipEl.style.opacity = 0; return; @@ -101,14 +103,14 @@ tableRoot.innerHTML = innerHtml; } - var positionY = this._chart.canvas.offsetTop; - var positionX = this._chart.canvas.offsetLeft; + var positionY = chart.canvas.offsetTop; + var positionX = chart.canvas.offsetLeft; // Display, position, and set styles for font tooltipEl.style.opacity = 1; tooltipEl.style.left = positionX + tooltip.caretX + 'px'; tooltipEl.style.top = positionY + tooltip.caretY + 'px'; - tooltipEl.style.font = tooltip.bodyFont.string; + tooltipEl.style.font = tooltip.options.bodyFont.string; tooltipEl.style.padding = tooltip.yPadding + 'px ' + tooltip.xPadding + 'px'; };
true
Other
chartjs
Chart.js
fb68e91312ad632fcefad0d5883d1d04c13e32ec.json
Fix errors in custom tooltip samples (#7595)
samples/tooltips/custom-pie.html
@@ -43,8 +43,9 @@ </div> <script> - Chart.defaults.plugins.tooltip.custom = function(tooltip) { + Chart.defaults.plugins.tooltip.custom = function(context) { // Tooltip Element + var tooltip = context.tooltip; var tooltipEl = document.getElementById('chartjs-tooltip'); // Hide if no tooltip @@ -91,14 +92,15 @@ tableRoot.innerHTML = innerHtml; } - var positionY = this._chart.canvas.offsetTop; - var positionX = this._chart.canvas.offsetLeft; + var chart = context.chart; + var positionY = chart.canvas.offsetTop; + var positionX = chart.canvas.offsetLeft; // Display, position, and set styles for font tooltipEl.style.opacity = 1; tooltipEl.style.left = positionX + tooltip.caretX + 'px'; tooltipEl.style.top = positionY + tooltip.caretY + 'px'; - tooltipEl.style.font = tooltip.bodyFont.string; + tooltipEl.style.font = tooltip.options.bodyFont.string; tooltipEl.style.padding = tooltip.yPadding + 'px ' + tooltip.xPadding + 'px'; };
true