annotations.src.js 40.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
/* *
 *
 *  (c) 2009-2017 Highsoft, Black Label
 *
 *  License: www.highcharts.com/license
 *
 * */

'use strict';

import H from '../parts/Globals.js';

import U from '../parts/Utilities.js';
var defined = U.defined,
    erase = U.erase,
    splat = U.splat;

import '../parts/Chart.js';
import controllableMixin from './controllable/controllableMixin.js';
import ControllableRect from './controllable/ControllableRect.js';
import ControllableCircle from './controllable/ControllableCircle.js';
import ControllablePath from './controllable/ControllablePath.js';
import ControllableImage from './controllable/ControllableImage.js';
import ControllableLabel from './controllable/ControllableLabel.js';
import eventEmitterMixin from './eventEmitterMixin.js';
import MockPoint from './MockPoint.js';
import ControlPoint from './ControlPoint.js';

var merge = H.merge,
    addEvent = H.addEvent,
    fireEvent = H.fireEvent,
    find = H.find,
    pick = H.pick,
    reduce = H.reduce,
    destroyObjectProperties = H.destroyObjectProperties,
    chartProto = H.Chart.prototype;

/* *********************************************************************
 *
 * ANNOTATION
 *
 ******************************************************************** */

/**
 * @typedef {
 *          Annotation.ControllableCircle|
 *          Annotation.ControllableImage|
 *          Annotation.ControllablePath|
 *          Annotation.ControllableRect
 *          }
 *          Annotation.Shape
 */

/**
 * @typedef {Annotation.ControllableLabel} Annotation.Label
 */

/**
 * An annotation class which serves as a container for items like labels or
 * shapes. Created items are positioned on the chart either by linking them to
 * existing points or created mock points
 *
 * @class
 * @name Highcharts.Annotation
 *
 * @param {Highcharts.Chart} chart a chart instance
 * @param {Highcharts.AnnotationsOptions} options the options object
 */
var Annotation = H.Annotation = function (chart, options) {
    var labelsAndShapes;

    /**
     * The chart that the annotation belongs to.
     *
     * @type {Highcharts.Chart}
     */
    this.chart = chart;

    /**
     * The array of points which defines the annotation.
     *
     * @type {Array<Highcharts.Point>}
     */
    this.points = [];

    /**
     * The array of control points.
     *
     * @type {Array<Annotation.ControlPoint>}
     */
    this.controlPoints = [];

    this.coll = 'annotations';

    /**
     * The array of labels which belong to the annotation.
     *
     * @type {Array<Annotation.Label>}
     */
    this.labels = [];

    /**
     * The array of shapes which belong to the annotation.
     *
     * @type {Array<Annotation.Shape>}
     */
    this.shapes = [];

    /**
     * The options for the annotations.
     *
     * @type {Highcharts.AnnotationsOptions}
     */
    // this.options = merge(this.defaultOptions, userOptions);
    this.options = options;

    /**
     * The user options for the annotations.
     *
     * @type {Highcharts.AnnotationsOptions}
     */
    this.userOptions = merge(true, {}, options);

    // Handle labels and shapes - those are arrays
    // Merging does not work with arrays (stores reference)
    labelsAndShapes = this.getLabelsAndShapesOptions(
        this.userOptions,
        options
    );
    this.userOptions.labels = labelsAndShapes.labels;
    this.userOptions.shapes = labelsAndShapes.shapes;

    /**
     * The callback that reports to the overlapping-labels module which
     * labels it should account for.
     *
     * @name labelCollector
     * @memberOf Annotation#
     * @type {Function}
     */

    /**
     * The group svg element.
     *
     * @name group
     * @memberOf Annotation#
     * @type {Highcharts.SVGElement}
     */

    /**
     * The group svg element of the annotation's shapes.
     *
     * @name shapesGroup
     * @memberOf Annotation#
     * @type {Highcharts.SVGElement}
     */

    /**
     * The group svg element of the annotation's labels.
     *
     * @name labelsGroup
     * @memberOf Annotation#
     * @type {Highcharts.SVGElement}
     */

    this.init(chart, options);
};


merge(
    true,
    Annotation.prototype,
    controllableMixin,
    eventEmitterMixin,
    /** @lends Annotation# */
    {

        /**
         * List of events for `annotation.options.events` that should not be
         * added to `annotation.graphic` but to the `annotation`.
         *
         * @type {Array<string>}
         */
        nonDOMEvents: ['add', 'afterUpdate', 'remove'],

        /**
         * A basic type of an annotation. It allows to add custom labels
         * or shapes. The items  can be tied to points, axis coordinates
         * or chart pixel coordinates.
         *
         * @sample highcharts/annotations/basic/
         *         Basic annotations
         * @sample highcharts/demo/annotations/
         *         Advanced annotations
         * @sample highcharts/css/annotations
         *         Styled mode
         * @sample highcharts/annotations-advanced/controllable
         *         Controllable items
         * @sample {highstock} stock/annotations/fibonacci-retracements
         *         Custom annotation, Fibonacci retracement
         *
         * @type         {Array<*>}
         * @since        6.0.0
         * @optionparent annotations
         */
        defaultOptions: {

            /**
             * Sets an ID for an annotation. Can be user later when removing an
             * annotation in [Chart#removeAnnotation(id)](
             * /class-reference/Highcharts.Chart#removeAnnotation) method.
             *
             * @type      {string|number}
             * @apioption annotations.id
             */

            /**
             * Whether the annotation is visible.
             *
             * @sample highcharts/annotations/visible/
             *         Set annotation visibility
             */
            visible: true,

            /**
             * Allow an annotation to be draggable by a user. Possible
             * values are `"x"`, `"xy"`, `"y"` and `""` (disabled).
             *
             * @sample highcharts/annotations/draggable/
             *         Annotations draggable: 'xy'
             *
             * @type       {string}
             * @validvalue ["x", "xy", "y", ""]
             */
            draggable: 'xy',

            /**
             * Options for annotation's labels. Each label inherits options
             * from the labelOptions object. An option from the labelOptions
             * can be overwritten by config for a specific label.
             */
            labelOptions: {

                /**
                 * The alignment of the annotation's label. If right,
                 * the right side of the label should be touching the point.
                 *
                 * @sample highcharts/annotations/label-position/
                 *         Set labels position
                 *
                 * @type {Highcharts.AlignValue}
                 */
                align: 'center',

                /**
                 * Whether to allow the annotation's labels to overlap.
                 * To make the labels less sensitive for overlapping,
                 * the can be set to 0.
                 *
                 * @sample highcharts/annotations/tooltip-like/
                 *         Hide overlapping labels
                 */
                allowOverlap: false,

                /**
                 * The background color or gradient for the annotation's label.
                 *
                 * @sample highcharts/annotations/label-presentation/
                 *         Set labels graphic options
                 *
                 * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
                 */
                backgroundColor: 'rgba(0, 0, 0, 0.75)',

                /**
                 * The border color for the annotation's label.
                 *
                 * @sample highcharts/annotations/label-presentation/
                 *         Set labels graphic options
                 *
                 * @type {Highcharts.ColorString}
                 */
                borderColor: 'black',

                /**
                 * The border radius in pixels for the annotaiton's label.
                 *
                 * @sample highcharts/annotations/label-presentation/
                 *         Set labels graphic options
                 */
                borderRadius: 3,

                /**
                 * The border width in pixels for the annotation's label
                 *
                 * @sample highcharts/annotations/label-presentation/
                 *         Set labels graphic options
                 */
                borderWidth: 1,

                /**
                 * A class name for styling by CSS.
                 *
                 * @sample highcharts/css/annotations
                 *         Styled mode annotations
                 *
                 * @since 6.0.5
                 */
                className: '',

                /**
                 * Whether to hide the annotation's label
                 * that is outside the plot area.
                 *
                 * @sample highcharts/annotations/label-crop-overflow/
                 *         Crop or justify labels
                 */
                crop: false,

                /**
                 * The label's pixel distance from the point.
                 *
                 * @sample highcharts/annotations/label-position/
                 *         Set labels position
                 *
                 * @type      {number}
                 * @apioption annotations.labelOptions.distance
                 */

                /**
                 * A
                 * [format](https://www.highcharts.com/docs/chart-concepts/labels-and-string-formatting)
                 * string for the data label.
                 *
                 * @see [plotOptions.series.dataLabels.format](plotOptions.series.dataLabels.format.html)
                 *
                 * @sample highcharts/annotations/label-text/
                 *         Set labels text
                 *
                 * @type      {string}
                 * @apioption annotations.labelOptions.format
                 */

                /**
                 * Alias for the format option.
                 *
                 * @see [format](annotations.labelOptions.format.html)
                 *
                 * @sample highcharts/annotations/label-text/
                 *         Set labels text
                 *
                 * @type      {string}
                 * @apioption annotations.labelOptions.text
                 */

                /**
                 * Callback JavaScript function to format the annotation's
                 * label. Note that if a `format` or `text` are defined, the
                 * format or text take precedence and the formatter is ignored.
                 * `This` refers to a point object.
                 *
                 * @sample highcharts/annotations/label-text/
                 *         Set labels text
                 *
                 * @type    {Highcharts.FormatterCallbackFunction<Highcharts.Point>}
                 * @default function () { return defined(this.y) ? this.y : 'Annotation label'; }
                 */
                formatter: function () {
                    return defined(this.y) ? this.y : 'Annotation label';
                },

                /**
                 * How to handle the annotation's label that flow outside the
                 * plot area. The justify option aligns the label inside the
                 * plot area.
                 *
                 * @sample highcharts/annotations/label-crop-overflow/
                 *         Crop or justify labels
                 *
                 * @validvalue ["allow", "justify"]
                 */
                overflow: 'justify',

                /**
                 * When either the borderWidth or the backgroundColor is set,
                 * this    is the padding within the box.
                 *
                 * @sample highcharts/annotations/label-presentation/
                 *         Set labels graphic options
                 */
                padding: 5,

                /**
                 * The shadow of the box. The shadow can be an object
                 * configuration containing `color`, `offsetX`, `offsetY`,
                 * `opacity` and `width`.
                 *
                 * @sample highcharts/annotations/label-presentation/
                 *         Set labels graphic options
                 *
                 * @type {boolean|Highcharts.ShadowOptionsObject}
                 */
                shadow: false,

                /**
                 * The name of a symbol to use for the border around the label.
                 * Symbols are predefined functions on the Renderer object.
                 *
                 * @sample highcharts/annotations/shapes/
                 *         Available shapes for labels
                 */
                shape: 'callout',

                /**
                 * Styles for the annotation's label.
                 *
                 * @see [plotOptions.series.dataLabels.style](plotOptions.series.dataLabels.style.html)
                 *
                 * @sample highcharts/annotations/label-presentation/
                 *         Set labels graphic options
                 *
                 * @type {Highcharts.CSSObject}
                 */
                style: {
                    /** @ignore */
                    fontSize: '11px',
                    /** @ignore */
                    fontWeight: 'normal',
                    /** @ignore */
                    color: 'contrast'
                },

                /**
                 * Whether to [use HTML](https://www.highcharts.com/docs/chart-concepts/labels-and-string-formatting#html)
                 * to render the annotation's label.
                 */
                useHTML: false,

                /**
                 * The vertical alignment of the annotation's label.
                 *
                 * @sample highcharts/annotations/label-position/
                 *         Set labels position
                 *
                 * @type {Highcharts.VerticalAlignValue}
                 */
                verticalAlign: 'bottom',

                /**
                 * The x position offset of the label relative to the point.
                 * Note that if a `distance` is defined, the distance takes
                 * precedence over `x` and `y` options.
                 *
                 * @sample highcharts/annotations/label-position/
                 *         Set labels position
                 */
                x: 0,

                /**
                 * The y position offset of the label relative to the point.
                 * Note that if a `distance` is defined, the distance takes
                 * precedence over `x` and `y` options.
                 *
                 * @sample highcharts/annotations/label-position/
                 *         Set labels position
                 */
                y: -16
            },

            /**
             * An array of labels for the annotation. For options that apply to
             * multiple labels, they can be added to the
             * [labelOptions](annotations.labelOptions.html).
             *
             * @type      {Array<*>}
             * @extends   annotations.labelOptions
             * @apioption annotations.labels
             */

            /**
             * This option defines the point to which the label will be
             * connected. It can be either the point which exists in the
             * series - it is referenced by the point's id - or a new point with
             * defined x, y properties and optionally axes.
             *
             * @sample highcharts/annotations/mock-point/
             *         Attach annotation to a mock point
             *
             * @type      {string|Highcharts.MockPointOptionsObject}
             * @apioption annotations.labels.point
             */

            /**
             * The x position of the point. Units can be either in axis
             * or chart pixel coordinates.
             *
             * @type      {number}
             * @apioption annotations.labels.point.x
             */

            /**
             * The y position of the point. Units can be either in axis
             * or chart pixel coordinates.
             *
             * @type      {number}
             * @apioption annotations.labels.point.y
             */

            /**
             * This number defines which xAxis the point is connected to. It
             * refers to either the axis id or the index of the axis in the
             * xAxis array. If the option is not configured or the axis is not
             * found the point's x coordinate refers to the chart pixels.
             *
             * @type      {number|string}
             * @apioption annotations.labels.point.xAxis
             */

            /**
             * This number defines which yAxis the point is connected to. It
             * refers to either the axis id or the index of the axis in the
             * yAxis array. If the option is not configured or the axis is not
             * found the point's y coordinate refers to the chart pixels.
             *
             * @type      {number|string}
             * @apioption annotations.labels.point.yAxis
             */


            /**
             * An array of shapes for the annotation. For options that apply to
             * multiple shapes, then can be added to the
             * [shapeOptions](annotations.shapeOptions.html).
             *
             * @type      {Array<*>}
             * @extends   annotations.shapeOptions
             * @apioption annotations.shapes
             */

            /**
             * This option defines the point to which the shape will be
             * connected. It can be either the point which exists in the
             * series - it is referenced by the point's id - or a new point with
             * defined x, y properties and optionally axes.
             *
             * @type      {string|Highcharts.MockPointOptionsObject}
             * @extends   annotations.labels.point
             * @apioption annotations.shapes.point
             */

            /**
             * An array of points for the shape. This option is available for
             * shapes which can use multiple points such as path. A point can be
             * either a point object or a point's id.
             *
             * @see [annotations.shapes.point](annotations.shapes.point.html)
             *
             * @type      {Array<string|Highcharts.MockPointOptionsObject>}
             * @extends   annotations.labels.point
             * @apioption annotations.shapes.points
             */

            /**
             * Id of the marker which will be drawn at the final vertex of the
             * path. Custom markers can be defined in defs property.
             *
             * @see [defs.markers](defs.markers.html)
             *
             * @sample highcharts/annotations/custom-markers/
             *         Define a custom marker for annotations
             *
             * @type      {string}
             * @apioption annotations.shapes.markerEnd
             */

            /**
             * Id of the marker which will be drawn at the first vertex of the
             * path. Custom markers can be defined in defs property.
             *
             * @see [defs.markers](defs.markers.html)
             *
             * @sample {highcharts} highcharts/annotations/custom-markers/
             *         Define a custom marker for annotations
             *
             * @type      {string}
             * @apioption annotations.shapes.markerStart
             */


            /**
             * Options for annotation's shapes. Each shape inherits options from
             * the shapeOptions object. An option from the shapeOptions can be
             * overwritten by config for a specific shape.
             */
            shapeOptions: {

                /**
                 * The width of the shape.
                 *
                 * @sample highcharts/annotations/shape/
                 *         Basic shape annotation
                 *
                 * @type      {number}
                 * @apioption annotations.shapeOptions.width
                 **/

                /**
                 * The height of the shape.
                 *
                 * @sample highcharts/annotations/shape/
                 *         Basic shape annotation
                 *
                 * @type      {number}
                 * @apioption annotations.shapeOptions.height
                 */

                /**
                 * The type of the shape, e.g. circle or rectangle.
                 *
                 * @sample highcharts/annotations/shape/
                 *         Basic shape annotation
                 *
                 * @type      {string}
                 * @default   'rect'
                 * @apioption annotations.shapeOptions.type
                 */

                /**
                 * The color of the shape's stroke.
                 *
                 * @sample highcharts/annotations/shape/
                 *         Basic shape annotation
                 *
                 * @type {Highcharts.ColorString}
                 */
                stroke: 'rgba(0, 0, 0, 0.75)',

                /**
                 * The pixel stroke width of the shape.
                 *
                 * @sample highcharts/annotations/shape/
                 *         Basic shape annotation
                 */
                strokeWidth: 1,

                /**
                 * The color of the shape's fill.
                 *
                 * @sample highcharts/annotations/shape/
                 *         Basic shape annotation
                 *
                 * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
                 */
                fill: 'rgba(0, 0, 0, 0.75)',

                /**
                 * The radius of the shape.
                 *
                 * @sample highcharts/annotations/shape/
                 *         Basic shape annotation
                 */
                r: 0,

                /**
                 * Defines additional snapping area around an annotation
                 * making this annotation to focus. Defined in pixels.
                 */
                snap: 2
            },

            /**
             * Options for annotation's control points. Each control point
             * inherits options from controlPointOptions object.
             * Options from the controlPointOptions can be overwritten
             * by options in a specific control point.
             *
             * @type      {Annotation.ControlPoint.Options}
             * @apioption annotations.controlPointOptions
             */
            controlPointOptions: {

                /**
                 * @function {Annotation.ControlPoint.Positioner}
                 * @apioption annotations.controlPointOptions.positioner
                 */

                symbol: 'circle',
                width: 10,
                height: 10,
                style: {
                    stroke: 'black',
                    'stroke-width': 2,
                    fill: 'white'
                },
                visible: false,
                events: {}
            },

            /**
             * Event callback when annotation is added to the chart.
             *
             * @type      {Highcharts.EventCallbackFunction<Highcharts.Annotation>}
             * @since     7.1.0
             * @apioption annotations.events.add
             */

            /**
             * Event callback when annotation is updated (e.g. drag and
             * droppped or resized by control points).
             *
             * @type      {Highcharts.EventCallbackFunction<Highcharts.Annotation>}
             * @since     7.1.0
             * @apioption annotations.events.afterUpdate
             */

            /**
             * Event callback when annotation is removed from the chart.
             *
             * @type      {Highcharts.EventCallbackFunction<Highcharts.Annotation>}
             * @since     7.1.0
             * @apioption annotations.events.remove
             */

            /**
             * Events available in annotations.
             */
            events: {},

            /**
             * The Z index of the annotation.
             */
            zIndex: 6

        },

        /**
         * Initialize the annotation.
         *
         * @param {Highcharts.Chart}
         *        The chart
         * @param {Highcharts.AnnotationsOptions}
         *        The user options for the annotation
         */
        init: function () {
            this.linkPoints();
            this.addControlPoints();
            this.addShapes();
            this.addLabels();
            this.addClipPaths();
            this.setLabelCollector();
        },

        getLabelsAndShapesOptions: function (baseOptions, newOptions) {
            var mergedOptions = {};

            ['labels', 'shapes'].forEach(function (name) {
                if (baseOptions[name]) {
                    mergedOptions[name] = splat(newOptions[name]).map(
                        function (basicOptions, i) {
                            return merge(baseOptions[name][i], basicOptions);
                        }
                    );
                }
            });

            return mergedOptions;
        },

        addShapes: function () {
            (this.options.shapes || []).forEach(
                this.initShape,
                this
            );
        },

        addLabels: function () {
            (this.options.labels || []).forEach(
                this.initLabel,
                this
            );
        },

        addClipPaths: function () {
            this.setClipAxes();

            if (this.clipXAxis && this.clipYAxis) {
                this.clipRect = this.chart.renderer.clipRect(
                    this.getClipBox()
                );
            }
        },

        setClipAxes: function () {
            var xAxes = this.chart.xAxis,
                yAxes = this.chart.yAxis,
                linkedAxes = reduce(
                    (this.options.labels || [])
                        .concat(this.options.shapes || []),
                    function (axes, labelOrShape) {
                        return [
                            xAxes[
                                labelOrShape &&
                                labelOrShape.point &&
                                labelOrShape.point.xAxis
                            ] || axes[0],
                            yAxes[
                                labelOrShape &&
                                labelOrShape.point &&
                                labelOrShape.point.yAxis
                            ] || axes[1]
                        ];
                    },
                    []
                );

            this.clipXAxis = linkedAxes[0];
            this.clipYAxis = linkedAxes[1];
        },

        getClipBox: function () {
            return {
                x: this.clipXAxis.left,
                y: this.clipYAxis.top,
                width: this.clipXAxis.width,
                height: this.clipYAxis.height
            };
        },

        setLabelCollector: function () {
            var annotation = this;

            annotation.labelCollector = function () {
                return annotation.labels.reduce(
                    function (labels, label) {
                        if (!label.options.allowOverlap) {
                            labels.push(label.graphic);
                        }

                        return labels;
                    },
                    []
                );
            };

            annotation.chart.labelCollectors.push(
                annotation.labelCollector
            );
        },

        /**
         * Set an annotation options.
         *
         * @param {Highcharts.AnnotationsOptions} - user options for an annotation
         */
        setOptions: function (userOptions) {
            this.options = merge(this.defaultOptions, userOptions);
        },

        redraw: function (animation) {
            this.linkPoints();

            if (!this.graphic) {
                this.render();
            }

            if (this.clipRect) {
                this.clipRect.animate(this.getClipBox());
            }

            this.redrawItems(this.shapes, animation);
            this.redrawItems(this.labels, animation);


            controllableMixin.redraw.call(this, animation);
        },

        /**
         * @param {Array<(Annotation.Label|Annotation.Shape)>} items
         * @param {boolean} [animation]
         */
        redrawItems: function (items, animation) {
            var i = items.length;

            // needs a backward loop
            // labels/shapes array might be modified
            // due to destruction of the item
            while (i--) {
                this.redrawItem(items[i], animation);
            }
        },

        render: function () {
            var renderer = this.chart.renderer;

            this.graphic = renderer
                .g('annotation')
                .attr({
                    zIndex: this.options.zIndex,
                    visibility: this.options.visible ?
                        'visible' :
                        'hidden'
                })
                .add();

            this.shapesGroup = renderer
                .g('annotation-shapes')
                .add(this.graphic)
                .clip(this.chart.plotBoxClip);

            this.labelsGroup = renderer
                .g('annotation-labels')
                .attr({
                    // hideOverlappingLabels requires translation
                    translateX: 0,
                    translateY: 0
                })
                .add(this.graphic);

            if (this.clipRect) {
                this.graphic.clip(this.clipRect);
            }

            this.addEvents();

            controllableMixin.render.call(this);
        },

        /**
         * Set the annotation's visibility.
         *
         * @param {Boolean} [visible] - Whether to show or hide an annotation.
         * If the param is omitted, the annotation's visibility is toggled.
         */
        setVisibility: function (visibility) {
            var options = this.options,
                visible = pick(visibility, !options.visible);

            this.graphic.attr(
                'visibility',
                visible ? 'visible' : 'hidden'
            );

            if (!visible) {
                this.setControlPointsVisibility(false);
            }

            options.visible = visible;
        },

        setControlPointsVisibility: function (visible) {
            var setItemControlPointsVisibility = function (item) {
                item.setControlPointsVisibility(visible);
            };

            controllableMixin.setControlPointsVisibility.call(
                this,
                visible
            );

            this.shapes.forEach(setItemControlPointsVisibility);
            this.labels.forEach(setItemControlPointsVisibility);
        },

        /**
         * Destroy the annotation. This function does not touch the chart
         * that the annotation belongs to (all annotations are kept in
         * the chart.annotations array) - it is recommended to use
         * {@link Highcharts.Chart#removeAnnotation} instead.
         */
        destroy: function () {
            var chart = this.chart,
                destroyItem = function (item) {
                    item.destroy();
                };

            this.labels.forEach(destroyItem);
            this.shapes.forEach(destroyItem);

            this.clipXAxis = null;
            this.clipYAxis = null;

            erase(chart.labelCollectors, this.labelCollector);

            eventEmitterMixin.destroy.call(this);
            controllableMixin.destroy.call(this);

            destroyObjectProperties(this, chart);
        },

        /**
         * See {@link Highcharts.Chart#removeAnnotation}.
         */
        remove: function () {
            // Let chart.update() remove annoations on demand
            return this.chart.removeAnnotation(this);
        },

        update: function (userOptions) {
            var chart = this.chart,
                labelsAndShapes = this.getLabelsAndShapesOptions(
                    this.userOptions,
                    userOptions
                ),
                userOptionsIndex = chart.annotations.indexOf(this),
                options = H.merge(true, this.userOptions, userOptions);

            options.labels = labelsAndShapes.labels;
            options.shapes = labelsAndShapes.shapes;

            this.destroy();
            this.constructor(chart, options);

            // Update options in chart options, used in exporting (#9767):
            chart.options.annotations[userOptionsIndex] = options;

            this.isUpdating = true;
            this.redraw();
            this.isUpdating = false;
            fireEvent(this, 'afterUpdate');
        },

        /* *************************************************************
         * ITEM SECTION
         * Contains methods for handling a single item in an annotation
         **************************************************************** */

        /**
         * Initialisation of a single shape
         *
         * @param {Object} shapeOptions - a confg object for a single shape
         */
        initShape: function (shapeOptions, index) {
            var options = merge(
                    this.options.shapeOptions,
                    {
                        controlPointOptions: this.options.controlPointOptions
                    },
                    shapeOptions
                ),
                shape = new Annotation.shapesMap[options.type](
                    this,
                    options,
                    index
                );

            shape.itemType = 'shape';

            this.shapes.push(shape);

            return shape;
        },

        /**
         * Initialisation of a single label
         *
         * @param {Object} labelOptions
         **/
        initLabel: function (labelOptions, index) {
            var options = merge(
                    this.options.labelOptions,
                    {
                        controlPointOptions: this.options.controlPointOptions
                    },
                    labelOptions
                ),
                label = new ControllableLabel(
                    this,
                    options,
                    index
                );

            label.itemType = 'label';

            this.labels.push(label);

            return label;
        },

        /**
         * Redraw a single item.
         *
         * @param {Annotation.Label|Annotation.Shape} item
         * @param {boolean} [animation]
         */
        redrawItem: function (item, animation) {
            item.linkPoints();

            if (!item.shouldBeDrawn()) {
                this.destroyItem(item);
            } else {
                if (!item.graphic) {
                    this.renderItem(item);
                }

                item.redraw(
                    H.pick(animation, true) && item.graphic.placed
                );

                if (item.points.length) {
                    this.adjustVisibility(item);
                }
            }
        },

        /**
         * Hide or show annotaiton attached to points.
         *
         * @param {Annotation.Label|Annotation.Shape} item
         */

        adjustVisibility: function (item) { // #9481
            var hasVisiblePoints = false,
                label = item.graphic;

            item.points.forEach(function (point) {
                if (
                    point.series.visible !== false &&
                    point.visible !== false
                ) {
                    hasVisiblePoints = true;
                }
            });

            if (!hasVisiblePoints) {
                label.hide();

            } else if (label.visibility === 'hidden') {
                label.show();
            }
        },

        /**
         * Destroy a single item.
         *
         * @param {Annotation.Label|Annotation.Shape} item
         */
        destroyItem: function (item) {
            // erase from shapes or labels array
            erase(this[item.itemType + 's'], item);
            item.destroy();
        },

        /**
         * @private
         */
        renderItem: function (item) {
            item.render(
                item.itemType === 'label' ?
                    this.labelsGroup :
                    this.shapesGroup
            );
        }
    }
);

/**
 * An object uses for mapping between a shape type and a constructor.
 * To add a new shape type extend this object with type name as a key
 * and a constructor as its value.
 */
Annotation.shapesMap = {
    'rect': ControllableRect,
    'circle': ControllableCircle,
    'path': ControllablePath,
    'image': ControllableImage
};

Annotation.types = {};

Annotation.MockPoint = MockPoint;
Annotation.ControlPoint = ControlPoint;

H.extendAnnotation = function (
    Constructor,
    BaseConstructor,
    prototype,
    defaultOptions
) {
    BaseConstructor = BaseConstructor || Annotation;

    merge(
        true,
        Constructor.prototype,
        BaseConstructor.prototype,
        prototype
    );

    Constructor.prototype.defaultOptions = merge(
        Constructor.prototype.defaultOptions,
        defaultOptions || {}
    );
};

/* *********************************************************************
 *
 * EXTENDING CHART PROTOTYPE
 *
 ******************************************************************** */

H.extend(chartProto, /** @lends Highcharts.Chart# */ {
    initAnnotation: function (userOptions) {
        var Constructor =
            Annotation.types[userOptions.type] || Annotation,
            options = H.merge(
                Constructor.prototype.defaultOptions,
                userOptions
            ),
            annotation = new Constructor(this, options);

        this.annotations.push(annotation);

        return annotation;
    },

    /**
     * Add an annotation to the chart after render time.
     *
     * @param  {Highcharts.AnnotationsOptions} options
     *         The annotation options for the new, detailed annotation.
     * @param {boolean} [redraw]
     *
     * @return {Highcharts.Annotation} - The newly generated annotation.
     */
    addAnnotation: function (userOptions, redraw) {
        var annotation = this.initAnnotation(userOptions);

        this.options.annotations.push(annotation.options);

        if (pick(redraw, true)) {
            annotation.redraw();
        }

        return annotation;
    },

    /**
     * Remove an annotation from the chart.
     *
     * @param {String|Number|Annotation} idOrAnnotation - The annotation's id or
     *      direct annotation object.
     */
    removeAnnotation: function (idOrAnnotation) {
        var annotations = this.annotations,
            annotation = idOrAnnotation.coll === 'annotations' ?
                idOrAnnotation :
                find(
                    annotations,
                    function (annotation) {
                        return annotation.options.id === idOrAnnotation;
                    }
                );

        if (annotation) {
            fireEvent(annotation, 'remove');
            erase(this.options.annotations, annotation.options);
            erase(annotations, annotation);
            annotation.destroy();
        }
    },

    drawAnnotations: function () {
        this.plotBoxClip.attr(this.plotBox);

        this.annotations.forEach(function (annotation) {
            annotation.redraw();
        });
    }
});

// Let chart.update() update annotations
chartProto.collectionsWithUpdate.push('annotations');

// Let chart.update() create annoations on demand
chartProto.collectionsWithInit.annotations = [chartProto.addAnnotation];

chartProto.callbacks.push(function (chart) {
    chart.annotations = [];

    if (!chart.options.annotations) {
        chart.options.annotations = [];
    }

    chart.plotBoxClip = this.renderer.clipRect(this.plotBox);

    chart.controlPointsGroup = chart.renderer
        .g('control-points')
        .attr({ zIndex: 99 })
        .clip(chart.plotBoxClip)
        .add();

    chart.options.annotations.forEach(function (annotationOptions, i) {
        var annotation = chart.initAnnotation(annotationOptions);

        chart.options.annotations[i] = annotation.options;
    });

    chart.drawAnnotations();
    addEvent(chart, 'redraw', chart.drawAnnotations);
    addEvent(chart, 'destroy', function () {
        chart.plotBoxClip.destroy();
        chart.controlPointsGroup.destroy();
    });
});