AccessibilityComponent.js 12.2 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
/* *
 *
 *  (c) 2009-2019 Øystein Moseng
 *
 *  Accessibility component class definition
 *
 *  License: www.highcharts.com/license
 *
 * */

'use strict';
import Highcharts from '../../parts/Globals.js';

var win = Highcharts.win,
    doc = win.document,
    merge = Highcharts.merge,
    addEvent = Highcharts.addEvent;


/**
 * The AccessibilityComponent base class, representing a part of the chart that
 * has accessibility logic connected to it. This class can be inherited from to
 * create a custom accessibility component for a chart.
 *
 * A component:
 *  - Must call initBase after inheriting.
 *  - Can override any of the following functions: init(), destroy(),
 *      getKeyboardNavigation(), onChartUpdate().
 *  - Should take care to destroy added elements and unregister event handlers
 *      on destroy.
 *
 * @sample highcharts/accessibility/custom-component
 *         Custom accessibility component
 *
 * @requires module:modules/accessibility
 * @class
 * @name Highcharts.AccessibilityComponent
 */
function AccessibilityComponent() {}
/**
 * @lends Highcharts.AccessibilityComponent
 */
AccessibilityComponent.prototype = {

    /**
     * Initialize the class
     * @private
     * @param {Highcharts.Chart} chart
     *        Chart object
     */
    initBase: function (chart) {
        this.chart = chart;
        this.eventRemovers = [];
        this.domElements = [];
        // Key code enum for common keys
        this.keyCodes = {
            left: 37,
            right: 39,
            up: 38,
            down: 40,
            enter: 13,
            space: 32,
            esc: 27,
            tab: 9
        };
        // CSS Styles for hiding elements visually but keeping them visible to
        // AT.
        this.hiddenStyle = {
            position: 'absolute',
            width: '1px',
            height: '1px',
            overflow: 'hidden'
        };
    },


    /**
     * Add an event to an element and keep track of it for destroy().
     * Same args as Highcharts.addEvent
     * @private
     */
    addEvent: function () {
        var remover = Highcharts.addEvent.apply(Highcharts, arguments);
        this.eventRemovers.push(remover);
        return remover;
    },


    /**
     * Create an element and keep track of it for destroy().
     * Same args as document.createElement
     * @private
     */
    createElement: function () {
        var el = Highcharts.win.document.createElement.apply(
            Highcharts.win.document, arguments
        );
        this.domElements.push(el);
        return el;
    },


    /**
     * Utility function to clone a mouse event for re-dispatching.
     * @private
     * @param {global.Event} e The event to clone.
     * @return {global.Event} The cloned event
     */
    cloneMouseEvent: function (e) {
        if (typeof win.MouseEvent === 'function') {
            return new win.MouseEvent(e.type, e);
        }
        // No MouseEvent support, try using initMouseEvent
        if (doc.createEvent) {
            var evt = doc.createEvent('MouseEvent');
            if (evt.initMouseEvent) {
                evt.initMouseEvent(
                    e.type,
                    e.type === 'click' || e.canBubble, // #10561
                    e.cancelable,
                    e.view,
                    e.detail,
                    e.screenX,
                    e.screenY,
                    e.clientX,
                    e.clientY,
                    e.ctrlKey,
                    e.altKey,
                    e.shiftKey,
                    e.metaKey,
                    e.button,
                    e.relatedTarget
                );
                return evt;
            }

            // Fallback to basic Event
            evt = doc.createEvent('Event');
            if (evt.initEvent) {
                evt.initEvent(e.type, true, true);
                return evt;
            }
        }
    },


    /**
     * Utility function to attempt to fake a click event on an element.
     * @private
     * @param {Highcharts.HTMLDOMElement|Highcharts.SVGDOMElement} element
     */
    fakeClickEvent: function (element) {
        if (element && element.onclick && doc.createEvent) {
            var fakeEvent = doc.createEvent('Event');
            fakeEvent.initEvent('click', true, false);
            element.onclick(fakeEvent);
        }
    },


    /**
     * Create an invisible proxy HTML button in the same position as an SVG
     * element
     * @private
     * @param {Highcharts.SVGElement} svgElement The wrapped svg el to proxy.
     * @param {Highcharts.HTMLElement} parentGroup The proxy group element in
     *          the proxy container to add this button to.
     * @param {object} [attributes] Additional attributes to set.
     * @param {Highcharts.SVGElement} [posElement] Element to use for
     *          positioning instead of svgElement.
     * @param {Function} [preClickEvent] Function to call before click event
     *          fires.
     *
     * @return {Highcharts.HTMLElement} The proxy button.
     */
    createProxyButton: function (
        svgElement, parentGroup, attributes, posElement, preClickEvent
    ) {
        var svgEl = svgElement.element,
            component = this,
            proxy = this.createElement('button'),
            attrs = merge({
                'aria-label': svgEl.getAttribute('aria-label')
            }, attributes),
            positioningElement = posElement || svgElement,
            bBox = this.getElementPosition(positioningElement);

        // If we don't support getBoundingClientRect, no button is made
        if (!bBox) {
            return;
        }

        Object.keys(attrs).forEach(function (prop) {
            if (attrs[prop] !== null) {
                proxy.setAttribute(prop, attrs[prop]);
            }
        });

        merge(true, proxy.style, {
            'border-width': 0,
            'background-color': 'transparent',
            position: 'absolute',
            width: (bBox.width || 1) + 'px',
            height: (bBox.height || 1) + 'px',
            display: 'block',
            cursor: 'pointer',
            overflow: 'hidden',
            outline: 'none',
            opacity: 0.001,
            filter: 'alpha(opacity=1)',
            '-ms-filter': 'progid:DXImageTransform.Microsoft.Alpha(Opacity=1)',
            zIndex: 999,
            padding: 0,
            margin: 0,
            left: bBox.x + 'px',
            top: bBox.y - this.chart.chartHeight + 'px'
        });

        // Handle pre-click
        if (preClickEvent) {
            addEvent(proxy, 'click', preClickEvent);
        }

        // Proxy mouse events
        [
            'click', 'mouseover', 'mouseenter', 'mouseleave', 'mouseout'
        ].forEach(function (evtType) {
            addEvent(proxy, evtType, function (e) {
                var clonedEvent = component.cloneMouseEvent(e);
                if (svgEl) {
                    if (clonedEvent) {
                        if (svgEl.fireEvent) {
                            svgEl.fireEvent(clonedEvent);
                        } else if (svgEl.dispatchEvent) {
                            svgEl.dispatchEvent(clonedEvent);
                        }
                    } else if (svgEl['on' + evtType]) {
                        svgEl['on' + evtType](e);
                    }
                }
            });
        });

        // Add to chart div and unhide from screen readers
        parentGroup.appendChild(proxy);
        if (!attrs['aria-hidden']) {
            this.unhideElementFromScreenReaders(proxy);
        }
        return proxy;
    },


    /**
     * Get the position relative to chart container for a wrapped SVG element.
     * @private
     * @param {Highcharts.SVGElement} element The element to calculate position
     *          for.
     *
     * @return {object} Object with x and y props for the position.
     */
    getElementPosition: function (element) {
        var el = element.element,
            div = this.chart.renderTo;
        if (div && el && el.getBoundingClientRect) {
            var rectEl = el.getBoundingClientRect(),
                rectDiv = div.getBoundingClientRect();
            return {
                x: rectEl.left - rectDiv.left,
                y: rectEl.top - rectDiv.top,
                width: rectEl.right - rectEl.left,
                height: rectEl.bottom - rectEl.top
            };
        }
    },


    /**
     * Add a new proxy group to the proxy container. Creates the proxy container
     * if it does not exist.
     * @private
     * @param {object} attrs The attributes to set on the new group div.
     *
     * @return {Highcharts.HTMLDOMElement} The new proxy group element.
     */
    addProxyGroup: function (attrs) {
        var chart = this.chart,
            proxyContainer = chart.a11yProxyContainer;

        // Add root proxy container if it does not exist
        if (!proxyContainer) {
            chart.a11yProxyContainer = doc.createElement('div');
            chart.a11yProxyContainer.style.position = 'relative';
        }
        // Add it if it is new, else make sure we move it to the end
        if (chart.container.nextSibling !== chart.a11yProxyContainer) {
            chart.renderTo.insertBefore(
                chart.a11yProxyContainer,
                chart.container.nextSibling
            );
        }

        // Create the group and add it
        var groupDiv = this.createElement('div');
        Object.keys(attrs || {}).forEach(function (prop) {
            if (attrs[prop] !== null) {
                groupDiv.setAttribute(prop, attrs[prop]);
            }
        });
        chart.a11yProxyContainer.appendChild(groupDiv);
        return groupDiv;
    },


    /**
     * Utility function for removing an element from the DOM.
     * @private
     * @param {Highcharts.HTMLDOMElement} element The element to remove.
     */
    removeElement: function (element) {
        if (element && element.parentNode) {
            element.parentNode.removeChild(element);
        }
    },


    /**
     * Unhide an element from screen readers. Also unhides parents, and hides
     * siblings that are not explicitly unhidden.
     * @private
     * @param {Highcharts.HTMLDOMElement|Highcharts.SVGDOMElement} element
     *      The element to unhide
     */
    unhideElementFromScreenReaders: function (element) {
        element.setAttribute('aria-hidden', false);
        if (element === this.chart.renderTo || !element.parentNode) {
            return;
        }

        // Hide siblings unless their hidden state is already explicitly set
        Array.prototype.forEach.call(
            element.parentNode.childNodes,
            function (node) {
                if (!node.hasAttribute('aria-hidden')) {
                    node.setAttribute('aria-hidden', true);
                }
            }
        );
        // Repeat for parent
        this.unhideElementFromScreenReaders(element.parentNode);
    },


    /**
     * Should remove any event handlers added, as well as any DOM elements.
     * @private
     */
    destroyBase: function () {
        // Destroy proxy container
        var chart = this.chart || {},
            component = this;
        this.removeElement(chart.a11yProxyContainer);

        // Remove event callbacks and dom elements
        this.eventRemovers.forEach(function (remover) {
            remover();
        });
        this.domElements.forEach(function (element) {
            component.removeElement(element);
        });
        this.eventRemovers = [];
        this.domElements = [];
    },


    // Functions to be overridden by derived classes

    /**
     * Initialize component.
     */
    init: function () {},

    /**
     * Get keyboard navigation handler for this component.
     * @return {Highcharts.KeyboardNavigationHandler}
     */
    getKeyboardNavigation: function () {},

    /**
     * Called on updates to the chart, including options changes.
     * Note that this is also called on first render of chart.
     */
    onChartUpdate: function () {},

    /**
     * Called on every chart render.
     */
    onChartRender: function () {},

    /**
     * Called when accessibility is disabled or chart is destroyed.
     * Should call destroyBase to make sure events/elements added are removed.
     */
    destroy: function () {
        this.destroyBase();
    }

};

export default AccessibilityComponent;