reflex-components-plotly 0.9.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,32 @@
1
+ """Plotly components."""
2
+
3
+ from reflex_base.components.component import ComponentNamespace
4
+
5
+ from .plotly import (
6
+ Plotly,
7
+ PlotlyBasic,
8
+ PlotlyCartesian,
9
+ PlotlyFinance,
10
+ PlotlyGeo,
11
+ PlotlyGl2d,
12
+ PlotlyGl3d,
13
+ PlotlyMapbox,
14
+ PlotlyStrict,
15
+ )
16
+
17
+
18
+ class PlotlyNamespace(ComponentNamespace):
19
+ """Plotly namespace."""
20
+
21
+ __call__ = Plotly.create
22
+ basic = PlotlyBasic.create
23
+ cartesian = PlotlyCartesian.create
24
+ geo = PlotlyGeo.create
25
+ gl2d = PlotlyGl2d.create
26
+ gl3d = PlotlyGl3d.create
27
+ finance = PlotlyFinance.create
28
+ mapbox = PlotlyMapbox.create
29
+ strict = PlotlyStrict.create
30
+
31
+
32
+ plotly = PlotlyNamespace()
@@ -0,0 +1,526 @@
1
+ """Component for displaying a plotly graph."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any, TypedDict, TypeVar
6
+
7
+ from reflex_base.components.component import Component, NoSSRComponent, field
8
+ from reflex_base.event import EventHandler, no_args_event_spec
9
+ from reflex_base.utils import console
10
+ from reflex_base.utils.imports import ImportDict, ImportVar
11
+ from reflex_base.vars.base import LiteralVar, Var
12
+ from reflex_components_core.core.cond import color_mode_cond
13
+
14
+ try:
15
+ from plotly.graph_objs import Figure
16
+ from plotly.graph_objs.layout import Template
17
+
18
+ except ImportError:
19
+ console.warn("Plotly is not installed. Please run `pip install plotly`.")
20
+ if not TYPE_CHECKING:
21
+ Figure = Any
22
+ Template = Any
23
+
24
+
25
+ def _event_points_data_signature(e0: Var) -> tuple[Var[list[Point]]]:
26
+ """For plotly events with event data containing a point array.
27
+
28
+ Args:
29
+ e0: The event data.
30
+
31
+ Returns:
32
+ The event data and the extracted points.
33
+ """
34
+ return (Var(_js_expr=f"extractPoints({e0}?.points)"),)
35
+
36
+
37
+ T = TypeVar("T")
38
+
39
+ ItemOrList = T | list[T]
40
+
41
+
42
+ class BBox(TypedDict):
43
+ """Bounding box for a point in a plotly graph."""
44
+
45
+ x0: float | int | None
46
+ x1: float | int | None
47
+ y0: float | int | None
48
+ y1: float | int | None
49
+ z0: float | int | None
50
+ z1: float | int | None
51
+
52
+
53
+ class Point(TypedDict):
54
+ """A point in a plotly graph."""
55
+
56
+ x: float | int | None
57
+ y: float | int | None
58
+ z: float | int | None
59
+ lat: float | int | None
60
+ lon: float | int | None
61
+ curveNumber: int | None
62
+ pointNumber: int | None
63
+ pointNumbers: list[int] | None
64
+ pointIndex: int | None
65
+ markerColor: ItemOrList[ItemOrList[float | int | str | None]] | None
66
+ markerSize: ItemOrList[ItemOrList[float | int | None,]] | None
67
+ bbox: BBox | None
68
+
69
+
70
+ class Plotly(NoSSRComponent):
71
+ """Display a plotly graph."""
72
+
73
+ library = "react-plotly.js@2.6.0"
74
+
75
+ lib_dependencies: list[str] = ["plotly.js@3.4.0"]
76
+
77
+ tag = "Plot"
78
+
79
+ is_default = True
80
+
81
+ data: Var[Figure] = field(
82
+ doc="The figure to display. This can be a plotly figure or a plotly data json."
83
+ )
84
+
85
+ layout: Var[dict] = field(doc="The layout of the graph.")
86
+
87
+ template: Var[Template] = field(
88
+ doc="The template for visual appearance of the graph."
89
+ )
90
+
91
+ config: Var[dict] = field(doc="The config of the graph.")
92
+
93
+ use_resize_handler: Var[bool] = field(
94
+ default=LiteralVar.create(True),
95
+ doc="If true, the graph will resize when the window is resized.",
96
+ )
97
+
98
+ on_after_plot: EventHandler[no_args_event_spec] = field(
99
+ doc="Fired after the plot is redrawn."
100
+ )
101
+
102
+ on_animated: EventHandler[no_args_event_spec] = field(
103
+ doc="Fired after the plot was animated."
104
+ )
105
+
106
+ on_animating_frame: EventHandler[no_args_event_spec] = field(
107
+ doc="Fired while animating a single frame (does not currently pass data through)."
108
+ )
109
+
110
+ on_animation_interrupted: EventHandler[no_args_event_spec] = field(
111
+ doc="Fired when an animation is interrupted (to start a new animation for example)."
112
+ )
113
+
114
+ on_autosize: EventHandler[no_args_event_spec] = field(
115
+ doc="Fired when the plot is responsively sized."
116
+ )
117
+
118
+ on_before_hover: EventHandler[no_args_event_spec] = field(
119
+ doc="Fired whenever mouse moves over a plot."
120
+ )
121
+
122
+ on_button_clicked: EventHandler[no_args_event_spec] = field(
123
+ doc="Fired when a plotly UI button is clicked."
124
+ )
125
+
126
+ on_click: EventHandler[_event_points_data_signature] = field(
127
+ doc="Fired when the plot is clicked."
128
+ )
129
+
130
+ on_deselect: EventHandler[no_args_event_spec] = field(
131
+ doc="Fired when a selection is cleared (via double click)."
132
+ )
133
+
134
+ on_double_click: EventHandler[no_args_event_spec] = field(
135
+ doc="Fired when the plot is double clicked."
136
+ )
137
+
138
+ on_hover: EventHandler[_event_points_data_signature] = field(
139
+ doc="Fired when a plot element is hovered over."
140
+ )
141
+
142
+ on_relayout: EventHandler[no_args_event_spec] = field(
143
+ doc="Fired after the plot is laid out (zoom, pan, etc)."
144
+ )
145
+
146
+ on_relayouting: EventHandler[no_args_event_spec] = field(
147
+ doc="Fired while the plot is being laid out."
148
+ )
149
+
150
+ on_restyle: EventHandler[no_args_event_spec] = field(
151
+ doc="Fired after the plot style is changed."
152
+ )
153
+
154
+ on_redraw: EventHandler[no_args_event_spec] = field(
155
+ doc="Fired after the plot is redrawn."
156
+ )
157
+
158
+ on_selected: EventHandler[_event_points_data_signature] = field(
159
+ doc="Fired after selecting plot elements."
160
+ )
161
+
162
+ on_selecting: EventHandler[_event_points_data_signature] = field(
163
+ doc="Fired while dragging a selection."
164
+ )
165
+
166
+ on_transitioning: EventHandler[no_args_event_spec] = field(
167
+ doc="Fired while an animation is occurring."
168
+ )
169
+
170
+ on_transition_interrupted: EventHandler[no_args_event_spec] = field(
171
+ doc="Fired when a transition is stopped early."
172
+ )
173
+
174
+ on_unhover: EventHandler[_event_points_data_signature] = field(
175
+ doc="Fired when a hovered element is no longer hovered."
176
+ )
177
+
178
+ def add_imports(self) -> dict[str, str]:
179
+ """Add imports for the plotly component.
180
+
181
+ Returns:
182
+ The imports for the plotly component.
183
+ """
184
+ return {
185
+ # For merging plotly data/layout/templates.
186
+ "mergician@v2.0.2": "mergician"
187
+ }
188
+
189
+ def add_custom_code(self) -> list[str]:
190
+ """Add custom codes for processing the plotly points data.
191
+
192
+ Returns:
193
+ Custom code snippets for the module level.
194
+ """
195
+ return [
196
+ "const removeUndefined = (obj) => {Object.keys(obj).forEach(key => obj[key] === undefined && delete obj[key]); return obj}",
197
+ """
198
+ const extractPoints = (points) => {
199
+ if (!points) return [];
200
+ return points.map(point => {
201
+ const bbox = point.bbox ? removeUndefined({
202
+ x0: point.bbox.x0,
203
+ x1: point.bbox.x1,
204
+ y0: point.bbox.y0,
205
+ y1: point.bbox.y1,
206
+ z0: point.bbox.y0,
207
+ z1: point.bbox.y1,
208
+ }) : undefined;
209
+ return removeUndefined({
210
+ x: point.x,
211
+ y: point.y,
212
+ z: point.z,
213
+ lat: point.lat,
214
+ lon: point.lon,
215
+ curveNumber: point.curveNumber,
216
+ pointNumber: point.pointNumber,
217
+ pointNumbers: point.pointNumbers,
218
+ pointIndex: point.pointIndex,
219
+ markerColor: point['marker.color'],
220
+ markerSize: point['marker.size'],
221
+ bbox: bbox,
222
+ })
223
+ })
224
+ }
225
+ """,
226
+ ]
227
+
228
+ @classmethod
229
+ def create(cls, *children, **props) -> Component:
230
+ """Create the Plotly component.
231
+
232
+ Args:
233
+ *children: The children of the component.
234
+ **props: The properties of the component.
235
+
236
+ Returns:
237
+ The Plotly component.
238
+ """
239
+ from plotly.graph_objs.layout import Template
240
+ from plotly.io import templates
241
+
242
+ responsive_template = color_mode_cond(
243
+ light=LiteralVar.create(templates["plotly"]),
244
+ dark=LiteralVar.create(templates["plotly_dark"]),
245
+ )
246
+ if isinstance(responsive_template, Var):
247
+ # Mark the conditional Var as a Template to avoid type mismatch
248
+ responsive_template = responsive_template.to(Template)
249
+ props.setdefault("template", responsive_template)
250
+ return super().create(*children, **props)
251
+
252
+ def _exclude_props(self) -> set[str]:
253
+ # These props are handled specially in the _render function
254
+ return {"data", "layout", "template"}
255
+
256
+ def _render(self):
257
+ tag = super()._render()
258
+ figure = self.data.to(dict) if self.data is not None else Var.create({})
259
+ merge_dicts = [] # Data will be merged and spread from these dict Vars
260
+ if self.layout is not None:
261
+ # Why is this not a literal dict? Great question... it didn't work
262
+ # reliably because of how _var_name_unwrapped strips the outer curly
263
+ # brackets if any of the contained Vars depend on state.
264
+ layout_dict = LiteralVar.create({"layout": self.layout})
265
+ merge_dicts.append(layout_dict)
266
+ if self.template is not None:
267
+ template_dict = LiteralVar.create({"layout": {"template": self.template}})
268
+ merge_dicts.append(template_dict._without_data())
269
+ if merge_dicts:
270
+ tag = tag.set(
271
+ special_props=[
272
+ *tag.special_props,
273
+ # Merge all dictionaries and spread the result over props.
274
+ Var(
275
+ _js_expr=f"{{...mergician({figure!s},"
276
+ f"{','.join(str(md) for md in merge_dicts)})}}",
277
+ ),
278
+ ]
279
+ )
280
+ else:
281
+ tag = tag.set(
282
+ special_props=[
283
+ *tag.special_props,
284
+ # Spread the figure dict over props, nothing to merge.
285
+ Var(_js_expr=str(figure)),
286
+ ]
287
+ )
288
+ return tag
289
+
290
+
291
+ CREATE_PLOTLY_COMPONENT: ImportDict = {
292
+ "react-plotly.js": [
293
+ ImportVar(
294
+ tag="createPlotlyComponent",
295
+ is_default=True,
296
+ package_path="/factory",
297
+ ),
298
+ ]
299
+ }
300
+
301
+
302
+ def dynamic_plotly_import(name: str, package: str) -> str:
303
+ """Create a dynamic import for a plotly component.
304
+
305
+ Args:
306
+ name: The name of the component.
307
+ package: The package path of the component.
308
+
309
+ Returns:
310
+ The dynamic import for the plotly component.
311
+ """
312
+ library_import = f"import('{package}')"
313
+ mod_import = ".then((mod) => createPlotlyComponent(mod))"
314
+ return f"""
315
+ const {name} = ClientSide(() =>
316
+ {library_import}{mod_import}
317
+ )
318
+ """
319
+
320
+
321
+ class PlotlyBasic(Plotly):
322
+ """Display a basic plotly graph."""
323
+
324
+ tag: str = "BasicPlotlyPlot"
325
+
326
+ library = "react-plotly.js@2.6.0"
327
+
328
+ lib_dependencies: list[str] = ["plotly.js-basic-dist-min@3.4.0"]
329
+
330
+ def add_imports(self) -> ImportDict | list[ImportDict]:
331
+ """Add imports for the plotly basic component.
332
+
333
+ Returns:
334
+ The imports for the plotly basic component.
335
+ """
336
+ return CREATE_PLOTLY_COMPONENT
337
+
338
+ def _get_dynamic_imports(self) -> str:
339
+ """Get the dynamic imports for the plotly basic component.
340
+
341
+ Returns:
342
+ The dynamic imports for the plotly basic component.
343
+ """
344
+ return dynamic_plotly_import(self.tag, "plotly.js-basic-dist-min")
345
+
346
+
347
+ class PlotlyCartesian(Plotly):
348
+ """Display a plotly cartesian graph."""
349
+
350
+ tag: str = "CartesianPlotlyPlot"
351
+
352
+ library = "react-plotly.js@2.6.0"
353
+
354
+ lib_dependencies: list[str] = ["plotly.js-cartesian-dist-min@3.4.0"]
355
+
356
+ def add_imports(self) -> ImportDict | list[ImportDict]:
357
+ """Add imports for the plotly cartesian component.
358
+
359
+ Returns:
360
+ The imports for the plotly cartesian component.
361
+ """
362
+ return CREATE_PLOTLY_COMPONENT
363
+
364
+ def _get_dynamic_imports(self) -> str:
365
+ """Get the dynamic imports for the plotly cartesian component.
366
+
367
+ Returns:
368
+ The dynamic imports for the plotly cartesian component.
369
+ """
370
+ return dynamic_plotly_import(self.tag, "plotly.js-cartesian-dist-min")
371
+
372
+
373
+ class PlotlyGeo(Plotly):
374
+ """Display a plotly geo graph."""
375
+
376
+ tag: str = "GeoPlotlyPlot"
377
+
378
+ library = "react-plotly.js@2.6.0"
379
+
380
+ lib_dependencies: list[str] = ["plotly.js-geo-dist-min@3.4.0"]
381
+
382
+ def add_imports(self) -> ImportDict | list[ImportDict]:
383
+ """Add imports for the plotly geo component.
384
+
385
+ Returns:
386
+ The imports for the plotly geo component.
387
+ """
388
+ return CREATE_PLOTLY_COMPONENT
389
+
390
+ def _get_dynamic_imports(self) -> str:
391
+ """Get the dynamic imports for the plotly geo component.
392
+
393
+ Returns:
394
+ The dynamic imports for the plotly geo component.
395
+ """
396
+ return dynamic_plotly_import(self.tag, "plotly.js-geo-dist-min")
397
+
398
+
399
+ class PlotlyGl3d(Plotly):
400
+ """Display a plotly 3d graph."""
401
+
402
+ tag: str = "Gl3dPlotlyPlot"
403
+
404
+ library = "react-plotly.js@2.6.0"
405
+
406
+ lib_dependencies: list[str] = ["plotly.js-gl3d-dist-min@3.4.0"]
407
+
408
+ def add_imports(self) -> ImportDict | list[ImportDict]:
409
+ """Add imports for the plotly 3d component.
410
+
411
+ Returns:
412
+ The imports for the plotly 3d component.
413
+ """
414
+ return CREATE_PLOTLY_COMPONENT
415
+
416
+ def _get_dynamic_imports(self) -> str:
417
+ """Get the dynamic imports for the plotly 3d component.
418
+
419
+ Returns:
420
+ The dynamic imports for the plotly 3d component.
421
+ """
422
+ return dynamic_plotly_import(self.tag, "plotly.js-gl3d-dist-min")
423
+
424
+
425
+ class PlotlyGl2d(Plotly):
426
+ """Display a plotly 2d graph."""
427
+
428
+ tag: str = "Gl2dPlotlyPlot"
429
+
430
+ library = "react-plotly.js@2.6.0"
431
+
432
+ lib_dependencies: list[str] = ["plotly.js-gl2d-dist-min@3.4.0"]
433
+
434
+ def add_imports(self) -> ImportDict | list[ImportDict]:
435
+ """Add imports for the plotly 2d component.
436
+
437
+ Returns:
438
+ The imports for the plotly 2d component.
439
+ """
440
+ return CREATE_PLOTLY_COMPONENT
441
+
442
+ def _get_dynamic_imports(self) -> str:
443
+ """Get the dynamic imports for the plotly 2d component.
444
+
445
+ Returns:
446
+ The dynamic imports for the plotly 2d component.
447
+ """
448
+ return dynamic_plotly_import(self.tag, "plotly.js-gl2d-dist-min")
449
+
450
+
451
+ class PlotlyMapbox(Plotly):
452
+ """Display a plotly mapbox graph."""
453
+
454
+ tag: str = "MapboxPlotlyPlot"
455
+
456
+ library = "react-plotly.js@2.6.0"
457
+
458
+ lib_dependencies: list[str] = ["plotly.js-mapbox-dist-min@3.4.0"]
459
+
460
+ def add_imports(self) -> ImportDict | list[ImportDict]:
461
+ """Add imports for the plotly mapbox component.
462
+
463
+ Returns:
464
+ The imports for the plotly mapbox component.
465
+ """
466
+ return CREATE_PLOTLY_COMPONENT
467
+
468
+ def _get_dynamic_imports(self) -> str:
469
+ """Get the dynamic imports for the plotly mapbox component.
470
+
471
+ Returns:
472
+ The dynamic imports for the plotly mapbox component.
473
+ """
474
+ return dynamic_plotly_import(self.tag, "plotly.js-mapbox-dist-min")
475
+
476
+
477
+ class PlotlyFinance(Plotly):
478
+ """Display a plotly finance graph."""
479
+
480
+ tag: str = "FinancePlotlyPlot"
481
+
482
+ library = "react-plotly.js@2.6.0"
483
+
484
+ lib_dependencies: list[str] = ["plotly.js-finance-dist-min@3.4.0"]
485
+
486
+ def add_imports(self) -> ImportDict | list[ImportDict]:
487
+ """Add imports for the plotly finance component.
488
+
489
+ Returns:
490
+ The imports for the plotly finance component.
491
+ """
492
+ return CREATE_PLOTLY_COMPONENT
493
+
494
+ def _get_dynamic_imports(self) -> str:
495
+ """Get the dynamic imports for the plotly finance component.
496
+
497
+ Returns:
498
+ The dynamic imports for the plotly finance component.
499
+ """
500
+ return dynamic_plotly_import(self.tag, "plotly.js-finance-dist-min")
501
+
502
+
503
+ class PlotlyStrict(Plotly):
504
+ """Display a plotly strict graph."""
505
+
506
+ tag: str = "StrictPlotlyPlot"
507
+
508
+ library = "react-plotly.js@2.6.0"
509
+
510
+ lib_dependencies: list[str] = ["plotly.js-strict-dist-min@3.4.0"]
511
+
512
+ def add_imports(self) -> ImportDict | list[ImportDict]:
513
+ """Add imports for the plotly strict component.
514
+
515
+ Returns:
516
+ The imports for the plotly strict component.
517
+ """
518
+ return CREATE_PLOTLY_COMPONENT
519
+
520
+ def _get_dynamic_imports(self) -> str:
521
+ """Get the dynamic imports for the plotly strict component.
522
+
523
+ Returns:
524
+ The dynamic imports for the plotly strict component.
525
+ """
526
+ return dynamic_plotly_import(self.tag, "plotly.js-strict-dist-min")