UNPKG

@netdata/charts

Version:

Netdata frontend SDK and chart utilities

240 lines (239 loc) 17.8 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = _interopRequireWildcard(require("react")); var _netdataUi = require("@netdata/netdata-ui"); var _html2canvas = _interopRequireDefault(require("html2canvas")); var _jspdf = _interopRequireDefault(require("jspdf")); var _download = _interopRequireDefault(require("@netdata/netdata-ui/dist/components/icon/assets/download.svg")); var _icon = _interopRequireWildcard(require("../icon")); var _provider = require("../provider"); var _jsxRuntime = require("react/jsx-runtime"); function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); } function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return r; }; var t, r = {}, e = Object.prototype, n = e.hasOwnProperty, o = "function" == typeof Symbol ? Symbol : {}, i = o.iterator || "@@iterator", a = o.asyncIterator || "@@asyncIterator", u = o.toStringTag || "@@toStringTag"; function c(t, r, e, n) { return Object.defineProperty(t, r, { value: e, enumerable: !n, configurable: !n, writable: !n }); } try { c({}, ""); } catch (t) { c = function c(t, r, e) { return t[r] = e; }; } function h(r, e, n, o) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype); return c(a, "_invoke", function (r, e, n) { var o = 1; return function (i, a) { if (3 === o) throw Error("Generator is already running"); if (4 === o) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var u = n.delegate; if (u) { var c = d(u, n); if (c) { if (c === f) continue; return c; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (1 === o) throw o = 4, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = 3; var h = s(r, e, n); if ("normal" === h.type) { if (o = n.done ? 4 : 2, h.arg === f) continue; return { value: h.arg, done: n.done }; } "throw" === h.type && (o = 4, n.method = "throw", n.arg = h.arg); } }; }(r, n, new Context(o || [])), !0), a; } function s(t, r, e) { try { return { type: "normal", arg: t.call(r, e) }; } catch (t) { return { type: "throw", arg: t }; } } r.wrap = h; var f = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var l = {}; c(l, i, function () { return this; }); var p = Object.getPrototypeOf, y = p && p(p(x([]))); y && y !== e && n.call(y, i) && (l = y); var v = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(l); function g(t) { ["next", "throw", "return"].forEach(function (r) { c(t, r, function (t) { return this._invoke(r, t); }); }); } function AsyncIterator(t, r) { function e(o, i, a, u) { var c = s(t[o], t, i); if ("throw" !== c.type) { var h = c.arg, f = h.value; return f && "object" == _typeof(f) && n.call(f, "__await") ? r.resolve(f.__await).then(function (t) { e("next", t, a, u); }, function (t) { e("throw", t, a, u); }) : r.resolve(f).then(function (t) { h.value = t, a(h); }, function (t) { return e("throw", t, a, u); }); } u(c.arg); } var o; c(this, "_invoke", function (t, n) { function i() { return new r(function (r, o) { e(t, n, r, o); }); } return o = o ? o.then(i, i) : i(); }, !0); } function d(r, e) { var n = e.method, o = r.i[n]; if (o === t) return e.delegate = null, "throw" === n && r.i["return"] && (e.method = "return", e.arg = t, d(r, e), "throw" === e.method) || "return" !== n && (e.method = "throw", e.arg = new TypeError("The iterator does not provide a '" + n + "' method")), f; var i = s(o, r.i, e.arg); if ("throw" === i.type) return e.method = "throw", e.arg = i.arg, e.delegate = null, f; var a = i.arg; return a ? a.done ? (e[r.r] = a.value, e.next = r.n, "return" !== e.method && (e.method = "next", e.arg = t), e.delegate = null, f) : a : (e.method = "throw", e.arg = new TypeError("iterator result is not an object"), e.delegate = null, f); } function w(t) { this.tryEntries.push(t); } function m(r) { var e = r[4] || {}; e.type = "normal", e.arg = t, r[4] = e; } function Context(t) { this.tryEntries = [[-1]], t.forEach(w, this), this.reset(!0); } function x(r) { if (null != r) { var e = r[i]; if (e) return e.call(r); if ("function" == typeof r.next) return r; if (!isNaN(r.length)) { var o = -1, a = function e() { for (; ++o < r.length;) if (n.call(r, o)) return e.value = r[o], e.done = !1, e; return e.value = t, e.done = !0, e; }; return a.next = a; } } throw new TypeError(_typeof(r) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, c(v, "constructor", GeneratorFunctionPrototype), c(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = c(GeneratorFunctionPrototype, u, "GeneratorFunction"), r.isGeneratorFunction = function (t) { var r = "function" == typeof t && t.constructor; return !!r && (r === GeneratorFunction || "GeneratorFunction" === (r.displayName || r.name)); }, r.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, c(t, u, "GeneratorFunction")), t.prototype = Object.create(v), t; }, r.awrap = function (t) { return { __await: t }; }, g(AsyncIterator.prototype), c(AsyncIterator.prototype, a, function () { return this; }), r.AsyncIterator = AsyncIterator, r.async = function (t, e, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(h(t, e, n, o), i); return r.isGeneratorFunction(e) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, g(v), c(v, u, "Generator"), c(v, i, function () { return this; }), c(v, "toString", function () { return "[object Generator]"; }), r.keys = function (t) { var r = Object(t), e = []; for (var n in r) e.unshift(n); return function t() { for (; e.length;) if ((n = e.pop()) in r) return t.value = n, t.done = !1, t; return t.done = !0, t; }; }, r.values = x, Context.prototype = { constructor: Context, reset: function reset(r) { if (this.prev = this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(m), !r) for (var e in this) "t" === e.charAt(0) && n.call(this, e) && !isNaN(+e.slice(1)) && (this[e] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0][4]; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(r) { if (this.done) throw r; var e = this; function n(t) { a.type = "throw", a.arg = r, e.next = t; } for (var o = e.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i[4], u = this.prev, c = i[1], h = i[2]; if (-1 === i[0]) return n("end"), !1; if (!c && !h) throw Error("try statement without catch or finally"); if (null != i[0] && i[0] <= u) { if (u < c) return this.method = "next", this.arg = t, n(c), !0; if (u < h) return n(h), !1; } } }, abrupt: function abrupt(t, r) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var n = this.tryEntries[e]; if (n[0] > -1 && n[0] <= this.prev && this.prev < n[2]) { var o = n; break; } } o && ("break" === t || "continue" === t) && o[0] <= r && r <= o[2] && (o = null); var i = o ? o[4] : {}; return i.type = t, i.arg = r, o ? (this.method = "next", this.next = o[2], f) : this.complete(i); }, complete: function complete(t, r) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && r && (this.next = r), f; }, finish: function finish(t) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var e = this.tryEntries[r]; if (e[2] === t) return this.complete(e[4], e[3]), m(e), f; } }, "catch": function _catch(t) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var e = this.tryEntries[r]; if (e[0] === t) { var n = e[4]; if ("throw" === n.type) { var o = n.arg; m(e); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(r, e, n) { return this.delegate = { i: x(r), r: e, n: n }, "next" === this.method && (this.arg = t), f; } }, r; } function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } var formatValue = function formatValue(value) { if (value === null || value === undefined) return "-"; if (_typeof(value) === "object") return JSON.stringify(value); return value; }; var convertToCSV = function convertToCSV(data) { return data.reduce(function (h, row) { return h + row.map(formatValue).join(",") + "\n"; }, ""); }; var labelTexts = { time: "timestamp", ANOMALY_RATE: "anomaly%", ANNOTATIONS: "annotations" }; var hideUnits = { time: true, ANOMALY_RATE: true, ANNOTATIONS: true }; var useDownloadCsv = function useDownloadCsv(chart) { var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "raw"; return function () { var shouldConvert = type === "converted"; var _chart$getPayload = chart.getPayload(), data = _chart$getPayload.data, labels = _chart$getPayload.labels; var tableData = [labels.map(function (l) { return hideUnits[l] ? labelTexts[l] || l : "".concat(labelTexts[l] || l, " (").concat(chart.getUnitSign({ key: "units", dimensionId: l, withoutConversion: !shouldConvert }), ")"); })]; data.forEach(function (row) { tableData.push(labels.map(function (l, index) { return shouldConvert ? index === 0 ? chart.formatTime(row[index]) : chart.getConvertedValue(row[index], { dimensionId: l }) : row[index]; })); }); var url = window.URL.createObjectURL(new Blob([convertToCSV(tableData)], { type: "text/csv;charset=utf-8;" })); var link = document.createElement("a"); link.href = url; var filename = "".concat(chart.getAttribute("name") || chart.getAttribute("contextScope").join("-").replace(".", "_"), "-").concat(type, ".csv"); link.setAttribute("download", filename); document.body.appendChild(link); link.click(); link.remove(); }; }; var useDownloadImage = function useDownloadImage(chart) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, uiName = _ref.uiName, _ref$type = _ref.type, type = _ref$type === void 0 ? "pdf" : _ref$type; return /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee() { var element, rect, filename, canvas, imgData, blob, blobUrl, link, isLandscape, pdf, pageWidth, pageHeight, imgWidth, imgHeight, pxToMm, imgWidthMm, imgHeightMm, scale, displayWidth, displayHeight; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: element = chart.getUI(uiName).getElement(); if (element.closest("[data-type='chart']")) { element = element.closest("[data-type='chart']"); } if (element) { _context.next = 4; break; } return _context.abrupt("return"); case 4: // Check if target element has size rect = element.getBoundingClientRect(); if (!(rect.width === 0 || rect.height === 0)) { _context.next = 7; break; } return _context.abrupt("return"); case 7: // Optional: log any images that might cause CORS problems document.querySelectorAll("img").forEach(function (img) { var src = img.currentSrc || img.src; try { var url = new URL(src); if (url.origin !== window.location.origin) return; } catch (_unused) { return; } }); filename = "".concat(chart.getAttribute("name") || chart.getAttribute("contextScope").join("-").replace(".", "_")); _context.prev = 9; _context.next = 12; return (0, _html2canvas["default"])(element, { useCORS: true, foreignObjectRendering: true, width: element.scrollWidth, height: element.scrollHeight, scale: 2, backgroundColor: chart.getThemeAttribute("themeBackground"), ignoreElements: function ignoreElements(el) { return el.hasAttribute("data-noprint"); } }); case 12: canvas = _context.sent; imgData = canvas.toDataURL("image/png"); if (!(type === "png")) { _context.next = 30; break; } _context.next = 17; return fetch(imgData); case 17: _context.next = 19; return _context.sent.blob(); case 19: blob = _context.sent; blobUrl = URL.createObjectURL(blob); link = document.createElement("a"); link.href = blobUrl; link.download = "".concat(filename || "print", ".png"); document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(blobUrl); _context.next = 44; break; case 30: isLandscape = element.scrollWidth > element.scrollHeight; pdf = new _jspdf["default"]({ orientation: isLandscape ? "landscape" : "portrait", unit: "mm", format: "a4" }); pageWidth = pdf.internal.pageSize.getWidth(); pageHeight = pdf.internal.pageSize.getHeight(); imgWidth = canvas.width; imgHeight = canvas.height; pxToMm = function pxToMm(px) { return px * 0.2645833333; }; imgWidthMm = pxToMm(imgWidth); imgHeightMm = pxToMm(imgHeight); scale = Math.min(pageWidth / imgWidthMm, pageHeight / imgHeightMm); displayWidth = imgWidthMm * scale; displayHeight = imgHeightMm * scale; pdf.addImage(imgData, "PNG", 0, 0, displayWidth, displayHeight); pdf.save("".concat(filename || "print", ".pdf")); case 44: _context.next = 49; break; case 46: _context.prev = 46; _context.t0 = _context["catch"](9); return _context.abrupt("return"); case 49: case "end": return _context.stop(); } }, _callee, null, [[9, 46]]); })); }; var useItems = function useItems(chart) { var downloadRawCsv = useDownloadCsv(chart); var downloadCsv = useDownloadCsv(chart, "converted"); var downloadPdf = useDownloadImage(chart); var downloadPng = useDownloadImage(chart, { type: "png" }); return (0, _react.useMemo)(function () { return [{ onClick: downloadCsv, label: "Download as CSV", "data-track": chart.track("download-csv") }, { onClick: downloadRawCsv, label: "Download raw data", "data-track": chart.track("download-raw-csv") }, { onClick: downloadPdf, label: "Download as PDF", "data-track": chart.track("download-pdf") }, { onClick: downloadPng, label: "Download as PNG", "data-track": chart.track("download-png") }]; }, [chart, chart.getHeatmapType()]); }; var Download = function Download(_ref3) { var disabled = _ref3.disabled; var chart = (0, _provider.useChart)(); var items = useItems(chart); return /*#__PURE__*/(0, _jsxRuntime.jsx)(_netdataUi.Menu, { items: items, dropProps: { align: { top: "bottom", right: "right" }, "data-toolbox": chart.getId() }, dropdownProps: { width: "130px" }, "data-track": chart.track("download-chart"), children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_icon.Button, { icon: /*#__PURE__*/(0, _jsxRuntime.jsx)(_icon["default"], { svg: _download["default"], size: "14px" }), title: "Download", disabled: disabled, "data-testid": "chartHeaderToolbox-download" }) }); }; var _default = exports["default"] = /*#__PURE__*/(0, _react.memo)(Download);