UNPKG

highcharts

Version:
1,283 lines 83.9 kB
/* * * * Exporting module * * (c) 2010-2026 Highsoft AS * Author: Torstein Hønsi * * Integration of this software requires a license. * - For commercial use, see www.highcharts.com/license * - For non-commercial, see www.highcharts.com/license-eula * * * */ 'use strict'; import AST from '../../Core/Renderer/HTML/AST.js'; import Chart from '../../Core/Chart/Chart.js'; import ChartNavigationComposition from '../../Core/Chart/ChartNavigationComposition.js'; import D from '../../Core/Defaults.js'; const { defaultOptions, setOptions } = D; import { downloadURL, getScript } from '../../Shared/DownloadURL.js'; import ExportingDefaults from './ExportingDefaults.js'; import ExportingSymbols from './ExportingSymbols.js'; import Fullscreen from './Fullscreen.js'; import G from '../../Core/Globals.js'; const { composed, doc, isFirefox, isMS, isSafari, SVG_NS, win } = G; import HU from '../../Core/HttpUtilities.js'; import { addEvent, createElement, css, discardElement, extend, find, fireEvent, internalClearTimeout, isObject, merge, objectEach, pick, pushUnique, removeEvent, splat } from '../../Shared/Utilities.js'; import { error, uniqueKey } from '../../Core/Utilities.js'; AST.allowedAttributes.push('data-z-index', 'fill-opacity', 'filter', 'preserveAspectRatio', 'rx', 'ry', 'stroke-dasharray', 'stroke-linejoin', 'stroke-opacity', 'text-anchor', 'transform', 'transform-origin', 'version', 'viewBox', 'visibility', 'xmlns', 'xmlns:xlink'); AST.allowedTags.push('desc', 'clippath', 'fedropshadow', 'femorphology', 'g', 'image'); /* * * * Constants * * */ const domurl = win.URL || win.webkitURL || win; /* * * * Class * * */ /** * The Exporting class provides methods for exporting charts to images. If the * exporting module is loaded, this class is instantiated on the chart and * available through the `chart.exporting` property. Read more about the * [exporting module](https://www.highcharts.com/docs/export-module-overview). * * @class * @name Highcharts.Exporting * * @param {Highcharts.Chart} chart * The chart instance. */ export class Exporting { /* * * * Constructor * * */ constructor(chart, options) { /** @internal */ this.options = {}; this.chart = chart; this.options = options; this.btnCount = 0; this.buttonOffset = 0; this.divElements = []; this.svgElements = []; } /* * * * Static Functions * * */ /** * Make hyphenated property names out of camelCase. * * @internal * @static * @function Highcharts.Exporting#hyphenate * * @param {string} property * Property name in camelCase. * * @return {string} * Hyphenated property name. * * @requires modules/exporting */ static hyphenate(property) { return property.replace(/[A-Z]/g, function (match) { return '-' + match.toLowerCase(); }); } /** * Get data:URL from image URL. * * @internal * @static * @async * @function Highcharts.Exporting#imageToDataURL * * @param {string} imageURL * The address or URL of the image. * @param {number} scale * The scale of the image. * @param {string} imageType * The export type of the image. * * @requires modules/exporting */ static async imageToDataURL(imageURL, scale, imageType) { // First, wait for the image to be loaded const img = await Exporting.loadImage(imageURL), canvas = doc.createElement('canvas'), ctx = canvas?.getContext('2d'); if (!ctx) { throw new Error('No canvas found!'); } else { canvas.height = img.height * scale; canvas.width = img.width * scale; ctx.drawImage(img, 0, 0, canvas.width, canvas.height); // Now we try to get the contents of the canvas return canvas.toDataURL(imageType); } } /** @internal */ static async fetchCSS(href) { try { const res = await fetch(href); const content = await res.text(); const newSheet = new CSSStyleSheet(); newSheet.replaceSync(content); return newSheet; } catch { error(`Warning: Failed to fetch CSS from ${href}`, false); } } /** @internal */ /** * Extract an array of font family names from a `font-family` string. * Handles trimming and removal of surrounding quotes. * * @param {string|undefined} fontFamily * The font-family CSS value to extract font names from. * * @return {string[]} * Array of font family names. */ static extractFontFamilies(fontFamily) { if (!fontFamily) { return []; } return fontFamily .split(',') .map((font) => font.trim().replace(/^['"]|['"]$/g, '')) .filter(Boolean); } /** * Checks if a given CSS selector affects the SVG element or any of * its descendants. Returns true if either the SVG element itself * matches the selector, or if any element within the SVG matches it. * * @internal * * @param {string} selector * The CSS selector to test against the SVG element and its descendants. * @param {SVGSVGElement} svg * The SVG element to check for matches with the selector. * * @return {boolean} * True if the selector matches the SVG or any of its descendants, * false otherwise. */ static selectorAffectsSVG(selector, svg) { try { if (svg.matches(selector)) { return true; } return !!svg.querySelector(selector); } catch { // Ignore invalid/unsupported selectors for matching. return false; } } /** @internal */ /** * Collects all unique font family names used inline within the root * SVG element and its <text> and <tspan> elements by inspecting * their style attributes and font-family attributes. * * @param {SVGSVGElement} svg * The SVG element in which to search for inline font families. * @param {Set<string>} usedFontFamilies * The set to store and accumulate unique font family names. */ static collectSVGInlineFonts(svg, usedFontFamilies) { // Include the root SVG element itself, since the chart-wide // `chart.style.fontFamily` is applied there rather than on the // individual text nodes (#24722). const nodes = [svg, ...Array.from(svg.querySelectorAll('text, tspan'))]; for (const textNode of nodes) { const styleAttr = textNode.getAttribute('style') || ''; const inlineFontFamily = textNode.getAttribute('font-family') || ''; if (styleAttr.indexOf('font-family') > -1) { const match = styleAttr.match(/font-family\s*:\s*([^;]+)/i); const families = Exporting.extractFontFamilies(match?.[1]); for (const family of families) { usedFontFamilies.add(family); } } for (const family of Exporting.extractFontFamilies(inlineFontFamily)) { usedFontFamilies.add(family); } } } /** @internal */ static async handleStyleSheet(sheet, fontFaceRules, usedFontFamilies, svg, visited = new Set()) { const href = sheet.href; if (href) { if (visited.has(href)) { return; } visited.add(href); } try { for (const rule of Array.from(sheet.cssRules)) { if (rule instanceof CSSImportRule) { try { const importedSheet = await Exporting.fetchCSS(rule.href); if (importedSheet) { await Exporting.handleStyleSheet(importedSheet, fontFaceRules, usedFontFamilies, svg, visited); } } catch { // Silently ignore CORS errors on imported stylesheets } } if (rule instanceof CSSStyleRule && Exporting.selectorAffectsSVG(rule.selectorText, svg)) { for (const family of Exporting.extractFontFamilies(rule.style.fontFamily)) { usedFontFamilies.add(family); } } if (rule instanceof CSSFontFaceRule) { let cssText = rule.cssText; if (href) { const baseUrl = href, regexp = /url\(\s*(['"]?)(?![a-z]+:|\/\/)([^'")]+?)\1\s*\)/gi; // Replace relative URLs cssText = cssText.replace(regexp, (_, quote, relPath) => { const absolutePath = new URL(relPath, baseUrl).href; return `url(${quote}${absolutePath}${quote})`; }); } fontFaceRules.push(cssText); } } } catch (e) { if (e.name === 'SecurityError' && href) { try { const newSheet = await Exporting.fetchCSS(href); if (newSheet) { await Exporting.handleStyleSheet(newSheet, fontFaceRules, usedFontFamilies, svg, visited); } } catch { // Silently ignore network failures on fallback } } } } /** @internal */ static async fetchStyleSheets(svg) { const fontFaceRules = [], usedFontFamilies = new Set(); Exporting.collectSVGInlineFonts(svg, usedFontFamilies); for (const sheet of Array.from(doc.styleSheets)) { await Exporting.handleStyleSheet(sheet, fontFaceRules, usedFontFamilies, svg); } if (!usedFontFamilies.size) { return fontFaceRules; } return fontFaceRules.filter((cssText) => { const familyMatch = cssText.match(/font-family\s*:\s*([^;]+);?/i), families = Exporting.extractFontFamilies(familyMatch?.[1]); return families.some((family) => usedFontFamilies.has(family)); }); } /** @internal */ static async inlineFonts(svg) { const cssTexts = await Exporting.fetchStyleSheets(svg), urlRegex = /url\(([^)]+)\)/g, urls = []; let cssText = cssTexts.join('\n'), match; while ((match = urlRegex.exec(cssText))) { const m = match[1].replace(/['"]/g, ''); if (!urls.includes(m)) { urls.push(m); } } const arrayBufferToBase64 = (buffer) => { let binary = ''; const bytes = new Uint8Array(buffer); for (let i = 0; i < bytes.byteLength; i++) { binary += String.fromCharCode(bytes[i]); } return btoa(binary); }; const replacements = {}; for (const url of urls) { try { const res = await fetch(url), contentType = res.headers.get('Content-Type') || '', b64 = arrayBufferToBase64(await res.arrayBuffer()); replacements[url] = `data:${contentType};base64,${b64}`; } catch { // eslint-disable-next-line } } cssText = cssText.replace(urlRegex, (_, url) => { const strippedUrl = url.replace(/['"]/g, ''); return `url(${replacements[strippedUrl] || strippedUrl})`; }); const styleEl = document.createElementNS('http://www.w3.org/2000/svg', 'style'); styleEl.textContent = cssText; // Needs to be appended to pass sanitization svg.append(styleEl); return svg; } /** * Loads an image from the provided URL. * * @internal * @static * @function Highcharts.Exporting#loadImage * * @param {string} imageURL * The address or URL of the image. * * @return {Promise<HTMLImageElement>} * Returns a Promise that resolves with the loaded HTMLImageElement. * * @requires modules/exporting */ static loadImage(imageURL) { return new Promise((resolve, reject) => { // Create an image const image = new win.Image(); // Must be set prior to loading image source image.crossOrigin = 'Anonymous'; // Return the image in case of success image.onload = () => { // IE bug where image is not always ready despite load event setTimeout(() => { resolve(image); }, Exporting.loadEventDeferDelay); }; // Reject in case of fail image.onerror = (error) => { // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors reject(error); }; // Provide the image URL image.src = imageURL; }); } /** * Prepares and returns the image export options with default values where * necessary. * * @internal * @static * @function Highcharts.Exporting#prepareImageOptions * * @param {Highcharts.ExportingOptions} exportingOptions * The exporting options. * * @return {Exporting.ImageOptions} * The finalized image export options with ensured values. * * @requires modules/exporting */ static prepareImageOptions(exportingOptions) { const type = exportingOptions?.type || 'image/png', libURL = (exportingOptions?.libURL || defaultOptions.exporting?.libURL); return { type, filename: ((exportingOptions?.filename || 'chart') + '.' + (type === 'image/svg+xml' ? 'svg' : type.split('/')[1])), scale: exportingOptions?.scale || 1, // Allow libURL to end with or without forward slash libURL: libURL?.slice(-1) !== '/' ? libURL + '/' : libURL }; } /** * Prepare the SVG DOM for exporting * * @private */ static sanitizeDOM(svg) { // Increase the size of foreignObjects to avoid clipping when the // applied font size in the export is larger than the on-screen font // size. svg.querySelectorAll('foreignObject').forEach((fo) => { ['width', 'height'].forEach((attr) => { const value = fo.getAttribute(attr); if (value) { fo.setAttribute(attr, Math.ceil(parseInt(value, 10) * 1.15)); } }); }); } /** * A collection of fixes on the produced SVG to account for expand * properties and browser bugs. Returns a cleaned SVG. * * @internal * @static * @function Highcharts.Exporting#sanitizeSVG * * @param {string} svg * SVG code to sanitize. * @param {Highcharts.Options} options * Chart options to apply. * * @return {string} * Sanitized SVG code. * * @requires modules/exporting */ static sanitizeSVG(svg, /* eslint-disable-next-line @typescript-eslint/no-unused-vars */ options) { // Remove any HTML added to the container after the SVG, like the // Stock Tools GUI wrapper (#894, #9087, #24754) const split = svg.lastIndexOf('</svg>'); if (split > -1) { svg = svg.substr(0, split + 6); } svg = svg // Some tags needs to be closed in xhtml (#13726) .replace(/(<(?:img|br).*?(?=\>))>/g, '$1 />') .replace(/(<svg(?![^>]*xmlns=)[^>]*)>/g, '$1 xmlns="http://www.w3.org/2000/svg">') .replace(/zIndex="[^"]+"/g, '') .replace(/symbolName="[^"]+"/g, '') .replace(/jQuery\d+="[^"]+"/g, '') .replace(/url\(("|&quot;)(.*?)("|&quot;)\;?\)/g, 'url($2)') .replace(/url\([^#]+#/g, 'url(#') .replace(/<svg /, '<svg xmlns:xlink="http://www.w3.org/1999/xlink" ') .replace(/ (NS\d+\:)?href=/g, ' xlink:href=') // #3567 // #24102- restore href for image elements (boost) .replace(/(<image[^>]*) xlink:href=/g, '$1 href=') .replace(/\n+/g, ' ') // Replace HTML entities, issue #347 .replace(/&nbsp;/g, '\u00A0') // No-break space .replace(/&shy;/g, '\u00AD'); // Soft hyphen return svg; } /** * Get blob URL from SVG code. Falls back to normal data URI. * * @internal * @static * @function Highcharts.Exporting#svgToDataURL * * @param {string} svg * SVG to get the URL from. * * @return {string} * The data URL. * * @requires modules/exporting */ static svgToDataURL(svg) { // Webkit and not chrome const userAgent = win.navigator.userAgent; const webKit = (userAgent.indexOf('WebKit') > -1 && userAgent.indexOf('Chrome') < 0); try { // Safari requires data URI since it doesn't allow navigation to // blob URLs. ForeignObjects also don't work well in Blobs in Chrome // (#14780). if (!webKit && svg.indexOf('<foreignObject') === -1) { return domurl.createObjectURL(new win.Blob([svg], { type: 'image/svg+xml;charset-utf-16' })); } } catch { // Ignore } return 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg); } /* * * * Functions * * */ /** * Add the export button to the chart, with options. * * @internal * @function Highcharts.Exporting#addButton * * @param {Highcharts.ExportingButtonOptions} options * The exporting button options object. * * @requires modules/exporting */ addButton(options) { const exporting = this, chart = exporting.chart, renderer = chart.renderer, btnOptions = merge(chart.options.navigation?.buttonOptions, options), onclick = btnOptions.onclick, menuItems = btnOptions.menuItems, symbolSize = btnOptions.symbolSize || 12; let symbol; if (btnOptions.enabled === false || !btnOptions.theme) { return; } const theme = chart.styledMode ? {} : btnOptions.theme; let callback = (() => { }); if (onclick) { callback = function (e) { if (e) { e.stopPropagation(); } onclick.call(chart, e, chart); }; } else if (menuItems) { callback = function (e) { // Consistent with onclick call (#3495) if (e) { e.stopPropagation(); } exporting.contextMenu(button.menuClassName, menuItems, button.translateX || 0, button.translateY || 0, button.width || 0, button.height || 0, button); button.setState(2); }; } if (btnOptions.text && btnOptions.symbol) { theme.paddingLeft = pick(theme.paddingLeft, 30); } else if (!btnOptions.text) { extend(theme, { width: btnOptions.width, height: btnOptions.height, padding: 0 }); } const button = renderer .button(btnOptions.text || '', 0, 0, callback, theme, void 0, void 0, void 0, void 0, btnOptions.useHTML) .addClass(options.className || '') .attr({ title: pick(chart.options.lang[(btnOptions._titleKey || btnOptions.titleKey)], '') }); button.menuClassName = (options.menuClassName || 'highcharts-menu-' + exporting.btnCount++); if (btnOptions.symbol) { symbol = renderer .symbol(btnOptions.symbol, Math.round((btnOptions.symbolX || 0) - (symbolSize / 2)), Math.round((btnOptions.symbolY || 0) - (symbolSize / 2)), symbolSize, symbolSize, // If symbol is an image, scale it (#7957) { width: symbolSize, height: symbolSize }) .addClass('highcharts-button-symbol') .attr({ zIndex: 1 }) .add(button); if (!chart.styledMode) { symbol.attr({ stroke: btnOptions.symbolStroke, fill: btnOptions.symbolFill, 'stroke-width': btnOptions.symbolStrokeWidth || 1 }); } } button .add(exporting.group) .align(extend(btnOptions, { width: button.width, x: pick(btnOptions.x, exporting.buttonOffset) // #1654 }), true, 'spacingBox'); exporting.buttonOffset += (((button.width || 0) + (btnOptions.buttonSpacing || 0)) * (btnOptions.align === 'right' ? -1 : 1)); exporting.svgElements.push(button, symbol); } /** * Clean up after printing a chart. * * @internal * @function Highcharts.Exporting#afterPrint * * @emits Highcharts.Chart#event:afterPrint * * @requires modules/exporting */ afterPrint() { const chart = this.chart; if (!this.printReverseInfo) { return void 0; } const { childNodes, origDisplay, resetParams } = this.printReverseInfo; // Put the chart back in this.moveContainers(chart.renderTo); // Restore all body content [].forEach.call(childNodes, function (node, i) { if (node.nodeType === 1) { node.style.display = (origDisplay[i] || ''); } }); this.isPrinting = false; // Reset printMaxWidth if (resetParams) { chart.setSize.apply(chart, resetParams); } delete this.printReverseInfo; Exporting.printingChart = void 0; fireEvent(chart, 'afterPrint'); } /** * Prepare chart and document before printing a chart. * * @internal * @function Highcharts.Exporting#beforePrint * * @emits Highcharts.Chart#event:beforePrint * * @requires modules/exporting */ beforePrint() { const chart = this.chart, body = doc.body, printMaxWidth = this.options.printMaxWidth, printReverseInfo = { childNodes: body.childNodes, origDisplay: [], resetParams: void 0 }; this.isPrinting = true; chart.pointer?.reset(void 0, 0); fireEvent(chart, 'beforePrint'); // Handle printMaxWidth if (printMaxWidth && chart.chartWidth > printMaxWidth) { printReverseInfo.resetParams = [ chart.options.chart.width, void 0, false ]; chart.setSize(printMaxWidth, void 0, false); } // Hide all body content [].forEach.call(printReverseInfo.childNodes, function (node, i) { if (node.nodeType === 1) { printReverseInfo.origDisplay[i] = node.style.display; node.style.display = 'none'; } }); // Pull out the chart this.moveContainers(body); // Storage details for undo action after printing this.printReverseInfo = printReverseInfo; } /** * Display a popup menu for choosing the export type. * * @internal * @function Highcharts.Exporting#contextMenu * * @param {string} className * An identifier for the menu. * @param {Array<(string | Highcharts.ExportingMenuObject)>} items * A collection with text and onclicks for the items. * @param {number} x * The x position of the opener button. * @param {number} y * The y position of the opener button. * @param {number} width * The width of the opener button. * @param {number} height * The height of the opener button. * @param {SVGElement} button * The SVG button element. * * @emits Highcharts.Chart#event:exportMenuHidden * @emits Highcharts.Chart#event:exportMenuShown * * @requires modules/exporting */ contextMenu(className, items, x, y, width, height, button) { const exporting = this, chart = exporting.chart, navOptions = chart.options.navigation, { chartWidth, chartHeight } = chart, cacheName = 'cache-' + className, // For mouse leave detection menuPadding = Math.max(width, height); let innerMenu, menu = chart[cacheName]; // Create the menu only the first time if (!menu) { // Create a HTML element above the SVG exporting.contextMenuEl = chart[cacheName] = menu = createElement('div', { className: className }, { position: 'absolute', zIndex: 1000, padding: menuPadding + 'px', pointerEvents: 'auto', ...chart.renderer.style }, chart.scrollablePlotArea?.fixedDiv || chart.container); innerMenu = createElement('ul', { className: 'highcharts-menu' }, chart.styledMode ? {} : { listStyle: 'none', margin: 0, padding: 0 }, menu); // Presentational CSS if (!chart.styledMode) { css(innerMenu, extend({ MozBoxShadow: '3px 3px 10px #0008', WebkitBoxShadow: '3px 3px 10px #0008', boxShadow: '3px 3px 10px #0008' }, navOptions?.menuStyle || {})); } // Hide on mouse out menu.hideMenu = function () { css(menu, { display: 'none' }); if (button) { button.setState(0); } if (chart.exporting) { chart.exporting.openMenu = false; } // #10361, #9998 css(chart.renderTo, { overflow: 'hidden' }); css(chart.container, { overflow: 'hidden' }); internalClearTimeout(menu.hideTimer); fireEvent(chart, 'exportMenuHidden'); }; // Hide the menu some time after mouse leave (#1357) exporting.events?.push(addEvent(menu, 'mouseleave', function () { menu.hideTimer = win.setTimeout(menu.hideMenu, 500); }), addEvent(menu, 'mouseenter', function () { internalClearTimeout(menu.hideTimer); }), // Hide it on clicking or touching outside the menu (#2258, // #2335, #2407) addEvent(doc, 'mouseup', function (e) { if (!chart.pointer?.inClass(e.target, className)) { menu.hideMenu(); } }), addEvent(menu, 'click', function () { if (chart.exporting?.openMenu) { menu.hideMenu(); } })); // Create the items items.forEach(function (item) { if (typeof item === 'string') { if (exporting.options.menuItemDefinitions?.[item]) { item = exporting.options.menuItemDefinitions[item]; } } if (isObject(item, true)) { let element; if (item.separator) { element = createElement('li', { className: 'highcharts-menu-item highcharts-separator', role: 'separator' }, void 0, innerMenu); if (!chart.styledMode) { css(element, { border: 'none', backgroundColor: 'var(--highcharts-neutral-color-40)', height: '0.5px', margin: '10px 0', padding: 0, listStyle: 'none', 'pointer-events': 'none' }); } } else { // When chart initialized with the table, wrong button // text displayed, #14352. if (item.textKey === 'viewData' && exporting.isDataTableVisible) { item.textKey = 'hideData'; } element = createElement('li', { className: 'highcharts-menu-item', onclick: function (e) { if (e) { // IE7 e.stopPropagation(); } menu.hideMenu(); if (typeof item !== 'string' && item.onclick) { // eslint-disable-next-line @typescript-eslint/no-floating-promises item.onclick.apply(chart, arguments); } } }, void 0, innerMenu); AST.setElementHTML(element, item.text || chart.options.lang[item.textKey]); if (!chart.styledMode) { element.onmouseover = function () { css(this, navOptions?.menuItemHoverStyle || {}); }; element.onmouseout = function () { css(this, navOptions?.menuItemStyle || {}); }; css(element, extend({ cursor: 'pointer' }, navOptions?.menuItemStyle || {})); } } // Keep references to menu divs to be able to destroy them exporting.divElements.push(element); } }); // Keep references to menu and innerMenu div to be able to destroy // them exporting.divElements.push(innerMenu, menu); exporting.menuHeight = menu.offsetHeight; exporting.menuWidth = menu.offsetWidth; } const menuStyle = { display: 'block' }; // If outside right, right align it if (x + (exporting.menuWidth || 0) > chartWidth) { menuStyle.right = (chartWidth - x - width - menuPadding) + 'px'; } else { menuStyle.left = (x - menuPadding) + 'px'; } // If outside bottom, bottom align it if (y + height + (exporting.menuHeight || 0) > chartHeight && button.alignOptions?.verticalAlign !== 'top') { menuStyle.bottom = (chartHeight - y - menuPadding) + 'px'; } else { menuStyle.top = (y + height - menuPadding) + 'px'; } css(menu, menuStyle); // #10361, #9998 css(chart.renderTo, { overflow: '' }); css(chart.container, { overflow: '' }); if (chart.exporting) { chart.exporting.openMenu = true; } fireEvent(chart, 'exportMenuShown'); } /** * Destroy the export buttons. * * @internal * @function Highcharts.Exporting#destroy * * @param {global.Event} [e] * Event object. * * @requires modules/exporting */ destroy(e) { const exporting = this, chart = e ? e.target : exporting.chart, { divElements, events, svgElements } = exporting; let cacheName; // Destroy the extra buttons added svgElements.forEach((elem, i) => { // Destroy and null the svg elements if (elem) { // #1822 elem.onclick = elem.ontouchstart = null; cacheName = 'cache-' + elem.menuClassName; if (chart[cacheName]) { delete chart[cacheName]; } svgElements[i] = elem.destroy(); } }); svgElements.length = 0; // Destroy the exporting group if (exporting.group) { exporting.group.destroy(); delete exporting.group; } // Destroy the divs for the menu divElements.forEach(function (elem, i) { if (elem) { // Remove the event handler internalClearTimeout(elem.hideTimer); // #5427 removeEvent(elem, 'mouseleave'); // Remove inline events divElements[i] = elem.onmouseout = elem.onmouseover = elem.ontouchstart = elem.onclick = null; // Destroy the div by moving to garbage bin discardElement(elem); } }); divElements.length = 0; if (events) { events.forEach(function (unbind) { unbind(); }); events.length = 0; } } /** * Get data URL to an image of an SVG and call download on its options * object: * * - **filename:** Name of resulting downloaded file without extension. * Default is based on the chart title. * - **type:** File type of resulting download. Default is `image/png`. * - **scale:** Scaling factor of downloaded image compared to source. * Default is `2`. * - **libURL:** URL pointing to location of dependency scripts to download * on demand. * * @async * @function Highcharts.Exporting#downloadSVG * * @param {string} svg * The generated SVG. * @param {Highcharts.ExportingOptions} exportingOptions * The exporting options. * * @requires modules/exporting */ // eslint-disable-next-line @typescript-eslint/require-await async downloadSVG(svg, exportingOptions) { const eventArgs = { svg, exportingOptions, exporting: this }; // Fire a custom event before the export starts fireEvent(Exporting.prototype, 'downloadSVG', eventArgs); // If the event was prevented, do not proceed with the export if (eventArgs.defaultPrevented) { return; } // Get the final image options const { type, filename, scale, libURL } = Exporting.prepareImageOptions(exportingOptions); let svgURL; // Initiate download depending on file type if (type === 'application/pdf') { // Error in case of offline-exporting module is not loaded throw new Error('Offline exporting logic for PDF type is not found.'); } else if (type === 'image/svg+xml') { // SVG download. In this case, we want to use Microsoft specific // Blob if available if (typeof win.MSBlobBuilder !== 'undefined') { const blob = new win.MSBlobBuilder(); blob.append(svg); svgURL = blob.getBlob('image/svg+xml'); } else { svgURL = Exporting.svgToDataURL(svg); } // Download the chart downloadURL(svgURL, filename); } else { // PNG/JPEG download - create bitmap from SVG svgURL = Exporting.svgToDataURL(svg); try { Exporting.objectURLRevoke = true; // First, try to get PNG by rendering on canvas const dataURL = await Exporting.imageToDataURL(svgURL, scale, type); downloadURL(dataURL, filename); } catch (error) { // No need for the below logic to run in case no canvas is // found if (error.message === 'No canvas found!') { throw error; } // Or in case of exceeding the input length if (svg.length > 100000000 /* RegexLimits.svgLimit */) { throw new Error('Input too long'); } // Failed due to tainted canvas // Create new and untainted canvas const canvas = doc.createElement('canvas'), ctx = canvas.getContext('2d'), matchedImageWidth = svg.match( // eslint-disable-next-line max-len /^<svg[^>]*\s{,1000}width\s{,1000}=\s{,1000}\"?(\d+)\"?[^>]*>/), matchedImageHeight = svg.match( // eslint-disable-next-line max-len /^<svg[^>]*\s{0,1000}height\s{,1000}=\s{,1000}\"?(\d+)\"?[^>]*>/); if (ctx && matchedImageWidth && matchedImageHeight) { const imageWidth = +matchedImageWidth[1] * scale, imageHeight = +matchedImageHeight[1] * scale, downloadWithCanVG = () => { const v = win.canvg.Canvg.fromString(ctx, svg); v.start(); downloadURL(win.navigator.msSaveOrOpenBlob ? canvas.msToBlob() : canvas.toDataURL(type), filename); }; canvas.width = imageWidth; canvas.height = imageHeight; // Must load canVG first if not found. Don't destroy the // object URL yet since we are doing things // asynchronously if (!win.canvg) { if (!libURL) { throw new Error('Image export requires canvg. Set ' + 'exporting.libURL or preload canvg.'); } Exporting.objectURLRevoke = true; await getScript(libURL + 'canvg.js'); } // Use loaded canvg downloadWithCanVG(); } } finally { if (Exporting.objectURLRevoke) { try { domurl.revokeObjectURL(svgURL); } catch { // Ignore } } } } } /** * Submit an SVG version of the chart along with some parameters for local * conversion (PNG, JPEG, and SVG) or conversion on a server (PDF). * * @sample highcharts/members/chart-exportchart/ * Export with no options * @sample highcharts/members/chart-exportchart-filename/ * PDF type and custom filename * @sample highcharts/exporting/menuitemdefinitions-webp/ * Export to WebP * @sample highcharts/members/chart-exportchart-custom-background/ * Different chart background in export * @sample stock/members/chart-exportchart/ * Export with Highcharts Stock * * @async * @function Highcharts.Exporting#exportChart * * @param {Highcharts.ExportingOptions} [exportingOptions] * Exporting options in addition to those defined in * [exporting](https://api.highcharts.com/highcharts/exporting). * @param {Highcharts.Options} [chartOptions] * Additional chart options for the exported chart. For example a different * background color can be added here, or `dataLabels` for export only. * * @requires modules/exporting */ async exportChart(exportingOptions, chartOptions) { // Merge the options exportingOptions = merge(this.options, exportingOptions); // If local if expected if (exportingOptions.local) { // Trigger the local export logic await this.localExport(exportingOptions, chartOptions || {}); } else { // Get the SVG representation const svg = await this.getSVGForExport(exportingOptions, chartOptions); // Do the post if (exportingOptions.url) { await HU.post(exportingOptions.url, { filename: exportingOptions.filename ? exportingOptions.filename.replace(/\//g, '-') : this.getFilename(), type: exportingOptions.type, width: exportingOptions.width, scale: exportingOptions.scale, svg }, exportingOptions.fetchOptions); } } } /** * Handles the fallback to the export server when a local export fails. * * @internal * @async * @function Highcharts.Exporting#fallbackToServer * * @param {Highcharts.ExportingOptions} exportingOptions * The exporting options. * @param {Error} err * The error that caused the local export to fail. * * @return {Promise<void>} * A promise that resolves when the fallback process is complete. * * @requires modules/exporting */ async fallbackToServer(exportingOptions, err) { if (exportingOptions.fallbackToExportServer === false) { if (exportingOptions.error) { exportingOptions.error(exportingOptions, err); } else { // Fallback disabled error(err?.message || 28, true, this.chart); } } else if (exportingOptions.type === 'application/pdf') { // The local must be false to fallback to server for PDF export exportingOptions.local = false; // Allow fallback to server only for PDFs that failed locally await this.exportChart(exportingOptions); } else { error(err.message, false); } } /** * Return the unfiltered innerHTML of the chart container. Used as hook for * plugins. In styled mode, it also takes care of inlining CSS style rules. * * @see Chart#getSVG * * @function Highcharts.Exporting#getChartHTML * * @param {boolean} [applyStyleSheets] * whether or not to apply the style sheets. * * @return {string} * The unfiltered SVG of the chart. * * @requires modules/exporting */ getChartHTML(applyStyleSheets) { const chart = this.chart; if (applyStyleSheets) { this.inlineStyles(); } this.resolveCSSVariables(); Exporting.sanitizeDOM(chart.renderer.box); // Move canvas contents over to SVG image elements chart.container.querySelectorAll('canvas').forEach(function (canvas) { const imageDataURL = canvas.toDataURL('image/png'), foreignObject = canvas.parentNode, imageElem = chart.renderer.image(imageDataURL, 0, 0, canvas.width, canvas.height); css(imageElem.element, { width: canvas.style.width, height: canvas.style.height }); foreignObject.parentNode.insertBefore(imageElem.element, foreignObject); foreignObject.remove(); }); return chart.container.innerHTML; } /** * Get the default file name used for exported charts. By default it creates * a file name based on the chart title. * * @function Highcharts.Exporting#getFilename * * @return {string} * A file name without extension. * * @requires modules/exporting */ getFilename() { const titleText = this.chart.userOptions.title?.text; let filename = this.options.filename; if (filename) { return filename.replace(/\//g, '-'); } if (typeof titleText === 'string') { filename = titleText .toLowerCase() .replace(/<\/?[^>]+(>|$)/g, '') // Strip HTML tags .replace(/[\s_]+/g, '-') .replace(/[^a-z\d\-]/g, '') // Preserve only latin .replace(/^[\-]+/g, '') // Dashes in the start .replace(/[\-]+/g, '-') // Dashes in a row .substr(0, 24) .replace(/[\-]+$/g, ''); // Dashes in the end; } if (!filename || filename.length < 5) { filename = 'chart'; } return filename; } /** * Return an SVG representation of the chart. * * @sample highcharts/members/chart-getsvg/ * View the SVG from a button * * @function Highcharts.Exporting#getSVG * * @param {Highcharts.Options} [chartOptions] * Additional chart options for the generated SVG representation. For * collections like `xAxis`, `yAxis` or `series`, the additional options is * either merged in to the original item of the same `id`, or to the first * item if a common id is not found. * * @param {boolean} [async=false] * Whether to get the SVG synchronously or asynchronously. The async mode * should be used when additional resources like WebGPU canvas needs to be * inlined before getting the SVG. In async mode, `getSVG` returns a * Promise. * * @return {string|Promise<string>} * The SVG representation of the rendered chart. * * @emits Highcharts.Chart#event:getSVG * @emits Highcharts.Chart#event:afterGetSVG * * @requires modules/exporting */ getSVG(chartOptions, async) { const chart = this.chart; let svg, seriesOptions, // Copy the options and add extra options options = merge(chart.options, chartOptions); // Use userOptions to make the options chain in series right (#3881) options.plotOptions = merge(chart.userOptions.plotOptions, chartOptions?.plotOptions); // ... and likewise with time, avoid that undefined time properties are // merged over legacy global time options options.time = merge(chart.userOptions.time, chartOptions?.time); // Create a sandbox where a new chart will be generated const sandbox = createElement('div', void 0, { position: 'absolute', top: '-9999em', width: chart.chartWidth + 'px', height: chart.chartHeight + 'px' }, doc.body); // Get the source size const cssWidth = chart.renderTo.style.width, cssHeight = chart.renderTo.style.height, sourceWidth = options.exporting?.sourceWidth || options.chart.width || (/px$/.test(cssWidth) && parseInt(cssWidth, 10)) || (options.isGantt ? 800 : 600), sourceHeight = options.exporting?.sourceHeight || options.chart.height || (/px$/.test(cssHeight) && parseInt(cssHeight, 10)) || 400; // Override some options extend(options.chart, { animation: false, renderTo: sandbox, forExport: true, renderer: 'SVGRenderer', width: sourceWidth, height: sourceHeight }); if (options.exporting) { options.exporting.enabled = false; // Hide buttons in print } delete options.data; // #3004 // Prepare for replicating the chart options.series = []; chart.series.forEach(function (s) { seriesOptions = merge(s.userOptions, { animation: false, // Turn off animation enableMouseTracking: false, showCheckbox: false, visible: s.visible }); // Used for the navigator series that has its own option set if (!seriesOptions.isInternal) { options?.series?.push(seriesOptions); } }); const colls = {}; chart.axes.forEach(function (axis) { // Assign an internal key to ensure a one-to-one mapping (#5924) if (!axis.userOptions.internalKey) { // #6444 axis.userOptions.internalKey = uniqueKey(); } if (options && !axis.options.isInternal) { if (!colls[axis.coll]) { colls[axis.coll] = true; options[axis.coll] = []; } options[axis.coll].push(merge(axis.userOptions, { visible: axis.visible, // Force some options that could have be set directly on // the axis while missing in the userOptions or options. type: axis.type, uniqueNames: axis.uniqueNames })); } }); // Make sure the `colorAxis` object of the `defaultOptions` isn't used // in the chart copy's user options, because a color axis should only be // added when the user actually applies it. options.colorAxis = chart.userOptions.colorAxis; // Operations to carry out on the chart copy when created. We need to do // this in a callback so that we can handle both sync and async calls. const postprocessAndGetSVG = (chartCopy) => { // Axis options and series options (#2022, #3900, #5982) if (chartOptions) { ['xAxis', 'yAxis', 'series'].forEach(fu