-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbase.py
More file actions
2935 lines (2534 loc) · 111 KB
/
Copy pathbase.py
File metadata and controls
2935 lines (2534 loc) · 111 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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Core React Flow component and helpers."""
from __future__ import annotations
import hashlib
import inspect
import json
import os
from collections.abc import Callable
from dataclasses import dataclass
from functools import partial
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal
from uuid import uuid4
import panel as pn
import param
from bokeh.embed.bundle import extension_dirs
from bokeh.plotting import figure
from panel.config import config
from panel.custom import Children, ReactComponent
from panel.io.resources import EXTENSION_CDN
from panel.io.state import state
from panel.util import base_version, classproperty
from panel.viewable import Viewer
from panel.widgets import JSONEditor
from .__version import __version__ # noqa
if TYPE_CHECKING:
from bokeh.models import UIElement
IS_RELEASE = __version__ == base_version(__version__)
BASE_PATH = Path(__file__).parent
DIST_PATH = BASE_PATH / "dist"
CDN_BASE = f"https://cdn.holoviz.org/panel-reactflow/v{base_version(__version__)}"
CDN_DIST = f"{CDN_BASE}/panel-reactflow.bundle.js"
extension_dirs["panel-reactflow"] = DIST_PATH
EXTENSION_CDN[DIST_PATH] = CDN_BASE
BK_FIGURE_CSS = """
.bk-Canvas {
transform: scale(var(--rf-inverse-zoom));
transform-origin: top left;
width: calc(var(--rf-zoom) * 100%);
height: calc(var(--rf-zoom) * 100%);
}
"""
def _ensure_jsonable(value: Any, path: str) -> None:
"""Ensure value can be JSON-serialized for syncing to the frontend."""
try:
json.dumps(value)
except Exception as exc:
raise ValueError(f"Value at {path} is not JSON-serializable.") from exc
def _is_param_class(obj: Any) -> bool:
"""Check if *obj* is a ``param.Parameterized`` **subclass** (not instance)."""
return isinstance(obj, type) and issubclass(obj, param.Parameterized)
def _is_pydantic_class(obj: Any) -> bool:
"""Check if *obj* is a Pydantic ``BaseModel`` subclass."""
try:
from pydantic import BaseModel
return isinstance(obj, type) and issubclass(obj, BaseModel)
except ImportError:
return False
def _param_to_jsonschema(parameterized_cls: type) -> dict[str, Any]:
"""Convert a ``param.Parameterized`` class to a JSON Schema dict.
Uses ``parameterized_cls.param.schema()`` for the per-property
schemas, then wraps them in a standard JSON Schema object envelope
while filtering out base ``Parameterized`` params and private
(``_``-prefixed) params.
"""
base_params = set(param.Parameterized.param)
raw = parameterized_cls.param.schema()
properties = {name: prop for name, prop in raw.items() if name not in base_params and not name.startswith("_")}
return {"type": "object", "properties": properties}
def _parameterized_data_param_names(parameterized_cls: type[param.Parameterized], base_cls: type[param.Parameterized]) -> list[str]:
"""Return subclass-defined parameter names included in node/edge data.
Only parameters with explicitly non-negative precedence are included.
"""
base_params = set(base_cls.param)
names: list[str] = []
for name in parameterized_cls.param:
if name in base_params or name.startswith("_"):
continue
precedence = parameterized_cls.param[name].precedence
if precedence is not None and precedence >= 0:
names.append(name)
return names
def _parameterized_data_schema(parameterized_cls: type[param.Parameterized], base_cls: type[param.Parameterized]) -> dict[str, Any]:
"""Build a JSON Schema for subclass-defined data parameters."""
names = _parameterized_data_param_names(parameterized_cls, base_cls)
schema = _param_to_jsonschema(parameterized_cls)
properties = schema.get("properties", {})
return {"type": "object", "properties": {name: properties[name] for name in names if name in properties}}
def _pydantic_to_jsonschema(model_cls: type) -> dict[str, Any]:
"""Convert a Pydantic ``BaseModel`` class to a JSON Schema dict."""
return model_cls.model_json_schema()
def _normalize_schema(schema: Any) -> dict[str, Any] | None:
"""Normalize a schema source to a JSON Schema dict (or ``None``)."""
if schema is None:
return None
if isinstance(schema, SchemaSource):
if schema.kind == "jsonschema":
return schema.value
elif schema.kind == "param":
return _param_to_jsonschema(schema.value)
elif schema.kind == "pydantic":
return _pydantic_to_jsonschema(schema.value)
if isinstance(schema, dict):
return schema
if _is_param_class(schema):
return _param_to_jsonschema(schema)
if _is_pydantic_class(schema):
return _pydantic_to_jsonschema(schema)
raise ValueError(f"Cannot normalize schema: {schema!r}")
def _validate_data(data: dict[str, Any], schema: dict[str, Any] | None) -> None:
"""Validate *data* against a JSON Schema if available."""
if schema is None:
return
try:
import jsonschema as _js
except ImportError:
return
try:
_js.validate(data, schema)
except _js.ValidationError as exc:
path = ".".join(str(p) for p in exc.absolute_path) or "(root)"
raise ValueError(f"Validation failed at {path}: {exc.message}") from exc
def _coerce_spec_map(specs: dict[str, Any] | None, *, edge: bool = False) -> dict[str, dict[str, Any]]:
"""Normalize a dict of type specs to JSON-serializable descriptors."""
if not specs:
return {}
normalized: dict[str, dict[str, Any]] = {}
for key, value in specs.items():
if hasattr(value, "to_dict") and callable(value.to_dict):
normalized[key] = value.to_dict()
elif isinstance(value, dict):
normalized[key] = value
elif _is_param_class(value):
klass = EdgeType if edge else NodeType
normalized[key] = klass(type=key, schema=value).to_dict()
elif _is_pydantic_class(value):
klass = EdgeType if edge else NodeType
normalized[key] = klass(type=key, schema=value).to_dict()
else:
raise ValueError(f"Unsupported spec type for '{key}'.")
return normalized
@dataclass
class SchemaSource:
"""Explicit schema source wrapper for type definitions.
Use this wrapper when you need to explicitly specify the schema format
for node or edge types. This is useful when automatic detection might
be ambiguous or when you want to be explicit about the schema source.
Parameters
----------
kind : {"jsonschema", "param", "pydantic"}
The schema format type:
- ``"jsonschema"``: A standard JSON Schema dictionary
- ``"param"``: A ``param.Parameterized`` class
- ``"pydantic"``: A Pydantic ``BaseModel`` class
value : dict or type
The schema value matching the specified ``kind``:
- For ``"jsonschema"``: A JSON Schema dictionary
- For ``"param"``: A ``param.Parameterized`` subclass
- For ``"pydantic"``: A Pydantic ``BaseModel`` subclass
Examples
--------
Using a JSON Schema:
>>> from panel_reactflow import SchemaSource
>>> schema = SchemaSource(
... kind="jsonschema",
... value={"type": "object", "properties": {"name": {"type": "string"}}}
... )
Using a Param class:
>>> import param
>>> class MyParams(param.Parameterized):
... label = param.String(default="")
>>> schema = SchemaSource(kind="param", value=MyParams)
Using a Pydantic model:
>>> from pydantic import BaseModel
>>> class MyModel(BaseModel):
... name: str
>>> schema = SchemaSource(kind="pydantic", value=MyModel)
"""
kind: Literal["jsonschema", "param", "pydantic"]
value: Any
@dataclass
class NodeType:
"""Define a custom node type with schema and port configuration.
Node types allow you to define reusable node templates with specific data
schemas, input/output ports, and display policies. When nodes are created
with this type, they automatically get schema validation and appropriate
editors.
Parameters
----------
type : str
Unique identifier for this node type. Used to reference this type
when creating nodes.
label : str, optional
Human-readable display name for this node type. If not provided,
the ``type`` value is used.
schema : dict or type, optional
Data schema for node validation and editor generation. Accepts:
- A JSON Schema dictionary
- A ``param.Parameterized`` subclass
- A Pydantic ``BaseModel`` subclass
- A :class:`SchemaSource` wrapper for explicit schema types
The schema is normalized to JSON Schema format internally.
inputs : list of str, optional
List of input port names. If provided, these ports will be rendered
on the node for incoming connections.
outputs : list of str, optional
List of output port names. If provided, these ports will be rendered
on the node for outgoing connections.
pane_policy : str, default "single"
Display policy for Panel viewables inside nodes.
Methods
-------
to_dict()
Convert this node type to a JSON-serializable dictionary.
Examples
--------
Define a simple node type with a JSON Schema:
>>> from panel_reactflow import NodeType
>>> transform_type = NodeType(
... type="transform",
... label="Data Transform",
... schema={
... "type": "object",
... "properties": {
... "operation": {"type": "string", "enum": ["filter", "map", "reduce"]},
... "parameter": {"type": "number"}
... }
... },
... inputs=["input"],
... outputs=["output"]
... )
Define a node type with a Param class:
>>> import param
>>> class TransformParams(param.Parameterized):
... operation = param.Selector(default="filter", objects=["filter", "map", "reduce"])
... parameter = param.Number(default=1.0)
>>> transform_type = NodeType(
... type="transform",
... label="Data Transform",
... schema=TransformParams,
... inputs=["input"],
... outputs=["output"]
... )
Use the node type in a ReactFlow graph:
>>> from panel_reactflow import ReactFlow, NodeSpec
>>> flow = ReactFlow(node_types={"transform": transform_type})
>>> flow.add_node(NodeSpec(
... id="t1",
... type="transform",
... position={"x": 100, "y": 100},
... data={"operation": "filter", "parameter": 2.5}
... ))
"""
type: str
label: str | None = None
schema: Any = None
inputs: list[str] | None = None
outputs: list[str] | None = None
pane_policy: str = "single"
def to_dict(self) -> dict[str, Any]:
"""Convert the node type to a JSON-serializable dictionary.
Returns
-------
dict
Dictionary representation with normalized schema.
"""
return {
"type": self.type,
"label": self.label,
"schema": _normalize_schema(self.schema),
"inputs": self.inputs,
"outputs": self.outputs,
"pane_policy": self.pane_policy,
}
@dataclass
class EdgeType:
"""Define a custom edge type with schema for edge properties.
Edge types allow you to define reusable edge templates with specific data
schemas for validation and editor generation. Use this when your edges
have custom properties beyond the basic source/target relationship.
Parameters
----------
type : str
Unique identifier for this edge type. Used to reference this type
when creating edges.
label : str, optional
Human-readable display name for this edge type. If not provided,
the ``type`` value is used.
schema : dict or type, optional
Data schema for edge validation and editor generation. Accepts the
same formats as :class:`NodeType`:
- A JSON Schema dictionary
- A ``param.Parameterized`` subclass
- A Pydantic ``BaseModel`` subclass
- A :class:`SchemaSource` wrapper for explicit schema types
Methods
-------
to_dict()
Convert this edge type to a JSON-serializable dictionary.
Examples
--------
Define an edge type with properties:
>>> from panel_reactflow import EdgeType
>>> weighted_edge = EdgeType(
... type="weighted",
... label="Weighted Connection",
... schema={
... "type": "object",
... "properties": {
... "weight": {"type": "number", "minimum": 0, "maximum": 1},
... "label": {"type": "string"}
... }
... }
... )
Use the edge type in a ReactFlow graph:
>>> from panel_reactflow import ReactFlow, EdgeSpec
>>> flow = ReactFlow(edge_types={"weighted": weighted_edge})
>>> flow.add_edge(EdgeSpec(
... id="e1",
... source="n1",
... target="n2",
... type="weighted",
... data={"weight": 0.75, "label": "strong"}
... ))
"""
type: str
label: str | None = None
schema: Any = None
def to_dict(self) -> dict[str, Any]:
"""Convert the edge type to a JSON-serializable dictionary.
Returns
-------
dict
Dictionary representation with normalized schema.
"""
return {
"type": self.type,
"label": self.label,
"schema": _normalize_schema(self.schema),
}
@dataclass
class NodeSpec:
"""Builder for node dictionaries with validation and type safety.
This helper class simplifies node creation by providing a structured
interface with sensible defaults. It ensures all required fields are
present and provides convenient conversion to/from dictionaries.
Parameters
----------
id : str
Unique identifier for the node. Must be unique within the graph.
position : dict, optional
Node position with ``x`` and ``y`` coordinates. Defaults to
``{"x": 0.0, "y": 0.0}`` if not provided.
type : str, default "panel"
Node type identifier. Use ``"panel"`` for basic nodes or reference
a custom type defined in ``ReactFlow.node_types``.
label : str, optional
Display label shown on the node. If ``None``, no label is displayed.
data : dict, optional
Custom data dictionary for the node. Defaults to ``{}`` if not provided.
This is where you store node-specific properties that match the schema.
selected : bool, default False
Whether the node is currently selected in the UI.
draggable : bool, default True
Whether the node can be dragged by users.
connectable : bool, default True
Whether edges can be connected to/from this node.
deletable : bool, default True
Whether the node can be deleted by users.
style : dict, optional
CSS style dictionary applied to the node. Example:
``{"backgroundColor": "#ff0000", "border": "2px solid black"}``
className : str, optional
CSS class name applied to the node for custom styling.
view : Panel viewable, optional
Optional Panel viewable (widget, pane, layout) to render inside
the node. The view will be displayed as the node's content.
Methods
-------
to_dict()
Convert to a dictionary for use with ReactFlow.
from_dict(payload)
Create a NodeSpec from a dictionary.
Examples
--------
Create a basic node:
>>> from panel_reactflow import NodeSpec
>>> node = NodeSpec(
... id="node1",
... position={"x": 100, "y": 50},
... label="Start Node"
... )
>>> node_dict = node.to_dict()
Create a node with custom styling:
>>> node = NodeSpec(
... id="node2",
... position={"x": 200, "y": 100},
... label="Process",
... style={"backgroundColor": "#e3f2fd", "border": "2px solid #1976d2"},
... className="custom-node"
... )
Create a node with data:
>>> node = NodeSpec(
... id="transform1",
... type="transform",
... position={"x": 300, "y": 150},
... label="Data Transform",
... data={"operation": "filter", "threshold": 0.5}
... )
Create a node with an embedded view:
>>> import panel as pn
>>> node = NodeSpec(
... id="plot1",
... position={"x": 400, "y": 200},
... label="Data Plot",
... view=pn.pane.Markdown("# Hello World")
... )
Add to a ReactFlow graph:
>>> from panel_reactflow import ReactFlow
>>> flow = ReactFlow()
>>> flow.add_node(node)
"""
id: str
position: dict[str, float] | dict[str, Any] = None
type: str = "panel"
label: str | None = None
data: dict[str, Any] | None = None
selected: bool = False
draggable: bool = True
connectable: bool = True
deletable: bool = True
style: dict[str, Any] | None = None
className: str | None = None
view: Any | None = None
def __post_init__(self) -> None:
if self.position is None:
self.position = {"x": 0.0, "y": 0.0}
if self.data is None:
self.data = {}
def to_dict(self) -> dict[str, Any]:
"""Convert the NodeSpec to a dictionary.
Returns
-------
dict
Dictionary representation suitable for ReactFlow.
"""
payload = {
"id": self.id,
"position": self.position,
"type": self.type,
"label": self.label,
"data": self.data,
"selected": self.selected,
"draggable": self.draggable,
"connectable": self.connectable,
"deletable": self.deletable,
}
if self.style is not None:
payload["style"] = self.style
if self.className is not None:
payload["className"] = self.className
if self.view is not None:
payload["view"] = self.view
return payload
@classmethod
def from_dict(cls, payload: dict[str, Any]) -> "NodeSpec":
"""Create a NodeSpec from a dictionary.
Parameters
----------
payload : dict
Dictionary containing node properties.
Returns
-------
NodeSpec
A new NodeSpec instance.
"""
return cls(**payload)
class Node(param.Parameterized):
"""Base class for object-oriented nodes.
Subclass this class when you want node instances to keep Python-side state
and react to graph events directly. Node instances can be passed anywhere
a node dict/``NodeSpec`` is accepted.
Subclasses can customize:
- ``__panel__`` to render node content.
- ``editor`` to provide a node-specific editor.
- ``on_event`` (wildcard) and event-specific ``on_*`` hooks.
"""
id = param.String(default="", doc="Unique node identifier.")
position = param.Dict(default={"x": 0.0, "y": 0.0}, doc="Node position.")
type = param.String(default="panel", doc="Node type.")
label = param.String(default=None, allow_None=True, doc="Display label.")
data = param.Dict(default={}, doc="Custom node data.")
selected = param.Boolean(default=False, doc="Selection state.")
draggable = param.Boolean(default=True, doc="Whether node is draggable.")
connectable = param.Boolean(default=True, doc="Whether node is connectable.")
deletable = param.Boolean(default=True, doc="Whether node is deletable.")
style = param.Dict(default=None, allow_None=True, doc="Optional node style.")
className = param.String(default=None, allow_None=True, doc="Optional CSS class.")
flow = param.Parameter(default=None, allow_None=True, precedence=-1, doc="Parent ReactFlow instance.")
@classmethod
def _data_param_names(cls) -> list[str]:
return _parameterized_data_param_names(cls, Node)
@classmethod
def _data_schema(cls) -> dict[str, Any]:
return _parameterized_data_schema(cls, Node)
def to_dict(self) -> dict[str, Any]:
"""Convert this node instance to a ReactFlow-compatible dictionary."""
data = dict(self.data or {})
for name in self._data_param_names():
data[name] = getattr(self, name)
payload = {
"id": self.id,
"position": dict(self.position or {"x": 0.0, "y": 0.0}),
"type": self.type or "panel",
"label": self.label,
"data": data,
"selected": self.selected,
"draggable": self.draggable,
"connectable": self.connectable,
"deletable": self.deletable,
}
if self.style is not None:
payload["style"] = dict(self.style)
if self.className is not None:
payload["className"] = self.className
view = self.__panel__()
if view is not None:
payload["view"] = view
return payload
def __panel__(self) -> Any | None:
"""Optional view rendered inside the node."""
return None
def editor(self, data, schema, *, id, type, on_patch):
"""Optional per-node editor factory.
Return ``None`` to fall back to type/default editors.
"""
return None
def on_event(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
"""Wildcard event hook for node-related events."""
def on_add(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
"""Hook called when this node is added."""
def on_delete(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
"""Hook called when this node is deleted."""
def on_move(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
"""Hook called when this node moves."""
def on_click(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
"""Hook called when this node is clicked."""
def on_data_change(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
"""Hook called when this node's data changes."""
def on_selection_changed(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
"""Hook called when this node participates in a selection update."""
def on_sync(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
"""Hook called when the graph receives a sync payload."""
@dataclass
class EdgeSpec:
"""Builder for edge dictionaries with validation and type safety.
This helper class simplifies edge creation by providing a structured
interface with sensible defaults. It ensures all required fields are
present and provides convenient conversion to/from dictionaries.
Parameters
----------
id : str
Unique identifier for the edge. Must be unique within the graph.
source : str
ID of the source node where the edge originates.
target : str
ID of the target node where the edge terminates.
label : str, optional
Display label shown on the edge. If ``None``, no label is displayed.
type : str, optional
Edge type identifier. Reference a custom type defined in
``ReactFlow.edge_types`` for schema validation and custom rendering.
selected : bool, default False
Whether the edge is currently selected in the UI.
data : dict, optional
Custom data dictionary for the edge. Defaults to ``{}`` if not provided.
This is where you store edge-specific properties that match the schema.
style : dict, optional
CSS style dictionary applied to the edge line. Example:
``{"stroke": "#ff0000", "strokeWidth": 3}``
markerEnd : dict, optional
Arrow marker configuration for the edge end. Example:
``{"type": "arrow", "color": "#000000"}``
sourceHandle : str, optional
ID of the specific handle on the source node where the edge originates.
Use this when the source node has multiple output handles defined.
targetHandle : str, optional
ID of the specific handle on the target node where the edge terminates.
Use this when the target node has multiple input handles defined.
Methods
-------
to_dict()
Convert to a dictionary for use with ReactFlow.
from_dict(payload)
Create an EdgeSpec from a dictionary.
Examples
--------
Create a basic edge:
>>> from panel_reactflow import EdgeSpec
>>> edge = EdgeSpec(
... id="edge1",
... source="node1",
... target="node2"
... )
>>> edge_dict = edge.to_dict()
Create an edge with styling:
>>> edge = EdgeSpec(
... id="edge2",
... source="node2",
... target="node3",
... label="Connection",
... style={"stroke": "#1976d2", "strokeWidth": 2},
... markerEnd={"type": "arrowclosed", "color": "#1976d2"}
... )
Create a typed edge with data:
>>> edge = EdgeSpec(
... id="weighted_edge",
... source="n1",
... target="n2",
... type="weighted",
... label="0.75",
... data={"weight": 0.75, "confidence": 0.9}
... )
Create an edge with specific handles:
>>> edge = EdgeSpec(
... id="handle_edge",
... source="producer",
... target="consumer",
... sourceHandle="result",
... targetHandle="mode"
... )
Add to a ReactFlow graph:
>>> from panel_reactflow import ReactFlow
>>> flow = ReactFlow()
>>> flow.add_edge(edge)
"""
id: str
source: str
target: str
label: str | None = None
type: str | None = None
selected: bool = False
data: dict[str, Any] | None = None
style: dict[str, Any] | None = None
markerEnd: dict[str, Any] | None = None
sourceHandle: str | None = None
targetHandle: str | None = None
def __post_init__(self) -> None:
if self.data is None:
self.data = {}
def to_dict(self) -> dict[str, Any]:
"""Convert the EdgeSpec to a dictionary.
Returns
-------
dict
Dictionary representation suitable for ReactFlow.
"""
payload = {
"id": self.id,
"source": self.source,
"target": self.target,
"label": self.label,
"type": self.type,
"selected": self.selected,
"data": self.data,
}
if self.style is not None:
payload["style"] = self.style
if self.markerEnd is not None:
payload["markerEnd"] = self.markerEnd
if self.sourceHandle is not None:
payload["sourceHandle"] = self.sourceHandle
if self.targetHandle is not None:
payload["targetHandle"] = self.targetHandle
return payload
@classmethod
def from_dict(cls, payload: dict[str, Any]) -> "EdgeSpec":
"""Create an EdgeSpec from a dictionary.
Parameters
----------
payload : dict
Dictionary containing edge properties.
Returns
-------
EdgeSpec
A new EdgeSpec instance.
"""
return cls(**payload)
class Edge(param.Parameterized):
"""Base class for object-oriented edges."""
id = param.String(default="", doc="Unique edge identifier.")
source = param.String(default="", doc="Source node id.")
target = param.String(default="", doc="Target node id.")
label = param.String(default=None, allow_None=True, doc="Display label.")
type = param.String(default=None, allow_None=True, doc="Edge type.")
selected = param.Boolean(default=False, doc="Selection state.")
data = param.Dict(default={}, doc="Custom edge data.")
style = param.Dict(default=None, allow_None=True, doc="Optional edge style.")
markerEnd = param.Dict(default=None, allow_None=True, doc="Optional edge end marker.")
sourceHandle = param.String(default=None, allow_None=True, doc="Optional source handle id.")
targetHandle = param.String(default=None, allow_None=True, doc="Optional target handle id.")
flow = param.Parameter(default=None, allow_None=True, precedence=-1, doc="Parent ReactFlow instance.")
@classmethod
def _data_param_names(cls) -> list[str]:
return _parameterized_data_param_names(cls, Edge)
@classmethod
def _data_schema(cls) -> dict[str, Any]:
return _parameterized_data_schema(cls, Edge)
def to_dict(self) -> dict[str, Any]:
"""Convert this edge instance to a ReactFlow-compatible dictionary."""
data = dict(self.data or {})
for name in self._data_param_names():
data[name] = getattr(self, name)
payload = {
"id": self.id,
"source": self.source,
"target": self.target,
"label": self.label,
"type": self.type,
"selected": self.selected,
"data": data,
}
if self.style is not None:
payload["style"] = dict(self.style)
if self.markerEnd is not None:
payload["markerEnd"] = dict(self.markerEnd)
if self.sourceHandle is not None:
payload["sourceHandle"] = self.sourceHandle
if self.targetHandle is not None:
payload["targetHandle"] = self.targetHandle
return payload
def editor(self, data, schema, *, id, type, on_patch):
"""Optional per-edge editor factory.
Return ``None`` to fall back to type/default editors.
"""
return None
def on_event(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
"""Wildcard event hook for edge-related events."""
def on_add(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
"""Hook called when this edge is added."""
def on_delete(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
"""Hook called when this edge is deleted."""
def on_data_change(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
"""Hook called when this edge's data changes."""
def on_selection_changed(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
"""Hook called when this edge participates in a selection update."""
def on_sync(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
"""Hook called when the graph receives a sync payload."""
class Editor(Viewer):
"""Base class for custom node and edge editors.
The Editor class provides a standardized interface for creating custom
property editors for nodes and edges. All editors receive a unified
signature and can report data changes back to the graph through a
callback mechanism.
All editor implementations (whether classes or functions) receive this
unified signature::
editor(data, schema, *, id, type, on_patch) -> Viewable
Parameters
----------
data : dict
Current node or edge data dictionary. This contains all the custom
properties stored in the node/edge.
schema : dict or None
Normalized JSON Schema for the node/edge type, or ``None`` if no
schema is defined. Use this to drive form generation or validation.
id : str
Unique identifier of the node or edge being edited.
type : str
Type name of the node or edge being edited.
on_patch : callable
Callback function ``on_patch(patch_dict)`` to report data changes
back to the graph. Call this with a dictionary of updated properties
when the user modifies data.
Examples
--------
Create a custom editor class:
>>> import panel as pn
>>> from panel_reactflow import Editor
>>>
>>> class ColorEditor(Editor):
... def __init__(self, data=None, schema=None, **kwargs):
... super().__init__(data, schema, **kwargs)
... self.color_picker = pn.widgets.ColorPicker(
... name="Node Color",
... value=self._data.get("color", "#000000")
... )
... self.color_picker.param.watch(self._on_change, "value")
...
... def _on_change(self, event):
... if self._on_patch:
... self._on_patch({"color": event.new})
...
... def __panel__(self):
... return self.color_picker
Use the custom editor:
>>> from panel_reactflow import ReactFlow
>>> flow = ReactFlow(
... node_editors={"panel": ColorEditor}
... )
Create an editor as a simple function:
>>> def simple_editor(data, schema, *, id, type, on_patch):
... widget = pn.widgets.TextInput(
... name="Label",
... value=data.get("label", "")
... )
... widget.param.watch(
... lambda e: on_patch({"label": e.new}),
... "value"
... )
... return widget
>>>
>>> flow = ReactFlow(default_node_editor=simple_editor)
"""
_data = param.Dict(default={}, doc="Node or edge data.")
_schema = param.Dict(default=None, allow_None=True, doc="JSON Schema for data.")
_node_id = param.String(default="", doc="Node or edge ID.")
_node_type = param.String(default="", doc="Node or edge type.")
_on_patch = param.Callable(default=None, allow_None=True, doc="Callback to report data changes.")
def __init__(self, data=None, schema=None, *, id="", type="", on_patch=None, **kwargs):
super().__init__(
_data=data if data is not None else {},
_schema=schema,
_node_id=id,
_node_type=type or "",
_on_patch=on_patch,
**kwargs,
)
class JsonEditor(Editor):
"""Simple JSON editor for node and edge data.
This editor provides a raw JSON editing interface using Panel's
JSONEditor widget. It's useful for debugging or when you want full
control over the data structure without schema-driven forms.