UNPKG

dash-core-components

Version:

Core component suite for Dash

500 lines (498 loc) 20.7 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.graphPropTypes = exports.graphDefaultProps = exports.default = void 0; var _react = _interopRequireWildcard(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _dashComponentPlugins = require("@plotly/dash-component-plugins"); var _graph = _interopRequireDefault(require("../utils/LazyLoader/graph")); var _plotly = _interopRequireDefault(require("../utils/LazyLoader/plotly")); var _mathjax = _interopRequireDefault(require("../utils/LazyLoader/mathjax")); var _Graph = require("../fragments/Graph.privateprops"); 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 ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); } var EMPTY_DATA = []; /** * Graph can be used to render any plotly.js-powered data visualization. * * You can define callbacks based on user interaction with Graphs such as * hovering, clicking or selecting */ class PlotlyGraph extends _react.Component { constructor(props) { super(props); if (props.mathjax) { PlotlyGraph._loadMathjax = true; } this.state = { prependData: [], extendData: [] }; this.clearState = this.clearState.bind(this); } componentDidMount() { if (this.props.prependData) { this.setState({ prependData: [this.props.prependData] }); } if (this.props.extendData) { this.setState({ extendData: [this.props.extendData] }); } } componentWillUnmount() { this.setState({ prependData: [], extendData: [] }); } UNSAFE_componentWillReceiveProps(nextProps) { var prependData = this.state.prependData.slice(0); if (this.props.figure !== nextProps.figure) { prependData = EMPTY_DATA; } if (nextProps.prependData && this.props.prependData !== nextProps.prependData) { prependData.push(nextProps.prependData); } else { prependData = EMPTY_DATA; } if (prependData !== EMPTY_DATA) { this.setState({ prependData }); } var extendData = this.state.extendData.slice(0); if (this.props.figure !== nextProps.figure) { extendData = EMPTY_DATA; } if (nextProps.extendData && this.props.extendData !== nextProps.extendData) { extendData.push(nextProps.extendData); } else { extendData = EMPTY_DATA; } if (extendData !== EMPTY_DATA) { this.setState({ extendData }); } } clearState(dataKey) { this.setState(props => { var data = props[dataKey]; var res = data && data.length ? { [dataKey]: EMPTY_DATA } : undefined; return res; }); } render() { return /*#__PURE__*/_react.default.createElement(ControlledPlotlyGraph, _extends({}, this.props, { prependData: this.state.prependData, extendData: this.state.extendData, clearState: this.clearState })); } } var RealPlotlyGraph = (0, _dashComponentPlugins.asyncDecorator)(PlotlyGraph, () => Promise.all([(0, _graph.default)(), (0, _plotly.default)(), PlotlyGraph._loadMathjax ? (0, _mathjax.default)() : undefined]).then(_ref => { var _ref2 = _slicedToArray(_ref, 1), graph = _ref2[0]; return graph; })); var ControlledPlotlyGraph = /*#__PURE__*/(0, _react.memo)(props => { var className = props.className, id = props.id; var extendedClassName = className ? 'dash-graph ' + className : 'dash-graph'; return /*#__PURE__*/_react.default.createElement(_react.Suspense, { fallback: /*#__PURE__*/_react.default.createElement("div", { id: id, key: id, className: "".concat(extendedClassName, " dash-graph--pending") }) }, /*#__PURE__*/_react.default.createElement(RealPlotlyGraph, _extends({}, props, { className: extendedClassName }))); }); ControlledPlotlyGraph.displayName = 'ControlledPlotlyGraph'; PlotlyGraph.propTypes = _objectSpread(_objectSpread({}, _Graph.privatePropTypes), {}, { /** * The ID of this component, used to identify dash components * in callbacks. The ID needs to be unique across all of the * components in an app. */ id: _propTypes.default.string, /** * If True, the Plotly.js plot will be fully responsive to window resize * and parent element resize event. This is achieved by overriding * `config.responsive` to True, `figure.layout.autosize` to True and unsetting * `figure.layout.height` and `figure.layout.width`. * If False, the Plotly.js plot not be responsive to window resize and * parent element resize event. This is achieved by overriding `config.responsive` * to False and `figure.layout.autosize` to False. * If 'auto' (default), the Graph will determine if the Plotly.js plot can be made fully * responsive (True) or not (False) based on the values in `config.responsive`, * `figure.layout.autosize`, `figure.layout.height`, `figure.layout.width`. * This is the legacy behavior of the Graph component. * * Needs to be combined with appropriate dimension / styling through the `style` prop * to fully take effect. */ responsive: _propTypes.default.oneOf([true, false, 'auto']), /** * Data from latest click event. Read-only. */ clickData: _propTypes.default.object, /** * Data from latest click annotation event. Read-only. */ clickAnnotationData: _propTypes.default.object, /** * Data from latest hover event. Read-only. */ hoverData: _propTypes.default.object, /** * If True, `clear_on_unhover` will clear the `hoverData` property * when the user "unhovers" from a point. * If False, then the `hoverData` property will be equal to the * data from the last point that was hovered over. */ clear_on_unhover: _propTypes.default.bool, /** * Data from latest select event. Read-only. */ selectedData: _propTypes.default.object, /** * Data from latest relayout event which occurs * when the user zooms or pans on the plot or other * layout-level edits. Has the form `{<attr string>: <value>}` * describing the changes made. Read-only. */ relayoutData: _propTypes.default.object, /** * Data that should be appended to existing traces. Has the form * `[updateData, traceIndices, maxPoints]`, where `updateData` is an object * containing the data to extend, `traceIndices` (optional) is an array of * trace indices that should be extended, and `maxPoints` (optional) is * either an integer defining the maximum number of points allowed or an * object with key:value pairs matching `updateData` * Reference the Plotly.extendTraces API for full usage: * https://plotly.com/javascript/plotlyjs-function-reference/#plotlyextendtraces */ extendData: _propTypes.default.oneOfType([_propTypes.default.array, _propTypes.default.object]), /** * Data that should be prepended to existing traces. Has the form * `[updateData, traceIndices, maxPoints]`, where `updateData` is an object * containing the data to prepend, `traceIndices` (optional) is an array of * trace indices that should be prepended, and `maxPoints` (optional) is * either an integer defining the maximum number of points allowed or an * object with key:value pairs matching `updateData` * Reference the Plotly.prependTraces API for full usage: * https://plotly.com/javascript/plotlyjs-function-reference/#plotlyprependtraces */ prependData: _propTypes.default.oneOfType([_propTypes.default.array, _propTypes.default.object]), /** * Data from latest restyle event which occurs * when the user toggles a legend item, changes * parcoords selections, or other trace-level edits. * Has the form `[edits, indices]`, where `edits` is an object * `{<attr string>: <value>}` describing the changes made, * and `indices` is an array of trace indices that were edited. * Read-only. */ restyleData: _propTypes.default.array, /** * Plotly `figure` object. See schema: * https://plotly.com/javascript/reference * * `config` is set separately by the `config` property */ figure: _propTypes.default.exact({ data: _propTypes.default.arrayOf(_propTypes.default.object), layout: _propTypes.default.object, frames: _propTypes.default.arrayOf(_propTypes.default.object) }), /** * Generic style overrides on the plot div */ style: _propTypes.default.object, /** * className of the parent div */ className: _propTypes.default.string, /** * If true, loads mathjax v3 (tex-svg) into the page and use it in the graph */ mathjax: _propTypes.default.bool, /** * Beta: If true, animate between updates using * plotly.js's `animate` function */ animate: _propTypes.default.bool, /** * Beta: Object containing animation settings. * Only applies if `animate` is `true` */ animation_options: _propTypes.default.object, /** * Plotly.js config options. * See https://plotly.com/javascript/configuration-options/ * for more info. */ config: _propTypes.default.exact({ /** * No interactivity, for export or image generation */ staticPlot: _propTypes.default.bool, /** * Base URL for a Plotly cloud instance, if `showSendToCloud` is enabled */ plotlyServerURL: _propTypes.default.string, /** * We can edit titles, move annotations, etc - sets all pieces of `edits` * unless a separate `edits` config item overrides individual parts */ editable: _propTypes.default.bool, /** * Enables moving selections */ editSelection: _propTypes.default.bool, /** * A set of editable properties */ edits: _propTypes.default.exact({ /** * The main anchor of the annotation, which is the * text (if no arrow) or the arrow (which drags the whole thing leaving * the arrow length & direction unchanged) */ annotationPosition: _propTypes.default.bool, /** * Just for annotations with arrows, change the length and direction of the arrow */ annotationTail: _propTypes.default.bool, annotationText: _propTypes.default.bool, axisTitleText: _propTypes.default.bool, colorbarPosition: _propTypes.default.bool, colorbarTitleText: _propTypes.default.bool, legendPosition: _propTypes.default.bool, /** * Edit the trace name fields from the legend */ legendText: _propTypes.default.bool, shapePosition: _propTypes.default.bool, /** * The global `layout.title` */ titleText: _propTypes.default.bool }), /** * DO autosize once regardless of layout.autosize * (use default width or height values otherwise) */ autosizable: _propTypes.default.bool, /** * Whether to change layout size when the window size changes */ responsive: _propTypes.default.bool, /** * Set the length of the undo/redo queue */ queueLength: _propTypes.default.number, /** * If we DO autosize, do we fill the container or the screen? */ fillFrame: _propTypes.default.bool, /** * If we DO autosize, set the frame margins in percents of plot size */ frameMargins: _propTypes.default.number, /** * Mousewheel or two-finger scroll zooms the plot */ scrollZoom: _propTypes.default.bool, /** * Double click interaction (false, 'reset', 'autosize' or 'reset+autosize') */ doubleClick: _propTypes.default.oneOf([false, 'reset', 'autosize', 'reset+autosize']), /** * Delay for registering a double-click event in ms. The * minimum value is 100 and the maximum value is 1000. By * default this is 300. */ doubleClickDelay: _propTypes.default.number, /** * New users see some hints about interactivity */ showTips: _propTypes.default.bool, /** * Enable axis pan/zoom drag handles */ showAxisDragHandles: _propTypes.default.bool, /** * Enable direct range entry at the pan/zoom drag points * (drag handles must be enabled above) */ showAxisRangeEntryBoxes: _propTypes.default.bool, /** * Link to open this plot in plotly */ showLink: _propTypes.default.bool, /** * If we show a link, does it contain data or just link to a plotly file? */ sendData: _propTypes.default.bool, /** * Text appearing in the sendData link */ linkText: _propTypes.default.string, /** * Display the mode bar (true, false, or 'hover') */ displayModeBar: _propTypes.default.oneOf([true, false, 'hover']), /** * Should we include a modebar button to send this data to a * Plotly Cloud instance, linked by `plotlyServerURL`. * By default this is false. */ showSendToCloud: _propTypes.default.bool, /** * Should we show a modebar button to send this data to a * Plotly Chart Studio plot. If both this and showSendToCloud * are selected, only showEditInChartStudio will be * honored. By default this is false. */ showEditInChartStudio: _propTypes.default.bool, /** * Remove mode bar button by name. * All modebar button names at https://github.com/plotly/plotly.js/blob/master/src/components/modebar/buttons.js * Common names include: * sendDataToCloud; * (2D) zoom2d, pan2d, select2d, lasso2d, zoomIn2d, zoomOut2d, autoScale2d, resetScale2d; * (Cartesian) hoverClosestCartesian, hoverCompareCartesian; * (3D) zoom3d, pan3d, orbitRotation, tableRotation, handleDrag3d, resetCameraDefault3d, resetCameraLastSave3d, hoverClosest3d; * (Geo) zoomInGeo, zoomOutGeo, resetGeo, hoverClosestGeo; * hoverClosestGl2d, hoverClosestPie, toggleHover, resetViews. */ modeBarButtonsToRemove: _propTypes.default.array, /** * Add mode bar button using config objects */ modeBarButtonsToAdd: _propTypes.default.array, /** * Fully custom mode bar buttons as nested array, * where the outer arrays represents button groups, and * the inner arrays have buttons config objects or names of default buttons */ modeBarButtons: _propTypes.default.any, /** * Modifications to how the toImage modebar button works */ toImageButtonOptions: _propTypes.default.exact({ /** * The file format to create */ format: _propTypes.default.oneOf(['jpeg', 'png', 'webp', 'svg']), /** * The name given to the downloaded file */ filename: _propTypes.default.string, /** * Width of the downloaded file, in px */ width: _propTypes.default.number, /** * Height of the downloaded file, in px */ height: _propTypes.default.number, /** * Extra resolution to give the file after * rendering it with the given width and height */ scale: _propTypes.default.number }), /** * Add the plotly logo on the end of the mode bar */ displaylogo: _propTypes.default.bool, /** * Add the plotly logo even with no modebar */ watermark: _propTypes.default.bool, /** * Increase the pixel ratio for Gl plot images */ plotGlPixelRatio: _propTypes.default.number, /** * URL to topojson files used in geo charts */ topojsonURL: _propTypes.default.string, /** * Mapbox access token (required to plot mapbox trace types) * If using an Mapbox Atlas server, set this option to '', * so that plotly.js won't attempt to authenticate to the public Mapbox server. */ mapboxAccessToken: _propTypes.default.any, /** * The locale to use. Locales may be provided with the plot * (`locales` below) or by loading them on the page, see: * https://github.com/plotly/plotly.js/blob/master/dist/README.md#to-include-localization */ locale: _propTypes.default.string, /** * Localization definitions, if you choose to provide them with the * plot rather than registering them globally. */ locales: _propTypes.default.object }), /** * Function that updates the state tree. */ setProps: _propTypes.default.func }); ControlledPlotlyGraph.propTypes = PlotlyGraph.propTypes; PlotlyGraph.defaultProps = _objectSpread(_objectSpread({}, _Graph.privateDefaultProps), {}, { clickData: null, clickAnnotationData: null, hoverData: null, selectedData: null, relayoutData: null, prependData: null, extendData: null, restyleData: null, figure: { data: [], layout: {}, frames: [] }, responsive: 'auto', mathjax: false, animate: false, animation_options: { frame: { redraw: false }, transition: { duration: 750, ease: 'cubic-in-out' } }, clear_on_unhover: false, config: {} }); var graphPropTypes = exports.graphPropTypes = PlotlyGraph.propTypes; var graphDefaultProps = exports.graphDefaultProps = PlotlyGraph.defaultProps; var _default = exports.default = PlotlyGraph;