NavigationBindings.js 40 KB

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