FlagsSeries.js 16.6 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
/**
 * (c) 2010-2018 Torstein Honsi
 *
 * License: www.highcharts.com/license
 */
'use strict';
import H from './Globals.js';
import './Utilities.js';
import './Series.js';
import './SvgRenderer.js';
import onSeriesMixin from '../mixins/on-series.js';
var addEvent = H.addEvent,
    each = H.each,
    merge = H.merge,
    noop = H.noop,
    Renderer = H.Renderer,
    Series = H.Series,
    seriesType = H.seriesType,
    SVGRenderer = H.SVGRenderer,
    TrackerMixin = H.TrackerMixin,
    VMLRenderer = H.VMLRenderer,
    symbols = SVGRenderer.prototype.symbols;

/**
 * The Flags series.
 *
 * @constructor seriesTypes.flags
 * @augments seriesTypes.column
 */
/**
 * Flags are used to mark events in stock charts. They can be added on the
 * timeline, or attached to a specific series.
 *
 * @sample       stock/demo/flags-general/ Flags on a line series
 * @extends      {plotOptions.column}
 * @excluding    animation,borderColor,borderRadius,borderWidth,colorByPoint,
 *               dataGrouping,pointPadding,pointWidth,turboThreshold
 * @product      highstock
 * @optionparent plotOptions.flags
 */
seriesType('flags', 'column', {

    /**
     * In case the flag is placed on a series, on what point key to place
     * it. Line and columns have one key, `y`. In range or OHLC-type series,
     * however, the flag can optionally be placed on the `open`, `high`,
     *  `low` or `close` key.
     *
     * @validvalue ["y", "open", "high", "low", "close"]
     * @type       {String}
     * @sample     {highstock} stock/plotoptions/flags-onkey/
     *             Range series, flag on high
     * @default    y
     * @since      4.2.2
     * @product    highstock
     * @apioption  plotOptions.flags.onKey
     */

    /**
     * The id of the series that the flags should be drawn on. If no id
     * is given, the flags are drawn on the x axis.
     *
     * @type      {String}
     * @sample    {highstock} stock/plotoptions/flags/
     *            Flags on series and on x axis
     * @default   undefined
     * @product   highstock
     * @apioption plotOptions.flags.onSeries
     */

    pointRange: 0, // #673

    /**
     * Whether the flags are allowed to overlap sideways. If `false`, the flags
     * are moved sideways using an algorithm that seeks to place every flag as
     * close as possible to its original position.
     *
     * @sample {highstock} stock/plotoptions/flags-allowoverlapx
     *         Allow sideways overlap
     * @since  6.0.4
     */
    allowOverlapX: false,

    /**
     * The shape of the marker. Can be one of "flag", "circlepin", "squarepin",
     * or an image of the format `url(/path-to-image.jpg)`. Individual
     * shapes can also be set for each point.
     *
     * @validvalue ["flag", "circlepin", "squarepin"]
     * @sample     {highstock} stock/plotoptions/flags/ Different shapes
     * @product    highstock
     */
    shape: 'flag',

    /**
     * When multiple flags in the same series fall on the same value, this
     * number determines the vertical offset between them.
     *
     * @sample  {highstock} stock/plotoptions/flags-stackdistance/
     *          A greater stack distance
     * @product highstock
     */
    stackDistance: 12,

    /**
     * Text alignment for the text inside the flag.
     *
     * @validvalue ["left", "center", "right"]
     * @since      5.0.0
     * @product    highstock
     */
    textAlign: 'center',

    /**
     * Specific tooltip options for flag series. Flag series tooltips are
     * different from most other types in that a flag doesn't have a data
     * value, so the tooltip rather displays the `text` option for each
     * point.
     *
     * @type      {Object}
     * @extends   plotOptions.series.tooltip
     * @excluding changeDecimals,valueDecimals,valuePrefix,valueSuffix
     * @product   highstock
     */
    tooltip: {
        pointFormat: '{point.text}<br/>'
    },

    threshold: null,

    /**
     * The text to display on each flag. This can be defined on series level,
     *  or individually for each point. Defaults to `"A"`.
     *
     * @type      {String}
     * @default   A
     * @product   highstock
     * @apioption plotOptions.flags.title
     */

    /**
     * The y position of the top left corner of the flag relative to either
     * the series (if onSeries is defined), or the x axis. Defaults to
     * `-30`.
     *
     * @product highstock
     */
    y: -30,

    /**
     * Whether to use HTML to render the flag texts. Using HTML allows for
     * advanced formatting, images and reliable bi-directional text rendering.
     * Note that exported images won't respect the HTML, and that HTML
     * won't respect Z-index settings.
     *
     * @type      {Boolean}
     * @default   false
     * @since     1.3
     * @product   highstock
     * @apioption plotOptions.flags.useHTML
     */

    /**
     * Fixed width of the flag's shape. By default, width is autocalculated
     * according to the flag's title.
     *
     * @type      {Number}
     * @default   undefined
     * @product   highstock
     * @sample    {highstock} stock/demo/flags-shapes/ Flags with fixed width
     * @apioption plotOptions.flags.width
     */

     /**
     * Fixed height of the flag's shape. By default, height is autocalculated
     * according to the flag's title.
     *
     * @type      {Number}
     * @default   undefined
     * @product   highstock
     * @apioption plotOptions.flags.height
     */

    

}, /** @lends seriesTypes.flags.prototype */ {
    sorted: false,
    noSharedTooltip: true,
    allowDG: false,
    takeOrdinalPosition: false, // #1074
    trackerGroups: ['markerGroup'],
    forceCrop: true,
    /**
     * Inherit the initialization from base Series.
     */
    init: Series.prototype.init,

    

    translate: onSeriesMixin.translate,
    getPlotBox: onSeriesMixin.getPlotBox,

    /**
     * Draw the markers
     */
    drawPoints: function () {
        var series = this,
            points = series.points,
            chart = series.chart,
            renderer = chart.renderer,
            plotX,
            plotY,
            inverted = chart.inverted,
            options = series.options,
            optionsY = options.y,
            shape,
            i,
            point,
            graphic,
            stackIndex,
            anchorY,
            attribs,
            outsideRight,
            yAxis = series.yAxis,
            boxesMap = {},
            boxes = [];

        i = points.length;
        while (i--) {
            point = points[i];
            outsideRight =
                (inverted ? point.plotY : point.plotX) > series.xAxis.len;
            plotX = point.plotX;
            stackIndex = point.stackIndex;
            shape = point.options.shape || options.shape;
            plotY = point.plotY;

            if (plotY !== undefined) {
                plotY = point.plotY + optionsY -
                    (
                        stackIndex !== undefined &&
                        stackIndex * options.stackDistance
                    );
            }
            // skip connectors for higher level stacked points
            point.anchorX = stackIndex ? undefined : point.plotX;
            anchorY = stackIndex ? undefined : point.plotY;

            graphic = point.graphic;

            // Only draw the point if y is defined and the flag is within
            // the visible area
            if (plotY !== undefined && plotX >= 0 && !outsideRight) {

                // Create the flag
                if (!graphic) {
                    graphic = point.graphic = renderer.label(
                        '',
                        null,
                        null,
                        shape,
                        null,
                        null,
                        options.useHTML
                    )
                    
                    .attr({
                        align: shape === 'flag' ? 'left' : 'center',
                        width: options.width,
                        height: options.height,
                        'text-align': options.textAlign
                    })
                    .addClass('highcharts-point')
                    .add(series.markerGroup);

                    // Add reference to the point for tracker (#6303)
                    if (point.graphic.div) {
                        point.graphic.div.point = point;
                    }

                    
                    graphic.isNew = true;
                }

                if (plotX > 0) { // #3119
                    plotX -= graphic.strokeWidth() % 2; // #4285
                }

                // Plant the flag
                attribs = {
                    y: plotY,
                    anchorY: anchorY
                };
                if (options.allowOverlapX) {
                    attribs.x = plotX;
                    attribs.anchorX = point.anchorX;
                }
                graphic.attr({
                    text: point.options.title || options.title || 'A'
                })[graphic.isNew ? 'attr' : 'animate'](attribs);

                // Rig for the distribute function
                if (!options.allowOverlapX) {
                    if (!boxesMap[point.plotX]) {
                        boxesMap[point.plotX] = {
                            align: 0,
                            size: graphic.width,
                            target: plotX,
                            anchorX: plotX
                        };
                    } else {
                        boxesMap[point.plotX].size = Math.max(
                            boxesMap[point.plotX].size,
                            graphic.width
                        );
                    }
                }

                // Set the tooltip anchor position
                point.tooltipPos = [
                    plotX,
                    plotY + yAxis.pos - chart.plotTop
                ]; // #6327

            } else if (graphic) {
                point.graphic = graphic.destroy();
            }

        }

        // Handle X-dimension overlapping
        if (!options.allowOverlapX) {
            H.objectEach(boxesMap, function (box) {
                box.plotX = box.anchorX;
                boxes.push(box);
            });

            H.distribute(boxes, inverted ? yAxis.len : this.xAxis.len, 100);

            each(points, function (point) {
                var box = point.graphic && boxesMap[point.plotX];
                if (box) {
                    point.graphic[point.graphic.isNew ? 'attr' : 'animate']({
                        x: box.pos,
                        anchorX: point.anchorX
                    });
                    // Hide flag when its box position is not specified (#8573)
                    if (!box.pos) {
                        point.graphic.attr({
                            x: -9999,
                            anchorX: -9999
                        });
                        point.graphic.isNew = true;
                    } else {
                        point.graphic.isNew = false;
                    }
                }
            });
        }

        // Might be a mix of SVG and HTML and we need events for both (#6303)
        if (options.useHTML) {
            H.wrap(series.markerGroup, 'on', function (proceed) {
                return H.SVGElement.prototype.on.apply(
                    // for HTML
                    proceed.apply(this, [].slice.call(arguments, 1)),
                    // and for SVG
                    [].slice.call(arguments, 1));
            });
        }

    },

    /**
     * Extend the column trackers with listeners to expand and contract stacks
     */
    drawTracker: function () {
        var series = this,
            points = series.points;

        TrackerMixin.drawTrackerPoint.apply(this);

        /**
         * Bring each stacked flag up on mouse over, this allows readability
         * of vertically stacked elements as well as tight points on
         * the x axis. #1924.
         */
        each(points, function (point) {
            var graphic = point.graphic;
            if (graphic) {
                addEvent(graphic.element, 'mouseover', function () {

                    // Raise this point
                    if (point.stackIndex > 0 && !point.raised) {
                        point._y = graphic.y;
                        graphic.attr({
                            y: point._y - 8
                        });
                        point.raised = true;
                    }

                    // Revert other raised points
                    each(points, function (otherPoint) {
                        if (
                            otherPoint !== point &&
                            otherPoint.raised &&
                            otherPoint.graphic
                        ) {
                            otherPoint.graphic.attr({
                                y: otherPoint._y
                            });
                            otherPoint.raised = false;
                        }
                    });
                });
            }
        });
    },

    // Disable animation, but keep clipping (#8546):
    animate: function (init) {
        if (init) {
            this.setClip();
        } else {
            this.animate = null;
        }
    },
    setClip: function () {
        Series.prototype.setClip.apply(this, arguments);
        if (this.options.clip !== false && this.sharedClipKey) {
            this.markerGroup.clip(this.chart[this.sharedClipKey]);
        }
    },
    buildKDTree: noop,
    /**
     * Don't invert the flag marker group (#4960)
     */
    invertGroups: noop

});

// create the flag icon with anchor
symbols.flag = function (x, y, w, h, options) {
    var anchorX = (options && options.anchorX) || x,
        anchorY = (options && options.anchorY) || y;

    return symbols.circle(anchorX - 1, anchorY - 1, 2, 2).concat(
        [
            'M', anchorX, anchorY,
            'L', x, y + h,
            x, y,
            x + w, y,
            x + w, y + h,
            x, y + h,
            'Z'
        ]
    );
};

/*
 * Create the circlepin and squarepin icons with anchor
 */
function createPinSymbol(shape) {
    symbols[shape + 'pin'] = function (x, y, w, h, options) {

        var anchorX = options && options.anchorX,
            anchorY = options && options.anchorY,
            path,
            labelTopOrBottomY;

        // For single-letter flags, make sure circular flags are not taller
        // than their width
        if (shape === 'circle' && h > w) {
            x -= Math.round((h - w) / 2);
            w = h;
        }

        path = symbols[shape](x, y, w, h);

        if (anchorX && anchorY) {
            /**
             * If the label is below the anchor, draw the connecting line
             * from the top edge of the label
             * otherwise start drawing from the bottom edge
             */
            labelTopOrBottomY = (y > anchorY) ? y : y + h;
            path.push(
                'M',
                shape === 'circle' ? path[1] - path[4] : path[1] + path[4] / 2,
                labelTopOrBottomY,
                'L',
                anchorX,
                anchorY
            );
            path = path.concat(
                symbols.circle(anchorX - 1, anchorY - 1, 2, 2)
            );
        }

        return path;
    };
}
createPinSymbol('circle');
createPinSymbol('square');



/**
 * A `flags` series. If the [type](#series.flags.type) option is not
 * specified, it is inherited from [chart.type](#chart.type).
 *
 * @type      {Object}
 * @extends   series,plotOptions.flags
 * @excluding dataParser,dataURL
 * @product   highstock
 * @apioption series.flags
 */

/**
 * An array of data points for the series. For the `flags` series type,
 * points can be given in the following ways:
 *
 * 1.  An array of objects with named values. The following snippet shows only a
 * few settings, see the complete options set below. If the total number of data
 * points exceeds the series' [turboThreshold](#series.flags.turboThreshold),
 * this option is not available.
 *
 *  ```js
 *     data: [{
 *     x: 1,
 *     title: "A",
 *     text: "First event"
 * }, {
 *     x: 1,
 *     title: "B",
 *     text: "Second event"
 * }]</pre>
 *
 * @type {Array<Object>}
 * @extends series.line.data
 * @excluding y,dataLabels,marker,name
 * @product highstock
 * @apioption series.flags.data
 */

/**
 * The fill color of an individual flag. By default it inherits from
 * the series color.
 *
 * @type      {Color}
 * @product   highstock
 * @apioption series.flags.data.fillColor
 */

/**
 * The longer text to be shown in the flag's tooltip.
 *
 * @type      {String}
 * @product   highstock
 * @apioption series.flags.data.text
 */

/**
 * The short text to be shown on the flag.
 *
 * @type      {String}
 * @product   highstock
 * @apioption series.flags.data.title
 */