NavigationBindings.js 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042
  1. /* *
  2. *
  3. * (c) 2009-2017 Highsoft, Black Label
  4. *
  5. * License: www.highcharts.com/license
  6. *
  7. * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
  8. *
  9. * */
  10. 'use strict';
  11. import Annotation from './Annotations.js';
  12. import Chart from '../../Core/Chart/Chart.js';
  13. import chartNavigationMixin from '../../Mixins/Navigation.js';
  14. import H from '../../Core/Globals.js';
  15. import U from '../../Core/Utilities.js';
  16. var addEvent = U.addEvent, attr = U.attr, extend = U.extend, format = U.format, fireEvent = U.fireEvent, isArray = U.isArray, isFunction = U.isFunction, isNumber = U.isNumber, isObject = U.isObject, merge = U.merge, objectEach = U.objectEach, pick = U.pick, setOptions = U.setOptions;
  17. /**
  18. * A config object for navigation bindings in annotations.
  19. *
  20. * @interface Highcharts.NavigationBindingsOptionsObject
  21. */ /**
  22. * ClassName of the element for a binding.
  23. * @name Highcharts.NavigationBindingsOptionsObject#className
  24. * @type {string|undefined}
  25. */ /**
  26. * Last event to be fired after last step event.
  27. * @name Highcharts.NavigationBindingsOptionsObject#end
  28. * @type {Function|undefined}
  29. */ /**
  30. * Initial event, fired on a button click.
  31. * @name Highcharts.NavigationBindingsOptionsObject#init
  32. * @type {Function|undefined}
  33. */ /**
  34. * Event fired on first click on a chart.
  35. * @name Highcharts.NavigationBindingsOptionsObject#start
  36. * @type {Function|undefined}
  37. */ /**
  38. * Last event to be fired after last step event. Array of step events to be
  39. * called sequentially after each user click.
  40. * @name Highcharts.NavigationBindingsOptionsObject#steps
  41. * @type {Array<Function>|undefined}
  42. */
  43. var doc = H.doc, win = H.win, PREFIX = 'highcharts-';
  44. /* eslint-disable no-invalid-this, valid-jsdoc */
  45. /**
  46. * IE 9-11 polyfill for Element.closest():
  47. * @private
  48. */
  49. function closestPolyfill(el, s) {
  50. var ElementProto = win.Element.prototype, elementMatches = ElementProto.matches ||
  51. ElementProto.msMatchesSelector ||
  52. ElementProto.webkitMatchesSelector, ret = null;
  53. if (ElementProto.closest) {
  54. ret = ElementProto.closest.call(el, s);
  55. }
  56. else {
  57. do {
  58. if (elementMatches.call(el, s)) {
  59. return el;
  60. }
  61. el = el.parentElement || el.parentNode;
  62. } while (el !== null && el.nodeType === 1);
  63. }
  64. return ret;
  65. }
  66. /**
  67. * @private
  68. * @interface bindingsUtils
  69. */
  70. var bindingsUtils = {
  71. /**
  72. * Update size of background (rect) in some annotations: Measure, Simple
  73. * Rect.
  74. *
  75. * @private
  76. * @function Highcharts.NavigationBindingsUtilsObject.updateRectSize
  77. *
  78. * @param {Highcharts.PointerEventObject} event
  79. * Normalized browser event
  80. *
  81. * @param {Highcharts.Annotation} annotation
  82. * Annotation to be updated
  83. */
  84. updateRectSize: function (event, annotation) {
  85. var chart = annotation.chart, options = annotation.options.typeOptions, coords = chart.pointer.getCoordinates(event), width = coords.xAxis[0].value - options.point.x, height = options.point.y - coords.yAxis[0].value;
  86. annotation.update({
  87. typeOptions: {
  88. background: {
  89. width: chart.inverted ? height : width,
  90. height: chart.inverted ? width : height
  91. }
  92. }
  93. });
  94. },
  95. /**
  96. * Get field type according to value
  97. *
  98. * @private
  99. * @function Highcharts.NavigationBindingsUtilsObject.getFieldType
  100. *
  101. * @param {'boolean'|'number'|'string'} value
  102. * Atomic type (one of: string, number, boolean)
  103. *
  104. * @return {'checkbox'|'number'|'text'}
  105. * Field type (one of: text, number, checkbox)
  106. */
  107. getFieldType: function (value) {
  108. return {
  109. 'string': 'text',
  110. 'number': 'number',
  111. 'boolean': 'checkbox'
  112. }[typeof value];
  113. }
  114. };
  115. /**
  116. * @private
  117. */
  118. var NavigationBindings = /** @class */ (function () {
  119. /* *
  120. *
  121. * Constructors
  122. *
  123. * */
  124. function NavigationBindings(chart, options) {
  125. this.boundClassNames = void 0;
  126. this.selectedButton = void 0;
  127. this.chart = chart;
  128. this.options = options;
  129. this.eventsToUnbind = [];
  130. this.container = doc.getElementsByClassName(this.options.bindingsClassName || '');
  131. }
  132. // Private properties added by bindings:
  133. // Active (selected) annotation that is editted through popup/forms
  134. // activeAnnotation: Annotation
  135. // Holder for current step, used on mouse move to update bound object
  136. // mouseMoveEvent: function () {}
  137. // Next event in `step` array to be called on chart's click
  138. // nextEvent: function () {}
  139. // Index in the `step` array of the current event
  140. // stepIndex: 0
  141. // Flag to determine if current binding has steps
  142. // steps: true|false
  143. // Bindings holder for all events
  144. // selectedButton: {}
  145. // Holder for user options, returned from `start` event, and passed on to
  146. // `step`'s' and `end`.
  147. // currentUserDetails: {}
  148. /* *
  149. *
  150. * Functions
  151. *
  152. * */
  153. /**
  154. * Initi all events conencted to NavigationBindings.
  155. *
  156. * @private
  157. * @function Highcharts.NavigationBindings#initEvents
  158. */
  159. NavigationBindings.prototype.initEvents = function () {
  160. var navigation = this, chart = navigation.chart, bindingsContainer = navigation.container, options = navigation.options;
  161. // Shorthand object for getting events for buttons:
  162. navigation.boundClassNames = {};
  163. objectEach((options.bindings || {}), function (value) {
  164. navigation.boundClassNames[value.className] = value;
  165. });
  166. // Handle multiple containers with the same class names:
  167. [].forEach.call(bindingsContainer, function (subContainer) {
  168. navigation.eventsToUnbind.push(addEvent(subContainer, 'click', function (event) {
  169. var bindings = navigation.getButtonEvents(subContainer, event);
  170. if (bindings) {
  171. navigation.bindingsButtonClick(bindings.button, bindings.events, event);
  172. }
  173. }));
  174. });
  175. objectEach(options.events || {}, function (callback, eventName) {
  176. if (isFunction(callback)) {
  177. navigation.eventsToUnbind.push(addEvent(navigation, eventName, callback));
  178. }
  179. });
  180. navigation.eventsToUnbind.push(addEvent(chart.container, 'click', function (e) {
  181. if (!chart.cancelClick &&
  182. chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
  183. navigation.bindingsChartClick(this, e);
  184. }
  185. }));
  186. navigation.eventsToUnbind.push(addEvent(chart.container, H.isTouchDevice ? 'touchmove' : 'mousemove', function (e) {
  187. navigation.bindingsContainerMouseMove(this, e);
  188. }));
  189. };
  190. /**
  191. * Common chart.update() delegation, shared between bindings and exporting.
  192. *
  193. * @private
  194. * @function Highcharts.NavigationBindings#initUpdate
  195. */
  196. NavigationBindings.prototype.initUpdate = function () {
  197. var navigation = this;
  198. chartNavigationMixin.addUpdate(function (options) {
  199. navigation.update(options);
  200. }, this.chart);
  201. };
  202. /**
  203. * Hook for click on a button, method selcts/unselects buttons,
  204. * then calls `bindings.init` callback.
  205. *
  206. * @private
  207. * @function Highcharts.NavigationBindings#bindingsButtonClick
  208. *
  209. * @param {Highcharts.HTMLDOMElement} [button]
  210. * Clicked button
  211. *
  212. * @param {object} events
  213. * Events passed down from bindings (`init`, `start`, `step`, `end`)
  214. *
  215. * @param {Highcharts.PointerEventObject} clickEvent
  216. * Browser's click event
  217. */
  218. NavigationBindings.prototype.bindingsButtonClick = function (button, events, clickEvent) {
  219. var navigation = this, chart = navigation.chart;
  220. if (navigation.selectedButtonElement) {
  221. fireEvent(navigation, 'deselectButton', { button: navigation.selectedButtonElement });
  222. if (navigation.nextEvent) {
  223. // Remove in-progress annotations adders:
  224. if (navigation.currentUserDetails &&
  225. navigation.currentUserDetails.coll === 'annotations') {
  226. chart.removeAnnotation(navigation.currentUserDetails);
  227. }
  228. navigation.mouseMoveEvent = navigation.nextEvent = false;
  229. }
  230. }
  231. navigation.selectedButton = events;
  232. navigation.selectedButtonElement = button;
  233. fireEvent(navigation, 'selectButton', { button: button });
  234. // Call "init" event, for example to open modal window
  235. if (events.init) {
  236. events.init.call(navigation, button, clickEvent);
  237. }
  238. if (events.start || events.steps) {
  239. chart.renderer.boxWrapper.addClass(PREFIX + 'draw-mode');
  240. }
  241. };
  242. /**
  243. * Hook for click on a chart, first click on a chart calls `start` event,
  244. * then on all subsequent clicks iterate over `steps` array.
  245. * When finished, calls `end` event.
  246. *
  247. * @private
  248. * @function Highcharts.NavigationBindings#bindingsChartClick
  249. *
  250. * @param {Highcharts.Chart} chart
  251. * Chart that click was performed on.
  252. *
  253. * @param {Highcharts.PointerEventObject} clickEvent
  254. * Browser's click event.
  255. */
  256. NavigationBindings.prototype.bindingsChartClick = function (chart, clickEvent) {
  257. var navigation = this, chart = navigation.chart, selectedButton = navigation.selectedButton, svgContainer = chart.renderer.boxWrapper;
  258. // Click outside popups, should close them and deselect the annotation
  259. if (navigation.activeAnnotation &&
  260. !clickEvent.activeAnnotation &&
  261. // Element could be removed in the child action, e.g. button
  262. clickEvent.target.parentNode &&
  263. // TO DO: Polyfill for IE11?
  264. !closestPolyfill(clickEvent.target, '.' + PREFIX + 'popup')) {
  265. fireEvent(navigation, 'closePopup');
  266. navigation.deselectAnnotation();
  267. }
  268. if (!selectedButton || !selectedButton.start) {
  269. return;
  270. }
  271. if (!navigation.nextEvent) {
  272. // Call init method:
  273. navigation.currentUserDetails = selectedButton.start.call(navigation, clickEvent);
  274. // If steps exists (e.g. Annotations), bind them:
  275. if (selectedButton.steps) {
  276. navigation.stepIndex = 0;
  277. navigation.steps = true;
  278. navigation.mouseMoveEvent = navigation.nextEvent =
  279. selectedButton.steps[navigation.stepIndex];
  280. }
  281. else {
  282. fireEvent(navigation, 'deselectButton', { button: navigation.selectedButtonElement });
  283. svgContainer.removeClass(PREFIX + 'draw-mode');
  284. navigation.steps = false;
  285. navigation.selectedButton = null;
  286. // First click is also the last one:
  287. if (selectedButton.end) {
  288. selectedButton.end.call(navigation, clickEvent, navigation.currentUserDetails);
  289. }
  290. }
  291. }
  292. else {
  293. navigation.nextEvent(clickEvent, navigation.currentUserDetails);
  294. if (navigation.steps) {
  295. navigation.stepIndex++;
  296. if (selectedButton.steps[navigation.stepIndex]) {
  297. // If we have more steps, bind them one by one:
  298. navigation.mouseMoveEvent = navigation.nextEvent =
  299. selectedButton.steps[navigation.stepIndex];
  300. }
  301. else {
  302. fireEvent(navigation, 'deselectButton', { button: navigation.selectedButtonElement });
  303. svgContainer.removeClass(PREFIX + 'draw-mode');
  304. // That was the last step, call end():
  305. if (selectedButton.end) {
  306. selectedButton.end.call(navigation, clickEvent, navigation.currentUserDetails);
  307. }
  308. navigation.nextEvent = false;
  309. navigation.mouseMoveEvent = false;
  310. navigation.selectedButton = null;
  311. }
  312. }
  313. }
  314. };
  315. /**
  316. * Hook for mouse move on a chart's container. It calls current step.
  317. *
  318. * @private
  319. * @function Highcharts.NavigationBindings#bindingsContainerMouseMove
  320. *
  321. * @param {Highcharts.HTMLDOMElement} container
  322. * Chart's container.
  323. *
  324. * @param {global.Event} moveEvent
  325. * Browser's move event.
  326. */
  327. NavigationBindings.prototype.bindingsContainerMouseMove = function (_container, moveEvent) {
  328. if (this.mouseMoveEvent) {
  329. this.mouseMoveEvent(moveEvent, this.currentUserDetails);
  330. }
  331. };
  332. /**
  333. * Translate fields (e.g. `params.period` or `marker.styles.color`) to
  334. * Highcharts options object (e.g. `{ params: { period } }`).
  335. *
  336. * @private
  337. * @function Highcharts.NavigationBindings#fieldsToOptions<T>
  338. *
  339. * @param {Highcharts.Dictionary<string>} fields
  340. * Fields from popup form.
  341. *
  342. * @param {T} config
  343. * Default config to be modified.
  344. *
  345. * @return {T}
  346. * Modified config
  347. */
  348. NavigationBindings.prototype.fieldsToOptions = function (fields, config) {
  349. objectEach(fields, function (value, field) {
  350. var parsedValue = parseFloat(value), path = field.split('.'), parent = config, pathLength = path.length - 1;
  351. // If it's a number (not "format" options), parse it:
  352. if (isNumber(parsedValue) &&
  353. !value.match(/px/g) &&
  354. !field.match(/format/g)) {
  355. value = parsedValue;
  356. }
  357. // Remove empty strings or values like 0
  358. if (value !== '' && value !== 'undefined') {
  359. path.forEach(function (name, index) {
  360. var nextName = pick(path[index + 1], '');
  361. if (pathLength === index) {
  362. // Last index, put value:
  363. parent[name] = value;
  364. }
  365. else if (!parent[name]) {
  366. // Create middle property:
  367. parent[name] = nextName.match(/\d/g) ? [] : {};
  368. parent = parent[name];
  369. }
  370. else {
  371. // Jump into next property
  372. parent = parent[name];
  373. }
  374. });
  375. }
  376. });
  377. return config;
  378. };
  379. /**
  380. * Shorthand method to deselect an annotation.
  381. *
  382. * @function Highcharts.NavigationBindings#deselectAnnotation
  383. */
  384. NavigationBindings.prototype.deselectAnnotation = function () {
  385. if (this.activeAnnotation) {
  386. this.activeAnnotation.setControlPointsVisibility(false);
  387. this.activeAnnotation = false;
  388. }
  389. };
  390. /**
  391. * Generates API config for popup in the same format as options for
  392. * Annotation object.
  393. *
  394. * @function Highcharts.NavigationBindings#annotationToFields
  395. *
  396. * @param {Highcharts.Annotation} annotation
  397. * Annotations object
  398. *
  399. * @return {Highcharts.Dictionary<string>}
  400. * Annotation options to be displayed in popup box
  401. */
  402. NavigationBindings.prototype.annotationToFields = function (annotation) {
  403. var options = annotation.options, editables = NavigationBindings.annotationsEditable, nestedEditables = editables.nestedOptions, getFieldType = this.utils.getFieldType, type = pick(options.type, options.shapes && options.shapes[0] &&
  404. options.shapes[0].type, options.labels && options.labels[0] &&
  405. options.labels[0].itemType, 'label'), nonEditables = NavigationBindings.annotationsNonEditable[options.langKey] || [], visualOptions = {
  406. langKey: options.langKey,
  407. type: type
  408. };
  409. /**
  410. * Nested options traversing. Method goes down to the options and copies
  411. * allowed options (with values) to new object, which is last parameter:
  412. * "parent".
  413. *
  414. * @private
  415. *
  416. * @param {*} option
  417. * Atomic type or object/array
  418. *
  419. * @param {string} key
  420. * Option name, for example "visible" or "x", "y"
  421. *
  422. * @param {object} parentEditables
  423. * Editables from NavigationBindings.annotationsEditable
  424. *
  425. * @param {object} parent
  426. * Where new options will be assigned
  427. */
  428. function traverse(option, key, parentEditables, parent) {
  429. var nextParent;
  430. if (parentEditables &&
  431. option &&
  432. nonEditables.indexOf(key) === -1 &&
  433. ((parentEditables.indexOf &&
  434. parentEditables.indexOf(key)) >= 0 ||
  435. parentEditables[key] || // nested array
  436. parentEditables === true // simple array
  437. )) {
  438. // Roots:
  439. if (isArray(option)) {
  440. parent[key] = [];
  441. option.forEach(function (arrayOption, i) {
  442. if (!isObject(arrayOption)) {
  443. // Simple arrays, e.g. [String, Number, Boolean]
  444. traverse(arrayOption, 0, nestedEditables[key], parent[key]);
  445. }
  446. else {
  447. // Advanced arrays, e.g. [Object, Object]
  448. parent[key][i] = {};
  449. objectEach(arrayOption, function (nestedOption, nestedKey) {
  450. traverse(nestedOption, nestedKey, nestedEditables[key], parent[key][i]);
  451. });
  452. }
  453. });
  454. }
  455. else if (isObject(option)) {
  456. nextParent = {};
  457. if (isArray(parent)) {
  458. parent.push(nextParent);
  459. nextParent[key] = {};
  460. nextParent = nextParent[key];
  461. }
  462. else {
  463. parent[key] = nextParent;
  464. }
  465. objectEach(option, function (nestedOption, nestedKey) {
  466. traverse(nestedOption, nestedKey, key === 0 ? parentEditables : nestedEditables[key], nextParent);
  467. });
  468. }
  469. else {
  470. // Leaf:
  471. if (key === 'format') {
  472. parent[key] = [
  473. format(option, annotation.labels[0].points[0]).toString(),
  474. 'text'
  475. ];
  476. }
  477. else if (isArray(parent)) {
  478. parent.push([option, getFieldType(option)]);
  479. }
  480. else {
  481. parent[key] = [option, getFieldType(option)];
  482. }
  483. }
  484. }
  485. }
  486. objectEach(options, function (option, key) {
  487. if (key === 'typeOptions') {
  488. visualOptions[key] = {};
  489. objectEach(options[key], function (typeOption, typeKey) {
  490. traverse(typeOption, typeKey, nestedEditables, visualOptions[key], true);
  491. });
  492. }
  493. else {
  494. traverse(option, key, editables[type], visualOptions);
  495. }
  496. });
  497. return visualOptions;
  498. };
  499. /**
  500. * Get all class names for all parents in the element. Iterates until finds
  501. * main container.
  502. *
  503. * @function Highcharts.NavigationBindings#getClickedClassNames
  504. *
  505. * @param {Highcharts.HTMLDOMElement}
  506. * Container that event is bound to.
  507. *
  508. * @param {global.Event} event
  509. * Browser's event.
  510. *
  511. * @return {Array<Array<string, Highcharts.HTMLDOMElement>>}
  512. * Array of class names with corresponding elements
  513. */
  514. NavigationBindings.prototype.getClickedClassNames = function (container, event) {
  515. var element = event.target, classNames = [], elemClassName;
  516. while (element) {
  517. elemClassName = attr(element, 'class');
  518. if (elemClassName) {
  519. classNames = classNames.concat(elemClassName
  520. .split(' ')
  521. .map(function (name) {
  522. return [
  523. name,
  524. element
  525. ];
  526. }));
  527. }
  528. element = element.parentNode;
  529. if (element === container) {
  530. return classNames;
  531. }
  532. }
  533. return classNames;
  534. };
  535. /**
  536. * Get events bound to a button. It's a custom event delegation to find all
  537. * events connected to the element.
  538. *
  539. * @private
  540. * @function Highcharts.NavigationBindings#getButtonEvents
  541. *
  542. * @param {Highcharts.HTMLDOMElement} container
  543. * Container that event is bound to.
  544. *
  545. * @param {global.Event} event
  546. * Browser's event.
  547. *
  548. * @return {object}
  549. * Object with events (init, start, steps, and end)
  550. */
  551. NavigationBindings.prototype.getButtonEvents = function (container, event) {
  552. var navigation = this, classNames = this.getClickedClassNames(container, event), bindings;
  553. classNames.forEach(function (className) {
  554. if (navigation.boundClassNames[className[0]] && !bindings) {
  555. bindings = {
  556. events: navigation.boundClassNames[className[0]],
  557. button: className[1]
  558. };
  559. }
  560. });
  561. return bindings;
  562. };
  563. /**
  564. * Bindings are just events, so the whole update process is simply
  565. * removing old events and adding new ones.
  566. *
  567. * @private
  568. * @function Highcharts.NavigationBindings#update
  569. */
  570. NavigationBindings.prototype.update = function (options) {
  571. this.options = merge(true, this.options, options);
  572. this.removeEvents();
  573. this.initEvents();
  574. };
  575. /**
  576. * Remove all events created in the navigation.
  577. *
  578. * @private
  579. * @function Highcharts.NavigationBindings#removeEvents
  580. */
  581. NavigationBindings.prototype.removeEvents = function () {
  582. this.eventsToUnbind.forEach(function (unbinder) {
  583. unbinder();
  584. });
  585. };
  586. NavigationBindings.prototype.destroy = function () {
  587. this.removeEvents();
  588. };
  589. /* *
  590. *
  591. * Static Properties
  592. *
  593. * */
  594. // Define which options from annotations should show up in edit box:
  595. NavigationBindings.annotationsEditable = {
  596. // `typeOptions` are always available
  597. // Nested and shared options:
  598. nestedOptions: {
  599. labelOptions: ['style', 'format', 'backgroundColor'],
  600. labels: ['style'],
  601. label: ['style'],
  602. style: ['fontSize', 'color'],
  603. background: ['fill', 'strokeWidth', 'stroke'],
  604. innerBackground: ['fill', 'strokeWidth', 'stroke'],
  605. outerBackground: ['fill', 'strokeWidth', 'stroke'],
  606. shapeOptions: ['fill', 'strokeWidth', 'stroke'],
  607. shapes: ['fill', 'strokeWidth', 'stroke'],
  608. line: ['strokeWidth', 'stroke'],
  609. backgroundColors: [true],
  610. connector: ['fill', 'strokeWidth', 'stroke'],
  611. crosshairX: ['strokeWidth', 'stroke'],
  612. crosshairY: ['strokeWidth', 'stroke']
  613. },
  614. // Simple shapes:
  615. circle: ['shapes'],
  616. verticalLine: [],
  617. label: ['labelOptions'],
  618. // Measure
  619. measure: ['background', 'crosshairY', 'crosshairX'],
  620. // Others:
  621. fibonacci: [],
  622. tunnel: ['background', 'line', 'height'],
  623. pitchfork: ['innerBackground', 'outerBackground'],
  624. rect: ['shapes'],
  625. // Crooked lines, elliots, arrows etc:
  626. crookedLine: [],
  627. basicAnnotation: ['shapes', 'labelOptions']
  628. };
  629. // Define non editable fields per annotation, for example Rectangle inherits
  630. // options from Measure, but crosshairs are not available
  631. NavigationBindings.annotationsNonEditable = {
  632. rectangle: ['crosshairX', 'crosshairY', 'label']
  633. };
  634. return NavigationBindings;
  635. }());
  636. /**
  637. * General utils for bindings
  638. *
  639. * @private
  640. * @name Highcharts.NavigationBindings.utils
  641. * @type {bindingsUtils}
  642. */
  643. NavigationBindings.prototype.utils = bindingsUtils;
  644. Chart.prototype.initNavigationBindings = function () {
  645. var chart = this, options = chart.options;
  646. if (options && options.navigation && options.navigation.bindings) {
  647. chart.navigationBindings = new NavigationBindings(chart, options.navigation);
  648. chart.navigationBindings.initEvents();
  649. chart.navigationBindings.initUpdate();
  650. }
  651. };
  652. addEvent(Chart, 'load', function () {
  653. this.initNavigationBindings();
  654. });
  655. addEvent(Chart, 'destroy', function () {
  656. if (this.navigationBindings) {
  657. this.navigationBindings.destroy();
  658. }
  659. });
  660. addEvent(NavigationBindings, 'deselectButton', function () {
  661. this.selectedButtonElement = null;
  662. });
  663. addEvent(Annotation, 'remove', function () {
  664. if (this.chart.navigationBindings) {
  665. this.chart.navigationBindings.deselectAnnotation();
  666. }
  667. });
  668. /**
  669. * Show edit-annotation form:
  670. * @private
  671. */
  672. function selectableAnnotation(annotationType) {
  673. var originalClick = annotationType.prototype.defaultOptions.events &&
  674. annotationType.prototype.defaultOptions.events.click;
  675. /**
  676. * @private
  677. */
  678. function selectAndshowPopup(event) {
  679. var annotation = this, navigation = annotation.chart.navigationBindings, prevAnnotation = navigation.activeAnnotation;
  680. if (originalClick) {
  681. originalClick.call(annotation, event);
  682. }
  683. if (prevAnnotation !== annotation) {
  684. // Select current:
  685. navigation.deselectAnnotation();
  686. navigation.activeAnnotation = annotation;
  687. annotation.setControlPointsVisibility(true);
  688. fireEvent(navigation, 'showPopup', {
  689. annotation: annotation,
  690. formType: 'annotation-toolbar',
  691. options: navigation.annotationToFields(annotation),
  692. onSubmit: function (data) {
  693. var config = {}, typeOptions;
  694. if (data.actionType === 'remove') {
  695. navigation.activeAnnotation = false;
  696. navigation.chart.removeAnnotation(annotation);
  697. }
  698. else {
  699. navigation.fieldsToOptions(data.fields, config);
  700. navigation.deselectAnnotation();
  701. typeOptions = config.typeOptions;
  702. if (annotation.options.type === 'measure') {
  703. // Manually disable crooshars according to
  704. // stroke width of the shape:
  705. typeOptions.crosshairY.enabled =
  706. typeOptions.crosshairY.strokeWidth !== 0;
  707. typeOptions.crosshairX.enabled =
  708. typeOptions.crosshairX.strokeWidth !== 0;
  709. }
  710. annotation.update(config);
  711. }
  712. }
  713. });
  714. }
  715. else {
  716. // Deselect current:
  717. navigation.deselectAnnotation();
  718. fireEvent(navigation, 'closePopup');
  719. }
  720. // Let bubble event to chart.click:
  721. event.activeAnnotation = true;
  722. }
  723. merge(true, annotationType.prototype.defaultOptions.events, {
  724. click: selectAndshowPopup
  725. });
  726. }
  727. if (H.Annotation) {
  728. // Basic shapes:
  729. selectableAnnotation(Annotation);
  730. // Advanced annotations:
  731. objectEach(Annotation.types, function (annotationType) {
  732. selectableAnnotation(annotationType);
  733. });
  734. }
  735. setOptions({
  736. /**
  737. * @optionparent lang
  738. *
  739. * @private
  740. */
  741. lang: {
  742. /**
  743. * Configure the Popup strings in the chart. Requires the
  744. * `annotations.js` or `annotations-advanced.src.js` module to be
  745. * loaded.
  746. *
  747. * @since 7.0.0
  748. * @product highcharts highstock
  749. */
  750. navigation: {
  751. /**
  752. * Translations for all field names used in popup.
  753. *
  754. * @product highcharts highstock
  755. */
  756. popup: {
  757. simpleShapes: 'Simple shapes',
  758. lines: 'Lines',
  759. circle: 'Circle',
  760. rectangle: 'Rectangle',
  761. label: 'Label',
  762. shapeOptions: 'Shape options',
  763. typeOptions: 'Details',
  764. fill: 'Fill',
  765. format: 'Text',
  766. strokeWidth: 'Line width',
  767. stroke: 'Line color',
  768. title: 'Title',
  769. name: 'Name',
  770. labelOptions: 'Label options',
  771. labels: 'Labels',
  772. backgroundColor: 'Background color',
  773. backgroundColors: 'Background colors',
  774. borderColor: 'Border color',
  775. borderRadius: 'Border radius',
  776. borderWidth: 'Border width',
  777. style: 'Style',
  778. padding: 'Padding',
  779. fontSize: 'Font size',
  780. color: 'Color',
  781. height: 'Height',
  782. shapes: 'Shape options'
  783. }
  784. }
  785. },
  786. /**
  787. * @optionparent navigation
  788. * @product highcharts highstock
  789. *
  790. * @private
  791. */
  792. navigation: {
  793. /**
  794. * A CSS class name where all bindings will be attached to. Multiple
  795. * charts on the same page should have separate class names to prevent
  796. * duplicating events.
  797. *
  798. * Default value of versions < 7.0.4 `highcharts-bindings-wrapper`
  799. *
  800. * @since 7.0.0
  801. * @type {string}
  802. */
  803. bindingsClassName: 'highcharts-bindings-container',
  804. /**
  805. * Bindings definitions for custom HTML buttons. Each binding implements
  806. * simple event-driven interface:
  807. *
  808. * - `className`: classname used to bind event to
  809. *
  810. * - `init`: initial event, fired on button click
  811. *
  812. * - `start`: fired on first click on a chart
  813. *
  814. * - `steps`: array of sequential events fired one after another on each
  815. * of users clicks
  816. *
  817. * - `end`: last event to be called after last step event
  818. *
  819. * @type {Highcharts.Dictionary<Highcharts.NavigationBindingsOptionsObject>|*}
  820. * @sample stock/stocktools/stocktools-thresholds
  821. * Custom bindings in Highstock
  822. * @since 7.0.0
  823. * @product highcharts highstock
  824. */
  825. bindings: {
  826. /**
  827. * A circle annotation bindings. Includes `start` and one event in
  828. * `steps` array.
  829. *
  830. * @type {Highcharts.NavigationBindingsOptionsObject}
  831. * @default {"className": "highcharts-circle-annotation", "start": function() {}, "steps": [function() {}], "annotationsOptions": {}}
  832. */
  833. circleAnnotation: {
  834. /** @ignore-option */
  835. className: 'highcharts-circle-annotation',
  836. /** @ignore-option */
  837. start: function (e) {
  838. var coords = this.chart.pointer.getCoordinates(e), navigation = this.chart.options.navigation;
  839. return this.chart.addAnnotation(merge({
  840. langKey: 'circle',
  841. type: 'basicAnnotation',
  842. shapes: [{
  843. type: 'circle',
  844. point: {
  845. xAxis: 0,
  846. yAxis: 0,
  847. x: coords.xAxis[0].value,
  848. y: coords.yAxis[0].value
  849. },
  850. r: 5
  851. }]
  852. }, navigation
  853. .annotationsOptions, navigation
  854. .bindings
  855. .circleAnnotation
  856. .annotationsOptions));
  857. },
  858. /** @ignore-option */
  859. steps: [
  860. function (e, annotation) {
  861. var point = annotation.options.shapes[0].point, x = this.chart.xAxis[0].toPixels(point.x), y = this.chart.yAxis[0].toPixels(point.y), inverted = this.chart.inverted, distance = Math.max(Math.sqrt(Math.pow(inverted ? y - e.chartX : x - e.chartX, 2) +
  862. Math.pow(inverted ? x - e.chartY : y - e.chartY, 2)), 5);
  863. annotation.update({
  864. shapes: [{
  865. r: distance
  866. }]
  867. });
  868. }
  869. ]
  870. },
  871. /**
  872. * A rectangle annotation bindings. Includes `start` and one event
  873. * in `steps` array.
  874. *
  875. * @type {Highcharts.NavigationBindingsOptionsObject}
  876. * @default {"className": "highcharts-rectangle-annotation", "start": function() {}, "steps": [function() {}], "annotationsOptions": {}}
  877. */
  878. rectangleAnnotation: {
  879. /** @ignore-option */
  880. className: 'highcharts-rectangle-annotation',
  881. /** @ignore-option */
  882. start: function (e) {
  883. var coords = this.chart.pointer.getCoordinates(e), navigation = this.chart.options.navigation, x = coords.xAxis[0].value, y = coords.yAxis[0].value;
  884. return this.chart.addAnnotation(merge({
  885. langKey: 'rectangle',
  886. type: 'basicAnnotation',
  887. shapes: [{
  888. type: 'path',
  889. points: [{
  890. xAxis: 0,
  891. yAxis: 0,
  892. x: x,
  893. y: y
  894. }, {
  895. xAxis: 0,
  896. yAxis: 0,
  897. x: x,
  898. y: y
  899. }, {
  900. xAxis: 0,
  901. yAxis: 0,
  902. x: x,
  903. y: y
  904. }, {
  905. xAxis: 0,
  906. yAxis: 0,
  907. x: x,
  908. y: y
  909. }]
  910. }]
  911. }, navigation
  912. .annotationsOptions, navigation
  913. .bindings
  914. .rectangleAnnotation
  915. .annotationsOptions));
  916. },
  917. /** @ignore-option */
  918. steps: [
  919. function (e, annotation) {
  920. var points = annotation.options.shapes[0].points, coords = this.chart.pointer.getCoordinates(e), x = coords.xAxis[0].value, y = coords.yAxis[0].value;
  921. // Top right point
  922. points[1].x = x;
  923. // Bottom right point (cursor position)
  924. points[2].x = x;
  925. points[2].y = y;
  926. // Bottom left
  927. points[3].y = y;
  928. annotation.update({
  929. shapes: [{
  930. points: points
  931. }]
  932. });
  933. }
  934. ]
  935. },
  936. /**
  937. * A label annotation bindings. Includes `start` event only.
  938. *
  939. * @type {Highcharts.NavigationBindingsOptionsObject}
  940. * @default {"className": "highcharts-label-annotation", "start": function() {}, "steps": [function() {}], "annotationsOptions": {}}
  941. */
  942. labelAnnotation: {
  943. /** @ignore-option */
  944. className: 'highcharts-label-annotation',
  945. /** @ignore-option */
  946. start: function (e) {
  947. var coords = this.chart.pointer.getCoordinates(e), navigation = this.chart.options.navigation;
  948. return this.chart.addAnnotation(merge({
  949. langKey: 'label',
  950. type: 'basicAnnotation',
  951. labelOptions: {
  952. format: '{y:.2f}'
  953. },
  954. labels: [{
  955. point: {
  956. xAxis: 0,
  957. yAxis: 0,
  958. x: coords.xAxis[0].value,
  959. y: coords.yAxis[0].value
  960. },
  961. overflow: 'none',
  962. crop: true
  963. }]
  964. }, navigation
  965. .annotationsOptions, navigation
  966. .bindings
  967. .labelAnnotation
  968. .annotationsOptions));
  969. }
  970. }
  971. },
  972. /**
  973. * Path where Highcharts will look for icons. Change this to use icons
  974. * from a different server.
  975. *
  976. * @type {string}
  977. * @default https://code.highcharts.com/8.2.2/gfx/stock-icons/
  978. * @since 7.1.3
  979. * @apioption navigation.iconsURL
  980. */
  981. /**
  982. * A `showPopup` event. Fired when selecting for example an annotation.
  983. *
  984. * @type {Function}
  985. * @apioption navigation.events.showPopup
  986. */
  987. /**
  988. * A `closePopup` event. Fired when Popup should be hidden, for example
  989. * when clicking on an annotation again.
  990. *
  991. * @type {Function}
  992. * @apioption navigation.events.closePopup
  993. */
  994. /**
  995. * Event fired on a button click.
  996. *
  997. * @type {Function}
  998. * @sample highcharts/annotations/gui/
  999. * Change icon in a dropddown on event
  1000. * @sample highcharts/annotations/gui-buttons/
  1001. * Change button class on event
  1002. * @apioption navigation.events.selectButton
  1003. */
  1004. /**
  1005. * Event fired when button state should change, for example after
  1006. * adding an annotation.
  1007. *
  1008. * @type {Function}
  1009. * @sample highcharts/annotations/gui/
  1010. * Change icon in a dropddown on event
  1011. * @sample highcharts/annotations/gui-buttons/
  1012. * Change button class on event
  1013. * @apioption navigation.events.deselectButton
  1014. */
  1015. /**
  1016. * Events to communicate between Stock Tools and custom GUI.
  1017. *
  1018. * @since 7.0.0
  1019. * @product highcharts highstock
  1020. * @optionparent navigation.events
  1021. */
  1022. events: {},
  1023. /**
  1024. * Additional options to be merged into all annotations.
  1025. *
  1026. * @sample stock/stocktools/navigation-annotation-options
  1027. * Set red color of all line annotations
  1028. *
  1029. * @type {Highcharts.AnnotationsOptions}
  1030. * @extends annotations
  1031. * @exclude crookedLine, elliottWave, fibonacci, infinityLine,
  1032. * measure, pitchfork, tunnel, verticalLine, basicAnnotation
  1033. * @apioption navigation.annotationsOptions
  1034. */
  1035. annotationsOptions: {
  1036. animation: {
  1037. defer: 0
  1038. }
  1039. }
  1040. }
  1041. });
  1042. export default NavigationBindings;