최초 커밋

This commit is contained in:
2025-10-01 09:29:34 +09:00
commit a8b84ff39a
1677 changed files with 954149 additions and 0 deletions

View File

@@ -0,0 +1,323 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Accessibility component class definition
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../parts/Globals.js';
var win = H.win, doc = win.document, fireEvent = H.fireEvent;
import U from '../../parts/Utilities.js';
var extend = U.extend, merge = U.merge;
import HTMLUtilities from './utils/htmlUtilities.js';
var removeElement = HTMLUtilities.removeElement, getFakeMouseEvent = HTMLUtilities.getFakeMouseEvent;
import ChartUtilities from './utils/chartUtilities.js';
var unhideChartElementFromAT = ChartUtilities.unhideChartElementFromAT;
import EventProvider from './utils/EventProvider.js';
import DOMElementProvider from './utils/DOMElementProvider.js';
/* eslint-disable valid-jsdoc */
/** @lends Highcharts.AccessibilityComponent */
var functionsToOverrideByDerivedClasses = {
/**
* Called on component initialization.
*/
init: function () { },
/**
* Get keyboard navigation handler for this component.
* @return {Highcharts.KeyboardNavigationHandler}
*/
getKeyboardNavigation: function () { },
/**
* Called on updates to the chart, including options changes.
* Note that this is also called on first render of chart.
*/
onChartUpdate: function () { },
/**
* Called on every chart render.
*/
onChartRender: function () { },
/**
* Called when accessibility is disabled or chart is destroyed.
*/
destroy: function () { }
};
/**
* The AccessibilityComponent base class, representing a part of the chart that
* has accessibility logic connected to it. This class can be inherited from to
* create a custom accessibility component for a chart.
*
* Components should take care to destroy added elements and unregister event
* handlers on destroy. This is handled automatically if using this.addEvent and
* this.createElement.
*
* @sample highcharts/accessibility/custom-component
* Custom accessibility component
*
* @requires module:modules/accessibility
* @class
* @name Highcharts.AccessibilityComponent
*/
function AccessibilityComponent() { }
/**
* @lends Highcharts.AccessibilityComponent
*/
AccessibilityComponent.prototype = {
/**
* Initialize the class
* @private
* @param {Highcharts.Chart} chart
* Chart object
*/
initBase: function (chart) {
this.chart = chart;
this.eventProvider = new EventProvider();
this.domElementProvider = new DOMElementProvider();
// Key code enum for common keys
this.keyCodes = {
left: 37,
right: 39,
up: 38,
down: 40,
enter: 13,
space: 32,
esc: 27,
tab: 9
};
},
/**
* Add an event to an element and keep track of it for later removal.
* See EventProvider for details.
* @private
*/
addEvent: function () {
return this.eventProvider.addEvent
.apply(this.eventProvider, arguments);
},
/**
* Create an element and keep track of it for later removal.
* See DOMElementProvider for details.
* @private
*/
createElement: function () {
return this.domElementProvider.createElement.apply(this.domElementProvider, arguments);
},
/**
* Fire an event on an element that is either wrapped by Highcharts,
* or a DOM element
* @private
* @param {Highcharts.HTMLElement|Highcharts.HTMLDOMElement|
* Highcharts.SVGDOMElement|Highcharts.SVGElement} el
* @param {Event} eventObject
*/
fireEventOnWrappedOrUnwrappedElement: function (el, eventObject) {
var type = eventObject.type;
if (doc.createEvent && (el.dispatchEvent || el.fireEvent)) {
if (el.dispatchEvent) {
el.dispatchEvent(eventObject);
}
else {
el.fireEvent(type, eventObject);
}
}
else {
fireEvent(el, type, eventObject);
}
},
/**
* Utility function to attempt to fake a click event on an element.
* @private
* @param {Highcharts.HTMLDOMElement|Highcharts.SVGDOMElement} element
*/
fakeClickEvent: function (element) {
if (element) {
var fakeEventObject = getFakeMouseEvent('click');
this.fireEventOnWrappedOrUnwrappedElement(element, fakeEventObject);
}
},
/**
* Add a new proxy group to the proxy container. Creates the proxy container
* if it does not exist.
* @private
* @param {Highcharts.HTMLAttributes} [attrs]
* The attributes to set on the new group div.
* @return {Highcharts.HTMLDOMElement}
* The new proxy group element.
*/
addProxyGroup: function (attrs) {
this.createOrUpdateProxyContainer();
var groupDiv = this.createElement('div');
Object.keys(attrs || {}).forEach(function (prop) {
if (attrs[prop] !== null) {
groupDiv.setAttribute(prop, attrs[prop]);
}
});
this.chart.a11yProxyContainer.appendChild(groupDiv);
return groupDiv;
},
/**
* Creates and updates DOM position of proxy container
* @private
*/
createOrUpdateProxyContainer: function () {
var chart = this.chart, rendererSVGEl = chart.renderer.box;
chart.a11yProxyContainer = chart.a11yProxyContainer ||
this.createProxyContainerElement();
if (rendererSVGEl.nextSibling !== chart.a11yProxyContainer) {
chart.container.insertBefore(chart.a11yProxyContainer, rendererSVGEl.nextSibling);
}
},
/**
* @private
* @return {Highcharts.HTMLDOMElement} element
*/
createProxyContainerElement: function () {
var pc = doc.createElement('div');
pc.className = 'highcharts-a11y-proxy-container';
return pc;
},
/**
* Create an invisible proxy HTML button in the same position as an SVG
* element
* @private
* @param {Highcharts.SVGElement} svgElement
* The wrapped svg el to proxy.
* @param {Highcharts.HTMLDOMElement} parentGroup
* The proxy group element in the proxy container to add this button to.
* @param {Highcharts.SVGAttributes} [attributes]
* Additional attributes to set.
* @param {Highcharts.SVGElement} [posElement]
* Element to use for positioning instead of svgElement.
* @param {Function} [preClickEvent]
* Function to call before click event fires.
*
* @return {Highcharts.HTMLDOMElement} The proxy button.
*/
createProxyButton: function (svgElement, parentGroup, attributes, posElement, preClickEvent) {
var svgEl = svgElement.element, proxy = this.createElement('button'), attrs = merge({
'aria-label': svgEl.getAttribute('aria-label')
}, attributes), bBox = this.getElementPosition(posElement || svgElement);
Object.keys(attrs).forEach(function (prop) {
if (attrs[prop] !== null) {
proxy.setAttribute(prop, attrs[prop]);
}
});
proxy.className = 'highcharts-a11y-proxy-button';
if (preClickEvent) {
this.addEvent(proxy, 'click', preClickEvent);
}
this.setProxyButtonStyle(proxy, bBox);
this.proxyMouseEventsForButton(svgEl, proxy);
// Add to chart div and unhide from screen readers
parentGroup.appendChild(proxy);
if (!attrs['aria-hidden']) {
unhideChartElementFromAT(this.chart, proxy);
}
return proxy;
},
/**
* Get the position relative to chart container for a wrapped SVG element.
* @private
* @param {Highcharts.SVGElement} element
* The element to calculate position for.
* @return {Highcharts.BBoxObject}
* Object with x and y props for the position.
*/
getElementPosition: function (element) {
var el = element.element, div = this.chart.renderTo;
if (div && el && el.getBoundingClientRect) {
var rectEl = el.getBoundingClientRect(), rectDiv = div.getBoundingClientRect();
return {
x: rectEl.left - rectDiv.left,
y: rectEl.top - rectDiv.top,
width: rectEl.right - rectEl.left,
height: rectEl.bottom - rectEl.top
};
}
return { x: 0, y: 0, width: 1, height: 1 };
},
/**
* @private
* @param {Highcharts.HTMLElement} button
* @param {Highcharts.BBoxObject} bBox
*/
setProxyButtonStyle: function (button, bBox) {
merge(true, button.style, {
'border-width': 0,
'background-color': 'transparent',
cursor: 'pointer',
outline: 'none',
opacity: 0.001,
filter: 'alpha(opacity=1)',
'-ms-filter': 'progid:DXImageTransform.Microsoft.Alpha(Opacity=1)',
zIndex: 999,
overflow: 'hidden',
padding: 0,
margin: 0,
display: 'block',
position: 'absolute',
width: (bBox.width || 1) + 'px',
height: (bBox.height || 1) + 'px',
left: (bBox.x || 0) + 'px',
top: (bBox.y || 0) + 'px'
});
},
/**
* @private
* @param {Highcharts.HTMLElement|Highcharts.HTMLDOMElement|
* Highcharts.SVGDOMElement|Highcharts.SVGElement} source
* @param {Highcharts.HTMLElement} button
*/
proxyMouseEventsForButton: function (source, button) {
var component = this;
[
'click', 'touchstart', 'touchend', 'touchcancel', 'touchmove',
'mouseover', 'mouseenter', 'mouseleave', 'mouseout'
].forEach(function (evtType) {
component.addEvent(button, evtType, function (e) {
var clonedEvent = component.cloneMouseEvent(e);
if (source) {
component.fireEventOnWrappedOrUnwrappedElement(source, clonedEvent);
}
e.stopPropagation();
e.preventDefault();
});
});
},
/**
* Utility function to clone a mouse event for re-dispatching.
* @private
* @param {global.MouseEvent} e The event to clone.
* @return {global.MouseEvent} The cloned event
*/
cloneMouseEvent: function (e) {
if (typeof win.MouseEvent === 'function') {
return new win.MouseEvent(e.type, e);
}
// No MouseEvent support, try using initMouseEvent
if (doc.createEvent) {
var evt = doc.createEvent('MouseEvent');
if (evt.initMouseEvent) {
evt.initMouseEvent(e.type, e.bubbles, // #10561, #12161
e.cancelable, e.view || win, e.detail, e.screenX, e.screenY, e.clientX, e.clientY, e.ctrlKey, e.altKey, e.shiftKey, e.metaKey, e.button, e.relatedTarget);
return evt;
}
}
return getFakeMouseEvent(e.type);
},
/**
* Remove traces of the component.
* @private
*/
destroyBase: function () {
removeElement(this.chart.a11yProxyContainer);
this.domElementProvider.destroyCreatedElements();
this.eventProvider.removeAddedEvents();
}
};
extend(AccessibilityComponent.prototype, functionsToOverrideByDerivedClasses);
export default AccessibilityComponent;

View File

@@ -0,0 +1,345 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Main keyboard navigation handling.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../parts/Globals.js';
var win = H.win, doc = win.document;
import U from '../../parts/Utilities.js';
var addEvent = U.addEvent, fireEvent = U.fireEvent;
import HTMLUtilities from './utils/htmlUtilities.js';
var getElement = HTMLUtilities.getElement;
import EventProvider from './utils/EventProvider.js';
/* eslint-disable valid-jsdoc */
// Add event listener to document to detect ESC key press and dismiss
// hover/popup content.
addEvent(doc, 'keydown', function (e) {
var keycode = e.which || e.keyCode;
var esc = 27;
if (keycode === esc && H.charts) {
H.charts.forEach(function (chart) {
if (chart && chart.dismissPopupContent) {
chart.dismissPopupContent();
}
});
}
});
/**
* Dismiss popup content in chart, including export menu and tooltip.
*/
H.Chart.prototype.dismissPopupContent = function () {
var chart = this;
fireEvent(this, 'dismissPopupContent', {}, function () {
if (chart.tooltip) {
chart.tooltip.hide(0);
}
chart.hideExportMenu();
});
};
/**
* The KeyboardNavigation class, containing the overall keyboard navigation
* logic for the chart.
*
* @requires module:modules/accessibility
*
* @private
* @class
* @param {Highcharts.Chart} chart
* Chart object
* @param {object} components
* Map of component names to AccessibilityComponent objects.
* @name Highcharts.KeyboardNavigation
*/
function KeyboardNavigation(chart, components) {
this.init(chart, components);
}
KeyboardNavigation.prototype = {
/**
* Initialize the class
* @private
* @param {Highcharts.Chart} chart
* Chart object
* @param {object} components
* Map of component names to AccessibilityComponent objects.
*/
init: function (chart, components) {
var _this = this;
var ep = this.eventProvider = new EventProvider();
this.chart = chart;
this.components = components;
this.modules = [];
this.currentModuleIx = 0;
ep.addEvent(chart.renderTo, 'keydown', function (e) { return _this.onKeydown(e); });
ep.addEvent(chart.container, 'focus', function (e) { return _this.onFocus(e); });
ep.addEvent(doc, 'mouseup', function () { return _this.onMouseUp(); });
ep.addEvent(chart.renderTo, 'mouseover', function () {
_this.pointerIsOverChart = true;
});
ep.addEvent(chart.renderTo, 'mouseout', function () {
_this.pointerIsOverChart = false;
});
// Run an update to get all modules
this.update();
// Init first module
if (this.modules.length) {
this.modules[0].init(1);
}
},
/**
* Update the modules for the keyboard navigation.
* @param {Array<string>} [order]
* Array specifying the tab order of the components.
*/
update: function (order) {
var a11yOptions = this.chart.options.accessibility, keyboardOptions = a11yOptions && a11yOptions.keyboardNavigation, components = this.components;
this.updateContainerTabindex();
if (keyboardOptions &&
keyboardOptions.enabled &&
order &&
order.length) {
// We (still) have keyboard navigation. Update module list
this.modules = order.reduce(function (modules, componentName) {
var navModules = components[componentName].getKeyboardNavigation();
return modules.concat(navModules);
}, []);
this.updateExitAnchor();
}
else {
this.modules = [];
this.currentModuleIx = 0;
this.removeExitAnchor();
}
},
/**
* Function to run on container focus
* @private
* @param {global.FocusEvent} e Browser focus event.
*/
onFocus: function (e) {
var _a;
var chart = this.chart;
var focusComesFromChart = (e.relatedTarget &&
chart.container.contains(e.relatedTarget));
if (!focusComesFromChart) {
(_a = this.modules[0]) === null || _a === void 0 ? void 0 : _a.init(1);
}
},
/**
* Reset chart navigation state if we click outside the chart and it's
* not already reset.
* @private
*/
onMouseUp: function () {
if (!this.keyboardReset && !this.pointerIsOverChart) {
var chart = this.chart, curMod = this.modules &&
this.modules[this.currentModuleIx || 0];
if (curMod && curMod.terminate) {
curMod.terminate();
}
if (chart.focusElement) {
chart.focusElement.removeFocusBorder();
}
this.currentModuleIx = 0;
this.keyboardReset = true;
}
},
/**
* Function to run on keydown
* @private
* @param {global.KeyboardEvent} ev Browser keydown event.
*/
onKeydown: function (ev) {
var e = ev || win.event, preventDefault, curNavModule = this.modules && this.modules.length &&
this.modules[this.currentModuleIx];
// Used for resetting nav state when clicking outside chart
this.keyboardReset = false;
// If there is a nav module for the current index, run it.
// Otherwise, we are outside of the chart in some direction.
if (curNavModule) {
var response = curNavModule.run(e);
if (response === curNavModule.response.success) {
preventDefault = true;
}
else if (response === curNavModule.response.prev) {
preventDefault = this.prev();
}
else if (response === curNavModule.response.next) {
preventDefault = this.next();
}
if (preventDefault) {
e.preventDefault();
e.stopPropagation();
}
}
},
/**
* Go to previous module.
* @private
*/
prev: function () {
return this.move(-1);
},
/**
* Go to next module.
* @private
*/
next: function () {
return this.move(1);
},
/**
* Move to prev/next module.
* @private
* @param {number} direction
* Direction to move. +1 for next, -1 for prev.
* @return {boolean}
* True if there was a valid module in direction.
*/
move: function (direction) {
var curModule = this.modules && this.modules[this.currentModuleIx];
if (curModule && curModule.terminate) {
curModule.terminate(direction);
}
// Remove existing focus border if any
if (this.chart.focusElement) {
this.chart.focusElement.removeFocusBorder();
}
this.currentModuleIx += direction;
var newModule = this.modules && this.modules[this.currentModuleIx];
if (newModule) {
if (newModule.validate && !newModule.validate()) {
return this.move(direction); // Invalid module, recurse
}
if (newModule.init) {
newModule.init(direction); // Valid module, init it
return true;
}
}
// No module
this.currentModuleIx = 0; // Reset counter
// Set focus to chart or exit anchor depending on direction
if (direction > 0) {
this.exiting = true;
this.exitAnchor.focus();
}
else {
this.chart.container.focus();
}
return false;
},
/**
* We use an exit anchor to move focus out of chart whenever we want, by
* setting focus to this div and not preventing the default tab action. We
* also use this when users come back into the chart by tabbing back, in
* order to navigate from the end of the chart.
* @private
*/
updateExitAnchor: function () {
var endMarkerId = 'highcharts-end-of-chart-marker-' + this.chart.index, endMarker = getElement(endMarkerId);
this.removeExitAnchor();
if (endMarker) {
this.makeElementAnExitAnchor(endMarker);
this.exitAnchor = endMarker;
}
else {
this.createExitAnchor();
}
},
/**
* Chart container should have tabindex if navigation is enabled.
* @private
*/
updateContainerTabindex: function () {
var a11yOptions = this.chart.options.accessibility, keyboardOptions = a11yOptions && a11yOptions.keyboardNavigation, shouldHaveTabindex = !(keyboardOptions && keyboardOptions.enabled === false), container = this.chart.container, curTabindex = container.getAttribute('tabIndex');
if (shouldHaveTabindex && !curTabindex) {
container.setAttribute('tabindex', '0');
}
else if (!shouldHaveTabindex && curTabindex === '0') {
container.removeAttribute('tabindex');
}
},
/**
* @private
*/
makeElementAnExitAnchor: function (el) {
el.setAttribute('class', 'highcharts-exit-anchor');
el.setAttribute('tabindex', '0');
el.setAttribute('aria-hidden', false);
// Handle focus
this.addExitAnchorEventsToEl(el);
},
/**
* Add new exit anchor to the chart.
*
* @private
*/
createExitAnchor: function () {
var chart = this.chart, exitAnchor = this.exitAnchor = doc.createElement('div');
chart.renderTo.appendChild(exitAnchor);
this.makeElementAnExitAnchor(exitAnchor);
},
/**
* @private
*/
removeExitAnchor: function () {
if (this.exitAnchor && this.exitAnchor.parentNode) {
this.exitAnchor.parentNode
.removeChild(this.exitAnchor);
delete this.exitAnchor;
}
},
/**
* @private
*/
addExitAnchorEventsToEl: function (element) {
var chart = this.chart, keyboardNavigation = this;
this.eventProvider.addEvent(element, 'focus', function (ev) {
var e = ev || win.event, curModule, focusComesFromChart = (e.relatedTarget &&
chart.container.contains(e.relatedTarget)), comingInBackwards = !(focusComesFromChart || keyboardNavigation.exiting);
if (comingInBackwards) {
chart.renderTo.focus();
e.preventDefault();
// Move to last valid keyboard nav module
// Note the we don't run it, just set the index
if (keyboardNavigation.modules &&
keyboardNavigation.modules.length) {
keyboardNavigation.currentModuleIx =
keyboardNavigation.modules.length - 1;
curModule = keyboardNavigation.modules[keyboardNavigation.currentModuleIx];
// Validate the module
if (curModule &&
curModule.validate && !curModule.validate()) {
// Invalid. Try moving backwards to find next valid.
keyboardNavigation.prev();
}
else if (curModule) {
// We have a valid module, init it
curModule.init(-1);
}
}
}
else {
// Don't skip the next focus, we only skip once.
keyboardNavigation.exiting = false;
}
});
},
/**
* Remove all traces of keyboard navigation.
* @private
*/
destroy: function () {
this.removeExitAnchor();
this.eventProvider.removeAddedEvents();
if (this.chart.container.getAttribute('tabindex') === '0') {
this.chart.container.removeAttribute('tabindex');
}
}
};
export default KeyboardNavigation;

View File

@@ -0,0 +1,99 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Keyboard navigation handler base class definition
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import U from '../../parts/Utilities.js';
var find = U.find;
/**
* Options for the keyboard navigation handler.
*
* @interface Highcharts.KeyboardNavigationHandlerOptionsObject
*/ /**
* An array containing pairs of an array of keycodes, mapped to a handler
* function. When the keycode is received, the handler is called with the
* keycode as parameter.
* @name Highcharts.KeyboardNavigationHandlerOptionsObject#keyCodeMap
* @type {Array<Array<Array<number>, Function>>}
*/ /**
* Function to run on initialization of module.
* @name Highcharts.KeyboardNavigationHandlerOptionsObject#init
* @type {Function}
*/ /**
* Function to run before moving to next/prev module. Receives moving direction
* as parameter: +1 for next, -1 for previous.
* @name Highcharts.KeyboardNavigationHandlerOptionsObject#terminate
* @type {Function|undefined}
*/ /**
* Function to run to validate module. Should return false if module should not
* run, true otherwise. Receives chart as parameter.
* @name Highcharts.KeyboardNavigationHandlerOptionsObject#validate
* @type {Function|undefined}
*/
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* Define a keyboard navigation handler for use with a
* Highcharts.AccessibilityComponent instance. This functions as an abstraction
* layer for keyboard navigation, and defines a map of keyCodes to handler
* functions.
*
* @requires module:modules/accessibility
*
* @sample highcharts/accessibility/custom-component
* Custom accessibility component
*
* @class
* @name Highcharts.KeyboardNavigationHandler
*
* @param {Highcharts.Chart} chart
* The chart this module should act on.
*
* @param {Highcharts.KeyboardNavigationHandlerOptionsObject} options
* Options for the keyboard navigation handler.
*/
function KeyboardNavigationHandler(chart, options) {
this.chart = chart;
this.keyCodeMap = options.keyCodeMap || [];
this.validate = options.validate;
this.init = options.init;
this.terminate = options.terminate;
// Response enum
this.response = {
success: 1,
prev: 2,
next: 3,
noHandler: 4,
fail: 5 // Handler failed
};
}
KeyboardNavigationHandler.prototype = {
/**
* Find handler function(s) for key code in the keyCodeMap and run it.
*
* @function KeyboardNavigationHandler#run
* @param {global.KeyboardEvent} e
* @return {number} Returns a response code indicating whether the run was
* a success/fail/unhandled, or if we should move to next/prev module.
*/
run: function (e) {
var keyCode = e.which || e.keyCode, response = this.response.noHandler, handlerCodeSet = find(this.keyCodeMap, function (codeSet) {
return codeSet[0].indexOf(keyCode) > -1;
});
if (handlerCodeSet) {
response = handlerCodeSet[1].call(this, keyCode, e);
}
else if (keyCode === 9) {
// Default tab handler, move to next/prev module
response = this.response[e.shiftKey ? 'prev' : 'next'];
}
return response;
}
};
export default KeyboardNavigationHandler;

View File

@@ -0,0 +1,251 @@
/* *
*
* Accessibility module - internationalization support
*
* (c) 2010-2020 Highsoft AS
* Author: Øystein Moseng
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../parts/Globals.js';
import U from '../../parts/Utilities.js';
var format = U.format, pick = U.pick;
/* eslint-disable valid-jsdoc */
/**
* String trim that works for IE6-8 as well.
*
* @private
* @function stringTrim
*
* @param {string} str
* The input string
*
* @return {string}
* The trimmed string
*/
function stringTrim(str) {
return str.trim && str.trim() || str.replace(/^\s+|\s+$/g, '');
}
/**
* i18n utility function. Format a single array or plural statement in a format
* string. If the statement is not an array or plural statement, returns the
* statement within brackets. Invalid array statements return an empty string.
*
* @private
* @function formatExtendedStatement
*
* @param {string} statement
*
* @param {Highcharts.Dictionary<*>} ctx
* Context to apply to the format string.
*
* @return {string}
*/
function formatExtendedStatement(statement, ctx) {
var eachStart = statement.indexOf('#each('), pluralStart = statement.indexOf('#plural('), indexStart = statement.indexOf('['), indexEnd = statement.indexOf(']'), arr, result;
// Dealing with an each-function?
if (eachStart > -1) {
var eachEnd = statement.slice(eachStart).indexOf(')') + eachStart, preEach = statement.substring(0, eachStart), postEach = statement.substring(eachEnd + 1), eachStatement = statement.substring(eachStart + 6, eachEnd), eachArguments = eachStatement.split(','), lenArg = Number(eachArguments[1]), len;
result = '';
arr = ctx[eachArguments[0]];
if (arr) {
lenArg = isNaN(lenArg) ? arr.length : lenArg;
len = lenArg < 0 ?
arr.length + lenArg :
Math.min(lenArg, arr.length); // Overshoot
// Run through the array for the specified length
for (var i = 0; i < len; ++i) {
result += preEach + arr[i] + postEach;
}
}
return result.length ? result : '';
}
// Dealing with a plural-function?
if (pluralStart > -1) {
var pluralEnd = statement.slice(pluralStart).indexOf(')') + pluralStart, pluralStatement = statement.substring(pluralStart + 8, pluralEnd), pluralArguments = pluralStatement.split(','), num = Number(ctx[pluralArguments[0]]);
switch (num) {
case 0:
result = pick(pluralArguments[4], pluralArguments[1]);
break;
case 1:
result = pick(pluralArguments[2], pluralArguments[1]);
break;
case 2:
result = pick(pluralArguments[3], pluralArguments[1]);
break;
default:
result = pluralArguments[1];
}
return result ? stringTrim(result) : '';
}
// Array index
if (indexStart > -1) {
var arrayName = statement.substring(0, indexStart), ix = Number(statement.substring(indexStart + 1, indexEnd)), val;
arr = ctx[arrayName];
if (!isNaN(ix) && arr) {
if (ix < 0) {
val = arr[arr.length + ix];
// Handle negative overshoot
if (typeof val === 'undefined') {
val = arr[0];
}
}
else {
val = arr[ix];
// Handle positive overshoot
if (typeof val === 'undefined') {
val = arr[arr.length - 1];
}
}
}
return typeof val !== 'undefined' ? val : '';
}
// Standard substitution, delegate to format or similar
return '{' + statement + '}';
}
/**
* i18n formatting function. Extends Highcharts.format() functionality by also
* handling arrays and plural conditionals. Arrays can be indexed as follows:
*
* - Format: 'This is the first index: {myArray[0]}. The last: {myArray[-1]}.'
*
* - Context: { myArray: [0, 1, 2, 3, 4, 5] }
*
* - Result: 'This is the first index: 0. The last: 5.'
*
*
* They can also be iterated using the #each() function. This will repeat the
* contents of the bracket expression for each element. Example:
*
* - Format: 'List contains: {#each(myArray)cm }'
*
* - Context: { myArray: [0, 1, 2] }
*
* - Result: 'List contains: 0cm 1cm 2cm '
*
*
* The #each() function optionally takes a length parameter. If positive, this
* parameter specifies the max number of elements to iterate through. If
* negative, the function will subtract the number from the length of the array.
* Use this to stop iterating before the array ends. Example:
*
* - Format: 'List contains: {#each(myArray, -1) }and {myArray[-1]}.'
*
* - Context: { myArray: [0, 1, 2, 3] }
*
* - Result: 'List contains: 0, 1, 2, and 3.'
*
*
* Use the #plural() function to pick a string depending on whether or not a
* context object is 1. Arguments are #plural(obj, plural, singular). Example:
*
* - Format: 'Has {numPoints} {#plural(numPoints, points, point}.'
*
* - Context: { numPoints: 5 }
*
* - Result: 'Has 5 points.'
*
*
* Optionally there are additional parameters for dual and none: #plural(obj,
* plural, singular, dual, none). Example:
*
* - Format: 'Has {#plural(numPoints, many points, one point, two points,
* none}.'
*
* - Context: { numPoints: 2 }
*
* - Result: 'Has two points.'
*
*
* The dual or none parameters will take precedence if they are supplied.
*
* @requires modules/accessibility
*
* @function Highcharts.i18nFormat
*
* @param {string} formatString
* The string to format.
*
* @param {Highcharts.Dictionary<*>} context
* Context to apply to the format string.
*
* @param {Highcharts.Chart} chart
* A `Chart` instance with a time object and numberFormatter, passed on
* to format().
*
* @return {string}
* The formatted string.
*/
H.i18nFormat = function (formatString, context, chart) {
var getFirstBracketStatement = function (sourceStr, offset) {
var str = sourceStr.slice(offset || 0), startBracket = str.indexOf('{'), endBracket = str.indexOf('}');
if (startBracket > -1 && endBracket > startBracket) {
return {
statement: str.substring(startBracket + 1, endBracket),
begin: offset + startBracket + 1,
end: offset + endBracket
};
}
}, tokens = [], bracketRes, constRes, cursor = 0;
// Tokenize format string into bracket statements and constants
do {
bracketRes = getFirstBracketStatement(formatString, cursor);
constRes = formatString.substring(cursor, bracketRes && bracketRes.begin - 1);
// If we have constant content before this bracket statement, add it
if (constRes.length) {
tokens.push({
value: constRes,
type: 'constant'
});
}
// Add the bracket statement
if (bracketRes) {
tokens.push({
value: bracketRes.statement,
type: 'statement'
});
}
cursor = bracketRes ? bracketRes.end + 1 : cursor + 1;
} while (bracketRes);
// Perform the formatting. The formatArrayStatement function returns the
// statement in brackets if it is not an array statement, which means it
// gets picked up by format below.
tokens.forEach(function (token) {
if (token.type === 'statement') {
token.value = formatExtendedStatement(token.value, context);
}
});
// Join string back together and pass to format to pick up non-array
// statements.
return format(tokens.reduce(function (acc, cur) {
return acc + cur.value;
}, ''), context, chart);
};
/**
* Apply context to a format string from lang options of the chart.
*
* @requires modules/accessibility
*
* @function Highcharts.Chart#langFormat
*
* @param {string} langKey
* Key (using dot notation) into lang option structure.
*
* @param {Highcharts.Dictionary<*>} context
* Context to apply to the format string.
*
* @return {string}
* The formatted string.
*/
H.Chart.prototype.langFormat = function (langKey, context) {
var keys = langKey.split('.'), formatString = this.options.lang, i = 0;
for (; i < keys.length; ++i) {
formatString = formatString && formatString[keys[i]];
}
return typeof formatString === 'string' ?
H.i18nFormat(formatString, context, this) : '';
};

View File

@@ -0,0 +1,280 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Accessibility module for Highcharts
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import ChartUtilities from './utils/chartUtilities.js';
import H from '../../parts/Globals.js';
import KeyboardNavigationHandler from './KeyboardNavigationHandler.js';
import Point from '../../parts/Point.js';
import U from '../../parts/Utilities.js';
var addEvent = U.addEvent, extend = U.extend, fireEvent = U.fireEvent, merge = U.merge;
var doc = H.win.document;
import AccessibilityComponent from './AccessibilityComponent.js';
import KeyboardNavigation from './KeyboardNavigation.js';
import LegendComponent from './components/LegendComponent.js';
import MenuComponent from './components/MenuComponent.js';
import SeriesComponent from './components/SeriesComponent/SeriesComponent.js';
import ZoomComponent from './components/ZoomComponent.js';
import RangeSelectorComponent from './components/RangeSelectorComponent.js';
import InfoRegionsComponent from './components/InfoRegionsComponent.js';
import ContainerComponent from './components/ContainerComponent.js';
import whcm from './high-contrast-mode.js';
import highContrastTheme from './high-contrast-theme.js';
import defaultOptions from './options/options.js';
import defaultLangOptions from './options/langOptions.js';
import copyDeprecatedOptions from './options/deprecatedOptions.js';
import './a11y-i18n.js';
import './focusBorder.js';
// Add default options
merge(true, H.defaultOptions, defaultOptions, {
accessibility: {
highContrastTheme: highContrastTheme
},
lang: defaultLangOptions
});
// Expose functionality on Highcharts namespace
H.A11yChartUtilities = ChartUtilities;
H.KeyboardNavigationHandler = KeyboardNavigationHandler;
H.AccessibilityComponent = AccessibilityComponent;
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* The Accessibility class
*
* @private
* @requires module:modules/accessibility
*
* @class
* @name Highcharts.Accessibility
*
* @param {Highcharts.Chart} chart
* Chart object
*/
function Accessibility(chart) {
this.init(chart);
}
Accessibility.prototype = {
/**
* Initialize the accessibility class
* @private
* @param {Highcharts.Chart} chart
* Chart object
*/
init: function (chart) {
this.chart = chart;
// Abort on old browsers
if (!doc.addEventListener || !chart.renderer.isSVG) {
chart.renderTo.setAttribute('aria-hidden', true);
return;
}
// Copy over any deprecated options that are used. We could do this on
// every update, but it is probably not needed.
copyDeprecatedOptions(chart);
this.initComponents();
this.keyboardNavigation = new KeyboardNavigation(chart, this.components);
this.update();
},
/**
* @private
*/
initComponents: function () {
var chart = this.chart, a11yOptions = chart.options.accessibility;
this.components = {
container: new ContainerComponent(),
infoRegions: new InfoRegionsComponent(),
legend: new LegendComponent(),
chartMenu: new MenuComponent(),
rangeSelector: new RangeSelectorComponent(),
series: new SeriesComponent(),
zoom: new ZoomComponent()
};
if (a11yOptions.customComponents) {
extend(this.components, a11yOptions.customComponents);
}
var components = this.components;
this.getComponentOrder().forEach(function (componentName) {
components[componentName].initBase(chart);
components[componentName].init();
});
},
/**
* Get order to update components in.
* @private
*/
getComponentOrder: function () {
if (!this.components) {
return []; // For zombie accessibility object on old browsers
}
if (!this.components.series) {
return Object.keys(this.components);
}
var componentsExceptSeries = Object.keys(this.components)
.filter(function (c) { return c !== 'series'; });
// Update series first, so that other components can read accessibility
// info on points.
return ['series'].concat(componentsExceptSeries);
},
/**
* Update all components.
*/
update: function () {
var components = this.components, chart = this.chart, a11yOptions = chart.options.accessibility;
fireEvent(chart, 'beforeA11yUpdate');
// Update the chart type list as this is used by multiple modules
chart.types = this.getChartTypes();
// Update markup
this.getComponentOrder().forEach(function (componentName) {
components[componentName].onChartUpdate();
fireEvent(chart, 'afterA11yComponentUpdate', {
name: componentName,
component: components[componentName]
});
});
// Update keyboard navigation
this.keyboardNavigation.update(a11yOptions.keyboardNavigation.order);
// Handle high contrast mode
if (!chart.highContrastModeActive && // Only do this once
whcm.isHighContrastModeActive()) {
whcm.setHighContrastTheme(chart);
}
fireEvent(chart, 'afterA11yUpdate', {
accessibility: this
});
},
/**
* Destroy all elements.
*/
destroy: function () {
var chart = this.chart || {};
// Destroy components
var components = this.components;
Object.keys(components).forEach(function (componentName) {
components[componentName].destroy();
components[componentName].destroyBase();
});
// Kill keyboard nav
if (this.keyboardNavigation) {
this.keyboardNavigation.destroy();
}
// Hide container from screen readers if it exists
if (chart.renderTo) {
chart.renderTo.setAttribute('aria-hidden', true);
}
// Remove focus border if it exists
if (chart.focusElement) {
chart.focusElement.removeFocusBorder();
}
},
/**
* Return a list of the types of series we have in the chart.
* @private
*/
getChartTypes: function () {
var types = {};
this.chart.series.forEach(function (series) {
types[series.type] = 1;
});
return Object.keys(types);
}
};
/**
* @private
*/
H.Chart.prototype.updateA11yEnabled = function () {
var a11y = this.accessibility, accessibilityOptions = this.options.accessibility;
if (accessibilityOptions && accessibilityOptions.enabled) {
if (a11y) {
a11y.update();
}
else {
this.accessibility = a11y = new Accessibility(this);
}
}
else if (a11y) {
// Destroy if after update we have a11y and it is disabled
if (a11y.destroy) {
a11y.destroy();
}
delete this.accessibility;
}
else {
// Just hide container
this.renderTo.setAttribute('aria-hidden', true);
}
};
// Handle updates to the module and send render updates to components
addEvent(H.Chart, 'render', function (e) {
// Update/destroy
if (this.a11yDirty && this.renderTo) {
delete this.a11yDirty;
this.updateA11yEnabled();
}
var a11y = this.accessibility;
if (a11y) {
a11y.getComponentOrder().forEach(function (componentName) {
a11y.components[componentName].onChartRender();
});
}
});
// Update with chart/series/point updates
addEvent(H.Chart, 'update', function (e) {
// Merge new options
var newOptions = e.options.accessibility;
if (newOptions) {
// Handle custom component updating specifically
if (newOptions.customComponents) {
this.options.accessibility.customComponents =
newOptions.customComponents;
delete newOptions.customComponents;
}
merge(true, this.options.accessibility, newOptions);
// Recreate from scratch
if (this.accessibility && this.accessibility.destroy) {
this.accessibility.destroy();
delete this.accessibility;
}
}
// Mark dirty for update
this.a11yDirty = true;
});
// Mark dirty for update
addEvent(Point, 'update', function () {
if (this.series.chart.accessibility) {
this.series.chart.a11yDirty = true;
}
});
['addSeries', 'init'].forEach(function (event) {
addEvent(H.Chart, event, function () {
this.a11yDirty = true;
});
});
['update', 'updatedData', 'remove'].forEach(function (event) {
addEvent(H.Series, event, function () {
if (this.chart.accessibility) {
this.chart.a11yDirty = true;
}
});
});
// Direct updates (events happen after render)
[
'afterDrilldown', 'drillupall'
].forEach(function (event) {
addEvent(H.Chart, event, function () {
if (this.accessibility) {
this.accessibility.update();
}
});
});
// Destroy with chart
addEvent(H.Chart, 'destroy', function () {
if (this.accessibility) {
this.accessibility.destroy();
}
});

View File

@@ -0,0 +1,136 @@
/* *
*
* (c) 2009-2019 Øystein Moseng
*
* Annotations accessibility code.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import U from '../../../parts/Utilities.js';
var inArray = U.inArray;
import HTMLUtilities from '../utils/htmlUtilities.js';
var escapeStringForHTML = HTMLUtilities.escapeStringForHTML, stripHTMLTagsFromString = HTMLUtilities.stripHTMLTagsFromString;
/**
* Get list of all annotation labels in the chart.
*
* @private
* @param {Highcharts.Chart} chart The chart to get annotation info on.
* @return {Array<object>} The labels, or empty array if none.
*/
function getChartAnnotationLabels(chart) {
var annotations = chart.annotations || [];
return annotations.reduce(function (acc, cur) {
var _a;
if (((_a = cur.options) === null || _a === void 0 ? void 0 : _a.visible) !== false) {
acc = acc.concat(cur.labels);
}
return acc;
}, []);
}
/**
* Get the text of an annotation label.
*
* @private
* @param {object} label The annotation label object
* @return {string} The text in the label.
*/
function getLabelText(label) {
var _a, _b, _c, _d;
var a11yDesc = (_b = (_a = label.options) === null || _a === void 0 ? void 0 : _a.accessibility) === null || _b === void 0 ? void 0 : _b.description;
return a11yDesc ? a11yDesc : ((_d = (_c = label.graphic) === null || _c === void 0 ? void 0 : _c.text) === null || _d === void 0 ? void 0 : _d.textStr) || '';
}
/**
* Describe an annotation label.
*
* @private
* @param {object} label The annotation label object to describe
* @return {string} The description for the label.
*/
function getAnnotationLabelDescription(label) {
var _a, _b;
var a11yDesc = (_b = (_a = label.options) === null || _a === void 0 ? void 0 : _a.accessibility) === null || _b === void 0 ? void 0 : _b.description;
if (a11yDesc) {
return a11yDesc;
}
var chart = label.chart;
var labelText = getLabelText(label);
var points = label.points;
var getAriaLabel = function (point) { var _a, _b; return ((_b = (_a = point === null || point === void 0 ? void 0 : point.graphic) === null || _a === void 0 ? void 0 : _a.element) === null || _b === void 0 ? void 0 : _b.getAttribute('aria-label')) || ''; };
var getValueDesc = function (point) {
var _a;
var valDesc = ((_a = point === null || point === void 0 ? void 0 : point.accessibility) === null || _a === void 0 ? void 0 : _a.valueDescription) || getAriaLabel(point);
var seriesName = (point === null || point === void 0 ? void 0 : point.series.name) || '';
return (seriesName ? seriesName + ', ' : '') + 'data point ' + valDesc;
};
var pointValueDescriptions = points
.filter(function (p) { return !!p.graphic; }) // Filter out mock points
.map(getValueDesc)
.filter(function (desc) { return !!desc; }); // Filter out points we can't describe
var numPoints = pointValueDescriptions.length;
var pointsSelector = numPoints > 1 ? 'MultiplePoints' : numPoints ? 'SinglePoint' : 'NoPoints';
var langFormatStr = 'accessibility.screenReaderSection.annotations.description' + pointsSelector;
var context = {
annotationText: labelText,
numPoints: numPoints,
annotationPoint: pointValueDescriptions[0],
additionalAnnotationPoints: pointValueDescriptions.slice(1)
};
return chart.langFormat(langFormatStr, context);
}
/**
* Return array of HTML strings for each annotation label in the chart.
*
* @private
* @param {Highcharts.Chart} chart The chart to get annotation info on.
* @return {Array<string>} Array of strings with HTML content for each annotation label.
*/
function getAnnotationListItems(chart) {
var labels = getChartAnnotationLabels(chart);
return labels.map(function (label) {
var desc = escapeStringForHTML(stripHTMLTagsFromString(getAnnotationLabelDescription(label)));
return desc ? "<li>" + desc + "</li>" : '';
});
}
/**
* Return the annotation info for a chart as string.
*
* @private
* @param {Highcharts.Chart} chart The chart to get annotation info on.
* @return {string} String with HTML content or empty string if no annotations.
*/
function getAnnotationsInfoHTML(chart) {
var annotations = chart.annotations;
if (!(annotations && annotations.length)) {
return '';
}
var annotationItems = getAnnotationListItems(chart);
return "<ul>" + annotationItems.join(' ') + "</ul>";
}
/**
* Return the texts for the annotation(s) connected to a point, or empty array
* if none.
*
* @private
* @param {Highcharts.Point} point The data point to get the annotation info from.
* @return {Array<string>} Annotation texts
*/
function getPointAnnotationTexts(point) {
var labels = getChartAnnotationLabels(point.series.chart);
var pointLabels = labels
.filter(function (label) { return inArray(point, label.points) > -1; });
if (!pointLabels.length) {
return [];
}
return pointLabels.map(function (label) { return "" + getLabelText(label); });
}
var AnnotationsA11y = {
getAnnotationsInfoHTML: getAnnotationsInfoHTML,
getAnnotationLabelDescription: getAnnotationLabelDescription,
getAnnotationListItems: getAnnotationListItems,
getPointAnnotationTexts: getPointAnnotationTexts
};
export default AnnotationsA11y;

View File

@@ -0,0 +1,115 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Accessibility component for chart container.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../../parts/Globals.js';
var doc = H.win.document;
import U from '../../../parts/Utilities.js';
var extend = U.extend;
import HTMLUtilities from '../utils/htmlUtilities.js';
var stripHTMLTags = HTMLUtilities.stripHTMLTagsFromString;
import ChartUtilities from '../utils/chartUtilities.js';
var unhideChartElementFromAT = ChartUtilities.unhideChartElementFromAT, getChartTitle = ChartUtilities.getChartTitle;
import AccessibilityComponent from '../AccessibilityComponent.js';
/* eslint-disable valid-jsdoc */
/**
* The ContainerComponent class
*
* @private
* @class
* @name Highcharts.ContainerComponent
*/
var ContainerComponent = function () { };
ContainerComponent.prototype = new AccessibilityComponent();
extend(ContainerComponent.prototype, /** @lends Highcharts.ContainerComponent */ {
/**
* Called on first render/updates to the chart, including options changes.
*/
onChartUpdate: function () {
this.handleSVGTitleElement();
this.setSVGContainerLabel();
this.setGraphicContainerAttrs();
this.setRenderToAttrs();
this.makeCreditsAccessible();
},
/**
* @private
*/
handleSVGTitleElement: function () {
var chart = this.chart, titleId = 'highcharts-title-' + chart.index, titleContents = stripHTMLTags(chart.langFormat('accessibility.svgContainerTitle', {
chartTitle: getChartTitle(chart)
}));
if (titleContents.length) {
var titleElement = this.svgTitleElement =
this.svgTitleElement || doc.createElementNS('http://www.w3.org/2000/svg', 'title');
titleElement.textContent = titleContents;
titleElement.id = titleId;
chart.renderTo.insertBefore(titleElement, chart.renderTo.firstChild);
}
},
/**
* @private
*/
setSVGContainerLabel: function () {
var chart = this.chart, svgContainerLabel = stripHTMLTags(chart.langFormat('accessibility.svgContainerLabel', {
chartTitle: getChartTitle(chart)
}));
if (chart.renderer.box && svgContainerLabel.length) {
chart.renderer.box.setAttribute('aria-label', svgContainerLabel);
}
},
/**
* @private
*/
setGraphicContainerAttrs: function () {
var chart = this.chart, label = chart.langFormat('accessibility.graphicContainerLabel', {
chartTitle: getChartTitle(chart)
});
if (label.length) {
chart.container.setAttribute('aria-label', label);
}
},
/**
* @private
*/
setRenderToAttrs: function () {
var chart = this.chart;
if (chart.options.accessibility.landmarkVerbosity !== 'disabled') {
chart.renderTo.setAttribute('role', 'region');
}
else {
chart.renderTo.removeAttribute('role');
}
chart.renderTo.setAttribute('aria-label', chart.langFormat('accessibility.chartContainerLabel', {
title: getChartTitle(chart),
chart: chart
}));
},
/**
* @private
*/
makeCreditsAccessible: function () {
var chart = this.chart, credits = chart.credits;
if (credits) {
if (credits.textStr) {
credits.element.setAttribute('aria-label', stripHTMLTags(chart.langFormat('accessibility.credits', { creditsStr: credits.textStr })));
}
unhideChartElementFromAT(chart, credits.element);
}
},
/**
* Accessibility disabled/chart destroyed.
*/
destroy: function () {
this.chart.renderTo.setAttribute('aria-hidden', true);
}
});
export default ContainerComponent;

View File

@@ -0,0 +1,564 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Accessibility component for chart info region and table.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../../parts/Globals.js';
var doc = H.win.document;
import U from '../../../parts/Utilities.js';
var extend = U.extend, format = U.format, pick = U.pick;
import AccessibilityComponent from '../AccessibilityComponent.js';
import Announcer from '../utils/Announcer.js';
import AnnotationsA11y from './AnnotationsA11y.js';
var getAnnotationsInfoHTML = AnnotationsA11y.getAnnotationsInfoHTML;
import ChartUtilities from '../utils/chartUtilities.js';
var unhideChartElementFromAT = ChartUtilities.unhideChartElementFromAT, getChartTitle = ChartUtilities.getChartTitle, getAxisDescription = ChartUtilities.getAxisDescription;
import HTMLUtilities from '../utils/htmlUtilities.js';
var addClass = HTMLUtilities.addClass, setElAttrs = HTMLUtilities.setElAttrs, escapeStringForHTML = HTMLUtilities.escapeStringForHTML, stripHTMLTagsFromString = HTMLUtilities.stripHTMLTagsFromString, getElement = HTMLUtilities.getElement, visuallyHideElement = HTMLUtilities.visuallyHideElement;
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* @private
*/
function getTypeDescForMapChart(chart, formatContext) {
return formatContext.mapTitle ?
chart.langFormat('accessibility.chartTypes.mapTypeDescription', formatContext) :
chart.langFormat('accessibility.chartTypes.unknownMap', formatContext);
}
/**
* @private
*/
function getTypeDescForCombinationChart(chart, formatContext) {
return chart.langFormat('accessibility.chartTypes.combinationChart', formatContext);
}
/**
* @private
*/
function getTypeDescForEmptyChart(chart, formatContext) {
return chart.langFormat('accessibility.chartTypes.emptyChart', formatContext);
}
/**
* @private
*/
function buildTypeDescriptionFromSeries(chart, types, context) {
var firstType = types[0], typeExplaination = chart.langFormat('accessibility.seriesTypeDescriptions.' + firstType, context), multi = chart.series && chart.series.length < 2 ? 'Single' : 'Multiple';
return (chart.langFormat('accessibility.chartTypes.' + firstType + multi, context) ||
chart.langFormat('accessibility.chartTypes.default' + multi, context)) + (typeExplaination ? ' ' + typeExplaination : '');
}
/**
* @private
*/
function getTableSummary(chart) {
return chart.langFormat('accessibility.table.tableSummary', { chart: chart });
}
/**
* @private
*/
function stripEmptyHTMLTags(str) {
return str.replace(/<(\w+)[^>]*?>\s*<\/\1>/g, '');
}
/**
* @private
*/
function enableSimpleHTML(str) {
return str
.replace(/&lt;(h[1-7]|p|div|ul|ol|li)&gt;/g, '<$1>')
.replace(/&lt;&#x2F;(h[1-7]|p|div|ul|ol|li|a|button)&gt;/g, '</$1>')
.replace(/&lt;(div|a|button) id=&quot;([a-zA-Z\-0-9#]*?)&quot;&gt;/g, '<$1 id="$2">');
}
/**
* @private
*/
function stringToSimpleHTML(str) {
return stripEmptyHTMLTags(enableSimpleHTML(escapeStringForHTML(str)));
}
/**
* Return simplified explaination of chart type. Some types will not be familiar
* to most users, but in those cases we try to add an explaination of the type.
*
* @private
* @function Highcharts.Chart#getTypeDescription
* @param {Array<string>} types The series types in this chart.
* @return {string} The text description of the chart type.
*/
H.Chart.prototype.getTypeDescription = function (types) {
var firstType = types[0], firstSeries = this.series && this.series[0] || {}, formatContext = {
numSeries: this.series.length,
numPoints: firstSeries.points && firstSeries.points.length,
chart: this,
mapTitle: firstSeries.mapTitle
};
if (!firstType) {
return getTypeDescForEmptyChart(this, formatContext);
}
if (firstType === 'map') {
return getTypeDescForMapChart(this, formatContext);
}
if (this.types.length > 1) {
return getTypeDescForCombinationChart(this, formatContext);
}
return buildTypeDescriptionFromSeries(this, types, formatContext);
};
/**
* The InfoRegionsComponent class
*
* @private
* @class
* @name Highcharts.InfoRegionsComponent
*/
var InfoRegionsComponent = function () { };
InfoRegionsComponent.prototype = new AccessibilityComponent();
extend(InfoRegionsComponent.prototype, /** @lends Highcharts.InfoRegionsComponent */ {
/**
* Init the component
* @private
*/
init: function () {
var chart = this.chart;
var component = this;
this.initRegionsDefinitions();
this.addEvent(chart, 'afterGetTable', function (e) {
component.onDataTableCreated(e);
});
this.addEvent(chart, 'afterViewData', function (tableDiv) {
component.dataTableDiv = tableDiv;
// Use small delay to give browsers & AT time to register new table
setTimeout(function () {
component.focusDataTable();
}, 300);
});
this.announcer = new Announcer(chart, 'assertive');
},
/**
* @private
*/
initRegionsDefinitions: function () {
var component = this;
this.screenReaderSections = {
before: {
element: null,
buildContent: function (chart) {
var formatter = chart.options.accessibility
.screenReaderSection.beforeChartFormatter;
return formatter ? formatter(chart) :
component.defaultBeforeChartFormatter(chart);
},
insertIntoDOM: function (el, chart) {
chart.renderTo.insertBefore(el, chart.renderTo.firstChild);
},
afterInserted: function () {
if (typeof component.sonifyButtonId !== 'undefined') {
component.initSonifyButton(component.sonifyButtonId);
}
if (typeof component.dataTableButtonId !== 'undefined') {
component.initDataTableButton(component.dataTableButtonId);
}
}
},
after: {
element: null,
buildContent: function (chart) {
var formatter = chart.options.accessibility.screenReaderSection
.afterChartFormatter;
return formatter ? formatter(chart) :
component.defaultAfterChartFormatter();
},
insertIntoDOM: function (el, chart) {
chart.renderTo.insertBefore(el, chart.container.nextSibling);
}
}
};
},
/**
* Called on chart render. Have to update the sections on render, in order
* to get a11y info from series.
*/
onChartRender: function () {
var component = this;
this.linkedDescriptionElement = this.getLinkedDescriptionElement();
this.setLinkedDescriptionAttrs();
Object.keys(this.screenReaderSections).forEach(function (regionKey) {
component.updateScreenReaderSection(regionKey);
});
},
/**
* @private
*/
getLinkedDescriptionElement: function () {
var chartOptions = this.chart.options, linkedDescOption = chartOptions.accessibility.linkedDescription;
if (!linkedDescOption) {
return;
}
if (typeof linkedDescOption !== 'string') {
return linkedDescOption;
}
var query = format(linkedDescOption, this.chart), queryMatch = doc.querySelectorAll(query);
if (queryMatch.length === 1) {
return queryMatch[0];
}
},
/**
* @private
*/
setLinkedDescriptionAttrs: function () {
var el = this.linkedDescriptionElement;
if (el) {
el.setAttribute('aria-hidden', 'true');
addClass(el, 'highcharts-linked-description');
}
},
/**
* @private
* @param {string} regionKey The name/key of the region to update
*/
updateScreenReaderSection: function (regionKey) {
var chart = this.chart, region = this.screenReaderSections[regionKey], content = region.buildContent(chart), sectionDiv = region.element = (region.element || this.createElement('div')), hiddenDiv = (sectionDiv.firstChild || this.createElement('div'));
this.setScreenReaderSectionAttribs(sectionDiv, regionKey);
hiddenDiv.innerHTML = content;
sectionDiv.appendChild(hiddenDiv);
region.insertIntoDOM(sectionDiv, chart);
visuallyHideElement(hiddenDiv);
unhideChartElementFromAT(chart, hiddenDiv);
if (region.afterInserted) {
region.afterInserted();
}
},
/**
* @private
* @param {Highcharts.HTMLDOMElement} sectionDiv The section element
* @param {string} regionKey Name/key of the region we are setting attrs for
*/
setScreenReaderSectionAttribs: function (sectionDiv, regionKey) {
var labelLangKey = ('accessibility.screenReaderSection.' + regionKey + 'RegionLabel'), chart = this.chart, labelText = chart.langFormat(labelLangKey, { chart: chart }), sectionId = 'highcharts-screen-reader-region-' + regionKey + '-' +
chart.index;
setElAttrs(sectionDiv, {
id: sectionId,
'aria-label': labelText
});
// Sections are wrapped to be positioned relatively to chart in case
// elements inside are tabbed to.
sectionDiv.style.position = 'relative';
if (chart.options.accessibility.landmarkVerbosity === 'all' &&
labelText) {
sectionDiv.setAttribute('role', 'region');
}
},
/**
* @private
* @return {string}
*/
defaultBeforeChartFormatter: function () {
var chart = this.chart, format = chart.options.accessibility
.screenReaderSection.beforeChartFormat, axesDesc = this.getAxesDescription(), sonifyButtonId = 'highcharts-a11y-sonify-data-btn-' +
chart.index, dataTableButtonId = 'hc-linkto-highcharts-data-table-' +
chart.index, annotationsList = getAnnotationsInfoHTML(chart), annotationsTitleStr = chart.langFormat('accessibility.screenReaderSection.annotations.heading', { chart: chart }), context = {
chartTitle: getChartTitle(chart),
typeDescription: this.getTypeDescriptionText(),
chartSubtitle: this.getSubtitleText(),
chartLongdesc: this.getLongdescText(),
xAxisDescription: axesDesc.xAxis,
yAxisDescription: axesDesc.yAxis,
playAsSoundButton: chart.sonify ?
this.getSonifyButtonText(sonifyButtonId) : '',
viewTableButton: chart.getCSV ?
this.getDataTableButtonText(dataTableButtonId) : '',
annotationsTitle: annotationsList ? annotationsTitleStr : '',
annotationsList: annotationsList
}, formattedString = H.i18nFormat(format, context, chart);
this.dataTableButtonId = dataTableButtonId;
this.sonifyButtonId = sonifyButtonId;
return stringToSimpleHTML(formattedString);
},
/**
* @private
* @return {string}
*/
defaultAfterChartFormatter: function () {
var chart = this.chart, format = chart.options.accessibility
.screenReaderSection.afterChartFormat, context = {
endOfChartMarker: this.getEndOfChartMarkerText()
}, formattedString = H.i18nFormat(format, context, chart);
return stringToSimpleHTML(formattedString);
},
/**
* @private
* @return {string}
*/
getLinkedDescription: function () {
var el = this.linkedDescriptionElement, content = el && el.innerHTML || '';
return stripHTMLTagsFromString(content);
},
/**
* @private
* @return {string}
*/
getLongdescText: function () {
var chartOptions = this.chart.options, captionOptions = chartOptions.caption, captionText = captionOptions && captionOptions.text, linkedDescription = this.getLinkedDescription();
return (chartOptions.accessibility.description ||
linkedDescription ||
captionText ||
'');
},
/**
* @private
* @return {string}
*/
getTypeDescriptionText: function () {
var chart = this.chart;
return chart.types ?
chart.options.accessibility.typeDescription ||
chart.getTypeDescription(chart.types) : '';
},
/**
* @private
* @param {string} buttonId
* @return {string}
*/
getDataTableButtonText: function (buttonId) {
var chart = this.chart, buttonText = chart.langFormat('accessibility.table.viewAsDataTableButtonText', { chart: chart, chartTitle: getChartTitle(chart) });
return '<a id="' + buttonId + '">' + buttonText + '</a>';
},
/**
* @private
* @param {string} buttonId
* @return {string}
*/
getSonifyButtonText: function (buttonId) {
var _a;
var chart = this.chart;
if (((_a = chart.options.sonification) === null || _a === void 0 ? void 0 : _a.enabled) === false) {
return '';
}
var buttonText = chart.langFormat('accessibility.sonification.playAsSoundButtonText', { chart: chart, chartTitle: getChartTitle(chart) });
return '<button id="' + buttonId + '">' + buttonText + '</button>';
},
/**
* @private
* @return {string}
*/
getSubtitleText: function () {
var subtitle = (this.chart.options.subtitle);
return stripHTMLTagsFromString(subtitle && subtitle.text || '');
},
/**
* @private
* @return {string}
*/
getEndOfChartMarkerText: function () {
var chart = this.chart, markerText = chart.langFormat('accessibility.screenReaderSection.endOfChartMarker', { chart: chart }), id = 'highcharts-end-of-chart-marker-' + chart.index;
return '<div id="' + id + '">' + markerText + '</div>';
},
/**
* @private
* @param {Highcharts.Dictionary<string>} e
*/
onDataTableCreated: function (e) {
var chart = this.chart;
if (chart.options.accessibility.enabled) {
if (this.viewDataTableButton) {
this.viewDataTableButton.setAttribute('aria-expanded', 'true');
}
e.html = e.html.replace('<table ', '<table tabindex="0" summary="' + getTableSummary(chart) + '"');
}
},
/**
* @private
*/
focusDataTable: function () {
var tableDiv = this.dataTableDiv, table = tableDiv && tableDiv.getElementsByTagName('table')[0];
if (table && table.focus) {
table.focus();
}
},
/**
* @private
* @param {string} sonifyButtonId
*/
initSonifyButton: function (sonifyButtonId) {
var _this = this;
var el = this.sonifyButton = getElement(sonifyButtonId);
var chart = this.chart;
var defaultHandler = function (e) {
el === null || el === void 0 ? void 0 : el.setAttribute('aria-hidden', 'true');
el === null || el === void 0 ? void 0 : el.setAttribute('aria-label', '');
e.preventDefault();
e.stopPropagation();
var announceMsg = chart.langFormat('accessibility.sonification.playAsSoundClickAnnouncement', { chart: chart });
_this.announcer.announce(announceMsg);
setTimeout(function () {
el === null || el === void 0 ? void 0 : el.removeAttribute('aria-hidden');
el === null || el === void 0 ? void 0 : el.removeAttribute('aria-label');
if (chart.sonify) {
chart.sonify();
}
}, 1000); // Delay to let screen reader speak the button press
};
if (el && chart) {
setElAttrs(el, {
tabindex: '-1'
});
el.onclick = function (e) {
var _a;
var onPlayAsSoundClick = (_a = chart.options.accessibility) === null || _a === void 0 ? void 0 : _a.screenReaderSection.onPlayAsSoundClick;
(onPlayAsSoundClick || defaultHandler).call(this, e, chart);
};
}
},
/**
* Set attribs and handlers for default viewAsDataTable button if exists.
* @private
* @param {string} tableButtonId
*/
initDataTableButton: function (tableButtonId) {
var el = this.viewDataTableButton = getElement(tableButtonId), chart = this.chart, tableId = tableButtonId.replace('hc-linkto-', '');
if (el) {
setElAttrs(el, {
role: 'button',
tabindex: '-1',
'aria-expanded': !!getElement(tableId),
href: '#' + tableId
});
el.onclick = chart.options.accessibility
.screenReaderSection.onViewDataTableClick ||
function () {
chart.viewData();
};
}
},
/**
* Return object with text description of each of the chart's axes.
* @private
* @return {Highcharts.Dictionary<string>}
*/
getAxesDescription: function () {
var chart = this.chart, shouldDescribeColl = function (collectionKey, defaultCondition) {
var axes = chart[collectionKey];
return axes.length > 1 || axes[0] &&
pick(axes[0].options.accessibility &&
axes[0].options.accessibility.enabled, defaultCondition);
}, hasNoMap = !!chart.types && chart.types.indexOf('map') < 0, hasCartesian = !!chart.hasCartesianSeries, showXAxes = shouldDescribeColl('xAxis', !chart.angular && hasCartesian && hasNoMap), showYAxes = shouldDescribeColl('yAxis', hasCartesian && hasNoMap), desc = {};
if (showXAxes) {
desc.xAxis = this.getAxisDescriptionText('xAxis');
}
if (showYAxes) {
desc.yAxis = this.getAxisDescriptionText('yAxis');
}
return desc;
},
/**
* @private
* @param {string} collectionKey
* @return {string}
*/
getAxisDescriptionText: function (collectionKey) {
var component = this, chart = this.chart, axes = chart[collectionKey];
return chart.langFormat('accessibility.axis.' + collectionKey + 'Description' + (axes.length > 1 ? 'Plural' : 'Singular'), {
chart: chart,
names: axes.map(function (axis) {
return getAxisDescription(axis);
}),
ranges: axes.map(function (axis) {
return component.getAxisRangeDescription(axis);
}),
numAxes: axes.length
});
},
/**
* Return string with text description of the axis range.
* @private
* @param {Highcharts.Axis} axis The axis to get range desc of.
* @return {string} A string with the range description for the axis.
*/
getAxisRangeDescription: function (axis) {
var axisOptions = axis.options || {};
// Handle overridden range description
if (axisOptions.accessibility &&
typeof axisOptions.accessibility.rangeDescription !== 'undefined') {
return axisOptions.accessibility.rangeDescription;
}
// Handle category axes
if (axis.categories) {
return this.getCategoryAxisRangeDesc(axis);
}
// Use time range, not from-to?
if (axis.isDatetimeAxis && (axis.min === 0 || axis.dataMin === 0)) {
return this.getAxisTimeLengthDesc(axis);
}
// Just use from and to.
// We have the range and the unit to use, find the desc format
return this.getAxisFromToDescription(axis);
},
/**
* @private
* @param {Highcharts.Axis} axis
* @return {string}
*/
getCategoryAxisRangeDesc: function (axis) {
var chart = this.chart;
if (axis.dataMax && axis.dataMin) {
return chart.langFormat('accessibility.axis.rangeCategories', {
chart: chart,
axis: axis,
numCategories: axis.dataMax - axis.dataMin + 1
});
}
return '';
},
/**
* @private
* @param {Highcharts.Axis} axis
* @return {string}
*/
getAxisTimeLengthDesc: function (axis) {
var chart = this.chart, range = {}, rangeUnit = 'Seconds';
range.Seconds = ((axis.max || 0) - (axis.min || 0)) / 1000;
range.Minutes = range.Seconds / 60;
range.Hours = range.Minutes / 60;
range.Days = range.Hours / 24;
['Minutes', 'Hours', 'Days'].forEach(function (unit) {
if (range[unit] > 2) {
rangeUnit = unit;
}
});
var rangeValue = range[rangeUnit].toFixed(rangeUnit !== 'Seconds' &&
rangeUnit !== 'Minutes' ? 1 : 0 // Use decimals for days/hours
);
// We have the range and the unit to use, find the desc format
return chart.langFormat('accessibility.axis.timeRange' + rangeUnit, {
chart: chart,
axis: axis,
range: rangeValue.replace('.0', '')
});
},
/**
* @private
* @param {Highcharts.Axis} axis
* @return {string}
*/
getAxisFromToDescription: function (axis) {
var chart = this.chart, dateRangeFormat = chart.options.accessibility
.screenReaderSection.axisRangeDateFormat, format = function (axisKey) {
return axis.isDatetimeAxis ? chart.time.dateFormat(dateRangeFormat, axis[axisKey]) : axis[axisKey];
};
return chart.langFormat('accessibility.axis.rangeFromTo', {
chart: chart,
axis: axis,
rangeFrom: format('min'),
rangeTo: format('max')
});
},
/**
* Remove component traces
*/
destroy: function () {
var _a;
(_a = this.announcer) === null || _a === void 0 ? void 0 : _a.destroy();
}
});
export default InfoRegionsComponent;

View File

@@ -0,0 +1,80 @@
/* *
*
* (c) 2009-2019 Øystein Moseng
*
* Annotations accessibility code.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
/**
* Describe an annotation label.
*
* @private
* @param {object} label The annotation label object to describe
* @return {string} The description for the label.
*/
function getAnnotationLabelDescription(label) {
var _a, _b;
var chart = label.chart;
var labelText = ((_b = (_a = label.graphic) === null || _a === void 0 ? void 0 : _a.text) === null || _b === void 0 ? void 0 : _b.textStr) || '';
var points = label.points;
var getAriaLabel = function (point) { var _a, _b, _c; return ((_c = (_b = (_a = point) === null || _a === void 0 ? void 0 : _a.graphic) === null || _b === void 0 ? void 0 : _b.element) === null || _c === void 0 ? void 0 : _c.getAttribute('aria-label')) || ''; };
var ariaLabels = points.map(getAriaLabel)
.filter(function (label) { return !!label; });
var numPoints = ariaLabels.length;
var pointsSelector = numPoints > 1 ? 'MultiplePoints' : numPoints ? 'SinglePoint' : 'NoPoints';
var langFormatStr = 'accessibility.screenReaderSection.annotations.description' + pointsSelector;
var context = {
annotationText: labelText,
numPoints: numPoints,
annotationPoints: ariaLabels,
annotationPoint: ariaLabels[0]
};
return chart.langFormat(langFormatStr, context);
}
/**
* Return array of HTML strings for each annotation label in the chart.
*
* @private
* @param {Highcharts.Chart} chart The chart to get annotation info on.
* @return {Array<string>} Array of strings with HTML content for each annotation label.
*/
function getAnnotationItems(chart) {
var annotations = chart.annotations || [];
var labels = annotations.reduce(function (acc, cur) {
var _a;
if (((_a = cur.options) === null || _a === void 0 ? void 0 : _a.visible) !== false) {
acc = acc.concat(cur.labels);
}
return acc;
}, []);
return labels.map(function (label) {
var desc = getAnnotationLabelDescription(label);
return desc ? "<li>" + desc + "</li>" : '';
});
}
/**
* Return the annotation info for a chart as string.
*
* @private
* @param {Highcharts.Chart} chart The chart to get annotation info on.
* @return {string} String with HTML content or empty string if no annotations.
*/
function getAnnotationsInfoHTML(chart) {
var annotations = chart.annotations;
if (!(annotations && annotations.length)) {
return '';
}
var annotationItems = getAnnotationItems(chart);
return "<ul>" + annotationItems.join(' ') + "</ul>";
}
var AnnotationsA11y = {
getAnnotationsInfoHTML: getAnnotationsInfoHTML,
getAnnotationItems: getAnnotationItems,
getAnnotationLabelDescription: getAnnotationLabelDescription
};
export default AnnotationsA11y;

View File

@@ -0,0 +1,499 @@
/* *
*
* (c) 2009-2019 Øystein Moseng
*
* Accessibility component for chart info region and table.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../../../parts/Globals.js';
var doc = H.win.document, format = H.format;
import U from '../../../../parts/Utilities.js';
var extend = U.extend, pick = U.pick;
import AccessibilityComponent from '../../AccessibilityComponent.js';
import AnnotationsA11y from '../AnnotationsA11y.js';
var getAnnotationsInfoHTML = AnnotationsA11y.getAnnotationsInfoHTML;
import ChartUtilities from '../../utils/chartUtilities.js';
var unhideChartElementFromAT = ChartUtilities.unhideChartElementFromAT, getChartTitle = ChartUtilities.getChartTitle, getAxisDescription = ChartUtilities.getAxisDescription;
import HTMLUtilities from '../../utils/htmlUtilities.js';
var addClass = HTMLUtilities.addClass, setElAttrs = HTMLUtilities.setElAttrs, escapeStringForHTML = HTMLUtilities.escapeStringForHTML, stripHTMLTagsFromString = HTMLUtilities.stripHTMLTagsFromString, getElement = HTMLUtilities.getElement, visuallyHideElement = HTMLUtilities.visuallyHideElement;
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* @private
*/
function getTypeDescForMapChart(chart, formatContext) {
return formatContext.mapTitle ?
chart.langFormat('accessibility.chartTypes.mapTypeDescription', formatContext) :
chart.langFormat('accessibility.chartTypes.unknownMap', formatContext);
}
/**
* @private
*/
function getTypeDescForCombinationChart(chart, formatContext) {
return chart.langFormat('accessibility.chartTypes.combinationChart', formatContext);
}
/**
* @private
*/
function getTypeDescForEmptyChart(chart, formatContext) {
return chart.langFormat('accessibility.chartTypes.emptyChart', formatContext);
}
/**
* @private
*/
function buildTypeDescriptionFromSeries(chart, types, context) {
var firstType = types[0], typeExplaination = chart.langFormat('accessibility.seriesTypeDescriptions.' + firstType, context), multi = chart.series && chart.series.length < 2 ? 'Single' : 'Multiple';
return (chart.langFormat('accessibility.chartTypes.' + firstType + multi, context) ||
chart.langFormat('accessibility.chartTypes.default' + multi, context)) + (typeExplaination ? ' ' + typeExplaination : '');
}
/**
* @private
*/
function getTableSummary(chart) {
return chart.langFormat('accessibility.table.tableSummary', { chart: chart });
}
/**
* @private
*/
function stripEmptyHTMLTags(str) {
return str.replace(/<(\w+)[^>]*?>\s*<\/\1>/g, '');
}
/**
* @private
*/
function enableSimpleHTML(str) {
return str
.replace(/&lt;(h[1-7]|p|div|ul|ol|li)&gt;/g, '<$1>')
.replace(/&lt;&#x2F;(h[1-7]|p|div|ul|ol|li|a|button)&gt;/g, '</$1>')
.replace(/&lt;(div|a|button) id=&quot;([a-zA-Z\-0-9#]*?)&quot;&gt;/g, '<$1 id="$2">');
}
/**
* @private
*/
function stringToSimpleHTML(str) {
return stripEmptyHTMLTags(enableSimpleHTML(escapeStringForHTML(str)));
}
/**
* Return simplified explaination of chart type. Some types will not be familiar
* to most users, but in those cases we try to add an explaination of the type.
*
* @private
* @function Highcharts.Chart#getTypeDescription
* @param {Array<string>} types The series types in this chart.
* @return {string} The text description of the chart type.
*/
H.Chart.prototype.getTypeDescription = function (types) {
var firstType = types[0], firstSeries = this.series && this.series[0] || {}, formatContext = {
numSeries: this.series.length,
numPoints: firstSeries.points && firstSeries.points.length,
chart: this,
mapTitle: firstSeries.mapTitle
};
if (!firstType) {
return getTypeDescForEmptyChart(this, formatContext);
}
if (firstType === 'map') {
return getTypeDescForMapChart(this, formatContext);
}
if (this.types.length > 1) {
return getTypeDescForCombinationChart(this, formatContext);
}
return buildTypeDescriptionFromSeries(this, types, formatContext);
};
/**
* The InfoRegionsComponent class
*
* @private
* @class
* @name Highcharts.InfoRegionsComponent
*/
var InfoRegionsComponent = function () { };
InfoRegionsComponent.prototype = new AccessibilityComponent();
extend(InfoRegionsComponent.prototype, /** @lends Highcharts.InfoRegionsComponent */ {
/**
* Init the component
* @private
*/
init: function () {
var chart = this.chart, component = this;
this.initRegionsDefinitions();
this.addEvent(chart, 'afterGetTable', function (e) {
component.onDataTableCreated(e);
});
this.addEvent(chart, 'afterViewData', function (tableDiv) {
component.dataTableDiv = tableDiv;
// Use small delay to give browsers & AT time to register new table
setTimeout(function () {
component.focusDataTable();
}, 300);
});
},
/**
* @private
*/
initRegionsDefinitions: function () {
var component = this;
this.screenReaderSections = {
before: {
element: null,
buildContent: function (chart) {
var formatter = chart.options.accessibility
.screenReaderSection.beforeChartFormatter;
return formatter ? formatter(chart) :
component.defaultBeforeChartFormatter(chart);
},
insertIntoDOM: function (el, chart) {
chart.renderTo.insertBefore(el, chart.renderTo.firstChild);
},
afterInserted: function () {
if (typeof component.dataTableButtonId !== 'undefined') {
component.initDataTableButton(component.dataTableButtonId);
}
}
},
after: {
element: null,
buildContent: function (chart) {
var formatter = chart.options.accessibility.screenReaderSection
.afterChartFormatter;
return formatter ? formatter(chart) :
component.defaultAfterChartFormatter();
},
insertIntoDOM: function (el, chart) {
chart.renderTo.insertBefore(el, chart.container.nextSibling);
}
}
};
},
/**
* Called on chart render. Have to update the sections on render, in order
* to get a11y info from series.
*/
onChartRender: function () {
var component = this;
this.linkedDescriptionElement = this.getLinkedDescriptionElement();
this.setLinkedDescriptionAttrs();
Object.keys(this.screenReaderSections).forEach(function (regionKey) {
component.updateScreenReaderSection(regionKey);
});
},
/**
* @private
*/
getLinkedDescriptionElement: function () {
var chartOptions = this.chart.options, linkedDescOption = chartOptions.accessibility.linkedDescription;
if (!linkedDescOption) {
return;
}
if (typeof linkedDescOption !== 'string') {
return linkedDescOption;
}
var query = format(linkedDescOption, this.chart), queryMatch = doc.querySelectorAll(query);
if (queryMatch.length === 1) {
return queryMatch[0];
}
},
/**
* @private
*/
setLinkedDescriptionAttrs: function () {
var el = this.linkedDescriptionElement;
if (el) {
el.setAttribute('aria-hidden', 'true');
addClass(el, 'highcharts-linked-description');
}
},
/**
* @private
* @param {string} regionKey The name/key of the region to update
*/
updateScreenReaderSection: function (regionKey) {
var chart = this.chart, region = this.screenReaderSections[regionKey], content = region.buildContent(chart), sectionDiv = region.element = (region.element || this.createElement('div')), hiddenDiv = (sectionDiv.firstChild || this.createElement('div'));
this.setScreenReaderSectionAttribs(sectionDiv, regionKey);
hiddenDiv.innerHTML = content;
sectionDiv.appendChild(hiddenDiv);
region.insertIntoDOM(sectionDiv, chart);
visuallyHideElement(hiddenDiv);
unhideChartElementFromAT(chart, hiddenDiv);
if (region.afterInserted) {
region.afterInserted();
}
},
/**
* @private
* @param {Highcharts.HTMLDOMElement} sectionDiv The section element
* @param {string} regionKey Name/key of the region we are setting attrs for
*/
setScreenReaderSectionAttribs: function (sectionDiv, regionKey) {
var labelLangKey = ('accessibility.screenReaderSection.' + regionKey + 'RegionLabel'), chart = this.chart, labelText = chart.langFormat(labelLangKey, { chart: chart }), sectionId = 'highcharts-screen-reader-region-' + regionKey + '-' +
chart.index;
setElAttrs(sectionDiv, {
id: sectionId,
'aria-label': labelText
});
// Sections are wrapped to be positioned relatively to chart in case
// elements inside are tabbed to.
sectionDiv.style.position = 'relative';
if (chart.options.accessibility.landmarkVerbosity === 'all' &&
labelText) {
sectionDiv.setAttribute('role', 'region');
}
},
/**
* @private
* @return {string}
*/
defaultBeforeChartFormatter: function () {
var chart = this.chart, format = chart.options.accessibility
.screenReaderSection.beforeChartFormat, axesDesc = this.getAxesDescription(), dataTableButtonId = 'hc-linkto-highcharts-data-table-' +
chart.index, annotationsTitleStr = chart.langFormat('accessibility.screenReaderSection.annotations.heading', { chart: chart }), context = {
chartTitle: getChartTitle(chart),
typeDescription: this.getTypeDescriptionText(),
chartSubtitle: this.getSubtitleText(),
chartLongdesc: this.getLongdescText(),
xAxisDescription: axesDesc.xAxis,
yAxisDescription: axesDesc.yAxis,
viewTableButton: chart.getCSV ?
this.getDataTableButtonText(dataTableButtonId) : '',
annotationsTitle: annotationsTitleStr,
annotationsList: getAnnotationsInfoHTML(chart)
}, formattedString = H.i18nFormat(format, context, chart);
this.dataTableButtonId = dataTableButtonId;
return stringToSimpleHTML(formattedString);
},
/**
* @private
* @return {string}
*/
defaultAfterChartFormatter: function () {
var chart = this.chart, format = chart.options.accessibility
.screenReaderSection.afterChartFormat, context = {
endOfChartMarker: this.getEndOfChartMarkerText()
}, formattedString = H.i18nFormat(format, context, chart);
return stringToSimpleHTML(formattedString);
},
/**
* @private
* @return {string}
*/
getLinkedDescription: function () {
var el = this.linkedDescriptionElement, content = el && el.innerHTML || '';
return stripHTMLTagsFromString(content);
},
/**
* @private
* @return {string}
*/
getLongdescText: function () {
var chartOptions = this.chart.options, captionOptions = chartOptions.caption, captionText = captionOptions && captionOptions.text, linkedDescription = this.getLinkedDescription();
return (chartOptions.accessibility.description ||
linkedDescription ||
captionText ||
'');
},
/**
* @private
* @return {string}
*/
getTypeDescriptionText: function () {
var chart = this.chart;
return chart.types ?
chart.options.accessibility.typeDescription ||
chart.getTypeDescription(chart.types) : '';
},
/**
* @private
* @param {string} buttonId
* @return {string}
*/
getDataTableButtonText: function (buttonId) {
var chart = this.chart, buttonText = chart.langFormat('accessibility.table.viewAsDataTableButtonText', { chart: chart, chartTitle: getChartTitle(chart) });
return '<a id="' + buttonId + '">' + buttonText + '</a>';
},
/**
* @private
* @return {string}
*/
getSubtitleText: function () {
var subtitle = (this.chart.options.subtitle);
return stripHTMLTagsFromString(subtitle && subtitle.text || '');
},
/**
* @private
* @return {string}
*/
getEndOfChartMarkerText: function () {
var chart = this.chart, markerText = chart.langFormat('accessibility.screenReaderSection.endOfChartMarker', { chart: chart }), id = 'highcharts-end-of-chart-marker-' + chart.index;
return '<div id="' + id + '">' + markerText + '</div>';
},
/**
* @private
* @param {Highcharts.Dictionary<string>} e
*/
onDataTableCreated: function (e) {
var chart = this.chart;
if (chart.options.accessibility.enabled) {
if (this.viewDataTableButton) {
this.viewDataTableButton.setAttribute('aria-expanded', 'true');
}
e.html = e.html.replace('<table ', '<table tabindex="0" summary="' + getTableSummary(chart) + '"');
}
},
/**
* @private
*/
focusDataTable: function () {
var tableDiv = this.dataTableDiv, table = tableDiv && tableDiv.getElementsByTagName('table')[0];
if (table && table.focus) {
table.focus();
}
},
/**
* Set attribs and handlers for default viewAsDataTable button if exists.
* @private
* @param {string} tableButtonId
*/
initDataTableButton: function (tableButtonId) {
var el = this.viewDataTableButton = getElement(tableButtonId), chart = this.chart, tableId = tableButtonId.replace('hc-linkto-', '');
if (el) {
setElAttrs(el, {
role: 'button',
tabindex: '-1',
'aria-expanded': !!getElement(tableId),
href: '#' + tableId
});
el.onclick = chart.options.accessibility
.screenReaderSection.onViewDataTableClick ||
function () {
chart.viewData();
};
}
},
/**
* Return object with text description of each of the chart's axes.
* @private
* @return {Highcharts.Dictionary<string>}
*/
getAxesDescription: function () {
var chart = this.chart, shouldDescribeColl = function (collectionKey, defaultCondition) {
var axes = chart[collectionKey];
return axes.length > 1 || axes[0] &&
pick(axes[0].options.accessibility &&
axes[0].options.accessibility.enabled, defaultCondition);
}, hasNoMap = !!chart.types && chart.types.indexOf('map') < 0, hasCartesian = !!chart.hasCartesianSeries, showXAxes = shouldDescribeColl('xAxis', !chart.angular && hasCartesian && hasNoMap), showYAxes = shouldDescribeColl('yAxis', hasCartesian && hasNoMap), desc = {};
if (showXAxes) {
desc.xAxis = this.getAxisDescriptionText('xAxis');
}
if (showYAxes) {
desc.yAxis = this.getAxisDescriptionText('yAxis');
}
return desc;
},
/**
* @private
* @param {string} collectionKey
* @return {string}
*/
getAxisDescriptionText: function (collectionKey) {
var component = this, chart = this.chart, axes = chart[collectionKey];
return chart.langFormat('accessibility.axis.' + collectionKey + 'Description' + (axes.length > 1 ? 'Plural' : 'Singular'), {
chart: chart,
names: axes.map(function (axis) {
return getAxisDescription(axis);
}),
ranges: axes.map(function (axis) {
return component.getAxisRangeDescription(axis);
}),
numAxes: axes.length
});
},
/**
* Return string with text description of the axis range.
* @private
* @param {Highcharts.Axis} axis The axis to get range desc of.
* @return {string} A string with the range description for the axis.
*/
getAxisRangeDescription: function (axis) {
var axisOptions = axis.options || {};
// Handle overridden range description
if (axisOptions.accessibility &&
typeof axisOptions.accessibility.rangeDescription !== 'undefined') {
return axisOptions.accessibility.rangeDescription;
}
// Handle category axes
if (axis.categories) {
return this.getCategoryAxisRangeDesc(axis);
}
// Use time range, not from-to?
if (axis.isDatetimeAxis && (axis.min === 0 || axis.dataMin === 0)) {
return this.getAxisTimeLengthDesc(axis);
}
// Just use from and to.
// We have the range and the unit to use, find the desc format
return this.getAxisFromToDescription(axis);
},
/**
* @private
* @param {Highcharts.Axis} axis
* @return {string}
*/
getCategoryAxisRangeDesc: function (axis) {
var chart = this.chart;
if (axis.dataMax && axis.dataMin) {
return chart.langFormat('accessibility.axis.rangeCategories', {
chart: chart,
axis: axis,
numCategories: axis.dataMax - axis.dataMin + 1
});
}
return '';
},
/**
* @private
* @param {Highcharts.Axis} axis
* @return {string}
*/
getAxisTimeLengthDesc: function (axis) {
var chart = this.chart, range = {}, rangeUnit = 'Seconds';
range.Seconds = ((axis.max || 0) - (axis.min || 0)) / 1000;
range.Minutes = range.Seconds / 60;
range.Hours = range.Minutes / 60;
range.Days = range.Hours / 24;
['Minutes', 'Hours', 'Days'].forEach(function (unit) {
if (range[unit] > 2) {
rangeUnit = unit;
}
});
var rangeValue = range[rangeUnit].toFixed(rangeUnit !== 'Seconds' &&
rangeUnit !== 'Minutes' ? 1 : 0 // Use decimals for days/hours
);
// We have the range and the unit to use, find the desc format
return chart.langFormat('accessibility.axis.timeRange' + rangeUnit, {
chart: chart,
axis: axis,
range: rangeValue.replace('.0', '')
});
},
/**
* @private
* @param {Highcharts.Axis} axis
* @return {string}
*/
getAxisFromToDescription: function (axis) {
var chart = this.chart, dateRangeFormat = chart.options.accessibility
.screenReaderSection.axisRangeDateFormat, format = function (axisKey) {
return axis.isDatetimeAxis ? chart.time.dateFormat(dateRangeFormat, axis[axisKey]) : axis[axisKey];
};
return chart.langFormat('accessibility.axis.rangeFromTo', {
chart: chart,
axis: axis,
rangeFrom: format('min'),
rangeTo: format('max')
});
}
});
export default InfoRegionsComponent;

View File

@@ -0,0 +1,262 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Accessibility component for chart legend.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../../parts/Globals.js';
import Legend from '../../../parts/Legend.js';
import U from '../../../parts/Utilities.js';
var addEvent = U.addEvent, extend = U.extend, fireEvent = U.fireEvent;
import AccessibilityComponent from '../AccessibilityComponent.js';
import KeyboardNavigationHandler from '../KeyboardNavigationHandler.js';
import HTMLUtilities from '../utils/htmlUtilities.js';
var stripHTMLTags = HTMLUtilities.stripHTMLTagsFromString, removeElement = HTMLUtilities.removeElement;
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* @private
*/
function scrollLegendToItem(legend, itemIx) {
var itemPage = legend.allItems[itemIx].pageIx, curPage = legend.currentPage;
if (typeof itemPage !== 'undefined' && itemPage + 1 !== curPage) {
legend.scroll(1 + itemPage - curPage);
}
}
/**
* @private
*/
function shouldDoLegendA11y(chart) {
var items = chart.legend && chart.legend.allItems, legendA11yOptions = (chart.options.legend.accessibility || {});
return !!(items && items.length &&
!(chart.colorAxis && chart.colorAxis.length) &&
legendA11yOptions.enabled !== false);
}
/**
* Highlight legend item by index.
*
* @private
* @function Highcharts.Chart#highlightLegendItem
*
* @param {number} ix
*
* @return {boolean}
*/
H.Chart.prototype.highlightLegendItem = function (ix) {
var items = this.legend.allItems, oldIx = this.highlightedLegendItemIx;
if (items[ix]) {
if (items[oldIx]) {
fireEvent(items[oldIx].legendGroup.element, 'mouseout');
}
scrollLegendToItem(this.legend, ix);
this.setFocusToElement(items[ix].legendItem, items[ix].a11yProxyElement);
fireEvent(items[ix].legendGroup.element, 'mouseover');
return true;
}
return false;
};
// Keep track of pressed state for legend items
addEvent(Legend, 'afterColorizeItem', function (e) {
var chart = this.chart, a11yOptions = chart.options.accessibility, legendItem = e.item;
if (a11yOptions.enabled && legendItem && legendItem.a11yProxyElement) {
legendItem.a11yProxyElement.setAttribute('aria-pressed', e.visible ? 'false' : 'true');
}
});
/**
* The LegendComponent class
*
* @private
* @class
* @name Highcharts.LegendComponent
*/
var LegendComponent = function () { };
LegendComponent.prototype = new AccessibilityComponent();
extend(LegendComponent.prototype, /** @lends Highcharts.LegendComponent */ {
/**
* Init the component
* @private
*/
init: function () {
var component = this;
this.addEvent(Legend, 'afterScroll', function () {
if (this.chart === component.chart) {
component.updateProxies();
}
});
},
/**
* @private
*/
updateLegendItemProxyVisibility: function () {
var legend = this.chart.legend, items = legend.allItems || [], curPage = legend.currentPage || 1;
items.forEach(function (item) {
var itemPage = item.pageIx || 0, hide = itemPage !== curPage - 1;
if (item.a11yProxyElement) {
item.a11yProxyElement.style.visibility = hide ?
'hidden' : 'visible';
}
});
},
/**
* The legend needs updates on every render, in order to update positioning
* of the proxy overlays.
*/
onChartRender: function () {
var component = this;
// Ignore render after proxy clicked. No need to destroy it, and
// destroying also kills focus.
if (this.legendProxyButtonClicked) {
delete component.legendProxyButtonClicked;
return;
}
this.updateProxies();
},
/**
* @private
*/
updateProxies: function () {
removeElement(this.legendProxyGroup);
if (shouldDoLegendA11y(this.chart)) {
this.addLegendProxyGroup();
this.proxyLegendItems();
this.updateLegendItemProxyVisibility();
}
},
/**
* @private
*/
addLegendProxyGroup: function () {
var a11yOptions = this.chart.options.accessibility, groupLabel = this.chart.langFormat('accessibility.legend.legendLabel', {}), groupRole = a11yOptions.landmarkVerbosity === 'all' ?
'region' : null;
this.legendProxyGroup = this.addProxyGroup({
'aria-label': groupLabel,
'role': groupRole
});
},
/**
* @private
*/
proxyLegendItems: function () {
var component = this, items = (this.chart.legend &&
this.chart.legend.allItems || []);
items.forEach(function (item) {
if (item.legendItem && item.legendItem.element) {
component.proxyLegendItem(item);
}
});
},
/**
* @private
* @param {Highcharts.BubbleLegend|Highcharts.Point|Highcharts.Series} item
*/
proxyLegendItem: function (item) {
var component = this, itemLabel = this.chart.langFormat('accessibility.legend.legendItem', {
chart: this.chart,
itemName: stripHTMLTags(item.name)
}), attribs = {
tabindex: -1,
'aria-pressed': !item.visible,
'aria-label': itemLabel
},
// Keep track of when we should ignore next render
preClickEvent = function () {
component.legendProxyButtonClicked = true;
},
// Considers useHTML
proxyPositioningElement = item.legendGroup.div ?
item.legendItem : item.legendGroup;
item.a11yProxyElement = this.createProxyButton(item.legendItem, this.legendProxyGroup, attribs, proxyPositioningElement, preClickEvent);
},
/**
* Get keyboard navigation handler for this component.
* @return {Highcharts.KeyboardNavigationHandler}
*/
getKeyboardNavigation: function () {
var keys = this.keyCodes, component = this, chart = this.chart;
return new KeyboardNavigationHandler(chart, {
keyCodeMap: [
[
[keys.left, keys.right, keys.up, keys.down],
function (keyCode) {
return component.onKbdArrowKey(this, keyCode);
}
],
[
[keys.enter, keys.space],
function () {
return component.onKbdClick(this);
}
]
],
validate: function () {
return component.shouldHaveLegendNavigation();
},
init: function (direction) {
return component.onKbdNavigationInit(direction);
}
});
},
/**
* @private
* @param {Highcharts.KeyboardNavigationHandler} keyboardNavigationHandler
* @param {number} keyCode
* @return {number}
* Response code
*/
onKbdArrowKey: function (keyboardNavigationHandler, keyCode) {
var keys = this.keyCodes, response = keyboardNavigationHandler.response, chart = this.chart, a11yOptions = chart.options.accessibility, numItems = chart.legend.allItems.length, direction = (keyCode === keys.left || keyCode === keys.up) ? -1 : 1;
var res = chart.highlightLegendItem(this.highlightedLegendItemIx + direction);
if (res) {
this.highlightedLegendItemIx += direction;
return response.success;
}
if (numItems > 1 &&
a11yOptions.keyboardNavigation.wrapAround) {
keyboardNavigationHandler.init(direction);
return response.success;
}
// No wrap, move
return response[direction > 0 ? 'next' : 'prev'];
},
/**
* @private
* @param {Highcharts.KeyboardNavigationHandler} keyboardNavigationHandler
* @return {number}
* Response code
*/
onKbdClick: function (keyboardNavigationHandler) {
var legendItem = this.chart.legend.allItems[this.highlightedLegendItemIx];
if (legendItem && legendItem.a11yProxyElement) {
fireEvent(legendItem.a11yProxyElement, 'click');
}
return keyboardNavigationHandler.response.success;
},
/**
* @private
* @return {boolean|undefined}
*/
shouldHaveLegendNavigation: function () {
var chart = this.chart, legendOptions = chart.options.legend || {}, hasLegend = chart.legend && chart.legend.allItems, hasColorAxis = chart.colorAxis && chart.colorAxis.length, legendA11yOptions = (legendOptions.accessibility || {});
return !!(hasLegend &&
chart.legend.display &&
!hasColorAxis &&
legendA11yOptions.enabled &&
legendA11yOptions.keyboardNavigation &&
legendA11yOptions.keyboardNavigation.enabled);
},
/**
* @private
* @param {number} direction
*/
onKbdNavigationInit: function (direction) {
var chart = this.chart, lastIx = chart.legend.allItems.length - 1, ixToHighlight = direction > 0 ? 0 : lastIx;
chart.highlightLegendItem(ixToHighlight);
this.highlightedLegendItemIx = ixToHighlight;
}
});
export default LegendComponent;

View File

@@ -0,0 +1,356 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Accessibility component for exporting menu.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../../parts/Globals.js';
import U from '../../../parts/Utilities.js';
var extend = U.extend;
import AccessibilityComponent from '../AccessibilityComponent.js';
import KeyboardNavigationHandler from '../KeyboardNavigationHandler.js';
import ChartUtilities from '../utils/chartUtilities.js';
var unhideChartElementFromAT = ChartUtilities.unhideChartElementFromAT;
import HTMLUtilities from '../utils/htmlUtilities.js';
var removeElement = HTMLUtilities.removeElement, getFakeMouseEvent = HTMLUtilities.getFakeMouseEvent;
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* Get the wrapped export button element of a chart.
*
* @private
* @param {Highcharts.Chart} chart
* @returns {Highcharts.SVGElement}
*/
function getExportMenuButtonElement(chart) {
return chart.exportSVGElements && chart.exportSVGElements[0];
}
/**
* Show the export menu and focus the first item (if exists).
*
* @private
* @function Highcharts.Chart#showExportMenu
*/
H.Chart.prototype.showExportMenu = function () {
var exportButton = getExportMenuButtonElement(this);
if (exportButton) {
var el = exportButton.element;
if (el.onclick) {
el.onclick(getFakeMouseEvent('click'));
}
}
};
/**
* @private
* @function Highcharts.Chart#hideExportMenu
*/
H.Chart.prototype.hideExportMenu = function () {
var chart = this, exportList = chart.exportDivElements;
if (exportList && chart.exportContextMenu) {
// Reset hover states etc.
exportList.forEach(function (el) {
if (el.className === 'highcharts-menu-item' && el.onmouseout) {
el.onmouseout(getFakeMouseEvent('mouseout'));
}
});
chart.highlightedExportItemIx = 0;
// Hide the menu div
chart.exportContextMenu.hideMenu();
// Make sure the chart has focus and can capture keyboard events
chart.container.focus();
}
};
/**
* Highlight export menu item by index.
*
* @private
* @function Highcharts.Chart#highlightExportItem
*
* @param {number} ix
*
* @return {boolean}
*/
H.Chart.prototype.highlightExportItem = function (ix) {
var listItem = this.exportDivElements && this.exportDivElements[ix], curHighlighted = this.exportDivElements &&
this.exportDivElements[this.highlightedExportItemIx], hasSVGFocusSupport;
if (listItem &&
listItem.tagName === 'LI' &&
!(listItem.children && listItem.children.length)) {
// Test if we have focus support for SVG elements
hasSVGFocusSupport = !!(this.renderTo.getElementsByTagName('g')[0] || {}).focus;
// Only focus if we can set focus back to the elements after
// destroying the menu (#7422)
if (listItem.focus && hasSVGFocusSupport) {
listItem.focus();
}
if (curHighlighted && curHighlighted.onmouseout) {
curHighlighted.onmouseout(getFakeMouseEvent('mouseout'));
}
if (listItem.onmouseover) {
listItem.onmouseover(getFakeMouseEvent('mouseover'));
}
this.highlightedExportItemIx = ix;
return true;
}
return false;
};
/**
* Try to highlight the last valid export menu item.
*
* @private
* @function Highcharts.Chart#highlightLastExportItem
* @return {boolean}
*/
H.Chart.prototype.highlightLastExportItem = function () {
var chart = this, i;
if (chart.exportDivElements) {
i = chart.exportDivElements.length;
while (i--) {
if (chart.highlightExportItem(i)) {
return true;
}
}
}
return false;
};
/**
* @private
* @param {Highcharts.Chart} chart
*/
function exportingShouldHaveA11y(chart) {
var exportingOpts = chart.options.exporting, exportButton = getExportMenuButtonElement(chart);
return !!(exportingOpts &&
exportingOpts.enabled !== false &&
exportingOpts.accessibility &&
exportingOpts.accessibility.enabled &&
exportButton &&
exportButton.element);
}
/**
* The MenuComponent class
*
* @private
* @class
* @name Highcharts.MenuComponent
*/
var MenuComponent = function () { };
MenuComponent.prototype = new AccessibilityComponent();
extend(MenuComponent.prototype, /** @lends Highcharts.MenuComponent */ {
/**
* Init the component
*/
init: function () {
var chart = this.chart, component = this;
this.addEvent(chart, 'exportMenuShown', function () {
component.onMenuShown();
});
this.addEvent(chart, 'exportMenuHidden', function () {
component.onMenuHidden();
});
},
/**
* @private
*/
onMenuHidden: function () {
var menu = this.chart.exportContextMenu;
if (menu) {
menu.setAttribute('aria-hidden', 'true');
}
this.isExportMenuShown = false;
this.setExportButtonExpandedState('false');
},
/**
* @private
*/
onMenuShown: function () {
var chart = this.chart, menu = chart.exportContextMenu;
if (menu) {
this.addAccessibleContextMenuAttribs();
unhideChartElementFromAT(chart, menu);
}
this.isExportMenuShown = true;
this.setExportButtonExpandedState('true');
},
/**
* @private
* @param {string} stateStr
*/
setExportButtonExpandedState: function (stateStr) {
var button = this.exportButtonProxy;
if (button) {
button.setAttribute('aria-expanded', stateStr);
}
},
/**
* Called on each render of the chart. We need to update positioning of the
* proxy overlay.
*/
onChartRender: function () {
var chart = this.chart, a11yOptions = chart.options.accessibility;
// Always start with a clean slate
removeElement(this.exportProxyGroup);
// Set screen reader properties on export menu
if (exportingShouldHaveA11y(chart)) {
// Proxy button and group
this.exportProxyGroup = this.addProxyGroup(
// Wrap in a region div if verbosity is high
a11yOptions.landmarkVerbosity === 'all' ? {
'aria-label': chart.langFormat('accessibility.exporting.exportRegionLabel', { chart: chart }),
'role': 'region'
} : {});
var button = getExportMenuButtonElement(this.chart);
this.exportButtonProxy = this.createProxyButton(button, this.exportProxyGroup, {
'aria-label': chart.langFormat('accessibility.exporting.menuButtonLabel', { chart: chart }),
'aria-expanded': 'false'
});
}
},
/**
* @private
*/
addAccessibleContextMenuAttribs: function () {
var chart = this.chart, exportList = chart.exportDivElements;
if (exportList && exportList.length) {
// Set tabindex on the menu items to allow focusing by script
// Set role to give screen readers a chance to pick up the contents
exportList.forEach(function (item) {
if (item.tagName === 'LI' &&
!(item.children && item.children.length)) {
item.setAttribute('tabindex', -1);
}
else {
item.setAttribute('aria-hidden', 'true');
}
});
// Set accessibility properties on parent div
var parentDiv = exportList[0].parentNode;
parentDiv.removeAttribute('aria-hidden');
parentDiv.setAttribute('aria-label', chart.langFormat('accessibility.exporting.chartMenuLabel', { chart: chart }));
}
},
/**
* Get keyboard navigation handler for this component.
* @return {Highcharts.KeyboardNavigationHandler}
*/
getKeyboardNavigation: function () {
var keys = this.keyCodes, chart = this.chart, component = this;
return new KeyboardNavigationHandler(chart, {
keyCodeMap: [
// Arrow prev handler
[
[keys.left, keys.up],
function () {
return component.onKbdPrevious(this);
}
],
// Arrow next handler
[
[keys.right, keys.down],
function () {
return component.onKbdNext(this);
}
],
// Click handler
[
[keys.enter, keys.space],
function () {
return component.onKbdClick(this);
}
],
// ESC handler
[
[keys.esc],
function () {
return this.response.prev;
}
]
],
// Only run exporting navigation if exporting support exists and is
// enabled on chart
validate: function () {
return chart.exportChart &&
chart.options.exporting.enabled !== false &&
chart.options.exporting.accessibility.enabled !==
false;
},
// Focus export menu button
init: function () {
var exportBtn = component.exportButtonProxy, exportGroup = chart.exportingGroup;
if (exportGroup && exportBtn) {
chart.setFocusToElement(exportGroup, exportBtn);
}
},
// Hide the menu
terminate: function () {
chart.hideExportMenu();
}
});
},
/**
* @private
* @param {Highcharts.KeyboardNavigationHandler} keyboardNavigationHandler
* @return {number}
* Response code
*/
onKbdPrevious: function (keyboardNavigationHandler) {
var chart = this.chart, a11yOptions = chart.options.accessibility, response = keyboardNavigationHandler.response, i = chart.highlightedExportItemIx || 0;
// Try to highlight prev item in list. Highlighting e.g.
// separators will fail.
while (i--) {
if (chart.highlightExportItem(i)) {
return response.success;
}
}
// We failed, so wrap around or move to prev module
if (a11yOptions.keyboardNavigation.wrapAround) {
chart.highlightLastExportItem();
return response.success;
}
return response.prev;
},
/**
* @private
* @param {Highcharts.KeyboardNavigationHandler} keyboardNavigationHandler
* @return {number}
* Response code
*/
onKbdNext: function (keyboardNavigationHandler) {
var chart = this.chart, a11yOptions = chart.options.accessibility, response = keyboardNavigationHandler.response, i = (chart.highlightedExportItemIx || 0) + 1;
// Try to highlight next item in list. Highlighting e.g.
// separators will fail.
for (; i < chart.exportDivElements.length; ++i) {
if (chart.highlightExportItem(i)) {
return response.success;
}
}
// We failed, so wrap around or move to next module
if (a11yOptions.keyboardNavigation.wrapAround) {
chart.highlightExportItem(0);
return response.success;
}
return response.next;
},
/**
* @private
* @param {Highcharts.KeyboardNavigationHandler} keyboardNavigationHandler
* @return {number}
* Response code
*/
onKbdClick: function (keyboardNavigationHandler) {
var chart = this.chart, curHighlightedItem = chart.exportDivElements[chart.highlightedExportItemIx], exportButtonElement = getExportMenuButtonElement(chart).element;
if (this.isExportMenuShown) {
this.fakeClickEvent(curHighlightedItem);
}
else {
this.fakeClickEvent(exportButtonElement);
chart.highlightExportItem(0);
}
return keyboardNavigationHandler.response.success;
}
});
export default MenuComponent;

View File

@@ -0,0 +1,265 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Accessibility component for the range selector.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../../parts/Globals.js';
import U from '../../../parts/Utilities.js';
var extend = U.extend;
import AccessibilityComponent from '../AccessibilityComponent.js';
import KeyboardNavigationHandler from '../KeyboardNavigationHandler.js';
import ChartUtilities from '../utils/chartUtilities.js';
var unhideChartElementFromAT = ChartUtilities.unhideChartElementFromAT;
import HTMLUtilities from '../utils/htmlUtilities.js';
var setElAttrs = HTMLUtilities.setElAttrs;
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* @private
*/
function shouldRunInputNavigation(chart) {
var inputVisible = (chart.rangeSelector &&
chart.rangeSelector.inputGroup &&
chart.rangeSelector.inputGroup.element
.getAttribute('visibility') !== 'hidden');
return (inputVisible &&
chart.options.rangeSelector.inputEnabled !== false &&
chart.rangeSelector.minInput &&
chart.rangeSelector.maxInput);
}
/**
* Highlight range selector button by index.
*
* @private
* @function Highcharts.Chart#highlightRangeSelectorButton
*
* @param {number} ix
*
* @return {boolean}
*/
H.Chart.prototype.highlightRangeSelectorButton = function (ix) {
var buttons = this.rangeSelector.buttons, curSelectedIx = this.highlightedRangeSelectorItemIx;
// Deselect old
if (typeof curSelectedIx !== 'undefined' && buttons[curSelectedIx]) {
buttons[curSelectedIx].setState(this.oldRangeSelectorItemState || 0);
}
// Select new
this.highlightedRangeSelectorItemIx = ix;
if (buttons[ix]) {
this.setFocusToElement(buttons[ix].box, buttons[ix].element);
this.oldRangeSelectorItemState = buttons[ix].state;
buttons[ix].setState(2);
return true;
}
return false;
};
/**
* The RangeSelectorComponent class
*
* @private
* @class
* @name Highcharts.RangeSelectorComponent
*/
var RangeSelectorComponent = function () { };
RangeSelectorComponent.prototype = new AccessibilityComponent();
extend(RangeSelectorComponent.prototype, /** @lends Highcharts.RangeSelectorComponent */ {
/**
* Called on first render/updates to the chart, including options changes.
*/
onChartUpdate: function () {
var chart = this.chart, component = this, rangeSelector = chart.rangeSelector;
if (!rangeSelector) {
return;
}
if (rangeSelector.buttons && rangeSelector.buttons.length) {
rangeSelector.buttons.forEach(function (button) {
unhideChartElementFromAT(chart, button.element);
component.setRangeButtonAttrs(button);
});
}
// Make sure input boxes are accessible and focusable
if (rangeSelector.maxInput && rangeSelector.minInput) {
['minInput', 'maxInput'].forEach(function (key, i) {
var input = rangeSelector[key];
if (input) {
unhideChartElementFromAT(chart, input);
component.setRangeInputAttrs(input, 'accessibility.rangeSelector.' + (i ? 'max' : 'min') +
'InputLabel');
}
});
}
},
/**
* @private
* @param {Highcharts.SVGElement} button
*/
setRangeButtonAttrs: function (button) {
var chart = this.chart, label = chart.langFormat('accessibility.rangeSelector.buttonText', {
chart: chart,
buttonText: button.text && button.text.textStr
});
setElAttrs(button.element, {
tabindex: -1,
role: 'button',
'aria-label': label
});
},
/**
* @private
*/
setRangeInputAttrs: function (input, langKey) {
var chart = this.chart;
setElAttrs(input, {
tabindex: -1,
role: 'textbox',
'aria-label': chart.langFormat(langKey, { chart: chart })
});
},
/**
* Get navigation for the range selector buttons.
* @private
* @return {Highcharts.KeyboardNavigationHandler} The module object.
*/
getRangeSelectorButtonNavigation: function () {
var chart = this.chart, keys = this.keyCodes, component = this;
return new KeyboardNavigationHandler(chart, {
keyCodeMap: [
[
[keys.left, keys.right, keys.up, keys.down],
function (keyCode) {
return component.onButtonNavKbdArrowKey(this, keyCode);
}
],
[
[keys.enter, keys.space],
function () {
return component.onButtonNavKbdClick(this);
}
]
],
validate: function () {
var hasRangeSelector = chart.rangeSelector &&
chart.rangeSelector.buttons &&
chart.rangeSelector.buttons.length;
return hasRangeSelector;
},
init: function (direction) {
var lastButtonIx = (chart.rangeSelector.buttons.length - 1);
chart.highlightRangeSelectorButton(direction > 0 ? 0 : lastButtonIx);
}
});
},
/**
* @private
* @param {Highcharts.KeyboardNavigationHandler} keyboardNavigationHandler
* @param {number} keyCode
* @return {number} Response code
*/
onButtonNavKbdArrowKey: function (keyboardNavigationHandler, keyCode) {
var response = keyboardNavigationHandler.response, keys = this.keyCodes, chart = this.chart, wrapAround = chart.options.accessibility
.keyboardNavigation.wrapAround, direction = (keyCode === keys.left || keyCode === keys.up) ? -1 : 1, didHighlight = chart.highlightRangeSelectorButton(chart.highlightedRangeSelectorItemIx + direction);
if (!didHighlight) {
if (wrapAround) {
keyboardNavigationHandler.init(direction);
return response.success;
}
return response[direction > 0 ? 'next' : 'prev'];
}
return response.success;
},
/**
* @private
*/
onButtonNavKbdClick: function (keyboardNavigationHandler) {
var response = keyboardNavigationHandler.response, chart = this.chart, wasDisabled = chart.oldRangeSelectorItemState === 3;
if (!wasDisabled) {
this.fakeClickEvent(chart.rangeSelector.buttons[chart.highlightedRangeSelectorItemIx].element);
}
return response.success;
},
/**
* Get navigation for the range selector input boxes.
* @private
* @return {Highcharts.KeyboardNavigationHandler}
* The module object.
*/
getRangeSelectorInputNavigation: function () {
var chart = this.chart, keys = this.keyCodes, component = this;
return new KeyboardNavigationHandler(chart, {
keyCodeMap: [
[
[
keys.tab, keys.up, keys.down
], function (keyCode, e) {
var direction = (keyCode === keys.tab && e.shiftKey ||
keyCode === keys.up) ? -1 : 1;
return component.onInputKbdMove(this, direction);
}
]
],
validate: function () {
return shouldRunInputNavigation(chart);
},
init: function (direction) {
component.onInputNavInit(direction);
},
terminate: function () {
component.onInputNavTerminate();
}
});
},
/**
* @private
* @param {Highcharts.KeyboardNavigationHandler} keyboardNavigationHandler
* @param {number} direction
* @return {number} Response code
*/
onInputKbdMove: function (keyboardNavigationHandler, direction) {
var chart = this.chart, response = keyboardNavigationHandler.response, newIx = chart.highlightedInputRangeIx =
chart.highlightedInputRangeIx + direction, newIxOutOfRange = newIx > 1 || newIx < 0;
if (newIxOutOfRange) {
return response[direction > 0 ? 'next' : 'prev'];
}
chart.rangeSelector[newIx ? 'maxInput' : 'minInput'].focus();
return response.success;
},
/**
* @private
* @param {number} direction
*/
onInputNavInit: function (direction) {
var chart = this.chart, buttonIxToHighlight = direction > 0 ? 0 : 1;
chart.highlightedInputRangeIx = buttonIxToHighlight;
chart.rangeSelector[buttonIxToHighlight ? 'maxInput' : 'minInput'].focus();
},
/**
* @private
*/
onInputNavTerminate: function () {
var rangeSel = (this.chart.rangeSelector || {});
if (rangeSel.maxInput) {
rangeSel.hideInput('max');
}
if (rangeSel.minInput) {
rangeSel.hideInput('min');
}
},
/**
* Get keyboard navigation handlers for this component.
* @return {Array<Highcharts.KeyboardNavigationHandler>}
* List of module objects.
*/
getKeyboardNavigation: function () {
return [
this.getRangeSelectorButtonNavigation(),
this.getRangeSelectorInputNavigation()
];
}
});
export default RangeSelectorComponent;

View File

@@ -0,0 +1,254 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Handle announcing new data for a chart.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../../../parts/Globals.js';
import U from '../../../../parts/Utilities.js';
var extend = U.extend, defined = U.defined;
import ChartUtilities from '../../utils/chartUtilities.js';
var getChartTitle = ChartUtilities.getChartTitle;
import SeriesDescriber from './SeriesDescriber.js';
var defaultPointDescriptionFormatter = SeriesDescriber
.defaultPointDescriptionFormatter, defaultSeriesDescriptionFormatter = SeriesDescriber
.defaultSeriesDescriptionFormatter;
import Announcer from '../../utils/Announcer.js';
import EventProvider from '../../utils/EventProvider.js';
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* @private
*/
function chartHasAnnounceEnabled(chart) {
return !!chart.options.accessibility.announceNewData.enabled;
}
/**
* @private
*/
function findPointInDataArray(point) {
var candidates = point.series.data.filter(function (candidate) {
return point.x === candidate.x && point.y === candidate.y;
});
return candidates.length === 1 ? candidates[0] : point;
}
/**
* Get array of unique series from two arrays
* @private
*/
function getUniqueSeries(arrayA, arrayB) {
var uniqueSeries = (arrayA || []).concat(arrayB || [])
.reduce(function (acc, cur) {
acc[cur.name + cur.index] = cur;
return acc;
}, {});
return Object.keys(uniqueSeries).map(function (ix) {
return uniqueSeries[ix];
});
}
/**
* @private
* @class
*/
var NewDataAnnouncer = function (chart) {
this.chart = chart;
};
extend(NewDataAnnouncer.prototype, {
/**
* Initialize the new data announcer.
* @private
*/
init: function () {
var chart = this.chart;
var announceOptions = chart.options.accessibility.announceNewData;
var announceType = announceOptions.interruptUser ? 'assertive' : 'polite';
this.lastAnnouncementTime = 0;
this.dirty = {
allSeries: {}
};
this.eventProvider = new EventProvider();
this.announcer = new Announcer(chart, announceType);
this.addEventListeners();
},
/**
* Remove traces of announcer.
* @private
*/
destroy: function () {
this.eventProvider.removeAddedEvents();
this.announcer.destroy();
},
/**
* Add event listeners for the announcer
* @private
*/
addEventListeners: function () {
var announcer = this, chart = this.chart, e = this.eventProvider;
e.addEvent(chart, 'afterDrilldown', function () {
announcer.lastAnnouncementTime = 0;
});
e.addEvent(H.Series, 'updatedData', function () {
announcer.onSeriesUpdatedData(this);
});
e.addEvent(chart, 'afterAddSeries', function (e) {
announcer.onSeriesAdded(e.series);
});
e.addEvent(H.Series, 'addPoint', function (e) {
announcer.onPointAdded(e.point);
});
e.addEvent(chart, 'redraw', function () {
announcer.announceDirtyData();
});
},
/**
* On new data in the series, make sure we add it to the dirty list.
* @private
* @param {Highcharts.Series} series
*/
onSeriesUpdatedData: function (series) {
var chart = this.chart;
if (series.chart === chart && chartHasAnnounceEnabled(chart)) {
this.dirty.hasDirty = true;
this.dirty.allSeries[series.name + series.index] = series;
}
},
/**
* On new data series added, update dirty list.
* @private
* @param {Highcharts.Series} series
*/
onSeriesAdded: function (series) {
if (chartHasAnnounceEnabled(this.chart)) {
this.dirty.hasDirty = true;
this.dirty.allSeries[series.name + series.index] = series;
// Add it to newSeries storage unless we already have one
this.dirty.newSeries = defined(this.dirty.newSeries) ?
void 0 : series;
}
},
/**
* On new point added, update dirty list.
* @private
* @param {Highcharts.Point} point
*/
onPointAdded: function (point) {
var chart = point.series.chart;
if (this.chart === chart && chartHasAnnounceEnabled(chart)) {
// Add it to newPoint storage unless we already have one
this.dirty.newPoint = defined(this.dirty.newPoint) ?
void 0 : point;
}
},
/**
* Gather what we know and announce the data to user.
* @private
*/
announceDirtyData: function () {
var chart = this.chart, announcer = this;
if (chart.options.accessibility.announceNewData &&
this.dirty.hasDirty) {
var newPoint = this.dirty.newPoint;
// If we have a single new point, see if we can find it in the
// data array. Otherwise we can only pass through options to
// the description builder, and it is a bit sparse in info.
if (newPoint) {
newPoint = findPointInDataArray(newPoint);
}
this.queueAnnouncement(Object.keys(this.dirty.allSeries).map(function (ix) {
return announcer.dirty.allSeries[ix];
}), this.dirty.newSeries, newPoint);
// Reset
this.dirty = {
allSeries: {}
};
}
},
/**
* Announce to user that there is new data.
* @private
* @param {Array<Highcharts.Series>} dirtySeries
* Array of series with new data.
* @param {Highcharts.Series} [newSeries]
* If a single new series was added, a reference to this series.
* @param {Highcharts.Point} [newPoint]
* If a single point was added, a reference to this point.
*/
queueAnnouncement: function (dirtySeries, newSeries, newPoint) {
var _this = this;
var chart = this.chart;
var annOptions = chart.options.accessibility.announceNewData;
if (annOptions.enabled) {
var now = +new Date();
var dTime = now - this.lastAnnouncementTime;
var time = Math.max(0, annOptions.minAnnounceInterval - dTime);
// Add series from previously queued announcement.
var allSeries = getUniqueSeries(this.queuedAnnouncement && this.queuedAnnouncement.series, dirtySeries);
// Build message and announce
var message = this.buildAnnouncementMessage(allSeries, newSeries, newPoint);
if (message) {
// Is there already one queued?
if (this.queuedAnnouncement) {
clearTimeout(this.queuedAnnouncementTimer);
}
// Build the announcement
this.queuedAnnouncement = {
time: now,
message: message,
series: allSeries
};
// Queue the announcement
this.queuedAnnouncementTimer = setTimeout(function () {
if (_this && _this.announcer) {
_this.lastAnnouncementTime = +new Date();
_this.announcer.announce(_this.queuedAnnouncement.message);
delete _this.queuedAnnouncement;
delete _this.queuedAnnouncementTimer;
}
}, time);
}
}
},
/**
* Get announcement message for new data.
* @private
* @param {Array<Highcharts.Series>} dirtySeries
* Array of series with new data.
* @param {Highcharts.Series} [newSeries]
* If a single new series was added, a reference to this series.
* @param {Highcharts.Point} [newPoint]
* If a single point was added, a reference to this point.
*
* @return {string|null}
* The announcement message to give to user.
*/
buildAnnouncementMessage: function (dirtySeries, newSeries, newPoint) {
var chart = this.chart, annOptions = chart.options.accessibility.announceNewData;
// User supplied formatter?
if (annOptions.announcementFormatter) {
var formatterRes = annOptions.announcementFormatter(dirtySeries, newSeries, newPoint);
if (formatterRes !== false) {
return formatterRes.length ? formatterRes : null;
}
}
// Default formatter - use lang options
var multiple = H.charts && H.charts.length > 1 ? 'Multiple' : 'Single', langKey = newSeries ? 'newSeriesAnnounce' + multiple :
newPoint ? 'newPointAnnounce' + multiple : 'newDataAnnounce', chartTitle = getChartTitle(chart);
return chart.langFormat('accessibility.announceNewData.' + langKey, {
chartTitle: chartTitle,
seriesDesc: newSeries ?
defaultSeriesDescriptionFormatter(newSeries) :
null,
pointDesc: newPoint ?
defaultPointDescriptionFormatter(newPoint) :
null,
point: newPoint,
series: newSeries
});
}
});
export default NewDataAnnouncer;

View File

@@ -0,0 +1,109 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Accessibility component for series and points.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../../../parts/Globals.js';
import U from '../../../../parts/Utilities.js';
var extend = U.extend;
import AccessibilityComponent from '../../AccessibilityComponent.js';
import SeriesKeyboardNavigation from './SeriesKeyboardNavigation.js';
import NewDataAnnouncer from './NewDataAnnouncer.js';
import addForceMarkersEvents from './forcedMarkers.js';
import ChartUtilities from '../../utils/chartUtilities.js';
var hideSeriesFromAT = ChartUtilities.hideSeriesFromAT;
import SeriesDescriber from './SeriesDescriber.js';
var describeSeries = SeriesDescriber.describeSeries;
import Tooltip from '../../../../parts/Tooltip.js';
// Expose functionality to users
H.SeriesAccessibilityDescriber = SeriesDescriber;
// Handle forcing markers
addForceMarkersEvents();
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* The SeriesComponent class
*
* @private
* @class
* @name Highcharts.SeriesComponent
*/
var SeriesComponent = function () { };
SeriesComponent.prototype = new AccessibilityComponent();
extend(SeriesComponent.prototype, /** @lends Highcharts.SeriesComponent */ {
/**
* Init the component.
*/
init: function () {
this.newDataAnnouncer = new NewDataAnnouncer(this.chart);
this.newDataAnnouncer.init();
this.keyboardNavigation = new SeriesKeyboardNavigation(this.chart, this.keyCodes);
this.keyboardNavigation.init();
this.hideTooltipFromATWhenShown();
this.hideSeriesLabelsFromATWhenShown();
},
/**
* @private
*/
hideTooltipFromATWhenShown: function () {
var component = this;
this.addEvent(Tooltip, 'refresh', function () {
if (this.chart === component.chart &&
this.label &&
this.label.element) {
this.label.element.setAttribute('aria-hidden', true);
}
});
},
/**
* @private
*/
hideSeriesLabelsFromATWhenShown: function () {
this.addEvent(this.chart, 'afterDrawSeriesLabels', function () {
this.series.forEach(function (series) {
if (series.labelBySeries) {
series.labelBySeries.attr('aria-hidden', true);
}
});
});
},
/**
* Called on chart render. It is necessary to do this for render in case
* markers change on zoom/pixel density.
*/
onChartRender: function () {
var chart = this.chart;
chart.series.forEach(function (series) {
var shouldDescribeSeries = (series.options.accessibility &&
series.options.accessibility.enabled) !== false &&
series.visible;
if (shouldDescribeSeries) {
describeSeries(series);
}
else {
hideSeriesFromAT(series);
}
});
},
/**
* Get keyboard navigation handler for this component.
* @return {Highcharts.KeyboardNavigationHandler}
*/
getKeyboardNavigation: function () {
return this.keyboardNavigation.getKeyboardNavigationHandler();
},
/**
* Remove traces
*/
destroy: function () {
this.newDataAnnouncer.destroy();
this.keyboardNavigation.destroy();
}
});
export default SeriesComponent;

View File

@@ -0,0 +1,396 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Place desriptions on a series and its points.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../../../parts/Globals.js';
var numberFormat = H.numberFormat, format = H.format;
import U from '../../../../parts/Utilities.js';
var find = U.find, isNumber = U.isNumber, pick = U.pick, defined = U.defined;
import AnnotationsA11y from '../AnnotationsA11y.js';
var getPointAnnotationTexts = AnnotationsA11y.getPointAnnotationTexts;
import HTMLUtilities from '../../utils/htmlUtilities.js';
var escapeStringForHTML = HTMLUtilities.escapeStringForHTML, reverseChildNodes = HTMLUtilities.reverseChildNodes, stripHTMLTags = HTMLUtilities.stripHTMLTagsFromString;
import ChartUtilities from '../../utils/chartUtilities.js';
var getAxisDescription = ChartUtilities.getAxisDescription, getSeriesFirstPointElement = ChartUtilities.getSeriesFirstPointElement, getSeriesA11yElement = ChartUtilities.getSeriesA11yElement, unhideChartElementFromAT = ChartUtilities.unhideChartElementFromAT;
import Tooltip from '../../../../parts/Tooltip.js';
/* eslint-disable valid-jsdoc */
/**
* @private
*/
function findFirstPointWithGraphic(point) {
var sourcePointIndex = point.index;
if (!point.series || !point.series.data || !defined(sourcePointIndex)) {
return null;
}
return find(point.series.data, function (p) {
return !!(p &&
typeof p.index !== 'undefined' &&
p.index > sourcePointIndex &&
p.graphic &&
p.graphic.element);
}) || null;
}
/**
* @private
*/
function shouldAddDummyPoint(point) {
// Note: Sunburst series use isNull for hidden points on drilldown.
// Ignore these.
var isSunburst = point.series && point.series.is('sunburst'), isNull = point.isNull;
return isNull && !isSunburst;
}
/**
* @private
*/
function makeDummyElement(point, pos) {
var renderer = point.series.chart.renderer, dummy = renderer.rect(pos.x, pos.y, 1, 1);
dummy.attr({
'class': 'highcharts-a11y-dummy-point',
fill: 'none',
opacity: 0,
'fill-opacity': 0,
'stroke-opacity': 0
});
return dummy;
}
/**
* @private
* @param {Highcharts.Point} point
* @return {Highcharts.HTMLDOMElement|Highcharts.SVGDOMElement|undefined}
*/
function addDummyPointElement(point) {
var series = point.series, firstPointWithGraphic = findFirstPointWithGraphic(point), firstGraphic = firstPointWithGraphic && firstPointWithGraphic.graphic, parentGroup = firstGraphic ?
firstGraphic.parentGroup :
series.graph || series.group, dummyPos = firstPointWithGraphic ? {
x: pick(point.plotX, firstPointWithGraphic.plotX, 0),
y: pick(point.plotY, firstPointWithGraphic.plotY, 0)
} : {
x: pick(point.plotX, 0),
y: pick(point.plotY, 0)
}, dummyElement = makeDummyElement(point, dummyPos);
if (parentGroup && parentGroup.element) {
point.graphic = dummyElement;
point.hasDummyGraphic = true;
dummyElement.add(parentGroup);
// Move to correct pos in DOM
parentGroup.element.insertBefore(dummyElement.element, firstGraphic ? firstGraphic.element : null);
return dummyElement.element;
}
}
/**
* @private
* @param {Highcharts.Series} series
* @return {boolean}
*/
function hasMorePointsThanDescriptionThreshold(series) {
var chartA11yOptions = series.chart.options.accessibility, threshold = (chartA11yOptions.series.pointDescriptionEnabledThreshold);
return !!(threshold !== false &&
series.points &&
series.points.length >= threshold);
}
/**
* @private
* @param {Highcharts.Series} series
* @return {boolean}
*/
function shouldSetScreenReaderPropsOnPoints(series) {
var seriesA11yOptions = series.options.accessibility || {};
return !hasMorePointsThanDescriptionThreshold(series) &&
!seriesA11yOptions.exposeAsGroupOnly;
}
/**
* @private
* @param {Highcharts.Series} series
* @return {boolean}
*/
function shouldSetKeyboardNavPropsOnPoints(series) {
var chartA11yOptions = series.chart.options.accessibility, seriesNavOptions = chartA11yOptions.keyboardNavigation.seriesNavigation;
return !!(series.points && (series.points.length <
seriesNavOptions.pointNavigationEnabledThreshold ||
seriesNavOptions.pointNavigationEnabledThreshold === false));
}
/**
* @private
* @param {Highcharts.Series} series
* @return {boolean}
*/
function shouldDescribeSeriesElement(series) {
var chart = series.chart, chartOptions = chart.options.chart || {}, chartHas3d = chartOptions.options3d && chartOptions.options3d.enabled, hasMultipleSeries = chart.series.length > 1, describeSingleSeriesOption = chart.options.accessibility.series.describeSingleSeries, exposeAsGroupOnlyOption = (series.options.accessibility || {}).exposeAsGroupOnly, noDescribe3D = chartHas3d && hasMultipleSeries;
return !noDescribe3D && (hasMultipleSeries || describeSingleSeriesOption ||
exposeAsGroupOnlyOption || hasMorePointsThanDescriptionThreshold(series));
}
/**
* @private
* @param {Highcharts.Point} point
* @param {number} value
* @return {string}
*/
function pointNumberToString(point, value) {
var chart = point.series.chart, a11yPointOptions = chart.options.accessibility.point || {}, tooltipOptions = point.series.tooltipOptions || {}, lang = chart.options.lang;
if (isNumber(value)) {
return numberFormat(value, a11yPointOptions.valueDecimals ||
tooltipOptions.valueDecimals ||
-1, lang.decimalPoint, lang.accessibility.thousandsSep || lang.thousandsSep);
}
return value;
}
/**
* @private
* @param {Highcharts.Series} series
* @return {string}
*/
function getSeriesDescriptionText(series) {
var seriesA11yOptions = series.options.accessibility || {}, descOpt = seriesA11yOptions.description;
return descOpt && series.chart.langFormat('accessibility.series.description', {
description: descOpt,
series: series
}) || '';
}
/**
* @private
* @param {Highcharts.series} series
* @param {string} axisCollection
* @return {string}
*/
function getSeriesAxisDescriptionText(series, axisCollection) {
var axis = series[axisCollection];
return series.chart.langFormat('accessibility.series.' + axisCollection + 'Description', {
name: getAxisDescription(axis),
series: series
});
}
/**
* Get accessible time description for a point on a datetime axis.
*
* @private
* @function Highcharts.Point#getTimeDescription
* @param {Highcharts.Point} point
* @return {string|undefined}
* The description as string.
*/
function getPointA11yTimeDescription(point) {
var series = point.series, chart = series.chart, a11yOptions = chart.options.accessibility.point || {}, hasDateXAxis = series.xAxis && series.xAxis.isDatetimeAxis;
if (hasDateXAxis) {
var tooltipDateFormat = Tooltip.prototype.getXDateFormat.call({
getDateFormat: Tooltip.prototype.getDateFormat,
chart: chart
}, point, chart.options.tooltip, series.xAxis), dateFormat = a11yOptions.dateFormatter &&
a11yOptions.dateFormatter(point) ||
a11yOptions.dateFormat ||
tooltipDateFormat;
return chart.time.dateFormat(dateFormat, point.x, void 0);
}
}
/**
* @private
* @param {Highcharts.Point} point
* @return {string}
*/
function getPointXDescription(point) {
var timeDesc = getPointA11yTimeDescription(point), xAxis = point.series.xAxis || {}, pointCategory = xAxis.categories && defined(point.category) &&
('' + point.category).replace('<br/>', ' '), canUseId = point.id && point.id.indexOf('highcharts-') < 0, fallback = 'x, ' + point.x;
return point.name || timeDesc || pointCategory ||
(canUseId ? point.id : fallback);
}
/**
* @private
* @param {Highcharts.Point} point
* @param {string} prefix
* @param {string} suffix
* @return {string}
*/
function getPointArrayMapValueDescription(point, prefix, suffix) {
var pre = prefix || '', suf = suffix || '', keyToValStr = function (key) {
var num = pointNumberToString(point, pick(point[key], point.options[key]));
return key + ': ' + pre + num + suf;
}, pointArrayMap = point.series.pointArrayMap;
return pointArrayMap.reduce(function (desc, key) {
return desc + (desc.length ? ', ' : '') + keyToValStr(key);
}, '');
}
/**
* @private
* @param {Highcharts.Point} point
* @return {string}
*/
function getPointValue(point) {
var series = point.series, a11yPointOpts = series.chart.options.accessibility.point || {}, tooltipOptions = series.tooltipOptions || {}, valuePrefix = a11yPointOpts.valuePrefix ||
tooltipOptions.valuePrefix || '', valueSuffix = a11yPointOpts.valueSuffix ||
tooltipOptions.valueSuffix || '', fallbackKey = (typeof point.value !==
'undefined' ?
'value' : 'y'), fallbackDesc = pointNumberToString(point, point[fallbackKey]);
if (point.isNull) {
return series.chart.langFormat('accessibility.series.nullPointValue', {
point: point
});
}
if (series.pointArrayMap) {
return getPointArrayMapValueDescription(point, valuePrefix, valueSuffix);
}
return valuePrefix + fallbackDesc + valueSuffix;
}
/**
* Return the description for the annotation(s) connected to a point, or empty
* string if none.
*
* @private
* @param {Highcharts.Point} point The data point to get the annotation info from.
* @return {string} Annotation description
*/
function getPointAnnotationDescription(point) {
var chart = point.series.chart;
var langKey = 'accessibility.series.pointAnnotationsDescription';
var annotations = getPointAnnotationTexts(point);
var context = { point: point, annotations: annotations };
return annotations.length ? chart.langFormat(langKey, context) : '';
}
/**
* Return string with information about point.
* @private
* @return {string}
*/
function getPointValueDescription(point) {
var series = point.series, chart = series.chart, pointValueDescriptionFormat = chart.options.accessibility
.point.valueDescriptionFormat, showXDescription = pick(series.xAxis &&
series.xAxis.options.accessibility &&
series.xAxis.options.accessibility.enabled, !chart.angular), xDesc = showXDescription ? getPointXDescription(point) : '', context = {
point: point,
index: defined(point.index) ? (point.index + 1) : '',
xDescription: xDesc,
value: getPointValue(point),
separator: showXDescription ? ', ' : ''
};
return format(pointValueDescriptionFormat, context, chart);
}
/**
* Return string with information about point.
* @private
* @return {string}
*/
function defaultPointDescriptionFormatter(point) {
var series = point.series, chart = series.chart, valText = getPointValueDescription(point), description = point.options && point.options.accessibility &&
point.options.accessibility.description, userDescText = description ? ' ' + description : '', seriesNameText = chart.series.length > 1 && series.name ?
' ' + series.name + '.' : '', annotationsDesc = getPointAnnotationDescription(point), pointAnnotationsText = annotationsDesc ? ' ' + annotationsDesc : '';
point.accessibility = point.accessibility || {};
point.accessibility.valueDescription = valText;
return valText + userDescText + seriesNameText + pointAnnotationsText;
}
/**
* Set a11y props on a point element
* @private
* @param {Highcharts.Point} point
* @param {Highcharts.HTMLDOMElement|Highcharts.SVGDOMElement} pointElement
*/
function setPointScreenReaderAttribs(point, pointElement) {
var series = point.series, a11yPointOptions = series.chart.options.accessibility.point || {}, seriesA11yOptions = series.options.accessibility || {}, label = escapeStringForHTML(stripHTMLTags(seriesA11yOptions.pointDescriptionFormatter &&
seriesA11yOptions.pointDescriptionFormatter(point) ||
a11yPointOptions.descriptionFormatter &&
a11yPointOptions.descriptionFormatter(point) ||
defaultPointDescriptionFormatter(point)));
pointElement.setAttribute('role', 'img');
pointElement.setAttribute('aria-label', label);
}
/**
* Add accessible info to individual point elements of a series
* @private
* @param {Highcharts.Series} series
*/
function describePointsInSeries(series) {
var setScreenReaderProps = shouldSetScreenReaderPropsOnPoints(series), setKeyboardProps = shouldSetKeyboardNavPropsOnPoints(series);
if (setScreenReaderProps || setKeyboardProps) {
series.points.forEach(function (point) {
var pointEl = point.graphic && point.graphic.element ||
shouldAddDummyPoint(point) && addDummyPointElement(point);
if (pointEl) {
// We always set tabindex, as long as we are setting
// props.
pointEl.setAttribute('tabindex', '-1');
if (setScreenReaderProps) {
setPointScreenReaderAttribs(point, pointEl);
}
else {
pointEl.setAttribute('aria-hidden', true);
}
}
});
}
}
/**
* Return string with information about series.
* @private
* @return {string}
*/
function defaultSeriesDescriptionFormatter(series) {
var chart = series.chart, chartTypes = chart.types || [], description = getSeriesDescriptionText(series), shouldDescribeAxis = function (coll) {
return chart[coll] && chart[coll].length > 1 && series[coll];
}, xAxisInfo = getSeriesAxisDescriptionText(series, 'xAxis'), yAxisInfo = getSeriesAxisDescriptionText(series, 'yAxis'), summaryContext = {
name: series.name || '',
ix: series.index + 1,
numSeries: chart.series && chart.series.length,
numPoints: series.points && series.points.length,
series: series
}, combinationSuffix = chartTypes.length > 1 ? 'Combination' : '', summary = chart.langFormat('accessibility.series.summary.' + series.type + combinationSuffix, summaryContext) || chart.langFormat('accessibility.series.summary.default' + combinationSuffix, summaryContext);
return summary + (description ? ' ' + description : '') + (shouldDescribeAxis('yAxis') ? ' ' + yAxisInfo : '') + (shouldDescribeAxis('xAxis') ? ' ' + xAxisInfo : '');
}
/**
* Set a11y props on a series element
* @private
* @param {Highcharts.Series} series
* @param {Highcharts.HTMLDOMElement|Highcharts.SVGDOMElement} seriesElement
*/
function describeSeriesElement(series, seriesElement) {
var seriesA11yOptions = series.options.accessibility || {}, a11yOptions = series.chart.options.accessibility, landmarkVerbosity = a11yOptions.landmarkVerbosity;
// Handle role attribute
if (seriesA11yOptions.exposeAsGroupOnly) {
seriesElement.setAttribute('role', 'img');
}
else if (landmarkVerbosity === 'all') {
seriesElement.setAttribute('role', 'region');
} /* else do not add role */
seriesElement.setAttribute('tabindex', '-1');
seriesElement.setAttribute('aria-label', escapeStringForHTML(stripHTMLTags(a11yOptions.series.descriptionFormatter &&
a11yOptions.series.descriptionFormatter(series) ||
defaultSeriesDescriptionFormatter(series))));
}
/**
* Put accessible info on series and points of a series.
* @param {Highcharts.Series} series The series to add info on.
*/
function describeSeries(series) {
var chart = series.chart, firstPointEl = getSeriesFirstPointElement(series), seriesEl = getSeriesA11yElement(series), is3d = chart.is3d && chart.is3d();
if (seriesEl) {
// For some series types the order of elements do not match the
// order of points in series. In that case we have to reverse them
// in order for AT to read them out in an understandable order.
// Due to z-index issues we can not do this for 3D charts.
if (seriesEl.lastChild === firstPointEl && !is3d) {
reverseChildNodes(seriesEl);
}
describePointsInSeries(series);
unhideChartElementFromAT(chart, seriesEl);
if (shouldDescribeSeriesElement(series)) {
describeSeriesElement(series, seriesEl);
}
else {
seriesEl.setAttribute('aria-label', '');
}
}
}
var SeriesDescriber = {
describeSeries: describeSeries,
defaultPointDescriptionFormatter: defaultPointDescriptionFormatter,
defaultSeriesDescriptionFormatter: defaultSeriesDescriptionFormatter,
getPointA11yTimeDescription: getPointA11yTimeDescription,
getPointXDescription: getPointXDescription,
getPointValue: getPointValue,
getPointValueDescription: getPointValueDescription
};
export default SeriesDescriber;

View File

@@ -0,0 +1,571 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Handle keyboard navigation for series.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../../../parts/Globals.js';
import Point from '../../../../parts/Point.js';
import U from '../../../../parts/Utilities.js';
var extend = U.extend, defined = U.defined;
import KeyboardNavigationHandler from '../../KeyboardNavigationHandler.js';
import EventProvider from '../../utils/EventProvider.js';
import ChartUtilities from '../../utils/chartUtilities.js';
var getPointFromXY = ChartUtilities.getPointFromXY, getSeriesFromName = ChartUtilities.getSeriesFromName;
/* eslint-disable no-invalid-this, valid-jsdoc */
/*
* Set for which series types it makes sense to move to the closest point with
* up/down arrows, and which series types should just move to next series.
*/
H.Series.prototype.keyboardMoveVertical = true;
['column', 'pie'].forEach(function (type) {
if (H.seriesTypes[type]) {
H.seriesTypes[type].prototype.keyboardMoveVertical = false;
}
});
/**
* Get the index of a point in a series. This is needed when using e.g. data
* grouping.
*
* @private
* @function getPointIndex
*
* @param {Highcharts.AccessibilityPoint} point
* The point to find index of.
*
* @return {number|undefined}
* The index in the series.points array of the point.
*/
function getPointIndex(point) {
var index = point.index, points = point.series.points, i = points.length;
if (points[index] !== point) {
while (i--) {
if (points[i] === point) {
return i;
}
}
}
else {
return index;
}
}
/**
* Determine if series navigation should be skipped
*
* @private
* @function isSkipSeries
*
* @param {Highcharts.Series} series
*
* @return {boolean|number|undefined}
*/
function isSkipSeries(series) {
var a11yOptions = series.chart.options.accessibility, seriesNavOptions = a11yOptions.keyboardNavigation.seriesNavigation, seriesA11yOptions = series.options.accessibility || {}, seriesKbdNavOptions = seriesA11yOptions.keyboardNavigation;
return seriesKbdNavOptions && seriesKbdNavOptions.enabled === false ||
seriesA11yOptions.enabled === false ||
series.options.enableMouseTracking === false || // #8440
!series.visible ||
// Skip all points in a series where pointNavigationEnabledThreshold is
// reached
(seriesNavOptions.pointNavigationEnabledThreshold &&
seriesNavOptions.pointNavigationEnabledThreshold <=
series.points.length);
}
/**
* Determine if navigation for a point should be skipped
*
* @private
* @function isSkipPoint
*
* @param {Highcharts.Point} point
*
* @return {boolean|number|undefined}
*/
function isSkipPoint(point) {
var a11yOptions = point.series.chart.options.accessibility;
return point.isNull &&
a11yOptions.keyboardNavigation.seriesNavigation.skipNullPoints ||
point.visible === false ||
isSkipSeries(point.series);
}
/**
* Get the point in a series that is closest (in pixel distance) to a reference
* point. Optionally supply weight factors for x and y directions.
*
* @private
* @function getClosestPoint
*
* @param {Highcharts.Point} point
* @param {Highcharts.Series} series
* @param {number} [xWeight]
* @param {number} [yWeight]
*
* @return {Highcharts.Point|undefined}
*/
function getClosestPoint(point, series, xWeight, yWeight) {
var minDistance = Infinity, dPoint, minIx, distance, i = series.points.length, hasUndefinedPosition = function (point) {
return !(defined(point.plotX) && defined(point.plotY));
};
if (hasUndefinedPosition(point)) {
return;
}
while (i--) {
dPoint = series.points[i];
if (hasUndefinedPosition(dPoint)) {
continue;
}
distance = (point.plotX - dPoint.plotX) *
(point.plotX - dPoint.plotX) *
(xWeight || 1) +
(point.plotY - dPoint.plotY) *
(point.plotY - dPoint.plotY) *
(yWeight || 1);
if (distance < minDistance) {
minDistance = distance;
minIx = i;
}
}
return defined(minIx) ? series.points[minIx] : void 0;
}
/**
* Highlights a point (show tooltip and display hover state).
*
* @private
* @function Highcharts.Point#highlight
*
* @return {Highcharts.Point}
* This highlighted point.
*/
Point.prototype.highlight = function () {
var chart = this.series.chart;
if (!this.isNull) {
this.onMouseOver(); // Show the hover marker and tooltip
}
else {
if (chart.tooltip) {
chart.tooltip.hide(0);
}
// Don't call blur on the element, as it messes up the chart div's focus
}
// We focus only after calling onMouseOver because the state change can
// change z-index and mess up the element.
if (this.graphic) {
chart.setFocusToElement(this.graphic);
}
chart.highlightedPoint = this;
return this;
};
/**
* Function to highlight next/previous point in chart.
*
* @private
* @function Highcharts.Chart#highlightAdjacentPoint
*
* @param {boolean} next
* Flag for the direction.
*
* @return {Highcharts.Point|boolean}
* Returns highlighted point on success, false on failure (no adjacent
* point to highlight in chosen direction).
*/
H.Chart.prototype.highlightAdjacentPoint = function (next) {
var chart = this, series = chart.series, curPoint = chart.highlightedPoint, curPointIndex = curPoint && getPointIndex(curPoint) || 0, curPoints = (curPoint && curPoint.series.points), lastSeries = chart.series && chart.series[chart.series.length - 1], lastPoint = lastSeries && lastSeries.points &&
lastSeries.points[lastSeries.points.length - 1], newSeries, newPoint;
// If no points, return false
if (!series[0] || !series[0].points) {
return false;
}
if (!curPoint) {
// No point is highlighted yet. Try first/last point depending on move
// direction
newPoint = next ? series[0].points[0] : lastPoint;
}
else {
// We have a highlighted point.
// Grab next/prev point & series
newSeries = series[curPoint.series.index + (next ? 1 : -1)];
newPoint = curPoints[curPointIndex + (next ? 1 : -1)];
if (!newPoint && newSeries) {
// Done with this series, try next one
newPoint = newSeries.points[next ? 0 : newSeries.points.length - 1];
}
// If there is no adjacent point, we return false
if (!newPoint) {
return false;
}
}
// Recursively skip points
if (isSkipPoint(newPoint)) {
// If we skip this whole series, move to the end of the series before we
// recurse, just to optimize
newSeries = newPoint.series;
if (isSkipSeries(newSeries)) {
chart.highlightedPoint = next ?
newSeries.points[newSeries.points.length - 1] :
newSeries.points[0];
}
else {
// Otherwise, just move one point
chart.highlightedPoint = newPoint;
}
// Retry
return chart.highlightAdjacentPoint(next);
}
// There is an adjacent point, highlight it
return newPoint.highlight();
};
/**
* Highlight first valid point in a series. Returns the point if successfully
* highlighted, otherwise false. If there is a highlighted point in the series,
* use that as starting point.
*
* @private
* @function Highcharts.Series#highlightFirstValidPoint
*
* @return {boolean|Highcharts.Point}
*/
H.Series.prototype.highlightFirstValidPoint = function () {
var curPoint = this.chart.highlightedPoint, start = (curPoint && curPoint.series) === this ?
getPointIndex(curPoint) :
0, points = this.points, len = points.length;
if (points && len) {
for (var i = start; i < len; ++i) {
if (!isSkipPoint(points[i])) {
return points[i].highlight();
}
}
for (var j = start; j >= 0; --j) {
if (!isSkipPoint(points[j])) {
return points[j].highlight();
}
}
}
return false;
};
/**
* Highlight next/previous series in chart. Returns false if no adjacent series
* in the direction, otherwise returns new highlighted point.
*
* @private
* @function Highcharts.Chart#highlightAdjacentSeries
*
* @param {boolean} down
*
* @return {Highcharts.Point|boolean}
*/
H.Chart.prototype.highlightAdjacentSeries = function (down) {
var chart = this, newSeries, newPoint, adjacentNewPoint, curPoint = chart.highlightedPoint, lastSeries = chart.series && chart.series[chart.series.length - 1], lastPoint = lastSeries && lastSeries.points &&
lastSeries.points[lastSeries.points.length - 1];
// If no point is highlighted, highlight the first/last point
if (!chart.highlightedPoint) {
newSeries = down ? (chart.series && chart.series[0]) : lastSeries;
newPoint = down ?
(newSeries && newSeries.points && newSeries.points[0]) : lastPoint;
return newPoint ? newPoint.highlight() : false;
}
newSeries = chart.series[curPoint.series.index + (down ? -1 : 1)];
if (!newSeries) {
return false;
}
// We have a new series in this direction, find the right point
// Weigh xDistance as counting much higher than Y distance
newPoint = getClosestPoint(curPoint, newSeries, 4);
if (!newPoint) {
return false;
}
// New series and point exists, but we might want to skip it
if (isSkipSeries(newSeries)) {
// Skip the series
newPoint.highlight();
adjacentNewPoint = chart.highlightAdjacentSeries(down); // Try recurse
if (!adjacentNewPoint) {
// Recurse failed
curPoint.highlight();
return false;
}
// Recurse succeeded
return adjacentNewPoint;
}
// Highlight the new point or any first valid point back or forwards from it
newPoint.highlight();
return newPoint.series.highlightFirstValidPoint();
};
/**
* Highlight the closest point vertically.
*
* @private
* @function Highcharts.Chart#highlightAdjacentPointVertical
*
* @param {boolean} down
*
* @return {Highcharts.Point|boolean}
*/
H.Chart.prototype.highlightAdjacentPointVertical = function (down) {
var curPoint = this.highlightedPoint, minDistance = Infinity, bestPoint;
if (!defined(curPoint.plotX) || !defined(curPoint.plotY)) {
return false;
}
this.series.forEach(function (series) {
if (isSkipSeries(series)) {
return;
}
series.points.forEach(function (point) {
if (!defined(point.plotY) || !defined(point.plotX) ||
point === curPoint) {
return;
}
var yDistance = point.plotY - curPoint.plotY, width = Math.abs(point.plotX - curPoint.plotX), distance = Math.abs(yDistance) * Math.abs(yDistance) +
width * width * 4; // Weigh horizontal distance highly
// Reverse distance number if axis is reversed
if (series.yAxis && series.yAxis.reversed) {
yDistance *= -1;
}
if (yDistance <= 0 && down || yDistance >= 0 && !down || // Chk dir
distance < 5 || // Points in same spot => infinite loop
isSkipPoint(point)) {
return;
}
if (distance < minDistance) {
minDistance = distance;
bestPoint = point;
}
});
});
return bestPoint ? bestPoint.highlight() : false;
};
/**
* @private
* @param {Highcharts.Chart} chart
* @return {Highcharts.Point|boolean}
*/
function highlightFirstValidPointInChart(chart) {
var res = false;
delete chart.highlightedPoint;
res = chart.series.reduce(function (acc, cur) {
return acc || cur.highlightFirstValidPoint();
}, false);
return res;
}
/**
* @private
* @param {Highcharts.Chart} chart
* @return {Highcharts.Point|boolean}
*/
function highlightLastValidPointInChart(chart) {
var numSeries = chart.series.length, i = numSeries, res = false;
while (i--) {
chart.highlightedPoint = chart.series[i].points[chart.series[i].points.length - 1];
// Highlight first valid point in the series will also
// look backwards. It always starts from currently
// highlighted point.
res = chart.series[i].highlightFirstValidPoint();
if (res) {
break;
}
}
return res;
}
/**
* @private
* @param {Highcharts.Chart} chart
*/
function updateChartFocusAfterDrilling(chart) {
highlightFirstValidPointInChart(chart);
if (chart.focusElement) {
chart.focusElement.removeFocusBorder();
}
}
/**
* @private
* @class
* @name Highcharts.SeriesKeyboardNavigation
*/
function SeriesKeyboardNavigation(chart, keyCodes) {
this.keyCodes = keyCodes;
this.chart = chart;
}
extend(SeriesKeyboardNavigation.prototype, /** @lends Highcharts.SeriesKeyboardNavigation */ {
/**
* Init the keyboard navigation
*/
init: function () {
var keyboardNavigation = this, chart = this.chart, e = this.eventProvider = new EventProvider();
e.addEvent(H.Series, 'destroy', function () {
return keyboardNavigation.onSeriesDestroy(this);
});
e.addEvent(chart, 'afterDrilldown', function () {
updateChartFocusAfterDrilling(this);
});
e.addEvent(chart, 'drilldown', function (e) {
var point = e.point, series = point.series;
keyboardNavigation.lastDrilledDownPoint = {
x: point.x,
y: point.y,
seriesName: series ? series.name : ''
};
});
e.addEvent(chart, 'drillupall', function () {
setTimeout(function () {
keyboardNavigation.onDrillupAll();
}, 10);
});
},
onDrillupAll: function () {
// After drillup we want to find the point that was drilled down to and
// highlight it.
var last = this.lastDrilledDownPoint, chart = this.chart, series = last && getSeriesFromName(chart, last.seriesName), point;
if (last && series && defined(last.x) && defined(last.y)) {
point = getPointFromXY(series, last.x, last.y);
}
// Container focus can be lost on drillup due to deleted elements.
if (chart.container) {
chart.container.focus();
}
if (point && point.highlight) {
point.highlight();
}
if (chart.focusElement) {
chart.focusElement.removeFocusBorder();
}
},
/**
* @return {Highcharts.KeyboardNavigationHandler}
*/
getKeyboardNavigationHandler: function () {
var keyboardNavigation = this, keys = this.keyCodes, chart = this.chart, inverted = chart.inverted;
return new KeyboardNavigationHandler(chart, {
keyCodeMap: [
[inverted ? [keys.up, keys.down] : [keys.left, keys.right],
function (keyCode) {
return keyboardNavigation.onKbdSideways(this, keyCode);
}],
[inverted ? [keys.left, keys.right] : [keys.up, keys.down],
function (keyCode) {
return keyboardNavigation.onKbdVertical(this, keyCode);
}],
[[keys.enter, keys.space],
function () {
if (chart.highlightedPoint) {
chart.highlightedPoint.firePointEvent('click');
}
return this.response.success;
}]
],
init: function (dir) {
return keyboardNavigation.onHandlerInit(this, dir);
},
terminate: function () {
return keyboardNavigation.onHandlerTerminate();
}
});
},
/**
* @private
* @param {Highcharts.KeyboardNavigationHandler} handler
* @param {number} keyCode
* @return {number}
* response
*/
onKbdSideways: function (handler, keyCode) {
var keys = this.keyCodes, isNext = keyCode === keys.right || keyCode === keys.down;
return this.attemptHighlightAdjacentPoint(handler, isNext);
},
/**
* @private
* @param {Highcharts.KeyboardNavigationHandler} handler
* @param {number} keyCode
* @return {number}
* response
*/
onKbdVertical: function (handler, keyCode) {
var chart = this.chart, keys = this.keyCodes, isNext = keyCode === keys.down || keyCode === keys.right, navOptions = chart.options.accessibility.keyboardNavigation
.seriesNavigation;
// Handle serialized mode, act like left/right
if (navOptions.mode && navOptions.mode === 'serialize') {
return this.attemptHighlightAdjacentPoint(handler, isNext);
}
// Normal mode, move between series
var highlightMethod = (chart.highlightedPoint &&
chart.highlightedPoint.series.keyboardMoveVertical) ?
'highlightAdjacentPointVertical' :
'highlightAdjacentSeries';
chart[highlightMethod](isNext);
return handler.response.success;
},
/**
* @private
* @param {Highcharts.KeyboardNavigationHandler} handler
* @param {number} initDirection
* @return {number}
* response
*/
onHandlerInit: function (handler, initDirection) {
var chart = this.chart;
if (initDirection > 0) {
highlightFirstValidPointInChart(chart);
}
else {
highlightLastValidPointInChart(chart);
}
return handler.response.success;
},
/**
* @private
*/
onHandlerTerminate: function () {
var chart = this.chart;
var curPoint = chart.highlightedPoint;
if (chart.tooltip) {
chart.tooltip.hide(0);
}
if (curPoint) {
curPoint.onMouseOut();
delete chart.highlightedPoint;
}
},
/**
* Function that attempts to highlight next/prev point. Handles wrap around.
* @private
* @param {Highcharts.KeyboardNavigationHandler} handler
* @param {boolean} directionIsNext
* @return {number}
* response
*/
attemptHighlightAdjacentPoint: function (handler, directionIsNext) {
var chart = this.chart, wrapAround = chart.options.accessibility.keyboardNavigation
.wrapAround, highlightSuccessful = chart.highlightAdjacentPoint(directionIsNext);
if (!highlightSuccessful) {
if (wrapAround) {
return handler.init(directionIsNext ? 1 : -1);
}
return handler.response[directionIsNext ? 'next' : 'prev'];
}
return handler.response.success;
},
/**
* @private
*/
onSeriesDestroy: function (series) {
var chart = this.chart, currentHighlightedPointDestroyed = chart.highlightedPoint &&
chart.highlightedPoint.series === series;
if (currentHighlightedPointDestroyed) {
delete chart.highlightedPoint;
if (chart.focusElement) {
chart.focusElement.removeFocusBorder();
}
}
},
/**
* @private
*/
destroy: function () {
this.eventProvider.removeAddedEvents();
}
});
export default SeriesKeyboardNavigation;

View File

@@ -0,0 +1,147 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Handle forcing series markers.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../../../parts/Globals.js';
import U from '../../../../parts/Utilities.js';
var addEvent = U.addEvent, merge = U.merge;
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* @private
*/
function isWithinDescriptionThreshold(series) {
var a11yOptions = series.chart.options.accessibility;
return series.points.length <
a11yOptions.series.pointDescriptionEnabledThreshold ||
a11yOptions.series.pointDescriptionEnabledThreshold === false;
}
/**
* @private
*/
function isWithinNavigationThreshold(series) {
var navOptions = series.chart.options.accessibility
.keyboardNavigation.seriesNavigation;
return series.points.length <
navOptions.pointNavigationEnabledThreshold ||
navOptions.pointNavigationEnabledThreshold === false;
}
/**
* @private
*/
function shouldForceMarkers(series) {
var chartA11yEnabled = series.chart.options.accessibility.enabled, seriesA11yEnabled = (series.options.accessibility &&
series.options.accessibility.enabled) !== false, withinDescriptionThreshold = isWithinDescriptionThreshold(series), withinNavigationThreshold = isWithinNavigationThreshold(series);
return chartA11yEnabled && seriesA11yEnabled &&
(withinDescriptionThreshold || withinNavigationThreshold);
}
/**
* @private
*/
function unforceMarkerOptions(series) {
var resetMarkerOptions = series.resetA11yMarkerOptions;
merge(true, series.options, {
marker: {
enabled: resetMarkerOptions.enabled,
states: {
normal: {
opacity: resetMarkerOptions.states &&
resetMarkerOptions.states.normal &&
resetMarkerOptions.states.normal.opacity
}
}
}
});
}
/**
* @private
*/
function forceZeroOpacityMarkerOptions(options) {
merge(true, options, {
marker: {
enabled: true,
states: {
normal: {
opacity: 0
}
}
}
});
}
/**
* @private
*/
function getPointMarkerOpacity(pointOptions) {
return pointOptions.marker.states &&
pointOptions.marker.states.normal &&
pointOptions.marker.states.normal.opacity || 1;
}
/**
* @private
*/
function forceDisplayPointMarker(pointOptions) {
merge(true, pointOptions.marker, {
states: {
normal: {
opacity: getPointMarkerOpacity(pointOptions)
}
}
});
}
/**
* @private
*/
function handleForcePointMarkers(points) {
var i = points.length;
while (i--) {
var pointOptions = points[i].options;
if (pointOptions.marker) {
if (pointOptions.marker.enabled) {
forceDisplayPointMarker(pointOptions);
}
else {
forceZeroOpacityMarkerOptions(pointOptions);
}
}
}
}
/**
* @private
*/
function addForceMarkersEvents() {
/**
* Keep track of forcing markers.
* @private
*/
addEvent(H.Series, 'render', function () {
var series = this, options = series.options;
if (shouldForceMarkers(series)) {
if (options.marker && options.marker.enabled === false) {
series.a11yMarkersForced = true;
forceZeroOpacityMarkerOptions(series.options);
}
if (series._hasPointMarkers && series.points && series.points.length) {
handleForcePointMarkers(series.points);
}
}
else if (series.a11yMarkersForced && series.resetMarkerOptions) {
delete series.a11yMarkersForced;
unforceMarkerOptions(series);
}
});
/**
* Keep track of options to reset markers to if no longer forced.
* @private
*/
addEvent(H.Series, 'afterSetOptions', function (e) {
this.resetA11yMarkerOptions = merge(e.options.marker || {}, this.userOptions.marker || {});
});
}
export default addForceMarkersEvents;

View File

@@ -0,0 +1,288 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Accessibility component for chart zoom.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../../parts/Globals.js';
import U from '../../../parts/Utilities.js';
var extend = U.extend, pick = U.pick;
import AccessibilityComponent from '../AccessibilityComponent.js';
import KeyboardNavigationHandler from '../KeyboardNavigationHandler.js';
import ChartUtilities from '../utils/chartUtilities.js';
var unhideChartElementFromAT = ChartUtilities.unhideChartElementFromAT;
import HTMLUtilities from '../utils/htmlUtilities.js';
var setElAttrs = HTMLUtilities.setElAttrs, removeElement = HTMLUtilities.removeElement;
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* @private
*/
function chartHasMapZoom(chart) {
return !!(chart.mapZoom &&
chart.mapNavButtons &&
chart.mapNavButtons.length);
}
/**
* Pan along axis in a direction (1 or -1), optionally with a defined
* granularity (number of steps it takes to walk across current view)
*
* @private
* @function Highcharts.Axis#panStep
*
* @param {number} direction
* @param {number} [granularity]
*/
H.Axis.prototype.panStep = function (direction, granularity) {
var gran = granularity || 3, extremes = this.getExtremes(), step = (extremes.max - extremes.min) / gran * direction, newMax = extremes.max + step, newMin = extremes.min + step, size = newMax - newMin;
if (direction < 0 && newMin < extremes.dataMin) {
newMin = extremes.dataMin;
newMax = newMin + size;
}
else if (direction > 0 && newMax > extremes.dataMax) {
newMax = extremes.dataMax;
newMin = newMax - size;
}
this.setExtremes(newMin, newMax);
};
/**
* The ZoomComponent class
*
* @private
* @class
* @name Highcharts.ZoomComponent
*/
var ZoomComponent = function () { };
ZoomComponent.prototype = new AccessibilityComponent();
extend(ZoomComponent.prototype, /** @lends Highcharts.ZoomComponent */ {
/**
* Initialize the component
*/
init: function () {
var component = this, chart = this.chart;
[
'afterShowResetZoom', 'afterDrilldown', 'drillupall'
].forEach(function (eventType) {
component.addEvent(chart, eventType, function () {
component.updateProxyOverlays();
});
});
},
/**
* Called when chart is updated
*/
onChartUpdate: function () {
var chart = this.chart, component = this;
// Make map zoom buttons accessible
if (chart.mapNavButtons) {
chart.mapNavButtons.forEach(function (button, i) {
unhideChartElementFromAT(chart, button.element);
component.setMapNavButtonAttrs(button.element, 'accessibility.zoom.mapZoom' + (i ? 'Out' : 'In'));
});
}
},
/**
* @private
* @param {Highcharts.HTMLDOMElement|Highcharts.SVGDOMElement} button
* @param {string} labelFormatKey
*/
setMapNavButtonAttrs: function (button, labelFormatKey) {
var chart = this.chart, label = chart.langFormat(labelFormatKey, { chart: chart });
setElAttrs(button, {
tabindex: -1,
role: 'button',
'aria-label': label
});
},
/**
* Update the proxy overlays on every new render to ensure positions are
* correct.
*/
onChartRender: function () {
this.updateProxyOverlays();
},
/**
* Update proxy overlays, recreating the buttons.
*/
updateProxyOverlays: function () {
var chart = this.chart;
// Always start with a clean slate
removeElement(this.drillUpProxyGroup);
removeElement(this.resetZoomProxyGroup);
if (chart.resetZoomButton) {
this.recreateProxyButtonAndGroup(chart.resetZoomButton, 'resetZoomProxyButton', 'resetZoomProxyGroup', chart.langFormat('accessibility.zoom.resetZoomButton', { chart: chart }));
}
if (chart.drillUpButton) {
this.recreateProxyButtonAndGroup(chart.drillUpButton, 'drillUpProxyButton', 'drillUpProxyGroup', chart.langFormat('accessibility.drillUpButton', {
chart: chart,
buttonText: chart.getDrilldownBackText()
}));
}
},
/**
* @private
* @param {Highcharts.SVGElement} buttonEl
* @param {string} buttonProp
* @param {string} groupProp
* @param {string} label
*/
recreateProxyButtonAndGroup: function (buttonEl, buttonProp, groupProp, label) {
removeElement(this[groupProp]);
this[groupProp] = this.addProxyGroup();
this[buttonProp] = this.createProxyButton(buttonEl, this[groupProp], { 'aria-label': label, tabindex: -1 });
},
/**
* Get keyboard navigation handler for map zoom.
* @private
* @return {Highcharts.KeyboardNavigationHandler} The module object
*/
getMapZoomNavigation: function () {
var keys = this.keyCodes, chart = this.chart, component = this;
return new KeyboardNavigationHandler(chart, {
keyCodeMap: [
[
[keys.up, keys.down, keys.left, keys.right],
function (keyCode) {
return component.onMapKbdArrow(this, keyCode);
}
],
[
[keys.tab],
function (_keyCode, e) {
return component.onMapKbdTab(this, e);
}
],
[
[keys.space, keys.enter],
function () {
return component.onMapKbdClick(this);
}
]
],
validate: function () {
return chartHasMapZoom(chart);
},
init: function (direction) {
return component.onMapNavInit(direction);
}
});
},
/**
* @private
* @param {Highcharts.KeyboardNavigationHandler} keyboardNavigationHandler
* @param {number} keyCode
* @return {number} Response code
*/
onMapKbdArrow: function (keyboardNavigationHandler, keyCode) {
var keys = this.keyCodes, panAxis = (keyCode === keys.up || keyCode === keys.down) ?
'yAxis' : 'xAxis', stepDirection = (keyCode === keys.left || keyCode === keys.up) ?
-1 : 1;
this.chart[panAxis][0].panStep(stepDirection);
return keyboardNavigationHandler.response.success;
},
/**
* @private
* @param {Highcharts.KeyboardNavigationHandler} keyboardNavigationHandler
* @param {global.KeyboardEvent} event
* @return {number} Response code
*/
onMapKbdTab: function (keyboardNavigationHandler, event) {
var button, chart = this.chart, response = keyboardNavigationHandler.response, isBackwards = event.shiftKey, isMoveOutOfRange = isBackwards && !this.focusedMapNavButtonIx ||
!isBackwards && this.focusedMapNavButtonIx;
// Deselect old
chart.mapNavButtons[this.focusedMapNavButtonIx].setState(0);
if (isMoveOutOfRange) {
chart.mapZoom(); // Reset zoom
return response[isBackwards ? 'prev' : 'next'];
}
// Select other button
this.focusedMapNavButtonIx += isBackwards ? -1 : 1;
button = chart.mapNavButtons[this.focusedMapNavButtonIx];
chart.setFocusToElement(button.box, button.element);
button.setState(2);
return response.success;
},
/**
* @private
* @param {Highcharts.KeyboardNavigationHandler} keyboardNavigationHandler
* @return {number} Response code
*/
onMapKbdClick: function (keyboardNavigationHandler) {
this.fakeClickEvent(this.chart.mapNavButtons[this.focusedMapNavButtonIx]
.element);
return keyboardNavigationHandler.response.success;
},
/**
* @private
* @param {number} direction
*/
onMapNavInit: function (direction) {
var chart = this.chart, zoomIn = chart.mapNavButtons[0], zoomOut = chart.mapNavButtons[1], initialButton = direction > 0 ? zoomIn : zoomOut;
chart.setFocusToElement(initialButton.box, initialButton.element);
initialButton.setState(2);
this.focusedMapNavButtonIx = direction > 0 ? 0 : 1;
},
/**
* Get keyboard navigation handler for a simple chart button. Provide the
* button reference for the chart, and a function to call on click.
*
* @private
* @param {string} buttonProp The property on chart referencing the button.
* @return {Highcharts.KeyboardNavigationHandler} The module object
*/
simpleButtonNavigation: function (buttonProp, proxyProp, onClick) {
var keys = this.keyCodes, component = this, chart = this.chart;
return new KeyboardNavigationHandler(chart, {
keyCodeMap: [
[
[keys.tab, keys.up, keys.down, keys.left, keys.right],
function (keyCode, e) {
var isBackwards = keyCode === keys.tab && e.shiftKey ||
keyCode === keys.left || keyCode === keys.up;
// Arrow/tab => just move
return this.response[isBackwards ? 'prev' : 'next'];
}
],
[
[keys.space, keys.enter],
function () {
var res = onClick(this, chart);
return pick(res, this.response.success);
}
]
],
validate: function () {
var hasButton = (chart[buttonProp] &&
chart[buttonProp].box &&
component[proxyProp]);
return hasButton;
},
init: function () {
chart.setFocusToElement(chart[buttonProp].box, component[proxyProp]);
}
});
},
/**
* Get keyboard navigation handlers for this component.
* @return {Array<Highcharts.KeyboardNavigationHandler>}
* List of module objects
*/
getKeyboardNavigation: function () {
return [
this.simpleButtonNavigation('resetZoomButton', 'resetZoomProxyButton', function (_handler, chart) {
chart.zoomOut();
}),
this.simpleButtonNavigation('drillUpButton', 'drillUpProxyButton', function (handler, chart) {
chart.drillUp();
return handler.response.prev;
}),
this.getMapZoomNavigation()
];
}
});
export default ZoomComponent;

View File

@@ -0,0 +1,107 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Extend SVG and Chart classes with focus border capabilities.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../parts/Globals.js';
import U from '../../parts/Utilities.js';
var addEvent = U.addEvent, extend = U.extend, pick = U.pick;
/* eslint-disable no-invalid-this, valid-jsdoc */
/*
* Add focus border functionality to SVGElements. Draws a new rect on top of
* element around its bounding box. This is used by multiple components.
*/
extend(H.SVGElement.prototype, {
/**
* @private
* @function Highcharts.SVGElement#addFocusBorder
*
* @param {number} margin
*
* @param {Highcharts.CSSObject} style
*/
addFocusBorder: function (margin, style) {
// Allow updating by just adding new border
if (this.focusBorder) {
this.removeFocusBorder();
}
// Add the border rect
var bb = this.getBBox(), pad = pick(margin, 3);
bb.x += this.translateX ? this.translateX : 0;
bb.y += this.translateY ? this.translateY : 0;
this.focusBorder = this.renderer.rect(bb.x - pad, bb.y - pad, bb.width + 2 * pad, bb.height + 2 * pad, parseInt((style && style.borderRadius || 0).toString(), 10))
.addClass('highcharts-focus-border')
.attr({
zIndex: 99
})
.add(this.parentGroup);
if (!this.renderer.styledMode) {
this.focusBorder.attr({
stroke: style && style.stroke,
'stroke-width': style && style.strokeWidth
});
}
},
/**
* @private
* @function Highcharts.SVGElement#removeFocusBorder
*/
removeFocusBorder: function () {
if (this.focusBorder) {
this.focusBorder.destroy();
delete this.focusBorder;
}
}
});
/**
* Set chart's focus to an SVGElement. Calls focus() on it, and draws the focus
* border. This is used by multiple components.
*
* @private
* @function Highcharts.Chart#setFocusToElement
*
* @param {Highcharts.SVGElement} svgElement
* Element to draw the border around.
*
* @param {SVGDOMElement|HTMLDOMElement} [focusElement]
* If supplied, it draws the border around svgElement and sets the focus
* to focusElement.
*/
H.Chart.prototype.setFocusToElement = function (svgElement, focusElement) {
var focusBorderOptions = this.options.accessibility.keyboardNavigation.focusBorder, browserFocusElement = focusElement || svgElement.element;
// Set browser focus if possible
if (browserFocusElement &&
browserFocusElement.focus) {
// If there is no focusin-listener, add one to work around Edge issue
// where Narrator is not reading out points despite calling focus().
if (!(browserFocusElement.hcEvents &&
browserFocusElement.hcEvents.focusin)) {
addEvent(browserFocusElement, 'focusin', function () { });
}
browserFocusElement.focus();
// Hide default focus ring
if (focusBorderOptions.hideBrowserFocusOutline) {
browserFocusElement.style.outline = 'none';
}
}
if (focusBorderOptions.enabled) {
// Remove old focus border
if (this.focusElement) {
this.focusElement.removeFocusBorder();
}
// Draw focus border (since some browsers don't do it automatically)
svgElement.addFocusBorder(focusBorderOptions.margin, {
stroke: focusBorderOptions.style.color,
strokeWidth: focusBorderOptions.style.lineWidth,
borderRadius: focusBorderOptions.style.borderRadius
});
this.focusElement = svgElement;
}
};

View File

@@ -0,0 +1,82 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Handling for Windows High Contrast Mode.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../parts/Globals.js';
var isMS = H.isMS, win = H.win, doc = win.document;
var whcm = {
/**
* Detect WHCM in the browser.
*
* @function Highcharts#isHighContrastModeActive
* @private
* @return {boolean} Returns true if the browser is in High Contrast mode.
*/
isHighContrastModeActive: function () {
// Use media query on Edge, but not on IE
var isEdge = /(Edg)/.test(win.navigator.userAgent);
if (win.matchMedia && isEdge) {
return win.matchMedia('(-ms-high-contrast: active)').matches;
}
// Test BG image for IE
if (isMS && win.getComputedStyle) {
var testDiv = doc.createElement('div');
testDiv.style.backgroundImage = 'url(#)';
doc.body.appendChild(testDiv);
var bi = (testDiv.currentStyle ||
win.getComputedStyle(testDiv)).backgroundImage;
doc.body.removeChild(testDiv);
return bi === 'none';
}
// Not used for other browsers
return false;
},
/**
* Force high contrast theme for the chart. The default theme is defined in
* a separate file.
*
* @function Highcharts#setHighContrastTheme
* @private
* @param {Highcharts.AccessibilityChart} chart The chart to set the theme of.
* @return {void}
*/
setHighContrastTheme: function (chart) {
// We might want to add additional functionality here in the future for
// storing the old state so that we can reset the theme if HC mode is
// disabled. For now, the user will have to reload the page.
chart.highContrastModeActive = true;
// Apply theme to chart
var theme = (chart.options.accessibility.highContrastTheme);
chart.update(theme, false);
// Force series colors (plotOptions is not enough)
chart.series.forEach(function (s) {
var plotOpts = theme.plotOptions[s.type] || {};
s.update({
color: plotOpts.color || 'windowText',
colors: [plotOpts.color || 'windowText'],
borderColor: plotOpts.borderColor || 'window'
});
// Force point colors if existing
s.points.forEach(function (p) {
if (p.options && p.options.color) {
p.update({
color: plotOpts.color || 'windowText',
borderColor: plotOpts.borderColor || 'window'
}, false);
}
});
});
// The redraw for each series and after is required for 3D pie
// (workaround)
chart.redraw();
}
};
export default whcm;

View File

@@ -0,0 +1,211 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Default theme for Windows High Contrast Mode.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
var theme = {
chart: {
backgroundColor: 'window'
},
title: {
style: {
color: 'windowText'
}
},
subtitle: {
style: {
color: 'windowText'
}
},
colorAxis: {
minColor: 'windowText',
maxColor: 'windowText',
stops: []
},
colors: ['windowText'],
xAxis: {
gridLineColor: 'windowText',
labels: {
style: {
color: 'windowText'
}
},
lineColor: 'windowText',
minorGridLineColor: 'windowText',
tickColor: 'windowText',
title: {
style: {
color: 'windowText'
}
}
},
yAxis: {
gridLineColor: 'windowText',
labels: {
style: {
color: 'windowText'
}
},
lineColor: 'windowText',
minorGridLineColor: 'windowText',
tickColor: 'windowText',
title: {
style: {
color: 'windowText'
}
}
},
tooltip: {
backgroundColor: 'window',
borderColor: 'windowText',
style: {
color: 'windowText'
}
},
plotOptions: {
series: {
lineColor: 'windowText',
fillColor: 'window',
borderColor: 'windowText',
edgeColor: 'windowText',
borderWidth: 1,
dataLabels: {
connectorColor: 'windowText',
color: 'windowText',
style: {
color: 'windowText',
textOutline: 'none'
}
},
marker: {
lineColor: 'windowText',
fillColor: 'windowText'
}
},
pie: {
color: 'window',
colors: ['window'],
borderColor: 'windowText',
borderWidth: 1
},
boxplot: {
fillColor: 'window'
},
candlestick: {
lineColor: 'windowText',
fillColor: 'window'
},
errorbar: {
fillColor: 'window'
}
},
legend: {
backgroundColor: 'window',
itemStyle: {
color: 'windowText'
},
itemHoverStyle: {
color: 'windowText'
},
itemHiddenStyle: {
color: '#555'
},
title: {
style: {
color: 'windowText'
}
}
},
credits: {
style: {
color: 'windowText'
}
},
labels: {
style: {
color: 'windowText'
}
},
drilldown: {
activeAxisLabelStyle: {
color: 'windowText'
},
activeDataLabelStyle: {
color: 'windowText'
}
},
navigation: {
buttonOptions: {
symbolStroke: 'windowText',
theme: {
fill: 'window'
}
}
},
rangeSelector: {
buttonTheme: {
fill: 'window',
stroke: 'windowText',
style: {
color: 'windowText'
},
states: {
hover: {
fill: 'window',
stroke: 'windowText',
style: {
color: 'windowText'
}
},
select: {
fill: '#444',
stroke: 'windowText',
style: {
color: 'windowText'
}
}
}
},
inputBoxBorderColor: 'windowText',
inputStyle: {
backgroundColor: 'window',
color: 'windowText'
},
labelStyle: {
color: 'windowText'
}
},
navigator: {
handles: {
backgroundColor: 'window',
borderColor: 'windowText'
},
outlineColor: 'windowText',
maskFill: 'transparent',
series: {
color: 'windowText',
lineColor: 'windowText'
},
xAxis: {
gridLineColor: 'windowText'
}
},
scrollbar: {
barBackgroundColor: '#444',
barBorderColor: 'windowText',
buttonArrowColor: 'windowText',
buttonBackgroundColor: 'window',
buttonBorderColor: 'windowText',
rifleColor: 'windowText',
trackBackgroundColor: 'window',
trackBorderColor: 'windowText'
}
};
export default theme;

View File

@@ -0,0 +1,243 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Default options for accessibility.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
/* eslint-disable max-len */
/*
* List of deprecated options:
*
* chart.description -> accessibility.description
* chart.typeDescription -> accessibility.typeDescription
* series.description -> series.accessibility.description
* series.exposeElementToA11y -> series.accessibility.exposeAsGroupOnly
* series.pointDescriptionFormatter ->
* series.accessibility.pointDescriptionFormatter
* series.skipKeyboardNavigation ->
* series.accessibility.keyboardNavigation.enabled
* point.description -> point.accessibility.description !!!! WARNING: No longer deprecated and handled, removed for HC8.
* axis.description -> axis.accessibility.description
*
* accessibility.pointDateFormat -> accessibility.point.dateFormat
* accessibility.addTableShortcut -> Handled by screenReaderSection.beforeChartFormat
* accessibility.pointDateFormatter -> accessibility.point.dateFormatter
* accessibility.pointDescriptionFormatter -> accessibility.point.descriptionFormatter
* accessibility.pointDescriptionThreshold -> accessibility.series.pointDescriptionEnabledThreshold
* accessibility.pointNavigationThreshold -> accessibility.keyboardNavigation.seriesNavigation.pointNavigationEnabledThreshold
* accessibility.pointValueDecimals -> accessibility.point.valueDecimals
* accessibility.pointValuePrefix -> accessibility.point.valuePrefix
* accessibility.pointValueSuffix -> accessibility.point.valueSuffix
* accessibility.screenReaderSectionFormatter -> accessibility.screenReaderSection.beforeChartFormatter
* accessibility.describeSingleSeries -> accessibility.series.describeSingleSeries
* accessibility.seriesDescriptionFormatter -> accessibility.series.descriptionFormatter
* accessibility.onTableAnchorClick -> accessibility.screenReaderSection.onViewDataTableClick
* accessibility.axisRangeDateFormat -> accessibility.screenReaderSection.axisRangeDateFormat
* accessibility.keyboardNavigation.skipNullPoints -> accessibility.keyboardNavigation.seriesNavigation.skipNullPoints
* accessibility.keyboardNavigation.mode -> accessibility.keyboardNavigation.seriesNavigation.mode
*
* lang.accessibility.chartHeading -> no longer used, remove
* lang.accessibility.legendItem -> lang.accessibility.legend.legendItem
* lang.accessibility.legendLabel -> lang.accessibility.legend.legendLabel
* lang.accessibility.mapZoomIn -> lang.accessibility.zoom.mapZoomIn
* lang.accessibility.mapZoomOut -> lang.accessibility.zoom.mapZoomOut
* lang.accessibility.resetZoomButton -> lang.accessibility.zoom.resetZoomButton
* lang.accessibility.screenReaderRegionLabel -> lang.accessibility.screenReaderSection.beforeRegionLabel
* lang.accessibility.rangeSelectorButton -> lang.accessibility.rangeSelector.buttonText
* lang.accessibility.rangeSelectorMaxInput -> lang.accessibility.rangeSelector.maxInputLabel
* lang.accessibility.rangeSelectorMinInput -> lang.accessibility.rangeSelector.minInputLabel
* lang.accessibility.svgContainerEnd -> lang.accessibility.screenReaderSection.endOfChartMarker
* lang.accessibility.viewAsDataTable -> lang.accessibility.table.viewAsDataTableButtonText
* lang.accessibility.tableSummary -> lang.accessibility.table.tableSummary
*
*/
/* eslint-enable max-len */
'use strict';
import U from '../../../parts/Utilities.js';
var error = U.error, pick = U.pick;
/* eslint-disable valid-jsdoc */
/**
* Warn user that a deprecated option was used.
* @private
* @param {Highcharts.Chart} chart
* @param {string} oldOption
* @param {string} newOption
* @return {void}
*/
function warn(chart, oldOption, newOption) {
error('Highcharts: Deprecated option ' + oldOption +
' used. This will be removed from future versions of Highcharts. Use ' +
newOption + ' instead.', false, chart);
}
/**
* Set a new option on a root prop, where the option is defined as an array of
* suboptions.
* @private
* @param root
* @param {Array<string>} optionAsArray
* @param {*} val
* @return {void}
*/
function traverseSetOption(root, optionAsArray, val) {
var opt = root, prop, i = 0;
for (; i < optionAsArray.length - 1; ++i) {
prop = optionAsArray[i];
opt = opt[prop] = pick(opt[prop], {});
}
opt[optionAsArray[optionAsArray.length - 1]] = val;
}
/**
* If we have a clear root option node for old and new options and a mapping
* between, we can use this generic function for the copy and warn logic.
*/
function deprecateFromOptionsMap(chart, rootOldAsArray, rootNewAsArray, mapToNewOptions) {
/**
* @private
*/
function getChildProp(root, propAsArray) {
return propAsArray.reduce(function (acc, cur) {
return acc[cur];
}, root);
}
var rootOld = getChildProp(chart.options, rootOldAsArray), rootNew = getChildProp(chart.options, rootNewAsArray);
Object.keys(mapToNewOptions).forEach(function (oldOptionKey) {
var val = rootOld[oldOptionKey];
if (typeof val !== 'undefined') {
traverseSetOption(rootNew, mapToNewOptions[oldOptionKey], val);
warn(chart, rootOldAsArray.join('.') + '.' + oldOptionKey, rootNewAsArray.join('.') + '.' +
mapToNewOptions[oldOptionKey].join('.'));
}
});
}
/**
* @private
*/
function copyDeprecatedChartOptions(chart) {
var chartOptions = chart.options.chart || {}, a11yOptions = chart.options.accessibility || {};
['description', 'typeDescription'].forEach(function (prop) {
if (chartOptions[prop]) {
a11yOptions[prop] = chartOptions[prop];
warn(chart, 'chart.' + prop, 'accessibility.' + prop);
}
});
}
/**
* @private
*/
function copyDeprecatedAxisOptions(chart) {
chart.axes.forEach(function (axis) {
var opts = axis.options;
if (opts && opts.description) {
opts.accessibility = opts.accessibility || {};
opts.accessibility.description = opts.description;
warn(chart, 'axis.description', 'axis.accessibility.description');
}
});
}
/**
* @private
*/
function copyDeprecatedSeriesOptions(chart) {
// Map of deprecated series options. New options are defined as
// arrays of paths under series.options.
var oldToNewSeriesOptions = {
description: ['accessibility', 'description'],
exposeElementToA11y: ['accessibility', 'exposeAsGroupOnly'],
pointDescriptionFormatter: [
'accessibility', 'pointDescriptionFormatter'
],
skipKeyboardNavigation: [
'accessibility', 'keyboardNavigation', 'enabled'
]
};
chart.series.forEach(function (series) {
// Handle series wide options
Object.keys(oldToNewSeriesOptions).forEach(function (oldOption) {
var optionVal = series.options[oldOption];
if (typeof optionVal !== 'undefined') {
// Set the new option
traverseSetOption(series.options, oldToNewSeriesOptions[oldOption],
// Note that skipKeyboardNavigation has inverted option
// value, since we set enabled rather than disabled
oldOption === 'skipKeyboardNavigation' ?
!optionVal : optionVal);
warn(chart, 'series.' + oldOption, 'series.' +
oldToNewSeriesOptions[oldOption].join('.'));
}
});
});
}
/**
* @private
*/
function copyDeprecatedTopLevelAccessibilityOptions(chart) {
deprecateFromOptionsMap(chart, ['accessibility'], ['accessibility'], {
pointDateFormat: ['point', 'dateFormat'],
pointDateFormatter: ['point', 'dateFormatter'],
pointDescriptionFormatter: ['point', 'descriptionFormatter'],
pointDescriptionThreshold: ['series',
'pointDescriptionEnabledThreshold'],
pointNavigationThreshold: ['keyboardNavigation', 'seriesNavigation',
'pointNavigationEnabledThreshold'],
pointValueDecimals: ['point', 'valueDecimals'],
pointValuePrefix: ['point', 'valuePrefix'],
pointValueSuffix: ['point', 'valueSuffix'],
screenReaderSectionFormatter: ['screenReaderSection',
'beforeChartFormatter'],
describeSingleSeries: ['series', 'describeSingleSeries'],
seriesDescriptionFormatter: ['series', 'descriptionFormatter'],
onTableAnchorClick: ['screenReaderSection', 'onViewDataTableClick'],
axisRangeDateFormat: ['screenReaderSection', 'axisRangeDateFormat']
});
}
/**
* @private
*/
function copyDeprecatedKeyboardNavigationOptions(chart) {
deprecateFromOptionsMap(chart, ['accessibility', 'keyboardNavigation'], ['accessibility', 'keyboardNavigation', 'seriesNavigation'], {
skipNullPoints: ['skipNullPoints'],
mode: ['mode']
});
}
/**
* @private
*/
function copyDeprecatedLangOptions(chart) {
deprecateFromOptionsMap(chart, ['lang', 'accessibility'], ['lang', 'accessibility'], {
legendItem: ['legend', 'legendItem'],
legendLabel: ['legend', 'legendLabel'],
mapZoomIn: ['zoom', 'mapZoomIn'],
mapZoomOut: ['zoom', 'mapZoomOut'],
resetZoomButton: ['zoom', 'resetZoomButton'],
screenReaderRegionLabel: ['screenReaderSection',
'beforeRegionLabel'],
rangeSelectorButton: ['rangeSelector', 'buttonText'],
rangeSelectorMaxInput: ['rangeSelector', 'maxInputLabel'],
rangeSelectorMinInput: ['rangeSelector', 'minInputLabel'],
svgContainerEnd: ['screenReaderSection', 'endOfChartMarker'],
viewAsDataTable: ['table', 'viewAsDataTableButtonText'],
tableSummary: ['table', 'tableSummary']
});
}
/**
* Copy options that are deprecated over to new options. Logs warnings to
* console if deprecated options are used.
*
* @private
*/
function copyDeprecatedOptions(chart) {
copyDeprecatedChartOptions(chart);
copyDeprecatedAxisOptions(chart);
if (chart.series) {
copyDeprecatedSeriesOptions(chart);
}
copyDeprecatedTopLevelAccessibilityOptions(chart);
copyDeprecatedKeyboardNavigationOptions(chart);
copyDeprecatedLangOptions(chart);
}
export default copyDeprecatedOptions;

View File

@@ -0,0 +1,338 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Default lang/i18n options for accessibility.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
var langOptions = {
/**
* Configure the accessibility strings in the chart. Requires the
* [accessibility module](https://code.highcharts.com/modules/accessibility.js)
* to be loaded. For a description of the module and information on its
* features, see
* [Highcharts Accessibility](https://www.highcharts.com/docs/chart-concepts/accessibility).
*
* For more dynamic control over the accessibility functionality, see
* [accessibility.pointDescriptionFormatter](#accessibility.pointDescriptionFormatter),
* [accessibility.seriesDescriptionFormatter](#accessibility.seriesDescriptionFormatter),
* and
* [accessibility.screenReaderSectionFormatter](#accessibility.screenReaderSectionFormatter).
*
* @since 6.0.6
* @optionparent lang.accessibility
*/
accessibility: {
defaultChartTitle: 'Chart',
chartContainerLabel: '{title}. Highcharts interactive chart.',
svgContainerLabel: 'Interactive chart',
drillUpButton: '{buttonText}',
credits: 'Chart credits: {creditsStr}',
/**
* Thousands separator to use when formatting numbers for screen
* readers. Note that many screen readers will not handle space as a
* thousands separator, and will consider "11 700" as two numbers.
*
* Set to `null` to use the separator defined in
* [lang.thousandsSep](lang.thousandsSep).
*
* @since 7.1.0
*/
thousandsSep: ',',
/**
* Title element text for the chart SVG element. Leave this
* empty to disable adding the title element. Browsers will display
* this content when hovering over elements in the chart. Assistive
* technology may use this element to label the chart.
*
* @since 6.0.8
*/
svgContainerTitle: '',
/**
* Set a label on the container wrapping the SVG.
*
* @see [chartContainerLabel](#lang.accessibility.chartContainerLabel)
*
* @since 8.0.0
*/
graphicContainerLabel: '',
/**
* Language options for the screen reader information sections added
* before and after the charts.
*
* @since 8.0.0
*/
screenReaderSection: {
beforeRegionLabel: 'Chart screen reader information.',
afterRegionLabel: '',
/**
* Language options for annotation descriptions.
*
* @since 8.0.1
*/
annotations: {
heading: 'Chart annotations summary',
descriptionSinglePoint: '{annotationText}. Related to {annotationPoint}',
descriptionMultiplePoints: '{annotationText}. Related to {annotationPoint}' +
'{ Also related to, #each(additionalAnnotationPoints)}',
descriptionNoPoints: '{annotationText}'
},
/**
* Label for the end of the chart. Announced by screen readers.
*
* @since 8.0.0
*/
endOfChartMarker: 'End of interactive chart.'
},
/**
* Language options for sonification.
*
* @since 8.0.1
*/
sonification: {
playAsSoundButtonText: 'Play as sound, {chartTitle}',
playAsSoundClickAnnouncement: 'Play'
},
/**
* Language options for accessibility of the legend.
*
* @since 8.0.0
*/
legend: {
legendLabel: 'Toggle series visibility',
legendItem: 'Toggle visibility of {itemName}'
},
/**
* Chart and map zoom accessibility language options.
*
* @since 8.0.0
*/
zoom: {
mapZoomIn: 'Zoom chart',
mapZoomOut: 'Zoom out chart',
resetZoomButton: 'Reset zoom'
},
/**
* Range selector language options for accessibility.
*
* @since 8.0.0
*/
rangeSelector: {
minInputLabel: 'Select start date.',
maxInputLabel: 'Select end date.',
buttonText: 'Select range {buttonText}'
},
/**
* Accessibility language options for the data table.
*
* @since 8.0.0
*/
table: {
viewAsDataTableButtonText: 'View as data table, {chartTitle}',
tableSummary: 'Table representation of chart.'
},
/**
* Default announcement for new data in charts. If addPoint or
* addSeries is used, and only one series/point is added, the
* `newPointAnnounce` and `newSeriesAnnounce` strings are used.
* The `...Single` versions will be used if there is only one chart
* on the page, and the `...Multiple` versions will be used if there
* are multiple charts on the page. For all other new data events,
* the `newDataAnnounce` string will be used.
*
* @since 7.1.0
*/
announceNewData: {
newDataAnnounce: 'Updated data for chart {chartTitle}',
newSeriesAnnounceSingle: 'New data series: {seriesDesc}',
newPointAnnounceSingle: 'New data point: {pointDesc}',
newSeriesAnnounceMultiple: 'New data series in chart {chartTitle}: {seriesDesc}',
newPointAnnounceMultiple: 'New data point in chart {chartTitle}: {pointDesc}'
},
/**
* Descriptions of lesser known series types. The relevant
* description is added to the screen reader information region
* when these series types are used.
*
* @since 6.0.6
*/
seriesTypeDescriptions: {
boxplot: 'Box plot charts are typically used to display ' +
'groups of statistical data. Each data point in the ' +
'chart can have up to 5 values: minimum, lower quartile, ' +
'median, upper quartile, and maximum.',
arearange: 'Arearange charts are line charts displaying a ' +
'range between a lower and higher value for each point.',
areasplinerange: 'These charts are line charts displaying a ' +
'range between a lower and higher value for each point.',
bubble: 'Bubble charts are scatter charts where each data ' +
'point also has a size value.',
columnrange: 'Columnrange charts are column charts ' +
'displaying a range between a lower and higher value for ' +
'each point.',
errorbar: 'Errorbar series are used to display the ' +
'variability of the data.',
funnel: 'Funnel charts are used to display reduction of data ' +
'in stages.',
pyramid: 'Pyramid charts consist of a single pyramid with ' +
'item heights corresponding to each point value.',
waterfall: 'A waterfall chart is a column chart where each ' +
'column contributes towards a total end value.'
},
/**
* Chart type description strings. This is added to the chart
* information region.
*
* If there is only a single series type used in the chart, we use
* the format string for the series type, or default if missing.
* There is one format string for cases where there is only a single
* series in the chart, and one for multiple series of the same
* type.
*
* @since 6.0.6
*/
chartTypes: {
/* eslint-disable max-len */
emptyChart: 'Empty chart',
mapTypeDescription: 'Map of {mapTitle} with {numSeries} data series.',
unknownMap: 'Map of unspecified region with {numSeries} data series.',
combinationChart: 'Combination chart with {numSeries} data series.',
defaultSingle: 'Chart with {numPoints} data {#plural(numPoints, points, point)}.',
defaultMultiple: 'Chart with {numSeries} data series.',
splineSingle: 'Line chart with {numPoints} data {#plural(numPoints, points, point)}.',
splineMultiple: 'Line chart with {numSeries} lines.',
lineSingle: 'Line chart with {numPoints} data {#plural(numPoints, points, point)}.',
lineMultiple: 'Line chart with {numSeries} lines.',
columnSingle: 'Bar chart with {numPoints} {#plural(numPoints, bars, bar)}.',
columnMultiple: 'Bar chart with {numSeries} data series.',
barSingle: 'Bar chart with {numPoints} {#plural(numPoints, bars, bar)}.',
barMultiple: 'Bar chart with {numSeries} data series.',
pieSingle: 'Pie chart with {numPoints} {#plural(numPoints, slices, slice)}.',
pieMultiple: 'Pie chart with {numSeries} pies.',
scatterSingle: 'Scatter chart with {numPoints} {#plural(numPoints, points, point)}.',
scatterMultiple: 'Scatter chart with {numSeries} data series.',
boxplotSingle: 'Boxplot with {numPoints} {#plural(numPoints, boxes, box)}.',
boxplotMultiple: 'Boxplot with {numSeries} data series.',
bubbleSingle: 'Bubble chart with {numPoints} {#plural(numPoints, bubbles, bubble)}.',
bubbleMultiple: 'Bubble chart with {numSeries} data series.'
},
/**
* Axis description format strings.
*
* @since 6.0.6
*/
axis: {
/* eslint-disable max-len */
xAxisDescriptionSingular: 'The chart has 1 X axis displaying {names[0]}. {ranges[0]}',
xAxisDescriptionPlural: 'The chart has {numAxes} X axes displaying {#each(names, -1) }and {names[-1]}.',
yAxisDescriptionSingular: 'The chart has 1 Y axis displaying {names[0]}. {ranges[0]}',
yAxisDescriptionPlural: 'The chart has {numAxes} Y axes displaying {#each(names, -1) }and {names[-1]}.',
timeRangeDays: 'Range: {range} days.',
timeRangeHours: 'Range: {range} hours.',
timeRangeMinutes: 'Range: {range} minutes.',
timeRangeSeconds: 'Range: {range} seconds.',
rangeFromTo: 'Range: {rangeFrom} to {rangeTo}.',
rangeCategories: 'Range: {numCategories} categories.'
},
/**
* Exporting menu format strings for accessibility module.
*
* @since 6.0.6
*/
exporting: {
chartMenuLabel: 'Chart menu',
menuButtonLabel: 'View chart menu',
exportRegionLabel: 'Chart menu'
},
/**
* Lang configuration for different series types. For more dynamic
* control over the series element descriptions, see
* [accessibility.seriesDescriptionFormatter](#accessibility.seriesDescriptionFormatter).
*
* @since 6.0.6
*/
series: {
/**
* Lang configuration for the series main summary. Each series
* type has two modes:
*
* 1. This series type is the only series type used in the
* chart
*
* 2. This is a combination chart with multiple series types
*
* If a definition does not exist for the specific series type
* and mode, the 'default' lang definitions are used.
*
* @since 6.0.6
*/
summary: {
/* eslint-disable max-len */
'default': '{name}, series {ix} of {numSeries} with {numPoints} data {#plural(numPoints, points, point)}.',
defaultCombination: '{name}, series {ix} of {numSeries} with {numPoints} data {#plural(numPoints, points, point)}.',
line: '{name}, line {ix} of {numSeries} with {numPoints} data {#plural(numPoints, points, point)}.',
lineCombination: '{name}, series {ix} of {numSeries}. Line with {numPoints} data {#plural(numPoints, points, point)}.',
spline: '{name}, line {ix} of {numSeries} with {numPoints} data {#plural(numPoints, points, point)}.',
splineCombination: '{name}, series {ix} of {numSeries}. Line with {numPoints} data {#plural(numPoints, points, point)}.',
column: '{name}, bar series {ix} of {numSeries} with {numPoints} {#plural(numPoints, bars, bar)}.',
columnCombination: '{name}, series {ix} of {numSeries}. Bar series with {numPoints} {#plural(numPoints, bars, bar)}.',
bar: '{name}, bar series {ix} of {numSeries} with {numPoints} {#plural(numPoints, bars, bar)}.',
barCombination: '{name}, series {ix} of {numSeries}. Bar series with {numPoints} {#plural(numPoints, bars, bar)}.',
pie: '{name}, pie {ix} of {numSeries} with {numPoints} {#plural(numPoints, slices, slice)}.',
pieCombination: '{name}, series {ix} of {numSeries}. Pie with {numPoints} {#plural(numPoints, slices, slice)}.',
scatter: '{name}, scatter plot {ix} of {numSeries} with {numPoints} {#plural(numPoints, points, point)}.',
scatterCombination: '{name}, series {ix} of {numSeries}, scatter plot with {numPoints} {#plural(numPoints, points, point)}.',
boxplot: '{name}, boxplot {ix} of {numSeries} with {numPoints} {#plural(numPoints, boxes, box)}.',
boxplotCombination: '{name}, series {ix} of {numSeries}. Boxplot with {numPoints} {#plural(numPoints, boxes, box)}.',
bubble: '{name}, bubble series {ix} of {numSeries} with {numPoints} {#plural(numPoints, bubbles, bubble)}.',
bubbleCombination: '{name}, series {ix} of {numSeries}. Bubble series with {numPoints} {#plural(numPoints, bubbles, bubble)}.',
map: '{name}, map {ix} of {numSeries} with {numPoints} {#plural(numPoints, areas, area)}.',
mapCombination: '{name}, series {ix} of {numSeries}. Map with {numPoints} {#plural(numPoints, areas, area)}.',
mapline: '{name}, line {ix} of {numSeries} with {numPoints} data {#plural(numPoints, points, point)}.',
maplineCombination: '{name}, series {ix} of {numSeries}. Line with {numPoints} data {#plural(numPoints, points, point)}.',
mapbubble: '{name}, bubble series {ix} of {numSeries} with {numPoints} {#plural(numPoints, bubbles, bubble)}.',
mapbubbleCombination: '{name}, series {ix} of {numSeries}. Bubble series with {numPoints} {#plural(numPoints, bubbles, bubble)}.'
},
/**
* User supplied description text. This is added in the point
* comment description by default if present.
*
* @since 6.0.6
*/
description: '{description}',
/**
* xAxis description for series if there are multiple xAxes in
* the chart.
*
* @since 6.0.6
*/
xAxisDescription: 'X axis, {name}',
/**
* yAxis description for series if there are multiple yAxes in
* the chart.
*
* @since 6.0.6
*/
yAxisDescription: 'Y axis, {name}',
/**
* Description for the value of null points.
*
* @since 8.0.0
*/
nullPointValue: 'No value',
/**
* Description for annotations on a point, as it is made available
* to assistive technology.
*
* @since 8.0.1
*/
pointAnnotationsDescription: '{Annotation: #each(annotations). }'
}
}
};
export default langOptions;

View File

@@ -0,0 +1,793 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Default options for accessibility.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
/**
* Formatter callback for the accessibility announcement.
*
* @callback Highcharts.AccessibilityAnnouncementFormatter
*
* @param {Array<Highcharts.Series>} updatedSeries
* Array of all series that received updates. If an announcement is already
* queued, the series that received updates for that announcement are also
* included in this array.
*
* @param {Highcharts.Series} [addedSeries]
* This is provided if {@link Highcharts.Chart#addSeries} was called, and there
* is a new series. In that case, this argument is a reference to the new
* series.
*
* @param {Highcharts.Point} [addedPoint]
* This is provided if {@link Highcharts.Series#addPoint} was called, and there
* is a new point. In that case, this argument is a reference to the new point.
*
* @return {false|string}
* The function should return a string with the text to announce to the user.
* Return empty string to not announce anything. Return `false` to use the
* default announcement format.
*/
/**
* @interface Highcharts.PointAccessibilityOptionsObject
*/ /**
* Provide a description of the data point, announced to screen readers.
* @name Highcharts.PointAccessibilityOptionsObject#description
* @type {string|undefined}
* @requires modules/accessibility
* @since 7.1.0
*/
/* *
* @interface Highcharts.PointOptionsObject in parts/Point.ts
*/ /**
* @name Highcharts.PointOptionsObject#accessibility
* @type {Highcharts.PointAccessibilityOptionsObject|undefined}
* @requires modules/accessibility
* @since 7.1.0
*/
/**
* @callback Highcharts.ScreenReaderClickCallbackFunction
*
* @param {global.MouseEvent} evt
* Mouse click event
*
* @return {void}
*/
/**
* Creates a formatted string for the screen reader module.
*
* @callback Highcharts.ScreenReaderFormatterCallbackFunction<T>
*
* @param {T} context
* Context to format
*
* @return {string}
* Formatted string for the screen reader module.
*/
var options = {
/**
* Options for configuring accessibility for the chart. Requires the
* [accessibility module](https://code.highcharts.com/modules/accessibility.js)
* to be loaded. For a description of the module and information
* on its features, see
* [Highcharts Accessibility](https://www.highcharts.com/docs/chart-concepts/accessibility).
*
* @since 5.0.0
* @requires modules/accessibility
* @optionparent accessibility
*/
accessibility: {
/**
* Enable accessibility functionality for the chart.
*
* @since 5.0.0
*/
enabled: true,
/**
* Accessibility options for the screen reader information sections
* added before and after the chart.
*
* @since 8.0.0
*/
screenReaderSection: {
/**
* Function to run upon clicking the "View as Data Table" link in
* the screen reader region.
*
* By default Highcharts will insert and set focus to a data table
* representation of the chart.
*
* @type {Highcharts.ScreenReaderClickCallbackFunction}
* @since 8.0.0
* @apioption accessibility.screenReaderSection.onViewDataTableClick
*/
/**
* Function to run upon clicking the "Play as sound" button in
* the screen reader region.
*
* By default Highcharts will call the `chart.sonify` function.
*
* @type {Highcharts.ScreenReaderClickCallbackFunction}
* @since 8.0.1
* @apioption accessibility.screenReaderSection.onPlayAsSoundClick
*/
/**
* A formatter function to create the HTML contents of the hidden
* screen reader information region before the chart. Receives one
* argument, `chart`, referring to the chart object. Should return a
* string with the HTML content of the region. By default this
* returns an automatic description of the chart based on
* [beforeChartFormat](#accessibility.screenReaderSection.beforeChartFormat).
*
* @type {Highcharts.ScreenReaderFormatterCallbackFunction<Highcharts.Chart>}
* @since 8.0.0
* @apioption accessibility.screenReaderSection.beforeChartFormatter
*/
/**
* Format for the screen reader information region before the chart.
* Supported HTML tags are `<h1-7>`, `<p>`, `<div>`, `<a>`, `<ul>`,
* `<ol>`, `<li>`, and `<button>`. Attributes are not supported,
* except for id on `<div>`, `<a>`, and `<button>`. Id is required
* on `<a>` and `<button>` in the format `<tag id="abcd">`. Numbers,
* lower- and uppercase letters, "-" and "#" are valid characters in
* IDs.
*
* @since 8.0.0
*/
beforeChartFormat: '<h5>{chartTitle}</h5>' +
'<div>{typeDescription}</div>' +
'<div>{chartSubtitle}</div>' +
'<div>{chartLongdesc}</div>' +
'<div>{playAsSoundButton}</div>' +
'<div>{viewTableButton}</div>' +
'<div>{xAxisDescription}</div>' +
'<div>{yAxisDescription}</div>' +
'<div>{annotationsTitle}{annotationsList}</div>',
/**
* A formatter function to create the HTML contents of the hidden
* screen reader information region after the chart. Analogous to
* [beforeChartFormatter](#accessibility.screenReaderSection.beforeChartFormatter).
*
* @type {Highcharts.ScreenReaderFormatterCallbackFunction<Highcharts.Chart>}
* @since 8.0.0
* @apioption accessibility.screenReaderSection.afterChartFormatter
*/
/**
* Format for the screen reader information region after the chart.
* Analogous to [beforeChartFormat](#accessibility.screenReaderSection.beforeChartFormat).
*
* @since 8.0.0
*/
afterChartFormat: '{endOfChartMarker}',
/**
* Date format to use to describe range of datetime axes.
*
* For an overview of the replacement codes, see
* [dateFormat](/class-reference/Highcharts#dateFormat).
*
* @see [point.dateFormat](#accessibility.point.dateFormat)
*
* @since 8.0.0
*/
axisRangeDateFormat: '%Y-%m-%d %H:%M:%S'
},
/**
* Accessibility options global to all data series. Individual series
* can also have specific [accessibility options](#plotOptions.series.accessibility)
* set.
*
* @since 8.0.0
*/
series: {
/**
* Formatter function to use instead of the default for series
* descriptions. Receives one argument, `series`, referring to the
* series to describe. Should return a string with the description
* of the series for a screen reader user. If `false` is returned,
* the default formatter will be used for that series.
*
* @see [series.description](#plotOptions.series.description)
*
* @type {Highcharts.ScreenReaderFormatterCallbackFunction<Highcharts.Series>}
* @since 8.0.0
* @apioption accessibility.series.descriptionFormatter
*/
/**
* Whether or not to add series descriptions to charts with a single
* series.
*
* @since 8.0.0
*/
describeSingleSeries: false,
/**
* When a series contains more points than this, we no longer expose
* information about individual points to screen readers.
*
* Set to `false` to disable.
*
* @type {boolean|number}
* @since 8.0.0
*/
pointDescriptionEnabledThreshold: 200
},
/**
* Options for descriptions of individual data points.
*
* @since 8.0.0
*/
point: {
/**
* Format to use for describing the values of data points
* to assistive technology - including screen readers.
* The point context is available as `{point}`.
*
* Additionally, the series name, annotation info, and
* description added in `point.accessibility.description`
* is added by default if relevant. To override this, use the
* [accessibility.point.descriptionFormatter](#accessibility.point.descriptionFormatter)
* option.
*
* @see [point.accessibility.description](#series.line.data.accessibility.description)
* @see [accessibility.point.descriptionFormatter](#accessibility.point.descriptionFormatter)
*
* @type {string}
* @since 8.0.1
*/
valueDescriptionFormat: '{index}. {xDescription}{separator}{value}.'
/**
* Date format to use for points on datetime axes when describing
* them to screen reader users.
*
* Defaults to the same format as in tooltip.
*
* For an overview of the replacement codes, see
* [dateFormat](/class-reference/Highcharts#dateFormat).
*
* @see [dateFormatter](#accessibility.point.dateFormatter)
*
* @type {string}
* @since 8.0.0
* @apioption accessibility.point.dateFormat
*/
/**
* Formatter function to determine the date/time format used with
* points on datetime axes when describing them to screen reader
* users. Receives one argument, `point`, referring to the point
* to describe. Should return a date format string compatible with
* [dateFormat](/class-reference/Highcharts#dateFormat).
*
* @see [dateFormat](#accessibility.point.dateFormat)
*
* @type {Highcharts.ScreenReaderFormatterCallbackFunction<Highcharts.Point>}
* @since 8.0.0
* @apioption accessibility.point.dateFormatter
*/
/**
* Prefix to add to the values in the point descriptions. Uses
* [tooltip.valuePrefix](#tooltip.valuePrefix) if not defined.
*
* @type {string}
* @since 8.0.0
* @apioption accessibility.point.valuePrefix
*/
/**
* Suffix to add to the values in the point descriptions. Uses
* [tooltip.valueSuffix](#tooltip.valueSuffix) if not defined.
*
* @type {string}
* @since 8.0.0
* @apioption accessibility.point.valueSuffix
*/
/**
* Decimals to use for the values in the point descriptions. Uses
* [tooltip.valueDecimals](#tooltip.valueDecimals) if not defined.
*
* @type {number}
* @since 8.0.0
* @apioption accessibility.point.valueDecimals
*/
/**
* Formatter function to use instead of the default for point
* descriptions.
*
* Receives one argument, `point`, referring to the point to
* describe. Should return a string with the description of the
* point for a screen reader user. If `false` is returned, the
* default formatter will be used for that point.
*
* Note: Prefer using [accessibility.point.valueDescriptionFormat](#accessibility.point.valueDescriptionFormat)
* instead if possible, as default functionality such as describing
* annotations will be preserved.
*
* @see [accessibility.point.valueDescriptionFormat](#accessibility.point.valueDescriptionFormat)
* @see [point.accessibility.description](#series.line.data.accessibility.description)
*
* @type {Highcharts.ScreenReaderFormatterCallbackFunction<Highcharts.Point>}
* @since 8.0.0
* @apioption accessibility.point.descriptionFormatter
*/
},
/**
* Amount of landmarks/regions to create for screen reader users. More
* landmarks can make navigation with screen readers easier, but can
* be distracting if there are lots of charts on the page. Three modes
* are available:
* - `all`: Adds regions for all series, legend, menu, information
* region.
* - `one`: Adds a single landmark per chart.
* - `disabled`: No landmarks are added.
*
* @since 7.1.0
* @validvalue ["all", "one", "disabled"]
*/
landmarkVerbosity: 'all',
/**
* Link the chart to an HTML element describing the contents of the
* chart.
*
* It is always recommended to describe charts using visible text, to
* improve SEO as well as accessibility for users with disabilities.
* This option lets an HTML element with a description be linked to the
* chart, so that screen reader users can connect the two.
*
* By setting this option to a string, Highcharts runs the string as an
* HTML selector query on the entire document. If there is only a single
* match, this element is linked to the chart. The content of the linked
* element will be included in the chart description for screen reader
* users.
*
* By default, the chart looks for an adjacent sibling element with the
* `highcharts-description` class.
*
* The feature can be disabled by setting the option to an empty string,
* or overridden by providing the
* [accessibility.description](#accessibility.description) option.
* Alternatively, the HTML element to link can be passed in directly as
* an HTML node.
*
* If you need the description to be part of the exported image,
* consider using the [caption](#caption) feature.
*
* If you need the description to be hidden visually, use the
* [accessibility.description](#accessibility.description) option.
*
* @see [caption](#caption)
* @see [description](#accessibility.description)
* @see [typeDescription](#accessibility.typeDescription)
*
* @sample highcharts/accessibility/accessible-line
* Accessible line chart
*
* @type {string|Highcharts.HTMLDOMElement}
* @since 8.0.0
*/
linkedDescription: '*[data-highcharts-chart="{index}"] + .highcharts-description',
/**
* A hook for adding custom components to the accessibility module.
* Should be an object mapping component names to instances of classes
* inheriting from the Highcharts.AccessibilityComponent base class.
* Remember to add the component to the
* [keyboardNavigation.order](#accessibility.keyboardNavigation.order)
* for the keyboard navigation to be usable.
*
* @sample highcharts/accessibility/custom-component
* Custom accessibility component
*
* @type {*}
* @since 7.1.0
* @apioption accessibility.customComponents
*/
/**
* Theme to apply to the chart when Windows High Contrast Mode is
* detected. By default, a high contrast theme matching the high
* contrast system system colors is used.
*
* @type {*}
* @since 7.1.3
* @apioption accessibility.highContrastTheme
*/
/**
* A text description of the chart.
*
* **Note: Prefer using [linkedDescription](#accessibility.linkedDescription)
* or [caption](#caption.text) instead.**
*
* If the Accessibility module is loaded, this option is included by
* default as a long description of the chart in the hidden screen
* reader information region.
*
* Note: Since Highcharts now supports captions and linked descriptions,
* it is preferred to define the description using those methods, as a
* visible caption/description benefits all users. If the
* `accessibility.description` option is defined, the linked description
* is ignored, and the caption is hidden from screen reader users.
*
* @see [linkedDescription](#accessibility.linkedDescription)
* @see [caption](#caption)
* @see [typeDescription](#accessibility.typeDescription)
*
* @type {string}
* @since 5.0.0
* @apioption accessibility.description
*/
/**
* A text description of the chart type.
*
* If the Accessibility module is loaded, this will be included in the
* description of the chart in the screen reader information region.
*
* Highcharts will by default attempt to guess the chart type, but for
* more complex charts it is recommended to specify this property for
* clarity.
*
* @type {string}
* @since 5.0.0
* @apioption accessibility.typeDescription
*/
/**
* Options for keyboard navigation.
*
* @declare Highcharts.KeyboardNavigationOptionsObject
* @since 5.0.0
*/
keyboardNavigation: {
/**
* Enable keyboard navigation for the chart.
*
* @since 5.0.0
*/
enabled: true,
/**
* Options for the focus border drawn around elements while
* navigating through them.
*
* @sample highcharts/accessibility/custom-focus
* Custom focus ring
*
* @declare Highcharts.KeyboardNavigationFocusBorderOptionsObject
* @since 6.0.3
*/
focusBorder: {
/**
* Enable/disable focus border for chart.
*
* @since 6.0.3
*/
enabled: true,
/**
* Hide the browser's default focus indicator.
*
* @since 6.0.4
*/
hideBrowserFocusOutline: true,
/**
* Style options for the focus border drawn around elements
* while navigating through them. Note that some browsers in
* addition draw their own borders for focused elements. These
* automatic borders can not be styled by Highcharts.
*
* In styled mode, the border is given the
* `.highcharts-focus-border` class.
*
* @type {Highcharts.CSSObject}
* @since 6.0.3
*/
style: {
/** @internal */
color: '#335cad',
/** @internal */
lineWidth: 2,
/** @internal */
borderRadius: 3
},
/**
* Focus border margin around the elements.
*
* @since 6.0.3
*/
margin: 2
},
/**
* Order of tab navigation in the chart. Determines which elements
* are tabbed to first. Available elements are: `series`, `zoom`,
* `rangeSelector`, `chartMenu`, `legend`. In addition, any custom
* components can be added here.
*
* @type {Array<string>}
* @since 7.1.0
*/
order: ['series', 'zoom', 'rangeSelector', 'legend', 'chartMenu'],
/**
* Whether or not to wrap around when reaching the end of arrow-key
* navigation for an element in the chart.
* @since 7.1.0
*/
wrapAround: true,
/**
* Options for the keyboard navigation of data points and series.
*
* @declare Highcharts.KeyboardNavigationSeriesNavigationOptionsObject
* @since 8.0.0
*/
seriesNavigation: {
/**
* Set the keyboard navigation mode for the chart. Can be
* "normal" or "serialize". In normal mode, left/right arrow
* keys move between points in a series, while up/down arrow
* keys move between series. Up/down navigation acts
* intelligently to figure out which series makes sense to move
* to from any given point.
*
* In "serialize" mode, points are instead navigated as a single
* list. Left/right behaves as in "normal" mode. Up/down arrow
* keys will behave like left/right. This can be useful for
* unifying navigation behavior with/without screen readers
* enabled.
*
* @type {string}
* @default normal
* @since 8.0.0
* @validvalue ["normal", "serialize"]
* @apioption accessibility.keyboardNavigation.seriesNavigation.mode
*/
/**
* Skip null points when navigating through points with the
* keyboard.
*
* @since 8.0.0
*/
skipNullPoints: true,
/**
* When a series contains more points than this, we no longer
* allow keyboard navigation for it.
*
* Set to `false` to disable.
*
* @type {boolean|number}
* @since 8.0.0
*/
pointNavigationEnabledThreshold: false
}
},
/**
* Options for announcing new data to screen reader users. Useful
* for dynamic data applications and drilldown.
*
* Keep in mind that frequent announcements will not be useful to
* users, as they won't have time to explore the new data. For these
* applications, consider making snapshots of the data accessible, and
* do the announcements in batches.
*
* @declare Highcharts.AccessibilityAnnounceNewDataOptionsObject
* @since 7.1.0
*/
announceNewData: {
/**
* Optional formatter callback for the announcement. Receives
* up to three arguments. The first argument is always an array
* of all series that received updates. If an announcement is
* already queued, the series that received updates for that
* announcement are also included in this array. The second
* argument is provided if `chart.addSeries` was called, and
* there is a new series. In that case, this argument is a
* reference to the new series. The third argument, similarly,
* is provided if `series.addPoint` was called, and there is a
* new point. In that case, this argument is a reference to the
* new point.
*
* The function should return a string with the text to announce
* to the user. Return empty string to not announce anything.
* Return `false` to use the default announcement format.
*
* @sample highcharts/accessibility/custom-dynamic
* High priority live alerts
*
* @type {Highcharts.AccessibilityAnnouncementFormatter}
* @apioption accessibility.announceNewData.announcementFormatter
*/
/**
* Enable announcing new data to screen reader users
* @sample highcharts/accessibility/accessible-dynamic
* Dynamic data accessible
*/
enabled: false,
/**
* Minimum interval between announcements in milliseconds. If
* new data arrives before this amount of time has passed, it is
* queued for announcement. If another new data event happens
* while an announcement is queued, the queued announcement is
* dropped, and the latest announcement is queued instead. Set
* to 0 to allow all announcements, but be warned that frequent
* announcements are disturbing to users.
*/
minAnnounceInterval: 5000,
/**
* Choose whether or not the announcements should interrupt the
* screen reader. If not enabled, the user will be notified once
* idle. It is recommended not to enable this setting unless
* there is a specific reason to do so.
*/
interruptUser: false
}
},
/**
* Accessibility options for a data point.
*
* @declare Highcharts.PointAccessibilityOptionsObject
* @since 7.1.0
* @apioption series.line.data.accessibility
*/
/**
* Provide a description of the data point, announced to screen readers.
*
* @type {string}
* @since 7.1.0
* @apioption series.line.data.accessibility.description
*/
/**
* Accessibility options for a series.
*
* @declare Highcharts.SeriesAccessibilityOptionsObject
* @since 7.1.0
* @requires modules/accessibility
* @apioption plotOptions.series.accessibility
*/
/**
* Enable/disable accessibility functionality for a specific series.
*
* @type {boolean}
* @since 7.1.0
* @apioption plotOptions.series.accessibility.enabled
*/
/**
* Provide a description of the series, announced to screen readers.
*
* @type {string}
* @since 7.1.0
* @apioption plotOptions.series.accessibility.description
*/
/**
* Formatter function to use instead of the default for point
* descriptions. Same as `accessibility.point.descriptionFormatter`, but for
* a single series.
*
* @see [accessibility.point.descriptionFormatter](#accessibility.point.descriptionFormatter)
*
* @type {Highcharts.ScreenReaderFormatterCallbackFunction<Highcharts.Point>}
* @since 7.1.0
* @apioption plotOptions.series.accessibility.pointDescriptionFormatter
*/
/**
* Expose only the series element to screen readers, not its points.
*
* @type {boolean}
* @since 7.1.0
* @apioption plotOptions.series.accessibility.exposeAsGroupOnly
*/
/**
* Keyboard navigation for a series
*
* @declare Highcharts.SeriesAccessibilityKeyboardNavigationOptionsObject
* @since 7.1.0
* @apioption plotOptions.series.accessibility.keyboardNavigation
*/
/**
* Enable/disable keyboard navigation support for a specific series.
*
* @type {boolean}
* @since 7.1.0
* @apioption plotOptions.series.accessibility.keyboardNavigation.enabled
*/
/**
* Accessibility options for an annotation label.
*
* @declare Highcharts.AnnotationLabelAccessibilityOptionsObject
* @since 8.0.1
* @requires modules/accessibility
* @apioption annotations.labelOptions.accessibility
*/
/**
* Description of an annotation label for screen readers and other assistive
* technology.
*
* @type {string}
* @since 8.0.1
* @apioption annotations.labelOptions.accessibility.description
*/
/**
* Accessibility options for an axis. Requires the accessibility module.
*
* @declare Highcharts.AxisAccessibilityOptionsObject
* @since 7.1.0
* @requires modules/accessibility
* @apioption xAxis.accessibility
*/
/**
* Enable axis accessibility features, including axis information in the
* screen reader information region. If this is disabled on the xAxis, the
* x values are not exposed to screen readers for the individual data points
* by default.
*
* @type {boolean}
* @since 7.1.0
* @apioption xAxis.accessibility.enabled
*/
/**
* Description for an axis to expose to screen reader users.
*
* @type {string}
* @since 7.1.0
* @apioption xAxis.accessibility.description
*/
/**
* Range description for an axis. Overrides the default range description.
* Set to empty to disable range description for this axis.
*
* @type {string}
* @since 7.1.0
* @apioption xAxis.accessibility.rangeDescription
*/
/**
* @optionparent legend
*/
legend: {
/**
* Accessibility options for the legend. Requires the Accessibility
* module.
*
* @since 7.1.0
* @requires modules/accessibility
*/
accessibility: {
/**
* Enable accessibility support for the legend.
*
* @since 7.1.0
*/
enabled: true,
/**
* Options for keyboard navigation for the legend.
*
* @since 7.1.0
* @requires modules/accessibility
*/
keyboardNavigation: {
/**
* Enable keyboard navigation for the legend.
*
* @see [accessibility.keyboardNavigation](#accessibility.keyboardNavigation.enabled)
*
* @since 7.1.0
*/
enabled: true
}
}
},
/**
* @optionparent exporting
*/
exporting: {
/**
* Accessibility options for the exporting menu. Requires the
* Accessibility module.
*
* @since 7.1.0
* @requires modules/accessibility
*/
accessibility: {
/**
* Enable accessibility support for the export menu.
*
* @since 7.1.0
*/
enabled: true
}
}
};
export default options;

View File

@@ -0,0 +1,51 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Create announcer to speak messages to screen readers and other AT.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../../parts/Globals.js';
import DOMElementProvider from './DOMElementProvider.js';
import HTMLUtilities from './htmlUtilities.js';
var visuallyHideElement = HTMLUtilities.visuallyHideElement;
var Announcer = /** @class */ (function () {
function Announcer(chart, type) {
this.chart = chart;
this.domElementProvider = new DOMElementProvider();
this.announceRegion = this.addAnnounceRegion(type);
}
Announcer.prototype.destroy = function () {
this.domElementProvider.destroyCreatedElements();
};
Announcer.prototype.announce = function (message) {
var _this = this;
this.announceRegion.innerHTML = message;
// Delete contents after a little while to avoid user finding the live
// region in the DOM.
if (this.clearAnnouncementRegionTimer) {
clearTimeout(this.clearAnnouncementRegionTimer);
}
this.clearAnnouncementRegionTimer = setTimeout(function () {
_this.announceRegion.innerHTML = '';
delete _this.clearAnnouncementRegionTimer;
}, 1000);
};
Announcer.prototype.addAnnounceRegion = function (type) {
var chartContainer = this.chart.renderTo;
var div = this.domElementProvider.createElement('div');
div.setAttribute('aria-hidden', false);
div.setAttribute('aria-live', type);
visuallyHideElement(div);
chartContainer.insertBefore(div, chartContainer.firstChild);
return div;
};
return Announcer;
}());
H.Announcer = Announcer;
export default Announcer;

View File

@@ -0,0 +1,50 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Class that can keep track of elements added to DOM and clean them up on
* destroy.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../../parts/Globals.js';
var doc = H.win.document;
import U from '../../../parts/Utilities.js';
var extend = U.extend;
import HTMLUtilities from './htmlUtilities.js';
var removeElement = HTMLUtilities.removeElement;
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* @private
* @class
*/
var DOMElementProvider = function () {
this.elements = [];
};
extend(DOMElementProvider.prototype, {
/**
* Create an element and keep track of it for later removal.
* Same args as document.createElement
* @private
*/
createElement: function () {
var el = doc.createElement.apply(doc, arguments);
this.elements.push(el);
return el;
},
/**
* Destroy all created elements, removing them from the DOM.
* @private
*/
destroyCreatedElements: function () {
this.elements.forEach(function (element) {
removeElement(element);
});
this.elements = [];
}
});
export default DOMElementProvider;

View File

@@ -0,0 +1,48 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Class that can keep track of events added, and clean them up on destroy.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../../parts/Globals.js';
import U from '../../../parts/Utilities.js';
var addEvent = U.addEvent, extend = U.extend;
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* @private
* @class
*/
var EventProvider = function () {
this.eventRemovers = [];
};
extend(EventProvider.prototype, {
/**
* Add an event to an element and keep track of it for later removal.
* Same args as Highcharts.addEvent.
* @private
* @return {Function}
*/
addEvent: function () {
var remover = addEvent.apply(H, arguments);
this.eventRemovers.push(remover);
return remover;
},
/**
* Remove all added events.
* @private
* @return {void}
*/
removeAddedEvents: function () {
this.eventRemovers.forEach(function (remover) {
remover();
});
this.eventRemovers = [];
}
});
export default EventProvider;

View File

@@ -0,0 +1,147 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Utils for dealing with charts.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import HTMLUtilities from './htmlUtilities.js';
var stripHTMLTags = HTMLUtilities.stripHTMLTagsFromString;
import U from '../../../parts/Utilities.js';
var find = U.find;
/* eslint-disable valid-jsdoc */
/**
* @return {string}
*/
function getChartTitle(chart) {
return stripHTMLTags(chart.options.title.text ||
chart.langFormat('accessibility.defaultChartTitle', { chart: chart }));
}
/**
* @param {Highcharts.Axis} axis
* @return {string}
*/
function getAxisDescription(axis) {
return stripHTMLTags(axis && (axis.userOptions && axis.userOptions.accessibility &&
axis.userOptions.accessibility.description ||
axis.axisTitle && axis.axisTitle.textStr ||
axis.options.id ||
axis.categories && 'categories' ||
axis.isDatetimeAxis && 'Time' ||
'values'));
}
/**
* Get the DOM element for the first point in the series.
* @private
* @param {Highcharts.Series} series
* The series to get element for.
* @return {Highcharts.HTMLDOMElement|Highcharts.SVGDOMElement|undefined}
* The DOM element for the point.
*/
function getSeriesFirstPointElement(series) {
if (series.points &&
series.points.length &&
series.points[0].graphic) {
return series.points[0].graphic.element;
}
}
/**
* Get the DOM element for the series that we put accessibility info on.
* @private
* @param {Highcharts.Series} series
* The series to get element for.
* @return {Highcharts.HTMLDOMElement|Highcharts.SVGDOMElement|undefined}
* The DOM element for the series
*/
function getSeriesA11yElement(series) {
var firstPointEl = getSeriesFirstPointElement(series);
return (firstPointEl &&
firstPointEl.parentNode || series.graph &&
series.graph.element || series.group &&
series.group.element); // Could be tracker series depending on series type
}
/**
* Remove aria-hidden from element. Also unhides parents of the element, and
* hides siblings that are not explicitly unhidden.
* @private
* @param {Highcharts.Chart} chart
* @param {Highcharts.HTMLDOMElement|Highcharts.SVGDOMElement} element
* @return {void}
*/
function unhideChartElementFromAT(chart, element) {
element.setAttribute('aria-hidden', false);
if (element === chart.renderTo || !element.parentNode) {
return;
}
// Hide siblings unless their hidden state is already explicitly set
Array.prototype.forEach.call(element.parentNode.childNodes, function (node) {
if (!node.hasAttribute('aria-hidden')) {
node.setAttribute('aria-hidden', true);
}
});
// Repeat for parent
unhideChartElementFromAT(chart, element.parentNode);
}
/**
* Hide series from screen readers.
* @private
* @param {Highcharts.Series} series
* The series to hide
* @return {void}
*/
function hideSeriesFromAT(series) {
var seriesEl = getSeriesA11yElement(series);
if (seriesEl) {
seriesEl.setAttribute('aria-hidden', true);
}
}
/**
* Get series objects by series name.
* @private
* @param {Highcharts.Chart} chart
* @param {string} name
* @return {Array<Highcharts.Series>}
*/
function getSeriesFromName(chart, name) {
if (!name) {
return chart.series;
}
return (chart.series || []).filter(function (s) {
return s.name === name;
});
}
/**
* Get point in a series from x/y values.
* @private
* @param {Array<Highcharts.Series>} series
* @param {number} x
* @param {number} y
* @return {Highcharts.Point|undefined}
*/
function getPointFromXY(series, x, y) {
var i = series.length, res;
while (i--) {
res = find(series[i].points || [], function (p) {
return p.x === x && p.y === y;
});
if (res) {
return res;
}
}
}
var ChartUtilities = {
getChartTitle: getChartTitle,
getAxisDescription: getAxisDescription,
getPointFromXY: getPointFromXY,
getSeriesFirstPointElement: getSeriesFirstPointElement,
getSeriesFromName: getSeriesFromName,
getSeriesA11yElement: getSeriesA11yElement,
unhideChartElementFromAT: unhideChartElementFromAT,
hideSeriesFromAT: hideSeriesFromAT
};
export default ChartUtilities;

View File

@@ -0,0 +1,173 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Utility functions for accessibility module.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import U from '../../../parts/Utilities.js';
var merge = U.merge;
import H from '../../../parts/Globals.js';
var win = H.win, doc = win.document;
/* eslint-disable valid-jsdoc */
/**
* @private
* @param {Highcharts.HTMLDOMElement} el
* @param {string} className
* @return {void}
*/
function addClass(el, className) {
if (el.classList) {
el.classList.add(className);
}
else if (el.className.indexOf(className) < 0) {
// Note: Dumb check for class name exists, should be fine for practical
// use cases, but will return false positives if the element has a class
// that contains the className.
el.className += className;
}
}
/**
* @private
* @param {string} str
* @return {string}
*/
function escapeStringForHTML(str) {
return str
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#x27;')
.replace(/\//g, '&#x2F;');
}
/**
* Get an element by ID
* @param {string} id
* @private
* @return {Highcharts.HTMLDOMElement|Highcharts.SVGDOMElement|null}
*/
function getElement(id) {
return doc.getElementById(id);
}
/**
* Get a fake mouse event of a given type
* @param {string} type
* @private
* @return {global.MouseEvent}
*/
function getFakeMouseEvent(type) {
if (typeof win.MouseEvent === 'function') {
return new win.MouseEvent(type);
}
// No MouseEvent support, try using initMouseEvent
if (doc.createEvent) {
var evt = doc.createEvent('MouseEvent');
if (evt.initMouseEvent) {
evt.initMouseEvent(type, true, // Bubble
true, // Cancel
win, // View
type === 'click' ? 1 : 0, // Detail
// Coords
0, 0, 0, 0,
// Pressed keys
false, false, false, false, 0, // button
null // related target
);
return evt;
}
}
return { type: type };
}
/**
* Remove an element from the DOM.
* @private
* @param {Highcharts.HTMLDOMElement|Highcharts.SVGDOMElement} [element]
* @return {void}
*/
function removeElement(element) {
if (element && element.parentNode) {
element.parentNode.removeChild(element);
}
}
/**
* Utility function. Reverses child nodes of a DOM element.
* @private
* @param {Highcharts.HTMLDOMElement|Highcharts.SVGDOMElement} node
* @return {void}
*/
function reverseChildNodes(node) {
var i = node.childNodes.length;
while (i--) {
node.appendChild(node.childNodes[i]);
}
}
/**
* Set attributes on element. Set to null to remove attribute.
* @private
* @param {Highcharts.HTMLDOMElement|Highcharts.SVGDOMElement} el
* @param {Highcharts.HTMLAttributes|Highcharts.SVGAttributes} attrs
* @return {void}
*/
function setElAttrs(el, attrs) {
Object.keys(attrs).forEach(function (attr) {
var val = attrs[attr];
if (val === null) {
el.removeAttribute(attr);
}
else {
var cleanedVal = escapeStringForHTML('' + val);
el.setAttribute(attr, cleanedVal);
}
});
}
/**
* Used for aria-label attributes, painting on a canvas will fail if the
* text contains tags.
* @private
* @param {string} str
* @return {string}
*/
function stripHTMLTagsFromString(str) {
return typeof str === 'string' ?
str.replace(/<\/?[^>]+(>|$)/g, '') : str;
}
/**
* Utility function for hiding an element visually, but still keeping it
* available to screen reader users.
* @private
* @param {Highcharts.HTMLDOMElement} element
* @return {void}
*/
function visuallyHideElement(element) {
var hiddenStyle = {
position: 'absolute',
width: '1px',
height: '1px',
overflow: 'hidden',
whiteSpace: 'nowrap',
clip: 'rect(1px, 1px, 1px, 1px)',
marginTop: '-3px',
'-ms-filter': 'progid:DXImageTransform.Microsoft.Alpha(Opacity=1)',
filter: 'alpha(opacity=1)',
opacity: '0.01'
};
merge(true, element.style, hiddenStyle);
}
var HTMLUtilities = {
addClass: addClass,
escapeStringForHTML: escapeStringForHTML,
getElement: getElement,
getFakeMouseEvent: getFakeMouseEvent,
removeElement: removeElement,
reverseChildNodes: reverseChildNodes,
setElAttrs: setElAttrs,
stripHTMLTagsFromString: stripHTMLTagsFromString,
visuallyHideElement: visuallyHideElement
};
export default HTMLUtilities;

View File

@@ -0,0 +1,144 @@
/* *
*
* (c) 2010-2020 Highsoft AS
*
* Author: Sebastian Domas
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import U from '../parts/Utilities.js';
var correctFloat = U.correctFloat, isNumber = U.isNumber, merge = U.merge, seriesType = U.seriesType;
import derivedSeriesMixin from '../mixins/derived-series.js';
/* ************************************************************************** *
* BELL CURVE *
* ************************************************************************** */
/* eslint-disable valid-jsdoc */
/**
* @private
*/
function mean(data) {
var length = data.length, sum = data.reduce(function (sum, value) {
return (sum += value);
}, 0);
return length > 0 && sum / length;
}
/**
* @private
*/
function standardDeviation(data, average) {
var len = data.length, sum;
average = isNumber(average) ? average : mean(data);
sum = data.reduce(function (sum, value) {
var diff = value - average;
return (sum += diff * diff);
}, 0);
return len > 1 && Math.sqrt(sum / (len - 1));
}
/**
* @private
*/
function normalDensity(x, mean, standardDeviation) {
var translation = x - mean;
return Math.exp(-(translation * translation) /
(2 * standardDeviation * standardDeviation)) / (standardDeviation * Math.sqrt(2 * Math.PI));
}
/* eslint-enable valid-jsdoc */
/**
* Bell curve class
*
* @private
* @class
* @name Highcharts.seriesTypes.bellcurve
*
* @augments Highcharts.Series
*/
seriesType('bellcurve', 'areaspline'
/**
* A bell curve is an areaspline series which represents the probability
* density function of the normal distribution. It calculates mean and
* standard deviation of the base series data and plots the curve according
* to the calculated parameters.
*
* @sample {highcharts} highcharts/demo/bellcurve/
* Bell curve
*
* @extends plotOptions.areaspline
* @since 6.0.0
* @product highcharts
* @excluding boostThreshold, connectNulls, dragDrop, stacking,
* pointInterval, pointIntervalUnit
* @requires modules/bellcurve
* @optionparent plotOptions.bellcurve
*/
, {
/**
* This option allows to define the length of the bell curve. A unit of
* the length of the bell curve is standard deviation.
*
* @sample highcharts/plotoptions/bellcurve-intervals-pointsininterval
* Intervals and points in interval
*/
intervals: 3,
/**
* Defines how many points should be plotted within 1 interval. See
* `plotOptions.bellcurve.intervals`.
*
* @sample highcharts/plotoptions/bellcurve-intervals-pointsininterval
* Intervals and points in interval
*/
pointsInInterval: 3,
marker: {
enabled: false
}
}, merge(derivedSeriesMixin, {
setMean: function () {
this.mean = correctFloat(mean(this.baseSeries.yData));
},
setStandardDeviation: function () {
this.standardDeviation = correctFloat(standardDeviation(this.baseSeries.yData, this.mean));
},
setDerivedData: function () {
if (this.baseSeries.yData.length > 1) {
this.setMean();
this.setStandardDeviation();
this.setData(this.derivedData(this.mean, this.standardDeviation), false);
}
return (void 0);
},
derivedData: function (mean, standardDeviation) {
var intervals = this.options.intervals, pointsInInterval = this.options.pointsInInterval, x = mean - intervals * standardDeviation, stop = intervals * pointsInInterval * 2 + 1, increment = standardDeviation / pointsInInterval, data = [], i;
for (i = 0; i < stop; i++) {
data.push([x, normalDensity(x, mean, standardDeviation)]);
x += increment;
}
return data;
}
}));
/**
* A `bellcurve` series. If the [type](#series.bellcurve.type) option is not
* specified, it is inherited from [chart.type](#chart.type).
*
* For options that apply to multiple series, it is recommended to add
* them to the [plotOptions.series](#plotOptions.series) options structure.
* To apply to all series of this specific type, apply it to
* [plotOptions.bellcurve](#plotOptions.bellcurve).
*
* @extends series,plotOptions.bellcurve
* @since 6.0.0
* @product highcharts
* @excluding dataParser, dataURL, data
* @requires modules/bellcurve
* @apioption series.bellcurve
*/
/**
* An integer identifying the index to use for the base series, or a string
* representing the id of the series.
*
* @type {number|string}
* @apioption series.bellcurve.baseSeries
*/
''; // adds doclets above to transpiled file

View File

@@ -0,0 +1,504 @@
/* *
*
* License: www.highcharts.com/license
* Author: Torstein Honsi, Christer Vasseng
*
* This module serves as a fallback for the Boost module in IE9 and IE10. Newer
* browsers support WebGL which is faster.
*
* It is recommended to include this module in conditional comments targeting
* IE9 and IE10.
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../parts/Globals.js';
import Color from '../parts/Color.js';
var color = Color.parse;
import U from '../parts/Utilities.js';
var addEvent = U.addEvent, extend = U.extend, fireEvent = U.fireEvent, isNumber = U.isNumber, merge = U.merge, pick = U.pick, wrap = U.wrap;
import '../parts/Series.js';
import '../parts/Options.js';
var win = H.win, doc = win.document, noop = function () { }, Series = H.Series, seriesTypes = H.seriesTypes, CHUNK_SIZE = 50000, destroyLoadingDiv;
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* Initialize the canvas boost.
*
* @function Highcharts.initCanvasBoost
*/
H.initCanvasBoost = function () {
if (H.seriesTypes.heatmap) {
wrap(H.seriesTypes.heatmap.prototype, 'drawPoints', function () {
var chart = this.chart, ctx = this.getContext(), inverted = this.chart.inverted, xAxis = this.xAxis, yAxis = this.yAxis;
if (ctx) {
// draw the columns
this.points.forEach(function (point) {
var plotY = point.plotY, shapeArgs, pointAttr;
if (typeof plotY !== 'undefined' &&
!isNaN(plotY) &&
point.y !== null) {
shapeArgs = point.shapeArgs;
if (!chart.styledMode) {
pointAttr = point.series.pointAttribs(point);
}
else {
pointAttr = point.series.colorAttribs(point);
}
ctx.fillStyle = pointAttr.fill;
if (inverted) {
ctx.fillRect(yAxis.len - shapeArgs.y + xAxis.left, xAxis.len - shapeArgs.x + yAxis.top, -shapeArgs.height, -shapeArgs.width);
}
else {
ctx.fillRect(shapeArgs.x + xAxis.left, shapeArgs.y + yAxis.top, shapeArgs.width, shapeArgs.height);
}
}
});
this.canvasToSVG();
}
else {
this.chart.showLoading('Your browser doesn\'t support HTML5 canvas, <br>' +
'please use a modern browser');
// Uncomment this to provide low-level (slow) support in oldIE.
// It will cause script errors on charts with more than a few
// thousand points.
// arguments[0].call(this);
}
});
}
extend(Series.prototype, {
/**
* Create a hidden canvas to draw the graph on. The contents is later
* copied over to an SVG image element.
*
* @private
* @function Highcharts.Series#getContext
*/
getContext: function () {
var chart = this.chart, width = chart.chartWidth, height = chart.chartHeight, targetGroup = chart.seriesGroup || this.group, target = this, ctx, swapXY = function (proceed, x, y, a, b, c, d) {
proceed.call(this, y, x, a, b, c, d);
};
if (chart.isChartSeriesBoosting()) {
target = chart;
targetGroup = chart.seriesGroup;
}
ctx = target.ctx;
if (!target.canvas) {
target.canvas = doc.createElement('canvas');
target.renderTarget = chart.renderer
.image('', 0, 0, width, height)
.addClass('highcharts-boost-canvas')
.add(targetGroup);
target.ctx = ctx = target.canvas.getContext('2d');
if (chart.inverted) {
['moveTo', 'lineTo', 'rect', 'arc'].forEach(function (fn) {
wrap(ctx, fn, swapXY);
});
}
target.boostCopy = function () {
target.renderTarget.attr({
href: target.canvas.toDataURL('image/png')
});
};
target.boostClear = function () {
ctx.clearRect(0, 0, target.canvas.width, target.canvas.height);
if (target === this) {
target.renderTarget.attr({ href: '' });
}
};
target.boostClipRect = chart.renderer.clipRect();
target.renderTarget.clip(target.boostClipRect);
}
else if (!(target instanceof H.Chart)) {
// ctx.clearRect(0, 0, width, height);
}
if (target.canvas.width !== width) {
target.canvas.width = width;
}
if (target.canvas.height !== height) {
target.canvas.height = height;
}
target.renderTarget.attr({
x: 0,
y: 0,
width: width,
height: height,
style: 'pointer-events: none',
href: ''
});
target.boostClipRect.attr(chart.getBoostClipRect(target));
return ctx;
},
/**
* Draw the canvas image inside an SVG image
*
* @private
* @function Highcharts.Series#canvasToSVG
*/
canvasToSVG: function () {
if (!this.chart.isChartSeriesBoosting()) {
if (this.boostCopy || this.chart.boostCopy) {
(this.boostCopy || this.chart.boostCopy)();
}
}
else {
if (this.boostClear) {
this.boostClear();
}
}
},
cvsLineTo: function (ctx, clientX, plotY) {
ctx.lineTo(clientX, plotY);
},
renderCanvas: function () {
var series = this, options = series.options, chart = series.chart, xAxis = this.xAxis, yAxis = this.yAxis, activeBoostSettings = chart.options.boost || {}, boostSettings = {
timeRendering: activeBoostSettings.timeRendering || false,
timeSeriesProcessing: activeBoostSettings.timeSeriesProcessing || false,
timeSetup: activeBoostSettings.timeSetup || false
}, ctx, c = 0, xData = series.processedXData, yData = series.processedYData, rawData = options.data, xExtremes = xAxis.getExtremes(), xMin = xExtremes.min, xMax = xExtremes.max, yExtremes = yAxis.getExtremes(), yMin = yExtremes.min, yMax = yExtremes.max, pointTaken = {}, lastClientX, sampling = !!series.sampling, points, r = options.marker && options.marker.radius, cvsDrawPoint = this.cvsDrawPoint, cvsLineTo = options.lineWidth ? this.cvsLineTo : void 0, cvsMarker = (r && r <= 1 ?
this.cvsMarkerSquare :
this.cvsMarkerCircle), strokeBatch = this.cvsStrokeBatch || 1000, enableMouseTracking = options.enableMouseTracking !== false, lastPoint, threshold = options.threshold, yBottom = yAxis.getThreshold(threshold), hasThreshold = isNumber(threshold), translatedThreshold = yBottom, doFill = this.fill, isRange = (series.pointArrayMap &&
series.pointArrayMap.join(',') === 'low,high'), isStacked = !!options.stacking, cropStart = series.cropStart || 0, loadingOptions = chart.options.loading, requireSorting = series.requireSorting, wasNull, connectNulls = options.connectNulls, useRaw = !xData, minVal, maxVal, minI, maxI, index, sdata = (isStacked ?
series.data :
(xData || rawData)), fillColor = (series.fillOpacity ?
new Color(series.color).setOpacity(pick(options.fillOpacity, 0.75)).get() :
series.color),
//
stroke = function () {
if (doFill) {
ctx.fillStyle = fillColor;
ctx.fill();
}
else {
ctx.strokeStyle = series.color;
ctx.lineWidth = options.lineWidth;
ctx.stroke();
}
},
//
drawPoint = function (clientX, plotY, yBottom, i) {
if (c === 0) {
ctx.beginPath();
if (cvsLineTo) {
ctx.lineJoin = 'round';
}
}
if (chart.scroller &&
series.options.className ===
'highcharts-navigator-series') {
plotY += chart.scroller.top;
if (yBottom) {
yBottom += chart.scroller.top;
}
}
else {
plotY += chart.plotTop;
}
clientX += chart.plotLeft;
if (wasNull) {
ctx.moveTo(clientX, plotY);
}
else {
if (cvsDrawPoint) {
cvsDrawPoint(ctx, clientX, plotY, yBottom, lastPoint);
}
else if (cvsLineTo) {
cvsLineTo(ctx, clientX, plotY);
}
else if (cvsMarker) {
cvsMarker.call(series, ctx, clientX, plotY, r, i);
}
}
// We need to stroke the line for every 1000 pixels. It will
// crash the browser memory use if we stroke too
// infrequently.
c = c + 1;
if (c === strokeBatch) {
stroke();
c = 0;
}
// Area charts need to keep track of the last point
lastPoint = {
clientX: clientX,
plotY: plotY,
yBottom: yBottom
};
},
//
compareX = options.findNearestPointBy === 'x',
//
xDataFull = (this.xData ||
this.options.xData ||
this.processedXData ||
false),
//
addKDPoint = function (clientX, plotY, i) {
// Shaves off about 60ms compared to repeated concatenation
index = compareX ? clientX : clientX + ',' + plotY;
// The k-d tree requires series points.
// Reduce the amount of points, since the time to build the
// tree increases exponentially.
if (enableMouseTracking && !pointTaken[index]) {
pointTaken[index] = true;
if (chart.inverted) {
clientX = xAxis.len - clientX;
plotY = yAxis.len - plotY;
}
points.push({
x: xDataFull ?
xDataFull[cropStart + i] :
false,
clientX: clientX,
plotX: clientX,
plotY: plotY,
i: cropStart + i
});
}
};
if (this.renderTarget) {
this.renderTarget.attr({ 'href': '' });
}
// If we are zooming out from SVG mode, destroy the graphics
if (this.points || this.graph) {
this.destroyGraphics();
}
// The group
series.plotGroup('group', 'series', series.visible ? 'visible' : 'hidden', options.zIndex, chart.seriesGroup);
series.markerGroup = series.group;
addEvent(series, 'destroy', function () {
// Prevent destroy twice
series.markerGroup = null;
});
points = this.points = [];
ctx = this.getContext();
series.buildKDTree = noop; // Do not start building while drawing
if (this.boostClear) {
this.boostClear();
}
// if (this.canvas) {
// ctx.clearRect(
// 0,
// 0,
// this.canvas.width,
// this.canvas.height
// );
// }
if (!this.visible) {
return;
}
// Display a loading indicator
if (rawData.length > 99999) {
chart.options.loading = merge(loadingOptions, {
labelStyle: {
backgroundColor: color('#ffffff').setOpacity(0.75).get(),
padding: '1em',
borderRadius: '0.5em'
},
style: {
backgroundColor: 'none',
opacity: 1
}
});
U.clearTimeout(destroyLoadingDiv);
chart.showLoading('Drawing...');
chart.options.loading = loadingOptions; // reset
}
if (boostSettings.timeRendering) {
console.time('canvas rendering'); // eslint-disable-line no-console
}
// Loop over the points
H.eachAsync(sdata, function (d, i) {
var x, y, clientX, plotY, isNull, low, isNextInside = false, isPrevInside = false, nx = false, px = false, chartDestroyed = typeof chart.index === 'undefined', isYInside = true;
if (!chartDestroyed) {
if (useRaw) {
x = d[0];
y = d[1];
if (sdata[i + 1]) {
nx = sdata[i + 1][0];
}
if (sdata[i - 1]) {
px = sdata[i - 1][0];
}
}
else {
x = d;
y = yData[i];
if (sdata[i + 1]) {
nx = sdata[i + 1];
}
if (sdata[i - 1]) {
px = sdata[i - 1];
}
}
if (nx && nx >= xMin && nx <= xMax) {
isNextInside = true;
}
if (px && px >= xMin && px <= xMax) {
isPrevInside = true;
}
// Resolve low and high for range series
if (isRange) {
if (useRaw) {
y = d.slice(1, 3);
}
low = y[0];
y = y[1];
}
else if (isStacked) {
x = d.x;
y = d.stackY;
low = y - d.y;
}
isNull = y === null;
// Optimize for scatter zooming
if (!requireSorting) {
isYInside = y >= yMin && y <= yMax;
}
if (!isNull &&
((x >= xMin && x <= xMax && isYInside) ||
(isNextInside || isPrevInside))) {
clientX = Math.round(xAxis.toPixels(x, true));
if (sampling) {
if (typeof minI === 'undefined' ||
clientX === lastClientX) {
if (!isRange) {
low = y;
}
if (typeof maxI === 'undefined' || y > maxVal) {
maxVal = y;
maxI = i;
}
if (typeof minI === 'undefined' ||
low < minVal) {
minVal = low;
minI = i;
}
}
// Add points and reset
if (clientX !== lastClientX) {
// maxI also a number:
if (typeof minI !== 'undefined') {
plotY = yAxis.toPixels(maxVal, true);
yBottom = yAxis.toPixels(minVal, true);
drawPoint(clientX, hasThreshold ?
Math.min(plotY, translatedThreshold) : plotY, hasThreshold ?
Math.max(yBottom, translatedThreshold) : yBottom, i);
addKDPoint(clientX, plotY, maxI);
if (yBottom !== plotY) {
addKDPoint(clientX, yBottom, minI);
}
}
minI = maxI = void 0;
lastClientX = clientX;
}
}
else {
plotY = Math.round(yAxis.toPixels(y, true));
drawPoint(clientX, plotY, yBottom, i);
addKDPoint(clientX, plotY, i);
}
}
wasNull = isNull && !connectNulls;
if (i % CHUNK_SIZE === 0) {
if (series.boostCopy || series.chart.boostCopy) {
(series.boostCopy || series.chart.boostCopy)();
}
}
}
return !chartDestroyed;
}, function () {
var loadingDiv = chart.loadingDiv, loadingShown = chart.loadingShown;
stroke();
// if (series.boostCopy || series.chart.boostCopy) {
// (series.boostCopy || series.chart.boostCopy)();
// }
series.canvasToSVG();
if (boostSettings.timeRendering) {
console.timeEnd('canvas rendering'); // eslint-disable-line no-console
}
fireEvent(series, 'renderedCanvas');
// Do not use chart.hideLoading, as it runs JS animation and
// will be blocked by buildKDTree. CSS animation looks good, but
// then it must be deleted in timeout. If we add the module to
// core, change hideLoading so we can skip this block.
if (loadingShown) {
extend(loadingDiv.style, {
transition: 'opacity 250ms',
opacity: 0
});
chart.loadingShown = false;
destroyLoadingDiv = setTimeout(function () {
if (loadingDiv.parentNode) { // In exporting it is falsy
loadingDiv.parentNode.removeChild(loadingDiv);
}
chart.loadingDiv = chart.loadingSpan = null;
}, 250);
}
// Go back to prototype, ready to build
delete series.buildKDTree;
series.buildKDTree();
// Don't do async on export, the exportChart, getSVGForExport and
// getSVG methods are not chained for it.
}, chart.renderer.forExport ? Number.MAX_VALUE : void 0);
}
});
seriesTypes.scatter.prototype.cvsMarkerCircle = function (ctx, clientX, plotY, r) {
ctx.moveTo(clientX, plotY);
ctx.arc(clientX, plotY, r, 0, 2 * Math.PI, false);
};
// Rect is twice as fast as arc, should be used for small markers
seriesTypes.scatter.prototype.cvsMarkerSquare = function (ctx, clientX, plotY, r) {
ctx.rect(clientX - r, plotY - r, r * 2, r * 2);
};
seriesTypes.scatter.prototype.fill = true;
if (seriesTypes.bubble) {
seriesTypes.bubble.prototype.cvsMarkerCircle = function (ctx, clientX, plotY, r, i) {
ctx.moveTo(clientX, plotY);
ctx.arc(clientX, plotY, this.radii && this.radii[i], 0, 2 * Math.PI, false);
};
seriesTypes.bubble.prototype.cvsStrokeBatch = 1;
}
extend(seriesTypes.area.prototype, {
cvsDrawPoint: function (ctx, clientX, plotY, yBottom, lastPoint) {
if (lastPoint && clientX !== lastPoint.clientX) {
ctx.moveTo(lastPoint.clientX, lastPoint.yBottom);
ctx.lineTo(lastPoint.clientX, lastPoint.plotY);
ctx.lineTo(clientX, plotY);
ctx.lineTo(clientX, yBottom);
}
},
fill: true,
fillOpacity: true,
sampling: true
});
extend(seriesTypes.column.prototype, {
cvsDrawPoint: function (ctx, clientX, plotY, yBottom) {
ctx.rect(clientX - 1, plotY, 1, yBottom - plotY);
},
fill: true,
sampling: true
});
H.Chart.prototype.callbacks.push(function (chart) {
/**
* @private
*/
function canvasToSVG() {
if (chart.boostCopy) {
chart.boostCopy();
}
}
/**
* @private
*/
function clear() {
if (chart.renderTarget) {
chart.renderTarget.attr({ href: '' });
}
if (chart.canvas) {
chart.canvas.getContext('2d').clearRect(0, 0, chart.canvas.width, chart.canvas.height);
}
}
addEvent(chart, 'predraw', clear);
addEvent(chart, 'render', canvasToSVG);
});
};

View File

@@ -0,0 +1,146 @@
/* *
*
* Copyright (c) 2019-2020 Highsoft AS
*
* Boost module: stripped-down renderer for higher performance
*
* License: highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../parts/Globals.js';
import '../../parts/Series.js';
import GLRenderer from './wgl-renderer.js';
import U from '../../parts/Utilities.js';
var error = U.error;
var win = H.win, doc = win.document, mainCanvas = doc.createElement('canvas');
/**
* Create a canvas + context and attach it to the target
*
* @private
* @function createAndAttachRenderer
*
* @param {Highcharts.Chart} chart
* the chart
*
* @param {Highcharts.Series} series
* the series
*
* @return {Highcharts.BoostGLRenderer}
* the canvas renderer
*/
function createAndAttachRenderer(chart, series) {
var width = chart.chartWidth, height = chart.chartHeight, target = chart, targetGroup = chart.seriesGroup || series.group, alpha = 1, foSupported = doc.implementation.hasFeature('www.http://w3.org/TR/SVG11/feature#Extensibility', '1.1');
if (chart.isChartSeriesBoosting()) {
target = chart;
}
else {
target = series;
}
// Support for foreignObject is flimsy as best.
// IE does not support it, and Chrome has a bug which messes up
// the canvas draw order.
// As such, we force the Image fallback for now, but leaving the
// actual Canvas path in-place in case this changes in the future.
foSupported = false;
if (!target.renderTarget) {
target.canvas = mainCanvas;
// Fall back to image tag if foreignObject isn't supported,
// or if we're exporting.
if (chart.renderer.forExport || !foSupported) {
target.renderTarget = chart.renderer.image('', 0, 0, width, height)
.addClass('highcharts-boost-canvas')
.add(targetGroup);
target.boostClear = function () {
target.renderTarget.attr({ href: '' });
};
target.boostCopy = function () {
target.boostResizeTarget();
target.renderTarget.attr({
href: target.canvas.toDataURL('image/png')
});
};
}
else {
target.renderTargetFo = chart.renderer
.createElement('foreignObject')
.add(targetGroup);
target.renderTarget = doc.createElement('canvas');
target.renderTargetCtx =
target.renderTarget.getContext('2d');
target.renderTargetFo.element.appendChild(target.renderTarget);
target.boostClear = function () {
target.renderTarget.width =
target.canvas.width;
target.renderTarget.height =
target.canvas.height;
};
target.boostCopy = function () {
target.renderTarget.width =
target.canvas.width;
target.renderTarget.height =
target.canvas.height;
target.renderTargetCtx
.drawImage(target.canvas, 0, 0);
};
}
target.boostResizeTarget = function () {
width = chart.chartWidth;
height = chart.chartHeight;
(target.renderTargetFo || target.renderTarget)
.attr({
x: 0,
y: 0,
width: width,
height: height
})
.css({
pointerEvents: 'none',
mixedBlendMode: 'normal',
opacity: alpha
});
if (target instanceof H.Chart) {
target.markerGroup.translate(chart.plotLeft, chart.plotTop);
}
};
target.boostClipRect = chart.renderer.clipRect();
(target.renderTargetFo || target.renderTarget)
.clip(target.boostClipRect);
if (target instanceof H.Chart) {
target.markerGroup = target.renderer.g().add(targetGroup);
target.markerGroup.translate(series.xAxis.pos, series.yAxis.pos);
}
}
target.canvas.width = width;
target.canvas.height = height;
target.boostClipRect.attr(chart.getBoostClipRect(target));
target.boostResizeTarget();
target.boostClear();
if (!target.ogl) {
target.ogl = GLRenderer(function () {
if (target.ogl.settings.debug.timeBufferCopy) {
console.time('buffer copy'); // eslint-disable-line no-console
}
target.boostCopy();
if (target.ogl.settings.debug.timeBufferCopy) {
console.timeEnd('buffer copy'); // eslint-disable-line no-console
}
});
if (!target.ogl.init(target.canvas)) {
// The OGL renderer couldn't be inited.
// This likely means a shader error as we wouldn't get to this point
// if there was no WebGL support.
error('[highcharts boost] - unable to init WebGL renderer');
}
// target.ogl.clear();
target.ogl.setOptions(chart.options.boost || {});
if (target instanceof H.Chart) {
target.ogl.allocateBuffer(chart);
}
}
target.ogl.setSize(width, height);
return target.ogl;
}
export default createAndAttachRenderer;

View File

@@ -0,0 +1,292 @@
/* *
*
* Copyright (c) 2019-2020 Highsoft AS
*
* Boost module: stripped-down renderer for higher performance
*
* License: highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../parts/Globals.js';
import U from '../../parts/Utilities.js';
var addEvent = U.addEvent, extend = U.extend, fireEvent = U.fireEvent, wrap = U.wrap;
import '../../parts/Series.js';
import butils from './boost-utils.js';
import createAndAttachRenderer from './boost-attach.js';
var Series = H.Series, seriesTypes = H.seriesTypes, noop = function () { }, eachAsync = butils.eachAsync, pointDrawHandler = butils.pointDrawHandler, allocateIfNotSeriesBoosting = butils.allocateIfNotSeriesBoosting, renderIfNotSeriesBoosting = butils.renderIfNotSeriesBoosting, shouldForceChartSeriesBoosting = butils.shouldForceChartSeriesBoosting, index;
/* eslint-disable valid-jsdoc */
/**
* Initialize the boot module.
*
* @private
* @return {void}
*/
function init() {
extend(Series.prototype, {
/**
* @private
* @function Highcharts.Series#renderCanvas
*/
renderCanvas: function () {
var series = this, options = series.options || {}, renderer = false, chart = series.chart, xAxis = this.xAxis, yAxis = this.yAxis, xData = options.xData || series.processedXData, yData = options.yData || series.processedYData, rawData = options.data, xExtremes = xAxis.getExtremes(), xMin = xExtremes.min, xMax = xExtremes.max, yExtremes = yAxis.getExtremes(), yMin = yExtremes.min, yMax = yExtremes.max, pointTaken = {}, lastClientX, sampling = !!series.sampling, points, enableMouseTracking = options.enableMouseTracking !== false, threshold = options.threshold, yBottom = yAxis.getThreshold(threshold), isRange = series.pointArrayMap &&
series.pointArrayMap.join(',') === 'low,high', isStacked = !!options.stacking, cropStart = series.cropStart || 0, requireSorting = series.requireSorting, useRaw = !xData, minVal, maxVal, minI, maxI, boostOptions, compareX = options.findNearestPointBy === 'x', xDataFull = (this.xData ||
this.options.xData ||
this.processedXData ||
false), addKDPoint = function (clientX, plotY, i) {
// We need to do ceil on the clientX to make things
// snap to pixel values. The renderer will frequently
// draw stuff on "sub-pixels".
clientX = Math.ceil(clientX);
// Shaves off about 60ms compared to repeated concatenation
index = compareX ? clientX : clientX + ',' + plotY;
// The k-d tree requires series points.
// Reduce the amount of points, since the time to build the
// tree increases exponentially.
if (enableMouseTracking && !pointTaken[index]) {
pointTaken[index] = true;
if (chart.inverted) {
clientX = xAxis.len - clientX;
plotY = yAxis.len - plotY;
}
points.push({
x: xDataFull ? xDataFull[cropStart + i] : false,
clientX: clientX,
plotX: clientX,
plotY: plotY,
i: cropStart + i
});
}
};
// Get or create the renderer
renderer = createAndAttachRenderer(chart, series);
chart.isBoosting = true;
boostOptions = renderer.settings;
if (!this.visible) {
return;
}
// If we are zooming out from SVG mode, destroy the graphics
if (this.points || this.graph) {
this.destroyGraphics();
}
// If we're rendering per. series we should create the marker groups
// as usual.
if (!chart.isChartSeriesBoosting()) {
// If all series were boosting, but are not anymore
// restore private markerGroup
if (this.markerGroup === chart.markerGroup) {
this.markerGroup = void 0;
}
this.markerGroup = series.plotGroup('markerGroup', 'markers', true, 1, chart.seriesGroup);
}
else {
// If series has a private markeGroup, remove that
// and use common markerGroup
if (this.markerGroup &&
this.markerGroup !== chart.markerGroup) {
this.markerGroup.destroy();
}
// Use a single group for the markers
this.markerGroup = chart.markerGroup;
// When switching from chart boosting mode, destroy redundant
// series boosting targets
if (this.renderTarget) {
this.renderTarget = this.renderTarget.destroy();
}
}
points = this.points = [];
// Do not start building while drawing
series.buildKDTree = noop;
if (renderer) {
allocateIfNotSeriesBoosting(renderer, this);
renderer.pushSeries(series);
// Perform the actual renderer if we're on series level
renderIfNotSeriesBoosting(renderer, this, chart);
}
/**
* This builds the KD-tree
* @private
*/
function processPoint(d, i) {
var x, y, clientX, plotY, isNull, low = false, chartDestroyed = typeof chart.index === 'undefined', isYInside = true;
if (!chartDestroyed) {
if (useRaw) {
x = d[0];
y = d[1];
}
else {
x = d;
y = yData[i];
}
// Resolve low and high for range series
if (isRange) {
if (useRaw) {
y = d.slice(1, 3);
}
low = y[0];
y = y[1];
}
else if (isStacked) {
x = d.x;
y = d.stackY;
low = y - d.y;
}
isNull = y === null;
// Optimize for scatter zooming
if (!requireSorting) {
isYInside = y >= yMin && y <= yMax;
}
if (!isNull && x >= xMin && x <= xMax && isYInside) {
clientX = xAxis.toPixels(x, true);
if (sampling) {
if (typeof minI === 'undefined' ||
clientX === lastClientX) {
if (!isRange) {
low = y;
}
if (typeof maxI === 'undefined' ||
y > maxVal) {
maxVal = y;
maxI = i;
}
if (typeof minI === 'undefined' ||
low < minVal) {
minVal = low;
minI = i;
}
}
// Add points and reset
if (clientX !== lastClientX) {
// maxI is number too:
if (typeof minI !== 'undefined') {
plotY =
yAxis.toPixels(maxVal, true);
yBottom =
yAxis.toPixels(minVal, true);
addKDPoint(clientX, plotY, maxI);
if (yBottom !== plotY) {
addKDPoint(clientX, yBottom, minI);
}
}
minI = maxI = void 0;
lastClientX = clientX;
}
}
else {
plotY = Math.ceil(yAxis.toPixels(y, true));
addKDPoint(clientX, plotY, i);
}
}
}
return !chartDestroyed;
}
/**
* @private
*/
function doneProcessing() {
fireEvent(series, 'renderedCanvas');
// Go back to prototype, ready to build
delete series.buildKDTree;
series.buildKDTree();
if (boostOptions.debug.timeKDTree) {
console.timeEnd('kd tree building'); // eslint-disable-line no-console
}
}
// Loop over the points to build the k-d tree - skip this if
// exporting
if (!chart.renderer.forExport) {
if (boostOptions.debug.timeKDTree) {
console.time('kd tree building'); // eslint-disable-line no-console
}
eachAsync(isStacked ? series.data : (xData || rawData), processPoint, doneProcessing);
}
}
});
/*
* We need to handle heatmaps separatly, since we can't perform the
* size/color calculations in the shader easily.
*
* This likely needs future optimization.
*/
['heatmap', 'treemap'].forEach(function (t) {
if (seriesTypes[t]) {
wrap(seriesTypes[t].prototype, 'drawPoints', pointDrawHandler);
}
});
/* eslint-disable no-invalid-this */
if (seriesTypes.bubble) {
// By default, the bubble series does not use the KD-tree, so force it
// to.
delete seriesTypes.bubble.prototype.buildKDTree;
// seriesTypes.bubble.prototype.directTouch = false;
// Needed for markers to work correctly
wrap(seriesTypes.bubble.prototype, 'markerAttribs', function (proceed) {
if (this.isSeriesBoosting) {
return false;
}
return proceed.apply(this, [].slice.call(arguments, 1));
});
}
seriesTypes.scatter.prototype.fill = true;
extend(seriesTypes.area.prototype, {
fill: true,
fillOpacity: true,
sampling: true
});
extend(seriesTypes.column.prototype, {
fill: true,
sampling: true
});
// Take care of the canvas blitting
H.Chart.prototype.callbacks.push(function (chart) {
/**
* Convert chart-level canvas to image.
* @private
*/
function canvasToSVG() {
if (chart.ogl && chart.isChartSeriesBoosting()) {
chart.ogl.render(chart);
}
}
/**
* Clear chart-level canvas.
* @private
*/
function preRender() {
// Reset force state
chart.boostForceChartBoost = void 0;
chart.boostForceChartBoost = shouldForceChartSeriesBoosting(chart);
chart.isBoosting = false;
if (!chart.isChartSeriesBoosting() && chart.didBoost) {
chart.didBoost = false;
}
// Clear the canvas
if (chart.boostClear) {
chart.boostClear();
}
if (chart.canvas && chart.ogl && chart.isChartSeriesBoosting()) {
chart.didBoost = true;
// Allocate
chart.ogl.allocateBuffer(chart);
}
// see #6518 + #6739
if (chart.markerGroup &&
chart.xAxis &&
chart.xAxis.length > 0 &&
chart.yAxis &&
chart.yAxis.length > 0) {
chart.markerGroup.translate(chart.xAxis[0].pos, chart.yAxis[0].pos);
}
}
addEvent(chart, 'predraw', preRender);
addEvent(chart, 'render', canvasToSVG);
// addEvent(chart, 'zoom', function () {
// chart.boostForceChartBoost =
// shouldForceChartSeriesBoosting(chart);
// });
});
/* eslint-enable no-invalid-this */
}
export default init;

View File

@@ -0,0 +1,178 @@
/* *
*
* Copyright (c) 2019-2020 Highsoft AS
*
* Boost module: stripped-down renderer for higher performance
*
* License: highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import '../../parts/Globals.js';
/**
* @requires modules/boost
* @apioption boost
*/
/**
* Set the series threshold for when the boost should kick in globally.
*
* Setting to e.g. 20 will cause the whole chart to enter boost mode
* if there are 20 or more series active. When the chart is in boost mode,
* every series in it will be rendered to a common canvas. This offers
* a significant speed improvment in charts with a very high
* amount of series.
*
* @type {number|null}
* @default null
* @apioption boost.seriesThreshold
*/
/**
* Enable or disable boost on a chart.
*
* @type {boolean}
* @default true
* @apioption boost.enabled
*/
/**
* Debugging options for boost.
* Useful for benchmarking, and general timing.
*
* @apioption boost.debug
*/
/**
* Time the series rendering.
*
* This outputs the time spent on actual rendering in the console when
* set to true.
*
* @type {boolean}
* @default false
* @apioption boost.debug.timeRendering
*/
/**
* Time the series processing.
*
* This outputs the time spent on transforming the series data to
* vertex buffers when set to true.
*
* @type {boolean}
* @default false
* @apioption boost.debug.timeSeriesProcessing
*/
/**
* Time the the WebGL setup.
*
* This outputs the time spent on setting up the WebGL context,
* creating shaders, and textures.
*
* @type {boolean}
* @default false
* @apioption boost.debug.timeSetup
*/
/**
* Time the building of the k-d tree.
*
* This outputs the time spent building the k-d tree used for
* markers etc.
*
* Note that the k-d tree is built async, and runs post-rendering.
* Following, it does not affect the performance of the rendering itself.
*
* @type {boolean}
* @default false
* @apioption boost.debug.timeKDTree
*/
/**
* Show the number of points skipped through culling.
*
* When set to true, the number of points skipped in series processing
* is outputted. Points are skipped if they are closer than 1 pixel from
* each other.
*
* @type {boolean}
* @default false
* @apioption boost.debug.showSkipSummary
*/
/**
* Time the WebGL to SVG buffer copy
*
* After rendering, the result is copied to an image which is injected
* into the SVG.
*
* If this property is set to true, the time it takes for the buffer copy
* to complete is outputted.
*
* @type {boolean}
* @default false
* @apioption boost.debug.timeBufferCopy
*/
/**
* Enable or disable GPU translations. GPU translations are faster than doing
* the translation in JavaScript.
*
* This option may cause rendering issues with certain datasets.
* Namely, if your dataset has large numbers with small increments (such as
* timestamps), it won't work correctly. This is due to floating point
* precission.
*
* @type {boolean}
* @default false
* @apioption boost.useGPUTranslations
*/
/**
* Enable or disable pre-allocation of vertex buffers.
*
* Enabling this will make it so that the binary data arrays required for
* storing the series data will be allocated prior to transforming the data
* to a WebGL-compatible format.
*
* This saves a copy operation on the order of O(n) and so is significantly more
* performant. However, this is currently an experimental option, and may cause
* visual artifacts with some datasets.
*
* As such, care should be taken when using this setting to make sure that
* it doesn't cause any rendering glitches with the given use-case.
*
* @type {boolean}
* @default false
* @apioption boost.usePreallocated
*/
/**
* Set the point threshold for when a series should enter boost mode.
*
* Setting it to e.g. 2000 will cause the series to enter boost mode when there
* are 2000 or more points in the series.
*
* To disable boosting on the series, set the `boostThreshold` to 0. Setting it
* to 1 will force boosting.
*
* Note that the [cropThreshold](plotOptions.series.cropThreshold) also affects
* this setting. When zooming in on a series that has fewer points than the
* `cropThreshold`, all points are rendered although outside the visible plot
* area, and the `boostThreshold` won't take effect.
*
* @type {number}
* @default 5000
* @requires modules/boost
* @apioption plotOptions.series.boostThreshold
*/
/**
* If set to true, the whole chart will be boosted if one of the series
* crosses its threshold, and all the series can be boosted.
*
* @type {boolean}
* @default true
* @apioption boost.allowForce
*/
/**
* Sets the color blending in the boost module.
*
* @type {string}
* @default undefined
* @validvalue ["add", "multiply", "darken"]
* @requires modules/boost
* @apioption plotOptions.series.boostBlending
*/
''; // adds doclets above to transpiled file

View File

@@ -0,0 +1,364 @@
/* *
*
* Copyright (c) 2019-2020 Highsoft AS
*
* Boost module: stripped-down renderer for higher performance
*
* License: highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../parts/Globals.js';
import Point from '../../parts/Point.js';
import U from '../../parts/Utilities.js';
var addEvent = U.addEvent, error = U.error, isNumber = U.isNumber, pick = U.pick, wrap = U.wrap;
import '../../parts/Series.js';
import '../../parts/Options.js';
import '../../parts/Interaction.js';
import butils from './boost-utils.js';
import boostable from './boostables.js';
import boostableMap from './boostable-map.js';
var boostEnabled = butils.boostEnabled, shouldForceChartSeriesBoosting = butils.shouldForceChartSeriesBoosting, Chart = H.Chart, Series = H.Series, seriesTypes = H.seriesTypes, plotOptions = H.getOptions().plotOptions;
/**
* Returns true if the chart is in series boost mode.
*
* @function Highcharts.Chart#isChartSeriesBoosting
*
* @param {Highcharts.Chart} chart
* the chart to check
*
* @return {boolean}
* true if the chart is in series boost mode
*/
Chart.prototype.isChartSeriesBoosting = function () {
var isSeriesBoosting, threshold = pick(this.options.boost && this.options.boost.seriesThreshold, 50);
isSeriesBoosting = threshold <= this.series.length ||
shouldForceChartSeriesBoosting(this);
return isSeriesBoosting;
};
/* eslint-disable valid-jsdoc */
/**
* Get the clip rectangle for a target, either a series or the chart. For the
* chart, we need to consider the maximum extent of its Y axes, in case of
* Highstock panes and navigator.
*
* @private
* @function Highcharts.Chart#getBoostClipRect
*
* @param {Highcharts.Chart} target
*
* @return {Highcharts.BBoxObject}
*/
Chart.prototype.getBoostClipRect = function (target) {
var clipBox = {
x: this.plotLeft,
y: this.plotTop,
width: this.plotWidth,
height: this.plotHeight
};
if (target === this) {
this.yAxis.forEach(function (yAxis) {
clipBox.y = Math.min(yAxis.pos, clipBox.y);
clipBox.height = Math.max(yAxis.pos - this.plotTop + yAxis.len, clipBox.height);
}, this);
}
return clipBox;
};
/**
* Return a full Point object based on the index.
* The boost module uses stripped point objects for performance reasons.
*
* @function Highcharts.Series#getPoint
*
* @param {object|Highcharts.Point} boostPoint
* A stripped-down point object
*
* @return {Highcharts.Point}
* A Point object as per https://api.highcharts.com/highcharts#Point
*/
Series.prototype.getPoint = function (boostPoint) {
var point = boostPoint, xData = (this.xData || this.options.xData || this.processedXData ||
false);
if (boostPoint && !(boostPoint instanceof this.pointClass)) {
point = (new this.pointClass()).init(// eslint-disable-line new-cap
this, this.options.data[boostPoint.i], xData ? xData[boostPoint.i] : void 0);
point.category = pick(this.xAxis.categories ?
this.xAxis.categories[point.x] :
point.x, // @todo simplify
point.x);
point.dist = boostPoint.dist;
point.distX = boostPoint.distX;
point.plotX = boostPoint.plotX;
point.plotY = boostPoint.plotY;
point.index = boostPoint.i;
point.isInside = this.isPointInside(boostPoint);
}
return point;
};
/* eslint-disable no-invalid-this */
// Return a point instance from the k-d-tree
wrap(Series.prototype, 'searchPoint', function (proceed) {
return this.getPoint(proceed.apply(this, [].slice.call(arguments, 1)));
});
// For inverted series, we need to swap X-Y values before running base methods
wrap(Point.prototype, 'haloPath', function (proceed) {
var halo, point = this, series = point.series, chart = series.chart, plotX = point.plotX, plotY = point.plotY, inverted = chart.inverted;
if (series.isSeriesBoosting && inverted) {
point.plotX = series.yAxis.len - plotY;
point.plotY = series.xAxis.len - plotX;
}
halo = proceed.apply(this, Array.prototype.slice.call(arguments, 1));
if (series.isSeriesBoosting && inverted) {
point.plotX = plotX;
point.plotY = plotY;
}
return halo;
});
wrap(Series.prototype, 'markerAttribs', function (proceed, point) {
var attribs, series = this, chart = series.chart, plotX = point.plotX, plotY = point.plotY, inverted = chart.inverted;
if (series.isSeriesBoosting && inverted) {
point.plotX = series.yAxis.len - plotY;
point.plotY = series.xAxis.len - plotX;
}
attribs = proceed.apply(this, Array.prototype.slice.call(arguments, 1));
if (series.isSeriesBoosting && inverted) {
point.plotX = plotX;
point.plotY = plotY;
}
return attribs;
});
/*
* Extend series.destroy to also remove the fake k-d-tree points (#5137).
* Normally this is handled by Series.destroy that calls Point.destroy,
* but the fake search points are not registered like that.
*/
addEvent(Series, 'destroy', function () {
var series = this, chart = series.chart;
if (chart.markerGroup === series.markerGroup) {
series.markerGroup = null;
}
if (chart.hoverPoints) {
chart.hoverPoints = chart.hoverPoints.filter(function (point) {
return point.series === series;
});
}
if (chart.hoverPoint && chart.hoverPoint.series === series) {
chart.hoverPoint = null;
}
});
/*
* Do not compute extremes when min and max are set.
* If we use this in the core, we can add the hook
* to hasExtremes to the methods directly.
*/
wrap(Series.prototype, 'getExtremes', function (proceed) {
if (!this.isSeriesBoosting || (!this.hasExtremes || !this.hasExtremes())) {
return proceed.apply(this, Array.prototype.slice.call(arguments, 1));
}
});
/*
* Override a bunch of methods the same way. If the number of points is
* below the threshold, run the original method. If not, check for a
* canvas version or do nothing.
*
* Note that we're not overriding any of these for heatmaps.
*/
[
'translate',
'generatePoints',
'drawTracker',
'drawPoints',
'render'
].forEach(function (method) {
/**
* @private
*/
function branch(proceed) {
var letItPass = this.options.stacking &&
(method === 'translate' || method === 'generatePoints');
if (!this.isSeriesBoosting ||
letItPass ||
!boostEnabled(this.chart) ||
this.type === 'heatmap' ||
this.type === 'treemap' ||
!boostableMap[this.type] ||
this.options.boostThreshold === 0) {
proceed.call(this);
// If a canvas version of the method exists, like renderCanvas(), run
}
else if (this[method + 'Canvas']) {
this[method + 'Canvas']();
}
}
wrap(Series.prototype, method, branch);
// A special case for some types - their translate method is already wrapped
if (method === 'translate') {
[
'column',
'bar',
'arearange',
'columnrange',
'heatmap',
'treemap'
].forEach(function (type) {
if (seriesTypes[type]) {
wrap(seriesTypes[type].prototype, method, branch);
}
});
}
});
// If the series is a heatmap or treemap, or if the series is not boosting
// do the default behaviour. Otherwise, process if the series has no extremes.
wrap(Series.prototype, 'processData', function (proceed) {
var series = this, dataToMeasure = this.options.data, firstPoint;
/**
* Used twice in this function, first on this.options.data, the second
* time it runs the check again after processedXData is built.
* @private
* @todo Check what happens with data grouping
*/
function getSeriesBoosting(data) {
return series.chart.isChartSeriesBoosting() || ((data ? data.length : 0) >=
(series.options.boostThreshold || Number.MAX_VALUE));
}
if (boostEnabled(this.chart) && boostableMap[this.type]) {
// If there are no extremes given in the options, we also need to
// process the data to read the data extremes. If this is a heatmap, do
// default behaviour.
if (!getSeriesBoosting(dataToMeasure) || // First pass with options.data
this.type === 'heatmap' ||
this.type === 'treemap' ||
this.options.stacking || // processedYData for the stack (#7481)
!this.hasExtremes ||
!this.hasExtremes(true)) {
proceed.apply(this, Array.prototype.slice.call(arguments, 1));
dataToMeasure = this.processedXData;
}
// Set the isBoosting flag, second pass with processedXData to see if we
// have zoomed.
this.isSeriesBoosting = getSeriesBoosting(dataToMeasure);
// Enter or exit boost mode
if (this.isSeriesBoosting) {
// Force turbo-mode:
firstPoint = this.getFirstValidPoint(this.options.data);
if (!isNumber(firstPoint) && !H.isArray(firstPoint)) {
error(12, false, this.chart);
}
this.enterBoost();
}
else if (this.exitBoost) {
this.exitBoost();
}
// The series type is not boostable
}
else {
proceed.apply(this, Array.prototype.slice.call(arguments, 1));
}
});
addEvent(Series, 'hide', function () {
if (this.canvas && this.renderTarget) {
if (this.ogl) {
this.ogl.clear();
}
this.boostClear();
}
});
/**
* Enter boost mode and apply boost-specific properties.
*
* @function Highcharts.Series#enterBoost
*/
Series.prototype.enterBoost = function () {
this.alteredByBoost = [];
// Save the original values, including whether it was an own property or
// inherited from the prototype.
['allowDG', 'directTouch', 'stickyTracking'].forEach(function (prop) {
this.alteredByBoost.push({
prop: prop,
val: this[prop],
own: Object.hasOwnProperty.call(this, prop)
});
}, this);
this.allowDG = false;
this.directTouch = false;
this.stickyTracking = true;
// Hide series label if any
if (this.labelBySeries) {
this.labelBySeries = this.labelBySeries.destroy();
}
};
/**
* Exit from boost mode and restore non-boost properties.
*
* @function Highcharts.Series#exitBoost
*/
Series.prototype.exitBoost = function () {
// Reset instance properties and/or delete instance properties and go back
// to prototype
(this.alteredByBoost || []).forEach(function (setting) {
if (setting.own) {
this[setting.prop] = setting.val;
}
else {
// Revert to prototype
delete this[setting.prop];
}
}, this);
// Clear previous run
if (this.boostClear) {
this.boostClear();
}
};
/**
* @private
* @function Highcharts.Series#hasExtremes
*
* @param {boolean} checkX
*
* @return {boolean}
*/
Series.prototype.hasExtremes = function (checkX) {
var options = this.options, data = options.data, xAxis = this.xAxis && this.xAxis.options, yAxis = this.yAxis && this.yAxis.options, colorAxis = this.colorAxis && this.colorAxis.options;
return data.length > (options.boostThreshold || Number.MAX_VALUE) &&
// Defined yAxis extremes
isNumber(yAxis.min) &&
isNumber(yAxis.max) &&
// Defined (and required) xAxis extremes
(!checkX ||
(isNumber(xAxis.min) && isNumber(xAxis.max))) &&
// Defined (e.g. heatmap) colorAxis extremes
(!colorAxis ||
(isNumber(colorAxis.min) && isNumber(colorAxis.max)));
};
/**
* If implemented in the core, parts of this can probably be
* shared with other similar methods in Highcharts.
*
* @function Highcharts.Series#destroyGraphics
*/
Series.prototype.destroyGraphics = function () {
var series = this, points = this.points, point, i;
if (points) {
for (i = 0; i < points.length; i = i + 1) {
point = points[i];
if (point && point.destroyElements) {
point.destroyElements(); // #7557
}
}
}
['graph', 'area', 'tracker'].forEach(function (prop) {
if (series[prop]) {
series[prop] = series[prop].destroy();
}
});
};
// Set default options
boostable.forEach(function (type) {
if (plotOptions[type]) {
plotOptions[type].boostThreshold = 5000;
plotOptions[type].boostData = [];
seriesTypes[type].prototype.fillOpacity = true;
}
});

View File

@@ -0,0 +1,260 @@
/* *
*
* Copyright (c) 2019-2020 Highsoft AS
*
* Boost module: stripped-down renderer for higher performance
*
* License: highcharts.com/license
*
* This files contains generic utility functions used by the boost module.
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../parts/Globals.js';
import '../../parts/Series.js';
import boostableMap from './boostable-map.js';
import createAndAttachRenderer from './boost-attach.js';
var win = H.win, doc = win.document, pick = H.pick;
// This should be a const.
var CHUNK_SIZE = 3000;
/**
* Tolerant max() function.
*
* @private
* @function patientMax
*
* @param {...Array<Array<unknown>>} args
* Max arguments
*
* @return {number}
* Max value
*/
function patientMax() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var r = -Number.MAX_VALUE;
args.forEach(function (t) {
if (typeof t !== 'undefined' &&
t !== null &&
typeof t.length !== 'undefined') {
// r = r < t.length ? t.length : r;
if (t.length > 0) {
r = t.length;
return true;
}
}
});
return r;
}
/**
* Return true if ths boost.enabled option is true
*
* @private
* @function boostEnabled
*
* @param {Highcharts.Chart} chart
* The chart
*
* @return {boolean}
* True, if boost is enabled.
*/
function boostEnabled(chart) {
return pick((chart &&
chart.options &&
chart.options.boost &&
chart.options.boost.enabled), true);
}
/**
* Returns true if we should force boosting the chart
* @private
* @function shouldForceChartSeriesBoosting
*
* @param {Highcharts.Chart} chart
* The chart to check for forcing on
*
* @return {boolean}
* True, if boosting should be forced.
*/
function shouldForceChartSeriesBoosting(chart) {
// If there are more than five series currently boosting,
// we should boost the whole chart to avoid running out of webgl contexts.
var sboostCount = 0, canBoostCount = 0, allowBoostForce = pick(chart.options.boost && chart.options.boost.allowForce, true), series;
if (typeof chart.boostForceChartBoost !== 'undefined') {
return chart.boostForceChartBoost;
}
if (chart.series.length > 1) {
for (var i = 0; i < chart.series.length; i++) {
series = chart.series[i];
// Don't count series with boostThreshold set to 0
// See #8950
// Also don't count if the series is hidden.
// See #9046
if (series.options.boostThreshold === 0 ||
series.visible === false) {
continue;
}
// Don't count heatmap series as they are handled differently.
// In the future we should make the heatmap/treemap path compatible
// with forcing. See #9636.
if (series.type === 'heatmap') {
continue;
}
if (boostableMap[series.type]) {
++canBoostCount;
}
if (patientMax(series.processedXData, series.options.data,
// series.xData,
series.points) >= (series.options.boostThreshold || Number.MAX_VALUE)) {
++sboostCount;
}
}
}
chart.boostForceChartBoost = allowBoostForce && ((canBoostCount === chart.series.length &&
sboostCount > 0) ||
sboostCount > 5);
return chart.boostForceChartBoost;
}
/* eslint-disable valid-jsdoc */
/**
* Performs the actual render if the renderer is
* attached to the series.
* @private
* @param renderer {OGLRenderer} - the renderer
* @param series {Highcharts.Series} - the series
*/
function renderIfNotSeriesBoosting(renderer, series, chart) {
if (renderer &&
series.renderTarget &&
series.canvas &&
!(chart || series.chart).isChartSeriesBoosting()) {
renderer.render(chart || series.chart);
}
}
/**
* @private
*/
function allocateIfNotSeriesBoosting(renderer, series) {
if (renderer &&
series.renderTarget &&
series.canvas &&
!series.chart.isChartSeriesBoosting()) {
renderer.allocateBufferForSingleSeries(series);
}
}
/**
* An "async" foreach loop. Uses a setTimeout to keep the loop from blocking the
* UI thread.
*
* @private
*
* @param arr {Array} - the array to loop through
* @param fn {Function} - the callback to call for each item
* @param finalFunc {Function} - the callback to call when done
* @param chunkSize {Number} - the number of iterations per timeout
* @param i {Number} - the current index
* @param noTimeout {Boolean} - set to true to skip timeouts
*/
function eachAsync(arr, fn, finalFunc, chunkSize, i, noTimeout) {
i = i || 0;
chunkSize = chunkSize || CHUNK_SIZE;
var threshold = i + chunkSize, proceed = true;
while (proceed && i < threshold && i < arr.length) {
proceed = fn(arr[i], i);
++i;
}
if (proceed) {
if (i < arr.length) {
if (noTimeout) {
eachAsync(arr, fn, finalFunc, chunkSize, i, noTimeout);
}
else if (win.requestAnimationFrame) {
// If available, do requestAnimationFrame - shaves off a few ms
win.requestAnimationFrame(function () {
eachAsync(arr, fn, finalFunc, chunkSize, i);
});
}
else {
setTimeout(function () {
eachAsync(arr, fn, finalFunc, chunkSize, i);
});
}
}
else if (finalFunc) {
finalFunc();
}
}
}
/**
* Returns true if the current browser supports webgl
*
* @private
* @function hasWebGLSupport
*
* @return {boolean}
*/
function hasWebGLSupport() {
var i = 0, canvas, contexts = ['webgl', 'experimental-webgl', 'moz-webgl', 'webkit-3d'], context = false;
if (typeof win.WebGLRenderingContext !== 'undefined') {
canvas = doc.createElement('canvas');
for (; i < contexts.length; i++) {
try {
context = canvas.getContext(contexts[i]);
if (typeof context !== 'undefined' && context !== null) {
return true;
}
}
catch (e) {
// silent error
}
}
}
return false;
}
/* eslint-disable no-invalid-this */
/**
* Used for treemap|heatmap.drawPoints
*
* @private
* @function pointDrawHandler
*
* @param {Function} proceed
*
* @return {*}
*/
function pointDrawHandler(proceed) {
var enabled = true, renderer;
if (this.chart.options && this.chart.options.boost) {
enabled = typeof this.chart.options.boost.enabled === 'undefined' ?
true :
this.chart.options.boost.enabled;
}
if (!enabled || !this.isSeriesBoosting) {
return proceed.call(this);
}
this.chart.isBoosting = true;
// Make sure we have a valid OGL context
renderer = createAndAttachRenderer(this.chart, this);
if (renderer) {
allocateIfNotSeriesBoosting(renderer, this);
renderer.pushSeries(this);
}
renderIfNotSeriesBoosting(renderer, this);
}
/* eslint-enable no-invalid-this, valid-jsdoc */
var funs = {
patientMax: patientMax,
boostEnabled: boostEnabled,
shouldForceChartSeriesBoosting: shouldForceChartSeriesBoosting,
renderIfNotSeriesBoosting: renderIfNotSeriesBoosting,
allocateIfNotSeriesBoosting: allocateIfNotSeriesBoosting,
eachAsync: eachAsync,
hasWebGLSupport: hasWebGLSupport,
pointDrawHandler: pointDrawHandler
};
// This needs to be fixed.
H.hasWebGLSupport = hasWebGLSupport;
export default funs;

View File

@@ -0,0 +1,34 @@
/* *
*
* Copyright (c) 2019-2020 Highsoft AS
*
* Boost module: stripped-down renderer for higher performance
*
* License: highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../parts/Globals.js';
import butils from './boost-utils.js';
import init from './boost-init.js';
import './boost-overrides.js';
import './named-colors.js';
import U from '../../parts/Utilities.js';
var error = U.error;
// These need to be fixed when we support named imports
var hasWebGLSupport = butils.hasWebGLSupport;
if (!hasWebGLSupport()) {
if (typeof H.initCanvasBoost !== 'undefined') {
// Fallback to canvas boost
H.initCanvasBoost();
}
else {
error(26);
}
}
else {
// WebGL support is alright, and we're good to go.
init();
}

View File

@@ -0,0 +1,18 @@
/* *
*
* Copyright (c) 2019-2020 Highsoft AS
*
* Boost module: stripped-down renderer for higher performance
*
* License: highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
import boostables from './boostables.js';
// These are the series we allow boosting for.
var boostableMap = {};
boostables.forEach(function (item) {
boostableMap[item] = 1;
});
export default boostableMap;

View File

@@ -0,0 +1,25 @@
/* *
*
* Copyright (c) 2019-2020 Highsoft AS
*
* Boost module: stripped-down renderer for higher performance
*
* License: highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
// These are the series we allow boosting for.
var boostables = [
'area',
'arearange',
'column',
'columnrange',
'bar',
'line',
'scatter',
'heatmap',
'bubble',
'treemap'
];
export default boostables;

View File

@@ -0,0 +1,162 @@
/* *
*
* Copyright (c) 2019-2020 Highsoft AS
*
* Boost module: stripped-down renderer for higher performance
*
* License: highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import Color from '../../parts/Color.js';
// Register color names since GL can't render those directly.
// TODO: When supporting modern syntax, make this a const and a named export
var defaultHTMLColorMap = {
aliceblue: '#f0f8ff',
antiquewhite: '#faebd7',
aqua: '#00ffff',
aquamarine: '#7fffd4',
azure: '#f0ffff',
beige: '#f5f5dc',
bisque: '#ffe4c4',
black: '#000000',
blanchedalmond: '#ffebcd',
blue: '#0000ff',
blueviolet: '#8a2be2',
brown: '#a52a2a',
burlywood: '#deb887',
cadetblue: '#5f9ea0',
chartreuse: '#7fff00',
chocolate: '#d2691e',
coral: '#ff7f50',
cornflowerblue: '#6495ed',
cornsilk: '#fff8dc',
crimson: '#dc143c',
cyan: '#00ffff',
darkblue: '#00008b',
darkcyan: '#008b8b',
darkgoldenrod: '#b8860b',
darkgray: '#a9a9a9',
darkgreen: '#006400',
darkkhaki: '#bdb76b',
darkmagenta: '#8b008b',
darkolivegreen: '#556b2f',
darkorange: '#ff8c00',
darkorchid: '#9932cc',
darkred: '#8b0000',
darksalmon: '#e9967a',
darkseagreen: '#8fbc8f',
darkslateblue: '#483d8b',
darkslategray: '#2f4f4f',
darkturquoise: '#00ced1',
darkviolet: '#9400d3',
deeppink: '#ff1493',
deepskyblue: '#00bfff',
dimgray: '#696969',
dodgerblue: '#1e90ff',
feldspar: '#d19275',
firebrick: '#b22222',
floralwhite: '#fffaf0',
forestgreen: '#228b22',
fuchsia: '#ff00ff',
gainsboro: '#dcdcdc',
ghostwhite: '#f8f8ff',
gold: '#ffd700',
goldenrod: '#daa520',
gray: '#808080',
green: '#008000',
greenyellow: '#adff2f',
honeydew: '#f0fff0',
hotpink: '#ff69b4',
indianred: '#cd5c5c',
indigo: '#4b0082',
ivory: '#fffff0',
khaki: '#f0e68c',
lavender: '#e6e6fa',
lavenderblush: '#fff0f5',
lawngreen: '#7cfc00',
lemonchiffon: '#fffacd',
lightblue: '#add8e6',
lightcoral: '#f08080',
lightcyan: '#e0ffff',
lightgoldenrodyellow: '#fafad2',
lightgrey: '#d3d3d3',
lightgreen: '#90ee90',
lightpink: '#ffb6c1',
lightsalmon: '#ffa07a',
lightseagreen: '#20b2aa',
lightskyblue: '#87cefa',
lightslateblue: '#8470ff',
lightslategray: '#778899',
lightsteelblue: '#b0c4de',
lightyellow: '#ffffe0',
lime: '#00ff00',
limegreen: '#32cd32',
linen: '#faf0e6',
magenta: '#ff00ff',
maroon: '#800000',
mediumaquamarine: '#66cdaa',
mediumblue: '#0000cd',
mediumorchid: '#ba55d3',
mediumpurple: '#9370d8',
mediumseagreen: '#3cb371',
mediumslateblue: '#7b68ee',
mediumspringgreen: '#00fa9a',
mediumturquoise: '#48d1cc',
mediumvioletred: '#c71585',
midnightblue: '#191970',
mintcream: '#f5fffa',
mistyrose: '#ffe4e1',
moccasin: '#ffe4b5',
navajowhite: '#ffdead',
navy: '#000080',
oldlace: '#fdf5e6',
olive: '#808000',
olivedrab: '#6b8e23',
orange: '#ffa500',
orangered: '#ff4500',
orchid: '#da70d6',
palegoldenrod: '#eee8aa',
palegreen: '#98fb98',
paleturquoise: '#afeeee',
palevioletred: '#d87093',
papayawhip: '#ffefd5',
peachpuff: '#ffdab9',
peru: '#cd853f',
pink: '#ffc0cb',
plum: '#dda0dd',
powderblue: '#b0e0e6',
purple: '#800080',
red: '#ff0000',
rosybrown: '#bc8f8f',
royalblue: '#4169e1',
saddlebrown: '#8b4513',
salmon: '#fa8072',
sandybrown: '#f4a460',
seagreen: '#2e8b57',
seashell: '#fff5ee',
sienna: '#a0522d',
silver: '#c0c0c0',
skyblue: '#87ceeb',
slateblue: '#6a5acd',
slategray: '#708090',
snow: '#fffafa',
springgreen: '#00ff7f',
steelblue: '#4682b4',
tan: '#d2b48c',
teal: '#008080',
thistle: '#d8bfd8',
tomato: '#ff6347',
turquoise: '#40e0d0',
violet: '#ee82ee',
violetred: '#d02090',
wheat: '#f5deb3',
white: '#ffffff',
whitesmoke: '#f5f5f5',
yellow: '#ffff00',
yellowgreen: '#9acd32'
};
Color.names = defaultHTMLColorMap;
export default defaultHTMLColorMap;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,471 @@
/* *
*
* Copyright (c) 2019-2020 Highsoft AS
*
* Boost module: stripped-down renderer for higher performance
*
* License: highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../parts/Globals.js';
import U from '../../parts/Utilities.js';
var clamp = U.clamp, error = U.error;
var pick = H.pick;
/* eslint-disable valid-jsdoc */
/**
* A static shader mimicing axis translation functions found in parts/Axis
*
* @private
* @function GLShader
*
* @param {WebGLContext} gl
* the context in which the shader is active
*
* @return {*}
*/
function GLShader(gl) {
var vertShade = [
/* eslint-disable max-len, @typescript-eslint/indent */
'#version 100',
'#define LN10 2.302585092994046',
'precision highp float;',
'attribute vec4 aVertexPosition;',
'attribute vec4 aColor;',
'varying highp vec2 position;',
'varying highp vec4 vColor;',
'uniform mat4 uPMatrix;',
'uniform float pSize;',
'uniform float translatedThreshold;',
'uniform bool hasThreshold;',
'uniform bool skipTranslation;',
'uniform float xAxisTrans;',
'uniform float xAxisMin;',
'uniform float xAxisMinPad;',
'uniform float xAxisPointRange;',
'uniform float xAxisLen;',
'uniform bool xAxisPostTranslate;',
'uniform float xAxisOrdinalSlope;',
'uniform float xAxisOrdinalOffset;',
'uniform float xAxisPos;',
'uniform bool xAxisCVSCoord;',
'uniform bool xAxisIsLog;',
'uniform bool xAxisReversed;',
'uniform float yAxisTrans;',
'uniform float yAxisMin;',
'uniform float yAxisMinPad;',
'uniform float yAxisPointRange;',
'uniform float yAxisLen;',
'uniform bool yAxisPostTranslate;',
'uniform float yAxisOrdinalSlope;',
'uniform float yAxisOrdinalOffset;',
'uniform float yAxisPos;',
'uniform bool yAxisCVSCoord;',
'uniform bool yAxisIsLog;',
'uniform bool yAxisReversed;',
'uniform bool isBubble;',
'uniform bool bubbleSizeByArea;',
'uniform float bubbleZMin;',
'uniform float bubbleZMax;',
'uniform float bubbleZThreshold;',
'uniform float bubbleMinSize;',
'uniform float bubbleMaxSize;',
'uniform bool bubbleSizeAbs;',
'uniform bool isInverted;',
'float bubbleRadius(){',
'float value = aVertexPosition.w;',
'float zMax = bubbleZMax;',
'float zMin = bubbleZMin;',
'float radius = 0.0;',
'float pos = 0.0;',
'float zRange = zMax - zMin;',
'if (bubbleSizeAbs){',
'value = value - bubbleZThreshold;',
'zMax = max(zMax - bubbleZThreshold, zMin - bubbleZThreshold);',
'zMin = 0.0;',
'}',
'if (value < zMin){',
'radius = bubbleZMin / 2.0 - 1.0;',
'} else {',
'pos = zRange > 0.0 ? (value - zMin) / zRange : 0.5;',
'if (bubbleSizeByArea && pos > 0.0){',
'pos = sqrt(pos);',
'}',
'radius = ceil(bubbleMinSize + pos * (bubbleMaxSize - bubbleMinSize)) / 2.0;',
'}',
'return radius * 2.0;',
'}',
'float translate(float val,',
'float pointPlacement,',
'float localA,',
'float localMin,',
'float minPixelPadding,',
'float pointRange,',
'float len,',
'bool cvsCoord,',
'bool isLog,',
'bool reversed',
'){',
'float sign = 1.0;',
'float cvsOffset = 0.0;',
'if (cvsCoord) {',
'sign *= -1.0;',
'cvsOffset = len;',
'}',
'if (isLog) {',
'val = log(val) / LN10;',
'}',
'if (reversed) {',
'sign *= -1.0;',
'cvsOffset -= sign * len;',
'}',
'return sign * (val - localMin) * localA + cvsOffset + ',
'(sign * minPixelPadding);',
'}',
'float xToPixels(float value) {',
'if (skipTranslation){',
'return value;// + xAxisPos;',
'}',
'return translate(value, 0.0, xAxisTrans, xAxisMin, xAxisMinPad, xAxisPointRange, xAxisLen, xAxisCVSCoord, xAxisIsLog, xAxisReversed);// + xAxisPos;',
'}',
'float yToPixels(float value, float checkTreshold) {',
'float v;',
'if (skipTranslation){',
'v = value;// + yAxisPos;',
'} else {',
'v = translate(value, 0.0, yAxisTrans, yAxisMin, yAxisMinPad, yAxisPointRange, yAxisLen, yAxisCVSCoord, yAxisIsLog, yAxisReversed);// + yAxisPos;',
'if (v > yAxisLen) {',
'v = yAxisLen;',
'}',
'}',
'if (checkTreshold > 0.0 && hasThreshold) {',
'v = min(v, translatedThreshold);',
'}',
'return v;',
'}',
'void main(void) {',
'if (isBubble){',
'gl_PointSize = bubbleRadius();',
'} else {',
'gl_PointSize = pSize;',
'}',
// 'gl_PointSize = 10.0;',
'vColor = aColor;',
'if (skipTranslation && isInverted) {',
// If we get translated values from JS, just swap them (x, y)
'gl_Position = uPMatrix * vec4(aVertexPosition.y + yAxisPos, aVertexPosition.x + xAxisPos, 0.0, 1.0);',
'} else if (isInverted) {',
// But when calculating pixel positions directly,
// swap axes and values (x, y)
'gl_Position = uPMatrix * vec4(yToPixels(aVertexPosition.y, aVertexPosition.z) + yAxisPos, xToPixels(aVertexPosition.x) + xAxisPos, 0.0, 1.0);',
'} else {',
'gl_Position = uPMatrix * vec4(xToPixels(aVertexPosition.x) + xAxisPos, yToPixels(aVertexPosition.y, aVertexPosition.z) + yAxisPos, 0.0, 1.0);',
'}',
// 'gl_Position = uPMatrix * vec4(aVertexPosition.x, aVertexPosition.y, 0.0, 1.0);',
'}'
/* eslint-enable max-len, @typescript-eslint/indent */
].join('\n'),
// Fragment shader source
fragShade = [
/* eslint-disable max-len, @typescript-eslint/indent */
'precision highp float;',
'uniform vec4 fillColor;',
'varying highp vec2 position;',
'varying highp vec4 vColor;',
'uniform sampler2D uSampler;',
'uniform bool isCircle;',
'uniform bool hasColor;',
// 'vec4 toColor(float value, vec2 point) {',
// 'return vec4(0.0, 0.0, 0.0, 0.0);',
// '}',
'void main(void) {',
'vec4 col = fillColor;',
'vec4 tcol;',
'if (hasColor) {',
'col = vColor;',
'}',
'if (isCircle) {',
'tcol = texture2D(uSampler, gl_PointCoord.st);',
'col *= tcol;',
'if (tcol.r < 0.0) {',
'discard;',
'} else {',
'gl_FragColor = col;',
'}',
'} else {',
'gl_FragColor = col;',
'}',
'}'
/* eslint-enable max-len, @typescript-eslint/indent */
].join('\n'), uLocations = {},
// The shader program
shaderProgram,
// Uniform handle to the perspective matrix
pUniform,
// Uniform for point size
psUniform,
// Uniform for fill color
fillColorUniform,
// Uniform for isBubble
isBubbleUniform,
// Uniform for bubble abs sizing
bubbleSizeAbsUniform, bubbleSizeAreaUniform,
// Skip translation uniform
skipTranslationUniform,
// Set to 1 if circle
isCircleUniform,
// Uniform for invertion
isInverted,
// Error stack
errors = [],
// Texture uniform
uSamplerUniform;
/**
* Handle errors accumulated in errors stack
* @private
*/
function handleErrors() {
if (errors.length) {
error('[highcharts boost] shader error - ' + errors.join('\n'));
}
}
/**
* String to shader program
* @private
* @param {string} str - the program source
* @param {string} type - the program type: either `vertex` or `fragment`
* @returns {bool|shader}
*/
function stringToProgram(str, type) {
var t = type === 'vertex' ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER, shader = gl.createShader(t);
gl.shaderSource(shader, str);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
errors.push('when compiling ' +
type +
' shader:\n' +
gl.getShaderInfoLog(shader));
return false;
}
return shader;
}
/**
* Create the shader.
* Loads the shader program statically defined above
* @private
*/
function createShader() {
var v = stringToProgram(vertShade, 'vertex'), f = stringToProgram(fragShade, 'fragment');
if (!v || !f) {
shaderProgram = false;
handleErrors();
return false;
}
/**
* @private
*/
function uloc(n) {
return gl.getUniformLocation(shaderProgram, n);
}
shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, v);
gl.attachShader(shaderProgram, f);
gl.linkProgram(shaderProgram);
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
errors.push(gl.getProgramInfoLog(shaderProgram));
handleErrors();
shaderProgram = false;
return false;
}
gl.useProgram(shaderProgram);
gl.bindAttribLocation(shaderProgram, 0, 'aVertexPosition');
pUniform = uloc('uPMatrix');
psUniform = uloc('pSize');
fillColorUniform = uloc('fillColor');
isBubbleUniform = uloc('isBubble');
bubbleSizeAbsUniform = uloc('bubbleSizeAbs');
bubbleSizeAreaUniform = uloc('bubbleSizeByArea');
uSamplerUniform = uloc('uSampler');
skipTranslationUniform = uloc('skipTranslation');
isCircleUniform = uloc('isCircle');
isInverted = uloc('isInverted');
return true;
}
/**
* Destroy the shader
* @private
*/
function destroy() {
if (gl && shaderProgram) {
gl.deleteProgram(shaderProgram);
shaderProgram = false;
}
}
/**
* Bind the shader.
* This makes the shader the active one until another one is bound,
* or until 0 is bound.
* @private
*/
function bind() {
if (gl && shaderProgram) {
gl.useProgram(shaderProgram);
}
}
/**
* Set a uniform value.
* This uses a hash map to cache uniform locations.
* @private
* @param name {string} - the name of the uniform to set
* @param val {float} - the value to set
*/
function setUniform(name, val) {
if (gl && shaderProgram) {
var u = uLocations[name] = (uLocations[name] ||
gl.getUniformLocation(shaderProgram, name));
gl.uniform1f(u, val);
}
}
/**
* Set the active texture
* @private
* @param texture - the texture
*/
function setTexture(texture) {
if (gl && shaderProgram) {
gl.uniform1i(uSamplerUniform, texture);
}
}
/**
* Set if inversion state
* @private
* @flag is the state
*/
function setInverted(flag) {
if (gl && shaderProgram) {
gl.uniform1i(isInverted, flag);
}
}
/**
* Enable/disable circle drawing
* @private
*/
function setDrawAsCircle(flag) {
if (gl && shaderProgram) {
gl.uniform1i(isCircleUniform, flag ? 1 : 0);
}
}
/**
* Flush
* @private
*/
function reset() {
if (gl && shaderProgram) {
gl.uniform1i(isBubbleUniform, 0);
gl.uniform1i(isCircleUniform, 0);
}
}
/**
* Set bubble uniforms
* @private
* @param series {Highcharts.Series} - the series to use
*/
function setBubbleUniforms(series, zCalcMin, zCalcMax) {
var seriesOptions = series.options, zMin = Number.MAX_VALUE, zMax = -Number.MAX_VALUE;
if (gl && shaderProgram && series.type === 'bubble') {
zMin = pick(seriesOptions.zMin, clamp(zCalcMin, seriesOptions.displayNegative === false ?
seriesOptions.zThreshold : -Number.MAX_VALUE, zMin));
zMax = pick(seriesOptions.zMax, Math.max(zMax, zCalcMax));
gl.uniform1i(isBubbleUniform, 1);
gl.uniform1i(isCircleUniform, 1);
gl.uniform1i(bubbleSizeAreaUniform, (series.options.sizeBy !== 'width'));
gl.uniform1i(bubbleSizeAbsUniform, series.options
.sizeByAbsoluteValue);
setUniform('bubbleZMin', zMin);
setUniform('bubbleZMax', zMax);
setUniform('bubbleZThreshold', series.options.zThreshold);
setUniform('bubbleMinSize', series.minPxSize);
setUniform('bubbleMaxSize', series.maxPxSize);
}
}
/**
* Set the Color uniform.
* @private
* @param color {Array<float>} - an array with RGBA values
*/
function setColor(color) {
if (gl && shaderProgram) {
gl.uniform4f(fillColorUniform, color[0] / 255.0, color[1] / 255.0, color[2] / 255.0, color[3]);
}
}
/**
* Set skip translation
* @private
*/
function setSkipTranslation(flag) {
if (gl && shaderProgram) {
gl.uniform1i(skipTranslationUniform, flag === true ? 1 : 0);
}
}
/**
* Set the perspective matrix
* @private
* @param m {Matrix4x4} - the matrix
*/
function setPMatrix(m) {
if (gl && shaderProgram) {
gl.uniformMatrix4fv(pUniform, false, m);
}
}
/**
* Set the point size.
* @private
* @param p {float} - point size
*/
function setPointSize(p) {
if (gl && shaderProgram) {
gl.uniform1f(psUniform, p);
}
}
/**
* Get the shader program handle
* @private
* @return {GLInt} - the handle for the program
*/
function getProgram() {
return shaderProgram;
}
if (gl) {
if (!createShader()) {
return false;
}
}
return {
psUniform: function () {
return psUniform;
},
pUniform: function () {
return pUniform;
},
fillColorUniform: function () {
return fillColorUniform;
},
setBubbleUniforms: setBubbleUniforms,
bind: bind,
program: getProgram,
create: createShader,
setUniform: setUniform,
setPMatrix: setPMatrix,
setColor: setColor,
setPointSize: setPointSize,
setSkipTranslation: setSkipTranslation,
setTexture: setTexture,
setDrawAsCircle: setDrawAsCircle,
reset: reset,
setInverted: setInverted,
destroy: destroy
};
}
export default GLShader;

View File

@@ -0,0 +1,153 @@
/* *
*
* Copyright (c) 2019-2020 Highsoft AS
*
* Boost module: stripped-down renderer for higher performance
*
* License: highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
/* eslint-disable valid-jsdoc */
/**
* Vertex Buffer abstraction.
* A vertex buffer is a set of vertices which are passed to the GPU
* in a single call.
*
* @private
* @function GLVertexBuffer
*
* @param {WebGLContext} gl
* the context in which to create the buffer
*
* @param {GLShader} shader
* the shader to use
*
* @return {*}
*/
function GLVertexBuffer(gl, shader, dataComponents
/* , type */
) {
var buffer = false, vertAttribute = false, components = dataComponents || 2, preAllocated = false, iterator = 0,
// farray = false,
data;
// type = type || 'float';
/**
* @private
*/
function destroy() {
if (buffer) {
gl.deleteBuffer(buffer);
buffer = false;
vertAttribute = false;
}
iterator = 0;
components = dataComponents || 2;
data = [];
}
/**
* Build the buffer
* @private
* @param dataIn {Array<float>} - a 0 padded array of indices
* @param attrib {String} - the name of the Attribute to bind the buffer to
* @param dataComponents {Integer} - the number of components per. indice
*/
function build(dataIn, attrib, dataComponents) {
var farray;
data = dataIn || [];
if ((!data || data.length === 0) && !preAllocated) {
// console.error('trying to render empty vbuffer');
destroy();
return false;
}
components = dataComponents || components;
if (buffer) {
gl.deleteBuffer(buffer);
}
if (!preAllocated) {
farray = new Float32Array(data);
}
buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, preAllocated || farray, gl.STATIC_DRAW);
// gl.bindAttribLocation(shader.program(), 0, 'aVertexPosition');
vertAttribute = gl.getAttribLocation(shader.program(), attrib);
gl.enableVertexAttribArray(vertAttribute);
// Trigger cleanup
farray = false;
return true;
}
/**
* Bind the buffer
* @private
*/
function bind() {
if (!buffer) {
return false;
}
// gl.bindAttribLocation(shader.program(), 0, 'aVertexPosition');
// gl.enableVertexAttribArray(vertAttribute);
// gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.vertexAttribPointer(vertAttribute, components, gl.FLOAT, false, 0, 0);
// gl.enableVertexAttribArray(vertAttribute);
}
/**
* Render the buffer
* @private
* @param from {Integer} - the start indice
* @param to {Integer} - the end indice
* @param drawMode {String} - the draw mode
*/
function render(from, to, drawMode) {
var length = preAllocated ? preAllocated.length : data.length;
if (!buffer) {
return false;
}
if (!length) {
return false;
}
if (!from || from > length || from < 0) {
from = 0;
}
if (!to || to > length) {
to = length;
}
drawMode = drawMode || 'points';
gl.drawArrays(gl[drawMode.toUpperCase()], from / components, (to - from) / components);
return true;
}
/**
* @private
*/
function push(x, y, a, b) {
if (preAllocated) { // && iterator <= preAllocated.length - 4) {
preAllocated[++iterator] = x;
preAllocated[++iterator] = y;
preAllocated[++iterator] = a;
preAllocated[++iterator] = b;
}
}
/**
* Note about pre-allocated buffers:
* - This is slower for charts with many series
* @private
*/
function allocate(size) {
size *= 4;
iterator = -1;
preAllocated = new Float32Array(size);
}
// /////////////////////////////////////////////////////////////////////////
return {
destroy: destroy,
bind: bind,
data: data,
build: build,
render: render,
allocate: allocate,
push: push
};
}
export default GLVertexBuffer;

View File

@@ -0,0 +1,448 @@
/* *
*
* (c) 2009-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../parts/Globals.js';
import U from '../parts/Utilities.js';
var addEvent = U.addEvent, extend = U.extend, find = U.find, fireEvent = U.fireEvent, isArray = U.isArray, pick = U.pick;
import '../parts/Axis.js';
import '../parts/Series.js';
var Axis = H.Axis, Series = H.Series;
/**
* Returns the first break found where the x is larger then break.from and
* smaller then break.to.
*
* @param {number} x
* The number which should be within a break.
* @param {Array<Highcharts.XAxisBreaksOptions>} breaks
* The array of breaks to search within.
* @return {Highcharts.XAxisBreaksOptions|undefined}
* Returns the first break found that matches, returns false if no break
* is found.
*/
var findBreakAt = function (x, breaks) {
return find(breaks, function (b) {
return b.from < x && x < b.to;
});
};
extend(Axis.prototype, {
isInBreak: function (brk, val) {
var ret, repeat = brk.repeat || Infinity, from = brk.from, length = brk.to - brk.from, test = (val >= from ?
(val - from) % repeat :
repeat - ((from - val) % repeat));
if (!brk.inclusive) {
ret = test < length && test !== 0;
}
else {
ret = test <= length;
}
return ret;
},
isInAnyBreak: function (val, testKeep) {
var breaks = this.options.breaks, i = breaks && breaks.length, inbrk, keep, ret;
if (i) {
while (i--) {
if (this.isInBreak(breaks[i], val)) {
inbrk = true;
if (!keep) {
keep = pick(breaks[i].showPoints, !this.isXAxis);
}
}
}
if (inbrk && testKeep) {
ret = inbrk && !keep;
}
else {
ret = inbrk;
}
}
return ret;
}
});
/* eslint-disable no-invalid-this */
addEvent(Axis, 'afterInit', function () {
if (typeof this.setBreaks === 'function') {
this.setBreaks(this.options.breaks, false);
}
});
addEvent(Axis, 'afterSetTickPositions', function () {
if (this.isBroken) {
var axis = this, tickPositions = this.tickPositions, info = this.tickPositions.info, newPositions = [], i;
for (i = 0; i < tickPositions.length; i++) {
if (!axis.isInAnyBreak(tickPositions[i])) {
newPositions.push(tickPositions[i]);
}
}
this.tickPositions = newPositions;
this.tickPositions.info = info;
}
});
// Force Axis to be not-ordinal when breaks are defined
addEvent(Axis, 'afterSetOptions', function () {
if (this.isBroken) {
this.options.ordinal = false;
}
});
/**
* Dynamically set or unset breaks in an axis. This function in lighter than
* usin Axis.update, and it also preserves animation.
*
* @private
* @function Highcharts.Axis#setBreaks
*
* @param {Array<Highcharts.XAxisBreaksOptions>} [breaks]
* The breaks to add. When `undefined` it removes existing breaks.
*
* @param {boolean} [redraw=true]
* Whether to redraw the chart immediately.
*
* @return {void}
*/
Axis.prototype.setBreaks = function (breaks, redraw) {
var axis = this, isBroken = (isArray(breaks) && !!breaks.length);
/* eslint-disable valid-jsdoc */
/**
* @private
*/
function breakVal2Lin(val) {
var nval = val, brk, i;
for (i = 0; i < axis.breakArray.length; i++) {
brk = axis.breakArray[i];
if (brk.to <= val) {
nval -= brk.len;
}
else if (brk.from >= val) {
break;
}
else if (axis.isInBreak(brk, val)) {
nval -= (val - brk.from);
break;
}
}
return nval;
}
/**
* @private
*/
function breakLin2Val(val) {
var nval = val, brk, i;
for (i = 0; i < axis.breakArray.length; i++) {
brk = axis.breakArray[i];
if (brk.from >= nval) {
break;
}
else if (brk.to < nval) {
nval += brk.len;
}
else if (axis.isInBreak(brk, nval)) {
nval += brk.len;
}
}
return nval;
}
/* eslint-enable valid-jsdoc */
axis.isDirty = axis.isBroken !== isBroken;
axis.isBroken = isBroken;
axis.options.breaks = axis.userOptions.breaks = breaks;
axis.forceRedraw = true; // Force recalculation in setScale
// Recalculate series related to the axis.
axis.series.forEach(function (series) {
series.isDirty = true;
});
if (!isBroken && axis.val2lin === breakVal2Lin) {
// Revert to prototype functions
delete axis.val2lin;
delete axis.lin2val;
}
if (isBroken) {
axis.userOptions.ordinal = false;
axis.val2lin = breakVal2Lin;
axis.lin2val = breakLin2Val;
axis.setExtremes = function (newMin, newMax, redraw, animation, eventArguments) {
// If trying to set extremes inside a break, extend min to after,
// and max to before the break ( #3857 )
if (this.isBroken) {
var axisBreak, breaks = this.options.breaks;
while ((axisBreak = findBreakAt(newMin, breaks))) {
newMin = axisBreak.to;
}
while ((axisBreak = findBreakAt(newMax, breaks))) {
newMax = axisBreak.from;
}
// If both min and max is within the same break.
if (newMax < newMin) {
newMax = newMin;
}
}
Axis.prototype.setExtremes.call(this, newMin, newMax, redraw, animation, eventArguments);
};
axis.setAxisTranslation = function (saveOld) {
Axis.prototype.setAxisTranslation.call(this, saveOld);
this.unitLength = null;
if (this.isBroken) {
var breaks = axis.options.breaks,
// Temporary one:
breakArrayT = [], breakArray = [], length = 0, inBrk, repeat, min = axis.userMin || axis.min, max = axis.userMax || axis.max, pointRangePadding = pick(axis.pointRangePadding, 0), start, i;
// Min & max check (#4247)
breaks.forEach(function (brk) {
repeat = brk.repeat || Infinity;
if (axis.isInBreak(brk, min)) {
min +=
(brk.to % repeat) -
(min % repeat);
}
if (axis.isInBreak(brk, max)) {
max -=
(max % repeat) -
(brk.from % repeat);
}
});
// Construct an array holding all breaks in the axis
breaks.forEach(function (brk) {
start = brk.from;
repeat = brk.repeat || Infinity;
while (start - repeat > min) {
start -= repeat;
}
while (start < min) {
start += repeat;
}
for (i = start; i < max; i += repeat) {
breakArrayT.push({
value: i,
move: 'in'
});
breakArrayT.push({
value: i + (brk.to - brk.from),
move: 'out',
size: brk.breakSize
});
}
});
breakArrayT.sort(function (a, b) {
return ((a.value === b.value) ?
((a.move === 'in' ? 0 : 1) -
(b.move === 'in' ? 0 : 1)) :
a.value - b.value);
});
// Simplify the breaks
inBrk = 0;
start = min;
breakArrayT.forEach(function (brk) {
inBrk += (brk.move === 'in' ? 1 : -1);
if (inBrk === 1 && brk.move === 'in') {
start = brk.value;
}
if (inBrk === 0) {
breakArray.push({
from: start,
to: brk.value,
len: brk.value - start - (brk.size || 0)
});
length += brk.value - start - (brk.size || 0);
}
});
axis.breakArray = breakArray;
// Used with staticScale, and below, the actual axis length when
// breaks are substracted.
axis.unitLength =
max - min - length + pointRangePadding;
fireEvent(axis, 'afterBreaks');
if (axis.staticScale) {
axis.transA = axis.staticScale;
}
else if (axis.unitLength) {
axis.transA *=
(max - axis.min + pointRangePadding) /
axis.unitLength;
}
if (pointRangePadding) {
axis.minPixelPadding =
axis.transA * axis.minPointOffset;
}
axis.min = min;
axis.max = max;
}
};
}
if (pick(redraw, true)) {
this.chart.redraw();
}
};
addEvent(Series, 'afterGeneratePoints', function () {
var _a = this, isDirty = _a.isDirty, connectNulls = _a.options.connectNulls, points = _a.points, xAxis = _a.xAxis, yAxis = _a.yAxis;
/* Set, or reset visibility of the points. Axis.setBreaks marks the series
as isDirty */
if (isDirty) {
var i = points.length;
while (i--) {
var point = points[i];
// Respect nulls inside the break (#4275)
var nullGap = point.y === null && connectNulls === false;
var isPointInBreak = (!nullGap &&
(xAxis && xAxis.isInAnyBreak(point.x, true) ||
yAxis && yAxis.isInAnyBreak(point.y, true)));
// Set point.visible if in any break.
// If not in break, reset visible to original value.
point.visible = isPointInBreak ?
false :
point.options.visible !== false;
}
}
});
addEvent(Series, 'afterRender', function drawPointsWrapped() {
this.drawBreaks(this.xAxis, ['x']);
this.drawBreaks(this.yAxis, pick(this.pointArrayMap, ['y']));
});
/* eslint-enable no-invalid-this */
H.Series.prototype.drawBreaks = function (axis, keys) {
var series = this, points = series.points, breaks, threshold, eventName, y;
if (!axis) {
return; // #5950
}
keys.forEach(function (key) {
breaks = axis.breakArray || [];
threshold = axis.isXAxis ?
axis.min :
pick(series.options.threshold, axis.min);
points.forEach(function (point) {
y = pick(point['stack' + key.toUpperCase()], point[key]);
breaks.forEach(function (brk) {
eventName = false;
if ((threshold < brk.from &&
y > brk.to) ||
(threshold > brk.from &&
y < brk.from)) {
eventName = 'pointBreak';
}
else if ((threshold < brk.from &&
y > brk.from &&
y < brk.to) ||
(threshold > brk.from &&
y > brk.to &&
y < brk.from)) {
eventName = 'pointInBreak';
}
if (eventName) {
fireEvent(axis, eventName, { point: point, brk: brk });
}
});
});
});
};
/**
* Extend getGraphPath by identifying gaps in the data so that we can draw a gap
* in the line or area. This was moved from ordinal axis module to broken axis
* module as of #5045.
*
* @private
* @function Highcharts.Series#gappedPath
*
* @return {Highcharts.SVGPathArray}
* Gapped path
*/
H.Series.prototype.gappedPath = function () {
var currentDataGrouping = this.currentDataGrouping, groupingSize = currentDataGrouping && currentDataGrouping.gapSize, gapSize = this.options.gapSize, points = this.points.slice(), i = points.length - 1, yAxis = this.yAxis, stack;
/**
* Defines when to display a gap in the graph, together with the
* [gapUnit](plotOptions.series.gapUnit) option.
*
* In case when `dataGrouping` is enabled, points can be grouped into a
* larger time span. This can make the grouped points to have a greater
* distance than the absolute value of `gapSize` property, which will result
* in disappearing graph completely. To prevent this situation the mentioned
* distance between grouped points is used instead of previously defined
* `gapSize`.
*
* In practice, this option is most often used to visualize gaps in
* time series. In a stock chart, intraday data is available for daytime
* hours, while gaps will appear in nights and weekends.
*
* @see [gapUnit](plotOptions.series.gapUnit)
* @see [xAxis.breaks](#xAxis.breaks)
*
* @sample {highstock} stock/plotoptions/series-gapsize/
* Setting the gap size to 2 introduces gaps for weekends in daily
* datasets.
*
* @type {number}
* @default 0
* @product highstock
* @requires modules/broken-axis
* @apioption plotOptions.series.gapSize
*/
/**
* Together with [gapSize](plotOptions.series.gapSize), this option defines
* where to draw gaps in the graph.
*
* When the `gapUnit` is `"relative"` (default), a gap size of 5 means
* that if the distance between two points is greater than five times
* that of the two closest points, the graph will be broken.
*
* When the `gapUnit` is `"value"`, the gap is based on absolute axis
* values, which on a datetime axis is milliseconds. This also applies
* to the navigator series that inherits gap options from the base series.
*
* @see [gapSize](plotOptions.series.gapSize)
*
* @type {string}
* @default relative
* @since 5.0.13
* @product highstock
* @validvalue ["relative", "value"]
* @requires modules/broken-axis
* @apioption plotOptions.series.gapUnit
*/
if (gapSize && i > 0) { // #5008
// Gap unit is relative
if (this.options.gapUnit !== 'value') {
gapSize *= this.basePointRange;
}
// Setting a new gapSize in case dataGrouping is enabled (#7686)
if (groupingSize &&
groupingSize > gapSize &&
// Except when DG is forced (e.g. from other series)
// and has lower granularity than actual points (#11351)
groupingSize >= this.basePointRange) {
gapSize = groupingSize;
}
// extension for ordinal breaks
var current = void 0, next = void 0;
while (i--) {
// Reassign next if it is not visible
if (!(next && next.visible !== false)) {
next = points[i + 1];
}
current = points[i];
// Skip iteration if one of the points is not visible
if (next.visible === false || current.visible === false) {
continue;
}
if (next.x - current.x > gapSize) {
var xRange = (current.x + next.x) / 2;
points.splice(// insert after this one
i + 1, 0, {
isNull: true,
x: xRange
});
// For stacked chart generate empty stack items, #6546
if (this.options.stacking) {
stack = yAxis.stacks[this.stackKey][xRange] =
new H.StackItem(yAxis, yAxis.options
.stackLabels, false, xRange, this.stack);
stack.total = 0;
}
}
// Assign current to next for the upcoming iteration
next = current;
}
}
// Call base method
return this.getGraphPath(points);
};

View File

@@ -0,0 +1,304 @@
/* *
*
* (c) 2010-2020 Kacper Madej
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../parts/Globals.js';
import U from '../parts/Utilities.js';
var isNumber = U.isNumber, merge = U.merge, pick = U.pick, relativeLength = U.relativeLength, seriesType = U.seriesType;
var columnProto = H.seriesTypes.column.prototype;
/**
* The bullet series type.
*
* @private
* @class
* @name Highcharts.seriesTypes.bullet
*
* @augments Highcharts.Series
*/
seriesType('bullet', 'column'
/**
* A bullet graph is a variation of a bar graph. The bullet graph features
* a single measure, compares it to a target, and displays it in the context
* of qualitative ranges of performance that could be set using
* [plotBands](#yAxis.plotBands) on [yAxis](#yAxis).
*
* @sample {highcharts} highcharts/demo/bullet-graph/
* Bullet graph
*
* @extends plotOptions.column
* @since 6.0.0
* @product highcharts
* @excluding allAreas, boostThreshold, colorAxis, compare, compareBase,
* dataSorting
* @requires modules/bullet
* @optionparent plotOptions.bullet
*/
, {
/**
* All options related with look and positiong of targets.
*
* @since 6.0.0
*/
targetOptions: {
/**
* The width of the rectangle representing the target. Could be set
* as a pixel value or as a percentage of a column width.
*
* @type {number|string}
* @since 6.0.0
*/
width: '140%',
/**
* The height of the rectangle representing the target.
*
* @since 6.0.0
*/
height: 3,
/**
* The border color of the rectangle representing the target. When
* not set, the point's border color is used.
*
* In styled mode, use class `highcharts-bullet-target` instead.
*
* @type {Highcharts.ColorString}
* @since 6.0.0
* @product highcharts
* @apioption plotOptions.bullet.targetOptions.borderColor
*/
/**
* The color of the rectangle representing the target. When not set,
* point's color (if set in point's options -
* [`color`](#series.bullet.data.color)) or zone of the target value
* (if [`zones`](#plotOptions.bullet.zones) or
* [`negativeColor`](#plotOptions.bullet.negativeColor) are set)
* or the same color as the point has is used.
*
* In styled mode, use class `highcharts-bullet-target` instead.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @since 6.0.0
* @product highcharts
* @apioption plotOptions.bullet.targetOptions.color
*/
/**
* The border width of the rectangle representing the target.
*
* In styled mode, use class `highcharts-bullet-target` instead.
*
* @since 6.0.0
*/
borderWidth: 0
},
tooltip: {
pointFormat: '<span style="color:{series.color}">\u25CF</span>' +
' {series.name}: <b>{point.y}</b>. Target: <b>{point.target}' +
'</b><br/>'
}
}, {
pointArrayMap: ['y', 'target'],
parallelArrays: ['x', 'y', 'target'],
/* eslint-disable valid-jsdoc */
/**
* Draws the targets. For inverted chart, the `series.group` is rotated,
* so the same coordinates apply. This method is based on column series
* drawPoints function.
*
* @ignore
* @function Highcharts.Series#drawPoints
*/
drawPoints: function () {
var series = this, chart = series.chart, options = series.options, animationLimit = options.animationLimit || 250;
columnProto.drawPoints.apply(this);
series.points.forEach(function (point) {
var pointOptions = point.options, shapeArgs, targetGraphic = point.targetGraphic, targetShapeArgs, targetVal = point.target, pointVal = point.y, width, height, targetOptions, y;
if (isNumber(targetVal) && targetVal !== null) {
targetOptions = merge(options.targetOptions, pointOptions.targetOptions);
height = targetOptions.height;
shapeArgs = point.shapeArgs;
width = relativeLength(targetOptions.width, shapeArgs.width);
y = series.yAxis.translate(targetVal, false, true, false, true) - targetOptions.height / 2 - 0.5;
targetShapeArgs = series.crispCol.apply({
// Use fake series object to set borderWidth of target
chart: chart,
borderWidth: targetOptions.borderWidth,
options: {
crisp: options.crisp
}
}, [
(shapeArgs.x +
shapeArgs.width / 2 - width / 2),
y,
width,
height
]);
if (targetGraphic) {
// Update
targetGraphic[chart.pointCount < animationLimit ?
'animate' :
'attr'](targetShapeArgs);
// Add or remove tooltip reference
if (isNumber(pointVal) && pointVal !== null) {
targetGraphic.element.point = point;
}
else {
targetGraphic.element.point = void 0;
}
}
else {
point.targetGraphic = targetGraphic = chart.renderer
.rect()
.attr(targetShapeArgs)
.add(series.group);
}
// Presentational
if (!chart.styledMode) {
targetGraphic.attr({
fill: pick(targetOptions.color, pointOptions.color, (series.zones.length && (point.getZone.call({
series: series,
x: point.x,
y: targetVal,
options: {}
}).color || series.color)) || void 0, point.color, series.color),
stroke: pick(targetOptions.borderColor, point.borderColor, series.options.borderColor),
'stroke-width': targetOptions.borderWidth
});
}
// Add tooltip reference
if (isNumber(pointVal) && pointVal !== null) {
targetGraphic.element.point = point;
}
targetGraphic.addClass(point.getClassName() +
' highcharts-bullet-target', true);
}
else if (targetGraphic) {
// #1269:
point.targetGraphic = targetGraphic.destroy();
}
});
},
/**
* Includes target values to extend extremes from y values.
*
* @ignore
* @function Highcharts.Series#getExtremes
*/
getExtremes: function (yData) {
var series = this, targetData = series.targetData, yMax, yMin;
columnProto.getExtremes.call(this, yData);
if (targetData && targetData.length) {
yMax = series.dataMax;
yMin = series.dataMin;
columnProto.getExtremes.call(this, targetData);
series.dataMax = Math.max(series.dataMax, yMax);
series.dataMin = Math.min(series.dataMin, yMin);
}
}
/* eslint-enable valid-jsdoc */
},
/** @lends Highcharts.seriesTypes.ohlc.prototype.pointClass.prototype */
{
// eslint-disable-next-line valid-jsdoc
/**
* Destroys target graphic.
*
* @private
* @function
*/
destroy: function () {
if (this.targetGraphic) {
this.targetGraphic = this.targetGraphic.destroy();
}
columnProto.pointClass.prototype.destroy
.apply(this, arguments);
return;
}
});
/**
* A `bullet` series. If the [type](#series.bullet.type) option is not
* specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.bullet
* @since 6.0.0
* @product highcharts
* @excluding dataParser, dataURL, marker, dataSorting
* @requires modules/bullet
* @apioption series.bullet
*/
/**
* An array of data points for the series. For the `bullet` series type,
* points can be given in the following ways:
*
* 1. An array of arrays with 3 or 2 values. In this case, the values correspond
* to `x,y,target`. If the first value is a string, it is applied as the name
* of the point, and the `x` value is inferred. The `x` value can also be
* omitted, in which case the inner arrays should be of length 2\. Then the
* `x` value is automatically calculated, either starting at 0 and
* incremented by 1, or from `pointStart` and `pointInterval` given in the
* series options.
* ```js
* data: [
* [0, 40, 75],
* [1, 50, 50],
* [2, 60, 40]
* ]
* ```
*
* 2. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.bullet.turboThreshold), this option is not
* available.
* ```js
* data: [{
* x: 0,
* y: 40,
* target: 75,
* name: "Point1",
* color: "#00FF00"
* }, {
* x: 1,
* y: 60,
* target: 40,
* name: "Point2",
* color: "#FF00FF"
* }]
* ```
*
* @type {Array<Array<(number|string),number>|Array<(number|string),number,number>|*>}
* @extends series.column.data
* @since 6.0.0
* @product highcharts
* @apioption series.bullet.data
*/
/**
* The target value of a point.
*
* @type {number}
* @since 6.0.0
* @product highcharts
* @apioption series.bullet.data.target
*/
/**
* Individual target options for each point.
*
* @extends plotOptions.bullet.targetOptions
* @product highcharts
* @apioption series.bullet.data.targetOptions
*/
/**
* @product highcharts
* @excluding halo, lineWidth, lineWidthPlus, marker
* @apioption series.bullet.states.hover
*/
/**
* @product highcharts
* @excluding halo, lineWidth, lineWidthPlus, marker
* @apioption series.bullet.states.select
*/
''; // adds doclets above to transpiled file

View File

@@ -0,0 +1,321 @@
/* *
*
* Highcharts cylinder - a 3D series
*
* (c) 2010-2020 Highsoft AS
*
* Author: Kacper Madej
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../parts/Globals.js';
import Color from '../parts/Color.js';
var color = Color.parse;
import U from '../parts/Utilities.js';
var merge = U.merge, pick = U.pick, seriesType = U.seriesType;
import '../parts/ColumnSeries.js';
import '../parts/SvgRenderer.js';
var charts = H.charts, deg2rad = H.deg2rad, perspective = H.perspective,
// Work on H.Renderer instead of H.SVGRenderer for VML support.
RendererProto = H.Renderer.prototype, cuboidPath = RendererProto.cuboidPath, cylinderMethods;
/**
* The cylinder series type.
*
* @requires module:highcharts-3d
* @requires module:modules/cylinder
*
* @private
* @class
* @name Highcharts.seriesTypes.cylinder
*
* @augments Highcharts.Series
*/
seriesType('cylinder', 'column',
/**
* A cylinder graph is a variation of a 3d column graph. The cylinder graph
* features cylindrical points.
*
* @sample {highcharts} highcharts/demo/cylinder/
* Cylinder graph
*
* @extends plotOptions.column
* @since 7.0.0
* @product highcharts
* @excluding allAreas, boostThreshold, colorAxis, compare, compareBase,
* dragDrop
* @requires modules/cylinder
* @optionparent plotOptions.cylinder
*/
{}, {},
/** @lends Highcharts.seriesTypes.cylinder#pointClass# */
{
shapeType: 'cylinder',
hasNewShapeType: H
.seriesTypes.column.prototype
.pointClass.prototype
.hasNewShapeType
});
/**
* A `cylinder` series. If the [type](#series.cylinder.type) option is not
* specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.cylinder
* @since 7.0.0
* @product highcharts
* @excluding allAreas, boostThreshold, colorAxis, compare, compareBase
* @requires modules/cylinder
* @apioption series.cylinder
*/
/**
* An array of data points for the series. For the `cylinder` series type,
* points can be given in the following ways:
*
* 1. An array of numerical values. In this case, the numerical values will be
* interpreted as `y` options. The `x` values will be automatically
* calculated, either starting at 0 and incremented by 1, or from
* `pointStart` and `pointInterval` given in the series options. If the axis
* has categories, these will be used. Example:
* ```js
* data: [0, 5, 3, 5]
* ```
*
* 2. An array of arrays with 2 values. In this case, the values correspond to
* `x,y`. If the first value is a string, it is applied as the name of the
* point, and the `x` value is inferred.
* ```js
* data: [
* [0, 0],
* [1, 8],
* [2, 9]
* ]
* ```
*
* 3. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.cylinder.turboThreshold), this option is not
* available.
*
* ```js
* data: [{
* x: 1,
* y: 2,
* name: "Point2",
* color: "#00FF00"
* }, {
* x: 1,
* y: 4,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @sample {highcharts} highcharts/chart/reflow-true/
* Numerical values
* @sample {highcharts} highcharts/series/data-array-of-arrays/
* Arrays of numeric x and y
* @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/
* Arrays of datetime x and y
* @sample {highcharts} highcharts/series/data-array-of-name-value/
* Arrays of point.name and y
* @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
*
* @type {Array<number|Array<(number|string),(number|null)>|null|*>}
* @extends series.column.data
* @product highcharts highstock
* @apioption series.cylinder.data
*/
// cylinder extends cuboid
cylinderMethods = merge(RendererProto.elements3d.cuboid, {
parts: ['top', 'bottom', 'front', 'back'],
pathType: 'cylinder',
fillSetter: function (fill) {
this.singleSetterForParts('fill', null, {
front: fill,
back: fill,
top: color(fill).brighten(0.1).get(),
bottom: color(fill).brighten(-0.1).get()
});
// fill for animation getter (#6776)
this.color = this.fill = fill;
return this;
}
});
RendererProto.elements3d.cylinder = cylinderMethods;
RendererProto.cylinder = function (shapeArgs) {
return this.element3d('cylinder', shapeArgs);
};
// Generates paths and zIndexes.
RendererProto.cylinderPath = function (shapeArgs) {
var renderer = this, chart = charts[renderer.chartIndex],
// decide zIndexes of parts based on cubiod logic, for consistency.
cuboidData = cuboidPath.call(renderer, shapeArgs), isTopFirst = !cuboidData.isTop, isFronFirst = !cuboidData.isFront, top = renderer.getCylinderEnd(chart, shapeArgs), bottom = renderer.getCylinderEnd(chart, shapeArgs, true);
return {
front: renderer.getCylinderFront(top, bottom),
back: renderer.getCylinderBack(top, bottom),
top: top,
bottom: bottom,
zIndexes: {
top: isTopFirst ? 3 : 0,
bottom: isTopFirst ? 0 : 3,
front: isFronFirst ? 2 : 1,
back: isFronFirst ? 1 : 2,
group: cuboidData.zIndexes.group
}
};
};
// Returns cylinder Front path
RendererProto.getCylinderFront = function (topPath, bottomPath) {
var path = topPath.slice(0, topPath.simplified ? 9 : 17);
path.push('L');
if (bottomPath.simplified) {
path = path
.concat(bottomPath.slice(7, 9))
.concat(bottomPath.slice(3, 6))
.concat(bottomPath.slice(0, 3));
// change 'M' into 'L'
path[path.length - 3] = 'L';
}
else {
path.push(bottomPath[15], bottomPath[16], 'C', bottomPath[13], bottomPath[14], bottomPath[11], bottomPath[12], bottomPath[8], bottomPath[9], 'C', bottomPath[6], bottomPath[7], bottomPath[4], bottomPath[5], bottomPath[1], bottomPath[2]);
}
path.push('Z');
return path;
};
// Returns cylinder Back path
RendererProto.getCylinderBack = function (topPath, bottomPath) {
var path = ['M'];
if (topPath.simplified) {
path = path.concat(topPath.slice(7, 12));
// end at start
path.push('L', topPath[1], topPath[2]);
}
else {
path = path.concat(topPath.slice(15));
}
path.push('L');
if (bottomPath.simplified) {
path = path
.concat(bottomPath.slice(1, 3))
.concat(bottomPath.slice(9, 12))
.concat(bottomPath.slice(6, 9));
}
else {
path.push(bottomPath[29], bottomPath[30], 'C', bottomPath[27], bottomPath[28], bottomPath[25], bottomPath[26], bottomPath[22], bottomPath[23], 'C', bottomPath[20], bottomPath[21], bottomPath[18], bottomPath[19], bottomPath[15], bottomPath[16]);
}
path.push('Z');
return path;
};
// Retruns cylinder path for top or bottom
RendererProto.getCylinderEnd = function (chart, shapeArgs, isBottom) {
// A half of the smaller one out of width or depth (optional, because
// there's no depth for a funnel that reuses the code)
var depth = pick(shapeArgs.depth, shapeArgs.width), radius = Math.min(shapeArgs.width, depth) / 2,
// Approximated longest diameter
angleOffset = deg2rad * (chart.options.chart.options3d.beta - 90 +
(shapeArgs.alphaCorrection || 0)),
// Could be top or bottom of the cylinder
y = shapeArgs.y + (isBottom ? shapeArgs.height : 0),
// Use cubic Bezier curve to draw a cricle in x,z (y is constant).
// More math. at spencermortensen.com/articles/bezier-circle/
c = 0.5519 * radius, centerX = shapeArgs.width / 2 + shapeArgs.x, centerZ = depth / 2 + shapeArgs.z,
// points could be generated in a loop, but readability will plummet
points = [{
x: 0,
y: y,
z: radius
}, {
x: c,
y: y,
z: radius
}, {
x: radius,
y: y,
z: c
}, {
x: radius,
y: y,
z: 0
}, {
x: radius,
y: y,
z: -c
}, {
x: c,
y: y,
z: -radius
}, {
x: 0,
y: y,
z: -radius
}, {
x: -c,
y: y,
z: -radius
}, {
x: -radius,
y: y,
z: -c
}, {
x: -radius,
y: y,
z: 0
}, {
x: -radius,
y: y,
z: c
}, {
x: -c,
y: y,
z: radius
}, {
x: 0,
y: y,
z: radius
}], cosTheta = Math.cos(angleOffset), sinTheta = Math.sin(angleOffset), perspectivePoints, path, x, z;
// rotete to match chart's beta and translate to the shape center
points.forEach(function (point, i) {
x = point.x;
z = point.z;
// x′ = (x * cosθ − z * sinθ) + centerX
// z′ = (z * cosθ + x * sinθ) + centerZ
points[i].x = (x * cosTheta - z * sinTheta) + centerX;
points[i].z = (z * cosTheta + x * sinTheta) + centerZ;
});
perspectivePoints = perspective(points, chart, true);
// check for sub-pixel curve issue, compare front and back edges
if (Math.abs(perspectivePoints[3].y - perspectivePoints[9].y) < 2.5 &&
Math.abs(perspectivePoints[0].y - perspectivePoints[6].y) < 2.5) {
// use simplied shape
path = this.toLinePath([
perspectivePoints[0],
perspectivePoints[3],
perspectivePoints[6],
perspectivePoints[9]
], true);
path.simplified = true;
}
else {
// or default curved path to imitate ellipse (2D circle)
path = this.getCurvedPath(perspectivePoints);
}
return path;
};
// Returns curved path in format of:
// [ M, x, y, ...[C, cp1x, cp2y, cp2x, cp2y, epx, epy]*n_times ]
// (cp - control point, ep - end point)
RendererProto.getCurvedPath = function (points) {
var path = [
'M',
points[0].x, points[0].y
], limit = points.length - 2, i;
for (i = 1; i < limit; i += 3) {
path.push('C', points[i].x, points[i].y, points[i + 1].x, points[i + 1].y, points[i + 2].x, points[i + 2].y);
}
return path;
};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,85 @@
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../parts/Globals.js';
import U from '../parts/Utilities.js';
var addEvent = U.addEvent, isNumber = U.isNumber;
var setOptions = H.setOptions, each = H.each;
setOptions({
/**
* @optionparent chart
*/
chart: {
/**
* Whether to display errors on the chart. When `false`, the errors will
* be shown only in the console.
*
* @sample highcharts/chart/display-errors/
* Show errors on chart
*
* @since 7.0.0
* @requires modules/debugger
*/
displayErrors: true
}
});
/* eslint-disable no-invalid-this */
addEvent(H.Chart, 'displayError', function (e) {
var chart = this, code = e.code, msg, options = chart.options.chart, renderer = chart.renderer, chartWidth, chartHeight;
if (chart.errorElements) {
each(chart.errorElements, function (el) {
if (el) {
el.destroy();
}
});
}
if (options && options.displayErrors && renderer) {
chart.errorElements = [];
msg = isNumber(code) ?
('Highcharts error #' + code + ': ' +
H.errorMessages[code].text) :
code;
chartWidth = chart.chartWidth;
chartHeight = chart.chartHeight;
// Format msg so SVGRenderer can handle it
msg = msg
.replace(/<h1>(.*)<\/h1>/g, '<br><span style="font-size: 24px">$1</span><br>')
.replace(/<\/p>/g, '</p><br>');
// Render red chart frame.
chart.errorElements[0] = renderer.rect(2, 2, chartWidth - 4, chartHeight - 4).attr({
'stroke-width': 4,
stroke: '#ff0000',
zIndex: 3
}).add();
// Render error message
chart.errorElements[1] = renderer.label(msg, 0, 0, 'rect', void 0, void 0, void 0, void 0, 'debugger').css({
color: '#ffffff',
width: chartWidth - 16,
padding: 0
}).attr({
fill: 'rgba(255, 0, 0, 0.9)',
width: chartWidth,
padding: 8,
zIndex: 10
}).add();
chart.errorElements[1].attr({
y: chartHeight - this.errorElements[1].getBBox().height
});
}
});
addEvent(H.Chart, 'beforeRedraw', function () {
var errorElements = this.errorElements;
if (errorElements && errorElements.length) {
each(errorElements, function (el) {
el.destroy();
});
}
this.errorElements = null;
});

View File

@@ -0,0 +1,333 @@
/* *
*
* Dependency wheel module
*
* (c) 2018-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../parts/Globals.js';
import U from '../parts/Utilities.js';
var animObject = U.animObject, seriesType = U.seriesType;
import '../parts/Options.js';
import '../mixins/nodes.js';
var base = H.seriesTypes.sankey.prototype;
/**
* @private
* @class
* @name Highcharts.seriesTypes.dependencywheel
*
* @augments Highcharts.seriesTypes.sankey
*/
seriesType('dependencywheel', 'sankey',
/**
* A dependency wheel chart is a type of flow diagram, where all nodes are
* laid out in a circle, and the flow between the are drawn as link bands.
*
* @sample highcharts/demo/dependency-wheel/
* Dependency wheel
*
* @extends plotOptions.sankey
* @exclude dataSorting
* @since 7.1.0
* @product highcharts
* @requires modules/dependencywheel
* @optionparent plotOptions.dependencywheel
*/
{
/**
* The center of the wheel relative to the plot area. Can be
* percentages or pixel values. The default behaviour is to
* center the wheel inside the plot area.
*
* @type {Array<number|string|null>}
* @default [null, null]
* @product highcharts
*/
center: [null, null],
curveFactor: 0.6,
/**
* The start angle of the dependency wheel, in degrees where 0 is up.
*/
startAngle: 0
}, {
orderNodes: false,
getCenter: H.seriesTypes.pie.prototype.getCenter,
/* eslint-disable valid-jsdoc */
/**
* Dependency wheel has only one column, it runs along the perimeter.
* @private
*/
createNodeColumns: function () {
var columns = [this.createNodeColumn()];
this.nodes.forEach(function (node) {
node.column = 0;
columns[0].push(node);
});
return columns;
},
/**
* Translate from vertical pixels to perimeter.
* @private
*/
getNodePadding: function () {
return this.options.nodePadding / Math.PI;
},
createNode: function (id) {
var node = base.createNode.call(this, id);
node.index = this.nodes.length - 1;
/**
* Return the sum of incoming and outgoing links.
* @private
*/
node.getSum = function () {
return node.linksFrom
.concat(node.linksTo)
.reduce(function (acc, link) {
return acc + link.weight;
}, 0);
};
/**
* Get the offset in weight values of a point/link.
* @private
*/
node.offset = function (point) {
var offset = 0, i, links = node.linksFrom.concat(node.linksTo), sliced;
/**
* @private
*/
function otherNode(link) {
if (link.fromNode === node) {
return link.toNode;
}
return link.fromNode;
}
// Sort and slice the links to avoid links going out of each
// node crossing each other.
links.sort(function (a, b) {
return otherNode(a).index - otherNode(b).index;
});
for (i = 0; i < links.length; i++) {
if (otherNode(links[i]).index > node.index) {
links = links.slice(0, i).reverse().concat(links.slice(i).reverse());
sliced = true;
break;
}
}
if (!sliced) {
links.reverse();
}
for (i = 0; i < links.length; i++) {
if (links[i] === point) {
return offset;
}
offset += links[i].weight;
}
};
return node;
},
/**
* @private
* @todo Override the refactored sankey translateLink and translateNode
* functions instead of the whole translate function.
*/
translate: function () {
var options = this.options, factor = 2 * Math.PI /
(this.chart.plotHeight + this.getNodePadding()), center = this.getCenter(), startAngle = (options.startAngle - 90) * H.deg2rad;
base.translate.call(this);
this.nodeColumns[0].forEach(function (node) {
// Don't render the nodes if sum is 0 #12453
if (node.sum) {
var shapeArgs = node.shapeArgs, centerX = center[0], centerY = center[1], r = center[2] / 2, innerR = r - options.nodeWidth, start = startAngle + factor * shapeArgs.y, end = startAngle +
factor * (shapeArgs.y + shapeArgs.height);
// Middle angle
node.angle = start + (end - start) / 2;
node.shapeType = 'arc';
node.shapeArgs = {
x: centerX,
y: centerY,
r: r,
innerR: innerR,
start: start,
end: end
};
node.dlBox = {
x: centerX + Math.cos((start + end) / 2) * (r + innerR) / 2,
y: centerY + Math.sin((start + end) / 2) * (r + innerR) / 2,
width: 1,
height: 1
};
// Draw the links from this node
node.linksFrom.forEach(function (point) {
if (point.linkBase) {
var distance;
var corners = point.linkBase.map(function (top, i) {
var angle = factor * top, x = Math.cos(startAngle + angle) * (innerR + 1), y = Math.sin(startAngle + angle) * (innerR + 1), curveFactor = options.curveFactor;
// The distance between the from and to node
// along the perimeter. This affect how curved
// the link is, so that links between neighbours
// don't extend too far towards the center.
distance = Math.abs(point.linkBase[3 - i] * factor - angle);
if (distance > Math.PI) {
distance = 2 * Math.PI - distance;
}
distance = distance * innerR;
if (distance < innerR) {
curveFactor *= (distance / innerR);
}
return {
x: centerX + x,
y: centerY + y,
cpX: centerX + (1 - curveFactor) * x,
cpY: centerY + (1 - curveFactor) * y
};
});
point.shapeArgs = {
d: [
'M',
corners[0].x, corners[0].y,
'A',
innerR, innerR,
0,
0,
1,
corners[1].x, corners[1].y,
'C',
corners[1].cpX, corners[1].cpY,
corners[2].cpX, corners[2].cpY,
corners[2].x, corners[2].y,
'A',
innerR, innerR,
0,
0,
1,
corners[3].x, corners[3].y,
'C',
corners[3].cpX, corners[3].cpY,
corners[0].cpX, corners[0].cpY,
corners[0].x, corners[0].y
]
};
}
});
}
});
},
animate: function (init) {
if (!init) {
var duration = animObject(this.options.animation).duration, step = (duration / 2) / this.nodes.length;
this.nodes.forEach(function (point, i) {
var graphic = point.graphic;
if (graphic) {
graphic.attr({ opacity: 0 });
setTimeout(function () {
graphic.animate({ opacity: 1 }, { duration: step });
}, step * i);
}
}, this);
this.points.forEach(function (point) {
var graphic = point.graphic;
if (!point.isNode && graphic) {
graphic.attr({ opacity: 0 })
.animate({
opacity: 1
}, this.options.animation);
}
}, this);
}
}
/* eslint-enable valid-jsdoc */
},
// Point class
{
setState: H.NodesMixin.setNodeState,
/* eslint-disable valid-jsdoc */
/**
* Return a text path that the data label uses.
* @private
*/
getDataLabelPath: function (label) {
var renderer = this.series.chart.renderer, shapeArgs = this.shapeArgs, upperHalf = this.angle < 0 || this.angle > Math.PI, start = shapeArgs.start, end = shapeArgs.end;
if (!this.dataLabelPath) {
this.dataLabelPath = renderer
.arc({ open: true })
// Add it inside the data label group so it gets destroyed
// with the label
.add(label);
}
this.dataLabelPath.attr({
x: shapeArgs.x,
y: shapeArgs.y,
r: (shapeArgs.r +
(this.dataLabel.options.distance || 0)),
start: (upperHalf ? start : end),
end: (upperHalf ? end : start),
clockwise: +upperHalf
});
return this.dataLabelPath;
},
isValid: function () {
// No null points here
return true;
}
/* eslint-enable valid-jsdoc */
});
/**
* A `dependencywheel` series. If the [type](#series.dependencywheel.type)
* option is not specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.dependencywheel
* @exclude dataSorting
* @product highcharts
* @requires modules/dependencywheel
* @apioption series.dependencywheel
*/
/**
* A collection of options for the individual nodes. The nodes in a dependency
* diagram are auto-generated instances of `Highcharts.Point`, but options can
* be applied here and linked by the `id`.
*
* @extends series.sankey.nodes
* @type {Array<*>}
* @product highcharts
* @excluding offset
* @apioption series.dependencywheel.nodes
*/
/**
* An array of data points for the series. For the `dependencywheel` series
* type, points can be given in the following way:
*
* An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of data
* points exceeds the series' [turboThreshold](#series.area.turboThreshold),
* this option is not available.
*
* ```js
* data: [{
* from: 'Category1',
* to: 'Category2',
* weight: 2
* }, {
* from: 'Category1',
* to: 'Category3',
* weight: 5
* }]
* ```
*
* @type {Array<*>}
* @extends series.sankey.data
* @product highcharts
* @excluding outgoing, dataLabels
* @apioption series.dependencywheel.data
*/
/**
* Individual data label for each node. The options are the same as
* the ones for [series.dependencywheel.dataLabels](#series.dependencywheel.dataLabels).
*
* @apioption series.dependencywheel.nodes.dataLabels
*/
''; // adds doclets above to the transpiled file

View File

@@ -0,0 +1,108 @@
/* *
*
* (c) 2009-2020 Torstein Honsi
*
* Dot plot series type for Highcharts
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
/**
* @private
* @todo
* - Check update, remove etc.
* - Custom icons like persons, carts etc. Either as images, font icons or
* Highcharts symbols.
*/
'use strict';
import H from '../parts/Globals.js';
import U from '../parts/Utilities.js';
var extend = U.extend, objectEach = U.objectEach, pick = U.pick, seriesType = U.seriesType;
import '../parts/Series.js';
/**
* @private
* @class
* @name Highcharts.seriesTypes.dotplot
*
* @augments Highcharts.Series
*/
seriesType('dotplot', 'column', {
itemPadding: 0.2,
marker: {
symbol: 'circle',
states: {
hover: {},
select: {}
}
}
}, {
markerAttribs: void 0,
drawPoints: function () {
var series = this, renderer = series.chart.renderer, seriesMarkerOptions = this.options.marker, itemPaddingTranslated = this.yAxis.transA *
series.options.itemPadding, borderWidth = this.borderWidth, crisp = borderWidth % 2 ? 0.5 : 1;
this.points.forEach(function (point) {
var yPos, attr, graphics, itemY, pointAttr, pointMarkerOptions = point.marker || {}, symbol = (pointMarkerOptions.symbol ||
seriesMarkerOptions.symbol), radius = pick(pointMarkerOptions.radius, seriesMarkerOptions.radius), size, yTop, isSquare = symbol !== 'rect', x, y;
point.graphics = graphics = point.graphics || {};
pointAttr = point.pointAttr ?
(point.pointAttr[point.selected ? 'selected' : ''] ||
series.pointAttr['']) :
series.pointAttribs(point, point.selected && 'select');
delete pointAttr.r;
if (series.chart.styledMode) {
delete pointAttr.stroke;
delete pointAttr['stroke-width'];
}
if (point.y !== null) {
if (!point.graphic) {
point.graphic = renderer.g('point').add(series.group);
}
itemY = point.y;
yTop = pick(point.stackY, point.y);
size = Math.min(point.pointWidth, series.yAxis.transA - itemPaddingTranslated);
for (yPos = yTop; yPos > yTop - point.y; yPos--) {
x = point.barX + (isSquare ?
point.pointWidth / 2 - size / 2 :
0);
y = series.yAxis.toPixels(yPos, true) +
itemPaddingTranslated / 2;
if (series.options.crisp) {
x = Math.round(x) - crisp;
y = Math.round(y) + crisp;
}
attr = {
x: x,
y: y,
width: Math.round(isSquare ? size : point.pointWidth),
height: Math.round(size),
r: radius
};
if (graphics[itemY]) {
graphics[itemY].animate(attr);
}
else {
graphics[itemY] = renderer.symbol(symbol)
.attr(extend(attr, pointAttr))
.add(point.graphic);
}
graphics[itemY].isActive = true;
itemY--;
}
}
objectEach(graphics, function (graphic, key) {
if (!graphic.isActive) {
graphic.destroy();
delete graphic[key];
}
else {
graphic.isActive = false;
}
});
});
}
});
H.SVGRenderer.prototype.symbols.rect = function (x, y, w, h, options) {
return H.SVGRenderer.prototype.symbols.callout(x, y, w, h, options);
};

View File

@@ -0,0 +1,499 @@
/* *
*
* Plugin for resizing axes / panes in a chart.
*
* (c) 2010-2017 Highsoft AS
*
* Author: Kacper Madej
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../parts/Globals.js';
import U from '../parts/Utilities.js';
var addEvent = U.addEvent, clamp = U.clamp, isNumber = U.isNumber, merge = U.merge, objectEach = U.objectEach, relativeLength = U.relativeLength, wrap = U.wrap;
import '../parts/Axis.js';
import '../parts/Pointer.js';
var hasTouch = H.hasTouch, Axis = H.Axis, Pointer = H.Pointer,
// Default options for AxisResizer.
resizerOptions = {
/**
* Minimal size of a resizable axis. Could be set as a percent
* of plot area or pixel size.
*
* @sample {highstock} stock/yaxis/resize-min-max-length
* minLength and maxLength
*
* @type {number|string}
* @product highstock
* @requires modules/drag-panes
* @apioption yAxis.minLength
*/
minLength: '10%',
/**
* Maximal size of a resizable axis. Could be set as a percent
* of plot area or pixel size.
*
* @sample {highstock} stock/yaxis/resize-min-max-length
* minLength and maxLength
*
* @type {number|string}
* @product highstock
* @requires modules/drag-panes
* @apioption yAxis.maxLength
*/
maxLength: '100%',
/**
* Options for axis resizing. It adds a thick line between panes which
* the user can drag in order to resize the panes.
*
* @sample {highstock} stock/demo/candlestick-and-volume
* Axis resizing enabled
*
* @product highstock
* @requires modules/drag-panes
* @optionparent yAxis.resize
*/
resize: {
/**
* Contains two arrays of axes that are controlled by control line
* of the axis.
*
* @requires modules/drag-panes
*/
controlledAxis: {
/**
* Array of axes that should move out of the way of resizing
* being done for the current axis. If not set, the next axis
* will be used.
*
* @sample {highstock} stock/yaxis/multiple-resizers
* Three panes with resizers
* @sample {highstock} stock/yaxis/resize-multiple-axes
* One resizer controlling multiple axes
*
* @type {Array<number|string>}
* @default []
* @requires modules/drag-panes
*/
next: [],
/**
* Array of axes that should move with the current axis
* while resizing.
*
* @sample {highstock} stock/yaxis/multiple-resizers
* Three panes with resizers
* @sample {highstock} stock/yaxis/resize-multiple-axes
* One resizer controlling multiple axes
*
* @type {Array<number|string>}
* @default []
* @requires modules/drag-panes
*/
prev: []
},
/**
* Enable or disable resize by drag for the axis.
*
* @sample {highstock} stock/demo/candlestick-and-volume
* Enabled resizer
*
* @requires modules/drag-panes
*/
enabled: false,
/**
* Cursor style for the control line.
*
* In styled mode use class `highcharts-axis-resizer` instead.
*
* @requires modules/drag-panes
*/
cursor: 'ns-resize',
/**
* Color of the control line.
*
* In styled mode use class `highcharts-axis-resizer` instead.
*
* @sample {highstock} stock/yaxis/styled-resizer
* Styled resizer
*
* @type {Highcharts.ColorString}
* @requires modules/drag-panes
*/
lineColor: '#cccccc',
/**
* Dash style of the control line.
*
* In styled mode use class `highcharts-axis-resizer` instead.
*
* @see For supported options check [dashStyle](#plotOptions.series.dashStyle)
*
* @sample {highstock} stock/yaxis/styled-resizer
* Styled resizer
*
* @requires modules/drag-panes
*/
lineDashStyle: 'Solid',
/**
* Width of the control line.
*
* In styled mode use class `highcharts-axis-resizer` instead.
*
* @sample {highstock} stock/yaxis/styled-resizer
* Styled resizer
*
* @requires modules/drag-panes
*/
lineWidth: 4,
/**
* Horizontal offset of the control line.
*
* @sample {highstock} stock/yaxis/styled-resizer
* Styled resizer
*
* @requires modules/drag-panes
*/
x: 0,
/**
* Vertical offset of the control line.
*
* @sample {highstock} stock/yaxis/styled-resizer
* Styled resizer
*
* @requires modules/drag-panes
*/
y: 0
}
};
merge(true, Axis.prototype.defaultYAxisOptions, resizerOptions);
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* The AxisResizer class.
*
* @private
* @class
* @name Highcharts.AxisResizer
*
* @param {Highcharts.Axis} axis
* Main axis for the AxisResizer.
*/
H.AxisResizer = function (axis) {
this.init(axis);
};
/* eslint-enable no-invalid-this */
H.AxisResizer.prototype = {
/**
* Initialize the AxisResizer object.
*
* @function Highcharts.AxisResizer#init
*
* @param {Highcharts.Axis} axis
* Main axis for the AxisResizer.
*/
init: function (axis, update) {
this.axis = axis;
this.options = axis.options.resize;
this.render();
if (!update) {
// Add mouse events.
this.addMouseEvents();
}
},
/**
* Render the AxisResizer
*
* @function Highcharts.AxisResizer#render
*/
render: function () {
var resizer = this, axis = resizer.axis, chart = axis.chart, options = resizer.options, x = options.x, y = options.y,
// Normalize control line position according to the plot area
pos = clamp(axis.top + axis.height + y, chart.plotTop, chart.plotTop + chart.plotHeight), attr = {}, lineWidth;
if (!chart.styledMode) {
attr = {
cursor: options.cursor,
stroke: options.lineColor,
'stroke-width': options.lineWidth,
dashstyle: options.lineDashStyle
};
}
// Register current position for future reference.
resizer.lastPos = pos - y;
if (!resizer.controlLine) {
resizer.controlLine = chart.renderer.path()
.addClass('highcharts-axis-resizer');
}
// Add to axisGroup after axis update, because the group is recreated
// Do .add() before path is calculated because strokeWidth() needs it.
resizer.controlLine.add(axis.axisGroup);
lineWidth = chart.styledMode ?
resizer.controlLine.strokeWidth() :
options.lineWidth;
attr.d = chart.renderer.crispLine([
'M', axis.left + x, pos,
'L', axis.left + axis.width + x, pos
], lineWidth);
resizer.controlLine.attr(attr);
},
/**
* Set up the mouse and touch events for the control line.
*
* @function Highcharts.AxisResizer#addMouseEvents
*/
addMouseEvents: function () {
var resizer = this, ctrlLineElem = resizer.controlLine.element, container = resizer.axis.chart.container, eventsToUnbind = [], mouseMoveHandler, mouseUpHandler, mouseDownHandler;
// Create mouse events' handlers.
// Make them as separate functions to enable wrapping them:
resizer.mouseMoveHandler = mouseMoveHandler = function (e) {
resizer.onMouseMove(e);
};
resizer.mouseUpHandler = mouseUpHandler = function (e) {
resizer.onMouseUp(e);
};
resizer.mouseDownHandler = mouseDownHandler = function (e) {
resizer.onMouseDown(e);
};
// Add mouse move and mouseup events. These are bind to doc/container,
// because resizer.grabbed flag is stored in mousedown events.
eventsToUnbind.push(addEvent(container, 'mousemove', mouseMoveHandler), addEvent(container.ownerDocument, 'mouseup', mouseUpHandler), addEvent(ctrlLineElem, 'mousedown', mouseDownHandler));
// Touch events.
if (hasTouch) {
eventsToUnbind.push(addEvent(container, 'touchmove', mouseMoveHandler), addEvent(container.ownerDocument, 'touchend', mouseUpHandler), addEvent(ctrlLineElem, 'touchstart', mouseDownHandler));
}
resizer.eventsToUnbind = eventsToUnbind;
},
/**
* Mouse move event based on x/y mouse position.
*
* @function Highcharts.AxisResizer#onMouseMove
*
* @param {Highcharts.PointerEventObject} e
* Mouse event.
*/
onMouseMove: function (e) {
/*
* In iOS, a mousemove event with e.pageX === 0 is fired when holding
* the finger down in the center of the scrollbar. This should
* be ignored. Borrowed from Navigator.
*/
if (!e.touches || e.touches[0].pageX !== 0) {
// Drag the control line
if (this.grabbed) {
this.hasDragged = true;
this.updateAxes(this.axis.chart.pointer.normalize(e).chartY -
this.options.y);
}
}
},
/**
* Mouse up event based on x/y mouse position.
*
* @function Highcharts.AxisResizer#onMouseUp
*
* @param {Highcharts.PointerEventObject} e
* Mouse event.
*/
onMouseUp: function (e) {
if (this.hasDragged) {
this.updateAxes(this.axis.chart.pointer.normalize(e).chartY -
this.options.y);
}
// Restore runPointActions.
this.grabbed = this.hasDragged = this.axis.chart.activeResizer =
null;
},
/**
* Mousedown on a control line.
* Will store necessary information for drag&drop.
*
* @function Highcharts.AxisResizer#onMouseDown
*/
onMouseDown: function (e) {
// Clear all hover effects.
this.axis.chart.pointer.reset(false, 0);
// Disable runPointActions.
this.grabbed = this.axis.chart.activeResizer = true;
},
/**
* Update all connected axes after a change of control line position
*
* @function Highcharts.AxisResizer#updateAxes
*
* @param {number} chartY
*/
updateAxes: function (chartY) {
var resizer = this, chart = resizer.axis.chart, axes = resizer.options.controlledAxis, nextAxes = axes.next.length === 0 ?
[chart.yAxis.indexOf(resizer.axis) + 1] : axes.next,
// Main axis is included in the prev array by default
prevAxes = [resizer.axis].concat(axes.prev),
// prev and next configs
axesConfigs = [], stopDrag = false, plotTop = chart.plotTop, plotHeight = chart.plotHeight, plotBottom = plotTop + plotHeight, yDelta, calculatePercent = function (value) {
return value * 100 / plotHeight + '%';
}, normalize = function (val, min, max) {
return Math.round(clamp(val, min, max));
};
// Normalize chartY to plot area limits
chartY = clamp(chartY, plotTop, plotBottom);
yDelta = chartY - resizer.lastPos;
// Update on changes of at least 1 pixel in the desired direction
if (yDelta * yDelta < 1) {
return;
}
// First gather info how axes should behave
[prevAxes, nextAxes].forEach(function (axesGroup, isNext) {
axesGroup.forEach(function (axisInfo, i) {
// Axes given as array index, axis object or axis id
var axis = isNumber(axisInfo) ?
// If it's a number - it's an index
chart.yAxis[axisInfo] :
(
// If it's first elem. in first group
(!isNext && !i) ?
// then it's an Axis object
axisInfo :
// else it should be an id
chart.get(axisInfo)), axisOptions = axis && axis.options, optionsToUpdate = {}, hDelta = 0, height, top, minLength, maxLength;
// Skip if axis is not found
// or it is navigator's yAxis (#7732)
if (!axisOptions ||
axisOptions.id === 'navigator-y-axis') {
return;
}
top = axis.top;
minLength = Math.round(relativeLength(axisOptions.minLength, plotHeight));
maxLength = Math.round(relativeLength(axisOptions.maxLength, plotHeight));
if (isNext) {
// Try to change height first. yDelta could had changed
yDelta = chartY - resizer.lastPos;
// Normalize height to option limits
height = normalize(axis.len - yDelta, minLength, maxLength);
// Adjust top, so the axis looks like shrinked from top
top = axis.top + yDelta;
// Check for plot area limits
if (top + height > plotBottom) {
hDelta = plotBottom - height - top;
chartY += hDelta;
top += hDelta;
}
// Fit to plot - when overflowing on top
if (top < plotTop) {
top = plotTop;
if (top + height > plotBottom) {
height = plotHeight;
}
}
// If next axis meets min length, stop dragging:
if (height === minLength) {
stopDrag = true;
}
axesConfigs.push({
axis: axis,
options: {
top: calculatePercent(top - plotTop),
height: calculatePercent(height)
}
});
}
else {
// Normalize height to option limits
height = normalize(chartY - top, minLength, maxLength);
// If prev axis meets max length, stop dragging:
if (height === maxLength) {
stopDrag = true;
}
// Check axis size limits
chartY = top + height;
axesConfigs.push({
axis: axis,
options: {
height: calculatePercent(height)
}
});
}
optionsToUpdate.height = height;
});
});
// If we hit the min/maxLength with dragging, don't do anything:
if (!stopDrag) {
// Now update axes:
axesConfigs.forEach(function (config) {
config.axis.update(config.options, false);
});
chart.redraw(false);
}
},
/**
* Destroy AxisResizer. Clear outside references, clear events,
* destroy elements, nullify properties.
*
* @function Highcharts.AxisResizer#destroy
*/
destroy: function () {
var resizer = this, axis = resizer.axis;
// Clear resizer in axis
delete axis.resizer;
// Clear control line events
if (this.eventsToUnbind) {
this.eventsToUnbind.forEach(function (unbind) {
unbind();
});
}
// Destroy AxisResizer elements
resizer.controlLine.destroy();
// Nullify properties
objectEach(resizer, function (val, key) {
resizer[key] = null;
});
}
};
// Keep resizer reference on axis update
Axis.prototype.keepProps.push('resizer');
/* eslint-disable no-invalid-this */
// Add new AxisResizer, update or remove it
addEvent(Axis, 'afterRender', function () {
var axis = this, resizer = axis.resizer, resizerOptions = axis.options.resize, enabled;
if (resizerOptions) {
enabled = resizerOptions.enabled !== false;
if (resizer) {
// Resizer present and enabled
if (enabled) {
// Update options
resizer.init(axis, true);
// Resizer present, but disabled
}
else {
// Destroy the resizer
resizer.destroy();
}
}
else {
// Resizer not present and enabled
if (enabled) {
// Add new resizer
axis.resizer = new H.AxisResizer(axis);
}
// Resizer not present and disabled, so do nothing
}
}
});
// Clear resizer on axis remove.
addEvent(Axis, 'destroy', function (e) {
if (!e.keepEvents && this.resizer) {
this.resizer.destroy();
}
});
// Prevent any hover effects while dragging a control line of AxisResizer.
wrap(Pointer.prototype, 'runPointActions', function (proceed) {
if (!this.chart.activeResizer) {
proceed.apply(this, Array.prototype.slice.call(arguments, 1));
}
});
// Prevent default drag action detection while dragging a control line of
// AxisResizer. (#7563)
wrap(Pointer.prototype, 'drag', function (proceed) {
if (!this.chart.activeResizer) {
proceed.apply(this, Array.prototype.slice.call(arguments, 1));
}
});

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,465 @@
/* *
*
* (c) 2010-2020 Sebastian Bochan, Rafal Sebestjanski
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../parts/Globals.js';
import U from '../parts/Utilities.js';
var seriesType = U.seriesType;
var pick = H.pick, seriesTypes = H.seriesTypes, seriesProto = H.Series.prototype, areaRangeProto = seriesTypes.arearange.prototype, columnRangeProto = seriesTypes.columnrange.prototype, colProto = seriesTypes.column.prototype, areaRangePointProto = areaRangeProto.pointClass.prototype;
/**
* The dumbbell series is a cartesian series with higher and lower values for
* each point along an X axis, connected with a line between the values.
* Requires `highcharts-more.js` and `modules/dumbbell.js`.
*
* @sample {highcharts} highcharts/demo/dumbbell/
* Dumbbell chart
* @sample {highcharts} highcharts/series-dumbbell/styled-mode-dumbbell/
* Styled mode
*
* @extends plotOptions.arearange
* @product highcharts highstock
* @excluding fillColor, fillOpacity, lineWidth, stack, stacking,
* stickyTracking, trackByArea
* @since 8.0.0
* @optionparent plotOptions.dumbbell
*/
seriesType('dumbbell', 'arearange', {
/** @ignore-option */
trackByArea: false,
/** @ignore-option */
fillColor: 'none',
/** @ignore-option */
lineWidth: 0,
pointRange: 1,
/**
* Pixel width of the line that connects the dumbbell point's values.
*
* @since 8.0.0
* @product highcharts highstock
*/
connectorWidth: 1,
/** @ignore-option */
stickyTracking: false,
groupPadding: 0.2,
pointPadding: 0.1,
/**
* Color of the start markers in a dumbbell graph.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @since 8.0.0
* @product highcharts highstock
*/
lowColor: '#333333',
/**
* Color of the line that connects the dumbbell point's values.
* By default it is the series' color.
*
* @type {string}
* @product highcharts highstock
* @since 8.0.0
* @apioption plotOptions.dumbbell.connectorColor
*/
states: {
hover: {
/** @ignore-option */
lineWidthPlus: 0,
/**
* The additional connector line width for a hovered point.
*
* @since 8.0.0
* @product highcharts highstock
*/
connectorWidthPlus: 1,
/** @ignore-option */
halo: false
}
}
}, {
trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'],
drawTracker: H.TrackerMixin.drawTrackerPoint,
drawGraph: H.noop,
/**
* Correct line position by Math.floor instead of round.
* As a result the line is aligned in the same way as marker
*
* @private
*
* @function Highcharts.seriesTypes.dumbbell#crispConnector
*
* @param {Highcharts.SVGRenderer} this
* Highcharts Renderer.
* @param {Highcharts.SVGPathArray} points
* The original points on the format `['M', 0, 0, 'L', 100, 0]`.
* @param {number} width
* Connector's width.
*
* @return {Highcharts.SVGPathArray}
* The original points array, but modified to render crisply.
*
*
*/
crispConnector: function (points, width) {
if (points[1] === points[4]) {
// Substract due to #1129. Now bottom and left axis gridlines behave
// the same.
points[1] = points[4] =
Math.floor(points[1]) + (width % 2 / 2);
}
if (points[2] === points[5]) {
points[2] = points[5] =
Math.floor(points[2]) + (width % 2 / 2);
}
return points;
},
crispCol: colProto.crispCol,
/**
* Get connector line path and styles that connects dumbbell point's low and
* high values.
* @private
*
* @param {Highcharts.Series} this The series of points.
* @param {Highcharts.Point} point The point to inspect.
*
* @return {Highcharts.SVGAttributes} attribs The path and styles.
*/
getConnectorAttribs: function (point) {
var series = this, chart = series.chart, pointOptions = point.options, seriesOptions = series.options, xAxis = series.xAxis, yAxis = series.yAxis, connectorWidth = pick(pointOptions.connectorWidth, seriesOptions.connectorWidth), connectorColor = pick(pointOptions.connectorColor, seriesOptions.connectorColor, pointOptions.color, point.zone ? point.zone.color : void 0, point.color), connectorWidthPlus = pick(seriesOptions.states &&
seriesOptions.states.hover &&
seriesOptions.states.hover.connectorWidthPlus, 1), dashStyle = pick(pointOptions.dashStyle, seriesOptions.dashStyle), pointTop = pick(point.plotLow, point.plotY), pxThreshold = yAxis.toPixels(seriesOptions.threshold || 0, true), pointHeight = chart.inverted ?
yAxis.len - pxThreshold : pxThreshold, pointBottom = pick(point.plotHigh, pointHeight), attribs, origProps;
if (point.state) {
connectorWidth = connectorWidth + connectorWidthPlus;
}
if (pointTop < 0) {
pointTop = 0;
}
else if (pointTop >= yAxis.len) {
pointTop = yAxis.len;
}
if (pointBottom < 0) {
pointBottom = 0;
}
else if (pointBottom >= yAxis.len) {
pointBottom = yAxis.len;
}
if (point.plotX < 0 || point.plotX > xAxis.len) {
connectorWidth = 0;
}
// Connector should reflect upper marker's zone color
if (point.upperGraphic) {
origProps = {
y: point.y,
zone: point.zone
};
point.y = point.high;
point.zone = point.zone ? point.getZone() : void 0;
connectorColor = pick(pointOptions.connectorColor, seriesOptions.connectorColor, pointOptions.color, point.zone ? point.zone.color : void 0, point.color);
H.extend(point, origProps);
}
attribs = {
d: series.crispConnector([
'M',
point.plotX,
pointTop,
'L',
point.plotX,
pointBottom
], connectorWidth)
};
if (!chart.styledMode) {
attribs.stroke = connectorColor;
attribs['stroke-width'] = connectorWidth;
if (dashStyle) {
attribs.dashstyle = dashStyle;
}
}
return attribs;
},
/**
* Draw connector line that connects dumbbell point's low and high values.
* @private
*
* @param {Highcharts.Series} this The series of points.
* @param {Highcharts.Point} point The point to inspect.
*
* @return {void}
*/
drawConnector: function (point) {
var series = this, animationLimit = pick(series.options.animationLimit, 250), verb = point.connector && series.chart.pointCount < animationLimit ?
'animate' : 'attr';
if (!point.connector) {
point.connector = series.chart.renderer.path()
.addClass('highcharts-lollipop-stem')
.attr({
zIndex: -1
})
.add(series.markerGroup);
}
point.connector[verb](this.getConnectorAttribs(point));
},
/**
* Return the width and x offset of the dumbbell adjusted for grouping,
* groupPadding, pointPadding, pointWidth etc.
*
* @private
*
* @function Highcharts.seriesTypes.column#getColumnMetrics
*
* @param {Highcharts.Series} this The series of points.
*
* @return {Highcharts.ColumnMetricsObject} metrics shapeArgs
*
*/
getColumnMetrics: function () {
var metrics = colProto.getColumnMetrics.apply(this, arguments);
metrics.offset = metrics.offset + metrics.width / 2;
return metrics;
},
translatePoint: areaRangeProto.translate,
setShapeArgs: columnRangeProto.translate,
/**
* Translate each point to the plot area coordinate system and find
* shape positions
*
* @private
*
* @function Highcharts.seriesTypes.dumbbell#translate
*
* @param {Highcharts.Series} this The series of points.
*
* @return {void}
*/
translate: function () {
// Calculate shapeargs
this.setShapeArgs.apply(this);
// Calculate point low / high values
this.translatePoint.apply(this, arguments);
// Correct x position
this.points.forEach(function (point) {
var shapeArgs = point.shapeArgs, pointWidth = point.pointWidth;
point.plotX = shapeArgs.x;
shapeArgs.x = point.plotX - pointWidth / 2;
point.tooltipPos = null;
});
},
seriesDrawPoints: areaRangeProto.drawPoints,
/**
* Extend the arearange series' drawPoints method by applying a connector
* and coloring markers.
* @private
*
* @function Highcharts.Series#drawPoints
*
* @param {Highcharts.Series} this The series of points.
*
* @return {void}
*/
drawPoints: function () {
var series = this, chart = series.chart, pointLength = series.points.length, seriesLowColor = series.lowColor = series.options.lowColor, i = 0, lowerGraphicColor, point, zoneColor;
this.seriesDrawPoints.apply(series, arguments);
// Draw connectors and color upper markers
while (i < pointLength) {
point = series.points[i];
series.drawConnector(point);
if (point.upperGraphic) {
point.upperGraphic.element.point = point;
point.upperGraphic.addClass('highcharts-lollipop-high');
}
point.connector.element.point = point;
if (point.lowerGraphic) {
zoneColor = point.zone && point.zone.color;
lowerGraphicColor = pick(point.options.lowColor, seriesLowColor, point.options.color, zoneColor, point.color, series.color);
if (!chart.styledMode) {
point.lowerGraphic.attr({
fill: lowerGraphicColor
});
}
point.lowerGraphic.addClass('highcharts-lollipop-low');
}
i++;
}
},
/**
* Get non-presentational attributes for a point. Used internally for
* both styled mode and classic. Set correct position in link with connector
* line.
*
* @see Series#pointAttribs
*
* @function Highcharts.Series#markerAttribs
*
* @param {Highcharts.Series} this The series of points.
*
* @return {Highcharts.SVGAttributes}
* A hash containing those attributes that are not settable from
* CSS.
*/
markerAttribs: function () {
var ret = areaRangeProto.markerAttribs.apply(this, arguments);
ret.x = Math.floor(ret.x);
ret.y = Math.floor(ret.y);
return ret;
},
/**
* Get presentational attributes
*
* @private
* @function Highcharts.seriesTypes.column#pointAttribs
*
* @param {Highcharts.Series} this The series of points.
* @param {Highcharts.Point} point The point to inspect.
* @param {string} state current state of point (normal, hover, select)
*
* @return {Highcharts.SVGAttributes} pointAttribs SVGAttributes
*/
pointAttribs: function (point, state) {
var pointAttribs;
pointAttribs = seriesProto.pointAttribs.apply(this, arguments);
if (state === 'hover') {
delete pointAttribs.fill;
}
return pointAttribs;
}
}, {
// seriesTypes doesn't inherit from arearange point proto so put below
// methods rigidly.
destroyElements: areaRangePointProto.destroyElements,
isValid: areaRangePointProto.isValid,
pointSetState: areaRangePointProto.setState,
/**
* Set the point's state extended by have influence on the connector
* (between low and high value).
*
* @private
* @param {Highcharts.Point} this The point to inspect.
*
* @return {void}
*/
setState: function () {
var point = this, series = point.series, chart = series.chart, seriesLowColor = series.options.lowColor, seriesMarker = series.options.marker, pointOptions = point.options, pointLowColor = pointOptions.lowColor, zoneColor = point.zone && point.zone.color, lowerGraphicColor = pick(pointLowColor, seriesLowColor, pointOptions.color, zoneColor, point.color, series.color), verb = 'attr', upperGraphicColor, origProps;
this.pointSetState.apply(this, arguments);
if (!point.state) {
verb = 'animate';
if (point.lowerGraphic && !chart.styledMode) {
point.lowerGraphic.attr({
fill: lowerGraphicColor
});
if (point.upperGraphic) {
origProps = {
y: point.y,
zone: point.zone
};
point.y = point.high;
point.zone = point.zone ? point.getZone() : void 0;
upperGraphicColor = pick(point.marker ? point.marker.fillColor : void 0, seriesMarker ? seriesMarker.fillColor : void 0, pointOptions.color, point.zone ? point.zone.color : void 0, point.color);
point.upperGraphic.attr({
fill: upperGraphicColor
});
H.extend(point, origProps);
}
}
}
point.connector[verb](series.getConnectorAttribs(point));
}
});
/**
* The `dumbbell` series. If the [type](#series.dumbbell.type) option is
* not specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.dumbbell
* @product highcharts highstock
* @requires highcharts-more
* @requires modules/dumbbell
* @apioption series.dumbbell
*/
/**
* An array of data points for the series. For the `dumbbell` series
* type, points can be given in the following ways:
*
* 1. An array of arrays with 3 or 2 values. In this case, the values correspond
* to `x,low,high`. If the first value is a string, it is applied as the name
* of the point, and the `x` value is inferred. The `x` value can also be
* omitted, in which case the inner arrays should be of length 2\. Then the
* `x` value is automatically calculated, either starting at 0 and
* incremented by 1, or from `pointStart` and `pointInterval` given in the
* series options.
* ```js
* data: [
* [0, 4, 2],
* [1, 2, 1],
* [2, 9, 10]
* ]
* ```
*
* 2. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.dumbbell.turboThreshold), this option is not
* available.
* ```js
* data: [{
* x: 1,
* low: 0,
* high: 4,
* name: "Point2",
* color: "#00FF00",
* lowColor: "#00FFFF",
* connectorWidth: 3,
* connectorColor: "#FF00FF"
* }, {
* x: 1,
* low: 5,
* high: 3,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @sample {highcharts} highcharts/series/data-array-of-arrays/
* Arrays of numeric x and y
* @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/
* Arrays of datetime x and y
* @sample {highcharts} highcharts/series/data-array-of-name-value/
* Arrays of point.name and y
* @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
*
* @type {Array<Array<(number|string),number>|Array<(number|string),number,number>|*>}
* @extends series.arearange.data
* @product highcharts highstock
* @apioption series.dumbbell.data
*/
/**
* Color of the line that connects the dumbbell point's values.
* By default it is the series' color.
*
* @type {string}
* @since 8.0.0
* @product highcharts highstock
* @apioption series.dumbbell.data.connectorColor
*/
/**
* Pixel width of the line that connects the dumbbell point's values.
*
* @type {number}
* @since 8.0.0
* @default 1
* @product highcharts highstock
* @apioption series.dumbbell.data.connectorWidth
*/
/**
* Color of the start markers in a dumbbell graph.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @since 8.0.0
* @default #333333
* @product highcharts highstock
* @apioption series.dumbbell.data.lowColor
*/
''; // adds doclets above to transpiled file

View File

@@ -0,0 +1,803 @@
/* *
*
* Experimental data export module for Highcharts
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
// @todo
// - Set up systematic tests for all series types, paired with tests of the data
// module importing the same data.
'use strict';
import Highcharts from '../parts/Globals.js';
/**
* Function callback to execute while data rows are processed for exporting.
* This allows the modification of data rows before processed into the final
* format.
*
* @callback Highcharts.ExportDataCallbackFunction
* @extends Highcharts.EventCallbackFunction<Highcharts.Chart>
*
* @param {Highcharts.Chart} this
* Chart context where the event occured.
*
* @param {Highcharts.ExportDataEventObject} event
* Event object with data rows that can be modified.
*/
/**
* Contains information about the export data event.
*
* @interface Highcharts.ExportDataEventObject
*/ /**
* Contains the data rows for the current export task and can be modified.
* @name Highcharts.ExportDataEventObject#dataRows
* @type {Array<Array<string>>}
*/
import U from '../parts/Utilities.js';
var defined = U.defined, extend = U.extend, isObject = U.isObject, pick = U.pick;
import '../parts/Chart.js';
import '../mixins/ajax.js';
import '../mixins/download-url.js';
var win = Highcharts.win, doc = win.document, seriesTypes = Highcharts.seriesTypes, downloadURL = Highcharts.downloadURL, fireEvent = Highcharts.fireEvent;
// Can we add this to utils? Also used in screen-reader.js
/**
* HTML encode some characters vulnerable for XSS.
* @private
* @param {string} html The input string
* @return {string} The excaped string
*/
function htmlencode(html) {
return html
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#x27;')
.replace(/\//g, '&#x2F;');
}
Highcharts.setOptions({
/**
* Callback that fires while exporting data. This allows the modification of
* data rows before processed into the final format.
*
* @type {Highcharts.ExportDataCallbackFunction}
* @context Highcharts.Chart
* @requires modules/export-data
* @apioption chart.events.exportData
*/
/**
* When set to `false` will prevent the series data from being included in
* any form of data export.
*
* Since version 6.0.0 until 7.1.0 the option was existing undocumented
* as `includeInCSVExport`.
*
* @type {boolean}
* @since 7.1.0
* @requires modules/export-data
* @apioption plotOptions.series.includeInDataExport
*/
/**
* @optionparent exporting
* @private
*/
exporting: {
/**
* Caption for the data table. Same as chart title by default. Set to
* `false` to disable.
*
* @sample highcharts/export-data/multilevel-table
* Multiple table headers
*
* @type {boolean|string}
* @since 6.0.4
* @requires modules/export-data
* @apioption exporting.tableCaption
*/
/**
* Options for exporting data to CSV or ExCel, or displaying the data
* in a HTML table or a JavaScript structure.
*
* This module adds data export options to the export menu and provides
* functions like `Chart.getCSV`, `Chart.getTable`, `Chart.getDataRows`
* and `Chart.viewData`.
*
* The XLS converter is limited and only creates a HTML string that is
* passed for download, which works but creates a warning before
* opening. The workaround for this is to use a third party XLSX
* converter, as demonstrated in the sample below.
*
* @sample highcharts/export-data/categorized/ Categorized data
* @sample highcharts/export-data/stock-timeaxis/ Highstock time axis
* @sample highcharts/export-data/xlsx/
* Using a third party XLSX converter
*
* @since 6.0.0
* @requires modules/export-data
*/
csv: {
/**
* Formatter callback for the column headers. Parameters are:
* - `item` - The series or axis object)
* - `key` - The point key, for example y or z
* - `keyLength` - The amount of value keys for this item, for
* example a range series has the keys `low` and `high` so the
* key length is 2.
*
* If [useMultiLevelHeaders](#exporting.useMultiLevelHeaders) is
* true, columnHeaderFormatter by default returns an object with
* columnTitle and topLevelColumnTitle for each key. Columns with
* the same topLevelColumnTitle have their titles merged into a
* single cell with colspan for table/Excel export.
*
* If `useMultiLevelHeaders` is false, or for CSV export, it returns
* the series name, followed by the key if there is more than one
* key.
*
* For the axis it returns the axis title or "Category" or
* "DateTime" by default.
*
* Return `false` to use Highcharts' proposed header.
*
* @sample highcharts/export-data/multilevel-table
* Multiple table headers
*
* @type {Function|null}
*/
columnHeaderFormatter: null,
/**
* Which date format to use for exported dates on a datetime X axis.
* See `Highcharts.dateFormat`.
*/
dateFormat: '%Y-%m-%d %H:%M:%S',
/**
* Which decimal point to use for exported CSV. Defaults to the same
* as the browser locale, typically `.` (English) or `,` (German,
* French etc).
*
* @type {string|null}
* @since 6.0.4
*/
decimalPoint: null,
/**
* The item delimiter in the exported data. Use `;` for direct
* exporting to Excel. Defaults to a best guess based on the browser
* locale. If the locale _decimal point_ is `,`, the `itemDelimiter`
* defaults to `;`, otherwise the `itemDelimiter` defaults to `,`.
*
* @type {string|null}
*/
itemDelimiter: null,
/**
* The line delimiter in the exported data, defaults to a newline.
*/
lineDelimiter: '\n'
},
/**
* Show a HTML table below the chart with the chart's current data.
*
* @sample highcharts/export-data/showtable/
* Show the table
* @sample highcharts/studies/exporting-table-html
* Experiment with putting the table inside the subtitle to
* allow exporting it.
*
* @since 6.0.0
* @requires modules/export-data
*/
showTable: false,
/**
* Use multi level headers in data table. If [csv.columnHeaderFormatter
* ](#exporting.csv.columnHeaderFormatter) is defined, it has to return
* objects in order for multi level headers to work.
*
* @sample highcharts/export-data/multilevel-table
* Multiple table headers
*
* @since 6.0.4
* @requires modules/export-data
*/
useMultiLevelHeaders: true,
/**
* If using multi level table headers, use rowspans for headers that
* have only one level.
*
* @sample highcharts/export-data/multilevel-table
* Multiple table headers
*
* @since 6.0.4
* @requires modules/export-data
*/
useRowspanHeaders: true
},
/**
* @optionparent lang
*
* @private
*/
lang: {
/**
* The text for the menu item.
*
* @since 6.0.0
* @requires modules/export-data
*/
downloadCSV: 'Download CSV',
/**
* The text for the menu item.
*
* @since 6.0.0
* @requires modules/export-data
*/
downloadXLS: 'Download XLS',
/**
* The text for the menu item.
*
* @since 6.0.0
* @requires modules/export-data
*/
viewData: 'View data table'
}
});
/* eslint-disable no-invalid-this */
// Add an event listener to handle the showTable option
Highcharts.addEvent(Highcharts.Chart, 'render', function () {
if (this.options &&
this.options.exporting &&
this.options.exporting.showTable &&
!this.options.chart.forExport) {
this.viewData();
}
});
/* eslint-enable no-invalid-this */
/**
* Set up key-to-axis bindings. This is used when the Y axis is datetime or
* categorized. For example in an arearange series, the low and high values
* should be formatted according to the Y axis type, and in order to link them
* we need this map.
*
* @private
* @function Highcharts.Chart#setUpKeyToAxis
* @return {void}
*/
Highcharts.Chart.prototype.setUpKeyToAxis = function () {
if (seriesTypes.arearange) {
seriesTypes.arearange.prototype.keyToAxis = {
low: 'y',
high: 'y'
};
}
if (seriesTypes.gantt) {
seriesTypes.gantt.prototype.keyToAxis = {
start: 'x',
end: 'x'
};
}
};
/**
* Export-data module required. Returns a two-dimensional array containing the
* current chart data.
*
* @function Highcharts.Chart#getDataRows
*
* @param {boolean} [multiLevelHeaders]
* Use multilevel headers for the rows by default. Adds an extra row with
* top level headers. If a custom columnHeaderFormatter is defined, this
* can override the behavior.
*
* @return {Array<Array<(number|string)>>}
* The current chart data
*
* @fires Highcharts.Chart#event:exportData
*/
Highcharts.Chart.prototype.getDataRows = function (multiLevelHeaders) {
var hasParallelCoords = this.hasParallelCoordinates, time = this.time, csvOptions = ((this.options.exporting && this.options.exporting.csv) || {}), xAxis, xAxes = this.xAxis, rows = {}, rowArr = [], dataRows, topLevelColumnTitles = [], columnTitles = [], columnTitleObj, i, x, xTitle,
// Options
columnHeaderFormatter = function (item, key, keyLength) {
if (csvOptions.columnHeaderFormatter) {
var s = csvOptions.columnHeaderFormatter(item, key, keyLength);
if (s !== false) {
return s;
}
}
if (!item) {
return 'Category';
}
if (item instanceof Highcharts.Axis) {
return (item.options.title && item.options.title.text) ||
(item.isDatetimeAxis ? 'DateTime' : 'Category');
}
if (multiLevelHeaders) {
return {
columnTitle: keyLength > 1 ?
key :
item.name,
topLevelColumnTitle: item.name
};
}
return item.name + (keyLength > 1 ? ' (' + key + ')' : '');
},
// Map the categories for value axes
getCategoryAndDateTimeMap = function (series, pointArrayMap, pIdx) {
var categoryMap = {}, dateTimeValueAxisMap = {};
pointArrayMap.forEach(function (prop) {
var axisName = ((series.keyToAxis && series.keyToAxis[prop]) ||
prop) + 'Axis',
// Points in parallel coordinates refers to all yAxis
// not only `series.yAxis`
axis = Highcharts.isNumber(pIdx) ?
series.chart[axisName][pIdx] :
series[axisName];
categoryMap[prop] = (axis && axis.categories) || [];
dateTimeValueAxisMap[prop] = (axis && axis.isDatetimeAxis);
});
return {
categoryMap: categoryMap,
dateTimeValueAxisMap: dateTimeValueAxisMap
};
}, xAxisIndices = [];
// Loop the series and index values
i = 0;
this.setUpKeyToAxis();
this.series.forEach(function (series) {
var keys = series.options.keys, pointArrayMap = keys || series.pointArrayMap || ['y'], valueCount = pointArrayMap.length, xTaken = !series.requireSorting && {}, xAxisIndex = xAxes.indexOf(series.xAxis), categoryAndDatetimeMap = getCategoryAndDateTimeMap(series, pointArrayMap), mockSeries, j;
if (series.options.includeInDataExport !== false &&
!series.options.isInternal &&
series.visible !== false // #55
) {
// Build a lookup for X axis index and the position of the first
// series that belongs to that X axis. Includes -1 for non-axis
// series types like pies.
if (!Highcharts.find(xAxisIndices, function (index) {
return index[0] === xAxisIndex;
})) {
xAxisIndices.push([xAxisIndex, i]);
}
// Compute the column headers and top level headers, usually the
// same as series names
j = 0;
while (j < valueCount) {
columnTitleObj = columnHeaderFormatter(series, pointArrayMap[j], pointArrayMap.length);
columnTitles.push(columnTitleObj.columnTitle || columnTitleObj);
if (multiLevelHeaders) {
topLevelColumnTitles.push(columnTitleObj.topLevelColumnTitle ||
columnTitleObj);
}
j++;
}
mockSeries = {
chart: series.chart,
autoIncrement: series.autoIncrement,
options: series.options,
pointArrayMap: series.pointArrayMap
};
// Export directly from options.data because we need the uncropped
// data (#7913), and we need to support Boost (#7026).
series.options.data.forEach(function eachData(options, pIdx) {
var key, prop, val, name, point;
// In parallel coordinates chart, each data point is connected
// to a separate yAxis, conform this
if (hasParallelCoords) {
categoryAndDatetimeMap = getCategoryAndDateTimeMap(series, pointArrayMap, pIdx);
}
point = { series: mockSeries };
series.pointClass.prototype.applyOptions.apply(point, [options]);
key = point.x;
name = series.data[pIdx] && series.data[pIdx].name;
j = 0;
// Pies, funnels, geo maps etc. use point name in X row
if (!series.xAxis || series.exportKey === 'name') {
key = name;
}
if (xTaken) {
if (xTaken[key]) {
key += '|' + pIdx;
}
xTaken[key] = true;
}
if (!rows[key]) {
// Generate the row
rows[key] = [];
// Contain the X values from one or more X axes
rows[key].xValues = [];
}
rows[key].x = point.x;
rows[key].name = name;
rows[key].xValues[xAxisIndex] = point.x;
while (j < valueCount) {
prop = pointArrayMap[j]; // y, z etc
val = point[prop];
rows[key][i + j] = pick(
// Y axis category if present
categoryAndDatetimeMap.categoryMap[prop][val],
// datetime yAxis
categoryAndDatetimeMap.dateTimeValueAxisMap[prop] ?
time.dateFormat(csvOptions.dateFormat, val) :
null,
// linear/log yAxis
val);
j++;
}
});
i = i + j;
}
});
// Make a sortable array
for (x in rows) {
if (Object.hasOwnProperty.call(rows, x)) {
rowArr.push(rows[x]);
}
}
var xAxisIndex, column;
// Add computed column headers and top level headers to final row set
dataRows = multiLevelHeaders ? [topLevelColumnTitles, columnTitles] :
[columnTitles];
i = xAxisIndices.length;
while (i--) { // Start from end to splice in
xAxisIndex = xAxisIndices[i][0];
column = xAxisIndices[i][1];
xAxis = xAxes[xAxisIndex];
// Sort it by X values
rowArr.sort(function (// eslint-disable-line no-loop-func
a, b) {
return a.xValues[xAxisIndex] - b.xValues[xAxisIndex];
});
// Add header row
xTitle = columnHeaderFormatter(xAxis);
dataRows[0].splice(column, 0, xTitle);
if (multiLevelHeaders && dataRows[1]) {
// If using multi level headers, we just added top level header.
// Also add for sub level
dataRows[1].splice(column, 0, xTitle);
}
// Add the category column
rowArr.forEach(function (// eslint-disable-line no-loop-func
row) {
var category = row.name;
if (xAxis && !defined(category)) {
if (xAxis.isDatetimeAxis) {
if (row.x instanceof Date) {
row.x = row.x.getTime();
}
category = time.dateFormat(csvOptions.dateFormat, row.x);
}
else if (xAxis.categories) {
category = pick(xAxis.names[row.x], xAxis.categories[row.x], row.x);
}
else {
category = row.x;
}
}
// Add the X/date/category
row.splice(column, 0, category);
});
}
dataRows = dataRows.concat(rowArr);
fireEvent(this, 'exportData', { dataRows: dataRows });
return dataRows;
};
/**
* Export-data module required. Returns the current chart data as a CSV string.
*
* @function Highcharts.Chart#getCSV
*
* @param {boolean} [useLocalDecimalPoint]
* Whether to use the local decimal point as detected from the browser.
* This makes it easier to export data to Excel in the same locale as the
* user is.
*
* @return {string}
* CSV representation of the data
*/
Highcharts.Chart.prototype.getCSV = function (useLocalDecimalPoint) {
var csv = '', rows = this.getDataRows(), csvOptions = this.options.exporting.csv, decimalPoint = pick(csvOptions.decimalPoint, csvOptions.itemDelimiter !== ',' && useLocalDecimalPoint ?
(1.1).toLocaleString()[1] :
'.'),
// use ';' for direct to Excel
itemDelimiter = pick(csvOptions.itemDelimiter, decimalPoint === ',' ? ';' : ','),
// '\n' isn't working with the js csv data extraction
lineDelimiter = csvOptions.lineDelimiter;
// Transform the rows to CSV
rows.forEach(function (row, i) {
var val = '', j = row.length;
while (j--) {
val = row[j];
if (typeof val === 'string') {
val = '"' + val + '"';
}
if (typeof val === 'number') {
if (decimalPoint !== '.') {
val = val.toString().replace('.', decimalPoint);
}
}
row[j] = val;
}
// Add the values
csv += row.join(itemDelimiter);
// Add the line delimiter
if (i < rows.length - 1) {
csv += lineDelimiter;
}
});
return csv;
};
/**
* Export-data module required. Build a HTML table with the chart's current
* data.
*
* @sample highcharts/export-data/viewdata/
* View the data from the export menu
*
* @function Highcharts.Chart#getTable
*
* @param {boolean} [useLocalDecimalPoint]
* Whether to use the local decimal point as detected from the browser.
* This makes it easier to export data to Excel in the same locale as the
* user is.
*
* @return {string}
* HTML representation of the data.
*
* @fires Highcharts.Chart#event:afterGetTable
*/
Highcharts.Chart.prototype.getTable = function (useLocalDecimalPoint) {
var html = '<table id="highcharts-data-table-' + this.index + '">', options = this.options, decimalPoint = useLocalDecimalPoint ? (1.1).toLocaleString()[1] : '.', useMultiLevelHeaders = pick(options.exporting.useMultiLevelHeaders, true), rows = this.getDataRows(useMultiLevelHeaders), rowLength = 0, topHeaders = useMultiLevelHeaders ? rows.shift() : null, subHeaders = rows.shift(),
// Compare two rows for equality
isRowEqual = function (row1, row2) {
var i = row1.length;
if (row2.length === i) {
while (i--) {
if (row1[i] !== row2[i]) {
return false;
}
}
}
else {
return false;
}
return true;
},
// Get table cell HTML from value
getCellHTMLFromValue = function (tag, classes, attrs, value) {
var val = pick(value, ''), className = 'text' + (classes ? ' ' + classes : '');
// Convert to string if number
if (typeof val === 'number') {
val = val.toString();
if (decimalPoint === ',') {
val = val.replace('.', decimalPoint);
}
className = 'number';
}
else if (!value) {
className = 'empty';
}
return '<' + tag + (attrs ? ' ' + attrs : '') +
' class="' + className + '">' +
val + '</' + tag + '>';
},
// Get table header markup from row data
getTableHeaderHTML = function (topheaders, subheaders, rowLength) {
var html = '<thead>', i = 0, len = rowLength || subheaders && subheaders.length, next, cur, curColspan = 0, rowspan;
// Clean up multiple table headers. Chart.getDataRows() returns two
// levels of headers when using multilevel, not merged. We need to
// merge identical headers, remove redundant headers, and keep it
// all marked up nicely.
if (useMultiLevelHeaders &&
topheaders &&
subheaders &&
!isRowEqual(topheaders, subheaders)) {
html += '<tr>';
for (; i < len; ++i) {
cur = topheaders[i];
next = topheaders[i + 1];
if (cur === next) {
++curColspan;
}
else if (curColspan) {
// Ended colspan
// Add cur to HTML with colspan.
html += getCellHTMLFromValue('th', 'highcharts-table-topheading', 'scope="col" ' +
'colspan="' + (curColspan + 1) + '"', cur);
curColspan = 0;
}
else {
// Cur is standalone. If it is same as sublevel,
// remove sublevel and add just toplevel.
if (cur === subheaders[i]) {
if (options.exporting.useRowspanHeaders) {
rowspan = 2;
delete subheaders[i];
}
else {
rowspan = 1;
subheaders[i] = '';
}
}
else {
rowspan = 1;
}
html += getCellHTMLFromValue('th', 'highcharts-table-topheading', 'scope="col"' +
(rowspan > 1 ?
' valign="top" rowspan="' + rowspan + '"' :
''), cur);
}
}
html += '</tr>';
}
// Add the subheaders (the only headers if not using multilevels)
if (subheaders) {
html += '<tr>';
for (i = 0, len = subheaders.length; i < len; ++i) {
if (typeof subheaders[i] !== 'undefined') {
html += getCellHTMLFromValue('th', null, 'scope="col"', subheaders[i]);
}
}
html += '</tr>';
}
html += '</thead>';
return html;
};
// Add table caption
if (options.exporting.tableCaption !== false) {
html += '<caption class="highcharts-table-caption">' + pick(options.exporting.tableCaption, (options.title.text ?
htmlencode(options.title.text) :
'Chart')) + '</caption>';
}
// Find longest row
for (var i = 0, len = rows.length; i < len; ++i) {
if (rows[i].length > rowLength) {
rowLength = rows[i].length;
}
}
// Add header
html += getTableHeaderHTML(topHeaders, subHeaders, Math.max(rowLength, subHeaders.length));
// Transform the rows to HTML
html += '<tbody>';
rows.forEach(function (row) {
html += '<tr>';
for (var j = 0; j < rowLength; j++) {
// Make first column a header too. Especially important for
// category axes, but also might make sense for datetime? Should
// await user feedback on this.
html += getCellHTMLFromValue(j ? 'td' : 'th', null, j ? '' : 'scope="row"', row[j]);
}
html += '</tr>';
});
html += '</tbody></table>';
var e = { html: html };
fireEvent(this, 'afterGetTable', e);
return e.html;
};
/**
* Get a blob object from content, if blob is supported
*
* @private
* @param {string} content
* The content to create the blob from.
* @param {string} type
* The type of the content.
* @return {string|undefined}
* The blob object, or undefined if not supported.
*/
function getBlobFromContent(content, type) {
var nav = win.navigator, webKit = (nav.userAgent.indexOf('WebKit') > -1 &&
nav.userAgent.indexOf('Chrome') < 0), domurl = win.URL || win.webkitURL || win;
try {
// MS specific
if (nav.msSaveOrOpenBlob && win.MSBlobBuilder) {
var blob = new win.MSBlobBuilder();
blob.append(content);
return blob.getBlob('image/svg+xml');
}
// Safari requires data URI since it doesn't allow navigation to blob
// URLs.
if (!webKit) {
return domurl.createObjectURL(new win.Blob(['\uFEFF' + content], // #7084
{ type: type }));
}
}
catch (e) {
// Ignore
}
}
/**
* Call this on click of 'Download CSV' button
*
* @private
* @function Highcharts.Chart#downloadCSV
* @return {void}
*/
Highcharts.Chart.prototype.downloadCSV = function () {
var csv = this.getCSV(true);
downloadURL(getBlobFromContent(csv, 'text/csv') ||
'data:text/csv,\uFEFF' + encodeURIComponent(csv), this.getFilename() + '.csv');
};
/**
* Call this on click of 'Download XLS' button
*
* @private
* @function Highcharts.Chart#downloadXLS
* @return {void}
*/
Highcharts.Chart.prototype.downloadXLS = function () {
var uri = 'data:application/vnd.ms-excel;base64,', template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" ' +
'xmlns:x="urn:schemas-microsoft-com:office:excel" ' +
'xmlns="http://www.w3.org/TR/REC-html40">' +
'<head><!--[if gte mso 9]><xml><x:ExcelWorkbook>' +
'<x:ExcelWorksheets><x:ExcelWorksheet>' +
'<x:Name>Ark1</x:Name>' +
'<x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions>' +
'</x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook>' +
'</xml><![endif]-->' +
'<style>td{border:none;font-family: Calibri, sans-serif;} ' +
'.number{mso-number-format:"0.00";} ' +
'.text{ mso-number-format:"\@";}</style>' +
'<meta name=ProgId content=Excel.Sheet>' +
'<meta charset=UTF-8>' +
'</head><body>' +
this.getTable(true) +
'</body></html>', base64 = function (s) {
return win.btoa(unescape(encodeURIComponent(s))); // #50
};
downloadURL(getBlobFromContent(template, 'application/vnd.ms-excel') ||
uri + base64(template), this.getFilename() + '.xls');
};
/**
* Export-data module required. View the data in a table below the chart.
*
* @function Highcharts.Chart#viewData
* @return {void}
*
* @fires Highcharts.Chart#event:afterViewData
*/
Highcharts.Chart.prototype.viewData = function () {
if (!this.dataTableDiv) {
this.dataTableDiv = doc.createElement('div');
this.dataTableDiv.className = 'highcharts-data-table';
// Insert after the chart container
this.renderTo.parentNode.insertBefore(this.dataTableDiv, this.renderTo.nextSibling);
}
this.dataTableDiv.innerHTML = this.getTable();
fireEvent(this, 'afterViewData', this.dataTableDiv);
};
// Add "Download CSV" to the exporting menu.
var exportingOptions = Highcharts.getOptions().exporting;
if (exportingOptions) {
extend(exportingOptions.menuItemDefinitions, {
downloadCSV: {
textKey: 'downloadCSV',
onclick: function () {
this.downloadCSV();
}
},
downloadXLS: {
textKey: 'downloadXLS',
onclick: function () {
this.downloadXLS();
}
},
viewData: {
textKey: 'viewData',
onclick: function () {
this.viewData();
}
}
});
if (exportingOptions.buttons) {
exportingOptions.buttons.contextButton.menuItems.push('separator', 'downloadCSV', 'downloadXLS', 'viewData');
}
}
// Series specific
if (seriesTypes.map) {
seriesTypes.map.prototype.exportKey = 'name';
}
if (seriesTypes.mapbubble) {
seriesTypes.mapbubble.prototype.exportKey = 'name';
}
if (seriesTypes.treemap) {
seriesTypes.treemap.prototype.exportKey = 'name';
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,214 @@
/* *
* (c) 2009-2020 Rafal Sebestjanski
*
* Full screen for Highcharts
*
* License: www.highcharts.com/license
*/
'use strict';
import H from '../parts/Globals.js';
var addEvent = H.addEvent, Chart = H.Chart;
/**
* The module allows user to enable display chart in full screen mode.
* Used in StockTools too.
* Based on default solutions in browsers.
*
*/
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* Handles displaying chart's container in the fullscreen mode.
*
* @class
* @name Highcharts.Fullscreen
* @hideconstructor
* @requires modules/full-screen
*/
var Fullscreen = /** @class */ (function () {
/* *
*
* Constructors
*
* */
function Fullscreen(chart) {
/**
* Chart managed by the fullscreen controller.
* @name Highcharts.Fullscreen#chart
* @type {Highcharts.Chart}
*/
this.chart = chart;
/**
* The flag is set to `true` when the chart is displayed in
* the fullscreen mode.
*
* @name Highcharts.Fullscreen#isOpen
* @type {boolean|undefined}
* @since 8.0.1
*/
this.isOpen = false;
if (!(chart.container.parentNode instanceof Element)) {
return;
}
var container = chart.container.parentNode;
// Hold event and methods available only for a current browser.
if (!this.browserProps) {
if (typeof container.requestFullscreen === 'function') {
this.browserProps = {
fullscreenChange: 'fullscreenchange',
requestFullscreen: 'requestFullscreen',
exitFullscreen: 'exitFullscreen'
};
}
else if (container.mozRequestFullScreen) {
this.browserProps = {
fullscreenChange: 'mozfullscreenchange',
requestFullscreen: 'mozRequestFullScreen',
exitFullscreen: 'mozCancelFullScreen'
};
}
else if (container.webkitRequestFullScreen) {
this.browserProps = {
fullscreenChange: 'webkitfullscreenchange',
requestFullscreen: 'webkitRequestFullScreen',
exitFullscreen: 'webkitExitFullscreen'
};
}
else if (container.msRequestFullscreen) {
this.browserProps = {
fullscreenChange: 'MSFullscreenChange',
requestFullscreen: 'msRequestFullscreen',
exitFullscreen: 'msExitFullscreen'
};
}
}
}
/* *
*
* Functions
*
* */
/**
* Stops displaying the chart in fullscreen mode.
* Exporting module required.
*
* @since 8.0.1
*
* @function Highcharts.Fullscreen#close
* @return {void}
* @requires modules/full-screen
*/
Fullscreen.prototype.close = function () {
var fullscreen = this, chart = fullscreen.chart;
// Don't fire exitFullscreen() when user exited using 'Escape' button.
if (fullscreen.isOpen &&
fullscreen.browserProps &&
chart.container.ownerDocument instanceof Document) {
chart.container.ownerDocument[fullscreen.browserProps.exitFullscreen]();
}
// Unbind event as it's necessary only before exiting from fullscreen.
if (fullscreen.unbindFullscreenEvent) {
fullscreen.unbindFullscreenEvent();
}
fullscreen.isOpen = false;
fullscreen.setButtonText();
};
/**
* Displays the chart in fullscreen mode.
* When fired customly by user before exporting context button is created,
* button's text will not be replaced - it's on the user side.
* Exporting module required.
*
* @since 8.0.1
*
* @function Highcharts.Fullscreen#open
* @return {void}
* @requires modules/full-screen
*/
Fullscreen.prototype.open = function () {
var fullscreen = this, chart = fullscreen.chart;
// Handle exitFullscreen() method when user clicks 'Escape' button.
if (fullscreen.browserProps) {
fullscreen.unbindFullscreenEvent = H.addEvent(chart.container.ownerDocument, // chart's document
fullscreen.browserProps.fullscreenChange, function () {
// Handle lack of async of browser's fullScreenChange event.
if (fullscreen.isOpen) {
fullscreen.isOpen = false;
fullscreen.close();
}
else {
fullscreen.isOpen = true;
fullscreen.setButtonText();
}
});
if (chart.container.parentNode instanceof Element) {
var promise = chart.container.parentNode[fullscreen.browserProps.requestFullscreen]();
if (promise) {
promise['catch'](function () {
alert(// eslint-disable-line no-alert
'Full screen is not supported inside a frame.');
});
}
}
H.addEvent(chart, 'destroy', fullscreen.unbindFullscreenEvent);
}
};
/**
* Replaces the exporting context button's text when toogling the
* fullscreen mode.
*
* @private
*
* @since 8.0.1
*
* @requires modules/full-screen
* @return {void}
*/
Fullscreen.prototype.setButtonText = function () {
var _a;
var chart = this.chart, exportDivElements = chart.exportDivElements, exportingOptions = chart.options.exporting, menuItems = (_a = exportingOptions === null || exportingOptions === void 0 ? void 0 : exportingOptions.buttons) === null || _a === void 0 ? void 0 : _a.contextButton.menuItems, lang = chart.options.lang;
if ((exportingOptions === null || exportingOptions === void 0 ? void 0 : exportingOptions.menuItemDefinitions) && (lang === null || lang === void 0 ? void 0 : lang.exitFullscreen) &&
lang.viewFullscreen &&
menuItems &&
exportDivElements &&
exportDivElements.length) {
exportDivElements[menuItems.indexOf('viewFullscreen')]
.innerHTML = !this.isOpen ?
(exportingOptions.menuItemDefinitions.viewFullscreen.text ||
lang.viewFullscreen) : lang.exitFullscreen;
}
};
/**
* Toggles displaying the chart in fullscreen mode.
* By default, when the exporting module is enabled, a context button with
* a drop down menu in the upper right corner accesses this function.
* Exporting module required.
*
* @since 8.0.1
*
* @sample highcharts/members/chart-togglefullscreen/
* Toggle fullscreen mode from a HTML button
*
* @function Highcharts.Fullscreen#toggle
* @requires modules/full-screen
*/
Fullscreen.prototype.toggle = function () {
var fullscreen = this;
if (!fullscreen.isOpen) {
fullscreen.open();
}
else {
fullscreen.close();
}
};
return Fullscreen;
}());
H.Fullscreen = Fullscreen;
export default H.Fullscreen;
// Initialize fullscreen
addEvent(Chart, 'beforeRender', function () {
/**
* @name Highcharts.Chart#fullscreen
* @type {Highcharts.Fullscreen}
* @requires modules/full-screen
*/
this.fullscreen = new H.Fullscreen(this);
});

View File

@@ -0,0 +1,548 @@
/* *
*
* Highcharts funnel module
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
/* eslint indent: 0 */
'use strict';
import Highcharts from '../parts/Globals.js';
import U from '../parts/Utilities.js';
var pick = U.pick;
import '../parts/Options.js';
import '../parts/Series.js';
import H from '../parts/Globals.js';
// create shortcuts
var seriesType = Highcharts.seriesType, seriesTypes = Highcharts.seriesTypes, fireEvent = Highcharts.fireEvent, addEvent = Highcharts.addEvent, noop = Highcharts.noop;
/**
* @private
* @class
* @name Highcharts.seriesTypes.funnel
*
* @augments Highcharts.Series
*/
seriesType('funnel', 'pie',
/**
* Funnel charts are a type of chart often used to visualize stages in a
* sales project, where the top are the initial stages with the most
* clients. It requires that the modules/funnel.js file is loaded.
*
* @sample highcharts/demo/funnel/
* Funnel demo
*
* @extends plotOptions.pie
* @excluding innerSize,size,dataSorting
* @product highcharts
* @requires modules/funnel
* @optionparent plotOptions.funnel
*/
{
/**
* Initial animation is by default disabled for the funnel chart.
*/
animation: false,
/**
* The center of the series. By default, it is centered in the middle
* of the plot area, so it fills the plot area height.
*
* @type {Array<number|string>}
* @default ["50%", "50%"]
* @since 3.0
*/
center: ['50%', '50%'],
/**
* The width of the funnel compared to the width of the plot area,
* or the pixel width if it is a number.
*
* @type {number|string}
* @since 3.0
*/
width: '90%',
/**
* The width of the neck, the lower part of the funnel. A number defines
* pixel width, a percentage string defines a percentage of the plot
* area width.
*
* @sample {highcharts} highcharts/demo/funnel/
* Funnel demo
*
* @type {number|string}
* @since 3.0
*/
neckWidth: '30%',
/**
* The height of the funnel or pyramid. If it is a number it defines
* the pixel height, if it is a percentage string it is the percentage
* of the plot area height.
*
* @sample {highcharts} highcharts/demo/funnel/
* Funnel demo
*
* @type {number|string}
* @since 3.0
*/
height: '100%',
/**
* The height of the neck, the lower part of the funnel. A number
* defines pixel width, a percentage string defines a percentage of the
* plot area height.
*
* @type {number|string}
*/
neckHeight: '25%',
/**
* A reversed funnel has the widest area down. A reversed funnel with
* no neck width and neck height is a pyramid.
*
* @since 3.0.10
*/
reversed: false,
/**
* To avoid adapting the data label size in Pie.drawDataLabels.
* @ignore-option
*/
size: true,
dataLabels: {
connectorWidth: 1,
verticalAlign: 'middle'
},
/**
* Options for the series states.
*/
states: {
/**
* @excluding halo, marker, lineWidth, lineWidthPlus
* @apioption plotOptions.funnel.states.hover
*/
/**
* Options for a selected funnel item.
*
* @excluding halo, marker, lineWidth, lineWidthPlus
*/
select: {
/**
* A specific color for the selected point.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
*/
color: '#cccccc',
/**
* A specific border color for the selected point.
*
* @type {Highcharts.ColorString}
*/
borderColor: '#000000'
}
}
},
// Properties
{
animate: noop,
// Overrides the pie translate method
translate: function () {
var sum = 0, series = this, chart = series.chart, options = series.options, reversed = options.reversed, ignoreHiddenPoint = options.ignoreHiddenPoint, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, cumulative = 0, // start at top
center = options.center, centerX = getLength(center[0], plotWidth), centerY = getLength(center[1], plotHeight), width = getLength(options.width, plotWidth), tempWidth, height = getLength(options.height, plotHeight), neckWidth = getLength(options.neckWidth, plotWidth), neckHeight = getLength(options.neckHeight, plotHeight), neckY = (centerY - height / 2) + height - neckHeight, data = series.data, path, fraction, half = (options.dataLabels.position === 'left' ?
1 :
0), x1, y1, x2, x3, y3, x4, y5;
/**
* Get positions - either an integer or a percentage string must be
* given.
* @private
* @param {number|string|undefined} length
* Length
* @param {number} relativeTo
* Relative factor
* @return {number}
* Relative position
*/
function getLength(length, relativeTo) {
return (/%$/).test(length) ?
relativeTo * parseInt(length, 10) / 100 :
parseInt(length, 10);
}
series.getWidthAt = function (y) {
var top = (centerY - height / 2);
return (y > neckY || height === neckHeight) ?
neckWidth :
neckWidth + (width - neckWidth) *
(1 - (y - top) / (height - neckHeight));
};
series.getX = function (y, half, point) {
return centerX + (half ? -1 : 1) *
((series.getWidthAt(reversed ? 2 * centerY - y : y) / 2) +
point.labelDistance);
};
// Expose
series.center = [centerX, centerY, height];
series.centerX = centerX;
/*
Individual point coordinate naming:
x1,y1 _________________ x2,y1
\ /
\ /
\ /
\ /
\ /
x3,y3 _________ x4,y3
Additional for the base of the neck:
| |
| |
| |
x3,y5 _________ x4,y5
*/
// get the total sum
data.forEach(function (point) {
if (!ignoreHiddenPoint || point.visible !== false) {
sum += point.y;
}
});
data.forEach(function (point) {
// set start and end positions
y5 = null;
fraction = sum ? point.y / sum : 0;
y1 = centerY - height / 2 + cumulative * height;
y3 = y1 + fraction * height;
tempWidth = series.getWidthAt(y1);
x1 = centerX - tempWidth / 2;
x2 = x1 + tempWidth;
tempWidth = series.getWidthAt(y3);
x3 = centerX - tempWidth / 2;
x4 = x3 + tempWidth;
// the entire point is within the neck
if (y1 > neckY) {
x1 = x3 = centerX - neckWidth / 2;
x2 = x4 = centerX + neckWidth / 2;
// the base of the neck
}
else if (y3 > neckY) {
y5 = y3;
tempWidth = series.getWidthAt(neckY);
x3 = centerX - tempWidth / 2;
x4 = x3 + tempWidth;
y3 = neckY;
}
if (reversed) {
y1 = 2 * centerY - y1;
y3 = 2 * centerY - y3;
if (y5 !== null) {
y5 = 2 * centerY - y5;
}
}
// save the path
path = [
'M',
x1, y1,
'L',
x2, y1,
x4, y3
];
if (y5 !== null) {
path.push(x4, y5, x3, y5);
}
path.push(x3, y3, 'Z');
// prepare for using shared dr
point.shapeType = 'path';
point.shapeArgs = { d: path };
// for tooltips and data labels
point.percentage = fraction * 100;
point.plotX = centerX;
point.plotY = (y1 + (y5 || y3)) / 2;
// Placement of tooltips and data labels
point.tooltipPos = [
centerX,
point.plotY
];
point.dlBox = {
x: x3,
y: y1,
topWidth: x2 - x1,
bottomWidth: x4 - x3,
height: Math.abs(pick(y5, y3) - y1),
width: NaN
};
// Slice is a noop on funnel points
point.slice = noop;
// Mimicking pie data label placement logic
point.half = half;
if (!ignoreHiddenPoint || point.visible !== false) {
cumulative += fraction;
}
});
fireEvent(series, 'afterTranslate');
},
// Funnel items don't have angles (#2289)
sortByAngle: function (points) {
points.sort(function (a, b) {
return a.plotY - b.plotY;
});
},
// Extend the pie data label method
drawDataLabels: function () {
var series = this, data = series.data, labelDistance = series.options.dataLabels.distance, leftSide, sign, point, i = data.length, x, y;
// In the original pie label anticollision logic, the slots are
// distributed from one labelDistance above to one labelDistance
// below the pie. In funnels we don't want this.
series.center[2] -= 2 * labelDistance;
// Set the label position array for each point.
while (i--) {
point = data[i];
leftSide = point.half;
sign = leftSide ? 1 : -1;
y = point.plotY;
point.labelDistance = pick(point.options.dataLabels &&
point.options.dataLabels.distance, labelDistance);
series.maxLabelDistance = Math.max(point.labelDistance, series.maxLabelDistance || 0);
x = series.getX(y, leftSide, point);
// set the anchor point for data labels
point.labelPosition = {
// initial position of the data label - it's utilized for
// finding the final position for the label
natural: {
x: 0,
y: y
},
'final': {
// used for generating connector path -
// initialized later in drawDataLabels function
// x: undefined,
// y: undefined
},
// left - funnel on the left side of the data label
// right - funnel on the right side of the data label
alignment: leftSide ? 'right' : 'left',
connectorPosition: {
breakAt: {
x: x + (point.labelDistance - 5) * sign,
y: y
},
touchingSliceAt: {
x: x + point.labelDistance * sign,
y: y
}
}
};
}
seriesTypes[series.options.dataLabels.inside ? 'column' : 'pie'].prototype.drawDataLabels.call(this);
},
alignDataLabel: function (point, dataLabel, options, alignTo, isNew) {
var series = point.series, reversed = series.options.reversed, dlBox = point.dlBox || point.shapeArgs, align = options.align, verticalAlign = options.verticalAlign, inside = ((series.options || {}).dataLabels || {}).inside, centerY = series.center[1], pointPlotY = (reversed ?
2 * centerY - point.plotY :
point.plotY), widthAtLabel = series.getWidthAt(pointPlotY - dlBox.height / 2 +
dataLabel.height), offset = verticalAlign === 'middle' ?
(dlBox.topWidth - dlBox.bottomWidth) / 4 :
(widthAtLabel - dlBox.bottomWidth) / 2, y = dlBox.y, x = dlBox.x;
if (verticalAlign === 'middle') {
y = dlBox.y - dlBox.height / 2 + dataLabel.height / 2;
}
else if (verticalAlign === 'top') {
y = dlBox.y - dlBox.height + dataLabel.height +
options.padding;
}
if (verticalAlign === 'top' && !reversed ||
verticalAlign === 'bottom' && reversed ||
verticalAlign === 'middle') {
if (align === 'right') {
x = dlBox.x - options.padding + offset;
}
else if (align === 'left') {
x = dlBox.x + options.padding - offset;
}
}
alignTo = {
x: x,
y: reversed ? y - dlBox.height : y,
width: dlBox.bottomWidth,
height: dlBox.height
};
options.verticalAlign = 'bottom';
// Call the parent method
if (!inside || point.visible) {
Highcharts.Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew);
}
if (inside) {
if (!point.visible && point.dataLabel) {
// Avoid animation from top
point.dataLabel.placed = false;
}
// If label is inside and we have contrast, set it:
if (point.contrastColor) {
dataLabel.css({
color: point.contrastColor
});
}
}
}
});
/* eslint-disable no-invalid-this */
addEvent(Highcharts.Chart, 'afterHideAllOverlappingLabels', function () {
this.series.forEach(function (series) {
var dataLabelsOptions = series.options && series.options.dataLabels;
if (H.isArray(dataLabelsOptions)) {
dataLabelsOptions = dataLabelsOptions[0];
}
if (series.is('pie') &&
series.placeDataLabels &&
dataLabelsOptions &&
!dataLabelsOptions.inside) {
series.placeDataLabels();
}
});
});
/**
* A `funnel` series. If the [type](#series.funnel.type) option is
* not specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.funnel
* @excluding dataParser, dataURL, stack, xAxis, yAxis, dataSorting
* @product highcharts
* @requires modules/funnel
* @apioption series.funnel
*/
/**
* An array of data points for the series. For the `funnel` series type,
* points can be given in the following ways:
*
* 1. An array of numerical values. In this case, the numerical values
* will be interpreted as `y` options. Example:
*
* ```js
* data: [0, 5, 3, 5]
* ```
*
* 2. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of data
* points exceeds the series' [turboThreshold](#series.funnel.turboThreshold),
* this option is not available.
*
* ```js
* data: [{
* y: 3,
* name: "Point2",
* color: "#00FF00"
* }, {
* y: 1,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @sample {highcharts} highcharts/chart/reflow-true/
* Numerical values
* @sample {highcharts} highcharts/series/data-array-of-arrays/
* Arrays of numeric x and y
* @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/
* Arrays of datetime x and y
* @sample {highcharts} highcharts/series/data-array-of-name-value/
* Arrays of point.name and y
* @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
*
* @type {Array<number|null|*>}
* @extends series.pie.data
* @excluding sliced
* @product highcharts
* @apioption series.funnel.data
*/
/**
* Pyramid series type.
*
* @private
* @class
* @name Highcharts.seriesTypes.pyramid
*
* @augments Highcharts.Series
*/
seriesType('pyramid', 'funnel',
/**
* A pyramid series is a special type of funnel, without neck and reversed
* by default.
*
* @sample highcharts/demo/pyramid/
* Pyramid chart
*
* @extends plotOptions.funnel
* @product highcharts
* @requires modules/funnel
* @optionparent plotOptions.pyramid
*/
{
/**
* The pyramid neck width is zero by default, as opposed to the funnel,
* which shares the same layout logic.
*
* @since 3.0.10
*/
neckWidth: '0%',
/**
* The pyramid neck width is zero by default, as opposed to the funnel,
* which shares the same layout logic.
*
* @since 3.0.10
*/
neckHeight: '0%',
/**
* The pyramid is reversed by default, as opposed to the funnel, which
* shares the layout engine, and is not reversed.
*
* @since 3.0.10
*/
reversed: true
});
/**
* A `pyramid` series. If the [type](#series.pyramid.type) option is
* not specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.pyramid
* @excluding dataParser, dataURL, stack, xAxis, yAxis, dataSorting
* @product highcharts
* @requires modules/funnel
* @apioption series.pyramid
*/
/**
* An array of data points for the series. For the `pyramid` series
* type, points can be given in the following ways:
*
* 1. An array of numerical values. In this case, the numerical values will be
* interpreted as `y` options. Example:
* ```js
* data: [0, 5, 3, 5]
* ```
*
* 2. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.pyramid.turboThreshold), this option is not
* available.
* ```js
* data: [{
* y: 9,
* name: "Point2",
* color: "#00FF00"
* }, {
* y: 6,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @sample {highcharts} highcharts/chart/reflow-true/
* Numerical values
* @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
*
* @type {Array<number|null|*>}
* @extends series.pie.data
* @excluding sliced
* @product highcharts
* @apioption series.pyramid.data
*/
''; // adds doclets above into transpiled file

View File

@@ -0,0 +1,701 @@
/* *
*
* Highcharts funnel3d series module
*
* (c) 2010-2020 Highsoft AS
*
* Author: Kacper Madej
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../parts/Globals.js';
import Color from '../parts/Color.js';
var color = Color.parse;
import U from '../parts/Utilities.js';
var error = U.error, extend = U.extend, merge = U.merge, pick = U.pick, relativeLength = U.relativeLength, seriesType = U.seriesType;
import '../parts/ColumnSeries.js';
import '../parts/SvgRenderer.js';
var charts = H.charts, seriesTypes = H.seriesTypes,
// Use H.Renderer instead of H.SVGRenderer for VML support.
RendererProto = H.Renderer.prototype,
//
cuboidPath = RendererProto.cuboidPath, funnel3dMethods;
/**
* The funnel3d series type.
*
* @constructor seriesTypes.funnel3d
* @augments seriesTypes.column
* @requires highcharts-3d
* @requires modules/cylinder
* @requires modules/funnel3d
*/
seriesType('funnel3d', 'column',
/**
* A funnel3d is a 3d version of funnel series type. Funnel charts are
* a type of chart often used to visualize stages in a sales project,
* where the top are the initial stages with the most clients.
*
* It requires that the `highcharts-3d.js`, `cylinder.js` and
* `funnel3d.js` module are loaded.
*
* @sample highcharts/demo/funnel3d/
* Funnel3d
*
* @extends plotOptions.column
* @excluding allAreas, boostThreshold, colorAxis, compare, compareBase,
* dataSorting
* @product highcharts
* @since 7.1.0
* @requires highcharts-3d
* @requires modules/cylinder
* @requires modules/funnel3d
* @optionparent plotOptions.funnel3d
*/
{
/** @ignore-option */
center: ['50%', '50%'],
/**
* The max width of the series compared to the width of the plot area,
* or the pixel width if it is a number.
*
* @type {number|string}
* @sample {highcharts} highcharts/demo/funnel3d/ Funnel3d demo
* @product highcharts
*/
width: '90%',
/**
* The width of the neck, the lower part of the funnel. A number defines
* pixel width, a percentage string defines a percentage of the plot
* area width.
*
* @type {number|string}
* @sample {highcharts} highcharts/demo/funnel3d/ Funnel3d demo
* @product highcharts
*/
neckWidth: '30%',
/**
* The height of the series. If it is a number it defines
* the pixel height, if it is a percentage string it is the percentage
* of the plot area height.
*
* @type {number|string}
* @sample {highcharts} highcharts/demo/funnel3d/ Funnel3d demo
* @product highcharts
*/
height: '100%',
/**
* The height of the neck, the lower part of the funnel. A number
* defines pixel width, a percentage string defines a percentage
* of the plot area height.
*
* @type {number|string}
* @sample {highcharts} highcharts/demo/funnel3d/ Funnel3d demo
* @product highcharts
*/
neckHeight: '25%',
/**
* A reversed funnel has the widest area down. A reversed funnel with
* no neck width and neck height is a pyramid.
*
* @product highcharts
*/
reversed: false,
/**
* By deafult sides fill is set to a gradient through this option being
* set to `true`. Set to `false` to get solid color for the sides.
*
* @product highcharts
*/
gradientForSides: true,
animation: false,
edgeWidth: 0,
colorByPoint: true,
showInLegend: false,
dataLabels: {
align: 'right',
crop: false,
inside: false,
overflow: 'allow'
}
}, {
// Override default axis options with series required options for axes
bindAxes: function () {
H.Series.prototype.bindAxes.apply(this, arguments);
extend(this.xAxis.options, {
gridLineWidth: 0,
lineWidth: 0,
title: null,
tickPositions: []
});
extend(this.yAxis.options, {
gridLineWidth: 0,
title: null,
labels: {
enabled: false
}
});
},
translate3dShapes: H.noop,
translate: function () {
H.Series.prototype.translate.apply(this, arguments);
var sum = 0, series = this, chart = series.chart, options = series.options, reversed = options.reversed, ignoreHiddenPoint = options.ignoreHiddenPoint, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, cumulative = 0, // start at top
center = options.center, centerX = relativeLength(center[0], plotWidth), centerY = relativeLength(center[1], plotHeight), width = relativeLength(options.width, plotWidth), tempWidth, getWidthAt, height = relativeLength(options.height, plotHeight), neckWidth = relativeLength(options.neckWidth, plotWidth), neckHeight = relativeLength(options.neckHeight, plotHeight), neckY = (centerY - height / 2) + height - neckHeight, data = series.data, fraction, tooltipPos,
//
y1, y3, y5,
//
h, shapeArgs;
// Return the width at a specific y coordinate
series.getWidthAt = getWidthAt = function (y) {
var top = (centerY - height / 2);
return (y > neckY || height === neckHeight) ?
neckWidth :
neckWidth + (width - neckWidth) *
(1 - (y - top) / (height - neckHeight));
};
// Expose
series.center = [centerX, centerY, height];
series.centerX = centerX;
/*
* Individual point coordinate naming:
*
* _________centerX,y1________
* \ /
* \ /
* \ /
* \ /
* \ /
* ___centerX,y3___
*
* Additional for the base of the neck:
*
* | |
* | |
* | |
* ___centerX,y5___
*/
// get the total sum
data.forEach(function (point) {
if (!ignoreHiddenPoint || point.visible !== false) {
sum += point.y;
}
});
data.forEach(function (point) {
// set start and end positions
y5 = null;
fraction = sum ? point.y / sum : 0;
y1 = centerY - height / 2 + cumulative * height;
y3 = y1 + fraction * height;
tempWidth = getWidthAt(y1);
h = y3 - y1;
shapeArgs = {
// for fill setter
gradientForSides: pick(point.options.gradientForSides, options.gradientForSides),
x: centerX,
y: y1,
height: h,
width: tempWidth,
z: 1,
top: {
width: tempWidth
}
};
tempWidth = getWidthAt(y3);
shapeArgs.bottom = {
fraction: fraction,
width: tempWidth
};
// the entire point is within the neck
if (y1 >= neckY) {
shapeArgs.isCylinder = true;
}
else if (y3 > neckY) {
// the base of the neck
y5 = y3;
tempWidth = getWidthAt(neckY);
y3 = neckY;
shapeArgs.bottom.width = tempWidth;
shapeArgs.middle = {
fraction: h ? (neckY - y1) / h : 0,
width: tempWidth
};
}
if (reversed) {
shapeArgs.y = y1 = centerY + height / 2 -
(cumulative + fraction) * height;
if (shapeArgs.middle) {
shapeArgs.middle.fraction = 1 -
(h ? shapeArgs.middle.fraction : 0);
}
tempWidth = shapeArgs.width;
shapeArgs.width = shapeArgs.bottom.width;
shapeArgs.bottom.width = tempWidth;
}
point.shapeArgs = extend(point.shapeArgs, shapeArgs);
// for tooltips and data labels context
point.percentage = fraction * 100;
point.plotX = centerX;
if (reversed) {
point.plotY = centerY + height / 2 -
(cumulative + fraction / 2) * height;
}
else {
point.plotY = (y1 + (y5 || y3)) / 2;
}
// Placement of tooltips and data labels in 3D
tooltipPos = H.perspective([{
x: centerX,
y: point.plotY,
z: reversed ?
-(width - getWidthAt(point.plotY)) / 2 :
-(getWidthAt(point.plotY)) / 2
}], chart, true)[0];
point.tooltipPos = [tooltipPos.x, tooltipPos.y];
// base to be used when alignment options are known
point.dlBoxRaw = {
x: centerX,
width: getWidthAt(point.plotY),
y: y1,
bottom: shapeArgs.height,
fullWidth: width
};
if (!ignoreHiddenPoint || point.visible !== false) {
cumulative += fraction;
}
});
},
alignDataLabel: function (point, dataLabel, options) {
var series = this, dlBoxRaw = point.dlBoxRaw, inverted = series.chart.inverted, below = point.plotY > pick(series.translatedThreshold, series.yAxis.len), inside = pick(options.inside, !!series.options.stacking), dlBox = {
x: dlBoxRaw.x,
y: dlBoxRaw.y,
height: 0
};
options.align = pick(options.align, !inverted || inside ? 'center' : below ? 'right' : 'left');
options.verticalAlign = pick(options.verticalAlign, inverted || inside ? 'middle' : below ? 'top' : 'bottom');
if (options.verticalAlign !== 'top') {
dlBox.y += dlBoxRaw.bottom /
(options.verticalAlign === 'bottom' ? 1 : 2);
}
dlBox.width = series.getWidthAt(dlBox.y);
if (series.options.reversed) {
dlBox.width = dlBoxRaw.fullWidth - dlBox.width;
}
if (inside) {
dlBox.x -= dlBox.width / 2;
}
else {
// swap for inside
if (options.align === 'left') {
options.align = 'right';
dlBox.x -= dlBox.width * 1.5;
}
else if (options.align === 'right') {
options.align = 'left';
dlBox.x += dlBox.width / 2;
}
else {
dlBox.x -= dlBox.width / 2;
}
}
point.dlBox = dlBox;
seriesTypes.column.prototype.alignDataLabel.apply(series, arguments);
}
}, /** @lends seriesTypes.funnel3d.prototype.pointClass.prototype */ {
shapeType: 'funnel3d',
hasNewShapeType: H
.seriesTypes.column.prototype
.pointClass.prototype
.hasNewShapeType
});
/**
* A `funnel3d` series. If the [type](#series.funnel3d.type) option is
* not specified, it is inherited from [chart.type](#chart.type).
*
* @sample {highcharts} highcharts/demo/funnel3d/
* Funnel3d demo
*
* @since 7.1.0
* @extends series,plotOptions.funnel3d
* @excluding allAreas,boostThreshold,colorAxis,compare,compareBase
* @product highcharts
* @requires highcharts-3d
* @requires modules/cylinder
* @requires modules/funnel3d
* @apioption series.funnel3d
*/
/**
* An array of data points for the series. For the `funnel3d` series
* type, points can be given in the following ways:
*
* 1. An array of numerical values. In this case, the numerical values
* will be interpreted as `y` options. The `x` values will be automatically
* calculated, either starting at 0 and incremented by 1, or from `pointStart`
* and `pointInterval` given in the series options. If the axis has
* categories, these will be used. Example:
*
* ```js
* data: [0, 5, 3, 5]
* ```
*
* 2. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of data
* points exceeds the series' [turboThreshold](#series.funnel3d.turboThreshold),
* this option is not available.
*
* ```js
* data: [{
* y: 2,
* name: "Point2",
* color: "#00FF00"
* }, {
* y: 4,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @sample {highcharts} highcharts/chart/reflow-true/
* Numerical values
* @sample {highcharts} highcharts/series/data-array-of-arrays/
* Arrays of numeric x and y
* @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/
* Arrays of datetime x and y
* @sample {highcharts} highcharts/series/data-array-of-name-value/
* Arrays of point.name and y
* @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
*
* @type {Array<number|Array<number>|*>}
* @extends series.column.data
* @product highcharts
* @apioption series.funnel3d.data
*/
/**
* By deafult sides fill is set to a gradient through this option being
* set to `true`. Set to `false` to get solid color for the sides.
*
* @type {boolean}
* @product highcharts
* @apioption series.funnel3d.data.gradientForSides
*/
funnel3dMethods = merge(RendererProto.elements3d.cuboid, {
parts: [
'top', 'bottom',
'frontUpper', 'backUpper',
'frontLower', 'backLower',
'rightUpper', 'rightLower'
],
mainParts: ['top', 'bottom'],
sideGroups: [
'upperGroup', 'lowerGroup'
],
sideParts: {
upperGroup: ['frontUpper', 'backUpper', 'rightUpper'],
lowerGroup: ['frontLower', 'backLower', 'rightLower']
},
pathType: 'funnel3d',
// override opacity and color setters to control opacity
opacitySetter: function (opacity) {
var funnel3d = this, parts = funnel3d.parts, chart = H.charts[funnel3d.renderer.chartIndex], filterId = 'group-opacity-' + opacity + '-' + chart.index;
// use default for top and bottom
funnel3d.parts = funnel3d.mainParts;
funnel3d.singleSetterForParts('opacity', opacity);
// restore
funnel3d.parts = parts;
if (!chart.renderer.filterId) {
chart.renderer.definition({
tagName: 'filter',
id: filterId,
children: [{
tagName: 'feComponentTransfer',
children: [{
tagName: 'feFuncA',
type: 'table',
tableValues: '0 ' + opacity
}]
}]
});
funnel3d.sideGroups.forEach(function (groupName) {
funnel3d[groupName].attr({
filter: 'url(#' + filterId + ')'
});
});
// styled mode
if (funnel3d.renderer.styledMode) {
chart.renderer.definition({
tagName: 'style',
textContent: '.highcharts-' + filterId +
' {filter:url(#' + filterId + ')}'
});
funnel3d.sideGroups.forEach(function (group) {
group.addClass('highcharts-' + filterId);
});
}
}
return funnel3d;
},
fillSetter: function (fill) {
// extract alpha channel to use the opacitySetter
var funnel3d = this, fillColor = color(fill), alpha = fillColor.rgba[3], partsWithColor = {
// standard color for top and bottom
top: color(fill).brighten(0.1).get(),
bottom: color(fill).brighten(-0.2).get()
};
if (alpha < 1) {
fillColor.rgba[3] = 1;
fillColor = fillColor.get('rgb');
// set opacity through the opacitySetter
funnel3d.attr({
opacity: alpha
});
}
else {
// use default for full opacity
fillColor = fill;
}
// add gradient for sides
if (!fillColor.linearGradient &&
!fillColor.radialGradient &&
funnel3d.gradientForSides) {
fillColor = {
linearGradient: { x1: 0, x2: 1, y1: 1, y2: 1 },
stops: [
[0, color(fill).brighten(-0.2).get()],
[0.5, fill],
[1, color(fill).brighten(-0.2).get()]
]
};
}
// gradient support
if (fillColor.linearGradient) {
// color in steps, as each gradient will generate a key
funnel3d.sideGroups.forEach(function (sideGroupName) {
var box = funnel3d[sideGroupName].gradientBox, gradient = fillColor.linearGradient, alteredGradient = merge(fillColor, {
linearGradient: {
x1: box.x + gradient.x1 * box.width,
y1: box.y + gradient.y1 * box.height,
x2: box.x + gradient.x2 * box.width,
y2: box.y + gradient.y2 * box.height
}
});
funnel3d.sideParts[sideGroupName].forEach(function (partName) {
partsWithColor[partName] = alteredGradient;
});
});
}
else {
merge(true, partsWithColor, {
frontUpper: fillColor,
backUpper: fillColor,
rightUpper: fillColor,
frontLower: fillColor,
backLower: fillColor,
rightLower: fillColor
});
if (fillColor.radialGradient) {
funnel3d.sideGroups.forEach(function (sideGroupName) {
var gradBox = funnel3d[sideGroupName].gradientBox, centerX = gradBox.x + gradBox.width / 2, centerY = gradBox.y + gradBox.height / 2, diameter = Math.min(gradBox.width, gradBox.height);
funnel3d.sideParts[sideGroupName].forEach(function (partName) {
funnel3d[partName].setRadialReference([
centerX, centerY, diameter
]);
});
});
}
}
funnel3d.singleSetterForParts('fill', null, partsWithColor);
// fill for animation getter (#6776)
funnel3d.color = funnel3d.fill = fill;
// change gradientUnits to userSpaceOnUse for linearGradient
if (fillColor.linearGradient) {
[funnel3d.frontLower, funnel3d.frontUpper].forEach(function (part) {
var elem = part.element, grad = elem && funnel3d.renderer.gradients[elem.gradient];
if (grad && grad.attr('gradientUnits') !== 'userSpaceOnUse') {
grad.attr({
gradientUnits: 'userSpaceOnUse'
});
}
});
}
return funnel3d;
},
adjustForGradient: function () {
var funnel3d = this, bbox;
funnel3d.sideGroups.forEach(function (sideGroupName) {
// use common extremes for groups for matching gradients
var topLeftEdge = {
x: Number.MAX_VALUE,
y: Number.MAX_VALUE
}, bottomRightEdge = {
x: -Number.MAX_VALUE,
y: -Number.MAX_VALUE
};
// get extremes
funnel3d.sideParts[sideGroupName].forEach(function (partName) {
var part = funnel3d[partName];
bbox = part.getBBox(true);
topLeftEdge = {
x: Math.min(topLeftEdge.x, bbox.x),
y: Math.min(topLeftEdge.y, bbox.y)
};
bottomRightEdge = {
x: Math.max(bottomRightEdge.x, bbox.x + bbox.width),
y: Math.max(bottomRightEdge.y, bbox.y + bbox.height)
};
});
// store for color fillSetter
funnel3d[sideGroupName].gradientBox = {
x: topLeftEdge.x,
width: bottomRightEdge.x - topLeftEdge.x,
y: topLeftEdge.y,
height: bottomRightEdge.y - topLeftEdge.y
};
});
},
zIndexSetter: function () {
// this.added won't work, because zIndex is set after the prop is set,
// but before the graphic is really added
if (this.finishedOnAdd) {
this.adjustForGradient();
}
// run default
return this.renderer.Element.prototype.zIndexSetter.apply(this, arguments);
},
onAdd: function () {
this.adjustForGradient();
this.finishedOnAdd = true;
}
});
RendererProto.elements3d.funnel3d = funnel3dMethods;
RendererProto.funnel3d = function (shapeArgs) {
var renderer = this, funnel3d = renderer.element3d('funnel3d', shapeArgs), styledMode = renderer.styledMode,
// hide stroke for Firefox
strokeAttrs = {
'stroke-width': 1,
stroke: 'none'
};
// create groups for sides for oppacity setter
funnel3d.upperGroup = renderer.g('funnel3d-upper-group').attr({
zIndex: funnel3d.frontUpper.zIndex
}).add(funnel3d);
[
funnel3d.frontUpper,
funnel3d.backUpper,
funnel3d.rightUpper
].forEach(function (upperElem) {
if (!styledMode) {
upperElem.attr(strokeAttrs);
}
upperElem.add(funnel3d.upperGroup);
});
funnel3d.lowerGroup = renderer.g('funnel3d-lower-group').attr({
zIndex: funnel3d.frontLower.zIndex
}).add(funnel3d);
[
funnel3d.frontLower,
funnel3d.backLower,
funnel3d.rightLower
].forEach(function (lowerElem) {
if (!styledMode) {
lowerElem.attr(strokeAttrs);
}
lowerElem.add(funnel3d.lowerGroup);
});
funnel3d.gradientForSides = shapeArgs.gradientForSides;
return funnel3d;
};
// eslint-disable-next-line valid-jsdoc
/**
* Generates paths and zIndexes.
* @private
*/
RendererProto.funnel3dPath = function (shapeArgs) {
// Check getCylinderEnd for better error message if
// the cylinder module is missing
if (!this.getCylinderEnd) {
error('A required Highcharts module is missing: cylinder.js', true, charts[this.chartIndex]);
}
var renderer = this, chart = charts[renderer.chartIndex],
// adjust angles for visible edges
// based on alpha, selected through visual tests
alphaCorrection = shapeArgs.alphaCorrection = 90 -
Math.abs((chart.options.chart.options3d.alpha % 180) - 90),
// set zIndexes of parts based on cubiod logic, for consistency
cuboidData = cuboidPath.call(renderer, merge(shapeArgs, {
depth: shapeArgs.width,
width: (shapeArgs.width + shapeArgs.bottom.width) / 2
})), isTopFirst = cuboidData.isTop, isFrontFirst = !cuboidData.isFront, hasMiddle = !!shapeArgs.middle,
//
top = renderer.getCylinderEnd(chart, merge(shapeArgs, {
x: shapeArgs.x - shapeArgs.width / 2,
z: shapeArgs.z - shapeArgs.width / 2,
alphaCorrection: alphaCorrection
})), bottomWidth = shapeArgs.bottom.width, bottomArgs = merge(shapeArgs, {
width: bottomWidth,
x: shapeArgs.x - bottomWidth / 2,
z: shapeArgs.z - bottomWidth / 2,
alphaCorrection: alphaCorrection
}), bottom = renderer.getCylinderEnd(chart, bottomArgs, true),
//
middleWidth = bottomWidth, middleTopArgs = bottomArgs, middleTop = bottom, middleBottom = bottom, ret,
// masking for cylinders or a missing part of a side shape
useAlphaCorrection;
if (hasMiddle) {
middleWidth = shapeArgs.middle.width;
middleTopArgs = merge(shapeArgs, {
y: shapeArgs.y + shapeArgs.middle.fraction * shapeArgs.height,
width: middleWidth,
x: shapeArgs.x - middleWidth / 2,
z: shapeArgs.z - middleWidth / 2
});
middleTop = renderer.getCylinderEnd(chart, middleTopArgs, false);
middleBottom = renderer.getCylinderEnd(chart, middleTopArgs, false);
}
ret = {
top: top,
bottom: bottom,
frontUpper: renderer.getCylinderFront(top, middleTop),
zIndexes: {
group: cuboidData.zIndexes.group,
top: isTopFirst !== 0 ? 0 : 3,
bottom: isTopFirst !== 1 ? 0 : 3,
frontUpper: isFrontFirst ? 2 : 1,
backUpper: isFrontFirst ? 1 : 2,
rightUpper: isFrontFirst ? 2 : 1
}
};
ret.backUpper = renderer.getCylinderBack(top, middleTop);
useAlphaCorrection = (Math.min(middleWidth, shapeArgs.width) /
Math.max(middleWidth, shapeArgs.width)) !== 1;
ret.rightUpper = renderer.getCylinderFront(renderer.getCylinderEnd(chart, merge(shapeArgs, {
x: shapeArgs.x - shapeArgs.width / 2,
z: shapeArgs.z - shapeArgs.width / 2,
alphaCorrection: useAlphaCorrection ? -alphaCorrection : 0
}), false), renderer.getCylinderEnd(chart, merge(middleTopArgs, {
alphaCorrection: useAlphaCorrection ? -alphaCorrection : 0
}), !hasMiddle));
if (hasMiddle) {
useAlphaCorrection = (Math.min(middleWidth, bottomWidth) /
Math.max(middleWidth, bottomWidth)) !== 1;
merge(true, ret, {
frontLower: renderer.getCylinderFront(middleBottom, bottom),
backLower: renderer.getCylinderBack(middleBottom, bottom),
rightLower: renderer.getCylinderFront(renderer.getCylinderEnd(chart, merge(bottomArgs, {
alphaCorrection: useAlphaCorrection ?
-alphaCorrection : 0
}), true), renderer.getCylinderEnd(chart, merge(middleTopArgs, {
alphaCorrection: useAlphaCorrection ?
-alphaCorrection : 0
}), false)),
zIndexes: {
frontLower: isFrontFirst ? 2 : 1,
backLower: isFrontFirst ? 1 : 2,
rightLower: isFrontFirst ? 1 : 2
}
});
}
return ret;
};

View File

@@ -0,0 +1,186 @@
/* *
*
* Copyright (c) 2010-2017 Highsoft AS
* Author: Sebastian Domas
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import U from '../parts/Utilities.js';
var arrayMax = U.arrayMax, arrayMin = U.arrayMin, correctFloat = U.correctFloat, isNumber = U.isNumber, merge = U.merge, objectEach = U.objectEach, seriesType = U.seriesType;
import derivedSeriesMixin from '../mixins/derived-series.js';
/* ************************************************************************** *
* HISTOGRAM
* ************************************************************************** */
/**
* A dictionary with formulas for calculating number of bins based on the
* base series
**/
var binsNumberFormulas = {
'square-root': function (baseSeries) {
return Math.ceil(Math.sqrt(baseSeries.options.data.length));
},
'sturges': function (baseSeries) {
return Math.ceil(Math.log(baseSeries.options.data.length) * Math.LOG2E);
},
'rice': function (baseSeries) {
return Math.ceil(2 * Math.pow(baseSeries.options.data.length, 1 / 3));
}
};
/**
* Returns a function for mapping number to the closed (right opened) bins
* @private
* @param {Array<number>} bins - Width of the bins
* @return {Function}
**/
function fitToBinLeftClosed(bins) {
return function (y) {
var i = 1;
while (bins[i] <= y) {
i++;
}
return bins[--i];
};
}
/**
* Histogram class
* @private
* @class
* @name Highcharts.seriesTypes.histogram
* @augments Highcharts.Series
*/
seriesType('histogram', 'column',
/**
* A histogram is a column series which represents the distribution of the
* data set in the base series. Histogram splits data into bins and shows
* their frequencies.
*
* @sample {highcharts} highcharts/demo/histogram/
* Histogram
*
* @extends plotOptions.column
* @excluding boostThreshold, dragDrop, pointInterval, pointIntervalUnit,
* stacking
* @product highcharts
* @since 6.0.0
* @requires modules/histogram
* @optionparent plotOptions.histogram
*/
{
/**
* A preferable number of bins. It is a suggestion, so a histogram may
* have a different number of bins. By default it is set to the square
* root of the base series' data length. Available options are:
* `square-root`, `sturges`, `rice`. You can also define a function
* which takes a `baseSeries` as a parameter and should return a
* positive integer.
*
* @type {"square-root"|"sturges"|"rice"|number|function}
*/
binsNumber: 'square-root',
/**
* Width of each bin. By default the bin's width is calculated as
* `(max - min) / number of bins`. This option takes precedence over
* [binsNumber](#plotOptions.histogram.binsNumber).
*
* @type {number}
*/
binWidth: void 0,
pointPadding: 0,
groupPadding: 0,
grouping: false,
pointPlacement: 'between',
tooltip: {
headerFormat: '',
pointFormat: ('<span style="font-size: 10px">{point.x} - {point.x2}' +
'</span><br/>' +
'<span style="color:{point.color}">\u25CF</span>' +
' {series.name} <b>{point.y}</b><br/>')
}
}, merge(derivedSeriesMixin, {
setDerivedData: function () {
var yData = this.baseSeries.yData;
if (!yData.length) {
return;
}
var data = this.derivedData(yData, this.binsNumber(), this.options.binWidth);
this.setData(data, false);
},
derivedData: function (baseData, binsNumber, binWidth) {
var series = this, max = arrayMax(baseData),
// Float correction needed, because first frequency value is not
// corrected when generating frequencies (within for loop).
min = correctFloat(arrayMin(baseData)), frequencies = [], bins = {}, data = [], x, fitToBin;
binWidth = series.binWidth = series.options.pointRange = (correctFloat(isNumber(binWidth) ?
(binWidth || 1) :
(max - min) / binsNumber));
// If binWidth is 0 then max and min are equaled,
// increment the x with some positive value to quit the loop
for (x = min;
// This condition is needed because of the margin of error while
// operating on decimal numbers. Without that, additional bin
// was sometimes noticeable on the graph, because of too small
// precision of float correction.
x < max &&
(series.userOptions.binWidth ||
correctFloat(max - x) >= binWidth ||
correctFloat(min + (frequencies.length * binWidth) - x) <= 0); x = correctFloat(x + binWidth)) {
frequencies.push(x);
bins[x] = 0;
}
if (bins[min] !== 0) {
frequencies.push(correctFloat(min));
bins[correctFloat(min)] = 0;
}
fitToBin = fitToBinLeftClosed(frequencies.map(function (elem) {
return parseFloat(elem);
}));
baseData.forEach(function (y) {
var x = correctFloat(fitToBin(y));
bins[x]++;
});
objectEach(bins, function (frequency, x) {
data.push({
x: Number(x),
y: frequency,
x2: correctFloat(Number(x) + binWidth)
});
});
data.sort(function (a, b) {
return a.x - b.x;
});
return data;
},
binsNumber: function () {
var binsNumberOption = this.options.binsNumber;
var binsNumber = binsNumberFormulas[binsNumberOption] ||
// #7457
(typeof binsNumberOption === 'function' && binsNumberOption);
return Math.ceil((binsNumber && binsNumber(this.baseSeries)) ||
(isNumber(binsNumberOption) ?
binsNumberOption :
binsNumberFormulas['square-root'](this.baseSeries)));
}
}));
/**
* A `histogram` series. If the [type](#series.histogram.type) option is not
* specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.histogram
* @excluding data, dataParser, dataURL
* @product highcharts
* @since 6.0.0
* @requires modules/histogram
* @apioption series.histogram
*/
/**
* An integer identifying the index to use for the base series, or a string
* representing the id of the series.
*
* @type {number|string}
* @apioption series.histogram.baseSeries
*/
''; // adds doclets above to transpiled file

View File

@@ -0,0 +1,447 @@
/* *
*
* (c) 2020 Torstein Honsi
*
* Item series type for Highcharts
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../parts/Globals.js';
import U from '../parts/Utilities.js';
var defined = U.defined, extend = U.extend, isNumber = U.isNumber, merge = U.merge, objectEach = U.objectEach, pick = U.pick, seriesType = U.seriesType;
import '../parts/Series.js';
var fireEvent = H.fireEvent, piePoint = H.seriesTypes.pie.prototype.pointClass.prototype;
/**
* The item series type.
*
* @requires module:modules/item-series
*
* @private
* @class
* @name Highcharts.seriesTypes.item
*
* @augments Highcharts.seriesTypes.pie
*/
seriesType('item',
// Inherits pie as the most tested non-cartesian series with individual
// point legend, tooltips etc. Only downside is we need to re-enable
// marker options.
'pie',
/**
* An item chart is an infographic chart where a number of items are laid
* out in either a rectangular or circular pattern. It can be used to
* visualize counts within a group, or for the circular pattern, typically
* a parliament.
*
* The circular layout has much in common with a pie chart. Many of the item
* series options, like `center`, `size` and data label positioning, are
* inherited from the pie series and don't apply for rectangular layouts.
*
* @sample highcharts/demo/parliament-chart
* Parliament chart (circular item chart)
* @sample highcharts/series-item/rectangular
* Rectangular item chart
* @sample highcharts/series-item/symbols
* Infographic with symbols
*
* @extends plotOptions.pie
* @since 7.1.0
* @product highcharts
* @excluding borderColor, borderWidth, depth, linecap, shadow,
* slicedOffset
* @requires modules/item-series
* @optionparent plotOptions.item
*/
{
/**
* In circular view, the end angle of the item layout, in degrees where
* 0 is up.
*
* @sample highcharts/demo/parliament-chart
* Parliament chart
* @type {undefined|number}
*/
endAngle: void 0,
/**
* In circular view, the size of the inner diameter of the circle. Can
* be a percentage or pixel value. Percentages are relative to the outer
* perimeter. Pixel values are given as integers.
*
* If the `rows` option is set, it overrides the `innerSize` setting.
*
* @sample highcharts/demo/parliament-chart
* Parliament chart
* @type {string|number}
*/
innerSize: '40%',
/**
* The padding between the items, given in relative size where the size
* of the item is 1.
* @type {number}
*/
itemPadding: 0.1,
/**
* The layout of the items in rectangular view. Can be either
* `horizontal` or `vertical`.
* @sample highcharts/series-item/symbols
* Horizontal layout
* @type {string}
*/
layout: 'vertical',
/**
* @extends plotOptions.series.marker
*/
marker: merge(H.defaultOptions.plotOptions.line.marker, {
radius: null
}),
/**
* The number of rows to display in the rectangular or circular view. If
* the `innerSize` is set, it will be overridden by the `rows` setting.
*
* @sample highcharts/series-item/rows-columns
* Fixed row count
* @type {number}
*/
rows: void 0,
showInLegend: true,
/**
* In circular view, the start angle of the item layout, in degrees
* where 0 is up.
*
* @sample highcharts/demo/parliament-chart
* Parliament chart
* @type {undefined|number}
*/
startAngle: void 0
},
// Prototype members
{
markerAttribs: void 0,
translate: function () {
if (!this.slots) {
this.slots = [];
}
if (isNumber(this.options.startAngle) &&
isNumber(this.options.endAngle)) {
H.seriesTypes.pie.prototype.translate.call(this);
this.slots = this.getSlots();
}
else {
this.generatePoints();
fireEvent(this, 'afterTranslate');
}
},
// Get the semi-circular slots
getSlots: function () {
var center = this.center, diameter = center[2], innerSize = center[3], row, slots = this.slots, x, y, rowRadius, rowLength, colCount, increment, angle, col, itemSize = 0, rowCount, fullAngle = (this.endAngleRad - this.startAngleRad), itemCount = Number.MAX_VALUE, finalItemCount, rows, testRows, rowsOption = this.options.rows,
// How many rows (arcs) should be used
rowFraction = (diameter - innerSize) / diameter;
// Increase the itemSize until we find the best fit
while (itemCount > this.total) {
finalItemCount = itemCount;
// Reset
slots.length = 0;
itemCount = 0;
// Now rows is the last successful run
rows = testRows;
testRows = [];
itemSize++;
// Total number of rows (arcs) from the center to the
// perimeter
rowCount = diameter / itemSize / 2;
if (rowsOption) {
innerSize = ((rowCount - rowsOption) / rowCount) * diameter;
if (innerSize >= 0) {
rowCount = rowsOption;
// If innerSize is negative, we are trying to set too
// many rows in the rows option, so fall back to
// treating it as innerSize 0
}
else {
innerSize = 0;
rowFraction = 1;
}
}
else {
rowCount = Math.floor(rowCount * rowFraction);
}
for (row = rowCount; row > 0; row--) {
rowRadius = (innerSize + (row / rowCount) *
(diameter - innerSize - itemSize)) / 2;
rowLength = fullAngle * rowRadius;
colCount = Math.ceil(rowLength / itemSize);
testRows.push({
rowRadius: rowRadius,
rowLength: rowLength,
colCount: colCount
});
itemCount += colCount + 1;
}
}
if (!rows) {
return;
}
// We now have more slots than we have total items. Loop over
// the rows and remove the last slot until the count is correct.
// For each iteration we sort the last slot by the angle, and
// remove those with the highest angles.
var overshoot = finalItemCount - this.total;
/**
* @private
* @param {Highcharts.ItemRowContainerObject} item
* Wrapped object with angle and row
* @return {void}
*/
function cutOffRow(item) {
if (overshoot > 0) {
item.row.colCount--;
overshoot--;
}
}
while (overshoot > 0) {
rows
// Return a simplified representation of the angle of
// the last slot within each row.
.map(function (row) {
return {
angle: row.colCount / row.rowLength,
row: row
};
})
// Sort by the angles...
.sort(function (a, b) {
return b.angle - a.angle;
})
// ...so that we can ignore the items with the lowest
// angles...
.slice(0, Math.min(overshoot, Math.ceil(rows.length / 2)))
// ...and remove the ones with the highest angles
.forEach(cutOffRow);
}
rows.forEach(function (row) {
var rowRadius = row.rowRadius, colCount = row.colCount;
increment = colCount ? fullAngle / colCount : 0;
for (col = 0; col <= colCount; col += 1) {
angle = this.startAngleRad + col * increment;
x = center[0] + Math.cos(angle) * rowRadius;
y = center[1] + Math.sin(angle) * rowRadius;
slots.push({ x: x, y: y, angle: angle });
}
}, this);
// Sort by angle
slots.sort(function (a, b) {
return a.angle - b.angle;
});
this.itemSize = itemSize;
return slots;
},
getRows: function () {
var rows = this.options.rows, cols, ratio;
// Get the row count that gives the most square cells
if (!rows) {
ratio = this.chart.plotWidth / this.chart.plotHeight;
rows = Math.sqrt(this.total);
if (ratio > 1) {
rows = Math.ceil(rows);
while (rows > 0) {
cols = this.total / rows;
if (cols / rows > ratio) {
break;
}
rows--;
}
}
else {
rows = Math.floor(rows);
while (rows < this.total) {
cols = this.total / rows;
if (cols / rows < ratio) {
break;
}
rows++;
}
}
}
return rows;
},
drawPoints: function () {
var series = this, options = this.options, renderer = series.chart.renderer, seriesMarkerOptions = options.marker, borderWidth = this.borderWidth, crisp = borderWidth % 2 ? 0.5 : 1, i = 0, rows = this.getRows(), cols = Math.ceil(this.total / rows), cellWidth = this.chart.plotWidth / cols, cellHeight = this.chart.plotHeight / rows, itemSize = this.itemSize || Math.min(cellWidth, cellHeight);
/*
this.slots.forEach(slot => {
this.chart.renderer.circle(slot.x, slot.y, 6)
.attr({
fill: 'silver'
})
.add(this.group);
});
//*/
this.points.forEach(function (point) {
var attr, graphics, pointAttr, pointMarkerOptions = point.marker || {}, symbol = (pointMarkerOptions.symbol ||
seriesMarkerOptions.symbol), r = pick(pointMarkerOptions.radius, seriesMarkerOptions.radius), size = defined(r) ? 2 * r : itemSize, padding = size * options.itemPadding, x, y, width, height;
point.graphics = graphics = point.graphics || {};
if (!series.chart.styledMode) {
pointAttr = series.pointAttribs(point, point.selected && 'select');
}
if (!point.isNull && point.visible) {
if (!point.graphic) {
point.graphic = renderer.g('point')
.add(series.group);
}
for (var val = 0; val < point.y; val++) {
// Semi-circle
if (series.center && series.slots) {
// Fill up the slots from left to right
var slot = series.slots.shift();
x = slot.x - itemSize / 2;
y = slot.y - itemSize / 2;
}
else if (options.layout === 'horizontal') {
x = cellWidth * (i % cols);
y = cellHeight * Math.floor(i / cols);
}
else {
x = cellWidth * Math.floor(i / rows);
y = cellHeight * (i % rows);
}
x += padding;
y += padding;
width = Math.round(size - 2 * padding);
height = width;
if (series.options.crisp) {
x = Math.round(x) - crisp;
y = Math.round(y) + crisp;
}
attr = {
x: x,
y: y,
width: width,
height: height
};
if (typeof r !== 'undefined') {
attr.r = r;
}
if (graphics[val]) {
graphics[val].animate(attr);
}
else {
graphics[val] = renderer
.symbol(symbol, null, null, null, null, {
backgroundSize: 'within'
})
.attr(extend(attr, pointAttr))
.add(point.graphic);
}
graphics[val].isActive = true;
i++;
}
}
objectEach(graphics, function (graphic, key) {
if (!graphic.isActive) {
graphic.destroy();
delete graphics[key];
}
else {
graphic.isActive = false;
}
});
});
},
drawDataLabels: function () {
if (this.center && this.slots) {
H.seriesTypes.pie.prototype.drawDataLabels.call(this);
// else, it's just a dot chart with no natural place to put the
// data labels
}
else {
this.points.forEach(function (point) {
point.destroyElements({ dataLabel: 1 });
});
}
},
// Fade in the whole chart
animate: function (init) {
if (init) {
this.group.attr({
opacity: 0
});
}
else {
this.group.animate({
opacity: 1
}, this.options.animation);
}
}
},
// Point class
{
connectorShapes: piePoint.connectorShapes,
getConnectorPath: piePoint.getConnectorPath,
setVisible: piePoint.setVisible,
getTranslate: piePoint.getTranslate
});
/**
* An `item` series. If the [type](#series.item.type) option is not specified,
* it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.item
* @excluding dataParser, dataURL, stack, xAxis, yAxis, dataSorting
* @product highcharts
* @requires modules/item-series
* @apioption series.item
*/
/**
* An array of data points for the series. For the `item` series type,
* points can be given in the following ways:
*
* 1. An array of numerical values. In this case, the numerical values will be
* interpreted as `y` options. Example:
* ```js
* data: [0, 5, 3, 5]
* ```
*
* 2. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.item.turboThreshold),
* this option is not available.
* ```js
* data: [{
* y: 1,
* name: "Point2",
* color: "#00FF00"
* }, {
* y: 7,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @sample {highcharts} highcharts/chart/reflow-true/
* Numerical values
* @sample {highcharts} highcharts/series/data-array-of-arrays/
* Arrays of numeric x and y
* @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/
* Arrays of datetime x and y
* @sample {highcharts} highcharts/series/data-array-of-name-value/
* Arrays of point.name and y
* @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
*
* @type {Array<number|Array<string,(number|null)>|null|*>}
* @extends series.pie.data
* @excludes sliced
* @product highcharts
* @apioption series.item.data
*/
/**
* The sequential index of the data point in the legend.
*
* @type {number}
* @product highcharts
* @apioption series.pie.data.legendIndex
*/
''; // adds the doclets above to the transpiled file

View File

@@ -0,0 +1,140 @@
/* *
*
* (c) 2010-2020 Sebastian Bochan, Rafal Sebestjanski
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../parts/Globals.js';
import U from '../parts/Utilities.js';
var seriesType = U.seriesType;
var areaProto = H.seriesTypes.area.prototype, colProto = H.seriesTypes.column.prototype;
/**
* The lollipop series is a carteseian series with a line anchored from
* the x axis and a dot at the end to mark the value.
* Requires `highcharts-more.js`, `modules/dumbbell.js` and
* `modules/lollipop.js`.
*
* @sample {highcharts} highcharts/demo/lollipop/
* Lollipop chart
* @sample {highcharts} highcharts/series-dumbbell/styled-mode-dumbbell/
* Styled mode
*
* @extends plotOptions.dumbbell
* @product highcharts highstock
* @excluding fillColor, fillOpacity, lineWidth, stack, stacking, lowColor,
* stickyTracking, trackByArea
* @since 8.0.0
* @optionparent plotOptions.lollipop
*/
seriesType('lollipop', 'dumbbell', {
/** @ignore-option */
lowColor: void 0,
/** @ignore-option */
threshold: 0,
/** @ignore-option */
connectorWidth: 1,
/** @ignore-option */
groupPadding: 0.2,
/** @ignore-option */
pointPadding: 0.1,
/** @ignore-option */
states: {
hover: {
/** @ignore-option */
lineWidthPlus: 0,
/** @ignore-option */
connectorWidthPlus: 1,
/** @ignore-option */
halo: false
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">●</span> {series.name}: <b>{point.low}</b><br/>'
}
}, {
translatePoint: areaProto.translate,
drawPoint: areaProto.drawPoints,
drawDataLabels: colProto.drawDataLabels,
setShapeArgs: colProto.translate
}, {
pointSetState: areaProto.pointClass.prototype.setState,
setState: H.seriesTypes.dumbbell.prototype.pointClass.prototype.setState
});
/**
* The `lollipop` series. If the [type](#series.lollipop.type) option is
* not specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.lollipop
* @product highcharts highstock
* @requires highcharts-more
* @requires modules/dumbbell
* @requires modules/lollipop
* @apioption series.lollipop
*/
/**
* An array of data points for the series. For the `lollipop` series type,
* points can be given in the following ways:
*
* 1. An array of numerical values. In this case, the numerical values will be
* interpreted as `y` options. The `x` values will be automatically
* calculated, either starting at 0 and incremented by 1, or from
* `pointStart` and `pointInterval` given in the series options. If the axis
* has categories, these will be used. Example:
* ```js
* data: [0, 5, 3, 5]
* ```
*
* 2. An array of arrays with 2 values. In this case, the values correspond to
* `x,y`. If the first value is a string, it is applied as the name of the
* point, and the `x` value is inferred.
* ```js
* data: [
* [0, 6],
* [1, 2],
* [2, 6]
* ]
* ```
*
* 3. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.lollipop.turboThreshold), this option is not
* available.
* ```js
* data: [{
* x: 1,
* y: 9,
* name: "Point2",
* color: "#00FF00",
* connectorWidth: 3,
* connectorColor: "#FF00FF"
* }, {
* x: 1,
* y: 6,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @sample {highcharts} highcharts/chart/reflow-true/
* Numerical values
* @sample {highcharts} highcharts/series/data-array-of-arrays/
* Arrays of numeric x and y
* @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/
* Arrays of datetime x and y
* @sample {highcharts} highcharts/series/data-array-of-name-value/
* Arrays of point.name and y
* @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
*
* @type {Array<number|Array<(number|string),(number|null)>|null|*>}
* @extends series.dumbbell.data
* @excluding lowColor
* @product highcharts highstock
* @apioption series.lollipop.data
*/
''; // adds doclets above to transpiled file

View File

@@ -0,0 +1,365 @@
/* *
*
* (c) 2009-2020 Torstein Honsi
*
* SVG map parser. This file requires data.js.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
/* global document, jQuery, $ */
'use strict';
import H from '../parts/Globals.js';
import U from '../parts/Utilities.js';
var extend = U.extend, wrap = U.wrap;
import './data.src.js';
/* eslint-disable no-invalid-this */
wrap(H.Data.prototype, 'init', function (proceed, options) {
proceed.call(this, options);
if (options.svg) {
this.loadSVG();
}
});
/* eslint-enable no-invalid-this */
extend(H.Data.prototype, {
// Parse an SVG path into a simplified array that Highcharts can read
pathToArray: function (path, matrix) {
var i = 0, position = 0, point, positions, fixedPoint = [0, 0], startPoint = [0, 0], isRelative, isString, operator, matrixTransform = function (p, m) {
return [
m.a * p[0] + m.c * p[1] + m.e,
m.b * p[0] + m.d * p[1] + m.f
];
};
path = path
// Scientific notation
.replace(/[0-9]+e-?[0-9]+/g, function (a) {
return (+a); // cast to number
})
// Move letters apart
.replace(/([A-Za-z])/g, ' $1 ')
// Add space before minus
.replace(/-/g, ' -')
// Trim
.replace(/^\s*/, '').replace(/\s*$/, '')
// Remove newlines, tabs etc
.replace(/\s+/g, ' ')
// Split on spaces, minus and commas
.split(/[ ,]+/);
// Blank path
if (path.length === 1) {
return [];
}
// Real path
for (i = 0; i < path.length; i++) {
isString = /[a-zA-Z]/.test(path[i]);
// Handle strings
if (isString) {
operator = path[i];
positions = 2;
// Curves have six positions
if (operator === 'c' || operator === 'C') {
positions = 6;
}
// When moving after a closed subpath, start again from previous
// subpath's starting point
if (operator === 'm') {
startPoint = [
parseFloat(path[i + 1]) + startPoint[0],
parseFloat(path[i + 2]) + startPoint[1]
];
}
else if (operator === 'M') {
startPoint = [
parseFloat(path[i + 1]),
parseFloat(path[i + 2])
];
}
// Enter or exit relative mode
if (operator === 'm' || operator === 'l' || operator === 'c') {
path[i] = operator.toUpperCase();
isRelative = true;
}
else if (operator === 'M' ||
operator === 'L' ||
operator === 'C') {
isRelative = false;
// Horizontal and vertical line to
}
else if (operator === 'h') {
isRelative = true;
path[i] = 'L';
path.splice(i + 2, 0, 0);
}
else if (operator === 'v') {
isRelative = true;
path[i] = 'L';
path.splice(i + 1, 0, 0);
}
else if (operator === 's') {
isRelative = true;
path[i] = 'L';
path.splice(i + 1, 2);
}
else if (operator === 'S') {
isRelative = false;
path[i] = 'L';
path.splice(i + 1, 2);
}
else if (operator === 'H' || operator === 'h') {
isRelative = false;
path[i] = 'L';
path.splice(i + 2, 0, fixedPoint[1]);
}
else if (operator === 'V' || operator === 'v') {
isRelative = false;
path[i] = 'L';
path.splice(i + 1, 0, fixedPoint[0]);
}
else if (operator === 'z' || operator === 'Z') {
fixedPoint = startPoint;
}
// Handle numbers
}
else {
path[i] = parseFloat(path[i]);
if (isRelative) {
path[i] += fixedPoint[position % 2];
}
if (position % 2 === 1) { // y
// only translate absolute points or initial moveTo
if (matrix &&
(!isRelative || (operator === 'm' && i < 3))) {
point = matrixTransform([path[i - 1], path[i]], matrix);
path[i - 1] = point[0];
path[i] = point[1];
}
}
// Reset to zero position (x/y switching)
if (position === positions - 1) {
// Set the fixed point for the next pair
fixedPoint = [path[i - 1], path[i]];
position = 0;
}
else {
position += 1;
}
}
}
// Handle polygon points
if (typeof path[0] === 'number' && path.length >= 4) {
path.unshift('M');
path.splice(3, 0, 'L');
}
return path;
},
// Join the path back to a string for compression
pathToString: function (arr) {
arr.forEach(function (point) {
var path = point.path;
// Join all by commas
path = path.join(',');
// Remove commas next to a letter
path = path.replace(/,?([a-zA-Z]),?/g, '$1');
// Reinsert
point.path = path;
});
return arr;
},
// Scale the path to fit within a given box and round all numbers
roundPaths: function (arr, scale) {
var mapProto = H.seriesTypes.map.prototype, fakeSeries, origSize, transA;
fakeSeries = {
xAxis: {
translate: H.Axis.prototype.translate,
options: {},
minPixelPadding: 0
},
yAxis: {
translate: H.Axis.prototype.translate,
options: {},
minPixelPadding: 0
}
};
// Borrow the map series type's getBox method
mapProto.getBox.call(fakeSeries, arr);
origSize = Math.max(fakeSeries.maxX - fakeSeries.minX, fakeSeries.maxY - fakeSeries.minY);
scale = scale || 1000;
transA = scale / origSize;
fakeSeries.xAxis.transA = fakeSeries.yAxis.transA = transA;
fakeSeries.xAxis.len = fakeSeries.yAxis.len = scale;
fakeSeries.xAxis.min = fakeSeries.minX;
fakeSeries.yAxis.min = (fakeSeries.minY + scale) / transA;
arr.forEach(function (point) {
var i, path;
point.path = path = mapProto.translatePath.call(fakeSeries, point.path, true);
i = path.length;
while (i--) {
if (typeof path[i] === 'number') {
path[i] = Math.round(path[i]);
}
}
delete point._foundBox;
});
return arr;
},
// Load an SVG file and extract the paths
loadSVG: function () {
var data = this, options = this.options;
/* eslint-disable valid-jsdoc */
/**
* @private
*/
function getPathLikeChildren(parent) {
return Array.prototype.slice
.call(parent.getElementsByTagName('path'))
.concat(Array.prototype.slice.call(parent.getElementsByTagName('polygon')))
.concat(Array.prototype.slice.call(parent.getElementsByTagName('rect')));
}
/**
* @private
*/
function getPathDefinition(node) {
if (node.nodeName === 'path') {
return node.getAttribute('d');
}
if (node.nodeName === 'polygon') {
return node.getAttribute('points');
}
if (node.nodeName === 'rect') {
var x = +node.getAttribute('x'), y = +node.getAttribute('y'), w = +node.getAttribute('width'), h = +node.getAttribute('height');
// Return polygon definition
return [x, y, x + w, y, x + w, y + h, x, y + h, x, y].join(' ');
}
}
/**
* @private
*/
function getTranslate(elem) {
var ctm = elem.getCTM();
if (!isNaN(ctm.f)) {
return ctm;
}
}
/**
* @private
*/
function getName(elem) {
var desc = elem.getElementsByTagName('desc'), nameTag = desc[0] && desc[0].getElementsByTagName('name'), name = nameTag && nameTag[0] && nameTag[0].innerText;
return (name ||
elem.getAttribute('inkscape:label') ||
elem.getAttribute('id') ||
elem.getAttribute('class'));
}
/**
* @private
*/
function hasFill(elem) {
return (!/fill[\s]?\:[\s]?none/.test(elem.getAttribute('style')) &&
elem.getAttribute('fill') !== 'none');
}
/**
* @private
*/
function handleSVG(xml) {
var arr = [], currentParent, allPaths, commonLineage, lastCommonAncestor, handleGroups;
// Make a hidden frame where the SVG is rendered
data.$frame = data.$frame || $('<div>')
.css({
position: 'absolute',
top: '-9999em'
})
.appendTo($(document.body));
data.$frame.html(xml);
xml = $('svg', data.$frame)[0];
xml.removeAttribute('viewBox');
allPaths = getPathLikeChildren(xml);
// Skip clip paths
['defs', 'clipPath'].forEach(function (nodeName) {
xml.getElementsByTagName(nodeName).forEach(function (parent) {
parent.getElementsByTagName('path').forEach(function (path) {
path.skip = true;
});
});
});
// If not all paths belong to the same group, handle groups
allPaths.forEach(function (path, i) {
if (!path.skip) {
var itemLineage = [], parentNode, j;
if (i > 0 && path.parentNode !== currentParent) {
handleGroups = true;
}
currentParent = path.parentNode;
// Handle common lineage
parentNode = path;
while (parentNode) {
itemLineage.push(parentNode);
parentNode = parentNode.parentNode;
}
itemLineage.reverse();
if (!commonLineage) {
commonLineage = itemLineage; // first iteration
}
else {
for (j = 0; j < commonLineage.length; j++) {
if (commonLineage[j] !== itemLineage[j]) {
commonLineage = commonLineage.slice(0, j);
}
}
}
}
});
lastCommonAncestor = commonLineage[commonLineage.length - 1];
// Iterate groups to find sub paths
if (handleGroups) {
lastCommonAncestor.getElementsByTagName('g').forEach(function (g) {
var groupPath = [], pathHasFill;
getPathLikeChildren(g).forEach(function (path) {
if (!path.skip) {
groupPath = groupPath.concat(data.pathToArray(getPathDefinition(path), getTranslate(path)));
if (hasFill(path)) {
pathHasFill = true;
}
path.skip = true;
}
});
arr.push({
name: getName(g),
path: groupPath,
hasFill: pathHasFill
});
});
}
// Iterate the remaining paths that are not parts of groups
allPaths.forEach(function (path) {
if (!path.skip) {
arr.push({
name: getName(path),
path: data.pathToArray(getPathDefinition(path), getTranslate(path)),
hasFill: hasFill(path)
});
}
});
// Round off to compress
data.roundPaths(arr);
// Do the callback
options.complete({
series: [{
data: arr
}]
});
}
/* eslint-enable valid-jsdoc */
if (options.svg.indexOf('<svg') !== -1) {
handleSVG(options.svg);
}
else {
jQuery.ajax({
url: options.svg,
dataType: 'text',
success: handleSVG
});
}
}
});

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,354 @@
/* *
*
* Networkgraph series
*
* (c) 2010-2020 Paweł Fus
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../parts/Globals.js';
import U from '../../parts/Utilities.js';
var extend = U.extend;
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* The QuadTree node class. Used in Networkgraph chart as a base for Barnes-Hut
* approximation.
*
* @private
* @class
* @name Highcharts.QuadTreeNode
*
* @param {Highcharts.Dictionary<number>} box Available space for the node
*/
var QuadTreeNode = H.QuadTreeNode = function (box) {
/**
* Read only. The available space for node.
*
* @name Highcharts.QuadTreeNode#box
* @type {Highcharts.Dictionary<number>}
*/
this.box = box;
/**
* Read only. The minium of width and height values.
*
* @name Highcharts.QuadTreeNode#boxSize
* @type {number}
*/
this.boxSize = Math.min(box.width, box.height);
/**
* Read only. Array of subnodes. Empty if QuadTreeNode has just one Point.
* When added another Point to this QuadTreeNode, array is filled with four
* subnodes.
*
* @name Highcharts.QuadTreeNode#nodes
* @type {Array<Highcharts.QuadTreeNode>}
*/
this.nodes = [];
/**
* Read only. Flag to determine if QuadTreeNode is internal (and has
* subnodes with mass and central position) or external (bound to Point).
*
* @name Highcharts.QuadTreeNode#isInternal
* @type {boolean}
*/
this.isInternal = false;
/**
* Read only. If QuadTreeNode is an external node, Point is stored in
* `this.body`.
*
* @name Highcharts.QuadTreeNode#body
* @type {boolean|Highcharts.Point}
*/
this.body = false;
/**
* Read only. Internal nodes when created are empty to reserve the space. If
* Point is added to this QuadTreeNode, QuadTreeNode is no longer empty.
*
* @name Highcharts.QuadTreeNode#isEmpty
* @type {boolean}
*/
this.isEmpty = true;
};
extend(QuadTreeNode.prototype,
/** @lends Highcharts.QuadTreeNode.prototype */
{
/**
* Insert recursively point(node) into the QuadTree. If the given
* quadrant is already occupied, divide it into smaller quadrants.
*
* @param {Highcharts.Point} point
* Point/node to be inserted
* @param {number} depth
* Max depth of the QuadTree
*/
insert: function (point, depth) {
var newQuadTreeNode;
if (this.isInternal) {
// Internal node:
this.nodes[this.getBoxPosition(point)].insert(point, depth - 1);
}
else {
this.isEmpty = false;
if (!this.body) {
// First body in a quadrant:
this.isInternal = false;
this.body = point;
}
else {
if (depth) {
// Every other body in a quadrant:
this.isInternal = true;
this.divideBox();
// Reinsert main body only once:
if (this.body !== true) {
this.nodes[this.getBoxPosition(this.body)]
.insert(this.body, depth - 1);
this.body = true;
}
// Add second body:
this.nodes[this.getBoxPosition(point)]
.insert(point, depth - 1);
}
else {
// We are below max allowed depth. That means either:
// - really huge number of points
// - falling two points into exactly the same position
// In this case, create another node in the QuadTree.
//
// Alternatively we could add some noise to the
// position, but that could result in different
// rendered chart in exporting.
newQuadTreeNode = new QuadTreeNode({
top: point.plotX,
left: point.plotY,
// Width/height below 1px
width: 0.1,
height: 0.1
});
newQuadTreeNode.body = point;
newQuadTreeNode.isInternal = false;
this.nodes.push(newQuadTreeNode);
}
}
}
},
/**
* Each quad node requires it's mass and center position. That mass and
* position is used to imitate real node in the layout by approximation.
*/
updateMassAndCenter: function () {
var mass = 0, plotX = 0, plotY = 0;
if (this.isInternal) {
// Calcualte weightened mass of the quad node:
this.nodes.forEach(function (pointMass) {
if (!pointMass.isEmpty) {
mass += pointMass.mass;
plotX +=
pointMass.plotX * pointMass.mass;
plotY +=
pointMass.plotY * pointMass.mass;
}
});
plotX /= mass;
plotY /= mass;
}
else if (this.body) {
// Just one node, use coordinates directly:
mass = this.body.mass;
plotX = this.body.plotX;
plotY = this.body.plotY;
}
// Store details:
this.mass = mass;
this.plotX = plotX;
this.plotY = plotY;
},
/**
* When inserting another node into the box, that already hove one node,
* divide the available space into another four quadrants.
*
* Indexes of quadrants are:
* ```
* ------------- -------------
* | | | | |
* | | | 0 | 1 |
* | | divide() | | |
* | 1 | -----------> -------------
* | | | | |
* | | | 3 | 2 |
* | | | | |
* ------------- -------------
* ```
*/
divideBox: function () {
var halfWidth = this.box.width / 2, halfHeight = this.box.height / 2;
// Top left
this.nodes[0] = new QuadTreeNode({
left: this.box.left,
top: this.box.top,
width: halfWidth,
height: halfHeight
});
// Top right
this.nodes[1] = new QuadTreeNode({
left: this.box.left + halfWidth,
top: this.box.top,
width: halfWidth,
height: halfHeight
});
// Bottom right
this.nodes[2] = new QuadTreeNode({
left: this.box.left + halfWidth,
top: this.box.top + halfHeight,
width: halfWidth,
height: halfHeight
});
// Bottom left
this.nodes[3] = new QuadTreeNode({
left: this.box.left,
top: this.box.top + halfHeight,
width: halfWidth,
height: halfHeight
});
},
/**
* Determine which of the quadrants should be used when placing node in
* the QuadTree. Returned index is always in range `< 0 , 3 >`.
*
* @param {Highcharts.Point} point
* @return {number}
*/
getBoxPosition: function (point) {
var left = point.plotX < this.box.left + this.box.width / 2, top = point.plotY < this.box.top + this.box.height / 2, index;
if (left) {
if (top) {
// Top left
index = 0;
}
else {
// Bottom left
index = 3;
}
}
else {
if (top) {
// Top right
index = 1;
}
else {
// Bottom right
index = 2;
}
}
return index;
}
});
/**
* The QuadTree class. Used in Networkgraph chart as a base for Barnes-Hut
* approximation.
*
* @private
* @class
* @name Highcharts.QuadTree
*
* @param {number} x left position of the plotting area
* @param {number} y top position of the plotting area
* @param {number} width width of the plotting area
* @param {number} height height of the plotting area
*/
var QuadTree = H.QuadTree = function (x, y, width, height) {
// Boundary rectangle:
this.box = {
left: x,
top: y,
width: width,
height: height
};
this.maxDepth = 25;
this.root = new QuadTreeNode(this.box, '0');
this.root.isInternal = true;
this.root.isRoot = true;
this.root.divideBox();
};
extend(QuadTree.prototype,
/** @lends Highcharts.QuadTree.prototype */
{
/**
* Insert nodes into the QuadTree
*
* @param {Array<Highcharts.Point>} points
*/
insertNodes: function (points) {
points.forEach(function (point) {
this.root.insert(point, this.maxDepth);
}, this);
},
/**
* Depfth first treversal (DFS). Using `before` and `after` callbacks,
* we can get two results: preorder and postorder traversals, reminder:
*
* ```
* (a)
* / \
* (b) (c)
* / \
* (d) (e)
* ```
*
* DFS (preorder): `a -> b -> d -> e -> c`
*
* DFS (postorder): `d -> e -> b -> c -> a`
*
* @param {Highcharts.QuadTreeNode|null} node
* @param {Function} [beforeCallback] function to be called before
* visiting children nodes
* @param {Function} [afterCallback] function to be called after
* visiting children nodes
*/
visitNodeRecursive: function (node, beforeCallback, afterCallback) {
var goFurther;
if (!node) {
node = this.root;
}
if (node === this.root && beforeCallback) {
goFurther = beforeCallback(node);
}
if (goFurther === false) {
return;
}
node.nodes.forEach(function (qtNode) {
if (qtNode.isInternal) {
if (beforeCallback) {
goFurther = beforeCallback(qtNode);
}
if (goFurther === false) {
return;
}
this.visitNodeRecursive(qtNode, beforeCallback, afterCallback);
}
else if (qtNode.body) {
if (beforeCallback) {
beforeCallback(qtNode.body);
}
}
if (afterCallback) {
afterCallback(qtNode);
}
}, this);
if (node === this.root && afterCallback) {
afterCallback(node);
}
},
/**
* Calculate mass of the each QuadNode in the tree.
*/
calculateMassAndCenter: function () {
this.visitNodeRecursive(null, null, function (node) {
node.updateMassAndCenter();
});
}
});

View File

@@ -0,0 +1,150 @@
/* *
*
* Networkgraph series
*
* (c) 2010-2020 Paweł Fus
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
import H from '../../parts/Globals.js';
import U from '../../parts/Utilities.js';
var addEvent = U.addEvent;
var Chart = H.Chart;
/* eslint-disable no-invalid-this, valid-jsdoc */
H.dragNodesMixin = {
/**
* Mouse down action, initializing drag&drop mode.
*
* @private
* @param {Highcharts.Point} point The point that event occured.
* @param {Highcharts.PointerEventObject} event Browser event, before normalization.
* @return {void}
*/
onMouseDown: function (point, event) {
var normalizedEvent = this.chart.pointer.normalize(event);
point.fixedPosition = {
chartX: normalizedEvent.chartX,
chartY: normalizedEvent.chartY,
plotX: point.plotX,
plotY: point.plotY
};
point.inDragMode = true;
},
/**
* Mouse move action during drag&drop.
*
* @private
*
* @param {global.Event} event Browser event, before normalization.
* @param {Highcharts.Point} point The point that event occured.
*
* @return {void}
*/
onMouseMove: function (point, event) {
if (point.fixedPosition && point.inDragMode) {
var series = this, chart = series.chart, normalizedEvent = chart.pointer.normalize(event), diffX = point.fixedPosition.chartX - normalizedEvent.chartX, diffY = point.fixedPosition.chartY - normalizedEvent.chartY, newPlotX, newPlotY;
// At least 5px to apply change (avoids simple click):
if (Math.abs(diffX) > 5 || Math.abs(diffY) > 5) {
newPlotX = point.fixedPosition.plotX - diffX;
newPlotY = point.fixedPosition.plotY - diffY;
if (chart.isInsidePlot(newPlotX, newPlotY)) {
point.plotX = newPlotX;
point.plotY = newPlotY;
point.hasDragged = true;
this.redrawHalo(point);
if (!series.layout.simulation) {
// When dragging nodes, we don't need to calculate
// initial positions and rendering nodes:
series.layout.setInitialRendering(false);
// Start new simulation:
if (!series.layout.enableSimulation) {
// Run only one iteration to speed things up:
series.layout.setMaxIterations(1);
}
else {
series.layout.start();
}
series.chart.redraw();
// Restore defaults:
series.layout.setInitialRendering(true);
}
else {
// Extend current simulation:
series.layout.resetSimulation();
}
}
}
}
},
/**
* Mouse up action, finalizing drag&drop.
*
* @private
* @param {Highcharts.Point} point The point that event occured.
* @return {void}
*/
onMouseUp: function (point, event) {
if (point.fixedPosition && point.hasDragged) {
if (this.layout.enableSimulation) {
this.layout.start();
}
else {
this.chart.redraw();
}
point.inDragMode = point.hasDragged = false;
if (!this.options.fixedDraggable) {
delete point.fixedPosition;
}
}
},
// Draggable mode:
/**
* Redraw halo on mousemove during the drag&drop action.
*
* @private
* @param {Highcharts.Point} point The point that should show halo.
* @return {void}
*/
redrawHalo: function (point) {
if (point && this.halo) {
this.halo.attr({
d: point.haloPath(this.options.states.hover.halo.size)
});
}
}
};
/*
* Draggable mode:
*/
addEvent(Chart, 'load', function () {
var chart = this, mousedownUnbinder, mousemoveUnbinder, mouseupUnbinder;
if (chart.container) {
mousedownUnbinder = addEvent(chart.container, 'mousedown', function (event) {
var point = chart.hoverPoint;
if (point &&
point.series &&
point.series.hasDraggableNodes &&
point.series.options.draggable) {
point.series.onMouseDown(point, event);
mousemoveUnbinder = addEvent(chart.container, 'mousemove', function (e) {
return point &&
point.series &&
point.series.onMouseMove(point, e);
});
mouseupUnbinder = addEvent(chart.container.ownerDocument, 'mouseup', function (e) {
mousemoveUnbinder();
mouseupUnbinder();
return point &&
point.series &&
point.series.onMouseUp(point, e);
});
}
});
}
addEvent(chart, 'destroy', function () {
mousedownUnbinder();
});
});

View File

@@ -0,0 +1,362 @@
/* *
*
* Networkgraph series
*
* (c) 2010-2020 Paweł Fus
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../parts/Globals.js';
/* eslint-disable no-invalid-this, valid-jsdoc */
H.networkgraphIntegrations = {
verlet: {
/**
* Attractive force funtion. Can be replaced by API's
* `layoutAlgorithm.attractiveForce`
*
* @private
* @param {number} d current distance between two nodes
* @param {number} k expected distance between two nodes
* @return {number} force
*/
attractiveForceFunction: function (d, k) {
// Used in API:
return (k - d) / d;
},
/**
* Repulsive force funtion. Can be replaced by API's
* `layoutAlgorithm.repulsiveForce`
*
* @private
* @param {number} d current distance between two nodes
* @param {number} k expected distance between two nodes
* @return {number} force
*/
repulsiveForceFunction: function (d, k) {
// Used in API:
return (k - d) / d * (k > d ? 1 : 0); // Force only for close nodes
},
/**
* Barycenter force. Calculate and applys barycenter forces on the
* nodes. Making them closer to the center of their barycenter point.
*
* In Verlet integration, force is applied on a node immidatelly to it's
* `plotX` and `plotY` position.
*
* @private
* @return {void}
*/
barycenter: function () {
var gravitationalConstant = this.options.gravitationalConstant, xFactor = this.barycenter.xFactor, yFactor = this.barycenter.yFactor;
// To consider:
xFactor = (xFactor - (this.box.left + this.box.width) / 2) *
gravitationalConstant;
yFactor = (yFactor - (this.box.top + this.box.height) / 2) *
gravitationalConstant;
this.nodes.forEach(function (node) {
if (!node.fixedPosition) {
node.plotX -=
xFactor / node.mass / node.degree;
node.plotY -=
yFactor / node.mass / node.degree;
}
});
},
/**
* Repulsive force.
*
* In Verlet integration, force is applied on a node immidatelly to it's
* `plotX` and `plotY` position.
*
* @private
* @param {Highcharts.Point} node
* Node that should be translated by force.
* @param {number} force
* Force calcualated in `repulsiveForceFunction`
* @param {Highcharts.PositionObject} distance
* Distance between two nodes e.g. `{x, y}`
* @return {void}
*/
repulsive: function (node, force, distanceXY) {
var factor = force * this.diffTemperature / node.mass / node.degree;
if (!node.fixedPosition) {
node.plotX += distanceXY.x * factor;
node.plotY += distanceXY.y * factor;
}
},
/**
* Attractive force.
*
* In Verlet integration, force is applied on a node immidatelly to it's
* `plotX` and `plotY` position.
*
* @private
* @param {Highcharts.Point} link
* Link that connects two nodes
* @param {number} force
* Force calcualated in `repulsiveForceFunction`
* @param {Highcharts.PositionObject} distance
* Distance between two nodes e.g. `{x, y}`
* @return {void}
*/
attractive: function (link, force, distanceXY) {
var massFactor = link.getMass(), translatedX = -distanceXY.x * force * this.diffTemperature, translatedY = -distanceXY.y * force * this.diffTemperature;
if (!link.fromNode.fixedPosition) {
link.fromNode.plotX -=
translatedX * massFactor.fromNode / link.fromNode.degree;
link.fromNode.plotY -=
translatedY * massFactor.fromNode / link.fromNode.degree;
}
if (!link.toNode.fixedPosition) {
link.toNode.plotX +=
translatedX * massFactor.toNode / link.toNode.degree;
link.toNode.plotY +=
translatedY * massFactor.toNode / link.toNode.degree;
}
},
/**
* Integration method.
*
* In Verlet integration, forces are applied on node immidatelly to it's
* `plotX` and `plotY` position.
*
* Verlet without velocity:
*
* x(n+1) = 2 * x(n) - x(n-1) + A(T) * deltaT ^ 2
*
* where:
* - x(n+1) - new position
* - x(n) - current position
* - x(n-1) - previous position
*
* Assuming A(t) = 0 (no acceleration) and (deltaT = 1) we get:
*
* x(n+1) = x(n) + (x(n) - x(n-1))
*
* where:
* - (x(n) - x(n-1)) - position change
*
* TO DO:
* Consider Verlet with velocity to support additional
* forces. Or even Time-Corrected Verlet by Jonathan
* "lonesock" Dummer
*
* @private
* @param {Highcharts.NetworkgraphLayout} layout layout object
* @param {Highcharts.Point} node node that should be translated
* @return {void}
*/
integrate: function (layout, node) {
var friction = -layout.options.friction, maxSpeed = layout.options.maxSpeed, prevX = node.prevX, prevY = node.prevY,
// Apply friciton:
diffX = ((node.plotX + node.dispX -
prevX) * friction), diffY = ((node.plotY + node.dispY -
prevY) * friction), abs = Math.abs, signX = abs(diffX) / (diffX || 1), // need to deal with 0
signY = abs(diffY) / (diffY || 1);
// Apply max speed:
diffX = signX * Math.min(maxSpeed, Math.abs(diffX));
diffY = signY * Math.min(maxSpeed, Math.abs(diffY));
// Store for the next iteration:
node.prevX = node.plotX + node.dispX;
node.prevY = node.plotY + node.dispY;
// Update positions:
node.plotX += diffX;
node.plotY += diffY;
node.temperature = layout.vectorLength({
x: diffX,
y: diffY
});
},
/**
* Estiamte the best possible distance between two nodes, making graph
* readable.
*
* @private
* @param {Highcharts.NetworkgraphLayout} layout layout object
* @return {number}
*/
getK: function (layout) {
return Math.pow(layout.box.width * layout.box.height / layout.nodes.length, 0.5);
}
},
euler: {
/**
* Attractive force funtion. Can be replaced by API's
* `layoutAlgorithm.attractiveForce`
*
* Other forces that can be used:
*
* basic, not recommended:
* `function (d, k) { return d / k }`
*
* @private
* @param {number} d current distance between two nodes
* @param {number} k expected distance between two nodes
* @return {number} force
*/
attractiveForceFunction: function (d, k) {
return d * d / k;
},
/**
* Repulsive force funtion. Can be replaced by API's
* `layoutAlgorithm.repulsiveForce`.
*
* Other forces that can be used:
*
* basic, not recommended:
* `function (d, k) { return k / d }`
*
* standard:
* `function (d, k) { return k * k / d }`
*
* grid-variant:
* `function (d, k) { return k * k / d * (2 * k - d > 0 ? 1 : 0) }`
*
* @private
* @param {number} d current distance between two nodes
* @param {number} k expected distance between two nodes
* @return {number} force
*/
repulsiveForceFunction: function (d, k) {
return k * k / d;
},
/**
* Barycenter force. Calculate and applys barycenter forces on the
* nodes. Making them closer to the center of their barycenter point.
*
* In Euler integration, force is stored in a node, not changing it's
* position. Later, in `integrate()` forces are applied on nodes.
*
* @private
* @return {void}
*/
barycenter: function () {
var gravitationalConstant = this.options.gravitationalConstant, xFactor = this.barycenter.xFactor, yFactor = this.barycenter.yFactor;
this.nodes.forEach(function (node) {
if (!node.fixedPosition) {
var degree = node.getDegree(), phi = degree * (1 + degree / 2);
node.dispX += ((xFactor - node.plotX) *
gravitationalConstant *
phi / node.degree);
node.dispY += ((yFactor - node.plotY) *
gravitationalConstant *
phi / node.degree);
}
});
},
/**
* Repulsive force.
*
* @private
* @param {Highcharts.Point} node
* Node that should be translated by force.
* @param {number} force
* Force calcualated in `repulsiveForceFunction`
* @param {Highcharts.PositionObject} distanceXY
* Distance between two nodes e.g. `{x, y}`
* @return {void}
*/
repulsive: function (node, force, distanceXY, distanceR) {
node.dispX +=
(distanceXY.x / distanceR) * force / node.degree;
node.dispY +=
(distanceXY.y / distanceR) * force / node.degree;
},
/**
* Attractive force.
*
* In Euler integration, force is stored in a node, not changing it's
* position. Later, in `integrate()` forces are applied on nodes.
*
* @private
* @param {Highcharts.Point} link
* Link that connects two nodes
* @param {number} force
* Force calcualated in `repulsiveForceFunction`
* @param {Highcharts.PositionObject} distanceXY
* Distance between two nodes e.g. `{x, y}`
* @param {number} distanceR
* @return {void}
*/
attractive: function (link, force, distanceXY, distanceR) {
var massFactor = link.getMass(), translatedX = (distanceXY.x / distanceR) * force, translatedY = (distanceXY.y / distanceR) * force;
if (!link.fromNode.fixedPosition) {
link.fromNode.dispX -=
translatedX * massFactor.fromNode / link.fromNode.degree;
link.fromNode.dispY -=
translatedY * massFactor.fromNode / link.fromNode.degree;
}
if (!link.toNode.fixedPosition) {
link.toNode.dispX +=
translatedX * massFactor.toNode / link.toNode.degree;
link.toNode.dispY +=
translatedY * massFactor.toNode / link.toNode.degree;
}
},
/**
* Integration method.
*
* In Euler integration, force were stored in a node, not changing it's
* position. Now, in the integrator method, we apply changes.
*
* Euler:
*
* Basic form: `x(n+1) = x(n) + v(n)`
*
* With Rengoild-Fruchterman we get:
* `x(n+1) = x(n) + v(n) / length(v(n)) * min(v(n), temperature(n))`
* where:
* - `x(n+1)`: next position
* - `x(n)`: current position
* - `v(n)`: velocity (comes from net force)
* - `temperature(n)`: current temperature
*
* Known issues:
* Oscillations when force vector has the same magnitude but opposite
* direction in the next step. Potentially solved by decreasing force by
* `v * (1 / node.degree)`
*
* Note:
* Actually `min(v(n), temperature(n))` replaces simulated annealing.
*
* @private
* @param {Highcharts.NetworkgraphLayout} layout
* Layout object
* @param {Highcharts.Point} node
* Node that should be translated
* @return {void}
*/
integrate: function (layout, node) {
var distanceR;
node.dispX +=
node.dispX * layout.options.friction;
node.dispY +=
node.dispY * layout.options.friction;
distanceR = node.temperature = layout.vectorLength({
x: node.dispX,
y: node.dispY
});
if (distanceR !== 0) {
node.plotX += (node.dispX / distanceR *
Math.min(Math.abs(node.dispX), layout.temperature));
node.plotY += (node.dispY / distanceR *
Math.min(Math.abs(node.dispY), layout.temperature));
}
},
/**
* Estiamte the best possible distance between two nodes, making graph
* readable.
*
* @private
* @param {object} layout layout object
* @return {number}
*/
getK: function (layout) {
return Math.pow(layout.box.width * layout.box.height / layout.nodes.length, 0.3);
}
}
};

View File

@@ -0,0 +1,504 @@
/* *
*
* Networkgraph series
*
* (c) 2010-2020 Paweł Fus
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../parts/Globals.js';
import U from '../../parts/Utilities.js';
var addEvent = U.addEvent, clamp = U.clamp, defined = U.defined, extend = U.extend, isFunction = U.isFunction, pick = U.pick, setAnimation = U.setAnimation;
import './integrations.js';
import './QuadTree.js';
var Chart = H.Chart;
/* eslint-disable no-invalid-this, valid-jsdoc */
H.layouts = {
'reingold-fruchterman': function () {
}
};
extend(
/**
* Reingold-Fruchterman algorithm from
* "Graph Drawing by Force-directed Placement" paper.
* @private
*/
H.layouts['reingold-fruchterman'].prototype, {
init: function (options) {
this.options = options;
this.nodes = [];
this.links = [];
this.series = [];
this.box = {
x: 0,
y: 0,
width: 0,
height: 0
};
this.setInitialRendering(true);
this.integration =
H.networkgraphIntegrations[options.integration];
this.attractiveForce = pick(options.attractiveForce, this.integration.attractiveForceFunction);
this.repulsiveForce = pick(options.repulsiveForce, this.integration.repulsiveForceFunction);
this.approximation = options.approximation;
},
start: function () {
var layout = this, series = this.series, options = this.options;
layout.currentStep = 0;
layout.forces = series[0] && series[0].forces || [];
if (layout.initialRendering) {
layout.initPositions();
// Render elements in initial positions:
series.forEach(function (s) {
s.render();
});
}
layout.setK();
layout.resetSimulation(options);
if (options.enableSimulation) {
layout.step();
}
},
step: function () {
var layout = this, series = this.series, options = this.options;
// Algorithm:
layout.currentStep++;
if (layout.approximation === 'barnes-hut') {
layout.createQuadTree();
layout.quadTree.calculateMassAndCenter();
}
layout.forces.forEach(function (forceName) {
layout[forceName + 'Forces'](layout.temperature);
});
// Limit to the plotting area and cool down:
layout.applyLimits(layout.temperature);
// Cool down the system:
layout.temperature = layout.coolDown(layout.startTemperature, layout.diffTemperature, layout.currentStep);
layout.prevSystemTemperature = layout.systemTemperature;
layout.systemTemperature = layout.getSystemTemperature();
if (options.enableSimulation) {
series.forEach(function (s) {
// Chart could be destroyed during the simulation
if (s.chart) {
s.render();
}
});
if (layout.maxIterations-- &&
isFinite(layout.temperature) &&
!layout.isStable()) {
if (layout.simulation) {
H.win.cancelAnimationFrame(layout.simulation);
}
layout.simulation = H.win.requestAnimationFrame(function () {
layout.step();
});
}
else {
layout.simulation = false;
}
}
},
stop: function () {
if (this.simulation) {
H.win.cancelAnimationFrame(this.simulation);
}
},
setArea: function (x, y, w, h) {
this.box = {
left: x,
top: y,
width: w,
height: h
};
},
setK: function () {
// Optimal distance between nodes,
// available space around the node:
this.k = this.options.linkLength || this.integration.getK(this);
},
addElementsToCollection: function (elements, collection) {
elements.forEach(function (elem) {
if (collection.indexOf(elem) === -1) {
collection.push(elem);
}
});
},
removeElementFromCollection: function (element, collection) {
var index = collection.indexOf(element);
if (index !== -1) {
collection.splice(index, 1);
}
},
clear: function () {
this.nodes.length = 0;
this.links.length = 0;
this.series.length = 0;
this.resetSimulation();
},
resetSimulation: function () {
this.forcedStop = false;
this.systemTemperature = 0;
this.setMaxIterations();
this.setTemperature();
this.setDiffTemperature();
},
setMaxIterations: function (maxIterations) {
this.maxIterations = pick(maxIterations, this.options.maxIterations);
},
setTemperature: function () {
this.temperature = this.startTemperature =
Math.sqrt(this.nodes.length);
},
setDiffTemperature: function () {
this.diffTemperature = this.startTemperature /
(this.options.maxIterations + 1);
},
setInitialRendering: function (enable) {
this.initialRendering = enable;
},
createQuadTree: function () {
this.quadTree = new H.QuadTree(this.box.left, this.box.top, this.box.width, this.box.height);
this.quadTree.insertNodes(this.nodes);
},
initPositions: function () {
var initialPositions = this.options.initialPositions;
if (isFunction(initialPositions)) {
initialPositions.call(this);
this.nodes.forEach(function (node) {
if (!defined(node.prevX)) {
node.prevX = node.plotX;
}
if (!defined(node.prevY)) {
node.prevY = node.plotY;
}
node.dispX = 0;
node.dispY = 0;
});
}
else if (initialPositions === 'circle') {
this.setCircularPositions();
}
else {
this.setRandomPositions();
}
},
setCircularPositions: function () {
var box = this.box, nodes = this.nodes, nodesLength = nodes.length + 1, angle = 2 * Math.PI / nodesLength, rootNodes = nodes.filter(function (node) {
return node.linksTo.length === 0;
}), sortedNodes = [], visitedNodes = {}, radius = this.options.initialPositionRadius;
/**
* @private
*/
function addToNodes(node) {
node.linksFrom.forEach(function (link) {
if (!visitedNodes[link.toNode.id]) {
visitedNodes[link.toNode.id] = true;
sortedNodes.push(link.toNode);
addToNodes(link.toNode);
}
});
}
// Start with identified root nodes an sort the nodes by their
// hierarchy. In trees, this ensures that branches don't cross
// eachother.
rootNodes.forEach(function (rootNode) {
sortedNodes.push(rootNode);
addToNodes(rootNode);
});
// Cyclic tree, no root node found
if (!sortedNodes.length) {
sortedNodes = nodes;
// Dangling, cyclic trees
}
else {
nodes.forEach(function (node) {
if (sortedNodes.indexOf(node) === -1) {
sortedNodes.push(node);
}
});
}
// Initial positions are laid out along a small circle, appearing
// as a cluster in the middle
sortedNodes.forEach(function (node, index) {
node.plotX = node.prevX = pick(node.plotX, box.width / 2 + radius * Math.cos(index * angle));
node.plotY = node.prevY = pick(node.plotY, box.height / 2 + radius * Math.sin(index * angle));
node.dispX = 0;
node.dispY = 0;
});
},
setRandomPositions: function () {
var box = this.box, nodes = this.nodes, nodesLength = nodes.length + 1;
/**
* Return a repeatable, quasi-random number based on an integer
* input. For the initial positions
* @private
*/
function unrandom(n) {
var rand = n * n / Math.PI;
rand = rand - Math.floor(rand);
return rand;
}
// Initial positions:
nodes.forEach(function (node, index) {
node.plotX = node.prevX = pick(node.plotX, box.width * unrandom(index));
node.plotY = node.prevY = pick(node.plotY, box.height * unrandom(nodesLength + index));
node.dispX = 0;
node.dispY = 0;
});
},
force: function (name) {
this.integration[name].apply(this, Array.prototype.slice.call(arguments, 1));
},
barycenterForces: function () {
this.getBarycenter();
this.force('barycenter');
},
getBarycenter: function () {
var systemMass = 0, cx = 0, cy = 0;
this.nodes.forEach(function (node) {
cx += node.plotX * node.mass;
cy += node.plotY * node.mass;
systemMass += node.mass;
});
this.barycenter = {
x: cx,
y: cy,
xFactor: cx / systemMass,
yFactor: cy / systemMass
};
return this.barycenter;
},
barnesHutApproximation: function (node, quadNode) {
var layout = this, distanceXY = layout.getDistXY(node, quadNode), distanceR = layout.vectorLength(distanceXY), goDeeper, force;
if (node !== quadNode && distanceR !== 0) {
if (quadNode.isInternal) {
// Internal node:
if (quadNode.boxSize / distanceR <
layout.options.theta &&
distanceR !== 0) {
// Treat as an external node:
force = layout.repulsiveForce(distanceR, layout.k);
layout.force('repulsive', node, force * quadNode.mass, distanceXY, distanceR);
goDeeper = false;
}
else {
// Go deeper:
goDeeper = true;
}
}
else {
// External node, direct force:
force = layout.repulsiveForce(distanceR, layout.k);
layout.force('repulsive', node, force * quadNode.mass, distanceXY, distanceR);
}
}
return goDeeper;
},
repulsiveForces: function () {
var layout = this;
if (layout.approximation === 'barnes-hut') {
layout.nodes.forEach(function (node) {
layout.quadTree.visitNodeRecursive(null, function (quadNode) {
return layout.barnesHutApproximation(node, quadNode);
});
});
}
else {
layout.nodes.forEach(function (node) {
layout.nodes.forEach(function (repNode) {
var force, distanceR, distanceXY;
if (
// Node can not repulse itself:
node !== repNode &&
// Only close nodes affect each other:
// layout.getDistR(node, repNode) < 2 * k &&
// Not dragged:
!node.fixedPosition) {
distanceXY = layout.getDistXY(node, repNode);
distanceR = layout.vectorLength(distanceXY);
if (distanceR !== 0) {
force = layout.repulsiveForce(distanceR, layout.k);
layout.force('repulsive', node, force * repNode.mass, distanceXY, distanceR);
}
}
});
});
}
},
attractiveForces: function () {
var layout = this, distanceXY, distanceR, force;
layout.links.forEach(function (link) {
if (link.fromNode && link.toNode) {
distanceXY = layout.getDistXY(link.fromNode, link.toNode);
distanceR = layout.vectorLength(distanceXY);
if (distanceR !== 0) {
force = layout.attractiveForce(distanceR, layout.k);
layout.force('attractive', link, force, distanceXY, distanceR);
}
}
});
},
applyLimits: function () {
var layout = this, nodes = layout.nodes;
nodes.forEach(function (node) {
if (node.fixedPosition) {
return;
}
layout.integration.integrate(layout, node);
layout.applyLimitBox(node, layout.box);
// Reset displacement:
node.dispX = 0;
node.dispY = 0;
});
},
/**
* External box that nodes should fall. When hitting an edge, node
* should stop or bounce.
* @private
*/
applyLimitBox: function (node, box) {
var radius = node.radius;
/*
TO DO: Consider elastic collision instead of stopping.
o' means end position when hitting plotting area edge:
- "inelastic":
o
\
______
| o'
| \
| \
- "elastic"/"bounced":
o
\
______
| ^
| / \
|o' \
Euler sample:
if (plotX < 0) {
plotX = 0;
dispX *= -1;
}
if (plotX > box.width) {
plotX = box.width;
dispX *= -1;
}
*/
// Limit X-coordinates:
node.plotX = clamp(node.plotX, box.left + radius, box.width - radius);
// Limit Y-coordinates:
node.plotY = clamp(node.plotY, box.top + radius, box.height - radius);
},
/**
* From "A comparison of simulated annealing cooling strategies" by
* Nourani and Andresen work.
* @private
*/
coolDown: function (temperature, temperatureStep, currentStep) {
// Logarithmic:
/*
return Math.sqrt(this.nodes.length) -
Math.log(
currentStep * layout.diffTemperature
);
*/
// Exponential:
/*
var alpha = 0.1;
layout.temperature = Math.sqrt(layout.nodes.length) *
Math.pow(alpha, layout.diffTemperature);
*/
// Linear:
return temperature - temperatureStep * currentStep;
},
isStable: function () {
return Math.abs(this.systemTemperature -
this.prevSystemTemperature) < 0.00001 || this.temperature <= 0;
},
getSystemTemperature: function () {
return this.nodes.reduce(function (value, node) {
return value + node.temperature;
}, 0);
},
vectorLength: function (vector) {
return Math.sqrt(vector.x * vector.x + vector.y * vector.y);
},
getDistR: function (nodeA, nodeB) {
var distance = this.getDistXY(nodeA, nodeB);
return this.vectorLength(distance);
},
getDistXY: function (nodeA, nodeB) {
var xDist = nodeA.plotX - nodeB.plotX, yDist = nodeA.plotY - nodeB.plotY;
return {
x: xDist,
y: yDist,
absX: Math.abs(xDist),
absY: Math.abs(yDist)
};
}
});
/* ************************************************************************** *
* Multiple series support:
* ************************************************************************** */
// Clear previous layouts
addEvent(Chart, 'predraw', function () {
if (this.graphLayoutsLookup) {
this.graphLayoutsLookup.forEach(function (layout) {
layout.stop();
});
}
});
addEvent(Chart, 'render', function () {
var systemsStable, afterRender = false;
/**
* @private
*/
function layoutStep(layout) {
if (layout.maxIterations-- &&
isFinite(layout.temperature) &&
!layout.isStable() &&
!layout.options.enableSimulation) {
// Hook similar to build-in addEvent, but instead of
// creating whole events logic, use just a function.
// It's faster which is important for rAF code.
// Used e.g. in packed-bubble series for bubble radius
// calculations
if (layout.beforeStep) {
layout.beforeStep();
}
layout.step();
systemsStable = false;
afterRender = true;
}
}
if (this.graphLayoutsLookup) {
setAnimation(false, this);
// Start simulation
this.graphLayoutsLookup.forEach(function (layout) {
layout.start();
});
// Just one sync step, to run different layouts similar to
// async mode.
while (!systemsStable) {
systemsStable = true;
this.graphLayoutsLookup.forEach(layoutStep);
}
if (afterRender) {
this.series.forEach(function (s) {
if (s && s.layout) {
s.render();
}
});
}
}
});

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,187 @@
/* *
*
* Plugin for displaying a message when there is no data visible in chart.
*
* (c) 2010-2020 Highsoft AS
*
* Author: Oystein Moseng
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../parts/Globals.js';
import U from '../parts/Utilities.js';
var addEvent = U.addEvent, extend = U.extend;
import '../parts/Series.js';
import '../parts/Options.js';
var chartPrototype = H.Chart.prototype, defaultOptions = H.getOptions();
// Add language option
extend(defaultOptions.lang,
/**
* @optionparent lang
*/
{
/**
* The text to display when the chart contains no data.
*
* @see [noData](#noData)
*
* @sample highcharts/no-data-to-display/no-data-line
* No-data text
*
* @since 3.0.8
* @product highcharts highstock
* @requires modules/no-data-to-display
*/
noData: 'No data to display'
});
// Add default display options for message
/**
* Options for displaying a message like "No data to display".
* This feature requires the file no-data-to-display.js to be loaded in the
* page. The actual text to display is set in the lang.noData option.
*
* @sample highcharts/no-data-to-display/no-data-line
* Line chart with no-data module
* @sample highcharts/no-data-to-display/no-data-pie
* Pie chart with no-data module
*
* @product highcharts highstock gantt
* @requires modules/no-data-to-display
* @optionparent noData
*/
defaultOptions.noData = {
/**
* An object of additional SVG attributes for the no-data label.
*
* @type {Highcharts.SVGAttributes}
* @since 3.0.8
* @product highcharts highstock gantt
* @apioption noData.attr
*/
attr: {
zIndex: 1
},
/**
* Whether to insert the label as HTML, or as pseudo-HTML rendered with
* SVG.
*
* @type {boolean}
* @default false
* @since 4.1.10
* @product highcharts highstock gantt
* @apioption noData.useHTML
*/
/**
* The position of the no-data label, relative to the plot area.
*
* @type {Highcharts.AlignObject}
* @since 3.0.8
*/
position: {
/**
* Horizontal offset of the label, in pixels.
*/
x: 0,
/**
* Vertical offset of the label, in pixels.
*/
y: 0,
/**
* Horizontal alignment of the label.
*
* @type {Highcharts.AlignValue}
*/
align: 'center',
/**
* Vertical alignment of the label.
*
* @type {Highcharts.VerticalAlignValue}
*/
verticalAlign: 'middle'
},
/**
* CSS styles for the no-data label.
*
* @sample highcharts/no-data-to-display/no-data-line
* Styled no-data text
*
* @type {Highcharts.CSSObject}
*/
style: {
/** @ignore */
fontWeight: 'bold',
/** @ignore */
fontSize: '12px',
/** @ignore */
color: '#666666'
}
};
/**
* Display a no-data message.
* @private
* @function Highcharts.Chart#showNoData
* @param {string} [str]
* An optional message to show in place of the default one
* @return {void}
* @requires modules/no-data-to-display
*/
chartPrototype.showNoData = function (str) {
var chart = this, options = chart.options, text = str || (options && options.lang.noData), noDataOptions = options && options.noData;
if (!chart.noDataLabel && chart.renderer) {
chart.noDataLabel = chart.renderer
.label(text, 0, 0, null, null, null, noDataOptions.useHTML, null, 'no-data');
if (!chart.styledMode) {
chart.noDataLabel
.attr(noDataOptions.attr)
.css(noDataOptions.style);
}
chart.noDataLabel.add();
chart.noDataLabel.align(extend(chart.noDataLabel.getBBox(), noDataOptions.position), false, 'plotBox');
}
};
/**
* Hide no-data message.
*
* @private
* @function Highcharts.Chart#hideNoData
* @return {void}
* @requires modules/no-data-to-display
*/
chartPrototype.hideNoData = function () {
var chart = this;
if (chart.noDataLabel) {
chart.noDataLabel = chart.noDataLabel.destroy();
}
};
/**
* Returns true if there are data points within the plot area now.
*
* @private
* @function Highcharts.Chart#hasData
* @return {boolean|undefined}
* True, if there are data points.
* @requires modules/no-data-to-display
*/
chartPrototype.hasData = function () {
var chart = this, series = chart.series || [], i = series.length;
while (i--) {
if (series[i].hasData() && !series[i].options.isInternal) {
return true;
}
}
return chart.loadingShown; // #4588
};
/* eslint-disable no-invalid-this */
// Add event listener to handle automatic show or hide no-data message.
addEvent(H.Chart, 'render', function handleNoData() {
if (this.hasData()) {
this.hideNoData();
}
else {
this.showNoData();
}
});

View File

@@ -0,0 +1,591 @@
/* *
*
* Client side exporting module
*
* (c) 2015 Torstein Honsi / Oystein Moseng
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
/* global MSBlobBuilder */
import Highcharts from '../parts/Globals.js';
import U from '../parts/Utilities.js';
var extend = U.extend;
import '../parts/Chart.js';
import '../parts/Options.js';
import '../mixins/download-url.js';
var addEvent = Highcharts.addEvent, merge = Highcharts.merge, win = Highcharts.win, nav = win.navigator, doc = win.document, domurl = win.URL || win.webkitURL || win, isMSBrowser = /Edge\/|Trident\/|MSIE /.test(nav.userAgent),
// Milliseconds to defer image load event handlers to offset IE bug
loadEventDeferDelay = isMSBrowser ? 150 : 0;
// Dummy object so we can reuse our canvas-tools.js without errors
Highcharts.CanVGRenderer = {};
/* eslint-disable valid-jsdoc */
/**
* Downloads a script and executes a callback when done.
*
* @private
* @function getScript
* @param {string} scriptLocation
* @param {Function} callback
* @return {void}
*/
function getScript(scriptLocation, callback) {
var head = doc.getElementsByTagName('head')[0], script = doc.createElement('script');
script.type = 'text/javascript';
script.src = scriptLocation;
script.onload = callback;
script.onerror = function () {
Highcharts.error('Error loading script ' + scriptLocation);
};
head.appendChild(script);
}
/**
* Get blob URL from SVG code. Falls back to normal data URI.
*
* @private
* @function Highcharts.svgToDataURL
* @param {string} svg
* @return {string}
*/
Highcharts.svgToDataUrl = function (svg) {
// Webkit and not chrome
var webKit = (nav.userAgent.indexOf('WebKit') > -1 &&
nav.userAgent.indexOf('Chrome') < 0);
try {
// Safari requires data URI since it doesn't allow navigation to blob
// URLs. Firefox has an issue with Blobs and internal references,
// leading to gradients not working using Blobs (#4550)
if (!webKit && nav.userAgent.toLowerCase().indexOf('firefox') < 0) {
return domurl.createObjectURL(new win.Blob([svg], {
type: 'image/svg+xml;charset-utf-16'
}));
}
}
catch (e) {
// Ignore
}
return 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg);
};
/**
* Get data:URL from image URL. Pass in callbacks to handle results.
*
* @private
* @function Highcharts.imageToDataUrl
*
* @param {string} imageURL
*
* @param {string} imageType
*
* @param {*} callbackArgs
* callbackArgs is used only by callbacks.
*
* @param {number} scale
*
* @param {Function} successCallback
* Receives four arguments: imageURL, imageType, callbackArgs, and scale.
*
* @param {Function} taintedCallback
* Receives four arguments: imageURL, imageType, callbackArgs, and scale.
*
* @param {Function} noCanvasSupportCallback
* Receives four arguments: imageURL, imageType, callbackArgs, and scale.
*
* @param {Function} failedLoadCallback
* Receives four arguments: imageURL, imageType, callbackArgs, and scale.
*
* @param {Function} [finallyCallback]
* finallyCallback is always called at the end of the process. All
* callbacks receive four arguments: imageURL, imageType, callbackArgs,
* and scale.
*
* @return {void}
*/
Highcharts.imageToDataUrl = function (imageURL, imageType, callbackArgs, scale, successCallback, taintedCallback, noCanvasSupportCallback, failedLoadCallback, finallyCallback) {
var img = new win.Image(), taintedHandler, loadHandler = function () {
setTimeout(function () {
var canvas = doc.createElement('canvas'), ctx = canvas.getContext && canvas.getContext('2d'), dataURL;
try {
if (!ctx) {
noCanvasSupportCallback(imageURL, imageType, callbackArgs, scale);
}
else {
canvas.height = img.height * scale;
canvas.width = img.width * scale;
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
// Now we try to get the contents of the canvas.
try {
dataURL = canvas.toDataURL(imageType);
successCallback(dataURL, imageType, callbackArgs, scale);
}
catch (e) {
taintedHandler(imageURL, imageType, callbackArgs, scale);
}
}
}
finally {
if (finallyCallback) {
finallyCallback(imageURL, imageType, callbackArgs, scale);
}
}
// IE bug where image is not always ready despite calling load
// event.
}, loadEventDeferDelay);
},
// Image load failed (e.g. invalid URL)
errorHandler = function () {
failedLoadCallback(imageURL, imageType, callbackArgs, scale);
if (finallyCallback) {
finallyCallback(imageURL, imageType, callbackArgs, scale);
}
};
// This is called on load if the image drawing to canvas failed with a
// security error. We retry the drawing with crossOrigin set to Anonymous.
taintedHandler = function () {
img = new win.Image();
taintedHandler = taintedCallback;
// Must be set prior to loading image source
img.crossOrigin = 'Anonymous';
img.onload = loadHandler;
img.onerror = errorHandler;
img.src = imageURL;
};
img.onload = loadHandler;
img.onerror = errorHandler;
img.src = imageURL;
};
/* eslint-enable valid-jsdoc */
/**
* Get data URL to an image of an SVG and call download on it options object:
*
* - **filename:** Name of resulting downloaded file without extension. Default
* is `chart`.
*
* - **type:** File type of resulting download. Default is `image/png`.
*
* - **scale:** Scaling factor of downloaded image compared to source. Default
* is `1`.
*
* - **libURL:** URL pointing to location of dependency scripts to download on
* demand. Default is the exporting.libURL option of the global Highcharts
* options pointing to our server.
*
* @function Highcharts.downloadSVGLocal
*
* @param {string} svg
* The generated SVG
*
* @param {Highcharts.ExportingOptions} options
* The exporting options
*
* @param {Function} failCallback
* The callback function in case of errors
*
* @param {Function} [successCallback]
* The callback function in case of success
*
* @return {void}
*/
Highcharts.downloadSVGLocal = function (svg, options, failCallback, successCallback) {
var svgurl, blob, objectURLRevoke = true, finallyHandler, libURL = (options.libURL || Highcharts.getOptions().exporting.libURL), dummySVGContainer = doc.createElement('div'), imageType = options.type || 'image/png', filename = ((options.filename || 'chart') +
'.' +
(imageType === 'image/svg+xml' ? 'svg' : imageType.split('/')[1])), scale = options.scale || 1;
// Allow libURL to end with or without fordward slash
libURL = libURL.slice(-1) !== '/' ? libURL + '/' : libURL;
/* eslint-disable valid-jsdoc */
/**
* @private
*/
function svgToPdf(svgElement, margin) {
var width = svgElement.width.baseVal.value + 2 * margin, height = svgElement.height.baseVal.value + 2 * margin, pdf = new win.jsPDF(// eslint-disable-line new-cap
'l', 'pt', [width, height]);
// Workaround for #7090, hidden elements were drawn anyway. It comes
// down to https://github.com/yWorks/svg2pdf.js/issues/28. Check this
// later.
[].forEach.call(svgElement.querySelectorAll('*[visibility="hidden"]'), function (node) {
node.parentNode.removeChild(node);
});
win.svg2pdf(svgElement, pdf, { removeInvalid: true });
return pdf.output('datauristring');
}
/**
* @private
* @return {void}
*/
function downloadPDF() {
dummySVGContainer.innerHTML = svg;
var textElements = dummySVGContainer.getElementsByTagName('text'), titleElements, svgData,
// Copy style property to element from parents if it's not there.
// Searches up hierarchy until it finds prop, or hits the chart
// container.
setStylePropertyFromParents = function (el, propName) {
var curParent = el;
while (curParent && curParent !== dummySVGContainer) {
if (curParent.style[propName]) {
el.style[propName] =
curParent.style[propName];
break;
}
curParent = curParent.parentNode;
}
};
// Workaround for the text styling. Making sure it does pick up settings
// for parent elements.
[].forEach.call(textElements, function (el) {
// Workaround for the text styling. making sure it does pick up the
// root element
['font-family', 'font-size'].forEach(function (property) {
setStylePropertyFromParents(el, property);
});
el.style['font-family'] = (el.style['font-family'] &&
el.style['font-family'].split(' ').splice(-1));
// Workaround for plotband with width, removing title from text
// nodes
titleElements = el.getElementsByTagName('title');
[].forEach.call(titleElements, function (titleElement) {
el.removeChild(titleElement);
});
});
svgData = svgToPdf(dummySVGContainer.firstChild, 0);
try {
Highcharts.downloadURL(svgData, filename);
if (successCallback) {
successCallback();
}
}
catch (e) {
failCallback(e);
}
}
/* eslint-enable valid-jsdoc */
// Initiate download depending on file type
if (imageType === 'image/svg+xml') {
// SVG download. In this case, we want to use Microsoft specific Blob if
// available
try {
if (typeof nav.msSaveOrOpenBlob !== 'undefined') {
blob = new MSBlobBuilder();
blob.append(svg);
svgurl = blob.getBlob('image/svg+xml');
}
else {
svgurl = Highcharts.svgToDataUrl(svg);
}
Highcharts.downloadURL(svgurl, filename);
if (successCallback) {
successCallback();
}
}
catch (e) {
failCallback(e);
}
}
else if (imageType === 'application/pdf') {
if (win.jsPDF && win.svg2pdf) {
downloadPDF();
}
else {
// Must load pdf libraries first. // Don't destroy the object URL
// yet since we are doing things asynchronously. A cleaner solution
// would be nice, but this will do for now.
objectURLRevoke = true;
getScript(libURL + 'jspdf.js', function () {
getScript(libURL + 'svg2pdf.js', function () {
downloadPDF();
});
});
}
}
else {
// PNG/JPEG download - create bitmap from SVG
svgurl = Highcharts.svgToDataUrl(svg);
finallyHandler = function () {
try {
domurl.revokeObjectURL(svgurl);
}
catch (e) {
// Ignore
}
};
// First, try to get PNG by rendering on canvas
Highcharts.imageToDataUrl(svgurl, imageType, {}, scale, function (imageURL) {
// Success
try {
Highcharts.downloadURL(imageURL, filename);
if (successCallback) {
successCallback();
}
}
catch (e) {
failCallback(e);
}
}, function () {
// Failed due to tainted canvas
// Create new and untainted canvas
var canvas = doc.createElement('canvas'), ctx = canvas.getContext('2d'), imageWidth = svg.match(/^<svg[^>]*width\s*=\s*\"?(\d+)\"?[^>]*>/)[1] * scale, imageHeight = svg.match(/^<svg[^>]*height\s*=\s*\"?(\d+)\"?[^>]*>/)[1] * scale, downloadWithCanVG = function () {
ctx.drawSvg(svg, 0, 0, imageWidth, imageHeight);
try {
Highcharts.downloadURL(nav.msSaveOrOpenBlob ?
canvas.msToBlob() :
canvas.toDataURL(imageType), filename);
if (successCallback) {
successCallback();
}
}
catch (e) {
failCallback(e);
}
finally {
finallyHandler();
}
};
canvas.width = imageWidth;
canvas.height = imageHeight;
if (win.canvg) {
// Use preloaded canvg
downloadWithCanVG();
}
else {
// Must load canVG first. // Don't destroy the object URL
// yet since we are doing things asynchronously. A cleaner
// solution would be nice, but this will do for now.
objectURLRevoke = true;
// Get RGBColor.js first, then canvg
getScript(libURL + 'rgbcolor.js', function () {
getScript(libURL + 'canvg.js', function () {
downloadWithCanVG();
});
});
}
},
// No canvas support
failCallback,
// Failed to load image
failCallback,
// Finally
function () {
if (objectURLRevoke) {
finallyHandler();
}
});
}
};
/* eslint-disable valid-jsdoc */
/**
* Get SVG of chart prepared for client side export. This converts embedded
* images in the SVG to data URIs. It requires the regular exporting module. The
* options and chartOptions arguments are passed to the getSVGForExport
* function.
*
* @private
* @function Highcharts.Chart#getSVGForLocalExport
* @param {Highcharts.ExportingOptions} options
* @param {Highcharts.Options} chartOptions
* @param {Function} failCallback
* @param {Function} successCallback
* @return {void}
*/
Highcharts.Chart.prototype.getSVGForLocalExport = function (options, chartOptions, failCallback, successCallback) {
var chart = this, images, imagesEmbedded = 0, chartCopyContainer, chartCopyOptions, el, i, l, href,
// After grabbing the SVG of the chart's copy container we need to do
// sanitation on the SVG
sanitize = function (svg) {
return chart.sanitizeSVG(svg, chartCopyOptions);
},
// When done with last image we have our SVG
checkDone = function () {
if (imagesEmbedded === images.length) {
successCallback(sanitize(chartCopyContainer.innerHTML));
}
},
// Success handler, we converted image to base64!
embeddedSuccess = function (imageURL, imageType, callbackArgs) {
++imagesEmbedded;
// Change image href in chart copy
callbackArgs.imageElement.setAttributeNS('http://www.w3.org/1999/xlink', 'href', imageURL);
checkDone();
};
// Hook into getSVG to get a copy of the chart copy's container (#8273)
chart.unbindGetSVG = addEvent(chart, 'getSVG', function (e) {
chartCopyOptions = e.chartCopy.options;
chartCopyContainer = e.chartCopy.container.cloneNode(true);
});
// Trigger hook to get chart copy
chart.getSVGForExport(options, chartOptions);
images = chartCopyContainer.getElementsByTagName('image');
try {
// If there are no images to embed, the SVG is okay now.
if (!images.length) {
// Use SVG of chart copy
successCallback(sanitize(chartCopyContainer.innerHTML));
return;
}
// Go through the images we want to embed
for (i = 0, l = images.length; i < l; ++i) {
el = images[i];
href = el.getAttributeNS('http://www.w3.org/1999/xlink', 'href');
if (href) {
Highcharts.imageToDataUrl(href, 'image/png', { imageElement: el }, options.scale, embeddedSuccess,
// Tainted canvas
failCallback,
// No canvas support
failCallback,
// Failed to load source
failCallback);
// Hidden, boosted series have blank href (#10243)
}
else {
++imagesEmbedded;
el.parentNode.removeChild(el);
checkDone();
}
}
}
catch (e) {
failCallback(e);
}
// Clean up
chart.unbindGetSVG();
};
/* eslint-enable valid-jsdoc */
/**
* Exporting and offline-exporting modules required. Export a chart to an image
* locally in the user's browser.
*
* @function Highcharts.Chart#exportChartLocal
*
* @param {Highcharts.ExportingOptions} [exportingOptions]
* Exporting options, the same as in
* {@link Highcharts.Chart#exportChart}.
*
* @param {Highcharts.Options} [chartOptions]
* Additional chart options for the exported chart. For example a
* different background color can be added here, or `dataLabels`
* for export only.
*
* @return {void}
*
* @requires modules/exporting
*/
Highcharts.Chart.prototype.exportChartLocal = function (exportingOptions, chartOptions) {
var chart = this, options = Highcharts.merge(chart.options.exporting, exportingOptions), fallbackToExportServer = function (err) {
if (options.fallbackToExportServer === false) {
if (options.error) {
options.error(options, err);
}
else {
Highcharts.error(28, true); // Fallback disabled
}
}
else {
chart.exportChart(options);
}
}, svgSuccess = function (svg) {
// If SVG contains foreignObjects all exports except SVG will fail,
// as both CanVG and svg2pdf choke on this. Gracefully fall back.
if (svg.indexOf('<foreignObject') > -1 &&
options.type !== 'image/svg+xml') {
fallbackToExportServer('Image type not supported' +
'for charts with embedded HTML');
}
else {
Highcharts.downloadSVGLocal(svg, extend({ filename: chart.getFilename() }, options), fallbackToExportServer);
}
},
// Return true if the SVG contains images with external data. With the
// boost module there are `image` elements with encoded PNGs, these are
// supported by svg2pdf and should pass (#10243).
hasExternalImages = function () {
return [].some.call(chart.container.getElementsByTagName('image'), function (image) {
var href = image.getAttribute('href');
return href !== '' && href.indexOf('data:') !== 0;
});
};
// If we are on IE and in styled mode, add a whitelist to the renderer for
// inline styles that we want to pass through. There are so many styles by
// default in IE that we don't want to blacklist them all.
if (isMSBrowser && chart.styledMode) {
Highcharts.SVGRenderer.prototype.inlineWhitelist = [
/^blockSize/,
/^border/,
/^caretColor/,
/^color/,
/^columnRule/,
/^columnRuleColor/,
/^cssFloat/,
/^cursor/,
/^fill$/,
/^fillOpacity/,
/^font/,
/^inlineSize/,
/^length/,
/^lineHeight/,
/^opacity/,
/^outline/,
/^parentRule/,
/^rx$/,
/^ry$/,
/^stroke/,
/^textAlign/,
/^textAnchor/,
/^textDecoration/,
/^transform/,
/^vectorEffect/,
/^visibility/,
/^x$/,
/^y$/
];
}
// Always fall back on:
// - MS browsers: Embedded images JPEG/PNG, or any PDF
// - Embedded images and PDF
if ((isMSBrowser &&
(options.type === 'application/pdf' ||
chart.container.getElementsByTagName('image').length &&
options.type !== 'image/svg+xml')) || (options.type === 'application/pdf' &&
hasExternalImages())) {
fallbackToExportServer('Image type not supported for this chart/browser.');
return;
}
chart.getSVGForLocalExport(options, chartOptions, fallbackToExportServer, svgSuccess);
};
// Extend the default options to use the local exporter logic
merge(true, Highcharts.getOptions().exporting, {
libURL: 'https://code.highcharts.com/8.0.4/lib/',
// When offline-exporting is loaded, redefine the menu item definitions
// related to download.
menuItemDefinitions: {
downloadPNG: {
textKey: 'downloadPNG',
onclick: function () {
this.exportChartLocal();
}
},
downloadJPEG: {
textKey: 'downloadJPEG',
onclick: function () {
this.exportChartLocal({
type: 'image/jpeg'
});
}
},
downloadSVG: {
textKey: 'downloadSVG',
onclick: function () {
this.exportChartLocal({
type: 'image/svg+xml'
});
}
},
downloadPDF: {
textKey: 'downloadPDF',
onclick: function () {
this.exportChartLocal({
type: 'application/pdf'
});
}
}
}
});

View File

@@ -0,0 +1,144 @@
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* Simple polyfills for array functions in old IE browsers (6, 7 and 8) in
* Highcharts v7+. These polyfills are sufficient for Highcharts to work, but
* for fully compatible polyfills, see MDN.
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
/* global document */
'use strict';
/* eslint-disable no-extend-native */
if (!Array.prototype.forEach) {
Array.prototype.forEach = function (fn, thisArg) {
var i = 0, len = this.length;
for (; i < len; i++) {
if (typeof this[i] !== 'undefined' && // added check
fn.call(thisArg, this[i], i, this) === false) {
return i;
}
}
};
}
if (!Array.prototype.map) {
Array.prototype.map = function (fn
// @todo support optional ctx
) {
var results = [], i = 0, len = this.length;
for (; i < len; i++) {
results[i] = fn.call(this[i], this[i], i, this);
}
return results;
};
}
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (member, fromIndex) {
var arr = this, // #8874
len, i = fromIndex || 0; // #8346
if (arr) {
len = arr.length;
for (; i < len; i++) {
if (arr[i] === member) {
return i;
}
}
}
return -1;
};
}
if (!Array.prototype.filter) {
Array.prototype.filter = function (fn
// @todo support optional ctx
) {
var ret = [], i = 0, length = this.length;
for (; i < length; i++) {
if (fn(this[i], i)) {
ret.push(this[i]);
}
}
return ret;
};
}
if (!Array.prototype.some) {
Array.prototype.some = function (fn, thisArg) {
var i = 0, len = this.length;
for (; i < len; i++) {
if (fn.call(thisArg, this[i], i, this) === true) {
return true;
}
}
return false;
};
}
if (!Array.prototype.reduce) {
Array.prototype.reduce = function (func, initialValue) {
var context = this, i = arguments.length > 1 ? 0 : 1, accumulator = arguments.length > 1 ? initialValue : this[0], len = this.length;
for (; i < len; ++i) {
accumulator = func.call(context, accumulator, this[i], i, this);
}
return accumulator;
};
}
if (!Function.prototype.bind) {
Function.prototype.bind = function () {
var thatFunc = this;
var thatArg = arguments[0];
var args = Array.prototype.slice.call(arguments, 1);
if (typeof thatFunc !== 'function') {
// closest thing possible to the ECMAScript 5
// internal IsCallable function
throw new TypeError('Function.prototype.bind - ' +
'what is trying to be bound is not callable');
}
return function () {
var funcArgs = args.concat(Array.prototype.slice.call(arguments));
return thatFunc.apply(thatArg, funcArgs);
};
};
}
if (!Object.keys) {
Object.keys = function (obj) {
var result = [], prop;
for (prop in obj) {
if (Object.hasOwnProperty.call(obj, prop)) {
result.push(prop);
}
}
return result;
};
}
// Add a getElementsByClassName function if the browser doesn't have one
// Limitation: only works with one class name
// Copyright: Eike Send https://eike.se/nd
// License: MIT License
if (!document.getElementsByClassName) {
document.getElementsByClassName = function (search) {
var d = document, elements, pattern, i, results = [];
if (d.querySelectorAll) { // IE8
return d.querySelectorAll('.' + search);
}
if (d.evaluate) { // IE6, IE7
pattern = './/*[contains(concat(\' \', @class, \' \'), \' ' +
search + ' \')]';
elements = d.evaluate(pattern, d, null, 0, null);
while ((i = elements.iterateNext())) {
results.push(i);
}
}
else {
elements = d.getElementsByTagName('*');
pattern = new RegExp('(^|\\s)' + search + '(\\s|$)');
for (i = 0; i < elements.length; i++) {
if (pattern.test(elements[i].className)) {
results.push(elements[i]);
}
}
}
return results;
};
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,491 @@
/* *
*
* Organization chart module
*
* (c) 2018-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../parts/Globals.js';
import U from '../parts/Utilities.js';
var css = U.css, pick = U.pick, seriesType = U.seriesType, wrap = U.wrap;
/**
* Layout value for the child nodes in an organization chart. If `hanging`, this
* node's children will hang below their parent, allowing a tighter packing of
* nodes in the diagram.
*
* @typedef {"normal"|"hanging"} Highcharts.SeriesOrganizationNodesLayoutValue
*/
var base = H.seriesTypes.sankey.prototype;
/**
* @private
* @class
* @name Highcharts.seriesTypes.organization
*
* @augments Highcharts.seriesTypes.sankey
*/
seriesType('organization', 'sankey',
/**
* An organization chart is a diagram that shows the structure of an
* organization and the relationships and relative ranks of its parts and
* positions.
*
* @sample highcharts/demo/organization-chart/
* Organization chart
* @sample highcharts/series-organization/horizontal/
* Horizontal organization chart
* @sample highcharts/series-organization/borderless
* Borderless design
* @sample highcharts/series-organization/center-layout
* Centered layout
*
* @extends plotOptions.sankey
* @excluding allowPointSelect, curveFactor, dataSorting
* @since 7.1.0
* @product highcharts
* @requires modules/organization
* @optionparent plotOptions.organization
*/
{
/**
* The border color of the node cards.
*
* @type {Highcharts.ColorString}
* @private
*/
borderColor: '#666666',
/**
* The border radius of the node cards.
*
* @private
*/
borderRadius: 3,
/**
* Radius for the rounded corners of the links between nodes.
*
* @sample highcharts/series-organization/link-options
* Square links
*
* @private
*/
linkRadius: 10,
borderWidth: 1,
/**
* @declare Highcharts.SeriesOrganizationDataLabelsOptionsObject
*
* @private
*/
dataLabels: {
/* eslint-disable valid-jsdoc */
/**
* A callback for defining the format for _nodes_ in the
* organization chart. The `nodeFormat` option takes precedence
* over `nodeFormatter`.
*
* In an organization chart, the `nodeFormatter` is a quite complex
* function of the available options, striving for a good default
* layout of cards with or without images. In organization chart,
* the data labels come with `useHTML` set to true, meaning they
* will be rendered as true HTML above the SVG.
*
* @sample highcharts/series-organization/datalabels-nodeformatter
* Modify the default label format output
*
* @type {Highcharts.SeriesSankeyDataLabelsFormatterCallbackFunction}
* @since 6.0.2
*/
nodeFormatter: function () {
var outerStyle = {
width: '100%',
height: '100%',
display: 'flex',
'flex-direction': 'row',
'align-items': 'center',
'justify-content': 'center'
}, imageStyle = {
'max-height': '100%',
'border-radius': '50%'
}, innerStyle = {
width: '100%',
padding: 0,
'text-align': 'center',
'white-space': 'normal'
}, nameStyle = {
margin: 0
}, titleStyle = {
margin: 0
}, descriptionStyle = {
opacity: 0.75,
margin: '5px'
};
// eslint-disable-next-line valid-jsdoc
/**
* @private
*/
function styleAttr(style) {
return Object.keys(style).reduce(function (str, key) {
return str + key + ':' + style[key] + ';';
}, 'style="') + '"';
}
if (this.point.image) {
imageStyle['max-width'] = '30%';
innerStyle.width = '70%';
}
// PhantomJS doesn't support flex, roll back to absolute
// positioning
if (this.series.chart.renderer.forExport) {
outerStyle.display = 'block';
innerStyle.position = 'absolute';
innerStyle.left = this.point.image ? '30%' : 0;
innerStyle.top = 0;
}
var html = '<div ' + styleAttr(outerStyle) + '>';
if (this.point.image) {
html += '<img src="' + this.point.image + '" ' +
styleAttr(imageStyle) + '>';
}
html += '<div ' + styleAttr(innerStyle) + '>';
if (this.point.name) {
html += '<h4 ' + styleAttr(nameStyle) + '>' +
this.point.name + '</h4>';
}
if (this.point.title) {
html += '<p ' + styleAttr(titleStyle) + '>' +
(this.point.title || '') + '</p>';
}
if (this.point.description) {
html += '<p ' + styleAttr(descriptionStyle) + '>' +
this.point.description + '</p>';
}
html += '</div>' +
'</div>';
return html;
},
/* eslint-enable valid-jsdoc */
style: {
/** @internal */
fontWeight: 'normal',
/** @internal */
fontSize: '13px'
},
useHTML: true
},
/**
* The indentation in pixels of hanging nodes, nodes which parent has
* [layout](#series.organization.nodes.layout) set to `hanging`.
*
* @private
*/
hangingIndent: 20,
/**
* The color of the links between nodes.
*
* @type {Highcharts.ColorString}
* @private
*/
linkColor: '#666666',
/**
* The line width of the links connecting nodes, in pixels.
*
* @sample highcharts/series-organization/link-options
* Square links
*
* @private
*/
linkLineWidth: 1,
/**
* In a horizontal chart, the width of the nodes in pixels. Node that
* most organization charts are vertical, so the name of this option
* is counterintuitive.
*
* @private
*/
nodeWidth: 50,
tooltip: {
nodeFormat: '{point.name}<br>{point.title}<br>{point.description}'
}
}, {
pointAttribs: function (point, state) {
var series = this, attribs = base.pointAttribs.call(series, point, state), level = point.isNode ? point.level : point.fromNode.level, levelOptions = series.mapOptionsToLevel[level || 0] || {}, options = point.options, stateOptions = (levelOptions.states && levelOptions.states[state]) || {}, values = ['borderRadius', 'linkColor', 'linkLineWidth']
.reduce(function (obj, key) {
obj[key] = pick(stateOptions[key], options[key], levelOptions[key], series.options[key]);
return obj;
}, {});
if (!point.isNode) {
attribs.stroke = values.linkColor;
attribs['stroke-width'] = values.linkLineWidth;
delete attribs.fill;
}
else {
if (values.borderRadius) {
attribs.r = values.borderRadius;
}
}
return attribs;
},
createNode: function (id) {
var node = base.createNode
.call(this, id);
// All nodes in an org chart are equal width
node.getSum = function () {
return 1;
};
return node;
},
createNodeColumn: function () {
var column = base.createNodeColumn.call(this);
// Wrap the offset function so that the hanging node's children are
// aligned to their parent
wrap(column, 'offset', function (proceed, node, factor) {
var offset = proceed.call(this, node, factor); // eslint-disable-line no-invalid-this
// Modify the default output if the parent's layout is 'hanging'
if (node.hangsFrom) {
return {
absoluteTop: node.hangsFrom.nodeY
};
}
return offset;
});
return column;
},
translateNode: function (node, column) {
base.translateNode.call(this, node, column);
if (node.hangsFrom) {
node.shapeArgs.height -=
this.options.hangingIndent;
if (!this.chart.inverted) {
node.shapeArgs.y += this.options.hangingIndent;
}
}
node.nodeHeight = this.chart.inverted ?
node.shapeArgs.width :
node.shapeArgs.height;
},
// General function to apply corner radius to a path - can be lifted to
// renderer or utilities if we need it elsewhere.
curvedPath: function (path, r) {
var d = [], i, x, y, x1, x2, y1, y2, directionX, directionY;
for (i = 0; i < path.length; i++) {
x = path[i][0];
y = path[i][1];
// moveTo
if (i === 0) {
d.push('M', x, y);
}
else if (i === path.length - 1) {
d.push('L', x, y);
// curveTo
}
else if (r) {
x1 = path[i - 1][0];
y1 = path[i - 1][1];
x2 = path[i + 1][0];
y2 = path[i + 1][1];
// Only apply to breaks
if (x1 !== x2 && y1 !== y2) {
directionX = x1 < x2 ? 1 : -1;
directionY = y1 < y2 ? 1 : -1;
d.push('L', x - directionX * Math.min(Math.abs(x - x1), r), y - directionY * Math.min(Math.abs(y - y1), r), 'C', x, y, x, y, x + directionX * Math.min(Math.abs(x - x2), r), y + directionY * Math.min(Math.abs(y - y2), r));
}
// lineTo
}
else {
d.push('L', x, y);
}
}
return d;
},
translateLink: function (point) {
var fromNode = point.fromNode, toNode = point.toNode, crisp = Math.round(this.options.linkLineWidth) % 2 / 2, x1 = Math.floor(fromNode.shapeArgs.x +
fromNode.shapeArgs.width) + crisp, y1 = Math.floor(fromNode.shapeArgs.y +
fromNode.shapeArgs.height / 2) + crisp, x2 = Math.floor(toNode.shapeArgs.x) + crisp, y2 = Math.floor(toNode.shapeArgs.y +
toNode.shapeArgs.height / 2) + crisp, xMiddle, hangingIndent = this.options.hangingIndent, toOffset = toNode.options.offset, percentOffset = /%$/.test(toOffset) && parseInt(toOffset, 10), inverted = this.chart.inverted;
if (inverted) {
x1 -= fromNode.shapeArgs.width;
x2 += toNode.shapeArgs.width;
}
xMiddle = Math.floor(x2 +
(inverted ? 1 : -1) *
(this.colDistance - this.nodeWidth) / 2) + crisp;
// Put the link on the side of the node when an offset is given. HR
// node in the main demo.
if (percentOffset &&
(percentOffset >= 50 || percentOffset <= -50)) {
xMiddle = x2 = Math.floor(x2 + (inverted ? -0.5 : 0.5) *
toNode.shapeArgs.width) + crisp;
y2 = toNode.shapeArgs.y;
if (percentOffset > 0) {
y2 += toNode.shapeArgs.height;
}
}
if (toNode.hangsFrom === fromNode) {
if (this.chart.inverted) {
y1 = Math.floor(fromNode.shapeArgs.y +
fromNode.shapeArgs.height -
hangingIndent / 2) + crisp;
y2 = (toNode.shapeArgs.y +
toNode.shapeArgs.height);
}
else {
y1 = Math.floor(fromNode.shapeArgs.y +
hangingIndent / 2) + crisp;
}
xMiddle = x2 = Math.floor(toNode.shapeArgs.x +
toNode.shapeArgs.width / 2) + crisp;
}
point.plotY = 1;
point.shapeType = 'path';
point.shapeArgs = {
d: this.curvedPath([
[x1, y1],
[xMiddle, y1],
[xMiddle, y2],
[x2, y2]
], this.options.linkRadius)
};
},
alignDataLabel: function (point, dataLabel, options) {
// Align the data label to the point graphic
if (options.useHTML) {
var width = point.shapeArgs.width, height = point.shapeArgs.height, padjust = (this.options.borderWidth +
2 * this.options.dataLabels.padding);
if (this.chart.inverted) {
width = height;
height = point.shapeArgs.width;
}
height -= padjust;
width -= padjust;
// Set the size of the surrounding div emulating `g`
css(dataLabel.text.element.parentNode, {
width: width + 'px',
height: height + 'px'
});
// Set properties for the span emulating `text`
css(dataLabel.text.element, {
left: 0,
top: 0,
width: '100%',
height: '100%',
overflow: 'hidden'
});
// The getBBox function is used in `alignDataLabel` to align
// inside the box
dataLabel.getBBox = function () {
return {
width: width,
height: height
};
};
}
H.seriesTypes.column.prototype.alignDataLabel.apply(this, arguments);
}
});
/**
* An `organization` series. If the [type](#series.organization.type) option is
* not specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.organization
* @exclude dataSorting
* @product highcharts
* @requires modules/organization
* @apioption series.organization
*/
/**
* @type {Highcharts.SeriesOrganizationDataLabelsOptionsObject|Array<Highcharts.SeriesOrganizationDataLabelsOptionsObject>}
* @product highcharts
* @apioption series.organization.data.dataLabels
*/
/**
* A collection of options for the individual nodes. The nodes in an org chart
* are auto-generated instances of `Highcharts.Point`, but options can be
* applied here and linked by the `id`.
*
* @extends series.sankey.nodes
* @type {Array<*>}
* @product highcharts
* @apioption series.organization.nodes
*/
/**
* Individual data label for each node. The options are the same as
* the ones for [series.organization.dataLabels](#series.organization.dataLabels).
*
* @type {Highcharts.SeriesOrganizationDataLabelsOptionsObject|Array<Highcharts.SeriesOrganizationDataLabelsOptionsObject>}
*
* @apioption series.organization.nodes.dataLabels
*/
/**
* The job description for the node card, will be inserted by the default
* `dataLabel.nodeFormatter`.
*
* @sample highcharts/demo/organization-chart
* Org chart with job descriptions
*
* @type {string}
* @product highcharts
* @apioption series.organization.nodes.description
*/
/**
* An image for the node card, will be inserted by the default
* `dataLabel.nodeFormatter`.
*
* @sample highcharts/demo/organization-chart
* Org chart with images
*
* @type {string}
* @product highcharts
* @apioption series.organization.nodes.image
*/
/**
* Layout for the node's children. If `hanging`, this node's children will hang
* below their parent, allowing a tighter packing of nodes in the diagram.
*
* @sample highcharts/demo/organization-chart
* Hanging layout
*
* @type {Highcharts.SeriesOrganizationNodesLayoutValue}
* @default normal
* @product highcharts
* @apioption series.organization.nodes.layout
*/
/**
* The job title for the node card, will be inserted by the default
* `dataLabel.nodeFormatter`.
*
* @sample highcharts/demo/organization-chart
* Org chart with job titles
*
* @type {string}
* @product highcharts
* @apioption series.organization.nodes.title
*/
/**
* An array of data points for the series. For the `organization` series
* type, points can be given in the following way:
*
* An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of data
* points exceeds the series' [turboThreshold](#series.area.turboThreshold),
* this option is not available.
*
* ```js
* data: [{
* from: 'Category1',
* to: 'Category2',
* weight: 2
* }, {
* from: 'Category1',
* to: 'Category3',
* weight: 5
* }]
* ```
*
* @type {Array<*>}
* @extends series.sankey.data
* @product highcharts
* @apioption series.organization.data
*/
''; // adds doclets above to transpiled file

View File

@@ -0,0 +1,180 @@
/* *
*
* Highcharts module to hide overlapping data labels.
* This module is included in Highcharts.
*
* (c) 2009-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../parts/Globals.js';
import U from '../parts/Utilities.js';
var addEvent = U.addEvent, fireEvent = U.fireEvent, isArray = U.isArray, objectEach = U.objectEach, pick = U.pick;
import '../parts/Chart.js';
var Chart = H.Chart;
/* eslint-disable no-invalid-this */
// Collect potensial overlapping data labels. Stack labels probably don't need
// to be considered because they are usually accompanied by data labels that lie
// inside the columns.
addEvent(Chart, 'render', function collectAndHide() {
var labels = [];
// Consider external label collectors
(this.labelCollectors || []).forEach(function (collector) {
labels = labels.concat(collector());
});
(this.yAxis || []).forEach(function (yAxis) {
if (yAxis.options.stackLabels &&
!yAxis.options.stackLabels.allowOverlap) {
objectEach(yAxis.stacks, function (stack) {
objectEach(stack, function (stackItem) {
labels.push(stackItem.label);
});
});
}
});
(this.series || []).forEach(function (series) {
var dlOptions = series.options.dataLabels;
if (series.visible &&
!(dlOptions.enabled === false && !series._hasPointLabels)) { // #3866
(series.nodes || series.points).forEach(function (point) {
if (point.visible) {
var dataLabels = (isArray(point.dataLabels) ?
point.dataLabels :
(point.dataLabel ? [point.dataLabel] : []));
dataLabels.forEach(function (label) {
var options = label.options;
label.labelrank = pick(options.labelrank, point.labelrank, point.shapeArgs && point.shapeArgs.height); // #4118
if (!options.allowOverlap) {
labels.push(label);
}
});
}
});
}
});
this.hideOverlappingLabels(labels);
});
/**
* Hide overlapping labels. Labels are moved and faded in and out on zoom to
* provide a smooth visual imression.
*
* @private
* @function Highcharts.Chart#hideOverlappingLabels
* @param {Array<Highcharts.SVGElement>} labels
* Rendered data labels
* @return {void}
* @requires modules/overlapping-datalabels
*/
Chart.prototype.hideOverlappingLabels = function (labels) {
var chart = this, len = labels.length, ren = chart.renderer, label, i, j, label1, label2, box1, box2, isLabelAffected = false, isIntersectRect = function (box1, box2) {
return !(box2.x > box1.x + box1.width ||
box2.x + box2.width < box1.x ||
box2.y > box1.y + box1.height ||
box2.y + box2.height < box1.y);
},
// Get the box with its position inside the chart, as opposed to getBBox
// that only reports the position relative to the parent.
getAbsoluteBox = function (label) {
var pos, parent, bBox,
// Substract the padding if no background or border (#4333)
padding = label.box ? 0 : (label.padding || 0), lineHeightCorrection = 0;
if (label &&
(!label.alignAttr || label.placed)) {
pos = label.alignAttr || {
x: label.attr('x'),
y: label.attr('y')
};
parent = label.parentGroup;
// Get width and height if pure text nodes (stack labels)
if (!label.width) {
bBox = label.getBBox();
label.width = bBox.width;
label.height = bBox.height;
// Labels positions are computed from top left corner, so
// we need to substract the text height from text nodes too.
lineHeightCorrection = ren
.fontMetrics(null, label.element).h;
}
return {
x: pos.x + (parent.translateX || 0) + padding,
y: pos.y + (parent.translateY || 0) + padding -
lineHeightCorrection,
width: label.width - 2 * padding,
height: label.height - 2 * padding
};
}
};
for (i = 0; i < len; i++) {
label = labels[i];
if (label) {
// Mark with initial opacity
label.oldOpacity = label.opacity;
label.newOpacity = 1;
label.absoluteBox = getAbsoluteBox(label);
}
}
// Prevent a situation in a gradually rising slope, that each label will
// hide the previous one because the previous one always has lower rank.
labels.sort(function (a, b) {
return (b.labelrank || 0) - (a.labelrank || 0);
});
// Detect overlapping labels
for (i = 0; i < len; i++) {
label1 = labels[i];
box1 = label1 && label1.absoluteBox;
for (j = i + 1; j < len; ++j) {
label2 = labels[j];
box2 = label2 && label2.absoluteBox;
if (box1 &&
box2 &&
label1 !== label2 && // #6465, polar chart with connectEnds
label1.newOpacity !== 0 &&
label2.newOpacity !== 0) {
if (isIntersectRect(box1, box2)) {
(label1.labelrank < label2.labelrank ? label1 : label2)
.newOpacity = 0;
}
}
}
}
// Hide or show
labels.forEach(function (label) {
var complete, newOpacity;
if (label) {
newOpacity = label.newOpacity;
if (label.oldOpacity !== newOpacity) {
// Make sure the label is completely hidden to avoid catching
// clicks (#4362)
if (label.alignAttr && label.placed) { // data labels
if (newOpacity) {
label.show(true);
}
else {
complete = function () {
label.hide(true);
label.placed = false; // avoid animation from top
};
}
isLabelAffected = true;
// Animate or set the opacity
label.alignAttr.opacity = newOpacity;
label[label.isOld ? 'animate' : 'attr'](label.alignAttr, null, complete);
fireEvent(chart, 'afterHideOverlappingLabel');
}
else { // other labels, tick labels
label.attr({
opacity: newOpacity
});
}
}
label.isOld = true;
}
});
if (isLabelAffected) {
fireEvent(chart, 'afterHideAllOverlappingLabels');
}
};

View File

@@ -0,0 +1,395 @@
/* *
*
* Parallel coordinates module
*
* (c) 2010-2020 Pawel Fus
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../parts/Globals.js';
import U from '../parts/Utilities.js';
var addEvent = U.addEvent, arrayMax = U.arrayMax, arrayMin = U.arrayMin, defined = U.defined, erase = U.erase, extend = U.extend, format = U.format, merge = U.merge, pick = U.pick, splat = U.splat, wrap = U.wrap;
import '../parts/Axis.js';
import '../parts/Chart.js';
import '../parts/Series.js';
// Extensions for parallel coordinates plot.
var Axis = H.Axis, Chart = H.Chart, ChartProto = Chart.prototype, AxisProto = H.Axis.prototype;
var defaultXAxisOptions = {
lineWidth: 0,
tickLength: 0,
opposite: true,
type: 'category'
};
/**
* @optionparent chart
*/
var defaultParallelOptions = {
/**
* Flag to render charts as a parallel coordinates plot. In a parallel
* coordinates plot (||-coords) by default all required yAxes are generated
* and the legend is disabled. This feature requires
* `modules/parallel-coordinates.js`.
*
* @sample {highcharts} /highcharts/demo/parallel-coordinates/
* Parallel coordinates demo
* @sample {highcharts} highcharts/parallel-coordinates/polar/
* Star plot, multivariate data in a polar chart
*
* @since 6.0.0
* @product highcharts
* @requires modules/parallel-coordinates
*/
parallelCoordinates: false,
/**
* Common options for all yAxes rendered in a parallel coordinates plot.
* This feature requires `modules/parallel-coordinates.js`.
*
* The default options are:
* ```js
* parallelAxes: {
* lineWidth: 1, // classic mode only
* gridlinesWidth: 0, // classic mode only
* title: {
* text: '',
* reserveSpace: false
* },
* labels: {
* x: 0,
* y: 0,
* align: 'center',
* reserveSpace: false
* },
* offset: 0
* }
* ```
*
* @sample {highcharts} highcharts/parallel-coordinates/parallelaxes/
* Set the same tickAmount for all yAxes
*
* @extends yAxis
* @since 6.0.0
* @product highcharts
* @excluding alternateGridColor, breaks, id, gridLineColor,
* gridLineDashStyle, gridLineWidth, minorGridLineColor,
* minorGridLineDashStyle, minorGridLineWidth, plotBands,
* plotLines, angle, gridLineInterpolation, maxColor, maxZoom,
* minColor, scrollbar, stackLabels, stops
* @requires modules/parallel-coordinates
*/
parallelAxes: {
lineWidth: 1,
/**
* Titles for yAxes are taken from
* [xAxis.categories](#xAxis.categories). All options for `xAxis.labels`
* applies to parallel coordinates titles. For example, to style
* categories, use [xAxis.labels.style](#xAxis.labels.style).
*
* @excluding align, enabled, margin, offset, position3d, reserveSpace,
* rotation, skew3d, style, text, useHTML, x, y
*/
title: {
text: '',
reserveSpace: false
},
labels: {
x: 0,
y: 4,
align: 'center',
reserveSpace: false
},
offset: 0
}
};
H.setOptions({
chart: defaultParallelOptions
});
/* eslint-disable no-invalid-this */
// Initialize parallelCoordinates
addEvent(Chart, 'init', function (e) {
var options = e.args[0], defaultyAxis = splat(options.yAxis || {}), yAxisLength = defaultyAxis.length, newYAxes = [];
/**
* Flag used in parallel coordinates plot to check if chart has ||-coords
* (parallel coords).
*
* @requires module:modules/parallel-coordinates
*
* @name Highcharts.Chart#hasParallelCoordinates
* @type {boolean}
*/
this.hasParallelCoordinates = options.chart &&
options.chart.parallelCoordinates;
if (this.hasParallelCoordinates) {
this.setParallelInfo(options);
// Push empty yAxes in case user did not define them:
for (; yAxisLength <= this.parallelInfo.counter; yAxisLength++) {
newYAxes.push({});
}
if (!options.legend) {
options.legend = {};
}
if (typeof options.legend.enabled === 'undefined') {
options.legend.enabled = false;
}
merge(true, options,
// Disable boost
{
boost: {
seriesThreshold: Number.MAX_VALUE
},
plotOptions: {
series: {
boostThreshold: Number.MAX_VALUE
}
}
});
options.yAxis = defaultyAxis.concat(newYAxes);
options.xAxis = merge(defaultXAxisOptions, // docs
splat(options.xAxis || {})[0]);
}
});
// Initialize parallelCoordinates
addEvent(Chart, 'update', function (e) {
var options = e.options;
if (options.chart) {
if (defined(options.chart.parallelCoordinates)) {
this.hasParallelCoordinates = options.chart.parallelCoordinates;
}
this.options.chart.parallelAxes = merge(this.options.chart.parallelAxes, options.chart.parallelAxes);
}
if (this.hasParallelCoordinates) {
// (#10081)
if (options.series) {
this.setParallelInfo(options);
}
this.yAxis.forEach(function (axis) {
axis.update({}, false);
});
}
});
/* eslint-disable valid-jsdoc */
extend(ChartProto, /** @lends Highcharts.Chart.prototype */ {
/**
* Define how many parellel axes we have according to the longest dataset.
* This is quite heavy - loop over all series and check series.data.length
* Consider:
*
* - make this an option, so user needs to set this to get better
* performance
*
* - check only first series for number of points and assume the rest is the
* same
*
* @private
* @function Highcharts.Chart#setParallelInfo
* @param {Highcharts.Options} options
* User options
* @return {void}
* @requires modules/parallel-coordinates
*/
setParallelInfo: function (options) {
var chart = this, seriesOptions = options.series;
chart.parallelInfo = {
counter: 0
};
seriesOptions.forEach(function (series) {
if (series.data) {
chart.parallelInfo.counter = Math.max(chart.parallelInfo.counter, series.data.length - 1);
}
});
}
});
// On update, keep parallelPosition.
AxisProto.keepProps.push('parallelPosition');
// Update default options with predefined for a parallel coords.
addEvent(Axis, 'afterSetOptions', function (e) {
var axis = this, chart = axis.chart, axisPosition = ['left', 'width', 'height', 'top'];
if (chart.hasParallelCoordinates) {
if (chart.inverted) {
axisPosition = axisPosition.reverse();
}
if (axis.isXAxis) {
axis.options = merge(axis.options, defaultXAxisOptions, e.userOptions);
}
else {
axis.options = merge(axis.options, axis.chart.options.chart.parallelAxes, e.userOptions);
axis.parallelPosition = pick(axis.parallelPosition, chart.yAxis.length);
axis.setParallelPosition(axisPosition, axis.options);
}
}
});
/* Each axis should gather extremes from points on a particular position in
series.data. Not like the default one, which gathers extremes from all series
bind to this axis. Consider using series.points instead of series.yData. */
addEvent(Axis, 'getSeriesExtremes', function (e) {
if (this.chart && this.chart.hasParallelCoordinates && !this.isXAxis) {
var index = this.parallelPosition, currentPoints = [];
this.series.forEach(function (series) {
if (series.visible &&
defined(series.yData[index])) {
// We need to use push() beacause of null points
currentPoints.push(series.yData[index]);
}
});
this.dataMin = arrayMin(currentPoints);
this.dataMax = arrayMax(currentPoints);
e.preventDefault();
}
});
extend(AxisProto, /** @lends Highcharts.Axis.prototype */ {
/**
* Set predefined left+width and top+height (inverted) for yAxes. This
* method modifies options param.
*
* @function Highcharts.Axis#setParallelPosition
*
* @param {Array<string>} axisPosition
* ['left', 'width', 'height', 'top'] or
* ['top', 'height', 'width', 'left'] for an inverted chart.
*
* @param {Highcharts.AxisOptions} options
* {@link Highcharts.Axis#options}.
*
* @return {void}
*
* @requires modules/parallel-coordinates
*/
setParallelPosition: function (axisPosition, options) {
var fraction = (this.parallelPosition + 0.5) /
(this.chart.parallelInfo.counter + 1);
if (this.chart.polar) {
options.angle = 360 * fraction;
}
else {
options[axisPosition[0]] = 100 * fraction + '%';
this[axisPosition[1]] =
options[axisPosition[1]] = 0;
// In case of chart.update(inverted), remove old options:
this[axisPosition[2]] =
options[axisPosition[2]] = null;
this[axisPosition[3]] =
options[axisPosition[3]] = null;
}
}
});
// Bind each series to each yAxis. yAxis needs a reference to all series to
// calculate extremes.
addEvent(H.Series, 'bindAxes', function (e) {
if (this.chart.hasParallelCoordinates) {
var series = this;
this.chart.axes.forEach(function (axis) {
series.insert(axis.series);
axis.isDirty = true;
});
series.xAxis = this.chart.xAxis[0];
series.yAxis = this.chart.yAxis[0];
e.preventDefault();
}
});
// Translate each point using corresponding yAxis.
addEvent(H.Series, 'afterTranslate', function () {
var series = this, chart = this.chart, points = series.points, dataLength = points && points.length, closestPointRangePx = Number.MAX_VALUE, lastPlotX, point, i;
if (this.chart.hasParallelCoordinates) {
for (i = 0; i < dataLength; i++) {
point = points[i];
if (defined(point.y)) {
if (chart.polar) {
point.plotX = chart.yAxis[i].angleRad || 0;
}
else if (chart.inverted) {
point.plotX = (chart.plotHeight -
chart.yAxis[i].top +
chart.plotTop);
}
else {
point.plotX = chart.yAxis[i].left - chart.plotLeft;
}
point.clientX = point.plotX;
point.plotY = chart.yAxis[i]
.translate(point.y, false, true, null, true);
if (typeof lastPlotX !== 'undefined') {
closestPointRangePx = Math.min(closestPointRangePx, Math.abs(point.plotX - lastPlotX));
}
lastPlotX = point.plotX;
point.isInside = chart.isInsidePlot(point.plotX, point.plotY, chart.inverted);
}
else {
point.isNull = true;
}
}
this.closestPointRangePx = closestPointRangePx;
}
}, { order: 1 });
// On destroy, we need to remove series from each axis.series
addEvent(H.Series, 'destroy', function () {
if (this.chart.hasParallelCoordinates) {
(this.chart.axes || []).forEach(function (axis) {
if (axis && axis.series) {
erase(axis.series, this);
axis.isDirty = axis.forceRedraw = true;
}
}, this);
}
});
/**
* @private
*/
function addFormattedValue(proceed) {
var chart = this.series && this.series.chart, config = proceed.apply(this, Array.prototype.slice.call(arguments, 1)), formattedValue, yAxisOptions, labelFormat, yAxis;
if (chart &&
chart.hasParallelCoordinates &&
!defined(config.formattedValue)) {
yAxis = chart.yAxis[this.x];
yAxisOptions = yAxis.options;
labelFormat = pick(
/**
* Parallel coordinates only. Format that will be used for point.y
* and available in [tooltip.pointFormat](#tooltip.pointFormat) as
* `{point.formattedValue}`. If not set, `{point.formattedValue}`
* will use other options, in this order:
*
* 1. [yAxis.labels.format](#yAxis.labels.format) will be used if
* set
*
* 2. If yAxis is a category, then category name will be displayed
*
* 3. If yAxis is a datetime, then value will use the same format as
* yAxis labels
*
* 4. If yAxis is linear/logarithmic type, then simple value will be
* used
*
* @sample {highcharts}
* /highcharts/parallel-coordinates/tooltipvalueformat/
* Different tooltipValueFormats's
*
* @type {string}
* @default undefined
* @since 6.0.0
* @product highcharts
* @requires modules/parallel-coordinates
* @apioption yAxis.tooltipValueFormat
*/
yAxisOptions.tooltipValueFormat, yAxisOptions.labels.format);
if (labelFormat) {
formattedValue = format(labelFormat, extend(this, { value: this.y }), chart);
}
else if (yAxis.isDatetimeAxis) {
formattedValue = chart.time.dateFormat(chart.time.resolveDTLFormat(yAxisOptions.dateTimeLabelFormats[yAxis.tickPositions.info.unitName]).main, this.y);
}
else if (yAxisOptions.categories) {
formattedValue = yAxisOptions.categories[this.y];
}
else {
formattedValue = this.y;
}
config.formattedValue = config.point.formattedValue = formattedValue;
}
return config;
}
['line', 'spline'].forEach(function (seriesName) {
wrap(H.seriesTypes[seriesName].prototype.pointClass.prototype, 'getLabelConfig', addFormattedValue);
});

View File

@@ -0,0 +1,140 @@
/* *
*
* (c) 2010-2017 Sebastian Bochan
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import U from '../parts/Utilities.js';
var correctFloat = U.correctFloat, merge = U.merge, seriesType = U.seriesType;
import '../parts/Options.js';
import derivedSeriesMixin from '../mixins/derived-series.js';
/**
* The pareto series type.
*
* @private
* @class
* @name Highcharts.seriesTypes.pareto
*
* @augments Highcharts.Series
*/
seriesType('pareto', 'line'
/**
* A pareto diagram is a type of chart that contains both bars and a line
* graph, where individual values are represented in descending order by
* bars, and the cumulative total is represented by the line.
*
* @sample {highcharts} highcharts/demo/pareto/
* Pareto diagram
*
* @extends plotOptions.line
* @since 6.0.0
* @product highcharts
* @excluding allAreas, boostThreshold, borderColor, borderRadius,
* borderWidth, crisp, colorAxis, depth, data, dragDrop,
* edgeColor, edgeWidth, findNearestPointBy, gapSize, gapUnit,
* grouping, groupPadding, groupZPadding, maxPointWidth, keys,
* negativeColor, pointInterval, pointIntervalUnit,
* pointPadding, pointPlacement, pointRange, pointStart,
* pointWidth, shadow, step, softThreshold, stacking,
* threshold, zoneAxis, zones
* @requires modules/pareto
* @optionparent plotOptions.pareto
*/
, {
/**
* Higher zIndex than column series to draw line above shapes.
*/
zIndex: 3
},
/* eslint-disable no-invalid-this, valid-jsdoc */
merge(derivedSeriesMixin, {
/**
* Calculate sum and return percent points.
*
* @private
* @function Highcharts.Series#setDerivedData
* @requires modules/pareto
*/
setDerivedData: function () {
var xValues = this.baseSeries.xData, yValues = this.baseSeries.yData, sum = this.sumPointsPercents(yValues, xValues, null, true);
this.setData(this.sumPointsPercents(yValues, xValues, sum, false), false);
},
/**
* Calculate y sum and each percent point.
*
* @private
* @function Highcharts.Series#sumPointsPercents
*
* @param {Array<number>} yValues
* Y values
*
* @param {Array<number>} xValues
* X values
*
* @param {number} sum
* Sum of all y values
*
* @param {boolean} [isSum]
* Declares if calculate sum of all points
*
* @return {number|Array<number,number>}
* Returns sum of points or array of points [x,sum]
*
* @requires modules/pareto
*/
sumPointsPercents: function (yValues, xValues, sum, isSum) {
var sumY = 0, sumPercent = 0, percentPoints = [], percentPoint;
yValues.forEach(function (point, i) {
if (point !== null) {
if (isSum) {
sumY += point;
}
else {
percentPoint = (point / sum) * 100;
percentPoints.push([
xValues[i],
correctFloat(sumPercent + percentPoint)
]);
sumPercent += percentPoint;
}
}
});
return (isSum ? sumY : percentPoints);
}
})
/* eslint-enable no-invalid-this, valid-jsdoc */
);
/**
* A `pareto` series. If the [type](#series.pareto.type) option is not
* specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.pareto
* @since 6.0.0
* @product highcharts
* @excluding data, dataParser, dataURL
* @requires modules/pareto
* @apioption series.pareto
*/
/**
* An integer identifying the index to use for the base series, or a string
* representing the id of the series.
*
* @type {number|string}
* @default undefined
* @apioption series.pareto.baseSeries
*/
/**
* An array of data points for the series. For the `pareto` series type,
* points are calculated dynamically.
*
* @type {Array<Array<number|string>|*>}
* @extends series.column.data
* @since 6.0.0
* @product highcharts
* @apioption series.pareto.data
*/
''; // adds the doclets above to the transpiled file

View File

@@ -0,0 +1,544 @@
/* *
*
* Module for using patterns or images as point fills.
*
* (c) 2010-2020 Highsoft AS
* Author: Torstein Hønsi, Øystein Moseng
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../parts/Globals.js';
/**
* Pattern options
*
* @interface Highcharts.PatternOptionsObject
*/ /**
* Background color for the pattern if a `path` is set (not images).
* @name Highcharts.PatternOptionsObject#backgroundColor
* @type {Highcharts.ColorString}
*/ /**
* URL to an image to use as the pattern.
* @name Highcharts.PatternOptionsObject#image
* @type {string}
*/ /**
* Width of the pattern. For images this is automatically set to the width of
* the element bounding box if not supplied. For non-image patterns the default
* is 32px. Note that automatic resizing of image patterns to fill a bounding
* box dynamically is only supported for patterns with an automatically
* calculated ID.
* @name Highcharts.PatternOptionsObject#width
* @type {number}
*/ /**
* Analogous to pattern.width.
* @name Highcharts.PatternOptionsObject#height
* @type {number}
*/ /**
* For automatically calculated width and height on images, it is possible to
* set an aspect ratio. The image will be zoomed to fill the bounding box,
* maintaining the aspect ratio defined.
* @name Highcharts.PatternOptionsObject#aspectRatio
* @type {number}
*/ /**
* Horizontal offset of the pattern. Defaults to 0.
* @name Highcharts.PatternOptionsObject#x
* @type {number|undefined}
*/ /**
* Vertical offset of the pattern. Defaults to 0.
* @name Highcharts.PatternOptionsObject#y
* @type {number|undefined}
*/ /**
* Either an SVG path as string, or an object. As an object, supply the path
* string in the `path.d` property. Other supported properties are standard SVG
* attributes like `path.stroke` and `path.fill`. If a path is supplied for the
* pattern, the `image` property is ignored.
* @name Highcharts.PatternOptionsObject#path
* @type {string|Highcharts.SVGAttributes}
*/ /**
* SVG `patternTransform` to apply to the entire pattern.
* @name Highcharts.PatternOptionsObject#patternTransform
* @type {string}
* @see [patternTransform demo](https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/series/pattern-fill-transform)
*/ /**
* Pattern color, used as default path stroke.
* @name Highcharts.PatternOptionsObject#color
* @type {Highcharts.ColorString}
*/ /**
* Opacity of the pattern as a float value from 0 to 1.
* @name Highcharts.PatternOptionsObject#opacity
* @type {number}
*/ /**
* ID to assign to the pattern. This is automatically computed if not added, and
* identical patterns are reused. To refer to an existing pattern for a
* Highcharts color, use `color: "url(#pattern-id)"`.
* @name Highcharts.PatternOptionsObject#id
* @type {string|undefined}
*/
/**
* Holds a pattern definition.
*
* @sample highcharts/series/pattern-fill-area/
* Define a custom path pattern
* @sample highcharts/series/pattern-fill-pie/
* Default patterns and a custom image pattern
* @sample maps/demo/pattern-fill-map/
* Custom images on map
*
* @example
* // Pattern used as a color option
* color: {
* pattern: {
* path: {
* d: 'M 3 3 L 8 3 L 8 8 Z',
* fill: '#102045'
* },
* width: 12,
* height: 12,
* color: '#907000',
* opacity: 0.5
* }
* }
*
* @interface Highcharts.PatternObject
*/ /**
* Pattern options
* @name Highcharts.PatternObject#pattern
* @type {Highcharts.PatternOptionsObject}
*/ /**
* Animation options for the image pattern loading.
* @name Highcharts.PatternObject#animation
* @type {boolean|Highcharts.AnimationOptionsObject|undefined}
*/ /**
* Optionally an index referencing which pattern to use. Highcharts adds
* 10 default patterns to the `Highcharts.patterns` array. Additional
* pattern definitions can be pushed to this array if desired. This option
* is an index into this array.
* @name Highcharts.PatternObject#patternIndex
* @type {number|undefined}
*/
''; // detach doclets above
import Point from '../parts/Point.js';
import U from '../parts/Utilities.js';
var addEvent = U.addEvent, animObject = U.animObject, erase = U.erase, merge = U.merge, pick = U.pick, removeEvent = U.removeEvent, wrap = U.wrap;
// Add the predefined patterns
H.patterns = (function () {
var patterns = [], colors = H.getOptions().colors;
[
'M 0 0 L 10 10 M 9 -1 L 11 1 M -1 9 L 1 11',
'M 0 10 L 10 0 M -1 1 L 1 -1 M 9 11 L 11 9',
'M 3 0 L 3 10 M 8 0 L 8 10',
'M 0 3 L 10 3 M 0 8 L 10 8',
'M 0 3 L 5 3 L 5 0 M 5 10 L 5 7 L 10 7',
'M 3 3 L 8 3 L 8 8 L 3 8 Z',
'M 5 5 m -4 0 a 4 4 0 1 1 8 0 a 4 4 0 1 1 -8 0',
'M 10 3 L 5 3 L 5 0 M 5 10 L 5 7 L 0 7',
'M 2 5 L 5 2 L 8 5 L 5 8 Z',
'M 0 0 L 5 10 L 10 0'
].forEach(function (pattern, i) {
patterns.push({
path: pattern,
color: colors[i],
width: 10,
height: 10
});
});
return patterns;
})();
/**
* Utility function to compute a hash value from an object. Modified Java
* String.hashCode implementation in JS. Use the preSeed parameter to add an
* additional seeding step.
*
* @private
* @function hashFromObject
*
* @param {object} obj
* The javascript object to compute the hash from.
*
* @param {boolean} [preSeed=false]
* Add an optional preSeed stage.
*
* @return {string}
* The computed hash.
*/
function hashFromObject(obj, preSeed) {
var str = JSON.stringify(obj), strLen = str.length || 0, hash = 0, i = 0, char, seedStep;
if (preSeed) {
seedStep = Math.max(Math.floor(strLen / 500), 1);
for (var a = 0; a < strLen; a += seedStep) {
hash += str.charCodeAt(a);
}
hash = hash & hash;
}
for (; i < strLen; ++i) {
char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash;
}
return hash.toString(16).replace('-', '1');
}
/**
* Set dimensions on pattern from point. This function will set internal
* pattern._width/_height properties if width and height are not both already
* set. We only do this on image patterns. The _width/_height properties are set
* to the size of the bounding box of the point, optionally taking aspect ratio
* into account. If only one of width or height are supplied as options, the
* undefined option is calculated as above.
*
* @private
* @function Highcharts.Point#calculatePatternDimensions
*
* @param {Highcharts.PatternOptionsObject} pattern
* The pattern to set dimensions on.
*
* @return {void}
*
* @requires modules/pattern-fill
*/
Point.prototype.calculatePatternDimensions = function (pattern) {
if (pattern.width && pattern.height) {
return;
}
var bBox = this.graphic && (this.graphic.getBBox &&
this.graphic.getBBox(true) ||
this.graphic.element &&
this.graphic.element.getBBox()) || {}, shapeArgs = this.shapeArgs;
// Prefer using shapeArgs, as it is animation agnostic
if (shapeArgs) {
bBox.width = shapeArgs.width || bBox.width;
bBox.height = shapeArgs.height || bBox.height;
bBox.x = shapeArgs.x || bBox.x;
bBox.y = shapeArgs.y || bBox.y;
}
// For images we stretch to bounding box
if (pattern.image) {
// If we do not have a bounding box at this point, simply add a defer
// key and pick this up in the fillSetter handler, where the bounding
// box should exist.
if (!bBox.width || !bBox.height) {
pattern._width = 'defer';
pattern._height = 'defer';
return;
}
// Handle aspect ratio filling
if (pattern.aspectRatio) {
bBox.aspectRatio = bBox.width / bBox.height;
if (pattern.aspectRatio > bBox.aspectRatio) {
// Height of bBox will determine width
bBox.aspectWidth = bBox.height * pattern.aspectRatio;
}
else {
// Width of bBox will determine height
bBox.aspectHeight = bBox.width / pattern.aspectRatio;
}
}
// We set the width/height on internal properties to differentiate
// between the options set by a user and by this function.
pattern._width = pattern.width ||
Math.ceil(bBox.aspectWidth || bBox.width);
pattern._height = pattern.height ||
Math.ceil(bBox.aspectHeight || bBox.height);
}
// Set x/y accordingly, centering if using aspect ratio, otherwise adjusting
// so bounding box corner is 0,0 of pattern.
if (!pattern.width) {
pattern._x = pattern.x || 0;
pattern._x += bBox.x - Math.round(bBox.aspectWidth ?
Math.abs(bBox.aspectWidth - bBox.width) / 2 :
0);
}
if (!pattern.height) {
pattern._y = pattern.y || 0;
pattern._y += bBox.y - Math.round(bBox.aspectHeight ?
Math.abs(bBox.aspectHeight - bBox.height) / 2 :
0);
}
};
/* eslint-disable no-invalid-this */
/**
* Add a pattern to the renderer.
*
* @private
* @function Highcharts.SVGRenderer#addPattern
*
* @param {Highcharts.PatternObject} options
* The pattern options.
*
* @param {boolean|Highcharts.AnimationOptionsObject} [animation]
* The animation options.
*
* @return {Highcharts.SVGElement|undefined}
* The added pattern. Undefined if the pattern already exists.
*
* @requires modules/pattern-fill
*/
H.SVGRenderer.prototype.addPattern = function (options, animation) {
var pattern, animate = pick(animation, true), animationOptions = animObject(animate), path, defaultSize = 32, width = options.width || options._width || defaultSize, height = (options.height || options._height || defaultSize), color = options.color || '#343434', id = options.id, ren = this, rect = function (fill) {
ren.rect(0, 0, width, height)
.attr({ fill: fill })
.add(pattern);
}, attribs;
if (!id) {
this.idCounter = this.idCounter || 0;
id = 'highcharts-pattern-' + this.idCounter + '-' + (this.chartIndex || 0);
++this.idCounter;
}
// Do nothing if ID already exists
this.defIds = this.defIds || [];
if (this.defIds.indexOf(id) > -1) {
return;
}
// Store ID in list to avoid duplicates
this.defIds.push(id);
// Calculate pattern element attributes
var attrs = {
id: id,
patternUnits: 'userSpaceOnUse',
patternContentUnits: options.patternContentUnits || 'userSpaceOnUse',
width: width,
height: height,
x: options._x || options.x || 0,
y: options._y || options.y || 0
};
if (options.patternTransform) {
attrs.patternTransform = options.patternTransform;
}
pattern = this.createElement('pattern').attr(attrs).add(this.defs);
// Set id on the SVGRenderer object
pattern.id = id;
// Use an SVG path for the pattern
if (options.path) {
path = options.path;
// The background
if (options.backgroundColor) {
rect(options.backgroundColor);
}
// The pattern
attribs = {
'd': path.d || path
};
if (!this.styledMode) {
attribs.stroke = path.stroke || color;
attribs['stroke-width'] = pick(path.strokeWidth, 2);
attribs.fill = path.fill || 'none';
}
if (path.transform) {
attribs.transform = path.transform;
}
this.createElement('path').attr(attribs).add(pattern);
pattern.color = color;
// Image pattern
}
else if (options.image) {
if (animate) {
this.image(options.image, 0, 0, width, height, function () {
// Onload
this.animate({
opacity: pick(options.opacity, 1)
}, animationOptions);
removeEvent(this.element, 'load');
}).attr({ opacity: 0 }).add(pattern);
}
else {
this.image(options.image, 0, 0, width, height).add(pattern);
}
}
// For non-animated patterns, set opacity now
if (!(options.image && animate) && typeof options.opacity !== 'undefined') {
[].forEach.call(pattern.element.childNodes, function (child) {
child.setAttribute('opacity', options.opacity);
});
}
// Store for future reference
this.patternElements = this.patternElements || {};
this.patternElements[id] = pattern;
return pattern;
};
// Make sure we have a series color
wrap(H.Series.prototype, 'getColor', function (proceed) {
var oldColor = this.options.color;
// Temporarely remove color options to get defaults
if (oldColor &&
oldColor.pattern &&
!oldColor.pattern.color) {
delete this.options.color;
// Get default
proceed.apply(this, Array.prototype.slice.call(arguments, 1));
// Replace with old, but add default color
oldColor.pattern.color =
this.color;
this.color = this.options.color = oldColor;
}
else {
// We have a color, no need to do anything special
proceed.apply(this, Array.prototype.slice.call(arguments, 1));
}
});
// Calculate pattern dimensions on points that have their own pattern.
addEvent(H.Series, 'render', function () {
var isResizing = this.chart.isResizing;
if (this.isDirtyData || isResizing || !this.chart.hasRendered) {
(this.points || []).forEach(function (point) {
var colorOptions = point.options && point.options.color;
if (colorOptions &&
colorOptions.pattern) {
// For most points we want to recalculate the dimensions on
// render, where we have the shape args and bbox. But if we
// are resizing and don't have the shape args, defer it, since
// the bounding box is still not resized.
if (isResizing &&
!(point.shapeArgs &&
point.shapeArgs.width &&
point.shapeArgs.height)) {
colorOptions.pattern._width =
'defer';
colorOptions.pattern._height =
'defer';
}
else {
point.calculatePatternDimensions(colorOptions.pattern);
}
}
});
}
});
// Merge series color options to points
addEvent(Point, 'afterInit', function () {
var point = this, colorOptions = point.options.color;
// Only do this if we have defined a specific color on this point. Otherwise
// we will end up trying to re-add the series color for each point.
if (colorOptions && colorOptions.pattern) {
// Move path definition to object, allows for merge with series path
// definition
if (typeof colorOptions.pattern.path === 'string') {
colorOptions.pattern.path = {
d: colorOptions.pattern.path
};
}
// Merge with series options
point.color = point.options.color = merge(point.series.options.color, colorOptions);
}
});
// Add functionality to SVG renderer to handle patterns as complex colors
addEvent(H.SVGRenderer, 'complexColor', function (args) {
var color = args.args[0], prop = args.args[1], element = args.args[2], chartIndex = (this.chartIndex || 0);
var pattern = color.pattern, value = '#343434';
// Handle patternIndex
if (typeof color.patternIndex !== 'undefined' && H.patterns) {
pattern = H.patterns[color.patternIndex];
}
// Skip and call default if there is no pattern
if (!pattern) {
return true;
}
// We have a pattern.
if (pattern.image ||
typeof pattern.path === 'string' ||
pattern.path && pattern.path.d) {
// Real pattern. Add it and set the color value to be a reference.
// Force Hash-based IDs for legend items, as they are drawn before
// point render, meaning they are drawn before autocalculated image
// width/heights. We don't want them to highjack the width/height for
// this ID if it is defined by users.
var forceHashId = element.parentNode &&
element.parentNode.getAttribute('class');
forceHashId = forceHashId &&
forceHashId.indexOf('highcharts-legend') > -1;
// If we don't have a width/height yet, handle it. Try faking a point
// and running the algorithm again.
if (pattern._width === 'defer' || pattern._height === 'defer') {
Point.prototype.calculatePatternDimensions.call({ graphic: { element: element } }, pattern);
}
// If we don't have an explicit ID, compute a hash from the
// definition and use that as the ID. This ensures that points with
// the same pattern definition reuse existing pattern elements by
// default. We combine two hashes, the second with an additional
// preSeed algorithm, to minimize collision probability.
if (forceHashId || !pattern.id) {
// Make a copy so we don't accidentally edit options when setting ID
pattern = merge({}, pattern);
pattern.id = 'highcharts-pattern-' + chartIndex + '-' +
hashFromObject(pattern) + hashFromObject(pattern, true);
}
// Add it. This function does nothing if an element with this ID
// already exists.
this.addPattern(pattern, !this.forExport && pick(pattern.animation, this.globalAnimation, { duration: 100 }));
value = "url(" + this.url + "#" + pattern.id + ")";
}
else {
// Not a full pattern definition, just add color
value = pattern.color || value;
}
// Set the fill/stroke prop on the element
element.setAttribute(prop, value);
// Allow the color to be concatenated into tooltips formatters etc.
color.toString = function () {
return value;
};
// Skip default handler
return false;
});
// When animation is used, we have to recalculate pattern dimensions after
// resize, as the bounding boxes are not available until then.
addEvent(H.Chart, 'endResize', function () {
if ((this.renderer && this.renderer.defIds || []).filter(function (id) {
return (id &&
id.indexOf &&
id.indexOf('highcharts-pattern-') === 0);
}).length) {
// We have non-default patterns to fix. Find them by looping through
// all points.
this.series.forEach(function (series) {
series.points.forEach(function (point) {
var colorOptions = point.options && point.options.color;
if (colorOptions &&
colorOptions.pattern) {
colorOptions.pattern._width =
'defer';
colorOptions.pattern._height =
'defer';
}
});
});
// Redraw without animation
this.redraw(false);
}
});
// Add a garbage collector to delete old patterns with autogenerated hashes that
// are no longer being referenced.
addEvent(H.Chart, 'redraw', function () {
var usedIds = {}, renderer = this.renderer,
// Get the autocomputed patterns - these are the ones we might delete
patterns = (renderer.defIds || []).filter(function (pattern) {
return (pattern.indexOf &&
pattern.indexOf('highcharts-pattern-') === 0);
});
if (patterns.length) {
// Look through the DOM for usage of the patterns. This can be points,
// series, tooltips etc.
[].forEach.call(this.renderTo.querySelectorAll('[color^="url("], [fill^="url("], [stroke^="url("]'), function (node) {
var id = node.getAttribute('fill') ||
node.getAttribute('color') ||
node.getAttribute('stroke');
if (id) {
var sanitizedId = id.replace(renderer.url, '').replace('url(#', '').replace(')', '');
usedIds[sanitizedId] = true;
}
});
// Loop through the patterns that exist and see if they are used
patterns.forEach(function (id) {
if (!usedIds[id]) {
// Remove id from used id list
erase(renderer.defIds, id);
// Remove pattern element
if (renderer.patternElements[id]) {
renderer.patternElements[id].destroy();
delete renderer.patternElements[id];
}
}
});
}
});

View File

@@ -0,0 +1,121 @@
/**
* (c) 2009-2020 Sebastian Bochann
*
* Price indicator for Highcharts
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*/
'use strict';
import H from '../parts/Globals.js';
import U from '../parts/Utilities.js';
var addEvent = U.addEvent, isArray = U.isArray, merge = U.merge;
/**
* The line marks the last price from visible range of points.
*
* @sample {highstock} stock/indicators/last-visible-price
* Last visible price
*
* @declare Highcharts.SeriesLastVisiblePriceOptionsObject
* @product highstock
* @requires modules/price-indicator
* @apioption plotOptions.series.lastVisiblePrice
*/
/**
* Enable or disable the indicator.
*
* @type {boolean}
* @product highstock
* @default true
* @apioption plotOptions.series.lastVisiblePrice.enabled
*/
/**
* @declare Highcharts.SeriesLastVisiblePriceLabelOptionsObject
* @apioption plotOptions.series.lastVisiblePrice.label
*/
/**
* Enable or disable the label.
*
* @type {boolean}
* @product highstock
* @default true
* @apioption plotOptions.series.lastVisiblePrice.label.enabled
*
*/
/**
* The line marks the last price from all points.
*
* @sample {highstock} stock/indicators/last-price
* Last price
*
* @declare Highcharts.SeriesLastPriceOptionsObject
* @product highstock
* @requires modules/price-indicator
* @apioption plotOptions.series.lastPrice
*/
/**
* Enable or disable the indicator.
*
* @type {boolean}
* @product highstock
* @default true
* @apioption plotOptions.series.lastPrice.enabled
*/
/**
* The color of the line of last price.
*
* @type {string}
* @product highstock
* @default red
* @apioption plotOptions.series.lastPrice.color
*
*/
/* eslint-disable no-invalid-this */
addEvent(H.Series, 'afterRender', function () {
var serie = this, seriesOptions = serie.options, pointRange = seriesOptions.pointRange, lastVisiblePrice = seriesOptions.lastVisiblePrice, lastPrice = seriesOptions.lastPrice;
if ((lastVisiblePrice || lastPrice) &&
seriesOptions.id !== 'highcharts-navigator-series') {
var xAxis = serie.xAxis, yAxis = serie.yAxis, origOptions = yAxis.crosshair, origGraphic = yAxis.cross, origLabel = yAxis.crossLabel, points = serie.points, yLength = serie.yData.length, pLength = points.length, x = serie.xData[serie.xData.length - 1], y = serie.yData[yLength - 1], lastPoint, yValue, crop;
if (lastPrice && lastPrice.enabled) {
yAxis.crosshair = yAxis.options.crosshair = seriesOptions.lastPrice;
yAxis.cross = serie.lastPrice;
yValue = isArray(y) ? y[3] : y;
yAxis.drawCrosshair(null, ({
x: x,
y: yValue,
plotX: xAxis.toPixels(x, true),
plotY: yAxis.toPixels(yValue, true)
}));
// Save price
if (serie.yAxis.cross) {
serie.lastPrice = serie.yAxis.cross;
serie.lastPrice.y = yValue;
}
}
if (lastVisiblePrice &&
lastVisiblePrice.enabled &&
pLength > 0) {
crop = (points[pLength - 1].x === x) || pointRange === null ? 1 : 2;
yAxis.crosshair = yAxis.options.crosshair = merge({
color: 'transparent'
}, seriesOptions.lastVisiblePrice);
yAxis.cross = serie.lastVisiblePrice;
lastPoint = points[pLength - crop];
// Save price
yAxis.drawCrosshair(null, lastPoint);
if (yAxis.cross) {
serie.lastVisiblePrice = yAxis.cross;
serie.lastVisiblePrice.y = lastPoint.y;
}
if (serie.crossLabel) {
serie.crossLabel.destroy();
}
serie.crossLabel = yAxis.crossLabel;
}
// Restore crosshair:
yAxis.crosshair = origOptions;
yAxis.cross = origGraphic;
yAxis.crossLabel = origLabel;
}
});

View File

@@ -0,0 +1,121 @@
/* *
*
* Highcharts pyramid3d series module
*
* (c) 2010-2020 Highsoft AS
* Author: Kacper Madej
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import U from '../parts/Utilities.js';
var seriesType = U.seriesType;
import '../parts/ColumnSeries.js';
import '../parts/SvgRenderer.js';
/**
* The pyramid3d series type.
*
* @constructor seriesTypes.pyramid3d
* @augments seriesTypes.funnel3d
* @requires highcharts-3d
* @requires modules/cylinder
* @requires modules/funnel3d
* @requires modules/pyramid3d
*/
seriesType('pyramid3d', 'funnel3d',
/**
* A pyramid3d is a 3d version of pyramid series type. Pyramid charts are
* a type of chart often used to visualize stages in a sales project,
* where the top are the initial stages with the most clients.
*
* @sample highcharts/demo/pyramid3d/
* Pyramid3d
*
* @extends plotOptions.funnel3d
* @excluding neckHeight, neckWidth, dataSorting
* @product highcharts
* @since 7.1.0
* @requires highcharts-3d
* @requires modules/cylinder
* @requires modules/funnel3d
* @requires modules/pyramid3d
* @optionparent plotOptions.pyramid3d
*/
{
/**
* A reversed pyramid3d is funnel3d, but the latter supports neck
* related options: neckHeight and neckWidth
*
* @product highcharts
*/
reversed: true,
neckHeight: 0,
neckWidth: 0,
dataLabels: {
verticalAlign: 'top'
}
});
/**
* A `pyramid3d` series. If the [type](#series.pyramid3d.type) option is
* not specified, it is inherited from [chart.type](#chart.type).
*
* @since 7.1.0
* @extends series,plotOptions.pyramid3d
* @excluding allAreas,boostThreshold,colorAxis,compare,compareBase,dataSorting
* @product highcharts
* @sample {highcharts} highcharts/demo/pyramid3d/ Pyramid3d
* @requires modules/pyramid3d
* @apioption series.pyramid3d
*/
/**
* An array of data points for the series. For the `pyramid3d` series
* type, points can be given in the following ways:
*
* 1. An array of numerical values. In this case, the numerical values
* will be interpreted as `y` options. The `x` values will be automatically
* calculated, either starting at 0 and incremented by 1, or from `pointStart`
* and `pointInterval` given in the series options. If the axis has
* categories, these will be used. Example:
*
* ```js
* data: [0, 5, 3, 5]
* ```
*
* 2. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of data
* points exceeds the series'
* [turboThreshold](#series.pyramid3d.turboThreshold),
* this option is not available.
*
* ```js
* data: [{
* y: 2,
* name: "Point2",
* color: "#00FF00"
* }, {
* y: 4,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @sample {highcharts} highcharts/chart/reflow-true/
* Numerical values
* @sample {highcharts} highcharts/series/data-array-of-arrays/
* Arrays of numeric x and y
* @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/
* Arrays of datetime x and y
* @sample {highcharts} highcharts/series/data-array-of-name-value/
* Arrays of point.name and y
* @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
*
* @type {Array<number|Array<number>|*>}
* @extends series.funnel3d.data
* @product highcharts
* @apioption series.pyramid3d.data
*/
''; // adds doclets above to the transpiled file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,717 @@
/* *
*
* (c) 2009-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../parts/Globals.js';
/**
* Containing the position of a box that should be avoided by labels.
*
* @interface Highcharts.LabelIntersectBoxObject
*/ /**
* @name Highcharts.LabelIntersectBoxObject#bottom
* @type {number}
*/ /**
* @name Highcharts.LabelIntersectBoxObject#left
* @type {number}
*/ /**
* @name Highcharts.LabelIntersectBoxObject#right
* @type {number}
*/ /**
* @name Highcharts.LabelIntersectBoxObject#top
* @type {number}
*/
/*
* Highcharts module to place labels next to a series in a natural position.
*
* TODO:
* - add column support (box collision detection, boxesToAvoid logic)
* - avoid data labels, when data labels above, show series label below.
* - add more options (connector, format, formatter)
*
* https://jsfiddle.net/highcharts/L2u9rpwr/
* https://jsfiddle.net/highcharts/y5A37/
* https://jsfiddle.net/highcharts/264Nm/
* https://jsfiddle.net/highcharts/y5A37/
*/
import U from '../parts/Utilities.js';
var addEvent = U.addEvent, animObject = U.animObject, extend = U.extend, isNumber = U.isNumber, pick = U.pick, syncTimeout = U.syncTimeout;
import '../parts/Chart.js';
import '../parts/Series.js';
var labelDistance = 3, Series = H.Series, SVGRenderer = H.SVGRenderer, Chart = H.Chart;
H.setOptions({
/**
* @optionparent plotOptions
*
* @private
*/
plotOptions: {
series: {
/**
* Series labels are placed as close to the series as possible in a
* natural way, seeking to avoid other series. The goal of this
* feature is to make the chart more easily readable, like if a
* human designer placed the labels in the optimal position.
*
* The series labels currently work with series types having a
* `graph` or an `area`.
*
* @sample highcharts/series-label/line-chart
* Line chart
* @sample highcharts/demo/streamgraph
* Stream graph
* @sample highcharts/series-label/stock-chart
* Stock chart
*
* @declare Highcharts.SeriesLabelOptionsObject
* @since 6.0.0
* @product highcharts highstock gantt
* @requires modules/series-label
*/
label: {
/**
* Enable the series label per series.
*/
enabled: true,
/**
* Allow labels to be placed distant to the graph if necessary,
* and draw a connector line to the graph. Setting this option
* to true may decrease the performance significantly, since the
* algorithm with systematically search for open spaces in the
* whole plot area. Visually, it may also result in a more
* cluttered chart, though more of the series will be labeled.
*/
connectorAllowed: false,
/**
* If the label is closer than this to a neighbour graph, draw a
* connector.
*/
connectorNeighbourDistance: 24,
/**
* For area-like series, allow the font size to vary so that
* small areas get a smaller font size. The default applies this
* effect to area-like series but not line-like series.
*
* @type {number|null}
*/
minFontSize: null,
/**
* For area-like series, allow the font size to vary so that
* small areas get a smaller font size. The default applies this
* effect to area-like series but not line-like series.
*
* @type {number|null}
*/
maxFontSize: null,
/**
* Draw the label on the area of an area series. By default it
* is drawn on the area. Set it to `false` to draw it next to
* the graph instead.
*
* @type {boolean|null}
*/
onArea: null,
/**
* Styles for the series label. The color defaults to the series
* color, or a contrast color if `onArea`.
*
* @type {Highcharts.CSSObject}
*/
style: {
/** @internal */
fontWeight: 'bold'
},
/**
* An array of boxes to avoid when laying out the labels. Each
* item has a `left`, `right`, `top` and `bottom` property.
*
* @type {Array<Highcharts.LabelIntersectBoxObject>}
*/
boxesToAvoid: []
}
}
}
});
/* eslint-disable valid-jsdoc */
/**
* Counter-clockwise, part of the fast line intersection logic.
*
* @private
* @function ccw
*/
function ccw(x1, y1, x2, y2, x3, y3) {
var cw = ((y3 - y1) * (x2 - x1)) - ((y2 - y1) * (x3 - x1));
return cw > 0 ? true : !(cw < 0);
}
/**
* Detect if two lines intersect.
*
* @private
* @function intersectLine
*/
function intersectLine(x1, y1, x2, y2, x3, y3, x4, y4) {
return ccw(x1, y1, x3, y3, x4, y4) !== ccw(x2, y2, x3, y3, x4, y4) &&
ccw(x1, y1, x2, y2, x3, y3) !== ccw(x1, y1, x2, y2, x4, y4);
}
/**
* Detect if a box intersects with a line.
*
* @private
* @function boxIntersectLine
*/
function boxIntersectLine(x, y, w, h, x1, y1, x2, y2) {
return (intersectLine(x, y, x + w, y, x1, y1, x2, y2) || // top of label
intersectLine(x + w, y, x + w, y + h, x1, y1, x2, y2) || // right
intersectLine(x, y + h, x + w, y + h, x1, y1, x2, y2) || // bottom
intersectLine(x, y, x, y + h, x1, y1, x2, y2) // left of label
);
}
/**
* General symbol definition for labels with connector.
*
* @private
* @function Highcharts.SVGRenderer#symbols.connector
*/
SVGRenderer.prototype.symbols.connector = function (x, y, w, h, options) {
var anchorX = options && options.anchorX, anchorY = options && options.anchorY, path, yOffset, lateral = w / 2;
if (isNumber(anchorX) && isNumber(anchorY)) {
path = ['M', anchorX, anchorY];
// Prefer 45 deg connectors
yOffset = y - anchorY;
if (yOffset < 0) {
yOffset = -h - yOffset;
}
if (yOffset < w) {
lateral = anchorX < x + (w / 2) ? yOffset : w - yOffset;
}
// Anchor below label
if (anchorY > y + h) {
path.push('L', x + lateral, y + h);
// Anchor above label
}
else if (anchorY < y) {
path.push('L', x + lateral, y);
// Anchor left of label
}
else if (anchorX < x) {
path.push('L', x, y + h / 2);
// Anchor right of label
}
else if (anchorX > x + w) {
path.push('L', x + w, y + h / 2);
}
}
return path || [];
};
/**
* Points to avoid. In addition to actual data points, the label should avoid
* interpolated positions.
*
* @private
* @function Highcharts.Series#getPointsOnGraph
*/
Series.prototype.getPointsOnGraph = function () {
if (!this.xAxis && !this.yAxis) {
return;
}
var distance = 16, points = this.points, point, last, interpolated = [], i, deltaX, deltaY, delta, len, n, j, d, graph = this.graph || this.area, node = graph.element, inverted = this.chart.inverted, xAxis = this.xAxis, yAxis = this.yAxis, paneLeft = inverted ? yAxis.pos : xAxis.pos, paneTop = inverted ? xAxis.pos : yAxis.pos, onArea = pick(this.options.label.onArea, !!this.area), translatedThreshold = yAxis.getThreshold(this.options.threshold), grid = {};
/**
* Push the point to the interpolated points, but only if that position in
* the grid has not been occupied. As a performance optimization, we divide
* the plot area into a grid and only add one point per series (#9815).
* @private
*/
function pushDiscrete(point) {
var cellSize = 8, key = Math.round(point.plotX / cellSize) + ',' +
Math.round(point.plotY / cellSize);
if (!grid[key]) {
grid[key] = 1;
interpolated.push(point);
}
}
// For splines, get the point at length (possible caveat: peaks are not
// correctly detected)
if (this.getPointSpline &&
node.getPointAtLength &&
!onArea &&
// Not performing well on complex series, node.getPointAtLength is too
// heavy (#9815)
points.length < this.chart.plotSizeX / distance) {
// If it is animating towards a path definition, use that briefly, and
// reset
if (graph.toD) {
d = graph.attr('d');
graph.attr({ d: graph.toD });
}
len = node.getTotalLength();
for (i = 0; i < len; i += distance) {
point = node.getPointAtLength(i);
pushDiscrete({
chartX: paneLeft + point.x,
chartY: paneTop + point.y,
plotX: point.x,
plotY: point.y
});
}
if (d) {
graph.attr({ d: d });
}
// Last point
point = points[points.length - 1];
point.chartX = paneLeft + point.plotX;
point.chartY = paneTop + point.plotY;
pushDiscrete(point);
// Interpolate
}
else {
len = points.length;
for (i = 0; i < len; i += 1) {
point = points[i];
last = points[i - 1];
// Absolute coordinates so we can compare different panes
point.chartX = paneLeft + point.plotX;
point.chartY = paneTop + point.plotY;
if (onArea) {
// Vertically centered inside area
point.chartCenterY = paneTop + (point.plotY +
pick(point.yBottom, translatedThreshold)) / 2;
}
// Add interpolated points
if (i > 0) {
deltaX = Math.abs(point.chartX - last.chartX);
deltaY = Math.abs(point.chartY - last.chartY);
delta = Math.max(deltaX, deltaY);
if (delta > distance) {
n = Math.ceil(delta / distance);
for (j = 1; j < n; j += 1) {
pushDiscrete({
chartX: last.chartX +
(point.chartX - last.chartX) *
(j / n),
chartY: last.chartY +
(point.chartY - last.chartY) *
(j / n),
chartCenterY: last.chartCenterY +
(point.chartCenterY -
last.chartCenterY) * (j / n),
plotX: last.plotX +
(point.plotX - last.plotX) *
(j / n),
plotY: last.plotY +
(point.plotY - last.plotY) *
(j / n)
});
}
}
}
// Add the real point in order to find positive and negative peaks
if (isNumber(point.plotY)) {
pushDiscrete(point);
}
}
}
// Get the bounding box so we can do a quick check first if the bounding
// boxes overlap.
/*
interpolated.bBox = node.getBBox();
interpolated.bBox.x += paneLeft;
interpolated.bBox.y += paneTop;
*/
return interpolated;
};
/**
* Overridable function to return series-specific font sizes for the labels. By
* default it returns bigger font sizes for series with the greater sum of y
* values.
*
* @private
* @function Highcharts.Series#labelFontSize
*/
Series.prototype.labelFontSize = function (minFontSize, maxFontSize) {
return minFontSize + ((this.sum / this.chart.labelSeriesMaxSum) *
(maxFontSize - minFontSize)) + 'px';
};
/**
* Check whether a proposed label position is clear of other elements.
*
* @private
* @function Highcharts.Series#checkClearPoint
*/
Series.prototype.checkClearPoint = function (x, y, bBox, checkDistance) {
var distToOthersSquared = Number.MAX_VALUE, // distance to other graphs
distToPointSquared = Number.MAX_VALUE, dist, connectorPoint, onArea = pick(this.options.label.onArea, !!this.area), findDistanceToOthers = (onArea || this.options.label.connectorAllowed), chart = this.chart, series, points, leastDistance = 16, withinRange, xDist, yDist, i, j;
/**
* @private
*/
function intersectRect(r1, r2) {
return !(r2.left > r1.right ||
r2.right < r1.left ||
r2.top > r1.bottom ||
r2.bottom < r1.top);
}
/**
* Get the weight in order to determine the ideal position. Larger distance
* to other series gives more weight. Smaller distance to the actual point
* (connector points only) gives more weight.
* @private
*/
function getWeight(distToOthersSquared, distToPointSquared) {
return distToOthersSquared - distToPointSquared;
}
// First check for collision with existing labels
for (i = 0; i < chart.boxesToAvoid.length; i += 1) {
if (intersectRect(chart.boxesToAvoid[i], {
left: x,
right: x + bBox.width,
top: y,
bottom: y + bBox.height
})) {
return false;
}
}
// For each position, check if the lines around the label intersect with any
// of the graphs.
for (i = 0; i < chart.series.length; i += 1) {
series = chart.series[i];
points = series.interpolatedPoints;
if (series.visible && points) {
for (j = 1; j < points.length; j += 1) {
if (
// To avoid processing, only check intersection if the X
// values are close to the box.
points[j].chartX >= x - leastDistance &&
points[j - 1].chartX <= x + bBox.width +
leastDistance
/* @todo condition above is not the same as below
(
(points[j].chartX as any) >=
(x - leastDistance)
) && (
(points[j - 1].chartX as any) <=
(x + bBox.width + leastDistance)
) */
) {
// If any of the box sides intersect with the line, return.
if (boxIntersectLine(x, y, bBox.width, bBox.height, points[j - 1].chartX, points[j - 1].chartY, points[j].chartX, points[j].chartY)) {
return false;
}
// But if it is too far away (a padded box doesn't
// intersect), also return.
if (this === series && !withinRange && checkDistance) {
withinRange = boxIntersectLine(x - leastDistance, y - leastDistance, bBox.width + 2 * leastDistance, bBox.height + 2 * leastDistance, points[j - 1].chartX, points[j - 1].chartY, points[j].chartX, points[j].chartY);
}
}
// Find the squared distance from the center of the label. On
// area series, avoid its own graph.
if ((findDistanceToOthers || withinRange) &&
(this !== series || onArea)) {
xDist = x + bBox.width / 2 - points[j].chartX;
yDist = y + bBox.height / 2 - points[j].chartY;
distToOthersSquared = Math.min(distToOthersSquared, xDist * xDist + yDist * yDist);
}
}
// Do we need a connector?
if (!onArea &&
findDistanceToOthers &&
this === series &&
((checkDistance && !withinRange) ||
distToOthersSquared < Math.pow(this.options.label.connectorNeighbourDistance, 2))) {
for (j = 1; j < points.length; j += 1) {
dist = Math.min((Math.pow(x + bBox.width / 2 - points[j].chartX, 2) +
Math.pow(y + bBox.height / 2 - points[j].chartY, 2)), (Math.pow(x - points[j].chartX, 2) +
Math.pow(y - points[j].chartY, 2)), (Math.pow(x + bBox.width - points[j].chartX, 2) +
Math.pow(y - points[j].chartY, 2)), (Math.pow(x + bBox.width - points[j].chartX, 2) +
Math.pow(y + bBox.height - points[j].chartY, 2)), (Math.pow(x - points[j].chartX, 2) +
Math.pow(y + bBox.height - points[j].chartY, 2)));
if (dist < distToPointSquared) {
distToPointSquared = dist;
connectorPoint = points[j];
}
}
withinRange = true;
}
}
}
return !checkDistance || withinRange ? {
x: x,
y: y,
weight: getWeight(distToOthersSquared, connectorPoint ? distToPointSquared : 0),
connectorPoint: connectorPoint
} : false;
};
/**
* The main initialize method that runs on chart level after initialization and
* redraw. It runs in a timeout to prevent locking, and loops over all series,
* taking all series and labels into account when placing the labels.
*
* @private
* @function Highcharts.Chart#drawSeriesLabels
*/
Chart.prototype.drawSeriesLabels = function () {
// console.time('drawSeriesLabels');
var chart = this, labelSeries = this.labelSeries;
chart.boxesToAvoid = [];
// Build the interpolated points
labelSeries.forEach(function (series) {
series.interpolatedPoints = series.getPointsOnGraph();
(series.options.label.boxesToAvoid || []).forEach(function (box) {
chart.boxesToAvoid.push(box);
});
});
chart.series.forEach(function (series) {
if (!series.xAxis && !series.yAxis) {
return;
}
var bBox, x, y, results = [], clearPoint, i, best, labelOptions = series.options.label, inverted = chart.inverted, paneLeft = (inverted ? series.yAxis.pos : series.xAxis.pos), paneTop = (inverted ? series.xAxis.pos : series.yAxis.pos), paneWidth = chart.inverted ? series.yAxis.len : series.xAxis.len, paneHeight = chart.inverted ? series.xAxis.len : series.yAxis.len, points = series.interpolatedPoints, onArea = pick(labelOptions.onArea, !!series.area), label = series.labelBySeries, isNew = !label, minFontSize = labelOptions.minFontSize, maxFontSize = labelOptions.maxFontSize, dataExtremes, areaMin, areaMax, colorClass = 'highcharts-color-' + pick(series.colorIndex, 'none');
// Stay within the area data bounds (#10038)
if (onArea && !inverted) {
dataExtremes = [
series.xAxis.toPixels(series.xData[0]),
series.xAxis.toPixels(series.xData[series.xData.length - 1])
];
areaMin = Math.min.apply(Math, dataExtremes);
areaMax = Math.max.apply(Math, dataExtremes);
}
/**
* @private
*/
function insidePane(x, y, bBox) {
var leftBound = Math.max(paneLeft, pick(areaMin, -Infinity)), rightBound = Math.min(paneLeft + paneWidth, pick(areaMax, Infinity));
return (x > leftBound &&
x <= rightBound - bBox.width &&
y >= paneTop &&
y <= paneTop + paneHeight - bBox.height);
}
/**
* @private
*/
function destroyLabel() {
if (label) {
series.labelBySeries = label.destroy();
}
}
if (series.visible && !series.isSeriesBoosting && points) {
if (!label) {
series.labelBySeries = label = chart.renderer
.label(series.name, 0, -9999, 'connector')
.addClass('highcharts-series-label ' +
'highcharts-series-label-' + series.index + ' ' +
(series.options.className || '') +
colorClass);
if (!chart.renderer.styledMode) {
label.css(extend({
color: onArea ?
chart.renderer.getContrast(series.color) :
series.color
}, series.options.label.style));
}
// Adapt label sizes to the sum of the data
if (minFontSize && maxFontSize) {
label.css({
fontSize: series.labelFontSize(minFontSize, maxFontSize)
});
}
label
.attr({
padding: 0,
opacity: chart.renderer.forExport ? 1 : 0,
stroke: series.color,
'stroke-width': 1,
zIndex: 3
})
.add();
}
bBox = label.getBBox();
bBox.width = Math.round(bBox.width);
// Ideal positions are centered above or below a point on right side
// of chart
for (i = points.length - 1; i > 0; i -= 1) {
if (onArea) {
// Centered
x = points[i].chartX - bBox.width / 2;
y = points[i].chartCenterY - bBox.height / 2;
if (insidePane(x, y, bBox)) {
best = series.checkClearPoint(x, y, bBox);
}
if (best) {
results.push(best);
}
}
else {
// Right - up
x = points[i].chartX + labelDistance;
y = points[i].chartY - bBox.height - labelDistance;
if (insidePane(x, y, bBox)) {
best = series.checkClearPoint(x, y, bBox, true);
}
if (best) {
results.push(best);
}
// Right - down
x = points[i].chartX + labelDistance;
y = points[i].chartY + labelDistance;
if (insidePane(x, y, bBox)) {
best = series.checkClearPoint(x, y, bBox, true);
}
if (best) {
results.push(best);
}
// Left - down
x = points[i].chartX - bBox.width - labelDistance;
y = points[i].chartY + labelDistance;
if (insidePane(x, y, bBox)) {
best = series.checkClearPoint(x, y, bBox, true);
}
if (best) {
results.push(best);
}
// Left - up
x = points[i].chartX - bBox.width - labelDistance;
y = points[i].chartY - bBox.height - labelDistance;
if (insidePane(x, y, bBox)) {
best = series.checkClearPoint(x, y, bBox, true);
}
if (best) {
results.push(best);
}
}
}
// Brute force, try all positions on the chart in a 16x16 grid
if (labelOptions.connectorAllowed && !results.length && !onArea) {
for (x = paneLeft + paneWidth - bBox.width; x >= paneLeft; x -= 16) {
for (y = paneTop; y < paneTop + paneHeight - bBox.height; y += 16) {
clearPoint = series.checkClearPoint(x, y, bBox, true);
if (clearPoint) {
results.push(clearPoint);
}
}
}
}
if (results.length) {
results.sort(function (a, b) {
return b.weight - a.weight;
});
best = results[0];
chart.boxesToAvoid.push({
left: best.x,
right: best.x + bBox.width,
top: best.y,
bottom: best.y + bBox.height
});
// Move it if needed
var dist = Math.sqrt(Math.pow(Math.abs(best.x - label.x), 2), Math.pow(Math.abs(best.y - label.y), 2));
if (dist) {
// Move fast and fade in - pure animation movement is
// distractive...
var attr = {
opacity: chart.renderer.forExport ? 1 : 0,
x: best.x,
y: best.y
}, anim = {
opacity: 1
};
// ... unless we're just moving a short distance
if (dist <= 10) {
anim = {
x: attr.x,
y: attr.y
};
attr = {};
}
series.labelBySeries
.attr(extend(attr, {
anchorX: best.connectorPoint &&
best.connectorPoint.plotX + paneLeft,
anchorY: best.connectorPoint &&
best.connectorPoint.plotY + paneTop
}))
.animate(anim, isNew ?
// Default initial animation to a fraction of
// the series animation (#9396)
animObject(series.options.animation).duration * 0.2 :
// On updating, default to the general chart
// animation
chart.renderer.globalAnimation);
// Record closest point to stick to for sync redraw
series.options.kdNow = true;
series.buildKDTree();
var closest = series.searchPoint({
chartX: best.x,
chartY: best.y
}, true);
label.closest = [
closest,
best.x - closest.plotX,
best.y - closest.plotY
];
}
}
else {
destroyLabel();
}
}
else {
destroyLabel();
}
});
H.fireEvent(chart, 'afterDrawSeriesLabels');
// console.timeEnd('drawSeriesLabels');
};
/* eslint-disable no-invalid-this */
/**
* Prepare drawing series labels.
*
* @private
* @function drawLabels
*/
function drawLabels(e) {
var chart = this, delay = animObject(chart.renderer.globalAnimation).duration;
chart.labelSeries = [];
chart.labelSeriesMaxSum = 0;
U.clearTimeout(chart.seriesLabelTimer);
// Which series should have labels
chart.series.forEach(function (series) {
var options = series.options.label, label = series.labelBySeries, closest = label && label.closest;
if (options.enabled &&
series.visible &&
(series.graph || series.area) &&
!series.isSeriesBoosting) {
chart.labelSeries.push(series);
if (options.minFontSize && options.maxFontSize) {
series.sum = series.yData.reduce(function (pv, cv) {
return (pv || 0) + (cv || 0);
}, 0);
chart.labelSeriesMaxSum = Math.max(chart.labelSeriesMaxSum, series.sum);
}
// The labels are processing heavy, wait until the animation is done
if (e.type === 'load') {
delay = Math.max(delay, animObject(series.options.animation).duration);
}
// Keep the position updated to the axis while redrawing
if (closest) {
if (typeof closest[0].plotX !== 'undefined') {
label.animate({
x: closest[0].plotX + closest[1],
y: closest[0].plotY + closest[2]
});
}
else {
label.attr({ opacity: 0 });
}
}
}
});
chart.seriesLabelTimer = syncTimeout(function () {
if (chart.series && chart.labelSeries) { // #7931, chart destroyed
chart.drawSeriesLabels();
}
}, chart.renderer.forExport || !delay ? 0 : delay);
}
// Leave both events, we handle animation differently (#9815)
addEvent(Chart, 'load', drawLabels);
addEvent(Chart, 'redraw', drawLabels);

View File

@@ -0,0 +1,414 @@
/* *
*
* Solid angular gauge module
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../parts/Globals.js';
/**
* Additional options, depending on the actual symbol drawn.
*
* @interface Highcharts.SymbolOptionsObject
*/ /**
* Whether to draw rounded edges.
* @name Highcharts.SymbolOptionsObject#rounded
* @type {boolean|undefined}
*/
import Color from '../parts/Color.js';
var color = Color.parse;
import LegendSymbolMixin from '../mixins/legend-symbol.js';
import U from '../parts/Utilities.js';
var clamp = U.clamp, extend = U.extend, isNumber = U.isNumber, merge = U.merge, pick = U.pick, pInt = U.pInt, seriesType = U.seriesType, wrap = U.wrap;
import '../parts/Options.js';
import '../parts-more/GaugeSeries.js';
var Renderer = H.Renderer, colorAxisMethods;
/**
* Symbol definition of an arc with round edges.
*
* @private
* @function Highcharts.Renderer#symbols.arc
*
* @param {number} x
* The X coordinate for the top left position.
*
* @param {number} y
* The Y coordinate for the top left position.
*
* @param {number} w
* The pixel width.
*
* @param {number} h
* The pixel height.
*
* @param {Highcharts.SymbolOptionsObject} [options]
* Additional options, depending on the actual symbol drawn.
*
* @return {Highcharts.SVGPathArray}
* Path of the created arc.
*/
wrap(Renderer.prototype.symbols, 'arc', function (proceed, x, y, w, h, options) {
var arc = proceed, path = arc(x, y, w, h, options);
if (options.rounded) {
var r = options.r || w, smallR = (r - options.innerR) / 2, x1 = path[1], y1 = path[2], x2 = path[12], y2 = path[13], roundStart = ['A', smallR, smallR, 0, 1, 1, x1, y1], roundEnd = ['A', smallR, smallR, 0, 1, 1, x2, y2];
// Insert rounded edge on end, and remove line.
path.splice.apply(path, [path.length - 1, 0].concat(roundStart));
// Insert rounded edge on end, and remove line.
path.splice.apply(path, [11, 3].concat(roundEnd));
}
return path;
});
// These methods are defined in the ColorAxis object, and copied here.
// If we implement an AMD system we should make ColorAxis a dependency.
colorAxisMethods = {
initDataClasses: function (userOptions) {
var chart = this.chart, dataClasses, colorCounter = 0, options = this.options;
this.dataClasses = dataClasses = [];
userOptions.dataClasses.forEach(function (dataClass, i) {
var colors;
dataClass = merge(dataClass);
dataClasses.push(dataClass);
if (!dataClass.color) {
if (options.dataClassColor === 'category') {
colors = chart.options.colors;
dataClass.color = colors[colorCounter++];
// loop back to zero
if (colorCounter === colors.length) {
colorCounter = 0;
}
}
else {
dataClass.color = color(options.minColor).tweenTo(color(options.maxColor), i / (userOptions.dataClasses.length - 1));
}
}
});
},
initStops: function (userOptions) {
this.stops = userOptions.stops || [
[0, this.options.minColor],
[1, this.options.maxColor]
];
this.stops.forEach(function (stop) {
stop.color = color(stop[1]);
});
},
// Translate from a value to a color
toColor: function (value, point) {
var pos, stops = this.stops, from, to, color, dataClasses = this.dataClasses, dataClass, i;
if (dataClasses) {
i = dataClasses.length;
while (i--) {
dataClass = dataClasses[i];
from = dataClass.from;
to = dataClass.to;
if ((typeof from === 'undefined' || value >= from) &&
(typeof to === 'undefined' || value <= to)) {
color = dataClass.color;
if (point) {
point.dataClass = i;
}
break;
}
}
}
else {
if (this.isLog) {
value = this.val2lin(value);
}
pos = 1 - ((this.max - value) / (this.max - this.min));
i = stops.length;
while (i--) {
if (pos > stops[i][0]) {
break;
}
}
from = stops[i] || stops[i + 1];
to = stops[i + 1] || from;
// The position within the gradient
pos = (1 - (to[0] - pos) / ((to[0] -
from[0]) || 1));
color = from.color.tweenTo(to.color, pos);
}
return color;
}
};
/**
* A solid gauge is a circular gauge where the value is indicated by a filled
* arc, and the color of the arc may variate with the value.
*
* @sample highcharts/demo/gauge-solid/
* Solid gauges
*
* @extends plotOptions.gauge
* @excluding dial, pivot, wrap
* @product highcharts
* @requires modules/solid-gauge
* @optionparent plotOptions.solidgauge
*/
var solidGaugeOptions = {
/**
* The inner radius for points in a solid gauge. Can be given as a number
* (pixels) or percentage string.
*
* @sample {highcharts} highcharts/plotoptions/solidgauge-radius/
* Individual radius and innerRadius
*
* @type {number|string}
* @default 60
* @since 4.1.6
* @product highcharts
* @apioption plotOptions.solidgauge.innerRadius
*/
/**
* Whether the strokes of the solid gauge should be `round` or `square`.
*
* @sample {highcharts} highcharts/demo/gauge-activity/
* Rounded gauge
*
* @type {string}
* @default round
* @since 4.2.2
* @product highcharts
* @validvalue ["square", "round"]
* @apioption plotOptions.solidgauge.linecap
*/
/**
* Allow the gauge to overshoot the end of the perimeter axis by this
* many degrees. Say if the gauge axis goes from 0 to 60, a value of
* 100, or 1000, will show 5 degrees beyond the end of the axis when this
* option is set to 5.
*
* @type {number}
* @default 0
* @since 3.0.10
* @product highcharts
* @apioption plotOptions.solidgauge.overshoot
*/
/**
* The outer radius for points in a solid gauge. Can be given as a number
* (pixels) or percentage string.
*
* @sample {highcharts} highcharts/plotoptions/solidgauge-radius/
* Individual radius and innerRadius
*
* @type {number|string}
* @default 100
* @since 4.1.6
* @product highcharts
* @apioption plotOptions.solidgauge.radius
*/
/**
* Wether to draw rounded edges on the gauge.
*
* @sample {highcharts} highcharts/demo/gauge-activity/
* Activity Gauge
*
* @type {boolean}
* @default false
* @since 5.0.8
* @product highcharts
* @apioption plotOptions.solidgauge.rounded
*/
/**
* The threshold or base level for the gauge.
*
* @sample {highcharts} highcharts/plotoptions/solidgauge-threshold/
* Zero threshold with negative and positive values
*
* @type {number}
* @since 5.0.3
* @product highcharts
* @apioption plotOptions.solidgauge.threshold
*/
/**
* Whether to give each point an individual color.
*/
colorByPoint: true,
dataLabels: {
y: 0
}
};
// The solidgauge series type
seriesType('solidgauge', 'gauge', solidGaugeOptions, {
drawLegendSymbol: LegendSymbolMixin.drawRectangle,
// Extend the translate function to extend the Y axis with the necessary
// decoration (#5895).
translate: function () {
var axis = this.yAxis;
extend(axis, colorAxisMethods);
// Prepare data classes
if (!axis.dataClasses && axis.options.dataClasses) {
axis.initDataClasses(axis.options);
}
axis.initStops(axis.options);
// Generate points and inherit data label position
H.seriesTypes.gauge.prototype.translate.call(this);
},
// Draw the points where each point is one needle.
drawPoints: function () {
var series = this, yAxis = series.yAxis, center = yAxis.center, options = series.options, renderer = series.chart.renderer, overshoot = options.overshoot, overshootVal = isNumber(overshoot) ?
overshoot / 180 * Math.PI :
0, thresholdAngleRad;
// Handle the threshold option
if (isNumber(options.threshold)) {
thresholdAngleRad = yAxis.startAngleRad + yAxis.translate(options.threshold, null, null, null, true);
}
this.thresholdAngleRad = pick(thresholdAngleRad, yAxis.startAngleRad);
series.points.forEach(function (point) {
// #10630 null point should not be draw
if (!point.isNull) { // condition like in pie chart
var graphic = point.graphic, rotation = (yAxis.startAngleRad +
yAxis.translate(point.y, null, null, null, true)), radius = ((pInt(pick(point.options.radius, options.radius, 100)) * center[2]) / 200), innerRadius = ((pInt(pick(point.options.innerRadius, options.innerRadius, 60)) * center[2]) / 200), shapeArgs, d, toColor = yAxis.toColor(point.y, point), axisMinAngle = Math.min(yAxis.startAngleRad, yAxis.endAngleRad), axisMaxAngle = Math.max(yAxis.startAngleRad, yAxis.endAngleRad), minAngle, maxAngle;
if (toColor === 'none') { // #3708
toColor = point.color || series.color || 'none';
}
if (toColor !== 'none') {
point.color = toColor;
}
// Handle overshoot and clipping to axis max/min
rotation = clamp(rotation, axisMinAngle - overshootVal, axisMaxAngle + overshootVal);
// Handle the wrap option
if (options.wrap === false) {
rotation = clamp(rotation, axisMinAngle, axisMaxAngle);
}
minAngle = Math.min(rotation, series.thresholdAngleRad);
maxAngle = Math.max(rotation, series.thresholdAngleRad);
if (maxAngle - minAngle > 2 * Math.PI) {
maxAngle = minAngle + 2 * Math.PI;
}
point.shapeArgs = shapeArgs = {
x: center[0],
y: center[1],
r: radius,
innerR: innerRadius,
start: minAngle,
end: maxAngle,
rounded: options.rounded
};
point.startR = radius; // For PieSeries.animate
if (graphic) {
d = shapeArgs.d;
graphic.animate(extend({ fill: toColor }, shapeArgs));
if (d) {
shapeArgs.d = d; // animate alters it
}
}
else {
point.graphic = graphic = renderer.arc(shapeArgs)
.attr({
fill: toColor,
'sweep-flag': 0
})
.add(series.group);
}
if (!series.chart.styledMode) {
if (options.linecap !== 'square') {
graphic.attr({
'stroke-linecap': 'round',
'stroke-linejoin': 'round'
});
}
graphic.attr({
stroke: options.borderColor || 'none',
'stroke-width': options.borderWidth || 0
});
}
if (graphic) {
graphic.addClass(point.getClassName(), true);
}
}
});
},
// Extend the pie slice animation by animating from start angle and up.
animate: function (init) {
if (!init) {
this.startAngleRad = this.thresholdAngleRad;
H.seriesTypes.pie.prototype.animate.call(this, init);
}
}
});
/**
* A `solidgauge` series. If the [type](#series.solidgauge.type) option is not
* specified, it is inherited from [chart.type](#chart.type).
*
*
* @extends series,plotOptions.solidgauge
* @excluding animationLimit, boostThreshold, connectEnds, connectNulls,
* cropThreshold, dashStyle, dataParser, dataURL, dial,
* findNearestPointBy, getExtremesFromAll, marker, negativeColor,
* pointPlacement, pivot, shadow, softThreshold, stack, stacking,
* states, step, threshold, turboThreshold, wrap, zoneAxis, zones,
* dataSorting
* @product highcharts
* @requires modules/solid-gauge
* @apioption series.solidgauge
*/
/**
* An array of data points for the series. For the `solidgauge` series
* type, points can be given in the following ways:
*
* 1. An array of numerical values. In this case, the numerical values will be
* interpreted as `y` options. Example:
* ```js
* data: [0, 5, 3, 5]
* ```
*
* 2. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.solidgauge.turboThreshold), this option is not
* available.
* ```js
* data: [{
* y: 5,
* name: "Point2",
* color: "#00FF00"
* }, {
* y: 7,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* The typical gauge only contains a single data value.
*
* @sample {highcharts} highcharts/chart/reflow-true/
* Numerical values
* @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
*
* @type {Array<number|null|*>}
* @extends series.gauge.data
* @product highcharts
* @apioption series.solidgauge.data
*/
/**
* The inner radius of an individual point in a solid gauge. Can be given as a
* number (pixels) or percentage string.
*
* @sample {highcharts} highcharts/plotoptions/solidgauge-radius/
* Individual radius and innerRadius
*
* @type {number|string}
* @since 4.1.6
* @product highcharts
* @apioption series.solidgauge.data.innerRadius
*/
/**
* The outer radius of an individual point in a solid gauge. Can be
* given as a number (pixels) or percentage string.
*
* @sample {highcharts} highcharts/plotoptions/solidgauge-radius/
* Individual radius and innerRadius
*
* @type {number|string}
* @since 4.1.6
* @product highcharts
* @apioption series.solidgauge.data.radius
*/
''; // adds doclets above to transpiled file

View File

@@ -0,0 +1,167 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Earcons for the sonification module in Highcharts.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../parts/Globals.js';
import U from '../../parts/Utilities.js';
var error = U.error, merge = U.merge, pick = U.pick, uniqueKey = U.uniqueKey;
/**
* Define an Instrument and the options for playing it.
*
* @requires module:modules/sonification
*
* @interface Highcharts.EarconInstrument
*/ /**
* An instrument instance or the name of the instrument in the
* Highcharts.sonification.instruments map.
* @name Highcharts.EarconInstrument#instrument
* @type {string|Highcharts.Instrument}
*/ /**
* The options to pass to Instrument.play.
* @name Highcharts.EarconInstrument#playOptions
* @type {Highcharts.InstrumentPlayOptionsObject}
*/
/**
* Options for an Earcon.
*
* @requires module:modules/sonification
*
* @interface Highcharts.EarconOptionsObject
*/ /**
* The instruments and their options defining this earcon.
* @name Highcharts.EarconOptionsObject#instruments
* @type {Array<Highcharts.EarconInstrument>}
*/ /**
* The unique ID of the Earcon. Generated if not supplied.
* @name Highcharts.EarconOptionsObject#id
* @type {string|undefined}
*/ /**
* Global panning of all instruments. Overrides all panning on individual
* instruments. Can be a number between -1 and 1.
* @name Highcharts.EarconOptionsObject#pan
* @type {number|undefined}
*/ /**
* Master volume for all instruments. Volume settings on individual instruments
* can still be used for relative volume between the instruments. This setting
* does not affect volumes set by functions in individual instruments. Can be a
* number between 0 and 1. Defaults to 1.
* @name Highcharts.EarconOptionsObject#volume
* @type {number|undefined}
*/ /**
* Callback function to call when earcon has finished playing.
* @name Highcharts.EarconOptionsObject#onEnd
* @type {Function|undefined}
*/
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* The Earcon class. Earcon objects represent a certain sound consisting of
* one or more instruments playing a predefined sound.
*
* @sample highcharts/sonification/earcon/
* Using earcons directly
*
* @requires module:modules/sonification
*
* @class
* @name Highcharts.Earcon
*
* @param {Highcharts.EarconOptionsObject} options
* Options for the Earcon instance.
*/
function Earcon(options) {
this.init(options || {});
}
Earcon.prototype.init = function (options) {
this.options = options;
if (!this.options.id) {
this.options.id = this.id = uniqueKey();
}
this.instrumentsPlaying = {};
};
/**
* Play the earcon, optionally overriding init options.
*
* @sample highcharts/sonification/earcon/
* Using earcons directly
*
* @function Highcharts.Earcon#sonify
*
* @param {Highcharts.EarconOptionsObject} options
* Override existing options.
*
* @return {void}
*/
Earcon.prototype.sonify = function (options) {
var playOptions = merge(this.options, options);
// Find master volume/pan settings
var masterVolume = pick(playOptions.volume, 1), masterPan = playOptions.pan, earcon = this, playOnEnd = options && options.onEnd, masterOnEnd = earcon.options.onEnd;
// Go through the instruments and play them
playOptions.instruments.forEach(function (opts) {
var instrument = typeof opts.instrument === 'string' ?
H.sonification.instruments[opts.instrument] : opts.instrument, instrumentOpts = merge(opts.playOptions), instrOnEnd, instrumentCopy, copyId = '';
if (instrument && instrument.play) {
if (opts.playOptions) {
// Handle master pan/volume
if (typeof opts.playOptions.volume !== 'function') {
instrumentOpts.volume = pick(masterVolume, 1) *
pick(opts.playOptions.volume, 1);
}
instrumentOpts.pan = pick(masterPan, instrumentOpts.pan);
// Handle onEnd
instrOnEnd = instrumentOpts.onEnd;
instrumentOpts.onEnd = function () {
delete earcon.instrumentsPlaying[copyId];
if (instrOnEnd) {
instrOnEnd.apply(this, arguments);
}
if (!Object.keys(earcon.instrumentsPlaying).length) {
if (playOnEnd) {
playOnEnd.apply(this, arguments);
}
if (masterOnEnd) {
masterOnEnd.apply(this, arguments);
}
}
};
// Play the instrument. Use a copy so we can play multiple at
// the same time.
instrumentCopy = instrument.copy();
copyId = instrumentCopy.id;
earcon.instrumentsPlaying[copyId] = instrumentCopy;
instrumentCopy.play(instrumentOpts);
}
}
else {
error(30);
}
});
};
/**
* Cancel any current sonification of the Earcon. Calls onEnd functions.
*
* @function Highcharts.Earcon#cancelSonify
*
* @param {boolean} [fadeOut=false]
* Whether or not to fade out as we stop. If false, the earcon is
* cancelled synchronously.
*
* @return {void}
*/
Earcon.prototype.cancelSonify = function (fadeOut) {
var playing = this.instrumentsPlaying, instrIds = playing && Object.keys(playing);
if (instrIds && instrIds.length) {
instrIds.forEach(function (instr) {
playing[instr].stop(!fadeOut, null, 'cancelled');
});
this.instrumentsPlaying = {};
}
};
export default Earcon;

View File

@@ -0,0 +1,515 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Instrument class for sonification module.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../parts/Globals.js';
import U from '../../parts/Utilities.js';
var error = U.error, merge = U.merge, pick = U.pick, uniqueKey = U.uniqueKey;
/**
* A set of options for the Instrument class.
*
* @requires module:modules/sonification
*
* @interface Highcharts.InstrumentOptionsObject
*/ /**
* The type of instrument. Currently only `oscillator` is supported. Defaults
* to `oscillator`.
* @name Highcharts.InstrumentOptionsObject#type
* @type {string|undefined}
*/ /**
* The unique ID of the instrument. Generated if not supplied.
* @name Highcharts.InstrumentOptionsObject#id
* @type {string|undefined}
*/ /**
* When using functions to determine frequency or other parameters during
* playback, this options specifies how often to call the callback functions.
* Number given in milliseconds. Defaults to 20.
* @name Highcharts.InstrumentOptionsObject#playCallbackInterval
* @type {number|undefined}
*/ /**
* A list of allowed frequencies for this instrument. If trying to play a
* frequency not on this list, the closest frequency will be used. Set to `null`
* to allow all frequencies to be used. Defaults to `null`.
* @name Highcharts.InstrumentOptionsObject#allowedFrequencies
* @type {Array<number>|undefined}
*/ /**
* Options specific to oscillator instruments.
* @name Highcharts.InstrumentOptionsObject#oscillator
* @type {Highcharts.OscillatorOptionsObject|undefined}
*/
/**
* Options for playing an instrument.
*
* @requires module:modules/sonification
*
* @interface Highcharts.InstrumentPlayOptionsObject
*/ /**
* The frequency of the note to play. Can be a fixed number, or a function. The
* function receives one argument: the relative time of the note playing (0
* being the start, and 1 being the end of the note). It should return the
* frequency number for each point in time. The poll interval of this function
* is specified by the Instrument.playCallbackInterval option.
* @name Highcharts.InstrumentPlayOptionsObject#frequency
* @type {number|Function}
*/ /**
* The duration of the note in milliseconds.
* @name Highcharts.InstrumentPlayOptionsObject#duration
* @type {number}
*/ /**
* The minimum frequency to allow. If the instrument has a set of allowed
* frequencies, the closest frequency is used by default. Use this option to
* stop too low frequencies from being used.
* @name Highcharts.InstrumentPlayOptionsObject#minFrequency
* @type {number|undefined}
*/ /**
* The maximum frequency to allow. If the instrument has a set of allowed
* frequencies, the closest frequency is used by default. Use this option to
* stop too high frequencies from being used.
* @name Highcharts.InstrumentPlayOptionsObject#maxFrequency
* @type {number|undefined}
*/ /**
* The volume of the instrument. Can be a fixed number between 0 and 1, or a
* function. The function receives one argument: the relative time of the note
* playing (0 being the start, and 1 being the end of the note). It should
* return the volume for each point in time. The poll interval of this function
* is specified by the Instrument.playCallbackInterval option. Defaults to 1.
* @name Highcharts.InstrumentPlayOptionsObject#volume
* @type {number|Function|undefined}
*/ /**
* The panning of the instrument. Can be a fixed number between -1 and 1, or a
* function. The function receives one argument: the relative time of the note
* playing (0 being the start, and 1 being the end of the note). It should
* return the panning value for each point in time. The poll interval of this
* function is specified by the Instrument.playCallbackInterval option.
* Defaults to 0.
* @name Highcharts.InstrumentPlayOptionsObject#pan
* @type {number|Function|undefined}
*/ /**
* Callback function to be called when the play is completed.
* @name Highcharts.InstrumentPlayOptionsObject#onEnd
* @type {Function|undefined}
*/
/**
* @requires module:modules/sonification
*
* @interface Highcharts.OscillatorOptionsObject
*/ /**
* The waveform shape to use for oscillator instruments. Defaults to `sine`.
* @name Highcharts.OscillatorOptionsObject#waveformShape
* @type {string|undefined}
*/
// Default options for Instrument constructor
var defaultOptions = {
type: 'oscillator',
playCallbackInterval: 20,
oscillator: {
waveformShape: 'sine'
}
};
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* The Instrument class. Instrument objects represent an instrument capable of
* playing a certain pitch for a specified duration.
*
* @sample highcharts/sonification/instrument/
* Using Instruments directly
* @sample highcharts/sonification/instrument-advanced/
* Using callbacks for instrument parameters
*
* @requires module:modules/sonification
*
* @class
* @name Highcharts.Instrument
*
* @param {Highcharts.InstrumentOptionsObject} options
* Options for the instrument instance.
*/
function Instrument(options) {
this.init(options);
}
Instrument.prototype.init = function (options) {
if (!this.initAudioContext()) {
error(29);
return;
}
this.options = merge(defaultOptions, options);
this.id = this.options.id = options && options.id || uniqueKey();
// Init the audio nodes
var ctx = H.audioContext;
this.gainNode = ctx.createGain();
this.setGain(0);
this.panNode = ctx.createStereoPanner && ctx.createStereoPanner();
if (this.panNode) {
this.setPan(0);
this.gainNode.connect(this.panNode);
this.panNode.connect(ctx.destination);
}
else {
this.gainNode.connect(ctx.destination);
}
// Oscillator initialization
if (this.options.type === 'oscillator') {
this.initOscillator(this.options.oscillator);
}
// Init timer list
this.playCallbackTimers = [];
};
/**
* Return a copy of an instrument. Only one instrument instance can play at a
* time, so use this to get a new copy of the instrument that can play alongside
* it. The new instrument copy will receive a new ID unless one is supplied in
* options.
*
* @function Highcharts.Instrument#copy
*
* @param {Highcharts.InstrumentOptionsObject} [options]
* Options to merge in for the copy.
*
* @return {Highcharts.Instrument}
* A new Instrument instance with the same options.
*/
Instrument.prototype.copy = function (options) {
return new Instrument(merge(this.options, { id: null }, options));
};
/**
* Init the audio context, if we do not have one.
* @private
* @return {boolean} True if successful, false if not.
*/
Instrument.prototype.initAudioContext = function () {
var Context = H.win.AudioContext || H.win.webkitAudioContext, hasOldContext = !!H.audioContext;
if (Context) {
H.audioContext = H.audioContext || new Context();
if (!hasOldContext &&
H.audioContext &&
H.audioContext.state === 'running') {
H.audioContext.suspend(); // Pause until we need it
}
return !!(H.audioContext &&
H.audioContext.createOscillator &&
H.audioContext.createGain);
}
return false;
};
/**
* Init an oscillator instrument.
* @private
* @param {Highcharts.OscillatorOptionsObject} oscillatorOptions
* The oscillator options passed to Highcharts.Instrument#init.
* @return {void}
*/
Instrument.prototype.initOscillator = function (options) {
var ctx = H.audioContext;
this.oscillator = ctx.createOscillator();
this.oscillator.type = options.waveformShape;
this.oscillator.connect(this.gainNode);
this.oscillatorStarted = false;
};
/**
* Set pan position.
* @private
* @param {number} panValue
* The pan position to set for the instrument.
* @return {void}
*/
Instrument.prototype.setPan = function (panValue) {
if (this.panNode) {
this.panNode.pan.setValueAtTime(panValue, H.audioContext.currentTime);
}
};
/**
* Set gain level. A maximum of 1.2 is allowed before we emit a warning. The
* actual volume is not set above this level regardless of input.
* @private
* @param {number} gainValue
* The gain level to set for the instrument.
* @param {number} [rampTime=0]
* Gradually change the gain level, time given in milliseconds.
* @return {void}
*/
Instrument.prototype.setGain = function (gainValue, rampTime) {
if (this.gainNode) {
if (gainValue > 1.2) {
console.warn(// eslint-disable-line
'Highcharts sonification warning: ' +
'Volume of instrument set too high.');
gainValue = 1.2;
}
if (rampTime) {
this.gainNode.gain.setValueAtTime(this.gainNode.gain.value, H.audioContext.currentTime);
this.gainNode.gain.linearRampToValueAtTime(gainValue, H.audioContext.currentTime + rampTime / 1000);
}
else {
this.gainNode.gain.setValueAtTime(gainValue, H.audioContext.currentTime);
}
}
};
/**
* Cancel ongoing gain ramps.
* @private
* @return {void}
*/
Instrument.prototype.cancelGainRamp = function () {
if (this.gainNode) {
this.gainNode.gain.cancelScheduledValues(0);
}
};
/**
* Get the closest valid frequency for this instrument.
* @private
* @param {number} frequency - The target frequency.
* @param {number} [min] - Minimum frequency to return.
* @param {number} [max] - Maximum frequency to return.
* @return {number} The closest valid frequency to the input frequency.
*/
Instrument.prototype.getValidFrequency = function (frequency, min, max) {
var validFrequencies = this.options.allowedFrequencies, maximum = pick(max, Infinity), minimum = pick(min, -Infinity);
return !validFrequencies || !validFrequencies.length ?
// No valid frequencies for this instrument, return the target
frequency :
// Use the valid frequencies and return the closest match
validFrequencies.reduce(function (acc, cur) {
// Find the closest allowed value
return Math.abs(cur - frequency) < Math.abs(acc - frequency) &&
cur < maximum && cur > minimum ?
cur : acc;
}, Infinity);
};
/**
* Clear existing play callback timers.
* @private
* @return {void}
*/
Instrument.prototype.clearPlayCallbackTimers = function () {
this.playCallbackTimers.forEach(function (timer) {
clearInterval(timer);
});
this.playCallbackTimers = [];
};
/**
* Set the current frequency being played by the instrument. The closest valid
* frequency between the frequency limits is used.
* @param {number} frequency
* The frequency to set.
* @param {Highcharts.Dictionary<number>} [frequencyLimits]
* Object with maxFrequency and minFrequency
* @return {void}
*/
Instrument.prototype.setFrequency = function (frequency, frequencyLimits) {
var limits = frequencyLimits || {}, validFrequency = this.getValidFrequency(frequency, limits.min, limits.max);
if (this.options.type === 'oscillator') {
this.oscillatorPlay(validFrequency);
}
};
/**
* Play oscillator instrument.
* @private
* @param {number} frequency - The frequency to play.
*/
Instrument.prototype.oscillatorPlay = function (frequency) {
if (!this.oscillatorStarted) {
this.oscillator.start();
this.oscillatorStarted = true;
}
this.oscillator.frequency.setValueAtTime(frequency, H.audioContext.currentTime);
};
/**
* Prepare instrument before playing. Resumes the audio context and starts the
* oscillator.
* @private
*/
Instrument.prototype.preparePlay = function () {
this.setGain(0.001);
if (H.audioContext.state === 'suspended') {
H.audioContext.resume();
}
if (this.oscillator && !this.oscillatorStarted) {
this.oscillator.start();
this.oscillatorStarted = true;
}
};
/**
* Play the instrument according to options.
*
* @sample highcharts/sonification/instrument/
* Using Instruments directly
* @sample highcharts/sonification/instrument-advanced/
* Using callbacks for instrument parameters
*
* @function Highcharts.Instrument#play
*
* @param {Highcharts.InstrumentPlayOptionsObject} options
* Options for the playback of the instrument.
*
* @return {void}
*/
Instrument.prototype.play = function (options) {
var instrument = this, duration = options.duration || 0,
// Set a value, or if it is a function, set it continously as a timer.
// Pass in the value/function to set, the setter function, and any
// additional data to pass through to the setter function.
setOrStartTimer = function (value, setter, setterData) {
var target = options.duration, currentDurationIx = 0, callbackInterval = instrument.options.playCallbackInterval;
if (typeof value === 'function') {
var timer = setInterval(function () {
currentDurationIx++;
var curTime = (currentDurationIx * callbackInterval / target);
if (curTime >= 1) {
instrument[setter](value(1), setterData);
clearInterval(timer);
}
else {
instrument[setter](value(curTime), setterData);
}
}, callbackInterval);
instrument.playCallbackTimers.push(timer);
}
else {
instrument[setter](value, setterData);
}
};
if (!instrument.id) {
// No audio support - do nothing
return;
}
// If the AudioContext is suspended we have to resume it before playing
if (H.audioContext.state === 'suspended' ||
this.oscillator && !this.oscillatorStarted) {
instrument.preparePlay();
// Try again in 10ms
setTimeout(function () {
instrument.play(options);
}, 10);
return;
}
// Clear any existing play timers
if (instrument.playCallbackTimers.length) {
instrument.clearPlayCallbackTimers();
}
// Clear any gain ramps
instrument.cancelGainRamp();
// Clear stop oscillator timer
if (instrument.stopOscillatorTimeout) {
clearTimeout(instrument.stopOscillatorTimeout);
delete instrument.stopOscillatorTimeout;
}
// If a note is playing right now, clear the stop timeout, and call the
// callback.
if (instrument.stopTimeout) {
clearTimeout(instrument.stopTimeout);
delete instrument.stopTimeout;
if (instrument.stopCallback) {
// We have a callback for the play we are interrupting. We do not
// allow this callback to start a new play, because that leads to
// chaos. We pass in 'cancelled' to indicate that this note did not
// finish, but still stopped.
instrument._play = instrument.play;
instrument.play = function () { };
instrument.stopCallback('cancelled');
instrument.play = instrument._play;
}
}
// Stop the note without fadeOut if the duration is too short to hear the
// note otherwise.
var immediate = duration < H.sonification.fadeOutDuration + 20;
// Stop the instrument after the duration of the note
instrument.stopCallback = options.onEnd;
var onStop = function () {
delete instrument.stopTimeout;
instrument.stop(immediate);
};
if (duration) {
instrument.stopTimeout = setTimeout(onStop, immediate ? duration :
duration - H.sonification.fadeOutDuration);
// Play the note
setOrStartTimer(options.frequency, 'setFrequency', {
minFrequency: options.minFrequency,
maxFrequency: options.maxFrequency
});
// Set the volume and panning
setOrStartTimer(pick(options.volume, 1), 'setGain', 4); // Slight ramp
setOrStartTimer(pick(options.pan, 0), 'setPan');
}
else {
// No note duration, so just stop immediately
onStop();
}
};
/**
* Mute an instrument that is playing. If the instrument is not currently
* playing, this function does nothing.
*
* @function Highcharts.Instrument#mute
*/
Instrument.prototype.mute = function () {
this.setGain(0.0001, H.sonification.fadeOutDuration * 0.8);
};
/**
* Stop the instrument playing.
*
* @function Highcharts.Instrument#stop
*
* @param {boolean} immediately
* Whether to do the stop immediately or fade out.
*
* @param {Function} [onStopped]
* Callback function to be called when the stop is completed.
*
* @param {*} [callbackData]
* Data to send to the onEnd callback functions.
*
* @return {void}
*/
Instrument.prototype.stop = function (immediately, onStopped, callbackData) {
var instr = this, reset = function () {
// Remove timeout reference
if (instr.stopOscillatorTimeout) {
delete instr.stopOscillatorTimeout;
}
// The oscillator may have stopped in the meantime here, so allow
// this function to fail if so.
try {
instr.oscillator.stop();
}
catch (e) {
// silent error
}
instr.oscillator.disconnect(instr.gainNode);
// We need a new oscillator in order to restart it
instr.initOscillator(instr.options.oscillator);
// Done stopping, call the callback from the stop
if (onStopped) {
onStopped(callbackData);
}
// Call the callback for the play we finished
if (instr.stopCallback) {
instr.stopCallback(callbackData);
}
};
// Clear any existing timers
if (instr.playCallbackTimers.length) {
instr.clearPlayCallbackTimers();
}
if (instr.stopTimeout) {
clearTimeout(instr.stopTimeout);
}
if (immediately) {
instr.setGain(0);
reset();
}
else {
instr.mute();
// Stop the oscillator after the mute fade-out has finished
instr.stopOscillatorTimeout =
setTimeout(reset, H.sonification.fadeOutDuration + 100);
}
};
export default Instrument;

View File

@@ -0,0 +1,606 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* TimelineEvent class definition.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../parts/Globals.js';
import U from '../../parts/Utilities.js';
var merge = U.merge, splat = U.splat, uniqueKey = U.uniqueKey;
/**
* A set of options for the TimelineEvent class.
*
* @requires module:modules/sonification
*
* @private
* @interface Highcharts.TimelineEventOptionsObject
*/ /**
* The object we want to sonify when playing the TimelineEvent. Can be any
* object that implements the `sonify` and `cancelSonify` functions. If this is
* not supplied, the TimelineEvent is considered a silent event, and the onEnd
* event is immediately called.
* @name Highcharts.TimelineEventOptionsObject#eventObject
* @type {*}
*/ /**
* Options to pass on to the eventObject when playing it.
* @name Highcharts.TimelineEventOptionsObject#playOptions
* @type {object|undefined}
*/ /**
* The time at which we want this event to play (in milliseconds offset). This
* is not used for the TimelineEvent.play function, but rather intended as a
* property to decide when to call TimelineEvent.play. Defaults to 0.
* @name Highcharts.TimelineEventOptionsObject#time
* @type {number|undefined}
*/ /**
* Unique ID for the event. Generated automatically if not supplied.
* @name Highcharts.TimelineEventOptionsObject#id
* @type {string|undefined}
*/ /**
* Callback called when the play has finished.
* @name Highcharts.TimelineEventOptionsObject#onEnd
* @type {Function|undefined}
*/
import utilities from './utilities.js';
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* The TimelineEvent class. Represents a sound event on a timeline.
*
* @requires module:modules/sonification
*
* @private
* @class
* @name Highcharts.TimelineEvent
*
* @param {Highcharts.TimelineEventOptionsObject} options
* Options for the TimelineEvent.
*/
function TimelineEvent(options) {
this.init(options || {});
}
TimelineEvent.prototype.init = function (options) {
this.options = options;
this.time = options.time || 0;
this.id = this.options.id = options.id || uniqueKey();
};
/**
* Play the event. Does not take the TimelineEvent.time option into account,
* and plays the event immediately.
*
* @function Highcharts.TimelineEvent#play
*
* @param {Highcharts.TimelineEventOptionsObject} [options]
* Options to pass in to the eventObject when playing it.
*
* @return {void}
*/
TimelineEvent.prototype.play = function (options) {
var eventObject = this.options.eventObject, masterOnEnd = this.options.onEnd, playOnEnd = options && options.onEnd, playOptionsOnEnd = this.options.playOptions &&
this.options.playOptions.onEnd, playOptions = merge(this.options.playOptions, options);
if (eventObject && eventObject.sonify) {
// If we have multiple onEnds defined, use all
playOptions.onEnd = masterOnEnd || playOnEnd || playOptionsOnEnd ?
function () {
var args = arguments;
[masterOnEnd, playOnEnd, playOptionsOnEnd].forEach(function (onEnd) {
if (onEnd) {
onEnd.apply(this, args);
}
});
} : void 0;
eventObject.sonify(playOptions);
}
else {
if (playOnEnd) {
playOnEnd();
}
if (masterOnEnd) {
masterOnEnd();
}
}
};
/**
* Cancel the sonification of this event. Does nothing if the event is not
* currently sonifying.
*
* @function Highcharts.TimelineEvent#cancel
*
* @param {boolean} [fadeOut=false]
* Whether or not to fade out as we stop. If false, the event is
* cancelled synchronously.
*/
TimelineEvent.prototype.cancel = function (fadeOut) {
this.options.eventObject.cancelSonify(fadeOut);
};
/**
* A set of options for the TimelinePath class.
*
* @requires module:modules/
*
* @private
* @interface Highcharts.TimelinePathOptionsObject
*/ /**
* List of TimelineEvents to play on this track.
* @name Highcharts.TimelinePathOptionsObject#events
* @type {Array<Highcharts.TimelineEvent>}
*/ /**
* If this option is supplied, this path ignores all events and just waits for
* the specified number of milliseconds before calling onEnd.
* @name Highcharts.TimelinePathOptionsObject#silentWait
* @type {number|undefined}
*/ /**
* Unique ID for this timeline path. Automatically generated if not supplied.
* @name Highcharts.TimelinePathOptionsObject#id
* @type {string|undefined}
*/ /**
* Callback called before the path starts playing.
* @name Highcharts.TimelinePathOptionsObject#onStart
* @type {Function|undefined}
*/ /**
* Callback function to call before an event plays.
* @name Highcharts.TimelinePathOptionsObject#onEventStart
* @type {Function|undefined}
*/ /**
* Callback function to call after an event has stopped playing.
* @name Highcharts.TimelinePathOptionsObject#onEventEnd
* @type {Function|undefined}
*/ /**
* Callback called when the whole path is finished.
* @name Highcharts.TimelinePathOptionsObject#onEnd
* @type {Function|undefined}
*/
/**
* The TimelinePath class. Represents a track on a timeline with a list of
* sound events to play at certain times relative to each other.
*
* @requires module:modules/sonification
*
* @private
* @class
* @name Highcharts.TimelinePath
*
* @param {Highcharts.TimelinePathOptionsObject} options
* Options for the TimelinePath.
*/
function TimelinePath(options) {
this.init(options);
}
TimelinePath.prototype.init = function (options) {
this.options = options;
this.id = this.options.id = options.id || uniqueKey();
this.cursor = 0;
this.eventsPlaying = {};
// Handle silent wait, otherwise use events from options
this.events = options.silentWait ?
[
new TimelineEvent({ time: 0 }),
new TimelineEvent({ time: options.silentWait })
] :
this.options.events;
// We need to sort our events by time
this.sortEvents();
// Get map from event ID to index
this.updateEventIdMap();
// Signal events to fire
this.signalHandler = new utilities.SignalHandler(['playOnEnd', 'masterOnEnd', 'onStart', 'onEventStart', 'onEventEnd']);
this.signalHandler.registerSignalCallbacks(merge(options, { masterOnEnd: options.onEnd }));
};
/**
* Sort the internal event list by time.
* @private
*/
TimelinePath.prototype.sortEvents = function () {
this.events = this.events.sort(function (a, b) {
return a.time - b.time;
});
};
/**
* Update the internal eventId to index map.
* @private
*/
TimelinePath.prototype.updateEventIdMap = function () {
this.eventIdMap = this.events.reduce(function (acc, cur, i) {
acc[cur.id] = i;
return acc;
}, {});
};
/**
* Add events to the path. Should not be done while the path is playing.
* The new events are inserted according to their time property.
* @private
* @param {Array<Highcharts.TimelineEvent>} newEvents - The new timeline events
* to add.
*/
TimelinePath.prototype.addTimelineEvents = function (newEvents) {
this.events = this.events.concat(newEvents);
this.sortEvents(); // Sort events by time
this.updateEventIdMap(); // Update the event ID to index map
};
/**
* Get the current TimelineEvent under the cursor.
* @private
* @return {Highcharts.TimelineEvent} The current timeline event.
*/
TimelinePath.prototype.getCursor = function () {
return this.events[this.cursor];
};
/**
* Set the current TimelineEvent under the cursor.
* @private
* @param {string} eventId
* The ID of the timeline event to set as current.
* @return {boolean}
* True if there is an event with this ID in the path. False otherwise.
*/
TimelinePath.prototype.setCursor = function (eventId) {
var ix = this.eventIdMap[eventId];
if (typeof ix !== 'undefined') {
this.cursor = ix;
return true;
}
return false;
};
/**
* Play the timeline from the current cursor.
* @private
* @param {Function} onEnd
* Callback to call when play finished. Does not override other onEnd callbacks.
* @return {void}
*/
TimelinePath.prototype.play = function (onEnd) {
this.pause();
this.signalHandler.emitSignal('onStart');
this.signalHandler.clearSignalCallbacks(['playOnEnd']);
this.signalHandler.registerSignalCallbacks({ playOnEnd: onEnd });
this.playEvents(1);
};
/**
* Play the timeline backwards from the current cursor.
* @private
* @param {Function} onEnd
* Callback to call when play finished. Does not override other onEnd callbacks.
* @return {void}
*/
TimelinePath.prototype.rewind = function (onEnd) {
this.pause();
this.signalHandler.emitSignal('onStart');
this.signalHandler.clearSignalCallbacks(['playOnEnd']);
this.signalHandler.registerSignalCallbacks({ playOnEnd: onEnd });
this.playEvents(-1);
};
/**
* Reset the cursor to the beginning.
* @private
*/
TimelinePath.prototype.resetCursor = function () {
this.cursor = 0;
};
/**
* Reset the cursor to the end.
* @private
*/
TimelinePath.prototype.resetCursorEnd = function () {
this.cursor = this.events.length - 1;
};
/**
* Cancel current playing. Leaves the cursor intact.
* @private
* @param {boolean} [fadeOut=false] - Whether or not to fade out as we stop. If
* false, the path is cancelled synchronously.
*/
TimelinePath.prototype.pause = function (fadeOut) {
var timelinePath = this;
// Cancel next scheduled play
clearTimeout(timelinePath.nextScheduledPlay);
// Cancel currently playing events
Object.keys(timelinePath.eventsPlaying).forEach(function (id) {
if (timelinePath.eventsPlaying[id]) {
timelinePath.eventsPlaying[id].cancel(fadeOut);
}
});
timelinePath.eventsPlaying = {};
};
/**
* Play the events, starting from current cursor, and going in specified
* direction.
* @private
* @param {number} direction
* The direction to play, 1 for forwards and -1 for backwards.
* @return {void}
*/
TimelinePath.prototype.playEvents = function (direction) {
var timelinePath = this, curEvent = timelinePath.events[this.cursor], nextEvent = timelinePath.events[this.cursor + direction], timeDiff, onEnd = function (signalData) {
timelinePath.signalHandler.emitSignal('masterOnEnd', signalData);
timelinePath.signalHandler.emitSignal('playOnEnd', signalData);
};
// Store reference to path on event
curEvent.timelinePath = timelinePath;
// Emit event, cancel if returns false
if (timelinePath.signalHandler.emitSignal('onEventStart', curEvent) === false) {
onEnd({
event: curEvent,
cancelled: true
});
return;
}
// Play the current event
timelinePath.eventsPlaying[curEvent.id] = curEvent;
curEvent.play({
onEnd: function (cancelled) {
var signalData = {
event: curEvent,
cancelled: !!cancelled
};
// Keep track of currently playing events for cancelling
delete timelinePath.eventsPlaying[curEvent.id];
// Handle onEventEnd
timelinePath.signalHandler.emitSignal('onEventEnd', signalData);
// Reached end of path?
if (!nextEvent) {
onEnd(signalData);
}
}
});
// Schedule next
if (nextEvent) {
timeDiff = Math.abs(nextEvent.time - curEvent.time);
if (timeDiff < 1) {
// Play immediately
timelinePath.cursor += direction;
timelinePath.playEvents(direction);
}
else {
// Schedule after the difference in ms
this.nextScheduledPlay = setTimeout(function () {
timelinePath.cursor += direction;
timelinePath.playEvents(direction);
}, timeDiff);
}
}
};
/* ************************************************************************** *
* TIMELINE *
* ************************************************************************** */
/**
* A set of options for the Timeline class.
*
* @requires module:modules/sonification
*
* @private
* @interface Highcharts.TimelineOptionsObject
*/ /**
* List of TimelinePaths to play. Multiple paths can be grouped together and
* played simultaneously by supplying an array of paths in place of a single
* path.
* @name Highcharts.TimelineOptionsObject#paths
* @type {Array<(Highcharts.TimelinePath|Array<Highcharts.TimelinePath>)>}
*/ /**
* Callback function to call before a path plays.
* @name Highcharts.TimelineOptionsObject#onPathStart
* @type {Function|undefined}
*/ /**
* Callback function to call after a path has stopped playing.
* @name Highcharts.TimelineOptionsObject#onPathEnd
* @type {Function|undefined}
*/ /**
* Callback called when the whole path is finished.
* @name Highcharts.TimelineOptionsObject#onEnd
* @type {Function|undefined}
*/
/**
* The Timeline class. Represents a sonification timeline with a list of
* timeline paths with events to play at certain times relative to each other.
*
* @requires module:modules/sonification
*
* @private
* @class
* @name Highcharts.Timeline
*
* @param {Highcharts.TimelineOptionsObject} options
* Options for the Timeline.
*/
function Timeline(options) {
this.init(options || {});
}
Timeline.prototype.init = function (options) {
this.options = options;
this.cursor = 0;
this.paths = options.paths;
this.pathsPlaying = {};
this.signalHandler = new utilities.SignalHandler(['playOnEnd', 'masterOnEnd', 'onPathStart', 'onPathEnd']);
this.signalHandler.registerSignalCallbacks(merge(options, { masterOnEnd: options.onEnd }));
};
/**
* Play the timeline forwards from cursor.
* @private
* @param {Function} [onEnd]
* Callback to call when play finished. Does not override other onEnd callbacks.
* @return {void}
*/
Timeline.prototype.play = function (onEnd) {
this.pause();
this.signalHandler.clearSignalCallbacks(['playOnEnd']);
this.signalHandler.registerSignalCallbacks({ playOnEnd: onEnd });
this.playPaths(1);
};
/**
* Play the timeline backwards from cursor.
* @private
* @param {Function} onEnd
* Callback to call when play finished. Does not override other onEnd callbacks.
* @return {void}
*/
Timeline.prototype.rewind = function (onEnd) {
this.pause();
this.signalHandler.clearSignalCallbacks(['playOnEnd']);
this.signalHandler.registerSignalCallbacks({ playOnEnd: onEnd });
this.playPaths(-1);
};
/**
* Play the timeline in the specified direction.
* @private
* @param {number} direction
* Direction to play in. 1 for forwards, -1 for backwards.
* @return {void}
*/
Timeline.prototype.playPaths = function (direction) {
var curPaths = splat(this.paths[this.cursor]), nextPaths = this.paths[this.cursor + direction], timeline = this, signalHandler = this.signalHandler, pathsEnded = 0,
// Play a path
playPath = function (path) {
// Emit signal and set playing state
signalHandler.emitSignal('onPathStart', path);
timeline.pathsPlaying[path.id] = path;
// Do the play
path[direction > 0 ? 'play' : 'rewind'](function (callbackData) {
// Play ended callback
// Data to pass to signal callbacks
var cancelled = callbackData && callbackData.cancelled, signalData = {
path: path,
cancelled: cancelled
};
// Clear state and send signal
delete timeline.pathsPlaying[path.id];
signalHandler.emitSignal('onPathEnd', signalData);
// Handle next paths
pathsEnded++;
if (pathsEnded >= curPaths.length) {
// We finished all of the current paths for cursor.
if (nextPaths && !cancelled) {
// We have more paths, move cursor along
timeline.cursor += direction;
// Reset upcoming path cursors before playing
splat(nextPaths).forEach(function (nextPath) {
nextPath[direction > 0 ? 'resetCursor' : 'resetCursorEnd']();
});
// Play next
timeline.playPaths(direction);
}
else {
// If it is the last path in this direction, call onEnd
signalHandler.emitSignal('playOnEnd', signalData);
signalHandler.emitSignal('masterOnEnd', signalData);
}
}
});
};
// Go through the paths under cursor and play them
curPaths.forEach(function (path) {
if (path) {
// Store reference to timeline
path.timeline = timeline;
// Leave a timeout to let notes fade out before next play
setTimeout(function () {
playPath(path);
}, H.sonification.fadeOutDuration);
}
});
};
/**
* Stop the playing of the timeline. Cancels all current sounds, but does not
* affect the cursor.
* @private
* @param {boolean} [fadeOut=false]
* Whether or not to fade out as we stop. If false, the timeline is cancelled
* synchronously.
* @return {void}
*/
Timeline.prototype.pause = function (fadeOut) {
var timeline = this;
// Cancel currently playing events
Object.keys(timeline.pathsPlaying).forEach(function (id) {
if (timeline.pathsPlaying[id]) {
timeline.pathsPlaying[id].pause(fadeOut);
}
});
timeline.pathsPlaying = {};
};
/**
* Reset the cursor to the beginning of the timeline.
* @private
* @return {void}
*/
Timeline.prototype.resetCursor = function () {
this.paths.forEach(function (paths) {
splat(paths).forEach(function (path) {
path.resetCursor();
});
});
this.cursor = 0;
};
/**
* Reset the cursor to the end of the timeline.
* @private
* @return {void}
*/
Timeline.prototype.resetCursorEnd = function () {
this.paths.forEach(function (paths) {
splat(paths).forEach(function (path) {
path.resetCursorEnd();
});
});
this.cursor = this.paths.length - 1;
};
/**
* Set the current TimelineEvent under the cursor. If multiple paths are being
* played at the same time, this function only affects a single path (the one
* that contains the eventId that is passed in).
* @private
* @param {string} eventId
* The ID of the timeline event to set as current.
* @return {boolean}
* True if the cursor was set, false if no TimelineEvent was found for this ID.
*/
Timeline.prototype.setCursor = function (eventId) {
return this.paths.some(function (paths) {
return splat(paths).some(function (path) {
return path.setCursor(eventId);
});
});
};
/**
* Get the current TimelineEvents under the cursors. This function will return
* the event under the cursor for each currently playing path, as an object
* where the path ID is mapped to the TimelineEvent under that path's cursor.
* @private
* @return {Highcharts.Dictionary<Highcharts.TimelineEvent>}
* The TimelineEvents under each path's cursors.
*/
Timeline.prototype.getCursor = function () {
return this.getCurrentPlayingPaths().reduce(function (acc, cur) {
acc[cur.id] = cur.getCursor();
return acc;
}, {});
};
/**
* Check if timeline is reset or at start.
* @private
* @return {boolean}
* True if timeline is at the beginning.
*/
Timeline.prototype.atStart = function () {
return !this.getCurrentPlayingPaths().some(function (path) {
return path.cursor;
});
};
/**
* Get the current TimelinePaths being played.
* @private
* @return {Array<Highcharts.TimelinePath>}
* The TimelinePaths currently being played.
*/
Timeline.prototype.getCurrentPlayingPaths = function () {
return splat(this.paths[this.cursor]);
};
// Export the classes
var timelineClasses = {
TimelineEvent: TimelineEvent,
TimelinePath: TimelinePath,
Timeline: Timeline
};
export default timelineClasses;

View File

@@ -0,0 +1,930 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Sonification functions for chart/series.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../parts/Globals.js';
/**
* An Earcon configuration, specifying an Earcon and when to play it.
*
* @requires module:modules/sonification
*
* @interface Highcharts.EarconConfiguration
*/ /**
* An Earcon instance.
* @name Highcharts.EarconConfiguration#earcon
* @type {Highcharts.Earcon}
*/ /**
* The ID of the point to play the Earcon on.
* @name Highcharts.EarconConfiguration#onPoint
* @type {string|undefined}
*/ /**
* A function to determine whether or not to play this earcon on a point. The
* function is called for every point, receiving that point as parameter. It
* should return either a boolean indicating whether or not to play the earcon,
* or a new Earcon instance - in which case the new Earcon will be played.
* @name Highcharts.EarconConfiguration#condition
* @type {Function|undefined}
*/
/**
* Options for sonifying a series.
*
* @requires module:modules/sonification
*
* @interface Highcharts.SonifySeriesOptionsObject
*/ /**
* The duration for playing the points. Note that points might continue to play
* after the duration has passed, but no new points will start playing.
* @name Highcharts.SonifySeriesOptionsObject#duration
* @type {number}
*/ /**
* The axis to use for when to play the points. Can be a string with a data
* property (e.g. `x`), or a function. If it is a function, this function
* receives the point as argument, and should return a numeric value. The points
* with the lowest numeric values are then played first, and the time between
* points will be proportional to the distance between the numeric values.
* @name Highcharts.SonifySeriesOptionsObject#pointPlayTime
* @type {string|Function}
*/ /**
* The instrument definitions for the points in this series.
* @name Highcharts.SonifySeriesOptionsObject#instruments
* @type {Array<Highcharts.PointInstrumentObject>}
*/ /**
* Earcons to add to the series.
* @name Highcharts.SonifySeriesOptionsObject#earcons
* @type {Array<Highcharts.EarconConfiguration>|undefined}
*/ /**
* Optionally provide the minimum/maximum data values for the points. If this is
* not supplied, it is calculated from all points in the chart on demand. This
* option is supplied in the following format, as a map of point data properties
* to objects with min/max values:
* ```js
* dataExtremes: {
* y: {
* min: 0,
* max: 100
* },
* z: {
* min: -10,
* max: 10
* }
* // Properties used and not provided are calculated on demand
* }
* ```
* @name Highcharts.SonifySeriesOptionsObject#dataExtremes
* @type {Highcharts.Dictionary<Highcharts.RangeObject>|undefined}
*/ /**
* Callback before a point is played.
* @name Highcharts.SonifySeriesOptionsObject#onPointStart
* @type {Function|undefined}
*/ /**
* Callback after a point has finished playing.
* @name Highcharts.SonifySeriesOptionsObject#onPointEnd
* @type {Function|undefined}
*/ /**
* Callback after the series has played.
* @name Highcharts.SonifySeriesOptionsObject#onEnd
* @type {Function|undefined}
*/
''; // detach doclets above
import Point from '../../parts/Point.js';
import U from '../../parts/Utilities.js';
var find = U.find, isArray = U.isArray, merge = U.merge, pick = U.pick, splat = U.splat;
import utilities from './utilities.js';
/**
* Get the relative time value of a point.
* @private
* @param {Highcharts.Point} point
* The point.
* @param {Function|string} timeProp
* The time axis data prop or the time function.
* @return {number}
* The time value.
*/
function getPointTimeValue(point, timeProp) {
return typeof timeProp === 'function' ?
timeProp(point) :
pick(point[timeProp], point.options[timeProp]);
}
/**
* Get the time extremes of this series. This is handled outside of the
* dataExtremes, as we always want to just sonify the visible points, and we
* always want the extremes to be the extremes of the visible points.
* @private
* @param {Highcharts.Series} series
* The series to compute on.
* @param {Function|string} timeProp
* The time axis data prop or the time function.
* @return {Highcharts.RangeObject}
* Object with min/max extremes for the time values.
*/
function getTimeExtremes(series, timeProp) {
// Compute the extremes from the visible points.
return series.points.reduce(function (acc, point) {
var value = getPointTimeValue(point, timeProp);
acc.min = Math.min(acc.min, value);
acc.max = Math.max(acc.max, value);
return acc;
}, {
min: Infinity,
max: -Infinity
});
}
/**
* Calculate value extremes for used instrument data properties.
* @private
* @param {Highcharts.Chart} chart
* The chart to calculate extremes from.
* @param {Array<Highcharts.PointInstrumentObject>} instruments
* The instrument definitions used.
* @param {Highcharts.Dictionary<Highcharts.RangeObject>} [dataExtremes]
* Predefined extremes for each data prop.
* @return {Highcharts.Dictionary<Highcharts.RangeObject>}
* New extremes with data properties mapped to min/max objects.
*/
function getExtremesForInstrumentProps(chart, instruments, dataExtremes) {
return (instruments || []).reduce(function (newExtremes, instrumentDefinition) {
Object.keys(instrumentDefinition.instrumentMapping || {}).forEach(function (instrumentParameter) {
var value = instrumentDefinition.instrumentMapping[instrumentParameter];
if (typeof value === 'string' && !newExtremes[value]) {
// This instrument parameter is mapped to a data prop.
// If we don't have predefined data extremes, find them.
newExtremes[value] = utilities.calculateDataExtremes(chart, value);
}
});
return newExtremes;
}, merge(dataExtremes));
}
/**
* Get earcons for the point if there are any.
* @private
* @param {Highcharts.Point} point
* The point to find earcons for.
* @param {Array<Highcharts.EarconConfiguration>} earconDefinitions
* Earcons to check.
* @return {Array<Highcharts.Earcon>}
* Array of earcons to be played with this point.
*/
function getPointEarcons(point, earconDefinitions) {
return earconDefinitions.reduce(function (earcons, earconDefinition) {
var cond, earcon = earconDefinition.earcon;
if (earconDefinition.condition) {
// We have a condition. This overrides onPoint
cond = earconDefinition.condition(point);
if (cond instanceof H.sonification.Earcon) {
// Condition returned an earcon
earcons.push(cond);
}
else if (cond) {
// Condition returned true
earcons.push(earcon);
}
}
else if (earconDefinition.onPoint &&
point.id === earconDefinition.onPoint) {
// We have earcon onPoint
earcons.push(earcon);
}
return earcons;
}, []);
}
/**
* Utility function to get a new list of instrument options where all the
* instrument references are copies.
* @private
* @param {Array<Highcharts.PointInstrumentObject>} instruments
* The instrument options.
* @return {Array<Highcharts.PointInstrumentObject>}
* Array of copied instrument options.
*/
function makeInstrumentCopies(instruments) {
return instruments.map(function (instrumentDef) {
var instrument = instrumentDef.instrument, copy = (typeof instrument === 'string' ?
H.sonification.instruments[instrument] :
instrument).copy();
return merge(instrumentDef, { instrument: copy });
});
}
/**
* Create a TimelinePath from a series. Takes the same options as seriesSonify.
* To intuitively allow multiple series to play simultaneously we make copies of
* the instruments for each series.
* @private
* @param {Highcharts.Series} series
* The series to build from.
* @param {Highcharts.SonifySeriesOptionsObject} options
* The options for building the TimelinePath.
* @return {Highcharts.TimelinePath}
* A timeline path with events.
*/
function buildTimelinePathFromSeries(series, options) {
// options.timeExtremes is internal and used so that the calculations from
// chart.sonify can be reused.
var timeExtremes = options.timeExtremes || getTimeExtremes(series, options.pointPlayTime),
// Get time offset for a point, relative to duration
pointToTime = function (point) {
return utilities.virtualAxisTranslate(getPointTimeValue(point, options.pointPlayTime), timeExtremes, { min: 0, max: options.duration });
},
// Compute any data extremes that aren't defined yet
dataExtremes = getExtremesForInstrumentProps(series.chart, options.instruments, options.dataExtremes),
// Make copies of the instruments used for this series, to allow
// multiple series with the same instrument to play together
instruments = makeInstrumentCopies(options.instruments),
// Go through the points, convert to events, optionally add Earcons
timelineEvents = series.points.reduce(function (events, point) {
var earcons = getPointEarcons(point, options.earcons || []), time = pointToTime(point);
return events.concat(
// Event object for point
new H.sonification.TimelineEvent({
eventObject: point,
time: time,
id: point.id,
playOptions: {
instruments: instruments,
dataExtremes: dataExtremes
}
}),
// Earcons
earcons.map(function (earcon) {
return new H.sonification.TimelineEvent({
eventObject: earcon,
time: time
});
}));
}, []);
// Build the timeline path
return new H.sonification.TimelinePath({
events: timelineEvents,
onStart: function () {
if (options.onStart) {
options.onStart(series);
}
},
onEventStart: function (event) {
var eventObject = event.options && event.options.eventObject;
if (eventObject instanceof Point) {
// Check for hidden series
if (!eventObject.series.visible &&
!eventObject.series.chart.series.some(function (series) {
return series.visible;
})) {
// We have no visible series, stop the path.
event.timelinePath.timeline.pause();
event.timelinePath.timeline.resetCursor();
return false;
}
// Emit onPointStart
if (options.onPointStart) {
options.onPointStart(event, eventObject);
}
}
},
onEventEnd: function (eventData) {
var eventObject = eventData.event && eventData.event.options &&
eventData.event.options.eventObject;
if (eventObject instanceof Point && options.onPointEnd) {
options.onPointEnd(eventData.event, eventObject);
}
},
onEnd: function () {
if (options.onEnd) {
options.onEnd(series);
}
}
});
}
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* Sonify a series.
*
* @sample highcharts/sonification/series-basic/
* Click on series to sonify
* @sample highcharts/sonification/series-earcon/
* Series with earcon
* @sample highcharts/sonification/point-play-time/
* Play y-axis by time
* @sample highcharts/sonification/earcon-on-point/
* Earcon set on point
*
* @requires module:modules/sonification
*
* @function Highcharts.Series#sonify
*
* @param {Highcharts.SonifySeriesOptionsObject} options
* The options for sonifying this series.
*
* @return {void}
*/
function seriesSonify(options) {
var timelinePath = buildTimelinePathFromSeries(this, options), chartSonification = this.chart.sonification;
// Only one timeline can play at a time. If we want multiple series playing
// at the same time, use chart.sonify.
if (chartSonification.timeline) {
chartSonification.timeline.pause();
}
// Store reference to duration
chartSonification.duration = options.duration;
// Create new timeline for this series, and play it.
chartSonification.timeline = new H.sonification.Timeline({
paths: [timelinePath]
});
chartSonification.timeline.play();
}
/**
* Utility function to assemble options for creating a TimelinePath from a
* series when sonifying an entire chart.
* @private
* @param {Highcharts.Series} series
* The series to return options for.
* @param {Highcharts.RangeObject} dataExtremes
* Pre-calculated data extremes for the chart.
* @param {Highcharts.SonificationOptions} chartSonifyOptions
* Options passed in to chart.sonify.
* @return {Partial<Highcharts.SonifySeriesOptionsObject>}
* Options for buildTimelinePathFromSeries.
*/
function buildSeriesOptions(series, dataExtremes, chartSonifyOptions) {
var seriesOptions = chartSonifyOptions.seriesOptions || {};
return merge({
// Calculated dataExtremes for chart
dataExtremes: dataExtremes,
// We need to get timeExtremes for each series. We pass this
// in when building the TimelinePath objects to avoid
// calculating twice.
timeExtremes: getTimeExtremes(series, chartSonifyOptions.pointPlayTime),
// Some options we just pass on
instruments: chartSonifyOptions.instruments,
onStart: chartSonifyOptions.onSeriesStart,
onEnd: chartSonifyOptions.onSeriesEnd,
earcons: chartSonifyOptions.earcons
},
// Merge in the specific series options by ID
isArray(seriesOptions) ? (find(seriesOptions, function (optEntry) {
return optEntry.id === pick(series.id, series.options.id);
}) || {}) : seriesOptions, {
// Forced options
pointPlayTime: chartSonifyOptions.pointPlayTime
});
}
/**
* Utility function to normalize the ordering of timeline paths when sonifying
* a chart.
* @private
* @param {string|Array<string|Highcharts.Earcon|Array<string|Highcharts.Earcon>>} orderOptions -
* Order options for the sonification.
* @param {Highcharts.Chart} chart - The chart we are sonifying.
* @param {Function} seriesOptionsCallback
* A function that takes a series as argument, and returns the series options
* for that series to be used with buildTimelinePathFromSeries.
* @return {Array<object|Array<object|Highcharts.TimelinePath>>} If order is
* sequential, we return an array of objects to create series paths from. If
* order is simultaneous we return an array of an array with the same. If there
* is a custom order, we return an array of arrays of either objects (for
* series) or TimelinePaths (for earcons and delays).
*/
function buildPathOrder(orderOptions, chart, seriesOptionsCallback) {
var order;
if (orderOptions === 'sequential' || orderOptions === 'simultaneous') {
// Just add the series from the chart
order = chart.series.reduce(function (seriesList, series) {
if (series.visible) {
seriesList.push({
series: series,
seriesOptions: seriesOptionsCallback(series)
});
}
return seriesList;
}, []);
// If order is simultaneous, group all series together
if (orderOptions === 'simultaneous') {
order = [order];
}
}
else {
// We have a specific order, and potentially custom items - like
// earcons or silent waits.
order = orderOptions.reduce(function (orderList, orderDef) {
// Return set of items to play simultaneously. Could be only one.
var simulItems = splat(orderDef).reduce(function (items, item) {
var itemObject;
// Is this item a series ID?
if (typeof item === 'string') {
var series = chart.get(item);
if (series.visible) {
itemObject = {
series: series,
seriesOptions: seriesOptionsCallback(series)
};
}
// Is it an earcon? If so, just create the path.
}
else if (item instanceof H.sonification.Earcon) {
// Path with a single event
itemObject = new H.sonification.TimelinePath({
events: [new H.sonification.TimelineEvent({
eventObject: item
})]
});
}
// Is this item a silent wait? If so, just create the path.
if (item.silentWait) {
itemObject = new H.sonification.TimelinePath({
silentWait: item.silentWait
});
}
// Add to items to play simultaneously
if (itemObject) {
items.push(itemObject);
}
return items;
}, []);
// Add to order list
if (simulItems.length) {
orderList.push(simulItems);
}
return orderList;
}, []);
}
return order;
}
/**
* Utility function to add a silent wait after all series.
* @private
* @param {Array<object|Array<object|TimelinePath>>} order
* The order of items.
* @param {number} wait
* The wait in milliseconds to add.
* @return {Array<object|Array<object|TimelinePath>>}
* The order with waits inserted.
*/
function addAfterSeriesWaits(order, wait) {
if (!wait) {
return order;
}
return order.reduce(function (newOrder, orderDef, i) {
var simultaneousPaths = splat(orderDef);
newOrder.push(simultaneousPaths);
// Go through the simultaneous paths and see if there is a series there
if (i < order.length - 1 && // Do not add wait after last series
simultaneousPaths.some(function (item) {
return item.series;
})) {
// We have a series, meaning we should add a wait after these
// paths have finished.
newOrder.push(new H.sonification.TimelinePath({
silentWait: wait
}));
}
return newOrder;
}, []);
}
/**
* Utility function to find the total amout of wait time in the TimelinePaths.
* @private
* @param {Array<object|Array<object|TimelinePath>>} order - The order of
* TimelinePaths/items.
* @return {number} The total time in ms spent on wait paths between playing.
*/
function getWaitTime(order) {
return order.reduce(function (waitTime, orderDef) {
var def = splat(orderDef);
return waitTime + (def.length === 1 &&
def[0].options &&
def[0].options.silentWait || 0);
}, 0);
}
/**
* Utility function to ensure simultaneous paths have start/end events at the
* same time, to sync them.
* @private
* @param {Array<Highcharts.TimelinePath>} paths - The paths to sync.
*/
function syncSimultaneousPaths(paths) {
// Find the extremes for these paths
var extremes = paths.reduce(function (extremes, path) {
var events = path.events;
if (events && events.length) {
extremes.min = Math.min(events[0].time, extremes.min);
extremes.max = Math.max(events[events.length - 1].time, extremes.max);
}
return extremes;
}, {
min: Infinity,
max: -Infinity
});
// Go through the paths and add events to make them fit the same timespan
paths.forEach(function (path) {
var events = path.events, hasEvents = events && events.length, eventsToAdd = [];
if (!(hasEvents && events[0].time <= extremes.min)) {
eventsToAdd.push(new H.sonification.TimelineEvent({
time: extremes.min
}));
}
if (!(hasEvents && events[events.length - 1].time >= extremes.max)) {
eventsToAdd.push(new H.sonification.TimelineEvent({
time: extremes.max
}));
}
if (eventsToAdd.length) {
path.addTimelineEvents(eventsToAdd);
}
});
}
/**
* Utility function to find the total duration span for all simul path sets
* that include series.
* @private
* @param {Array<object|Array<object|Highcharts.TimelinePath>>} order - The
* order of TimelinePaths/items.
* @return {number} The total time value span difference for all series.
*/
function getSimulPathDurationTotal(order) {
return order.reduce(function (durationTotal, orderDef) {
return durationTotal + splat(orderDef).reduce(function (maxPathDuration, item) {
var timeExtremes = (item.series &&
item.seriesOptions &&
item.seriesOptions.timeExtremes);
return timeExtremes ?
Math.max(maxPathDuration, timeExtremes.max - timeExtremes.min) : maxPathDuration;
}, 0);
}, 0);
}
/**
* Function to calculate the duration in ms for a series.
* @private
* @param {number} seriesValueDuration - The duration of the series in value
* difference.
* @param {number} totalValueDuration - The total duration of all (non
* simultaneous) series in value difference.
* @param {number} totalDurationMs - The desired total duration for all series
* in milliseconds.
* @return {number} The duration for the series in milliseconds.
*/
function getSeriesDurationMs(seriesValueDuration, totalValueDuration, totalDurationMs) {
// A series spanning the whole chart would get the full duration.
return utilities.virtualAxisTranslate(seriesValueDuration, { min: 0, max: totalValueDuration }, { min: 0, max: totalDurationMs });
}
/**
* Convert series building objects into paths and return a new list of
* TimelinePaths.
* @private
* @param {Array<object|Array<object|Highcharts.TimelinePath>>} order - The
* order list.
* @param {number} duration - Total duration to aim for in milliseconds.
* @return {Array<Array<Highcharts.TimelinePath>>} Array of TimelinePath objects
* to play.
*/
function buildPathsFromOrder(order, duration) {
// Find time used for waits (custom or after series), and subtract it from
// available duration.
var totalAvailableDurationMs = Math.max(duration - getWaitTime(order), 0),
// Add up simultaneous path durations to find total value span duration
// of everything
totalUsedDuration = getSimulPathDurationTotal(order);
// Go through the order list and convert the items
return order.reduce(function (allPaths, orderDef) {
var simultaneousPaths = splat(orderDef).reduce(function (simulPaths, item) {
if (item instanceof H.sonification.TimelinePath) {
// This item is already a path object
simulPaths.push(item);
}
else if (item.series) {
// We have a series.
// We need to set the duration of the series
item.seriesOptions.duration =
item.seriesOptions.duration || getSeriesDurationMs(item.seriesOptions.timeExtremes.max -
item.seriesOptions.timeExtremes.min, totalUsedDuration, totalAvailableDurationMs);
// Add the path
simulPaths.push(buildTimelinePathFromSeries(item.series, item.seriesOptions));
}
return simulPaths;
}, []);
// Add in the simultaneous paths
allPaths.push(simultaneousPaths);
return allPaths;
}, []);
}
/**
* @private
* @param {Highcharts.Chart} chart The chart to get options for.
* @param {Highcharts.SonificationOptions} userOptions
* Options to merge with options on chart and default options.
* @returns {Highcharts.SonificationOptions} The merged options.
*/
function getChartSonifyOptions(chart, userOptions) {
return merge(chart.options.sonification, userOptions);
}
/**
* Options for sonifying a chart.
*
* @requires module:modules/sonification
*
* @interface Highcharts.SonificationOptions
*/ /**
* Duration for sonifying the entire chart. The duration is distributed across
* the different series intelligently, but does not take earcons into account.
* It is also possible to set the duration explicitly per series, using
* `seriesOptions`. Note that points may continue to play after the duration has
* passed, but no new points will start playing.
* @name Highcharts.SonificationOptions#duration
* @type {number}
*/ /**
* Define the order to play the series in. This can be given as a string, or an
* array specifying a custom ordering. If given as a string, valid values are
* `sequential` - where each series is played in order - or `simultaneous`,
* where all series are played at once. For custom ordering, supply an array as
* the order. Each element in the array can be either a string with a series ID,
* an Earcon object, or an object with a numeric `silentWait` property
* designating a number of milliseconds to wait before continuing. Each element
* of the array will be played in order. To play elements simultaneously, group
* the elements in an array.
* @name Highcharts.SonificationOptions#order
* @type {string|Array<string|Highcharts.Earcon|Array<string|Highcharts.Earcon>>}
*/ /**
* The axis to use for when to play the points. Can be a string with a data
* property (e.g. `x`), or a function. If it is a function, this function
* receives the point as argument, and should return a numeric value. The points
* with the lowest numeric values are then played first, and the time between
* points will be proportional to the distance between the numeric values. This
* option can not be overridden per series.
* @name Highcharts.SonificationOptions#pointPlayTime
* @type {string|Function}
*/ /**
* Milliseconds of silent waiting to add between series. Note that waiting time
* is considered part of the sonify duration.
* @name Highcharts.SonificationOptions#afterSeriesWait
* @type {number|undefined}
*/ /**
* Options as given to `series.sonify` to override options per series. If the
* option is supplied as an array of options objects, the `id` property of the
* object should correspond to the series' id. If the option is supplied as a
* single object, the options apply to all series.
* @name Highcharts.SonificationOptions#seriesOptions
* @type {Object|Array<object>|undefined}
*/ /**
* The instrument definitions for the points in this chart.
* @name Highcharts.SonificationOptions#instruments
* @type {Array<Highcharts.PointInstrumentObject>|undefined}
*/ /**
* Earcons to add to the chart. Note that earcons can also be added per series
* using `seriesOptions`.
* @name Highcharts.SonificationOptions#earcons
* @type {Array<Highcharts.EarconConfiguration>|undefined}
*/ /**
* Optionally provide the minimum/maximum data values for the points. If this is
* not supplied, it is calculated from all points in the chart on demand. This
* option is supplied in the following format, as a map of point data properties
* to objects with min/max values:
* ```js
* dataExtremes: {
* y: {
* min: 0,
* max: 100
* },
* z: {
* min: -10,
* max: 10
* }
* // Properties used and not provided are calculated on demand
* }
* ```
* @name Highcharts.SonificationOptions#dataExtremes
* @type {Highcharts.Dictionary<Highcharts.RangeObject>|undefined}
*/ /**
* Callback before a series is played.
* @name Highcharts.SonificationOptions#onSeriesStart
* @type {Function|undefined}
*/ /**
* Callback after a series has finished playing.
* @name Highcharts.SonificationOptions#onSeriesEnd
* @type {Function|undefined}
*/ /**
* Callback after the chart has played.
* @name Highcharts.SonificationOptions#onEnd
* @type {Function|undefined}
*/
/**
* Sonify a chart.
*
* @sample highcharts/sonification/chart-sequential/
* Sonify a basic chart
* @sample highcharts/sonification/chart-simultaneous/
* Sonify series simultaneously
* @sample highcharts/sonification/chart-custom-order/
* Custom defined order of series
* @sample highcharts/sonification/chart-earcon/
* Earcons on chart
* @sample highcharts/sonification/chart-events/
* Sonification events on chart
*
* @requires module:modules/sonification
*
* @function Highcharts.Chart#sonify
*
* @param {Highcharts.SonificationOptions} options
* The options for sonifying this chart.
*
* @return {void}
*/
function chartSonify(options) {
var opts = getChartSonifyOptions(this, options);
if (opts.enabled === false) {
return;
}
// Only one timeline can play at a time.
if (this.sonification.timeline) {
this.sonification.timeline.pause();
}
// Store reference to duration
this.sonification.duration = opts.duration;
// Calculate data extremes for the props used
var dataExtremes = getExtremesForInstrumentProps(this, opts.instruments, opts.dataExtremes);
// Figure out ordering of series and custom paths
var order = buildPathOrder(opts.order, this, function (series) {
return buildSeriesOptions(series, dataExtremes, opts);
});
// Add waits after simultaneous paths with series in them.
order = addAfterSeriesWaits(order, opts.afterSeriesWait || 0);
// We now have a list of either TimelinePath objects or series that need to
// be converted to TimelinePath objects. Convert everything to paths.
var paths = buildPathsFromOrder(order, opts.duration);
// Sync simultaneous paths
paths.forEach(function (simultaneousPaths) {
syncSimultaneousPaths(simultaneousPaths);
});
// We have a set of paths. Create the timeline, and play it.
this.sonification.timeline = new H.sonification.Timeline({
paths: paths,
onEnd: opts.onEnd
});
this.sonification.timeline.play();
}
/**
* Get a list of the points currently under cursor.
*
* @requires module:modules/sonification
*
* @function Highcharts.Chart#getCurrentSonifyPoints
*
* @return {Array<Highcharts.Point>}
* The points currently under the cursor.
*/
function getCurrentPoints() {
var cursorObj;
if (this.sonification.timeline) {
cursorObj = this.sonification.timeline.getCursor(); // Cursor per pathID
return Object.keys(cursorObj).map(function (path) {
// Get the event objects under cursor for each path
return cursorObj[path].eventObject;
}).filter(function (eventObj) {
// Return the events that are points
return eventObj instanceof Point;
});
}
return [];
}
/**
* Set the cursor to a point or set of points in different series.
*
* @requires module:modules/sonification
*
* @function Highcharts.Chart#setSonifyCursor
*
* @param {Highcharts.Point|Array<Highcharts.Point>} points
* The point or points to set the cursor to. If setting multiple points
* under the cursor, the points have to be in different series that are
* being played simultaneously.
*/
function setCursor(points) {
var timeline = this.sonification.timeline;
if (timeline) {
splat(points).forEach(function (point) {
// We created the events with the ID of the points, which makes
// this easy. Just call setCursor for each ID.
timeline.setCursor(point.id);
});
}
}
/**
* Pause the running sonification.
*
* @requires module:modules/sonification
*
* @function Highcharts.Chart#pauseSonify
*
* @param {boolean} [fadeOut=true]
* Fade out as we pause to avoid clicks.
*
* @return {void}
*/
function pause(fadeOut) {
if (this.sonification.timeline) {
this.sonification.timeline.pause(pick(fadeOut, true));
}
else if (this.sonification.currentlyPlayingPoint) {
this.sonification.currentlyPlayingPoint.cancelSonify(fadeOut);
}
}
/**
* Resume the currently running sonification. Requires series.sonify or
* chart.sonify to have been played at some point earlier.
*
* @requires module:modules/sonification
*
* @function Highcharts.Chart#resumeSonify
*
* @param {Function} onEnd
* Callback to call when play finished.
*
* @return {void}
*/
function resume(onEnd) {
if (this.sonification.timeline) {
this.sonification.timeline.play(onEnd);
}
}
/**
* Play backwards from cursor. Requires series.sonify or chart.sonify to have
* been played at some point earlier.
*
* @requires module:modules/sonification
*
* @function Highcharts.Chart#rewindSonify
*
* @param {Function} onEnd
* Callback to call when play finished.
*
* @return {void}
*/
function rewind(onEnd) {
if (this.sonification.timeline) {
this.sonification.timeline.rewind(onEnd);
}
}
/**
* Cancel current sonification and reset cursor.
*
* @requires module:modules/sonification
*
* @function Highcharts.Chart#cancelSonify
*
* @param {boolean} [fadeOut=true]
* Fade out as we pause to avoid clicks.
*
* @return {void}
*/
function cancel(fadeOut) {
this.pauseSonify(fadeOut);
this.resetSonifyCursor();
}
/**
* Reset cursor to start. Requires series.sonify or chart.sonify to have been
* played at some point earlier.
*
* @requires module:modules/sonification
*
* @function Highcharts.Chart#resetSonifyCursor
*
* @return {void}
*/
function resetCursor() {
if (this.sonification.timeline) {
this.sonification.timeline.resetCursor();
}
}
/**
* Reset cursor to end. Requires series.sonify or chart.sonify to have been
* played at some point earlier.
*
* @requires module:modules/sonification
*
* @function Highcharts.Chart#resetSonifyCursorEnd
*
* @return {void}
*/
function resetCursorEnd() {
if (this.sonification.timeline) {
this.sonification.timeline.resetCursorEnd();
}
}
// Export functions
var chartSonifyFunctions = {
chartSonify: chartSonify,
seriesSonify: seriesSonify,
pause: pause,
resume: resume,
rewind: rewind,
cancel: cancel,
getCurrentPoints: getCurrentPoints,
setCursor: setCursor,
resetCursor: resetCursor,
resetCursorEnd: resetCursorEnd
};
export default chartSonifyFunctions;

View File

@@ -0,0 +1,32 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Instrument definitions for sonification module.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import Instrument from './Instrument.js';
import utilities from './utilities.js';
var instruments = {};
['sine', 'square', 'triangle', 'sawtooth'].forEach(function (waveform) {
// Add basic instruments
instruments[waveform] = new Instrument({
oscillator: { waveformShape: waveform }
});
// Add musical instruments
instruments[waveform + 'Musical'] = new Instrument({
allowedFrequencies: utilities.musicalFrequencies,
oscillator: { waveformShape: waveform }
});
// Add scaled instruments
instruments[waveform + 'Major'] = new Instrument({
allowedFrequencies: utilities.getMusicalScale([1, 3, 5, 6, 8, 10, 12]),
oscillator: { waveformShape: waveform }
});
});
export default instruments;

View File

@@ -0,0 +1,112 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* List of musical frequencies from C0 to C8.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
var frequencies = [
16.351597831287414,
17.323914436054505,
18.354047994837977,
19.445436482630058,
20.601722307054366,
21.826764464562746,
23.12465141947715,
24.499714748859326,
25.956543598746574,
27.5,
29.13523509488062,
30.86770632850775,
32.70319566257483,
34.64782887210901,
36.70809598967594,
38.890872965260115,
41.20344461410875,
43.653528929125486,
46.2493028389543,
48.999429497718666,
51.91308719749314,
55,
58.27047018976124,
61.7354126570155,
65.40639132514966,
69.29565774421802,
73.41619197935188,
77.78174593052023,
82.4068892282175,
87.30705785825097,
92.4986056779086,
97.99885899543733,
103.82617439498628,
110,
116.54094037952248,
123.47082531403103,
130.8127826502993,
138.59131548843604,
146.8323839587038,
155.56349186104046,
164.81377845643496,
174.61411571650194,
184.9972113558172,
195.99771799087463,
207.65234878997256,
220,
233.08188075904496,
246.94165062806206,
261.6255653005986,
277.1826309768721,
293.6647679174076,
311.1269837220809,
329.6275569128699,
349.2282314330039,
369.9944227116344,
391.99543598174927,
415.3046975799451,
440,
466.1637615180899,
493.8833012561241,
523.2511306011972,
554.3652619537442,
587.3295358348151,
622.2539674441618,
659.2551138257398,
698.4564628660078,
739.9888454232688,
783.9908719634985,
830.6093951598903,
880,
932.3275230361799,
987.7666025122483,
1046.5022612023945,
1108.7305239074883,
1174.6590716696303,
1244.5079348883237,
1318.5102276514797,
1396.9129257320155,
1479.9776908465376,
1567.981743926997,
1661.2187903197805,
1760,
1864.6550460723597,
1975.533205024496,
2093.004522404789,
2217.4610478149766,
2349.31814333926,
2489.0158697766474,
2637.02045530296,
2793.825851464031,
2959.955381693075,
3135.9634878539946,
3322.437580639561,
3520,
3729.3100921447194,
3951.066410048992,
4186.009044809578 // C8
];
export default frequencies;

View File

@@ -0,0 +1,36 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Default options for sonification.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
// Experimental, disabled by default, not exposed in API
var options = {
sonification: {
enabled: false,
duration: 2000,
afterSeriesWait: 1000,
order: 'sequential',
pointPlayTime: 'x',
instruments: [{
instrument: 'sineMusical',
instrumentMapping: {
duration: 400,
frequency: 'y',
volume: 0.7
},
// Start at G4 note, end at C6
instrumentOptions: {
minFrequency: 392,
maxFrequency: 1046
}
}]
}
};
export default options;

View File

@@ -0,0 +1,321 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Code for sonifying single points.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../parts/Globals.js';
import U from '../../parts/Utilities.js';
var error = U.error, merge = U.merge, pick = U.pick;
/**
* Define the parameter mapping for an instrument.
*
* @requires module:modules/sonification
*
* @interface Highcharts.PointInstrumentMappingObject
*/ /**
* Define the volume of the instrument. This can be a string with a data
* property name, e.g. `'y'`, in which case this data property is used to define
* the volume relative to the `y`-values of the other points. A higher `y` value
* would then result in a higher volume. This option can also be a fixed number
* or a function. If it is a function, this function is called in regular
* intervals while the note is playing. It receives three arguments: The point,
* the dataExtremes, and the current relative time - where 0 is the beginning of
* the note and 1 is the end. The function should return the volume of the note
* as a number between 0 and 1.
* @name Highcharts.PointInstrumentMappingObject#volume
* @type {string|number|Function}
*/ /**
* Define the duration of the notes for this instrument. This can be a string
* with a data property name, e.g. `'y'`, in which case this data property is
* used to define the duration relative to the `y`-values of the other points. A
* higher `y` value would then result in a longer duration. This option can also
* be a fixed number or a function. If it is a function, this function is called
* once before the note starts playing, and should return the duration in
* milliseconds. It receives two arguments: The point, and the dataExtremes.
* @name Highcharts.PointInstrumentMappingObject#duration
* @type {string|number|Function}
*/ /**
* Define the panning of the instrument. This can be a string with a data
* property name, e.g. `'x'`, in which case this data property is used to define
* the panning relative to the `x`-values of the other points. A higher `x`
* value would then result in a higher panning value (panned further to the
* right). This option can also be a fixed number or a function. If it is a
* function, this function is called in regular intervals while the note is
* playing. It receives three arguments: The point, the dataExtremes, and the
* current relative time - where 0 is the beginning of the note and 1 is the
* end. The function should return the panning of the note as a number between
* -1 and 1.
* @name Highcharts.PointInstrumentMappingObject#pan
* @type {string|number|Function|undefined}
*/ /**
* Define the frequency of the instrument. This can be a string with a data
* property name, e.g. `'y'`, in which case this data property is used to define
* the frequency relative to the `y`-values of the other points. A higher `y`
* value would then result in a higher frequency. This option can also be a
* fixed number or a function. If it is a function, this function is called in
* regular intervals while the note is playing. It receives three arguments:
* The point, the dataExtremes, and the current relative time - where 0 is the
* beginning of the note and 1 is the end. The function should return the
* frequency of the note as a number (in Hz).
* @name Highcharts.PointInstrumentMappingObject#frequency
* @type {string|number|Function}
*/
/**
* @requires module:modules/sonification
*
* @interface Highcharts.PointInstrumentOptionsObject
*/ /**
* The minimum duration for a note when using a data property for duration. Can
* be overridden by using either a fixed number or a function for
* instrumentMapping.duration. Defaults to 20.
* @name Highcharts.PointInstrumentOptionsObject#minDuration
* @type {number|undefined}
*/ /**
* The maximum duration for a note when using a data property for duration. Can
* be overridden by using either a fixed number or a function for
* instrumentMapping.duration. Defaults to 2000.
* @name Highcharts.PointInstrumentOptionsObject#maxDuration
* @type {number|undefined}
*/ /**
* The minimum pan value for a note when using a data property for panning. Can
* be overridden by using either a fixed number or a function for
* instrumentMapping.pan. Defaults to -1 (fully left).
* @name Highcharts.PointInstrumentOptionsObject#minPan
* @type {number|undefined}
*/ /**
* The maximum pan value for a note when using a data property for panning. Can
* be overridden by using either a fixed number or a function for
* instrumentMapping.pan. Defaults to 1 (fully right).
* @name Highcharts.PointInstrumentOptionsObject#maxPan
* @type {number|undefined}
*/ /**
* The minimum volume for a note when using a data property for volume. Can be
* overridden by using either a fixed number or a function for
* instrumentMapping.volume. Defaults to 0.1.
* @name Highcharts.PointInstrumentOptionsObject#minVolume
* @type {number|undefined}
*/ /**
* The maximum volume for a note when using a data property for volume. Can be
* overridden by using either a fixed number or a function for
* instrumentMapping.volume. Defaults to 1.
* @name Highcharts.PointInstrumentOptionsObject#maxVolume
* @type {number|undefined}
*/ /**
* The minimum frequency for a note when using a data property for frequency.
* Can be overridden by using either a fixed number or a function for
* instrumentMapping.frequency. Defaults to 220.
* @name Highcharts.PointInstrumentOptionsObject#minFrequency
* @type {number|undefined}
*/ /**
* The maximum frequency for a note when using a data property for frequency.
* Can be overridden by using either a fixed number or a function for
* instrumentMapping.frequency. Defaults to 2200.
* @name Highcharts.PointInstrumentOptionsObject#maxFrequency
* @type {number|undefined}
*/
/**
* An instrument definition for a point, specifying the instrument to play and
* how to play it.
*
* @interface Highcharts.PointInstrumentObject
*/ /**
* An Instrument instance or the name of the instrument in the
* Highcharts.sonification.instruments map.
* @name Highcharts.PointInstrumentObject#instrument
* @type {Highcharts.Instrument|string}
*/ /**
* Mapping of instrument parameters for this instrument.
* @name Highcharts.PointInstrumentObject#instrumentMapping
* @type {Highcharts.PointInstrumentMappingObject}
*/ /**
* Options for this instrument.
* @name Highcharts.PointInstrumentObject#instrumentOptions
* @type {Highcharts.PointInstrumentOptionsObject|undefined}
*/ /**
* Callback to call when the instrument has stopped playing.
* @name Highcharts.PointInstrumentObject#onEnd
* @type {Function|undefined}
*/
/**
* Options for sonifying a point.
* @interface Highcharts.PointSonifyOptionsObject
*/ /**
* The instrument definitions for this point.
* @name Highcharts.PointSonifyOptionsObject#instruments
* @type {Array<Highcharts.PointInstrumentObject>}
*/ /**
* Optionally provide the minimum/maximum values for the points. If this is not
* supplied, it is calculated from the points in the chart on demand. This
* option is supplied in the following format, as a map of point data properties
* to objects with min/max values:
* ```js
* dataExtremes: {
* y: {
* min: 0,
* max: 100
* },
* z: {
* min: -10,
* max: 10
* }
* // Properties used and not provided are calculated on demand
* }
* ```
* @name Highcharts.PointSonifyOptionsObject#dataExtremes
* @type {object|undefined}
*/ /**
* Callback called when the sonification has finished.
* @name Highcharts.PointSonifyOptionsObject#onEnd
* @type {Function|undefined}
*/
import utilities from './utilities.js';
// Defaults for the instrument options
// NOTE: Also change defaults in Highcharts.PointInstrumentOptionsObject if
// making changes here.
var defaultInstrumentOptions = {
minDuration: 20,
maxDuration: 2000,
minVolume: 0.1,
maxVolume: 1,
minPan: -1,
maxPan: 1,
minFrequency: 220,
maxFrequency: 2200
};
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* Sonify a single point.
*
* @sample highcharts/sonification/point-basic/
* Click on points to sonify
* @sample highcharts/sonification/point-advanced/
* Sonify bubbles
*
* @requires module:modules/sonification
*
* @function Highcharts.Point#sonify
*
* @param {Highcharts.PointSonifyOptionsObject} options
* Options for the sonification of the point.
*
* @return {void}
*/
function pointSonify(options) {
var point = this, chart = point.series.chart, dataExtremes = options.dataExtremes || {},
// Get the value to pass to instrument.play from the mapping value
// passed in.
getMappingValue = function (value, makeFunction, allowedExtremes) {
// Function. Return new function if we try to use callback,
// otherwise call it now and return result.
if (typeof value === 'function') {
return makeFunction ?
function (time) {
return value(point, dataExtremes, time);
} :
value(point, dataExtremes);
}
// String, this is a data prop.
if (typeof value === 'string') {
// Find data extremes if we don't have them
dataExtremes[value] = dataExtremes[value] ||
utilities.calculateDataExtremes(point.series.chart, value);
// Find the value
return utilities.virtualAxisTranslate(pick(point[value], point.options[value]), dataExtremes[value], allowedExtremes);
}
// Fixed number or something else weird, just use that
return value;
};
// Register playing point on chart
chart.sonification.currentlyPlayingPoint = point;
// Keep track of instruments playing
point.sonification = point.sonification || {};
point.sonification.instrumentsPlaying =
point.sonification.instrumentsPlaying || {};
// Register signal handler for the point
var signalHandler = point.sonification.signalHandler =
point.sonification.signalHandler ||
new utilities.SignalHandler(['onEnd']);
signalHandler.clearSignalCallbacks();
signalHandler.registerSignalCallbacks({ onEnd: options.onEnd });
// If we have a null point or invisible point, just return
if (point.isNull || !point.visible || !point.series.visible) {
signalHandler.emitSignal('onEnd');
return;
}
// Go through instruments and play them
options.instruments.forEach(function (instrumentDefinition) {
var instrument = typeof instrumentDefinition.instrument === 'string' ?
H.sonification.instruments[instrumentDefinition.instrument] :
instrumentDefinition.instrument, mapping = instrumentDefinition.instrumentMapping || {}, extremes = merge(defaultInstrumentOptions, instrumentDefinition.instrumentOptions), id = instrument.id, onEnd = function (cancelled) {
// Instrument on end
if (instrumentDefinition.onEnd) {
instrumentDefinition.onEnd.apply(this, arguments);
}
// Remove currently playing point reference on chart
if (chart.sonification &&
chart.sonification.currentlyPlayingPoint) {
delete chart.sonification.currentlyPlayingPoint;
}
// Remove reference from instruments playing
if (point.sonification && point.sonification.instrumentsPlaying) {
delete point.sonification.instrumentsPlaying[id];
// This was the last instrument?
if (!Object.keys(point.sonification.instrumentsPlaying).length) {
signalHandler.emitSignal('onEnd', cancelled);
}
}
};
// Play the note on the instrument
if (instrument && instrument.play) {
point.sonification.instrumentsPlaying[instrument.id] =
instrument;
instrument.play({
frequency: getMappingValue(mapping.frequency, true, { min: extremes.minFrequency, max: extremes.maxFrequency }),
duration: getMappingValue(mapping.duration, false, { min: extremes.minDuration, max: extremes.maxDuration }),
pan: getMappingValue(mapping.pan, true, { min: extremes.minPan, max: extremes.maxPan }),
volume: getMappingValue(mapping.volume, true, { min: extremes.minVolume, max: extremes.maxVolume }),
onEnd: onEnd,
minFrequency: extremes.minFrequency,
maxFrequency: extremes.maxFrequency
});
}
else {
error(30);
}
});
}
/**
* Cancel sonification of a point. Calls onEnd functions.
*
* @requires module:modules/sonification
*
* @function Highcharts.Point#cancelSonify
*
* @param {boolean} [fadeOut=false]
* Whether or not to fade out as we stop. If false, the points are
* cancelled synchronously.
*
* @return {void}
*/
function pointCancelSonify(fadeOut) {
var playing = this.sonification && this.sonification.instrumentsPlaying, instrIds = playing && Object.keys(playing);
if (instrIds && instrIds.length) {
instrIds.forEach(function (instr) {
playing[instr].stop(!fadeOut, null, 'cancelled');
});
this.sonification.instrumentsPlaying = {};
this.sonification.signalHandler.emitSignal('onEnd', 'cancelled');
}
}
var pointSonifyFunctions = {
pointSonify: pointSonify,
pointCancelSonify: pointCancelSonify
};
export default pointSonifyFunctions;

View File

@@ -0,0 +1,119 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Sonification module for Highcharts
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../parts/Globals.js';
import Point from '../../parts/Point.js';
import U from '../../parts/Utilities.js';
var addEvent = U.addEvent, extend = U.extend, merge = U.merge;
import Instrument from './Instrument.js';
import instruments from './instrumentDefinitions.js';
import Earcon from './Earcon.js';
import pointSonifyFunctions from './pointSonify.js';
import chartSonifyFunctions from './chartSonify.js';
import utilities from './utilities.js';
import TimelineClasses from './Timeline.js';
import sonificationOptions from './options.js';
// Expose on the Highcharts object
/**
* Global classes and objects related to sonification.
*
* @requires module:modules/sonification
*
* @name Highcharts.sonification
* @type {Highcharts.SonificationObject}
*/
/**
* Global classes and objects related to sonification.
*
* @requires module:modules/sonification
*
* @interface Highcharts.SonificationObject
*/ /**
* Note fade-out-time in milliseconds. Most notes are faded out quickly by
* default if there is time. This is to avoid abrupt stops which will cause
* perceived clicks.
* @name Highcharts.SonificationObject#fadeOutDuration
* @type {number}
*/ /**
* Utility functions.
* @name Highcharts.SonificationObject#utilities
* @private
* @type {object}
*/ /**
* The Instrument class.
* @name Highcharts.SonificationObject#Instrument
* @type {Function}
*/ /**
* Predefined instruments, given as an object with a map between the instrument
* name and the Highcharts.Instrument object.
* @name Highcharts.SonificationObject#instruments
* @type {Object}
*/ /**
* The Earcon class.
* @name Highcharts.SonificationObject#Earcon
* @type {Function}
*/ /**
* The TimelineEvent class.
* @private
* @name Highcharts.SonificationObject#TimelineEvent
* @type {Function}
*/ /**
* The TimelinePath class.
* @private
* @name Highcharts.SonificationObject#TimelinePath
* @type {Function}
*/ /**
* The Timeline class.
* @private
* @name Highcharts.SonificationObject#Timeline
* @type {Function}
*/
H.sonification = {
fadeOutDuration: 20,
// Classes and functions
utilities: utilities,
Instrument: Instrument,
instruments: instruments,
Earcon: Earcon,
TimelineEvent: TimelineClasses.TimelineEvent,
TimelinePath: TimelineClasses.TimelinePath,
Timeline: TimelineClasses.Timeline
};
// Add default options
merge(true, H.defaultOptions, sonificationOptions);
// Chart specific
Point.prototype.sonify = pointSonifyFunctions.pointSonify;
Point.prototype.cancelSonify = pointSonifyFunctions.pointCancelSonify;
H.Series.prototype.sonify = chartSonifyFunctions.seriesSonify;
extend(H.Chart.prototype, {
sonify: chartSonifyFunctions.chartSonify,
pauseSonify: chartSonifyFunctions.pause,
resumeSonify: chartSonifyFunctions.resume,
rewindSonify: chartSonifyFunctions.rewind,
cancelSonify: chartSonifyFunctions.cancel,
getCurrentSonifyPoints: chartSonifyFunctions.getCurrentPoints,
setSonifyCursor: chartSonifyFunctions.setCursor,
resetSonifyCursor: chartSonifyFunctions.resetCursor,
resetSonifyCursorEnd: chartSonifyFunctions.resetCursorEnd
});
/* eslint-disable no-invalid-this */
// Prepare charts for sonification on init
addEvent(H.Chart, 'init', function () {
this.sonification = {};
});
// Update with chart/series/point updates
addEvent(H.Chart, 'update', function (e) {
var newOptions = e.options.sonification;
if (newOptions) {
merge(true, this.options.sonification, newOptions);
}
});

View File

@@ -0,0 +1,165 @@
/* *
*
* (c) 2009-2020 Øystein Moseng
*
* Utility functions for sonification.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import musicalFrequencies from './musicalFrequencies.js';
import U from '../../parts/Utilities.js';
var clamp = U.clamp;
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* The SignalHandler class. Stores signal callbacks (event handlers), and
* provides an interface to register them, and emit signals. The word "event" is
* not used to avoid confusion with TimelineEvents.
*
* @requires module:modules/sonification
*
* @private
* @class
* @name Highcharts.SignalHandler
*
* @param {Array<string>} supportedSignals
* List of supported signal names.
*/
function SignalHandler(supportedSignals) {
this.init(supportedSignals || []);
}
SignalHandler.prototype.init = function (supportedSignals) {
this.supportedSignals = supportedSignals;
this.signals = {};
};
/**
* Register a set of signal callbacks with this SignalHandler.
* Multiple signal callbacks can be registered for the same signal.
* @private
* @param {Highcharts.Dictionary<(Function|undefined)>} signals
* An object that contains a mapping from the signal name to the callbacks. Only
* supported events are considered.
* @return {void}
*/
SignalHandler.prototype.registerSignalCallbacks = function (signals) {
var signalHandler = this;
signalHandler.supportedSignals.forEach(function (supportedSignal) {
var signal = signals[supportedSignal];
if (signal) {
(signalHandler.signals[supportedSignal] =
signalHandler.signals[supportedSignal] || []).push(signal);
}
});
};
/**
* Clear signal callbacks, optionally by name.
* @private
* @param {Array<string>} [signalNames] - A list of signal names to clear. If
* not supplied, all signal callbacks are removed.
* @return {void}
*/
SignalHandler.prototype.clearSignalCallbacks = function (signalNames) {
var signalHandler = this;
if (signalNames) {
signalNames.forEach(function (signalName) {
if (signalHandler.signals[signalName]) {
delete signalHandler.signals[signalName];
}
});
}
else {
signalHandler.signals = {};
}
};
/**
* Emit a signal. Does nothing if the signal does not exist, or has no
* registered callbacks.
* @private
* @param {string} signalNames
* Name of signal to emit.
* @param {*} [data]
* Data to pass to the callback.
* @return {*}
*/
SignalHandler.prototype.emitSignal = function (signalName, data) {
var retval;
if (this.signals[signalName]) {
this.signals[signalName].forEach(function (handler) {
var result = handler(data);
retval = typeof result !== 'undefined' ? result : retval;
});
}
return retval;
};
var utilities = {
// List of musical frequencies from C0 to C8
musicalFrequencies: musicalFrequencies,
// SignalHandler class
SignalHandler: SignalHandler,
/**
* Get a musical scale by specifying the semitones from 1-12 to include.
* 1: C, 2: C#, 3: D, 4: D#, 5: E, 6: F,
* 7: F#, 8: G, 9: G#, 10: A, 11: Bb, 12: B
* @private
* @param {Array<number>} semitones
* Array of semitones from 1-12 to include in the scale. Duplicate entries
* are ignored.
* @return {Array<number>}
* Array of frequencies from C0 to C8 that are included in this scale.
*/
getMusicalScale: function (semitones) {
return musicalFrequencies.filter(function (freq, i) {
var interval = i % 12 + 1;
return semitones.some(function (allowedInterval) {
return allowedInterval === interval;
});
});
},
/**
* Calculate the extreme values in a chart for a data prop.
* @private
* @param {Highcharts.Chart} chart - The chart
* @param {string} prop - The data prop to find extremes for
* @return {Highcharts.RangeObject} Object with min and max properties
*/
calculateDataExtremes: function (chart, prop) {
return chart.series.reduce(function (extremes, series) {
// We use cropped points rather than series.data here, to allow
// users to zoom in for better fidelity.
series.points.forEach(function (point) {
var val = typeof point[prop] !== 'undefined' ?
point[prop] : point.options[prop];
extremes.min = Math.min(extremes.min, val);
extremes.max = Math.max(extremes.max, val);
});
return extremes;
}, {
min: Infinity,
max: -Infinity
});
},
/**
* Translate a value on a virtual axis. Creates a new, virtual, axis with a
* min and max, and maps the relative value onto this axis.
* @private
* @param {number} value
* The relative data value to translate.
* @param {Highcharts.RangeObject} dataExtremes
* The possible extremes for this value.
* @param {object} limits
* Limits for the virtual axis.
* @return {number}
* The value mapped to the virtual axis.
*/
virtualAxisTranslate: function (value, dataExtremes, limits) {
var lenValueAxis = dataExtremes.max - dataExtremes.min, lenVirtualAxis = limits.max - limits.min, virtualAxisValue = limits.min +
lenVirtualAxis * (value - dataExtremes.min) / lenValueAxis;
return lenValueAxis > 0 ?
clamp(virtualAxisValue, limits.min, limits.max) :
limits.min;
}
};
export default utilities;

View File

@@ -0,0 +1,74 @@
/* *
*
* (c) 2016-2020 Torstein Honsi, Lars Cabrera
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../parts/Globals.js';
import U from '../parts/Utilities.js';
var addEvent = U.addEvent, defined = U.defined, isNumber = U.isNumber, pick = U.pick;
var Chart = H.Chart;
/* eslint-disable no-invalid-this */
/**
* For vertical axes only. Setting the static scale ensures that each tick unit
* is translated into a fixed pixel height. For example, setting the static
* scale to 24 results in each Y axis category taking up 24 pixels, and the
* height of the chart adjusts. Adding or removing items will make the chart
* resize.
*
* @sample gantt/xrange-series/demo/
* X-range series with static scale
*
* @type {number}
* @default 50
* @since 6.2.0
* @product gantt
* @apioption yAxis.staticScale
*/
addEvent(H.Axis, 'afterSetOptions', function () {
var chartOptions = this.chart.options && this.chart.options.chart;
if (!this.horiz &&
isNumber(this.options.staticScale) &&
(!chartOptions.height ||
(chartOptions.scrollablePlotArea &&
chartOptions.scrollablePlotArea.minHeight))) {
this.staticScale = this.options.staticScale;
}
});
Chart.prototype.adjustHeight = function () {
if (this.redrawTrigger !== 'adjustHeight') {
(this.axes || []).forEach(function (axis) {
var chart = axis.chart, animate = !!chart.initiatedScale &&
chart.options.animation, staticScale = axis.options.staticScale, height, diff;
if (axis.staticScale && defined(axis.min)) {
height = pick(axis.unitLength, axis.max + axis.tickInterval - axis.min) * staticScale;
// Minimum height is 1 x staticScale.
height = Math.max(height, staticScale);
diff = height - chart.plotHeight;
if (Math.abs(diff) >= 1) {
chart.plotHeight = height;
chart.redrawTrigger = 'adjustHeight';
chart.setSize(void 0, chart.chartHeight + diff, animate);
}
// Make sure clip rects have the right height before initial
// animation.
axis.series.forEach(function (series) {
var clipRect = series.sharedClipKey &&
chart[series.sharedClipKey];
if (clipRect) {
clipRect.attr({
height: chart.plotHeight
});
}
});
}
});
this.initiatedScale = true;
}
this.redrawTrigger = null;
};
addEvent(Chart, 'render', Chart.prototype.adjustHeight);

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,127 @@
/* *
*
* Streamgraph module
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import '../parts/AreaSeries.js';
import U from '../parts/Utilities.js';
var seriesType = U.seriesType;
/**
* @private
* @class
* @name Highcharts.seriesTypes.streamgraph
*
* @augments Highcharts.Series
*/
seriesType('streamgraph', 'areaspline'
/**
* A streamgraph is a type of stacked area graph which is displaced around a
* central axis, resulting in a flowing, organic shape.
*
* @sample {highcharts|highstock} highcharts/demo/streamgraph/
* Streamgraph
*
* @extends plotOptions.areaspline
* @since 6.0.0
* @product highcharts highstock
* @requires modules/streamgraph
* @optionparent plotOptions.streamgraph
*/
, {
fillOpacity: 1,
lineWidth: 0,
marker: {
enabled: false
},
stacking: 'stream'
// Prototype functions
}, {
negStacks: false,
// Modifier function for stream stacks. It simply moves the point up or
// down in order to center the full stack vertically.
streamStacker: function (pointExtremes, stack, i) {
// Y bottom value
pointExtremes[0] -= stack.total / 2;
// Y value
pointExtremes[1] -= stack.total / 2;
// Record the Y data for use when getting axis extremes
this.stackedYData[i] = pointExtremes;
}
});
/**
* A `streamgraph` series. If the [type](#series.streamgraph.type) option is not
* specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.streamgraph
* @excluding dataParser, dataURL, step
* @product highcharts highstock
* @requires modules/streamgraph
* @apioption series.streamgraph
*/
/**
* An array of data points for the series. For the `streamgraph` series type,
* points can be given in the following ways:
*
* 1. An array of numerical values. In this case, the numerical values will be
* interpreted as `y` options. The `x` values will be automatically
* calculated, either starting at 0 and incremented by 1, or from
* `pointStart` and `pointInterval` given in the series options. If the axis
* has categories, these will be used. Example:
* ```js
* data: [0, 5, 3, 5]
* ```
*
* 2. An array of arrays with 2 values. In this case, the values correspond to
* `x,y`. If the first value is a string, it is applied as the name of the
* point, and the `x` value is inferred.
* ```js
* data: [
* [0, 9],
* [1, 7],
* [2, 6]
* ]
* ```
*
* 3. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.area.turboThreshold),
* this option is not available.
* ```js
* data: [{
* x: 1,
* y: 9,
* name: "Point2",
* color: "#00FF00"
* }, {
* x: 1,
* y: 6,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @sample {highcharts} highcharts/chart/reflow-true/
* Numerical values
* @sample {highcharts} highcharts/series/data-array-of-arrays/
* Arrays of numeric x and y
* @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/
* Arrays of datetime x and y
* @sample {highcharts} highcharts/series/data-array-of-name-value/
* Arrays of point.name and y
* @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
*
* @type {Array<number|Array<(number|string),(number|null)>|null|*>}
* @extends series.line.data
* @product highcharts highstock
* @apioption series.streamgraph.data
*/
''; // adds doclets above to transpiled file

View File

@@ -0,0 +1,955 @@
/* *
*
* This module implements sunburst charts in Highcharts.
*
* (c) 2016-2020 Highsoft AS
*
* Authors: Jon Arild Nygard
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../parts/Globals.js';
import U from '../parts/Utilities.js';
var correctFloat = U.correctFloat, error = U.error, extend = U.extend, isNumber = U.isNumber, isObject = U.isObject, isString = U.isString, merge = U.merge, seriesType = U.seriesType, splat = U.splat;
import '../mixins/centered-series.js';
import drawPoint from '../mixins/draw-point.js';
import mixinTreeSeries from '../mixins/tree-series.js';
import '../parts/Series.js';
import './treemap.src.js';
var CenteredSeriesMixin = H.CenteredSeriesMixin, Series = H.Series, getCenter = CenteredSeriesMixin.getCenter, getColor = mixinTreeSeries.getColor, getLevelOptions = mixinTreeSeries.getLevelOptions, getStartAndEndRadians = CenteredSeriesMixin.getStartAndEndRadians, isBoolean = function (x) {
return typeof x === 'boolean';
}, noop = H.noop, rad2deg = 180 / Math.PI, seriesTypes = H.seriesTypes, setTreeValues = mixinTreeSeries.setTreeValues, updateRootId = mixinTreeSeries.updateRootId;
// TODO introduce step, which should default to 1.
var range = function range(from, to) {
var result = [], i;
if (isNumber(from) && isNumber(to) && from <= to) {
for (i = from; i <= to; i++) {
result.push(i);
}
}
return result;
};
/**
* @private
* @function calculateLevelSizes
*
* @param {object} levelOptions
* Map of level to its options.
*
* @param {Highcharts.Dictionary<number>} params
* Object containing number parameters `innerRadius` and `outerRadius`.
*
* @return {Highcharts.SunburstSeriesLevelsOptions|undefined}
* Returns the modified options, or undefined.
*/
var calculateLevelSizes = function calculateLevelSizes(levelOptions, params) {
var result, p = isObject(params) ? params : {}, totalWeight = 0, diffRadius, levels, levelsNotIncluded, remainingSize, from, to;
if (isObject(levelOptions)) {
result = merge({}, levelOptions);
from = isNumber(p.from) ? p.from : 0;
to = isNumber(p.to) ? p.to : 0;
levels = range(from, to);
levelsNotIncluded = Object.keys(result).filter(function (k) {
return levels.indexOf(+k) === -1;
});
diffRadius = remainingSize = isNumber(p.diffRadius) ? p.diffRadius : 0;
// Convert percentage to pixels.
// Calculate the remaining size to divide between "weight" levels.
// Calculate total weight to use in convertion from weight to pixels.
levels.forEach(function (level) {
var options = result[level], unit = options.levelSize.unit, value = options.levelSize.value;
if (unit === 'weight') {
totalWeight += value;
}
else if (unit === 'percentage') {
options.levelSize = {
unit: 'pixels',
value: (value / 100) * diffRadius
};
remainingSize -= options.levelSize.value;
}
else if (unit === 'pixels') {
remainingSize -= value;
}
});
// Convert weight to pixels.
levels.forEach(function (level) {
var options = result[level], weight;
if (options.levelSize.unit === 'weight') {
weight = options.levelSize.value;
result[level].levelSize = {
unit: 'pixels',
value: (weight / totalWeight) * remainingSize
};
}
});
// Set all levels not included in interval [from,to] to have 0 pixels.
levelsNotIncluded.forEach(function (level) {
result[level].levelSize = {
value: 0,
unit: 'pixels'
};
});
}
return result;
};
/**
* Find a set of coordinates given a start coordinates, an angle, and a
* distance.
*
* @private
* @function getEndPoint
*
* @param {number} x
* Start coordinate x
*
* @param {number} y
* Start coordinate y
*
* @param {number} angle
* Angle in radians
*
* @param {number} distance
* Distance from start to end coordinates
*
* @return {Highcharts.SVGAttributes}
* Returns the end coordinates, x and y.
*/
var getEndPoint = function getEndPoint(x, y, angle, distance) {
return {
x: x + (Math.cos(angle) * distance),
y: y + (Math.sin(angle) * distance)
};
};
var layoutAlgorithm = function layoutAlgorithm(parent, children, options) {
var startAngle = parent.start, range = parent.end - startAngle, total = parent.val, x = parent.x, y = parent.y, radius = ((options &&
isObject(options.levelSize) &&
isNumber(options.levelSize.value)) ?
options.levelSize.value :
0), innerRadius = parent.r, outerRadius = innerRadius + radius, slicedOffset = options && isNumber(options.slicedOffset) ?
options.slicedOffset :
0;
return (children || []).reduce(function (arr, child) {
var percentage = (1 / total) * child.val, radians = percentage * range, radiansCenter = startAngle + (radians / 2), offsetPosition = getEndPoint(x, y, radiansCenter, slicedOffset), values = {
x: child.sliced ? offsetPosition.x : x,
y: child.sliced ? offsetPosition.y : y,
innerR: innerRadius,
r: outerRadius,
radius: radius,
start: startAngle,
end: startAngle + radians
};
arr.push(values);
startAngle = values.end;
return arr;
}, []);
};
var getDlOptions = function getDlOptions(params) {
// Set options to new object to avoid problems with scope
var point = params.point, shape = isObject(params.shapeArgs) ? params.shapeArgs : {}, optionsPoint = (isObject(params.optionsPoint) ?
params.optionsPoint.dataLabels :
{}),
// The splat was used because levels dataLabels
// options doesn't work as an array
optionsLevel = splat(isObject(params.level) ?
params.level.dataLabels :
{})[0], options = merge({
style: {}
}, optionsLevel, optionsPoint), rotationRad, rotation, rotationMode = options.rotationMode;
if (!isNumber(options.rotation)) {
if (rotationMode === 'auto' || rotationMode === 'circular') {
if (point.innerArcLength < 1 &&
point.outerArcLength > shape.radius) {
rotationRad = 0;
// Triger setTextPath function to get textOutline etc.
if (point.dataLabelPath && rotationMode === 'circular') {
options.textPath = {
enabled: true
};
}
}
else if (point.innerArcLength > 1 &&
point.outerArcLength > 1.5 * shape.radius) {
if (rotationMode === 'circular') {
options.textPath = {
enabled: true,
attributes: {
dy: 5
}
};
}
else {
rotationMode = 'parallel';
}
}
else {
// Trigger the destroyTextPath function
if (point.dataLabel &&
point.dataLabel.textPathWrapper &&
rotationMode === 'circular') {
options.textPath = {
enabled: false
};
}
rotationMode = 'perpendicular';
}
}
if (rotationMode !== 'auto' && rotationMode !== 'circular') {
rotationRad = (shape.end -
(shape.end - shape.start) / 2);
}
if (rotationMode === 'parallel') {
options.style.width = Math.min(shape.radius * 2.5, (point.outerArcLength + point.innerArcLength) / 2);
}
else {
options.style.width = shape.radius;
}
if (rotationMode === 'perpendicular' &&
point.series.chart.renderer.fontMetrics(options.style.fontSize).h > point.outerArcLength) {
options.style.width = 1;
}
// Apply padding (#8515)
options.style.width = Math.max(options.style.width - 2 * (options.padding || 0), 1);
rotation = (rotationRad * rad2deg) % 180;
if (rotationMode === 'parallel') {
rotation -= 90;
}
// Prevent text from rotating upside down
if (rotation > 90) {
rotation -= 180;
}
else if (rotation < -90) {
rotation += 180;
}
options.rotation = rotation;
}
if (options.textPath) {
if (point.shapeExisting.innerR === 0 &&
options.textPath.enabled) {
// Enable rotation to render text
options.rotation = 0;
// Center dataLabel - disable textPath
options.textPath.enabled = false;
// Setting width and padding
options.style.width = Math.max((point.shapeExisting.r * 2) -
2 * (options.padding || 0), 1);
}
else if (point.dlOptions &&
point.dlOptions.textPath &&
!point.dlOptions.textPath.enabled &&
(rotationMode === 'circular')) {
// Bring dataLabel back if was a center dataLabel
options.textPath.enabled = true;
}
if (options.textPath.enabled) {
// Enable rotation to render text
options.rotation = 0;
// Setting width and padding
options.style.width = Math.max((point.outerArcLength +
point.innerArcLength) / 2 -
2 * (options.padding || 0), 1);
}
}
// NOTE: alignDataLabel positions the data label differntly when rotation is
// 0. Avoiding this by setting rotation to a small number.
if (options.rotation === 0) {
options.rotation = 0.001;
}
return options;
};
var getAnimation = function getAnimation(shape, params) {
var point = params.point, radians = params.radians, innerR = params.innerR, idRoot = params.idRoot, idPreviousRoot = params.idPreviousRoot, shapeExisting = params.shapeExisting, shapeRoot = params.shapeRoot, shapePreviousRoot = params.shapePreviousRoot, visible = params.visible, from = {}, to = {
end: shape.end,
start: shape.start,
innerR: shape.innerR,
r: shape.r,
x: shape.x,
y: shape.y
};
if (visible) {
// Animate points in
if (!point.graphic && shapePreviousRoot) {
if (idRoot === point.id) {
from = {
start: radians.start,
end: radians.end
};
}
else {
from = (shapePreviousRoot.end <= shape.start) ? {
start: radians.end,
end: radians.end
} : {
start: radians.start,
end: radians.start
};
}
// Animate from center and outwards.
from.innerR = from.r = innerR;
}
}
else {
// Animate points out
if (point.graphic) {
if (idPreviousRoot === point.id) {
to = {
innerR: innerR,
r: innerR
};
}
else if (shapeRoot) {
to = (shapeRoot.end <= shapeExisting.start) ?
{
innerR: innerR,
r: innerR,
start: radians.end,
end: radians.end
} : {
innerR: innerR,
r: innerR,
start: radians.start,
end: radians.start
};
}
}
}
return {
from: from,
to: to
};
};
var getDrillId = function getDrillId(point, idRoot, mapIdToNode) {
var drillId, node = point.node, nodeRoot;
if (!node.isLeaf) {
// When it is the root node, the drillId should be set to parent.
if (idRoot === point.id) {
nodeRoot = mapIdToNode[idRoot];
drillId = nodeRoot.parent;
}
else {
drillId = point.id;
}
}
return drillId;
};
var getLevelFromAndTo = function getLevelFromAndTo(_a) {
var level = _a.level, height = _a.height;
// Never displays level below 1
var from = level > 0 ? level : 1;
var to = level + height;
return { from: from, to: to };
};
var cbSetTreeValuesBefore = function before(node, options) {
var mapIdToNode = options.mapIdToNode, nodeParent = mapIdToNode[node.parent], series = options.series, chart = series.chart, points = series.points, point = points[node.i], colors = (series.options.colors || chart && chart.options.colors), colorInfo = getColor(node, {
colors: colors,
colorIndex: series.colorIndex,
index: options.index,
mapOptionsToLevel: options.mapOptionsToLevel,
parentColor: nodeParent && nodeParent.color,
parentColorIndex: nodeParent && nodeParent.colorIndex,
series: options.series,
siblings: options.siblings
});
node.color = colorInfo.color;
node.colorIndex = colorInfo.colorIndex;
if (point) {
point.color = node.color;
point.colorIndex = node.colorIndex;
// Set slicing on node, but avoid slicing the top node.
node.sliced = (node.id !== options.idRoot) ? point.sliced : false;
}
return node;
};
/**
* A Sunburst displays hierarchical data, where a level in the hierarchy is
* represented by a circle. The center represents the root node of the tree.
* The visualization bears a resemblance to both treemap and pie charts.
*
* @sample highcharts/demo/sunburst
* Sunburst chart
*
* @extends plotOptions.pie
* @excluding allAreas, clip, colorAxis, colorKey, compare, compareBase,
* dataGrouping, depth, dragDrop, endAngle, gapSize, gapUnit,
* ignoreHiddenPoint, innerSize, joinBy, legendType, linecap,
* minSize, navigatorOptions, pointRange
* @product highcharts
* @requires modules/sunburst.js
* @optionparent plotOptions.sunburst
* @private
*/
var sunburstOptions = {
/**
* Set options on specific levels. Takes precedence over series options,
* but not point options.
*
* @sample highcharts/demo/sunburst
* Sunburst chart
*
* @type {Array<*>}
* @apioption plotOptions.sunburst.levels
*/
/**
* Can set a `borderColor` on all points which lies on the same level.
*
* @type {Highcharts.ColorString}
* @apioption plotOptions.sunburst.levels.borderColor
*/
/**
* Can set a `borderWidth` on all points which lies on the same level.
*
* @type {number}
* @apioption plotOptions.sunburst.levels.borderWidth
*/
/**
* Can set a `borderDashStyle` on all points which lies on the same level.
*
* @type {Highcharts.DashStyleValue}
* @apioption plotOptions.sunburst.levels.borderDashStyle
*/
/**
* Can set a `color` on all points which lies on the same level.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @apioption plotOptions.sunburst.levels.color
*/
/**
* Can set a `colorVariation` on all points which lies on the same level.
*
* @apioption plotOptions.sunburst.levels.colorVariation
*/
/**
* The key of a color variation. Currently supports `brightness` only.
*
* @type {string}
* @apioption plotOptions.sunburst.levels.colorVariation.key
*/
/**
* The ending value of a color variation. The last sibling will receive this
* value.
*
* @type {number}
* @apioption plotOptions.sunburst.levels.colorVariation.to
*/
/**
* Can set `dataLabels` on all points which lies on the same level.
*
* @extends plotOptions.sunburst.dataLabels
* @apioption plotOptions.sunburst.levels.dataLabels
*/
/**
* Can set a `levelSize` on all points which lies on the same level.
*
* @type {object}
* @apioption plotOptions.sunburst.levels.levelSize
*/
/**
* Can set a `rotation` on all points which lies on the same level.
*
* @type {number}
* @apioption plotOptions.sunburst.levels.rotation
*/
/**
* Can set a `rotationMode` on all points which lies on the same level.
*
* @type {string}
* @apioption plotOptions.sunburst.levels.rotationMode
*/
/**
* When enabled the user can click on a point which is a parent and
* zoom in on its children. Deprecated and replaced by
* [allowTraversingTree](#plotOptions.sunburst.allowTraversingTree).
*
* @deprecated
* @type {boolean}
* @default false
* @since 6.0.0
* @product highcharts
* @apioption plotOptions.sunburst.allowDrillToNode
*/
/**
* When enabled the user can click on a point which is a parent and
* zoom in on its children.
*
* @type {boolean}
* @default false
* @since 7.0.3
* @product highcharts
* @apioption plotOptions.sunburst.allowTraversingTree
*/
/**
* The center of the sunburst chart relative to the plot area. Can be
* percentages or pixel values.
*
* @sample {highcharts} highcharts/plotoptions/pie-center/
* Centered at 100, 100
*
* @type {Array<number|string>}
* @default ["50%", "50%"]
* @product highcharts
*/
center: ['50%', '50%'],
colorByPoint: false,
/**
* Disable inherited opacity from Treemap series.
*
* @ignore-option
*/
opacity: 1,
/**
* @declare Highcharts.SeriesSunburstDataLabelsOptionsObject
*/
dataLabels: {
allowOverlap: true,
defer: true,
/**
* Decides how the data label will be rotated relative to the perimeter
* of the sunburst. Valid values are `auto`, `circular`, `parallel` and
* `perpendicular`. When `auto`, the best fit will be
* computed for the point. The `circular` option works similiar
* to `auto`, but uses the `textPath` feature - labels are curved,
* resulting in a better layout, however multiple lines and
* `textOutline` are not supported.
*
* The `series.rotation` option takes precedence over `rotationMode`.
*
* @type {string}
* @sample {highcharts} highcharts/plotoptions/sunburst-datalabels-rotationmode-circular/
* Circular rotation mode
* @validvalue ["auto", "perpendicular", "parallel", "circular"]
* @since 6.0.0
*/
rotationMode: 'auto',
style: {
/** @internal */
textOverflow: 'ellipsis'
}
},
/**
* Which point to use as a root in the visualization.
*
* @type {string}
*/
rootId: void 0,
/**
* Used together with the levels and `allowDrillToNode` options. When
* set to false the first level visible when drilling is considered
* to be level one. Otherwise the level will be the same as the tree
* structure.
*/
levelIsConstant: true,
/**
* Determines the width of the ring per level.
*
* @sample {highcharts} highcharts/plotoptions/sunburst-levelsize/
* Sunburst with various sizes per level
*
* @since 6.0.5
*/
levelSize: {
/**
* The value used for calculating the width of the ring. Its' affect is
* determined by `levelSize.unit`.
*
* @sample {highcharts} highcharts/plotoptions/sunburst-levelsize/
* Sunburst with various sizes per level
*/
value: 1,
/**
* How to interpret `levelSize.value`.
*
* - `percentage` gives a width relative to result of outer radius minus
* inner radius.
*
* - `pixels` gives the ring a fixed width in pixels.
*
* - `weight` takes the remaining width after percentage and pixels, and
* distributes it accross all "weighted" levels. The value relative to
* the sum of all weights determines the width.
*
* @sample {highcharts} highcharts/plotoptions/sunburst-levelsize/
* Sunburst with various sizes per level
*
* @validvalue ["percentage", "pixels", "weight"]
*/
unit: 'weight'
},
/**
* Options for the button appearing when traversing down in a treemap.
*
* @extends plotOptions.treemap.traverseUpButton
* @since 6.0.0
* @apioption plotOptions.sunburst.traverseUpButton
*/
/**
* If a point is sliced, moved out from the center, how many pixels
* should it be moved?.
*
* @sample highcharts/plotoptions/sunburst-sliced
* Sliced sunburst
*
* @since 6.0.4
*/
slicedOffset: 10
};
// Properties of the Sunburst series.
var sunburstSeries = {
drawDataLabels: noop,
drawPoints: function drawPoints() {
var series = this, mapOptionsToLevel = series.mapOptionsToLevel, shapeRoot = series.shapeRoot, group = series.group, hasRendered = series.hasRendered, idRoot = series.rootNode, idPreviousRoot = series.idPreviousRoot, nodeMap = series.nodeMap, nodePreviousRoot = nodeMap[idPreviousRoot], shapePreviousRoot = nodePreviousRoot && nodePreviousRoot.shapeArgs, points = series.points, radians = series.startAndEndRadians, chart = series.chart, optionsChart = chart && chart.options && chart.options.chart || {}, animation = (isBoolean(optionsChart.animation) ?
optionsChart.animation :
true), positions = series.center, center = {
x: positions[0],
y: positions[1]
}, innerR = positions[3] / 2, renderer = series.chart.renderer, animateLabels, animateLabelsCalled = false, addedHack = false, hackDataLabelAnimation = !!(animation &&
hasRendered &&
idRoot !== idPreviousRoot &&
series.dataLabelsGroup);
if (hackDataLabelAnimation) {
series.dataLabelsGroup.attr({ opacity: 0 });
animateLabels = function () {
var s = series;
animateLabelsCalled = true;
if (s.dataLabelsGroup) {
s.dataLabelsGroup.animate({
opacity: 1,
visibility: 'visible'
});
}
};
}
points.forEach(function (point) {
var node = point.node, level = mapOptionsToLevel[node.level], shapeExisting = point.shapeExisting || {}, shape = node.shapeArgs || {}, animationInfo, onComplete, visible = !!(node.visible && node.shapeArgs);
if (hasRendered && animation) {
animationInfo = getAnimation(shape, {
center: center,
point: point,
radians: radians,
innerR: innerR,
idRoot: idRoot,
idPreviousRoot: idPreviousRoot,
shapeExisting: shapeExisting,
shapeRoot: shapeRoot,
shapePreviousRoot: shapePreviousRoot,
visible: visible
});
}
else {
// When animation is disabled, attr is called from animation.
animationInfo = {
to: shape,
from: {}
};
}
extend(point, {
shapeExisting: shape,
tooltipPos: [shape.plotX, shape.plotY],
drillId: getDrillId(point, idRoot, nodeMap),
name: '' + (point.name || point.id || point.index),
plotX: shape.plotX,
plotY: shape.plotY,
value: node.val,
isNull: !visible // used for dataLabels & point.draw
});
point.dlOptions = getDlOptions({
point: point,
level: level,
optionsPoint: point.options,
shapeArgs: shape
});
if (!addedHack && visible) {
addedHack = true;
onComplete = animateLabels;
}
point.draw({
animatableAttribs: animationInfo.to,
attribs: extend(animationInfo.from, (!chart.styledMode && series.pointAttribs(point, (point.selected && 'select')))),
onComplete: onComplete,
group: group,
renderer: renderer,
shapeType: 'arc',
shapeArgs: shape
});
});
// Draw data labels after points
// TODO draw labels one by one to avoid addtional looping
if (hackDataLabelAnimation && addedHack) {
series.hasRendered = false;
series.options.dataLabels.defer = true;
Series.prototype.drawDataLabels.call(series);
series.hasRendered = true;
// If animateLabels is called before labels were hidden, then call
// it again.
if (animateLabelsCalled) {
animateLabels();
}
}
else {
Series.prototype.drawDataLabels.call(series);
}
},
pointAttribs: seriesTypes.column.prototype.pointAttribs,
// The layout algorithm for the levels
layoutAlgorithm: layoutAlgorithm,
// Set the shape arguments on the nodes. Recursive from root down.
setShapeArgs: function (parent, parentValues, mapOptionsToLevel) {
var childrenValues = [], level = parent.level + 1, options = mapOptionsToLevel[level],
// Collect all children which should be included
children = parent.children.filter(function (n) {
return n.visible;
}), twoPi = 6.28; // Two times Pi.
childrenValues = this.layoutAlgorithm(parentValues, children, options);
children.forEach(function (child, index) {
var values = childrenValues[index], angle = values.start + ((values.end - values.start) / 2), radius = values.innerR + ((values.r - values.innerR) / 2), radians = (values.end - values.start), isCircle = (values.innerR === 0 && radians > twoPi), center = (isCircle ?
{ x: values.x, y: values.y } :
getEndPoint(values.x, values.y, angle, radius)), val = (child.val ?
(child.childrenTotal > child.val ?
child.childrenTotal :
child.val) :
child.childrenTotal);
// The inner arc length is a convenience for data label filters.
if (this.points[child.i]) {
this.points[child.i].innerArcLength = radians * values.innerR;
this.points[child.i].outerArcLength = radians * values.r;
}
child.shapeArgs = merge(values, {
plotX: center.x,
plotY: center.y + 4 * Math.abs(Math.cos(angle))
});
child.values = merge(values, {
val: val
});
// If node has children, then call method recursively
if (child.children.length) {
this.setShapeArgs(child, child.values, mapOptionsToLevel);
}
}, this);
},
translate: function translate() {
var series = this, options = series.options, positions = series.center = getCenter.call(series), radians = series.startAndEndRadians = getStartAndEndRadians(options.startAngle, options.endAngle), innerRadius = positions[3] / 2, outerRadius = positions[2] / 2, diffRadius = outerRadius - innerRadius,
// NOTE: updateRootId modifies series.
rootId = updateRootId(series), mapIdToNode = series.nodeMap, mapOptionsToLevel, idTop, nodeRoot = mapIdToNode && mapIdToNode[rootId], nodeTop, tree, values, nodeIds = {};
series.shapeRoot = nodeRoot && nodeRoot.shapeArgs;
// Call prototype function
Series.prototype.translate.call(series);
// @todo Only if series.isDirtyData is true
tree = series.tree = series.getTree();
// Render traverseUpButton, after series.nodeMap i calculated.
series.renderTraverseUpButton(rootId);
mapIdToNode = series.nodeMap;
nodeRoot = mapIdToNode[rootId];
idTop = isString(nodeRoot.parent) ? nodeRoot.parent : '';
nodeTop = mapIdToNode[idTop];
var _a = getLevelFromAndTo(nodeRoot), from = _a.from, to = _a.to;
mapOptionsToLevel = getLevelOptions({
from: from,
levels: series.options.levels,
to: to,
defaults: {
colorByPoint: options.colorByPoint,
dataLabels: options.dataLabels,
levelIsConstant: options.levelIsConstant,
levelSize: options.levelSize,
slicedOffset: options.slicedOffset
}
});
// NOTE consider doing calculateLevelSizes in a callback to
// getLevelOptions
mapOptionsToLevel = calculateLevelSizes(mapOptionsToLevel, {
diffRadius: diffRadius,
from: from,
to: to
});
// TODO Try to combine setTreeValues & setColorRecursive to avoid
// unnecessary looping.
setTreeValues(tree, {
before: cbSetTreeValuesBefore,
idRoot: rootId,
levelIsConstant: options.levelIsConstant,
mapOptionsToLevel: mapOptionsToLevel,
mapIdToNode: mapIdToNode,
points: series.points,
series: series
});
values = mapIdToNode[''].shapeArgs = {
end: radians.end,
r: innerRadius,
start: radians.start,
val: nodeRoot.val,
x: positions[0],
y: positions[1]
};
this.setShapeArgs(nodeTop, values, mapOptionsToLevel);
// Set mapOptionsToLevel on series for use in drawPoints.
series.mapOptionsToLevel = mapOptionsToLevel;
// #10669 - verify if all nodes have unique ids
series.data.forEach(function (child) {
if (nodeIds[child.id]) {
error(31, false, series.chart);
}
// map
nodeIds[child.id] = true;
});
// reset object
nodeIds = {};
},
alignDataLabel: function (point, dataLabel, labelOptions) {
if (labelOptions.textPath && labelOptions.textPath.enabled) {
return;
}
return seriesTypes.treemap.prototype.alignDataLabel
.apply(this, arguments);
},
// Animate the slices in. Similar to the animation of polar charts.
animate: function (init) {
var chart = this.chart, center = [
chart.plotWidth / 2,
chart.plotHeight / 2
], plotLeft = chart.plotLeft, plotTop = chart.plotTop, attribs, group = this.group;
// Initialize the animation
if (init) {
// Scale down the group and place it in the center
attribs = {
translateX: center[0] + plotLeft,
translateY: center[1] + plotTop,
scaleX: 0.001,
scaleY: 0.001,
rotation: 10,
opacity: 0.01
};
group.attr(attribs);
// Run the animation
}
else {
attribs = {
translateX: plotLeft,
translateY: plotTop,
scaleX: 1,
scaleY: 1,
rotation: 0,
opacity: 1
};
group.animate(attribs, this.options.animation);
}
},
utils: {
calculateLevelSizes: calculateLevelSizes,
getLevelFromAndTo: getLevelFromAndTo,
range: range
}
};
// Properties of the Sunburst series.
var sunburstPoint = {
draw: drawPoint,
shouldDraw: function shouldDraw() {
return !this.isNull;
},
isValid: function isValid() {
return true;
},
getDataLabelPath: function (label) {
var renderer = this.series.chart.renderer, shapeArgs = this.shapeExisting, start = shapeArgs.start, end = shapeArgs.end, angle = start + (end - start) / 2, // arc middle value
upperHalf = angle < 0 &&
angle > -Math.PI ||
angle > Math.PI, r = (shapeArgs.r + (label.options.distance || 0)), moreThanHalf;
// Check if point is a full circle
if (start === -Math.PI / 2 &&
correctFloat(end) === correctFloat(Math.PI * 1.5)) {
start = -Math.PI + Math.PI / 360;
end = -Math.PI / 360;
upperHalf = true;
}
// Check if dataLabels should be render in the
// upper half of the circle
if (end - start > Math.PI) {
upperHalf = false;
moreThanHalf = true;
}
if (this.dataLabelPath) {
this.dataLabelPath = this.dataLabelPath.destroy();
}
this.dataLabelPath = renderer
.arc({
open: true,
longArc: moreThanHalf ? 1 : 0
})
// Add it inside the data label group so it gets destroyed
// with the label
.add(label);
this.dataLabelPath.attr({
start: (upperHalf ? start : end),
end: (upperHalf ? end : start),
clockwise: +upperHalf,
x: shapeArgs.x,
y: shapeArgs.y,
r: (r + shapeArgs.innerR) / 2
});
return this.dataLabelPath;
}
};
/**
* A `sunburst` series. If the [type](#series.sunburst.type) option is
* not specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.sunburst
* @excluding dataParser, dataURL, stack, dataSorting
* @product highcharts
* @requires modules/sunburst.js
* @apioption series.sunburst
*/
/**
* @type {Array<number|null|*>}
* @extends series.treemap.data
* @excluding x, y
* @product highcharts
* @apioption series.sunburst.data
*/
/**
* @type {Highcharts.SeriesSunburstDataLabelsOptionsObject|Array<Highcharts.SeriesSunburstDataLabelsOptionsObject>}
* @product highcharts
* @apioption series.sunburst.data.dataLabels
*/
/**
* The value of the point, resulting in a relative area of the point
* in the sunburst.
*
* @type {number|null}
* @since 6.0.0
* @product highcharts
* @apioption series.sunburst.data.value
*/
/**
* Use this option to build a tree structure. The value should be the id of the
* point which is the parent. If no points has a matching id, or this option is
* undefined, then the parent will be set to the root.
*
* @type {string}
* @since 6.0.0
* @product highcharts
* @apioption series.sunburst.data.parent
*/
/**
* Whether to display a slice offset from the center. When a sunburst point is
* sliced, its children are also offset.
*
* @sample highcharts/plotoptions/sunburst-sliced
* Sliced sunburst
*
* @type {boolean}
* @default false
* @since 6.0.4
* @product highcharts
* @apioption series.sunburst.data.sliced
*/
/**
* @private
* @class
* @name Highcharts.seriesTypes.sunburst
*
* @augments Highcharts.Series
*/
seriesType('sunburst', 'treemap', sunburstOptions, sunburstSeries, sunburstPoint);

View File

@@ -0,0 +1,560 @@
/* *
*
* Tilemaps module
*
* (c) 2010-2017 Highsoft AS
* Author: Øystein Moseng
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../parts/Globals.js';
/**
* @typedef {"circle"|"diamond"|"hexagon"|"square"} Highcharts.TilemapShapeValue
*/
''; // detach doclets above
import U from '../parts/Utilities.js';
var addEvent = U.addEvent, clamp = U.clamp, extend = U.extend, pick = U.pick, seriesType = U.seriesType;
import '../parts-map/HeatmapSeries.js';
/**
* Utility func to get padding definition from tile size division
* @private
* @param {Highcharts.TilemapSeries} series
* series
* @param {Highcharts.number} xDiv
* xDiv
* @param {Highcharts.number} yDiv
* yDiv
* @return {Highcharts.TilemapPaddingObject}
*/
function tilePaddingFromTileSize(series, xDiv, yDiv) {
var options = series.options;
return {
xPad: (options.colsize || 1) / -xDiv,
yPad: (options.rowsize || 1) / -yDiv
};
}
// Map of shape types.
H.tileShapeTypes = {
// Hexagon shape type.
hexagon: {
alignDataLabel: H.seriesTypes.scatter.prototype.alignDataLabel,
getSeriesPadding: function (series) {
return tilePaddingFromTileSize(series, 3, 2);
},
haloPath: function (size) {
if (!size) {
return [];
}
var hexagon = this.tileEdges;
return [
'M', hexagon.x2 - size, hexagon.y1 + size,
'L', hexagon.x3 + size, hexagon.y1 + size,
hexagon.x4 + size * 1.5, hexagon.y2,
hexagon.x3 + size, hexagon.y3 - size,
hexagon.x2 - size, hexagon.y3 - size,
hexagon.x1 - size * 1.5, hexagon.y2,
'Z'
];
},
translate: function () {
var series = this, options = series.options, xAxis = series.xAxis, yAxis = series.yAxis, seriesPointPadding = options.pointPadding || 0, xPad = (options.colsize || 1) / 3, yPad = (options.rowsize || 1) / 2, yShift;
series.generatePoints();
series.points.forEach(function (point) {
var x1 = clamp(Math.floor(xAxis.len -
xAxis.translate(point.x - xPad * 2, 0, 1, 0, 1)), -xAxis.len, 2 * xAxis.len), x2 = clamp(Math.floor(xAxis.len -
xAxis.translate(point.x - xPad, 0, 1, 0, 1)), -xAxis.len, 2 * xAxis.len), x3 = clamp(Math.floor(xAxis.len -
xAxis.translate(point.x + xPad, 0, 1, 0, 1)), -xAxis.len, 2 * xAxis.len), x4 = clamp(Math.floor(xAxis.len -
xAxis.translate(point.x + xPad * 2, 0, 1, 0, 1)), -xAxis.len, 2 * xAxis.len), y1 = clamp(Math.floor(yAxis.translate(point.y - yPad, 0, 1, 0, 1)), -yAxis.len, 2 * yAxis.len), y2 = clamp(Math.floor(yAxis.translate(point.y, 0, 1, 0, 1)), -yAxis.len, 2 * yAxis.len), y3 = clamp(Math.floor(yAxis.translate(point.y + yPad, 0, 1, 0, 1)), -yAxis.len, 2 * yAxis.len), pointPadding = pick(point.pointPadding, seriesPointPadding),
// We calculate the point padding of the midpoints to
// preserve the angles of the shape.
midPointPadding = pointPadding *
Math.abs(x2 - x1) / Math.abs(y3 - y2), xMidPadding = xAxis.reversed ?
-midPointPadding : midPointPadding, xPointPadding = xAxis.reversed ?
-pointPadding : pointPadding, yPointPadding = yAxis.reversed ?
-pointPadding : pointPadding;
// Shift y-values for every second grid column
if (point.x % 2) {
yShift = yShift || Math.round(Math.abs(y3 - y1) / 2) *
// We have to reverse the shift for reversed y-axes
(yAxis.reversed ? -1 : 1);
y1 += yShift;
y2 += yShift;
y3 += yShift;
}
// Set plotX and plotY for use in K-D-Tree and more
point.plotX = point.clientX = (x2 + x3) / 2;
point.plotY = y2;
// Apply point padding to translated coordinates
x1 += xMidPadding + xPointPadding;
x2 += xPointPadding;
x3 -= xPointPadding;
x4 -= xMidPadding + xPointPadding;
y1 -= yPointPadding;
y3 += yPointPadding;
// Store points for halo creation
point.tileEdges = {
x1: x1, x2: x2, x3: x3, x4: x4, y1: y1, y2: y2, y3: y3
};
// Finally set the shape for this point
point.shapeType = 'path';
point.shapeArgs = {
d: [
'M', x2, y1,
'L', x3, y1,
x4, y2,
x3, y3,
x2, y3,
x1, y2,
'Z'
]
};
});
series.translateColors();
}
},
// Diamond shape type.
diamond: {
alignDataLabel: H.seriesTypes.scatter.prototype.alignDataLabel,
getSeriesPadding: function (series) {
return tilePaddingFromTileSize(series, 2, 2);
},
haloPath: function (size) {
if (!size) {
return [];
}
var diamond = this.tileEdges;
return [
'M', diamond.x2, diamond.y1 + size,
'L', diamond.x3 + size, diamond.y2,
diamond.x2, diamond.y3 - size,
diamond.x1 - size, diamond.y2,
'Z'
];
},
translate: function () {
var series = this, options = series.options, xAxis = series.xAxis, yAxis = series.yAxis, seriesPointPadding = options.pointPadding || 0, xPad = (options.colsize || 1), yPad = (options.rowsize || 1) / 2, yShift;
series.generatePoints();
series.points.forEach(function (point) {
var x1 = clamp(Math.round(xAxis.len -
xAxis.translate(point.x - xPad, 0, 1, 0, 0)), -xAxis.len, 2 * xAxis.len), x2 = clamp(Math.round(xAxis.len -
xAxis.translate(point.x, 0, 1, 0, 0)), -xAxis.len, 2 * xAxis.len), x3 = clamp(Math.round(xAxis.len -
xAxis.translate(point.x + xPad, 0, 1, 0, 0)), -xAxis.len, 2 * xAxis.len), y1 = clamp(Math.round(yAxis.translate(point.y - yPad, 0, 1, 0, 0)), -yAxis.len, 2 * yAxis.len), y2 = clamp(Math.round(yAxis.translate(point.y, 0, 1, 0, 0)), -yAxis.len, 2 * yAxis.len), y3 = clamp(Math.round(yAxis.translate(point.y + yPad, 0, 1, 0, 0)), -yAxis.len, 2 * yAxis.len), pointPadding = pick(point.pointPadding, seriesPointPadding),
// We calculate the point padding of the midpoints to
// preserve the angles of the shape.
midPointPadding = pointPadding *
Math.abs(x2 - x1) / Math.abs(y3 - y2), xPointPadding = xAxis.reversed ?
-midPointPadding : midPointPadding, yPointPadding = yAxis.reversed ?
-pointPadding : pointPadding;
// Shift y-values for every second grid column
// We have to reverse the shift for reversed y-axes
if (point.x % 2) {
yShift = Math.abs(y3 - y1) / 2 * (yAxis.reversed ? -1 : 1);
y1 += yShift;
y2 += yShift;
y3 += yShift;
}
// Set plotX and plotY for use in K-D-Tree and more
point.plotX = point.clientX = x2;
point.plotY = y2;
// Apply point padding to translated coordinates
x1 += xPointPadding;
x3 -= xPointPadding;
y1 -= yPointPadding;
y3 += yPointPadding;
// Store points for halo creation
point.tileEdges = {
x1: x1, x2: x2, x3: x3, y1: y1, y2: y2, y3: y3
};
// Set this point's shape parameters
point.shapeType = 'path';
point.shapeArgs = {
d: [
'M', x2, y1,
'L', x3, y2,
x2, y3,
x1, y2,
'Z'
]
};
});
series.translateColors();
}
},
// Circle shape type.
circle: {
alignDataLabel: H.seriesTypes.scatter.prototype.alignDataLabel,
getSeriesPadding: function (series) {
return tilePaddingFromTileSize(series, 2, 2);
},
haloPath: function (size) {
return H.seriesTypes.scatter.prototype.pointClass.prototype.haloPath
.call(this, size + (size && this.radius));
},
translate: function () {
var series = this, options = series.options, xAxis = series.xAxis, yAxis = series.yAxis, seriesPointPadding = options.pointPadding || 0, yRadius = (options.rowsize || 1) / 2, colsize = (options.colsize || 1), colsizePx, yRadiusPx, xRadiusPx, radius, forceNextRadiusCompute = false;
series.generatePoints();
series.points.forEach(function (point) {
var x = clamp(Math.round(xAxis.len -
xAxis.translate(point.x, 0, 1, 0, 0)), -xAxis.len, 2 * xAxis.len), y = clamp(Math.round(yAxis.translate(point.y, 0, 1, 0, 0)), -yAxis.len, 2 * yAxis.len), pointPadding = seriesPointPadding, hasPerPointPadding = false;
// If there is point padding defined on a single point, add it
if (typeof point.pointPadding !== 'undefined') {
pointPadding = point.pointPadding;
hasPerPointPadding = true;
forceNextRadiusCompute = true;
}
// Find radius if not found already.
// Use the smallest one (x vs y) to avoid overlap.
// Note that the radius will be recomputed for each series.
// Ideal (max) x radius is dependent on y radius:
/*
* (circle 2)
* (circle 3)
| yRadiusPx
(circle 1) *-------|
colsizePx
The distance between circle 1 and 3 (and circle 2 and 3) is
2r, which is the hypotenuse of the triangle created by
colsizePx and yRadiusPx. If the distance between circle 2
and circle 1 is less than 2r, we use half of that distance
instead (yRadiusPx).
*/
if (!radius || forceNextRadiusCompute) {
colsizePx = Math.abs(clamp(Math.floor(xAxis.len -
xAxis.translate(point.x + colsize, 0, 1, 0, 0)), -xAxis.len, 2 * xAxis.len) - x);
yRadiusPx = Math.abs(clamp(Math.floor(yAxis.translate(point.y + yRadius, 0, 1, 0, 0)), -yAxis.len, 2 * yAxis.len) - y);
xRadiusPx = Math.floor(Math.sqrt((colsizePx * colsizePx + yRadiusPx * yRadiusPx)) / 2);
radius = Math.min(colsizePx, xRadiusPx, yRadiusPx) - pointPadding;
// If we have per point padding we need to always compute
// the radius for this point and the next. If we used to
// have per point padding but don't anymore, don't force
// compute next radius.
if (forceNextRadiusCompute && !hasPerPointPadding) {
forceNextRadiusCompute = false;
}
}
// Shift y-values for every second grid column.
// Note that we always use the optimal y axis radius for this.
// Also note: We have to reverse the shift for reversed y-axes.
if (point.x % 2) {
y += yRadiusPx * (yAxis.reversed ? -1 : 1);
}
// Set plotX and plotY for use in K-D-Tree and more
point.plotX = point.clientX = x;
point.plotY = y;
// Save radius for halo
point.radius = radius;
// Set this point's shape parameters
point.shapeType = 'circle';
point.shapeArgs = {
x: x,
y: y,
r: radius
};
});
series.translateColors();
}
},
// Square shape type.
square: {
alignDataLabel: H.seriesTypes.heatmap.prototype.alignDataLabel,
translate: H.seriesTypes.heatmap.prototype.translate,
getSeriesPadding: function () {
},
haloPath: H.seriesTypes.heatmap.prototype.pointClass.prototype.haloPath
}
};
/* eslint-disable no-invalid-this */
// Extension to add pixel padding for series. Uses getSeriesPixelPadding on each
// series and adds the largest padding required. If no series has this function
// defined, we add nothing.
addEvent(H.Axis, 'afterSetAxisTranslation', function () {
if (this.recomputingForTilemap || this.coll === 'colorAxis') {
return;
}
var axis = this,
// Find which series' padding to use
seriesPadding = axis.series
.map(function (series) {
return series.getSeriesPixelPadding &&
series.getSeriesPixelPadding(axis);
})
.reduce(function (a, b) {
return (a && a.padding) > (b && b.padding) ?
a :
b;
}, void 0) ||
{
padding: 0,
axisLengthFactor: 1
}, lengthPadding = Math.round(seriesPadding.padding * seriesPadding.axisLengthFactor);
// Don't waste time on this if we're not adding extra padding
if (seriesPadding.padding) {
// Recompute translation with new axis length now (minus padding)
axis.len -= lengthPadding;
axis.recomputingForTilemap = true;
axis.setAxisTranslation();
delete axis.recomputingForTilemap;
axis.minPixelPadding += seriesPadding.padding;
axis.len += lengthPadding;
}
});
/**
* @private
* @class
* @name Highcharts.seriesTypes.tilemap
*
* @augments Highcharts.Series
*/
seriesType('tilemap', 'heatmap'
/**
* A tilemap series is a type of heatmap where the tile shapes are
* configurable.
*
* @sample highcharts/demo/honeycomb-usa/
* Honeycomb tilemap, USA
* @sample maps/plotoptions/honeycomb-brazil/
* Honeycomb tilemap, Brazil
* @sample maps/plotoptions/honeycomb-china/
* Honeycomb tilemap, China
* @sample maps/plotoptions/honeycomb-europe/
* Honeycomb tilemap, Europe
* @sample maps/demo/circlemap-africa/
* Circlemap tilemap, Africa
* @sample maps/demo/diamondmap
* Diamondmap tilemap
*
* @extends plotOptions.heatmap
* @since 6.0.0
* @excluding jitter, joinBy, shadow, allAreas, mapData, data,
* dataSorting
* @product highcharts highmaps
* @requires modules/tilemap.js
* @optionparent plotOptions.tilemap
*/
, {
states: {
hover: {
halo: {
enabled: true,
size: 2,
opacity: 0.5,
attributes: {
zIndex: 3
}
}
}
},
/**
* The padding between points in the tilemap.
*
* @sample maps/plotoptions/tilemap-pointpadding
* Point padding on tiles
*/
pointPadding: 2,
/**
* The column size - how many X axis units each column in the tilemap
* should span. Works as in [Heatmaps](#plotOptions.heatmap.colsize).
*
* @sample {highcharts} maps/demo/heatmap/
* One day
* @sample {highmaps} maps/demo/heatmap/
* One day
*
* @type {number}
* @default 1
* @product highcharts highmaps
* @apioption plotOptions.tilemap.colsize
*/
/**
* The row size - how many Y axis units each tilemap row should span.
* Analogous to [colsize](#plotOptions.tilemap.colsize).
*
* @sample {highcharts} maps/demo/heatmap/
* 1 by default
* @sample {highmaps} maps/demo/heatmap/
* 1 by default
*
* @type {number}
* @default 1
* @product highcharts highmaps
* @apioption plotOptions.tilemap.rowsize
*/
/**
* The shape of the tiles in the tilemap. Possible values are `hexagon`,
* `circle`, `diamond`, and `square`.
*
* @sample maps/demo/circlemap-africa
* Circular tile shapes
* @sample maps/demo/diamondmap
* Diamond tile shapes
*
* @type {Highcharts.TilemapShapeValue}
*/
tileShape: 'hexagon'
}, {
// Set tile shape object on series
setOptions: function () {
// Call original function
var ret = H.seriesTypes.heatmap.prototype.setOptions.apply(this, Array.prototype.slice.call(arguments));
this.tileShape = H.tileShapeTypes[ret.tileShape];
return ret;
},
// Use the shape's defined data label alignment function
alignDataLabel: function () {
return this.tileShape.alignDataLabel.apply(this, Array.prototype.slice.call(arguments));
},
// Get metrics for padding of axis for this series
getSeriesPixelPadding: function (axis) {
var isX = axis.isXAxis, padding = this.tileShape.getSeriesPadding(this), coord1, coord2;
// If the shape type does not require padding, return no-op padding
if (!padding) {
return {
padding: 0,
axisLengthFactor: 1
};
}
// Use translate to compute how far outside the points we
// draw, and use this difference as padding.
coord1 = Math.round(axis.translate(isX ?
padding.xPad * 2 :
padding.yPad, 0, 1, 0, 1));
coord2 = Math.round(axis.translate(isX ? padding.xPad : 0, 0, 1, 0, 1));
return {
padding: Math.abs(coord1 - coord2) || 0,
// Offset the yAxis length to compensate for shift. Setting the
// length factor to 2 would add the same margin to max as min.
// Now we only add a slight bit of the min margin to max, as we
// don't actually draw outside the max bounds. For the xAxis we
// draw outside on both sides so we add the same margin to min
// and max.
axisLengthFactor: isX ? 2 : 1.1
};
},
// Use translate from tileShape
translate: function () {
return this.tileShape.translate.apply(this, Array.prototype.slice.call(arguments));
}
}, extend({
// eslint-disable-next-line valid-jsdoc
/**
* @private
* @function Highcharts.Point#haloPath
*
* @return {Highcharts.SVGElement|Highcharts.SVGPathArray|Array<Highcharts.SVGElement>}
*/
haloPath: function () {
return this.series.tileShape.haloPath.apply(this, Array.prototype.slice.call(arguments));
}
}, H.colorPointMixin));
/**
* A `tilemap` series. If the [type](#series.tilemap.type) option is
* not specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.tilemap
* @excluding allAreas, dataParser, dataURL, joinBy, mapData, marker,
* pointRange, shadow, stack, dataSorting
* @product highcharts highmaps
* @requires modules/tilemap.js
* @apioption series.tilemap
*/
/**
* An array of data points for the series. For the `tilemap` series
* type, points can be given in the following ways:
*
* 1. An array of arrays with 3 or 2 values. In this case, the values correspond
* to `x,y,value`. If the first value is a string, it is applied as the name
* of the point, and the `x` value is inferred. The `x` value can also be
* omitted, in which case the inner arrays should be of length 2\. Then the
* `x` value is automatically calculated, either starting at 0 and
* incremented by 1, or from `pointStart` and `pointInterval` given in the
* series options.
* ```js
* data: [
* [0, 9, 7],
* [1, 10, 4],
* [2, 6, 3]
* ]
* ```
*
* 2. An array of objects with named values. The objects are point configuration
* objects as seen below. If the total number of data points exceeds the
* series' [turboThreshold](#series.tilemap.turboThreshold), this option is
* not available.
* ```js
* data: [{
* x: 1,
* y: 3,
* value: 10,
* name: "Point2",
* color: "#00FF00"
* }, {
* x: 1,
* y: 7,
* value: 10,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* Note that for some [tileShapes](#plotOptions.tilemap.tileShape) the grid
* coordinates are offset.
*
* @sample maps/series/tilemap-gridoffset
* Offset grid coordinates
* @sample {highcharts} highcharts/series/data-array-of-arrays/
* Arrays of numeric x and y
* @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/
* Arrays of datetime x and y
* @sample {highcharts} highcharts/series/data-array-of-name-value/
* Arrays of point.name and y
* @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
*
* @type {Array<Array<(number|string),number>|Array<(number|string),number,number>|*>}
* @extends series.heatmap.data
* @excluding marker
* @product highcharts highmaps
* @apioption series.tilemap.data
*/
/**
* The color of the point. In tilemaps the point color is rarely set
* explicitly, as we use the color to denote the `value`. Options for
* this are set in the [colorAxis](#colorAxis) configuration.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @product highcharts highmaps
* @apioption series.tilemap.data.color
*/
/**
* The x coordinate of the point.
*
* Note that for some [tileShapes](#plotOptions.tilemap.tileShape) the grid
* coordinates are offset.
*
* @sample maps/series/tilemap-gridoffset
* Offset grid coordinates
*
* @type {number}
* @product highcharts highmaps
* @apioption series.tilemap.data.x
*/
/**
* The y coordinate of the point.
*
* Note that for some [tileShapes](#plotOptions.tilemap.tileShape) the grid
* coordinates are offset.
*
* @sample maps/series/tilemap-gridoffset
* Offset grid coordinates
*
* @type {number}
* @product highcharts highmaps
* @apioption series.tilemap.data.y
*/
''; // adds doclets above to the transpiled file

Some files were not shown because too many files have changed in this diff Show More