Skip to content

Reference

Accessible imports for the panel_reactflow package.

Edge

Bases: Parameterized

Base class for object-oriented edges.

Assigning to a parameter after the edge is part of a graph updates the browser in place, without re-serializing the whole ReactFlow.edges list. Parameters declared on a subclass are synced into the edge's data; the base parameters listed in _synced_props are synced as top-level React Flow fields.

Source code in src/panel_reactflow/base.py
class Edge(param.Parameterized):
    """Base class for object-oriented edges.

    Assigning to a parameter after the edge is part of a graph updates the
    browser in place, without re-serializing the whole ``ReactFlow.edges``
    list. Parameters declared on a subclass are synced into the edge's
    ``data``; the base parameters listed in ``_synced_props`` are synced as
    top-level React Flow fields.
    """

    # Fields ``to_dict`` serializes outside ``data``, i.e. the ones
    # ``ReactFlow.patch_edge_props`` may update in place.
    _props = (
        "source",
        "target",
        "label",
        "type",
        "selected",
        "style",
        "markerEnd",
        "sourceHandle",
        "targetHandle",
    )

    # Subset of ``_props`` pushed to the browser on assignment. ``selected``
    # is driven by the frontend while the user selects, so echoing it back
    # would fight the pointer; use ``ReactFlow.patch_edge_props`` to set it.
    _synced_props = (
        "source",
        "target",
        "label",
        "type",
        "style",
        "markerEnd",
        "sourceHandle",
        "targetHandle",
    )

    # ``data`` keys ``ReactFlow.patch_edge_data`` mirrors onto a top-level
    # property. The frontend has always promoted a patched label onto the edge
    # itself, so the parameter has to follow or the next full serialization
    # reverts it.
    _mirrored_data_keys = {"label": "label"}

    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_props_change(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
        """Hook called when this edge's top-level properties change."""

    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."""

data = param.Dict(default={}, doc='Custom edge data.') class-attribute instance-attribute

flow = param.Parameter(default=None, allow_None=True, precedence=-1, doc='Parent ReactFlow instance.') class-attribute instance-attribute

id = param.String(default='', doc='Unique edge identifier.') class-attribute instance-attribute

label = param.String(default=None, allow_None=True, doc='Display label.') class-attribute instance-attribute

markerEnd = param.Dict(default=None, allow_None=True, doc='Optional edge end marker.') class-attribute instance-attribute

selected = param.Boolean(default=False, doc='Selection state.') class-attribute instance-attribute

source = param.String(default='', doc='Source node id.') class-attribute instance-attribute

sourceHandle = param.String(default=None, allow_None=True, doc='Optional source handle id.') class-attribute instance-attribute

style = param.Dict(default=None, allow_None=True, doc='Optional edge style.') class-attribute instance-attribute

target = param.String(default='', doc='Target node id.') class-attribute instance-attribute

targetHandle = param.String(default=None, allow_None=True, doc='Optional target handle id.') class-attribute instance-attribute

type = param.String(default=None, allow_None=True, doc='Edge type.') class-attribute instance-attribute

editor(data, schema, *, id, type, on_patch)

Optional per-edge editor factory.

Return None to fall back to type/default editors.

Source code in src/panel_reactflow/base.py
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

on_add(payload, flow)

Hook called when this edge is added.

Source code in src/panel_reactflow/base.py
def on_add(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
    """Hook called when this edge is added."""

on_data_change(payload, flow)

Hook called when this edge's data changes.

Source code in src/panel_reactflow/base.py
def on_data_change(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
    """Hook called when this edge's data changes."""

on_delete(payload, flow)

Hook called when this edge is deleted.

Source code in src/panel_reactflow/base.py
def on_delete(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
    """Hook called when this edge is deleted."""

on_event(payload, flow)

Wildcard event hook for edge-related events.

Source code in src/panel_reactflow/base.py
def on_event(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
    """Wildcard event hook for edge-related events."""

on_props_change(payload, flow)

Hook called when this edge's top-level properties change.

Source code in src/panel_reactflow/base.py
def on_props_change(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
    """Hook called when this edge's top-level properties change."""

on_selection_changed(payload, flow)

Hook called when this edge participates in a selection update.

Source code in src/panel_reactflow/base.py
def on_selection_changed(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
    """Hook called when this edge participates in a selection update."""

on_sync(payload, flow)

Hook called when the graph receives a sync payload.

Source code in src/panel_reactflow/base.py
def on_sync(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
    """Hook called when the graph receives a sync payload."""

to_dict()

Convert this edge instance to a ReactFlow-compatible dictionary.

Source code in src/panel_reactflow/base.py
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

EdgeSpec dataclass

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:

Name Type Description Default
id str

Unique identifier for the edge. Must be unique within the graph.

required
source str

ID of the source node where the edge originates.

required
target str

ID of the target node where the edge terminates.

required
label str

Display label shown on the edge. If None, no label is displayed.

None
type str

Edge type identifier. Built-in types are:

  • 'bezier' (default): Smooth bezier curve
  • 'straight': Straight line between nodes
  • 'step': Orthogonal step path (right angles)
  • 'smoothstep': Step path with rounded corners
  • 'smart_bezier': Bezier curve that routes around nodes
  • 'smart_straight': Straight segments that route around nodes
  • 'smart_step': Step path that routes around nodes

You can also reference a custom type defined in ReactFlow.edge_types for schema validation and custom rendering.

None
selected bool

Whether the edge is currently selected in the UI.

False
data dict

Custom data dictionary for the edge. Defaults to {} if not provided. This is where you store edge-specific properties that match the schema.

None
style dict

CSS style dictionary applied to the edge line. Example: {"stroke": "#ff0000", "strokeWidth": 3}

None
markerEnd dict

Arrow marker configuration for the edge end. Example: {"type": "arrow", "color": "#000000"}

None
sourceHandle str

ID of the specific handle on the source node where the edge originates. Use this when the source node has multiple output handles defined.

None
targetHandle str

ID of the specific handle on the target node where the edge terminates. Use this when the target node has multiple input handles defined.

None

Methods:

Name Description
to_dict

Convert to a dictionary for use with ReactFlow.

from_dict

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)
Source code in src/panel_reactflow/base.py
@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. Built-in types are:

        - ``'bezier'`` (default): Smooth bezier curve
        - ``'straight'``: Straight line between nodes
        - ``'step'``: Orthogonal step path (right angles)
        - ``'smoothstep'``: Step path with rounded corners
        - ``'smart_bezier'``: Bezier curve that routes around nodes
        - ``'smart_straight'``: Straight segments that route around nodes
        - ``'smart_step'``: Step path that routes around nodes

        You can also 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)

data = None class-attribute instance-attribute

id instance-attribute

label = None class-attribute instance-attribute

markerEnd = None class-attribute instance-attribute

selected = False class-attribute instance-attribute

source instance-attribute

sourceHandle = None class-attribute instance-attribute

style = None class-attribute instance-attribute

target instance-attribute

targetHandle = None class-attribute instance-attribute

type = None class-attribute instance-attribute

from_dict(payload) classmethod

Create an EdgeSpec from a dictionary.

Parameters:

Name Type Description Default
payload dict

Dictionary containing edge properties.

required

Returns:

Type Description
EdgeSpec

A new EdgeSpec instance.

Source code in src/panel_reactflow/base.py
@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)

to_dict()

Convert the EdgeSpec to a dictionary.

Returns:

Type Description
dict

Dictionary representation suitable for ReactFlow.

Source code in src/panel_reactflow/base.py
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

EdgeType dataclass

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:

Name Type Description Default
type str

Unique identifier for this edge type. Used to reference this type when creating edges.

required
label str

Human-readable display name for this edge type. If not provided, the type value is used.

None
schema dict or type

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
None

Methods:

Name Description
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"}
... ))
Source code in src/panel_reactflow/base.py
@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),
        }

label = None class-attribute instance-attribute

schema = None class-attribute instance-attribute

type instance-attribute

to_dict()

Convert the edge type to a JSON-serializable dictionary.

Returns:

Type Description
dict

Dictionary representation with normalized schema.

Source code in src/panel_reactflow/base.py
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),
    }

Editor

Bases: 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:

Name Type Description Default
data dict

Current node or edge data dictionary. This contains all the custom properties stored in the node/edge.

None
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.

None
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.

None

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)
Source code in src/panel_reactflow/base.py
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,
        )

JsonEditor

Bases: 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.

The editor automatically syncs changes back to the graph when the user modifies the JSON content.

Parameters:

Name Type Description Default
data dict

Initial node or edge data dictionary. Defaults to {}.

None
schema dict

JSON Schema (not used by this editor but part of the standard interface). This editor ignores the schema and allows free-form JSON editing.

None
**kwargs

Additional keyword arguments passed to the :class:Editor base class.

{}

Examples:

Use as default editor for all nodes:

>>> from panel_reactflow import ReactFlow, JsonEditor
>>> flow = ReactFlow(default_node_editor=JsonEditor)

Use for specific node types:

>>> flow = ReactFlow(
...     node_editors={"custom": JsonEditor}
... )

The editor will display a JSON editor interface where users can directly edit the node's data dictionary.

Source code in src/panel_reactflow/base.py
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.

    The editor automatically syncs changes back to the graph when the
    user modifies the JSON content.

    Parameters
    ----------
    data : dict, optional
        Initial node or edge data dictionary. Defaults to ``{}``.
    schema : dict, optional
        JSON Schema (not used by this editor but part of the standard
        interface). This editor ignores the schema and allows free-form
        JSON editing.
    **kwargs
        Additional keyword arguments passed to the :class:`Editor` base class.

    Examples
    --------
    Use as default editor for all nodes:

    >>> from panel_reactflow import ReactFlow, JsonEditor
    >>> flow = ReactFlow(default_node_editor=JsonEditor)

    Use for specific node types:

    >>> flow = ReactFlow(
    ...     node_editors={"custom": JsonEditor}
    ... )

    The editor will display a JSON editor interface where users can
    directly edit the node's data dictionary.
    """

    def __init__(self, data=None, schema=None, **kwargs):
        super().__init__(data, schema, **kwargs)
        self._editor = JSONEditor(value=self._data)
        self._editor.param.watch(self._on_json_change, "value")

    def _on_json_change(self, event: param.parameterized.Event) -> None:
        if self._on_patch is not None and event.new != self._data:
            self._data = event.new
            self._on_patch(event.new)

    def __panel__(self):
        return self._editor

Node

Bases: 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.

Assigning to a parameter after the node is part of a graph updates the browser in place, without re-serializing the whole ReactFlow.nodes list. Parameters declared on a subclass are synced into the node's data; the presentational base parameters listed in _synced_props are synced as top-level React Flow fields.

Source code in src/panel_reactflow/base.py
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.

    Assigning to a parameter after the node is part of a graph updates the
    browser in place, without re-serializing the whole ``ReactFlow.nodes``
    list. Parameters declared on a subclass are synced into the node's
    ``data``; the presentational base parameters listed in ``_synced_props``
    are synced as top-level React Flow fields.
    """

    # Fields ``to_dict`` serializes outside ``data``, i.e. the ones
    # ``ReactFlow.patch_node_props`` may update in place.
    _props = (
        "position",
        "type",
        "label",
        "selected",
        "draggable",
        "connectable",
        "deletable",
        "style",
        "className",
    )

    # Subset of ``_props`` pushed to the browser on assignment. ``position``
    # and ``selected`` are driven by the frontend while the user drags or
    # selects, so echoing them back would fight the pointer mid-interaction;
    # use ``ReactFlow.patch_node_props`` to set them explicitly.
    _synced_props = (
        "type",
        "label",
        "draggable",
        "connectable",
        "deletable",
        "style",
        "className",
    )

    # ``data`` keys ``ReactFlow.patch_node_data`` mirrors onto a top-level
    # property. The node components render the label out of ``data._label``, so
    # a data patch that carries a label has to update the parameter too or the
    # next full serialization reverts it.
    _mirrored_data_keys = {"label": "label", "_label": "label"}

    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 context_menu(self) -> Any | None:
        """Return a Panel component to render as a context menu on right-click.

        Override this method to provide a custom context menu for this node.
        Return ``None`` to disable the context menu for this node.
        """
        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_props_change(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
        """Hook called when this node's top-level properties change."""

    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."""

className = param.String(default=None, allow_None=True, doc='Optional CSS class.') class-attribute instance-attribute

connectable = param.Boolean(default=True, doc='Whether node is connectable.') class-attribute instance-attribute

data = param.Dict(default={}, doc='Custom node data.') class-attribute instance-attribute

deletable = param.Boolean(default=True, doc='Whether node is deletable.') class-attribute instance-attribute

draggable = param.Boolean(default=True, doc='Whether node is draggable.') class-attribute instance-attribute

flow = param.Parameter(default=None, allow_None=True, precedence=-1, doc='Parent ReactFlow instance.') class-attribute instance-attribute

id = param.String(default='', doc='Unique node identifier.') class-attribute instance-attribute

label = param.String(default=None, allow_None=True, doc='Display label.') class-attribute instance-attribute

position = param.Dict(default={'x': 0.0, 'y': 0.0}, doc='Node position.') class-attribute instance-attribute

selected = param.Boolean(default=False, doc='Selection state.') class-attribute instance-attribute

style = param.Dict(default=None, allow_None=True, doc='Optional node style.') class-attribute instance-attribute

type = param.String(default='panel', doc='Node type.') class-attribute instance-attribute

context_menu()

Return a Panel component to render as a context menu on right-click.

Override this method to provide a custom context menu for this node. Return None to disable the context menu for this node.

Source code in src/panel_reactflow/base.py
def context_menu(self) -> Any | None:
    """Return a Panel component to render as a context menu on right-click.

    Override this method to provide a custom context menu for this node.
    Return ``None`` to disable the context menu for this node.
    """
    return None

editor(data, schema, *, id, type, on_patch)

Optional per-node editor factory.

Return None to fall back to type/default editors.

Source code in src/panel_reactflow/base.py
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

on_add(payload, flow)

Hook called when this node is added.

Source code in src/panel_reactflow/base.py
def on_add(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
    """Hook called when this node is added."""

on_click(payload, flow)

Hook called when this node is clicked.

Source code in src/panel_reactflow/base.py
def on_click(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
    """Hook called when this node is clicked."""

on_data_change(payload, flow)

Hook called when this node's data changes.

Source code in src/panel_reactflow/base.py
def on_data_change(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
    """Hook called when this node's data changes."""

on_delete(payload, flow)

Hook called when this node is deleted.

Source code in src/panel_reactflow/base.py
def on_delete(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
    """Hook called when this node is deleted."""

on_event(payload, flow)

Wildcard event hook for node-related events.

Source code in src/panel_reactflow/base.py
def on_event(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
    """Wildcard event hook for node-related events."""

on_move(payload, flow)

Hook called when this node moves.

Source code in src/panel_reactflow/base.py
def on_move(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
    """Hook called when this node moves."""

on_props_change(payload, flow)

Hook called when this node's top-level properties change.

Source code in src/panel_reactflow/base.py
def on_props_change(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
    """Hook called when this node's top-level properties change."""

on_selection_changed(payload, flow)

Hook called when this node participates in a selection update.

Source code in src/panel_reactflow/base.py
def on_selection_changed(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
    """Hook called when this node participates in a selection update."""

on_sync(payload, flow)

Hook called when the graph receives a sync payload.

Source code in src/panel_reactflow/base.py
def on_sync(self, payload: dict[str, Any], flow: "ReactFlow") -> None:
    """Hook called when the graph receives a sync payload."""

to_dict()

Convert this node instance to a ReactFlow-compatible dictionary.

Source code in src/panel_reactflow/base.py
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

NodeSpec dataclass

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:

Name Type Description Default
id str

Unique identifier for the node. Must be unique within the graph.

required
position dict

Node position with x and y coordinates. Defaults to {"x": 0.0, "y": 0.0} if not provided.

None
type str

Node type identifier. Use "panel" for basic nodes or reference a custom type defined in ReactFlow.node_types.

"panel"
label str

Display label shown on the node. If None, no label is displayed.

None
data dict

Custom data dictionary for the node. Defaults to {} if not provided. This is where you store node-specific properties that match the schema.

None
selected bool

Whether the node is currently selected in the UI.

False
draggable bool

Whether the node can be dragged by users.

True
connectable bool

Whether edges can be connected to/from this node.

True
deletable bool

Whether the node can be deleted by users.

True
style dict

CSS style dictionary applied to the node. Example: {"backgroundColor": "#ff0000", "border": "2px solid black"}

None
className str

CSS class name applied to the node for custom styling.

None
view Panel viewable

Optional Panel viewable (widget, pane, layout) to render inside the node. The view will be displayed as the node's content.

None

Methods:

Name Description
to_dict

Convert to a dictionary for use with ReactFlow.

from_dict

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)
Source code in src/panel_reactflow/base.py
@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)

className = None class-attribute instance-attribute

connectable = True class-attribute instance-attribute

data = None class-attribute instance-attribute

deletable = True class-attribute instance-attribute

draggable = True class-attribute instance-attribute

id instance-attribute

label = None class-attribute instance-attribute

position = None class-attribute instance-attribute

selected = False class-attribute instance-attribute

style = None class-attribute instance-attribute

type = 'panel' class-attribute instance-attribute

view = None class-attribute instance-attribute

from_dict(payload) classmethod

Create a NodeSpec from a dictionary.

Parameters:

Name Type Description Default
payload dict

Dictionary containing node properties.

required

Returns:

Type Description
NodeSpec

A new NodeSpec instance.

Source code in src/panel_reactflow/base.py
@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)

to_dict()

Convert the NodeSpec to a dictionary.

Returns:

Type Description
dict

Dictionary representation suitable for ReactFlow.

Source code in src/panel_reactflow/base.py
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

NodeType dataclass

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:

Name Type Description Default
type str

Unique identifier for this node type. Used to reference this type when creating nodes.

required
label str

Human-readable display name for this node type. If not provided, the type value is used.

None
schema dict or type

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.

None
inputs list of str or dict

List of input port definitions. Each entry can be a plain string (the handle ID) or a dict with "id" and optional "label" and "type" keys. An optional "maxConnections" integer limits connections when connection_validation["capacity"] is enabled. Labels and types render as tooltips on hover.

None
outputs list of str or dict

List of output port definitions. Each entry can be a plain string (the handle ID) or a dict with "id" and optional "label" and "type" keys. When a label and/or type is provided it renders as a tooltip on hover, e.g. "Raw data input (DataFrame)".

None
input_connectable bool

Whether input handles are connectable. When False, users cannot create connections to or from input handles.

True
input_connectable_start bool

Whether new edges can start from input handles. Set to False to prevent dragging out from input handles while still allowing edges to terminate there.

True
input_connectable_end bool

Whether new edges can end at input handles. Set to False to prevent edges from terminating at input handles while still allowing dragging from them.

True
output_connectable bool

Whether output handles are connectable. When False, users cannot create connections to or from output handles.

True
output_connectable_start bool

Whether new edges can start from output handles. Set to False to prevent dragging out from output handles while still allowing edges to terminate there.

True
output_connectable_end bool

Whether new edges can end at output handles. Set to False to prevent edges from terminating at output handles while still allowing dragging from them.

True
pane_policy str

Display policy for Panel viewables inside nodes.

"single"

Methods:

Name Description
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"]
... )

Define a sink node that accepts connections but cannot be a source:

>>> sink_type = NodeType(
...     type="sink",
...     label="Data Sink",
...     inputs=["in"],
...     outputs=["status"],
...     input_connectable_start=False,  # Cannot drag from input handles
...     output_connectable_end=False,   # Cannot drag to output handles
... )

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}
... ))
Source code in src/panel_reactflow/base.py
@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 or dict, optional
        List of input port definitions. Each entry can be a plain string
        (the handle ID) or a dict with ``"id"`` and optional ``"label"``
        and ``"type"`` keys. An optional ``"maxConnections"`` integer limits
        connections when ``connection_validation["capacity"]`` is enabled.
        Labels and types render as tooltips on hover.
    outputs : list of str or dict, optional
        List of output port definitions. Each entry can be a plain string
        (the handle ID) or a dict with ``"id"`` and optional ``"label"``
        and ``"type"`` keys. When a label and/or type is provided it renders
        as a tooltip on hover, e.g. ``"Raw data input (DataFrame)"``.
    input_connectable : bool, default True
        Whether input handles are connectable. When False, users cannot create
        connections to or from input handles.
    input_connectable_start : bool, default True
        Whether new edges can start from input handles. Set to False to prevent
        dragging out from input handles while still allowing edges to terminate there.
    input_connectable_end : bool, default True
        Whether new edges can end at input handles. Set to False to prevent
        edges from terminating at input handles while still allowing dragging from them.
    output_connectable : bool, default True
        Whether output handles are connectable. When False, users cannot create
        connections to or from output handles.
    output_connectable_start : bool, default True
        Whether new edges can start from output handles. Set to False to prevent
        dragging out from output handles while still allowing edges to terminate there.
    output_connectable_end : bool, default True
        Whether new edges can end at output handles. Set to False to prevent
        edges from terminating at output handles while still allowing dragging from them.
    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"]
    ... )

    Define a sink node that accepts connections but cannot be a source:

    >>> sink_type = NodeType(
    ...     type="sink",
    ...     label="Data Sink",
    ...     inputs=["in"],
    ...     outputs=["status"],
    ...     input_connectable_start=False,  # Cannot drag from input handles
    ...     output_connectable_end=False,   # Cannot drag to output handles
    ... )

    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 | dict[str, Any]] | None = None
    outputs: list[str | dict[str, Any]] | None = None
    input_connectable: bool = True
    input_connectable_start: bool = True
    input_connectable_end: bool = True
    output_connectable: bool = True
    output_connectable_start: bool = True
    output_connectable_end: bool = True
    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,
            "inputConnectable": self.input_connectable,
            "inputConnectableStart": self.input_connectable_start,
            "inputConnectableEnd": self.input_connectable_end,
            "outputConnectable": self.output_connectable,
            "outputConnectableStart": self.output_connectable_start,
            "outputConnectableEnd": self.output_connectable_end,
            "pane_policy": self.pane_policy,
        }

input_connectable = True class-attribute instance-attribute

input_connectable_end = True class-attribute instance-attribute

input_connectable_start = True class-attribute instance-attribute

inputs = None class-attribute instance-attribute

label = None class-attribute instance-attribute

output_connectable = True class-attribute instance-attribute

output_connectable_end = True class-attribute instance-attribute

output_connectable_start = True class-attribute instance-attribute

outputs = None class-attribute instance-attribute

pane_policy = 'single' class-attribute instance-attribute

schema = None class-attribute instance-attribute

type instance-attribute

to_dict()

Convert the node type to a JSON-serializable dictionary.

Returns:

Type Description
dict

Dictionary representation with normalized schema.

Source code in src/panel_reactflow/base.py
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,
        "inputConnectable": self.input_connectable,
        "inputConnectableStart": self.input_connectable_start,
        "inputConnectableEnd": self.input_connectable_end,
        "outputConnectable": self.output_connectable,
        "outputConnectableStart": self.output_connectable_start,
        "outputConnectableEnd": self.output_connectable_end,
        "pane_policy": self.pane_policy,
    }

ReactFlow

Bases: ReactComponent

Interactive flow-based graph visualization and editing component.

ReactFlow is a Panel wrapper around the React Flow library, providing a Python-first interface for creating interactive node-based graphs. It supports dragging, connecting, selecting, and deleting nodes and edges, with automatic synchronization between Python and JavaScript.

The component is ideal for building workflow editors, data pipelines, state machines, mind maps, and other node-based interfaces.

Parameters:

Name Type Description Default
nodes list of dict or Node

List of node dictionaries or :class:Node instances defining the graph nodes. Each node should have at minimum id, position, and type fields. Use :class:NodeSpec or :class:Node for structured node creation.

[]
edges list of dict or Edge

List of edge dictionaries or :class:Edge instances defining connections between nodes. Each edge should have id, source, and target fields. Use :class:EdgeSpec or :class:Edge for structured edge creation.

[]
node_types dict

Dictionary mapping type names to :class:NodeType definitions or dicts. Define custom node types with schemas, ports, and validation.

{}
edge_types dict

Dictionary mapping type names to :class:EdgeType definitions or dicts. Define custom edge types with schemas and validation.

{}
node_editors dict

Dictionary mapping node type names to custom editor classes or functions. Editors must follow the standard signature: editor(data, schema, *, id, type, on_patch).

{}
edge_editors dict

Dictionary mapping edge type names to custom editor classes or functions.

{}
default_node_editor type or callable

Default editor factory used for nodes without a specific editor. Defaults to :class:SchemaEditor.

required
default_edge_editor type or callable

Default editor factory used for edges without a specific editor. Defaults to :class:SchemaEditor.

required
debounce_ms int

Debounce delay in milliseconds when sync_mode='debounce'. Controls how often updates are sent from JavaScript to Python.

150
default_edge_options dict

Default React Flow edge options applied to all edges (e.g., animated, type). See React Flow documentation for available options.

{}
editable bool

Enable interactive editing on the canvas (drag, connect, delete). Set to False for read-only visualization.

True
editor_mode ('toolbar', 'node', 'side')

Where to render node editors:

  • "toolbar": Editors appear in a toolbar above the canvas
  • "node": Editors appear embedded within each node
  • "side": Editors appear in a side panel
"toolbar"
enable_connect bool

Allow users to create new edges by connecting nodes.

True
enable_delete bool

Allow users to delete selected nodes or edges using keyboard shortcuts.

True
enable_multiselect bool

Allow selecting multiple nodes/edges with modifier keys (Shift/Ctrl).

True
max_zoom float

Maximum zoom level the viewport can be zoomed in to.

2
min_zoom float

Minimum zoom level the viewport can be zoomed out to.

0.5
selection dict

Current selection state with lists of selected node and edge IDs. Read-only; updated automatically when selection changes.

{"nodes": [], "edges": []}
show_minimap bool

Show a minimap overlay in the corner for navigation in large graphs.

False
sync_mode ('event', 'debounce')

Synchronization mode for JavaScript to Python updates:

  • "event": Immediate sync on every change
  • "debounce": Batched sync with debounce_ms delay
"event"
validate_on_add bool

Validate node/edge data against schemas when adding via :meth:add_node or :meth:add_edge.

True
validate_on_patch bool

Validate node/edge data against schemas when patching via :meth:patch_node_data or :meth:patch_edge_data.

False
viewport dict

Persisted viewport state with x, y (position) and zoom. Set to restore a specific view on initialization.

required
top_panel list

Panel viewables rendered in a top-center overlay panel.

[]
bottom_panel list

Panel viewables rendered in a bottom-center overlay panel.

[]
left_panel list

Panel viewables rendered in a center-left overlay panel.

[]
right_panel list

Panel viewables rendered in a center-right overlay panel.

[]

Examples:

Create a basic flow graph:

>>> import panel as pn
>>> from panel_reactflow import ReactFlow, NodeSpec, EdgeSpec
>>>
>>> pn.extension()
>>>
>>> nodes = [
...     NodeSpec(id="1", position={"x": 0, "y": 0}, label="Start").to_dict(),
...     NodeSpec(id="2", position={"x": 200, "y": 0}, label="Process").to_dict(),
...     NodeSpec(id="3", position={"x": 400, "y": 0}, label="End").to_dict(),
... ]
>>> edges = [
...     EdgeSpec(id="e1", source="1", target="2").to_dict(),
...     EdgeSpec(id="e2", source="2", target="3").to_dict(),
... ]
>>> flow = ReactFlow(nodes=nodes, edges=edges)
>>> flow.servable()

Define custom node types with schemas:

>>> from panel_reactflow import NodeType
>>> import param
>>>
>>> class FilterParams(param.Parameterized):
...     threshold = param.Number(default=0.5, bounds=(0, 1))
...     operation = param.Selector(default="gt", objects=["gt", "lt", "eq"])
>>>
>>> flow = ReactFlow(
...     node_types={
...         "filter": NodeType(
...             type="filter",
...             label="Filter Node",
...             schema=FilterParams,
...             inputs=["input"],
...             outputs=["output"]
...         )
...     }
... )
>>> flow.add_node(NodeSpec(
...     id="f1",
...     type="filter",
...     position={"x": 100, "y": 100},
...     data={"threshold": 0.7, "operation": "gt"}
... ))

Listen to events:

>>> def on_node_moved(event):
...     print(f"Node {event['node_id']} moved to {event['position']}")
>>>
>>> flow.on("node_moved", on_node_moved)
>>> flow.on("edge_added", lambda e: print(f"Edge added: {e['edge']}"))

Embed Panel viewables in nodes:

>>> nodes = [
...     {
...         "id": "plot1",
...         "position": {"x": 0, "y": 0},
...         "label": "Markdown View",
...         "view": pn.pane.Markdown("# Hello World"),
...         "data": {}
...     }
... ]
>>> flow = ReactFlow(nodes=nodes)

Convert from/to NetworkX:

>>> import networkx as nx
>>> G = nx.DiGraph()
>>> G.add_edge("A", "B", weight=0.5)
>>> G.add_edge("B", "C", weight=0.8)
>>>
>>> flow = ReactFlow.from_networkx(G)
>>>
>>> # Make modifications...
>>>
>>> G_modified = flow.to_networkx()
See Also

Node : Base class for object-oriented nodes NodeSpec : Builder for node dictionaries Edge : Base class for object-oriented edges EdgeSpec : Builder for edge dictionaries NodeType : Define custom node types with schemas EdgeType : Define custom edge types with schemas Editor : Base class for custom editors SchemaEditor : Smart schema-driven editor (default) JsonEditor : Simple JSON editor

Notes

The component requires the Panel extension to be loaded. Make sure to call pn.extension() before using ReactFlow.

For optimal performance with large graphs (>100 nodes), consider: - Using sync_mode='debounce' with appropriate debounce_ms - Setting validate_on_patch=False if validation is expensive - Disabling show_minimap if not needed

Source code in src/panel_reactflow/base.py
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
class ReactFlow(ReactComponent):
    """Interactive flow-based graph visualization and editing component.

    ReactFlow is a Panel wrapper around the React Flow library, providing
    a Python-first interface for creating interactive node-based graphs.
    It supports dragging, connecting, selecting, and deleting nodes and edges,
    with automatic synchronization between Python and JavaScript.

    The component is ideal for building workflow editors, data pipelines,
    state machines, mind maps, and other node-based interfaces.

    Parameters
    ----------
    nodes : list of dict or Node, default []
        List of node dictionaries or :class:`Node` instances defining the
        graph nodes. Each node should have at minimum ``id``, ``position``,
        and ``type`` fields. Use :class:`NodeSpec` or :class:`Node` for
        structured node creation.
    edges : list of dict or Edge, default []
        List of edge dictionaries or :class:`Edge` instances defining
        connections between nodes. Each edge should have ``id``, ``source``,
        and ``target`` fields. Use :class:`EdgeSpec` or :class:`Edge` for
        structured edge creation.
    node_types : dict, default {}
        Dictionary mapping type names to :class:`NodeType` definitions or dicts.
        Define custom node types with schemas, ports, and validation.
    edge_types : dict, default {}
        Dictionary mapping type names to :class:`EdgeType` definitions or dicts.
        Define custom edge types with schemas and validation.
    node_editors : dict, default {}
        Dictionary mapping node type names to custom editor classes or functions.
        Editors must follow the standard signature:
        ``editor(data, schema, *, id, type, on_patch)``.
    edge_editors : dict, default {}
        Dictionary mapping edge type names to custom editor classes or functions.
    default_node_editor : type or callable, optional
        Default editor factory used for nodes without a specific editor.
        Defaults to :class:`SchemaEditor`.
    default_edge_editor : type or callable, optional
        Default editor factory used for edges without a specific editor.
        Defaults to :class:`SchemaEditor`.
    debounce_ms : int, default 150
        Debounce delay in milliseconds when ``sync_mode='debounce'``.
        Controls how often updates are sent from JavaScript to Python.
    default_edge_options : dict, default {}
        Default React Flow edge options applied to all edges (e.g., ``animated``,
        ``type``). See React Flow documentation for available options.
    editable : bool, default True
        Enable interactive editing on the canvas (drag, connect, delete).
        Set to ``False`` for read-only visualization.
    editor_mode : {"toolbar", "node", "side"}, default "toolbar"
        Where to render node editors:

        - ``"toolbar"``: Editors appear in a toolbar above the canvas
        - ``"node"``: Editors appear embedded within each node
        - ``"side"``: Editors appear in a side panel
    enable_connect : bool, default True
        Allow users to create new edges by connecting nodes.
    enable_delete : bool, default True
        Allow users to delete selected nodes or edges using keyboard shortcuts.
    enable_multiselect : bool, default True
        Allow selecting multiple nodes/edges with modifier keys (Shift/Ctrl).
    max_zoom : float, default 2
        Maximum zoom level the viewport can be zoomed in to.
    min_zoom : float, default 0.5
        Minimum zoom level the viewport can be zoomed out to.
    selection : dict, default {"nodes": [], "edges": []}
        Current selection state with lists of selected node and edge IDs.
        Read-only; updated automatically when selection changes.
    show_minimap : bool, default False
        Show a minimap overlay in the corner for navigation in large graphs.
    sync_mode : {"event", "debounce"}, default "event"
        Synchronization mode for JavaScript to Python updates:

        - ``"event"``: Immediate sync on every change
        - ``"debounce"``: Batched sync with ``debounce_ms`` delay
    validate_on_add : bool, default True
        Validate node/edge data against schemas when adding via
        :meth:`add_node` or :meth:`add_edge`.
    validate_on_patch : bool, default False
        Validate node/edge data against schemas when patching via
        :meth:`patch_node_data` or :meth:`patch_edge_data`.
    viewport : dict, optional
        Persisted viewport state with ``x``, ``y`` (position) and ``zoom``.
        Set to restore a specific view on initialization.
    top_panel : list, default []
        Panel viewables rendered in a top-center overlay panel.
    bottom_panel : list, default []
        Panel viewables rendered in a bottom-center overlay panel.
    left_panel : list, default []
        Panel viewables rendered in a center-left overlay panel.
    right_panel : list, default []
        Panel viewables rendered in a center-right overlay panel.

    Examples
    --------
    Create a basic flow graph:

    >>> import panel as pn
    >>> from panel_reactflow import ReactFlow, NodeSpec, EdgeSpec
    >>>
    >>> pn.extension()
    >>>
    >>> nodes = [
    ...     NodeSpec(id="1", position={"x": 0, "y": 0}, label="Start").to_dict(),
    ...     NodeSpec(id="2", position={"x": 200, "y": 0}, label="Process").to_dict(),
    ...     NodeSpec(id="3", position={"x": 400, "y": 0}, label="End").to_dict(),
    ... ]
    >>> edges = [
    ...     EdgeSpec(id="e1", source="1", target="2").to_dict(),
    ...     EdgeSpec(id="e2", source="2", target="3").to_dict(),
    ... ]
    >>> flow = ReactFlow(nodes=nodes, edges=edges)
    >>> flow.servable()

    Define custom node types with schemas:

    >>> from panel_reactflow import NodeType
    >>> import param
    >>>
    >>> class FilterParams(param.Parameterized):
    ...     threshold = param.Number(default=0.5, bounds=(0, 1))
    ...     operation = param.Selector(default="gt", objects=["gt", "lt", "eq"])
    >>>
    >>> flow = ReactFlow(
    ...     node_types={
    ...         "filter": NodeType(
    ...             type="filter",
    ...             label="Filter Node",
    ...             schema=FilterParams,
    ...             inputs=["input"],
    ...             outputs=["output"]
    ...         )
    ...     }
    ... )
    >>> flow.add_node(NodeSpec(
    ...     id="f1",
    ...     type="filter",
    ...     position={"x": 100, "y": 100},
    ...     data={"threshold": 0.7, "operation": "gt"}
    ... ))

    Listen to events:

    >>> def on_node_moved(event):
    ...     print(f"Node {event['node_id']} moved to {event['position']}")
    >>>
    >>> flow.on("node_moved", on_node_moved)
    >>> flow.on("edge_added", lambda e: print(f"Edge added: {e['edge']}"))

    Embed Panel viewables in nodes:

    >>> nodes = [
    ...     {
    ...         "id": "plot1",
    ...         "position": {"x": 0, "y": 0},
    ...         "label": "Markdown View",
    ...         "view": pn.pane.Markdown("# Hello World"),
    ...         "data": {}
    ...     }
    ... ]
    >>> flow = ReactFlow(nodes=nodes)

    Convert from/to NetworkX:

    >>> import networkx as nx
    >>> G = nx.DiGraph()
    >>> G.add_edge("A", "B", weight=0.5)
    >>> G.add_edge("B", "C", weight=0.8)
    >>>
    >>> flow = ReactFlow.from_networkx(G)
    >>>
    >>> # Make modifications...
    >>>
    >>> G_modified = flow.to_networkx()

    See Also
    --------
    Node : Base class for object-oriented nodes
    NodeSpec : Builder for node dictionaries
    Edge : Base class for object-oriented edges
    EdgeSpec : Builder for edge dictionaries
    NodeType : Define custom node types with schemas
    EdgeType : Define custom edge types with schemas
    Editor : Base class for custom editors
    SchemaEditor : Smart schema-driven editor (default)
    JsonEditor : Simple JSON editor

    Notes
    -----
    The component requires the Panel extension to be loaded. Make sure to
    call ``pn.extension()`` before using ReactFlow.

    For optimal performance with large graphs (>100 nodes), consider:
    - Using ``sync_mode='debounce'`` with appropriate ``debounce_ms``
    - Setting ``validate_on_patch=False`` if validation is expensive
    - Disabling ``show_minimap`` if not needed
    """

    nodes = param.List(default=[], doc="Canonical list of node dictionaries or Node instances.")
    edges = param.List(default=[], doc="Canonical list of edge dictionaries or Edge instances.")
    node_types = param.Dict(default={}, doc="Node type descriptors keyed by type name.")
    edge_types = param.Dict(default={}, doc="Edge type descriptors keyed by type name.")
    connection_validation = param.Dict(default={}, doc="Opt-in frontend connection policies (direction, cycles, duplicates, types, capacity).")
    has_connection_validators = param.Boolean(default=False, doc="Whether Python connection validators are registered.")

    node_editors = param.Dict(default={}, doc="Node editor factories keyed by type name.", precedence=-1)
    edge_editors = param.Dict(default={}, doc="Edge editor factories keyed by type name.", precedence=-1)
    default_node_editor = param.Parameter(default=None, doc="Default node editor factory.", precedence=-1)
    default_edge_editor = param.Parameter(default=None, doc="Default edge editor factory.", precedence=-1)

    color_mode = param.ObjectSelector(default=None, objects=["light", "dark"], doc="Color mode for the graph.")

    allow_edge_loops = param.Boolean(default=False, doc="Allow to have edge loops in the graph (can lead to update infinite loops).")

    display_side_bar = param.Boolean(default=True, doc="Display the side bar to drag and drop new nodes.")

    debounce_ms = param.Integer(default=150, bounds=(0, None), doc="Debounce delay in milliseconds when sync_mode='debounce'.")

    default_edge_options = param.Dict(default={}, doc="Default React Flow edge options.")

    editable = param.Boolean(default=True, doc="Enable interactive editing on the canvas.")

    editor_mode = param.ObjectSelector(
        default="toolbar",
        objects=["toolbar", "node", "side"],
        doc="Where to render node editors: toolbar, node, or side panel.",
    )

    enable_connect = param.Boolean(default=True, doc="Allow connecting nodes to create edges.")

    enable_delete = param.Boolean(default=True, doc="Allow deleting selected nodes or edges.")

    enable_multiselect = param.Boolean(default=True, doc="Allow multiselect with modifier key.")

    error_recovery = param.ObjectSelector(
        default="auto",
        objects=["auto", "manual", "off"],
        doc=(
            "How to handle a rendering error in the graph view. 'auto' silently "
            "remounts the canvas, then retries in safe mode, before showing a "
            "recovery panel; 'manual' shows the recovery panel immediately; "
            "'off' disables the error boundary so exceptions propagate."
        ),
    )

    max_zoom = param.Number(default=2, bounds=(0, None), inclusive_bounds=(False, True), doc="Maximum zoom level of the viewport.")

    min_zoom = param.Number(default=0.5, bounds=(0, None), inclusive_bounds=(False, True), doc="Minimum zoom level of the viewport.")

    selection = param.Dict(default={"nodes": [], "edges": []}, doc="Derived selection state for node and edge ids.")

    show_minimap = param.Boolean(default=False, doc="Show the minimap overlay.")

    sync_mode = param.ObjectSelector(default="event", objects=["event", "debounce"], doc="Sync mode for JS->Python updates.")

    validate_on_add = param.Boolean(default=True, doc="Validate data against schema on add_node/add_edge.")
    validate_on_patch = param.Boolean(default=False, doc="Validate data against schema on patch_node_data/patch_edge_data.")

    viewport = param.Dict(default=None, allow_None=True, doc="Optional persisted viewport state.")

    drop_types = param.List(
        default=[],
        item_type=str,
        doc="""
        MIME types accepted when data is dropped onto the canvas, e.g. the
        ``drag_type`` of a draggable ``panel_material_ui.MenuList``. Include
        ``"Files"`` to accept files dragged in from the operating system.
        Each accepted drop emits a ``"drop"`` event; drops of other types are
        ignored, as are all drops while ``editable`` is False.""",
    )

    popup_trigger = param.ObjectSelector(
        default="click",
        objects=["click", "hover", "none"],
        doc="Whether port and edge inspection events are triggered on click, hover, or not automatically.",
    )

    popup_hover_delay = param.Integer(
        default=500,
        bounds=(0, None),
        doc="Delay in milliseconds before a hover inspection event is emitted.",
    )

    top_panel = Children(default=[], doc="Children rendered in a top-center panel.")
    bottom_panel = Children(default=[], doc="Children rendered in a bottom-center panel.")
    left_panel = Children(default=[], doc="Children rendered in a center-left panel.")
    right_panel = Children(default=[], doc="Children rendered in a center-right panel.")

    # Internal view parameters
    _node_editors = param.Dict(default={}, doc="Per-node editors.", precedence=-1)
    _node_editor_views = Children(default=[], doc="Node editor views (one per node, same order).")
    _edge_editors = param.Dict(default={}, doc="Per-edge editors.", precedence=-1)
    _selected_editor = Child(doc="Active editor for the selected node/edge in side mode.")
    _context_menu = Child(doc="Context menu component rendered on node right-click.")
    _context_menu_position = param.Dict(default=None, allow_None=True, doc="Screen position for the context menu overlay.")
    _value_popup = Child(doc="Popup component rendered on handle/edge click, e.g. via show_popup().")
    _value_popup_position = param.Dict(default=None, allow_None=True, doc="Screen position for the value popup overlay.")
    _views = Children(default=[], doc="Panel viewables rendered inside nodes via view_idx.")
    _node_update_count = param.Integer(default=0, doc="Monotonic counter for normalized node updates.")

    _bundle = DIST_PATH / "panel-reactflow.bundle.js"
    _esm = Path(__file__).parent / "models" / "reactflow.jsx"
    _importmap = {
        "imports": {
            "@xyflow/react": "https://esm.sh/@xyflow/react@12.8.3",
            "@tisoap/react-flow-smart-edge": "https://esm.sh/@tisoap/react-flow-smart-edge",
        }
    }
    _stylesheets = [DIST_PATH / "panel-reactflow.bundle.css", DIST_PATH / "css" / "reactflow.css"]
    _render_policy = "manual"

    def __init__(self, **params: Any):
        if "color_mode" not in params:
            params["color_mode"] = "dark" if pn.config.theme == "dark" else "light"
        self._node_ids: list[str] = []
        self._edge_ids: list[str] = []
        self._attached_node_instances: dict[int, Node] = {}
        self._attached_edge_instances: dict[int, Edge] = {}
        self._node_data_param_watchers: dict[str, tuple[Node, list[Any]]] = {}
        self._edge_data_param_watchers: dict[str, tuple[Edge, list[Any]]] = {}
        self._suppress_prop_sync = False
        self._node_view_cache: dict[str, tuple[int, Any]] = {}
        # Normalize type specs before parent init so the frontend receives
        # JSON-serializable descriptors from the start.
        if "node_types" in params:
            params["node_types"] = _coerce_spec_map(params["node_types"])
        if "edge_types" in params:
            params["edge_types"] = _coerce_spec_map(params["edge_types"], edge=True)
        # Normalize nodes and edges to ensure NodeSpec/EdgeSpec are converted.
        if "nodes" in params:
            params["nodes"] = [ReactFlow._coerce_node(node) for node in params["nodes"]]
        if "edges" in params:
            params["edges"] = [ReactFlow._coerce_edge(edge) for edge in params["edges"]]
        super().__init__(**params)
        self._event_handlers: dict[str, list[Callable]] = {"*": []}
        self._connection_validators: list[Callable] = []
        self.param.watch(self._sync_instance_flow_refs, ["nodes", "edges"])
        self.param.watch(self._normalize_nodes, ["nodes"])
        self.param.watch(self._normalize_edges, ["edges"])
        self.param.watch(self._update_instance_data_param_watchers, ["nodes", "edges"])
        self.param.watch(self._update_selection_from_graph, ["nodes", "edges"])
        self.param.watch(self._normalize_specs, ["node_types", "edge_types"])
        self.param.watch(
            self._update_node_editors,
            ["nodes", "editor_mode", "node_editors", "default_node_editor"],
        )
        self.param.watch(
            self._update_edge_editors,
            ["edges", "edge_editors", "default_edge_editor"],
        )
        self.param.watch(
            self._update_selected_editor,
            ["selection", "editor_mode", "nodes", "edges"],
        )
        self.param.watch(self._update_views, ["nodes"])
        self._sync_instance_flow_refs()
        self._update_node_editors()
        self._update_edge_editors()
        self._update_selected_editor()
        self._update_instance_data_param_watchers()

    @classmethod
    def _esm_path(cls, compiled: bool | Literal["compiling"] = True) -> os.PathLike | None:
        return super()._esm_path(compiled or True)

    @classmethod
    def _render_esm(cls, compiled: bool | Literal["compiling"] = True, server: bool = False):
        esm_path = cls._esm_path(compiled=compiled)
        if compiled != "compiling" and server:
            # Generate relative path to handle apps served on subpaths
            esm = ("" if state.rel_path else "./") + cls._component_resource_path(esm_path, compiled)
            if config.autoreload:
                esm_hash = hashlib.sha256(str(esm_path.stat().st_mtime).encode("utf-8")).hexdigest()
            else:
                esm_hash = hashlib.md5(__version__.encode("utf-8")).hexdigest()
            esm += f"?{esm_hash}"
        else:
            esm = esm_path.read_text(encoding="utf-8")
        return esm

    @classproperty
    def _bundle_path(cls) -> os.PathLike | None:
        return cls._bundle

    def _get_node_schema(self, node_type: str) -> dict[str, Any] | None:
        """Return the normalized JSON Schema for *node_type*, or ``None``."""
        type_spec = self.node_types.get(node_type)
        if type_spec is not None and type_spec.get("schema") is not None:
            return type_spec.get("schema")
        for node in self.nodes:
            if isinstance(node, Node) and node.type == node_type:
                schema = node._data_schema()
                if schema.get("properties"):
                    return schema
                break
        return None

    def _get_edge_schema(self, edge_type: str) -> dict[str, Any] | None:
        """Return the normalized JSON Schema for *edge_type*, or ``None``."""
        type_spec = self.edge_types.get(edge_type)
        if type_spec is not None and type_spec.get("schema") is not None:
            return type_spec.get("schema")
        for edge in self.edges:
            if isinstance(edge, Edge) and (edge.type or "") == edge_type:
                schema = edge._data_schema()
                if schema.get("properties"):
                    return schema
                break
        return None

    def _create_editor(
        self,
        factory: Any,
        item_id: str,
        data: dict,
        schema: dict | None,
        item_type: str,
        *,
        patch_fn: Callable[[str, dict], None],
    ) -> Any:
        """Instantiate an editor from *factory*.

        All editors (classes and plain callables) receive the unified
        signature ``(data, schema, *, id, type, on_patch)``.

        *patch_fn* is the method to call when data changes –
        ``patch_node_data`` for nodes, ``patch_edge_data`` for edges.
        """

        def on_patch(patch: dict) -> None:
            patch_fn(item_id, patch)

        return factory(data, schema, id=item_id, type=item_type, on_patch=on_patch)

    @staticmethod
    def _node_is_instance(node: Any) -> bool:
        return isinstance(node, Node)

    @staticmethod
    def _node_id(node: dict[str, Any] | Node) -> str | None:
        return node.id if isinstance(node, Node) else node.get("id")

    @staticmethod
    def _node_type(node: dict[str, Any] | Node) -> str:
        if isinstance(node, Node):
            return node.type or "panel"
        return node.get("type", "panel")

    @staticmethod
    def _node_data(node: dict[str, Any] | Node) -> dict[str, Any]:
        if isinstance(node, Node):
            return dict(node.data or {})
        return dict(node.get("data", {}))

    def _node_view(self, node: dict[str, Any] | Node) -> Any | None:
        if isinstance(node, Node):
            node_id = self._node_id(node)
            node_ref = id(node)
            if node_id is not None:
                cached = self._node_view_cache.get(node_id)
                if cached is not None and cached[0] == node_ref:
                    return cached[1]
            view = node.__panel__()
            if node_id is not None and view is not None:
                self._node_view_cache[node_id] = (node_ref, view)
            return view
        return node.get("view", None)

    @staticmethod
    def _node_set_position(node: dict[str, Any] | Node, position: dict[str, Any]) -> None:
        if isinstance(node, Node):
            node.position = dict(position)
        else:
            node["position"] = position

    @staticmethod
    def _node_set_selected(node: dict[str, Any] | Node, selected: bool) -> None:
        if isinstance(node, Node):
            node.selected = selected
        else:
            node["selected"] = selected

    @staticmethod
    def _node_set_data(node: dict[str, Any] | Node, data: dict[str, Any]) -> None:
        if isinstance(node, Node):
            node.data = dict(data)
        else:
            node["data"] = data

    @staticmethod
    def _node_payload(node: dict[str, Any] | NodeSpec | Node) -> dict[str, Any]:
        if isinstance(node, Node):
            return node.to_dict()
        if isinstance(node, NodeSpec):
            return node.to_dict()
        return dict(node)

    @staticmethod
    def _edge_id(edge: dict[str, Any] | Edge) -> str | None:
        return edge.id if isinstance(edge, Edge) else edge.get("id")

    @staticmethod
    def _edge_type(edge: dict[str, Any] | Edge) -> str:
        if isinstance(edge, Edge):
            return edge.type or ""
        return edge.get("type", "")

    @staticmethod
    def _edge_data(edge: dict[str, Any] | Edge) -> dict[str, Any]:
        if isinstance(edge, Edge):
            return dict(edge.data or {})
        return dict(edge.get("data", {}))

    @staticmethod
    def _edge_set_selected(edge: dict[str, Any] | Edge, selected: bool) -> None:
        if isinstance(edge, Edge):
            edge.selected = selected
        else:
            edge["selected"] = selected

    @staticmethod
    def _edge_set_data(edge: dict[str, Any] | Edge, data: dict[str, Any]) -> None:
        if isinstance(edge, Edge):
            edge.data = dict(data)
        else:
            edge["data"] = data

    @staticmethod
    def _edge_payload(edge: dict[str, Any] | EdgeSpec | Edge) -> dict[str, Any]:
        if isinstance(edge, Edge):
            return edge.to_dict()
        if isinstance(edge, EdgeSpec):
            return edge.to_dict()
        return dict(edge)

    def _get_node_instance(self, node_id: str) -> Node | None:
        for node in self.nodes:
            if isinstance(node, Node) and node.id == node_id:
                return node
        return None

    def _get_edge_instance(self, edge_id: str) -> Edge | None:
        for edge in self.edges:
            if isinstance(edge, Edge) and edge.id == edge_id:
                return edge
        return None

    @staticmethod
    def _sync_node_data_params_from_data(node: Node) -> None:
        for name in node._data_param_names():
            if name in (node.data or {}):
                setattr(node, name, node.data[name])

    @staticmethod
    def _sync_edge_data_params_from_data(edge: Edge) -> None:
        for name in edge._data_param_names():
            if name in (edge.data or {}):
                setattr(edge, name, edge.data[name])

    @staticmethod
    def _teardown_param_watcher(watcher_store: dict[str, tuple[Any, list[Any]]], item_id: str) -> None:
        record = watcher_store.pop(item_id, None)
        if record is None:
            return
        item, watchers = record
        for watcher in watchers:
            try:
                item.param.unwatch(watcher)
            except Exception:
                pass

    def _update_instance_data_param_watchers(self, *_: param.parameterized.Event) -> None:
        self._update_node_data_param_watchers()
        self._update_edge_data_param_watchers()

    def _sync_instance_flow_refs(self, *_: param.parameterized.Event) -> None:
        current_nodes = {id(node): node for node in self.nodes if isinstance(node, Node)}
        for node_ref, old_node in list(self._attached_node_instances.items()):
            if node_ref not in current_nodes:
                old_node.flow = None
        for node in current_nodes.values():
            if node.flow is not self:
                node.flow = self
        self._attached_node_instances = current_nodes

        current_edges = {id(edge): edge for edge in self.edges if isinstance(edge, Edge)}
        for edge_ref, old_edge in list(self._attached_edge_instances.items()):
            if edge_ref not in current_edges:
                old_edge.flow = None
        for edge in current_edges.values():
            if edge.flow is not self:
                edge.flow = self
        self._attached_edge_instances = current_edges

    def _update_node_data_param_watchers(self) -> None:
        current_nodes = {node.id: node for node in self.nodes if isinstance(node, Node) and node.id}
        self._update_param_watchers(
            current_items=current_nodes,
            watcher_store=self._node_data_param_watchers,
            get_instance=self._get_node_instance,
            data_patch_fn=self.patch_node_data,
            prop_patch_fn=self.patch_node_props,
        )

    def _update_edge_data_param_watchers(self) -> None:
        current_edges = {edge.id: edge for edge in self.edges if isinstance(edge, Edge) and edge.id}
        self._update_param_watchers(
            current_items=current_edges,
            watcher_store=self._edge_data_param_watchers,
            get_instance=self._get_edge_instance,
            data_patch_fn=self.patch_edge_data,
            prop_patch_fn=self.patch_edge_props,
        )

    def _update_param_watchers(
        self,
        *,
        current_items: dict[str, Node | Edge],
        watcher_store: dict[str, tuple[Node | Edge, list[Any]]],
        get_instance: Callable[[str], Node | Edge | None],
        data_patch_fn: Callable[[str, dict[str, Any]], None],
        prop_patch_fn: Callable[[str, dict[str, Any]], None],
    ) -> None:
        """Keep param watchers for a set of live ``Node``/``Edge`` instances in sync.

        Watches both the subclass-defined data params
        (``item._data_param_names()``), which are patched into ``data``, and the
        presentational base params (``item._synced_props``, e.g.
        ``label``/``style``), which are patched as top-level React Flow fields,
        so that assigning either on a live instance reaches the frontend.
        """
        for item_id, (watched_item, _) in list(watcher_store.items()):
            current = current_items.get(item_id)
            if current is None or current is not watched_item:
                self._teardown_param_watcher(watcher_store, item_id)
        for item_id, item in current_items.items():
            if item_id in watcher_store:
                continue
            watchers = [
                item.param.watch(
                    lambda event, _id=item_id, _name=name, _item=item: self._on_data_param_change(get_instance, data_patch_fn, _id, _name, _item, event),
                    name,
                )
                for name in item._data_param_names()
            ]
            # A single watcher for every property, so that a batched
            # ``param.update`` coalesces into one patch message.
            watchers.append(
                item.param.watch(
                    lambda *events, _id=item_id, _item=item: self._on_prop_param_change(get_instance, prop_patch_fn, _id, _item, *events),
                    list(item._synced_props),
                )
            )
            watcher_store[item_id] = (item, watchers)

    @staticmethod
    def _on_data_param_change(
        get_instance: Callable[[str], Node | Edge | None],
        patch_fn: Callable[[str, dict[str, Any]], None],
        item_id: str,
        param_name: str,
        item: Node | Edge,
        event: param.parameterized.Event,
    ) -> None:
        if get_instance(item_id) is not item:
            return
        # Guards against the redundant re-send ``_sync_*_data_params_from_data``
        # would otherwise cause.
        if (item.data or {}).get(param_name) == event.new:
            return
        patch_fn(item_id, {param_name: event.new})

    def _on_prop_param_change(
        self,
        get_instance: Callable[[str], Node | Edge | None],
        patch_fn: Callable[[str, dict[str, Any]], None],
        item_id: str,
        item: Node | Edge,
        *events: param.parameterized.Event,
    ) -> None:
        if self._suppress_prop_sync:
            return
        if get_instance(item_id) is not item:
            return
        patch_fn(item_id, {event.name: event.new for event in events})

    @contextmanager
    def _suppressed_prop_sync(self):
        """Apply values that came from (or are already in) the browser.

        Prevents the ``Node``/``Edge`` property watchers from echoing a patch
        back to the frontend for a value the frontend already holds.
        """
        previous = self._suppress_prop_sync
        self._suppress_prop_sync = True
        try:
            yield
        finally:
            self._suppress_prop_sync = previous

    @staticmethod
    def _invoke_node_callback(callback: Callable, payload: dict[str, Any], flow: "ReactFlow") -> None:
        if len(inspect.signature(callback).parameters) == 2:
            cb = partial(callback, payload, flow)
        else:
            cb = partial(callback, payload)
        # schedule=False: the outer _process_event already forced this whole
        # message-handling pass onto the doc's own callback (schedule=False),
        # so 'auto' scheduling here would see the doc as still locked and
        # defer to the next tick. That breaks Child-param updates (e.g. via
        # show_popup) made from inside a hook, since the model reconciliation
        # that turns a Viewable into its Bokeh model expects to run in the
        # same pass as the triggering event.
        pn.state.execute(cb, schedule=False)

    def _invoke_node_hook(self, node: Node, hook_name: str, payload: dict[str, Any]) -> None:
        hook = getattr(node, hook_name, None)
        if callable(hook):
            self._invoke_node_callback(hook, payload, self)

    def _invoke_edge_hook(self, edge: Edge, hook_name: str, payload: dict[str, Any]) -> None:
        hook = getattr(edge, hook_name, None)
        if callable(hook):
            self._invoke_node_callback(hook, payload, self)

    def _dispatch_node_hooks(self, event_type: str, payload: dict[str, Any]) -> None:
        node_ids: list[str] = []
        if event_type == "node_added":
            node_payload = payload.get("node", {})
            if isinstance(node_payload, dict) and node_payload.get("id"):
                node_ids = [node_payload["id"]]
        elif event_type in ("node_moved", "node_clicked", "node_data_changed", "node_props_changed"):
            node_id = payload.get("node_id")
            if node_id:
                node_ids = [node_id]
        elif event_type == "selection_changed":
            node_ids = list(payload.get("nodes") or [])
        elif event_type == "sync":
            node_ids = [node.id for node in self.nodes if isinstance(node, Node)]

        hook_map = {
            "node_added": "on_add",
            "node_moved": "on_move",
            "node_clicked": "on_click",
            "node_data_changed": "on_data_change",
            "node_props_changed": "on_props_change",
            "selection_changed": "on_selection_changed",
            "sync": "on_sync",
        }
        hook_name = hook_map.get(event_type)
        for node_id in node_ids:
            node = self._get_node_instance(node_id)
            if node is None:
                continue
            if hook_name is not None:
                self._invoke_node_hook(node, hook_name, payload)
            self._invoke_node_hook(node, "on_event", payload)

    def _dispatch_edge_hooks(self, event_type: str, payload: dict[str, Any]) -> None:
        edge_ids: list[str] = []
        if event_type == "edge_added":
            edge_payload = payload.get("edge", {})
            if isinstance(edge_payload, dict) and edge_payload.get("id"):
                edge_ids = [edge_payload["id"]]
        elif event_type in ("edge_deleted", "edge_data_changed", "edge_props_changed"):
            edge_id = payload.get("edge_id")
            if edge_id:
                edge_ids = [edge_id]
        elif event_type == "selection_changed":
            edge_ids = list(payload.get("edges") or [])
        elif event_type == "sync":
            edge_ids = [edge.id for edge in self.edges if isinstance(edge, Edge)]

        hook_map = {
            "edge_added": "on_add",
            "edge_deleted": "on_delete",
            "edge_data_changed": "on_data_change",
            "edge_props_changed": "on_props_change",
            "selection_changed": "on_selection_changed",
            "sync": "on_sync",
        }
        hook_name = hook_map.get(event_type)
        for edge_id in edge_ids:
            edge = self._get_edge_instance(edge_id)
            if edge is None:
                continue
            if hook_name is not None:
                self._invoke_edge_hook(edge, hook_name, payload)
            self._invoke_edge_hook(edge, "on_event", payload)

    def _update_node_editors(self, *events: tuple[param.parameterized.Event]) -> None:
        node_ids = [self._node_id(node) for node in self.nodes]
        node_ids = [node_id for node_id in node_ids if node_id is not None]
        config_changed = any(event.name in ("editor_mode", "node_editors", "default_node_editor") for event in events)
        if node_ids == self._node_ids and not config_changed:
            return
        self._node_ids = node_ids

        editors = {}
        for node in self.nodes:
            node_id = self._node_id(node)
            if node_id is None:
                continue
            if node_id in self._node_editors and not config_changed:
                editors[node_id] = self._node_editors[node_id]
                continue
            node_type = self._node_type(node)
            editor_factory = None
            if isinstance(node, Node) and type(node).editor is not Node.editor:
                editor_factory = node.editor
            if editor_factory is None:
                editor_factory = self.node_editors.get(node_type) or self.default_node_editor or SchemaEditor
            schema = self._get_node_schema(node_type)
            data = self._node_data(node)
            if callable(editor_factory):
                editor = self._create_editor(
                    editor_factory,
                    node_id,
                    data,
                    schema,
                    node_type,
                    patch_fn=self.patch_node_data,
                )
            else:
                editor = editor_factory
            editors[node_id] = editor
        self._node_editors = editors
        self.param.trigger("_node_editor_views")

    def _update_edge_editors(self, *events: tuple[param.parameterized.Event]) -> None:
        edge_ids = [self._edge_id(edge) for edge in self.edges]
        edge_ids = [edge_id for edge_id in edge_ids if edge_id is not None]
        config_changed = any(event.name in ("edge_editors", "default_edge_editor") for event in events)
        if edge_ids == self._edge_ids and not config_changed:
            return
        self._edge_ids = edge_ids

        editors = {}
        for edge in self.edges:
            edge_id = self._edge_id(edge)
            if edge_id is None:
                continue
            if edge_id in self._edge_editors and not config_changed:
                editors[edge_id] = self._edge_editors[edge_id]
                continue
            edge_type = self._edge_type(edge)
            editor_factory = None
            if isinstance(edge, Edge) and type(edge).editor is not Edge.editor:
                editor_factory = edge.editor
            if editor_factory is None:
                editor_factory = self.edge_editors.get(edge_type) or self.default_edge_editor or SchemaEditor
            schema = self._get_edge_schema(edge_type) if edge_type else None
            data = self._edge_data(edge)
            if callable(editor_factory):
                editor = self._create_editor(
                    editor_factory,
                    edge_id,
                    data,
                    schema,
                    edge_type,
                    patch_fn=self.patch_edge_data,
                )
            else:
                editor = editor_factory
            editors[edge_id] = editor
        self._edge_editors = editors

    def _update_selected_editor(self, *events: tuple[param.parameterized.Event]) -> None:
        selected_nodes = self.selection.get("nodes", [])
        selected_edges = self.selection.get("edges", [])
        editor = None
        if selected_nodes and self.editor_mode == "side":
            editor = self._node_editors.get(selected_nodes[0])
        elif selected_edges and not selected_nodes:
            editor = self._edge_editors.get(selected_edges[0])
        if editor is not None:
            view = self._resolve_editor_view(editor)
        else:
            view = None
        self._selected_editor = view

    @staticmethod
    def _resolve_editor_view(editor: Any) -> Any:
        """Return a Panel viewable from an editor (class or plain object)."""
        if editor is None:
            return pn.pane.HTML("")
        if hasattr(editor, "__panel__"):
            return editor.__panel__()
        return pn.panel(editor)

    def _get_children(self, data_model, doc, root, parent, comm) -> tuple[dict[str, list[UIElement] | UIElement | None], list[UIElement]]:
        views = []
        for node in self.nodes:
            view = self._node_view(node)
            if view is not None:
                views.append(self._resolve_editor_view(view))

        children: dict[str, list[UIElement] | UIElement | None] = {}
        old_models: list[UIElement] = []
        views, view_models = self._get_child_model(views, doc, root, parent, comm)
        self._patch_views(view_models)
        children["_views"] = views
        old_models += view_models

        if self.editor_mode == "side":
            children["_node_editor_views"] = []
        else:
            node_editors = [self._resolve_editor_view(self._node_editors.get(self._node_id(node))) for node in self.nodes]
            editor_models, editor_old = self._get_child_model(node_editors, doc, root, parent, comm)
            children["_node_editor_views"] = editor_models
            old_models += editor_old

        for name in ("top_panel", "bottom_panel", "left_panel", "right_panel", "_context_menu", "_value_popup", "_selected_editor"):
            panels = getattr(self, name, None)
            if panels is None:
                children[name] = None
            elif isinstance(panels, list):
                if panels:
                    panel_models, panel_old = self._get_child_model(panels, doc, root, parent, comm)
                    children[name] = panel_models
                    old_models += panel_old
                else:
                    children[name] = []
            else:
                panel_models, panel_old = self._get_child_model([panels], doc, root, parent, comm)
                children[name] = panel_models[0] if panel_models else None
                old_models += panel_old
        return children, old_models

    def _patch_views(self, view_models: list[UIElement]) -> None:
        for model in view_models:
            for fig in model.select({"type": figure}):
                if BK_FIGURE_CSS not in fig.stylesheets:
                    fig.stylesheets = fig.stylesheets + [BK_FIGURE_CSS]

    def _update_views(self, *events: tuple[param.parameterized.Event]) -> None:
        event = events[0] if events else None
        nodes = event.new if event is not None else self.nodes
        normalized = [self._coerce_node(node) for node in nodes]
        node_ids = {self._node_id(node) for node in normalized}
        self._node_view_cache = {node_id: cached for node_id, cached in self._node_view_cache.items() if node_id in node_ids}
        is_normalized = not any(n1 is not n2 for n1, n2 in zip(normalized, nodes, strict=False))
        if not is_normalized:
            return
        self.param.trigger("_views")
        self._node_update_count += 1

    def _process_param_change(self, params):
        params = super()._process_param_change(params)
        if "nodes" in params:
            nodes = []
            view_idx = 0
            for node in params["nodes"]:
                node = self._node_payload(node)
                view = node.pop("view", None)
                data = dict(node.get("data", {}))
                if view is not None:
                    data["view_idx"] = view_idx
                    view_idx += 1
                node["data"] = data
                nodes.append(node)
            params["nodes"] = nodes
        if "edges" in params:
            params["edges"] = [self._edge_payload(edge) for edge in params["edges"]]
        # Panel syncs a new value before `_normalize_specs` replaces it, so
        # schema classes must be coerced here to stay out of the payload.
        if "node_types" in params:
            params["node_types"] = _coerce_spec_map(params["node_types"])
        if "edge_types" in params:
            params["edge_types"] = _coerce_spec_map(params["edge_types"], edge=True)
        # Pop Python-only editor registries and internal state.
        params.pop("node_editors", None)
        params.pop("edge_editors", None)
        params.pop("default_node_editor", None)
        params.pop("default_edge_editor", None)
        params.pop("validate_on_add", None)
        params.pop("validate_on_patch", None)
        params.pop("_node_editors", None)
        params.pop("_edge_editors", None)
        return params

    def add_node(self, node: dict[str, Any] | NodeSpec | Node) -> None:
        """Add a node to the graph.

        Adds a new node to the graph with optional validation. If a ``view``
        is included in the node dict or :class:`NodeSpec`, it will be embedded
        inside the node and rendered as Panel content.

        Parameters
        ----------
        node : dict or NodeSpec or Node
            Node dictionary, :class:`NodeSpec`, or :class:`Node` instance to add. The only
            required field is ``id``. Other fields have defaults:

            - ``id``: Unique node identifier (required)
            - ``position``: Dict with ``x`` and ``y`` coordinates
              (defaults to ``{"x": 0.0, "y": 0.0}``)
            - ``type``: Node type (defaults to ``"panel"``)
            - ``data``: Custom data dict (defaults to ``{}``)

        Raises
        ------
        ValueError
            If the node is missing the required ``id`` field or if
            validation is enabled and the data doesn't match the schema.

        Examples
        --------
        Add a simple node:

        >>> flow = ReactFlow()
        >>> flow.add_node({
        ...     "id": "n1",
        ...     "position": {"x": 0, "y": 0},
        ...     "type": "panel",
        ...     "label": "My Node",
        ...     "data": {}
        ... })

        Add a node using NodeSpec:

        >>> from panel_reactflow import NodeSpec
        >>> flow.add_node(NodeSpec(
        ...     id="n2",
        ...     position={"x": 100, "y": 100},
        ...     label="Another Node"
        ... ))

        Add a node with embedded view via NodeSpec:

        >>> import panel as pn
        >>> flow.add_node(NodeSpec(
        ...     id="plot1",
        ...     position={"x": 200, "y": 0},
        ...     view=pn.pane.Markdown("# Hello World")
        ... ))

        Add a typed node with data:

        >>> flow.add_node(NodeSpec(
        ...     id="filter1",
        ...     type="filter",
        ...     position={"x": 300, "y": 100},
        ...     data={"threshold": 0.7, "operation": "gt"}
        ... ))

        See Also
        --------
        remove_node : Remove a node from the graph
        NodeSpec : Helper for constructing node dictionaries
        """
        raw_node = self._coerce_node(node)
        payload = self._node_payload(raw_node)
        payload.setdefault("type", "panel")
        payload.setdefault("data", {})
        payload.setdefault("position", {"x": 0.0, "y": 0.0})
        payload.setdefault("selected", False)
        payload.setdefault("draggable", True)
        payload.setdefault("connectable", True)
        payload.setdefault("deletable", True)
        if isinstance(raw_node, Node):
            raw_node.type = payload["type"]
            raw_node.data = dict(payload["data"])
            raw_node.position = dict(payload["position"])
            raw_node.selected = payload["selected"]
            raw_node.draggable = payload["draggable"]
            raw_node.connectable = payload["connectable"]
            raw_node.deletable = payload["deletable"]
            raw_node.flow = self
            self._sync_node_data_params_from_data(raw_node)
        self._validate_graph_payload(payload, kind="node")
        if self.validate_on_add:
            schema = self._get_node_schema(payload.get("type", "panel"))
            _validate_data(payload.get("data", {}), schema)
        self.nodes = self.nodes + [raw_node if isinstance(raw_node, Node) else payload]
        self._emit("node_added", {"type": "node_added", "node": payload})

    def _apply_sync(self, nodes: list[dict[str, Any]] | None, edges: list[dict[str, Any]] | None) -> None:
        """Apply a full graph payload coming from the frontend."""
        if nodes is not None:
            node_instances = {node.id: node for node in self.nodes if isinstance(node, Node)}
            synced_nodes: list[dict[str, Any] | Node] = []
            for payload in nodes:
                node = node_instances.get(payload.get("id"))
                if node is None:
                    synced_nodes.append(payload)
                    continue
                node.position = dict(payload.get("position", node.position))
                node.type = payload.get("type", node.type)
                node.label = payload.get("label", node.label)
                node.data = dict(payload.get("data", node.data))
                self._sync_node_data_params_from_data(node)
                node.selected = payload.get("selected", node.selected)
                node.draggable = payload.get("draggable", node.draggable)
                node.connectable = payload.get("connectable", node.connectable)
                node.deletable = payload.get("deletable", node.deletable)
                if "style" in payload:
                    node.style = payload.get("style")
                if "className" in payload:
                    node.className = payload.get("className")
                synced_nodes.append(node)
            self.nodes = synced_nodes
        if edges is not None:
            edge_instances = {edge.id: edge for edge in self.edges if isinstance(edge, Edge)}
            synced_edges: list[dict[str, Any] | Edge] = []
            for payload in edges:
                edge = edge_instances.get(payload.get("id"))
                if edge is None:
                    synced_edges.append(payload)
                    continue
                edge.source = payload.get("source", edge.source)
                edge.target = payload.get("target", edge.target)
                edge.label = payload.get("label", edge.label)
                edge.type = payload.get("type", edge.type)
                edge.selected = payload.get("selected", edge.selected)
                edge.data = dict(payload.get("data", edge.data))
                self._sync_edge_data_params_from_data(edge)
                if "style" in payload:
                    edge.style = payload.get("style")
                if "markerEnd" in payload:
                    edge.markerEnd = payload.get("markerEnd")
                if "sourceHandle" in payload:
                    edge.sourceHandle = payload.get("sourceHandle")
                if "targetHandle" in payload:
                    edge.targetHandle = payload.get("targetHandle")
                synced_edges.append(edge)
            self.edges = synced_edges

    def _handle_msg(self, msg: dict[str, Any]) -> None:
        """Handle sync messages from the frontend.

        Held so that every parameter update triggered by one frontend message
        is combined into a single patch. Without the hold each assignment syncs
        on its own and the browser renders every intermediate graph, e.g.
        deleting a multi-node selection shows the nodes disappearing one by one.
        """
        if not isinstance(msg, dict):
            return
        with hold():
            self._process_msg(msg)

    def _process_msg(self, msg: dict[str, Any]) -> None:
        match msg.get("type"):
            case "connection_validation_requested":
                self._validate_connection_request(msg)
            case "drop":
                self._emit(
                    "drop",
                    {
                        "type": "drop",
                        "drop_type": msg.get("drop_type"),
                        "data": msg.get("data"),
                        "position": msg.get("position"),
                        "target": msg.get("target"),
                    },
                )
            case "sync":
                nodes = msg.get("nodes")
                edges = msg.get("edges")
                with self._suppressed_prop_sync():
                    self._apply_sync(nodes, edges)
                self._emit("sync", msg)
            case "node_moved":
                node_id = msg.get("node_id")
                position = msg.get("position")
                if node_id is None or position is None:
                    return
                for node in self.nodes:
                    if self._node_id(node) == node_id:
                        self._node_set_position(node, position)
                self._emit("node_moved", msg)
            case "selection_changed":
                node_ids = msg.get("nodes") or []
                edge_ids = msg.get("edges") or []
                for node in self.nodes:
                    self._node_set_selected(node, self._node_id(node) in node_ids)
                for edge in self.edges:
                    self._edge_set_selected(edge, self._edge_id(edge) in edge_ids)
                self.selection = {"nodes": list(node_ids), "edges": list(edge_ids)}
                self._update_selected_editor()
                self._emit("selection_changed", msg)
            case "edge_added":
                edge = msg.get("edge")
                if edge is None:
                    return
                self.add_edge(edge)
            case "node_deleted":
                node_ids = list(msg.get("node_ids") or [])
                if msg.get("node_id") and msg["node_id"] not in node_ids:
                    node_ids.append(msg["node_id"])
                self.remove_node(node_ids)
            case "edge_deleted":
                edge_ids = list(msg.get("edge_ids") or [])
                if msg.get("edge_id") and msg["edge_id"] not in edge_ids:
                    edge_ids.append(msg["edge_id"])
                self.remove_edge(edge_ids)
            case "node_clicked":
                node_id = msg.get("node_id")
                if node_id is None:
                    return
                self._emit("node_clicked", msg)
            case "handle_clicked":
                node_id = msg.get("node_id")
                if node_id is None:
                    return
                if self.popup_trigger == "click":
                    self._emit("handle_clicked", msg)
            case "edge_clicked":
                edge_id = msg.get("edge_id")
                if edge_id is None:
                    return
                if self.popup_trigger == "click":
                    self._emit("edge_clicked", msg)
            case "handle_hovered":
                if self.popup_trigger == "hover" and msg.get("node_id") is not None:
                    self._emit("handle_hovered", msg)
            case "handle_unhovered":
                if self.popup_trigger == "hover" and msg.get("node_id") is not None:
                    self._emit("handle_unhovered", msg)
            case "edge_hovered":
                if self.popup_trigger == "hover" and msg.get("edge_id") is not None:
                    self._emit("edge_hovered", msg)
            case "edge_unhovered":
                if self.popup_trigger == "hover" and msg.get("edge_id") is not None:
                    self._emit("edge_unhovered", msg)
            case "node_context_menu":
                node_id = msg.get("node_id")
                position = msg.get("position")
                if node_id is None:
                    return
                node = next((n for n in self.nodes if self._node_id(n) == node_id), None)
                if node is None or not isinstance(node, Node):
                    return
                menu = node.context_menu()
                if menu is None:
                    return
                self._context_menu = menu
                self._context_menu_position = position
                self._emit("node_context_menu", msg)
            case "close_context_menu":
                self._context_menu = None
                self._context_menu_position = None
            case "close_value_popup":
                self._value_popup = None
                self._value_popup_position = None
            case "client_error":
                self._handle_client_error(msg)
            case _:
                return

    def add_connection_validator(self, callback: Callable) -> None:
        """Register a validator returning None to allow or a reason to reject.

        Callbacks accept either a connection payload or (payload, flow).
        They run in registration order for each candidate during a drag.
        """
        if not callable(callback):
            raise TypeError("Connection validator must be callable.")
        self._connection_validators.append(callback)
        self.has_connection_validators = True

    def remove_connection_validator(self, callback: Callable) -> None:
        """Unregister a previously added connection validator."""
        self._connection_validators.remove(callback)
        self.has_connection_validators = bool(self._connection_validators)

    def _validate_connection_request(self, msg: dict[str, Any]) -> None:
        node_id = msg["node_id"]
        handle_id = msg["handle_id"]
        handle_type = msg["handle_type"]
        opposite_type = "target" if handle_type == "source" else "source"
        port_key = "inputs" if opposite_type == "target" else "outputs"
        results = []
        for node in self.nodes:
            candidate_id = self._node_id(node)
            node_type = self.node_types.get(self._node_type(node), {})
            handles = node_type.get(port_key)
            if handles is None:
                handles = [None]
            for handle in handles:
                candidate_handle = handle.get("id") if isinstance(handle, dict) else handle
                if handle_type == "source":
                    payload = {"source": node_id, "target": candidate_id, "sourceHandle": handle_id, "targetHandle": candidate_handle}
                else:
                    payload = {"source": candidate_id, "target": node_id, "sourceHandle": candidate_handle, "targetHandle": handle_id}
                reason = None
                for callback in self._connection_validators:
                    try:
                        if len(inspect.signature(callback).parameters) == 2:
                            reason = callback(payload, self)
                        else:
                            reason = callback(payload)
                        if reason is not None and not isinstance(reason, str):
                            reason = "Connection validator must return None or a reason string."
                        elif reason == "":
                            reason = "Connection rejected."
                    except Exception as exc:
                        _LOGGER.exception("Connection validator failed")
                        reason = str(exc) or "Connection validator failed."
                    if reason is not None:
                        break
                results.append({"node_id": candidate_id, "handle_id": candidate_handle, "handle_type": opposite_type, "reason": reason})
        self._send_msg({"type": "connection_validation_result", "request_id": msg["request_id"], "results": results})

    def _handle_client_error(self, msg: dict[str, Any]) -> None:
        """Log a client-side error reported by the frontend and re-emit it.

        Rendering errors in the graph view previously died in the browser
        console, leaving the server with no record that the UI had broken. The
        frontend now reports them here so they land in the application log and
        can be handled via ``flow.on("client_error", ...)``.
        """
        source = msg.get("source", "unknown")
        message = msg.get("message", "Unknown error")
        if source == "safe_mode":
            _LOGGER.warning(
                "panel-reactflow %s Affected elements: %s",
                message,
                json.dumps(msg.get("issues", [])),
            )
        else:
            _LOGGER.error(
                "panel-reactflow client error (%s, attempt %s, mode %s): %s\n%s%s",
                source,
                msg.get("attempt", 0),
                msg.get("mode", "normal"),
                message,
                msg.get("stack") or "",
                msg.get("component_stack") or "",
            )
        self._emit("client_error", msg)

    def remove_node(self, *node_ids: str | Sequence[str]) -> None:
        """Remove one or more nodes and all connected edges from the graph.

        Removes the specified nodes and automatically removes any edges that
        are connected to them (either as source or target). This ensures the
        graph remains consistent.

        Ids may be passed as separate arguments or as a single sequence. All
        of them are removed in one update, i.e. ``nodes`` and ``edges`` are
        each assigned once. Removing nodes one at a time instead syncs an
        intermediate graph to the browser per node, which React Flow renders
        as the nodes disappearing one by one.

        Parameters
        ----------
        *node_ids : str or sequence of str
            Unique identifiers of the nodes to remove, either as separate
            arguments or as a single sequence. Ids that are not part of the
            graph are ignored.

        Examples
        --------
        Remove a node:

        >>> flow = ReactFlow()
        >>> flow.add_node(NodeSpec(id="n1", position={"x": 0, "y": 0}))
        >>> flow.add_node(NodeSpec(id="n2", position={"x": 100, "y": 0}))
        >>> flow.add_edge(EdgeSpec(id="e1", source="n1", target="n2"))
        >>>
        >>> flow.remove_node("n1")  # Also removes edge "e1"

        Remove several nodes in a single update:

        >>> flow.remove_node("n1", "n2")
        >>> flow.remove_node(["n1", "n2"])

        See Also
        --------
        add_node : Add a node to the graph
        remove_edge : Remove one or more edges from the graph
        """
        ids = list(dict.fromkeys(_flatten_ids(node_ids)))
        if not ids:
            return
        id_set = set(ids)
        removed_nodes = {}
        remaining_nodes = []
        for node in self.nodes:
            node_id = self._node_id(node)
            if node_id in id_set:
                removed_nodes.setdefault(node_id, node)
            else:
                remaining_nodes.append(node)
        removed_edges = [edge for edge in self.edges if self._edge_endpoints(edge) & id_set]
        updates: dict[str, Any] = {}
        if removed_nodes:
            updates["nodes"] = remaining_nodes
        if removed_edges:
            updates["edges"] = [edge for edge in self.edges if edge not in removed_edges]
        if updates:
            self.param.update(**updates)
        # Report each edge under the first node that removed it, matching the
        # payloads emitted when removing the nodes sequentially.
        reported_edges: set[str | None] = set()
        for node_id in ids:
            deleted_edges = []
            for edge in removed_edges:
                edge_id = self._edge_id(edge)
                if edge_id in reported_edges or node_id not in self._edge_endpoints(edge):
                    continue
                reported_edges.add(edge_id)
                deleted_edges.append(edge_id)
            payload = {
                "type": "node_deleted",
                "node_id": node_id,
                "deleted_edges": deleted_edges,
            }
            self._emit("node_deleted", payload)
            removed_node = removed_nodes.get(node_id)
            if isinstance(removed_node, Node):
                removed_node.flow = None
                self._invoke_node_hook(removed_node, "on_delete", dict(payload))
                self._invoke_node_hook(removed_node, "on_event", dict(payload))

    @classmethod
    def _edge_endpoints(cls, edge: dict[str, Any] | Edge) -> set[str | None]:
        """Return the source and target node ids of *edge*."""
        if isinstance(edge, Edge):
            return {edge.source, edge.target}
        return {edge.get("source"), edge.get("target")}

    def add_edge(self, edge: dict[str, Any] | EdgeSpec | Edge) -> None:
        """Add an edge to the graph.

        Adds a new edge connecting two nodes with optional validation. If no
        ``id`` is provided, one will be automatically generated based on the
        source and target nodes.

        Parameters
        ----------
        edge : dict or EdgeSpec or Edge
            Edge dictionary, :class:`EdgeSpec`, or :class:`Edge` instance to add. Required
            fields are ``source`` and ``target``. Other fields have defaults:

            - ``source``: ID of the source node (required)
            - ``target``: ID of the target node (required)
            - ``id``: Unique edge identifier (auto-generated if not provided)
            - ``data``: Custom data dict (defaults to ``{}``)

        Raises
        ------
        ValueError
            If the edge is missing required fields (``source``, ``target``)
            or if validation is enabled and the data doesn't match the schema.

        Examples
        --------
        Add a simple edge:

        >>> flow = ReactFlow()
        >>> flow.add_edge({
        ...     "id": "e1",
        ...     "source": "n1",
        ...     "target": "n2"
        ... })

        Add an edge using EdgeSpec:

        >>> from panel_reactflow import EdgeSpec
        >>> flow.add_edge(EdgeSpec(
        ...     id="e2",
        ...     source="n2",
        ...     target="n3",
        ...     label="Connection"
        ... ))

        Add a typed edge with data:

        >>> flow.add_edge(EdgeSpec(
        ...     id="weighted1",
        ...     source="n1",
        ...     target="n3",
        ...     type="weighted",
        ...     data={"weight": 0.75}
        ... ))

        Add an edge with styling:

        >>> flow.add_edge(EdgeSpec(
        ...     id="e3",
        ...     source="n3",
        ...     target="n4",
        ...     style={"stroke": "#ff0000", "strokeWidth": 3},
        ...     markerEnd={"type": "arrowclosed", "color": "#ff0000"}
        ... ))

        See Also
        --------
        remove_edge : Remove an edge from the graph
        EdgeSpec : Helper for constructing edge dictionaries
        """
        raw_edge = self._coerce_edge(edge)
        payload = self._edge_payload(raw_edge)
        payload.setdefault("data", {})
        if not payload.get("id"):
            payload["id"] = self._generate_edge_id(payload["source"], payload["target"])
        if isinstance(raw_edge, Edge):
            raw_edge.id = payload["id"]
            raw_edge.data = dict(payload["data"])
            raw_edge.flow = self
            self._sync_edge_data_params_from_data(raw_edge)
        self._validate_graph_payload(payload, kind="edge")
        if self.validate_on_add:
            edge_type = payload.get("type")
            schema = self._get_edge_schema(edge_type) if edge_type else None
            _validate_data(payload.get("data", {}), schema)
        self.edges = self.edges + [raw_edge if isinstance(raw_edge, Edge) else payload]
        self._emit("edge_added", {"type": "edge_added", "edge": payload})

    def remove_edge(self, *edge_ids: str | Sequence[str]) -> None:
        """Remove one or more edges from the graph by their ID.

        Ids may be passed as separate arguments or as a single sequence. All
        of them are removed in one update, i.e. ``edges`` is only assigned
        once, so the browser renders a single update instead of one per edge.

        Parameters
        ----------
        *edge_ids : str or sequence of str
            Unique identifiers of the edges to remove, either as separate
            arguments or as a single sequence. Ids that are not part of the
            graph are ignored.

        Examples
        --------
        Remove an edge:

        >>> flow = ReactFlow()
        >>> flow.add_edge(EdgeSpec(id="e1", source="n1", target="n2"))
        >>> flow.remove_edge("e1")

        Remove several edges in a single update:

        >>> flow.remove_edge("e1", "e2")
        >>> flow.remove_edge(["e1", "e2"])

        See Also
        --------
        add_edge : Add an edge to the graph
        remove_node : Remove one or more nodes from the graph
        """
        ids = list(dict.fromkeys(_flatten_ids(edge_ids)))
        if not ids:
            return
        id_set = set(ids)
        removed_edges = {}
        remaining_edges = []
        for edge in self.edges:
            edge_id = self._edge_id(edge)
            if edge_id in id_set:
                removed_edges.setdefault(edge_id, edge)
            else:
                remaining_edges.append(edge)
        if removed_edges:
            self.edges = remaining_edges
        for edge_id in ids:
            removed_edge = removed_edges.get(edge_id)
            if removed_edge is None:
                continue
            payload = {"type": "edge_deleted", "edge_id": edge_id}
            self._emit("edge_deleted", payload)
            if isinstance(removed_edge, Edge):
                removed_edge.flow = None
                self._invoke_edge_hook(removed_edge, "on_delete", dict(payload))
                self._invoke_edge_hook(removed_edge, "on_event", dict(payload))

    def _apply_data_patch(
        self,
        *,
        items: list,
        item_id: str,
        patch: dict[str, Any],
        get_id: Callable[[Any], str | None],
        get_data: Callable[[Any], dict[str, Any]],
        set_data: Callable[[Any, dict[str, Any]], None],
        get_schema: Callable[[Any], dict[str, Any] | None],
        sync_from_data: Callable[[Any], None],
        instance_cls: type,
    ) -> None:
        """Shared implementation for ``patch_node_data``/``patch_edge_data``.

        Merges ``patch`` into the matching item's ``data``, validating it
        against the item type's schema when ``validate_on_patch`` is enabled.
        Top-level React Flow fields are patched separately, by
        ``patch_node_props``/``patch_edge_props``.
        """
        for item in items:
            if get_id(item) != item_id:
                continue
            data = get_data(item)
            data.update(patch)
            if self.validate_on_patch:
                _validate_data(data, get_schema(item))
            set_data(item, data)
            if isinstance(item, instance_cls):
                sync_from_data(item)
            break

    def patch_node_data(self, node_id: str, patch: dict[str, Any]) -> None:
        """Update specific properties in a node's data dictionary.

        Merges the provided patch dictionary into the node's existing ``data``
        dict, allowing you to update individual properties without replacing
        the entire data object.

        Parameters
        ----------
        node_id : str
            Unique identifier of the node to update.
        patch : dict
            Dictionary of key-value pairs to merge into the node's ``data``.
            Existing keys will be updated, new keys will be added.

        Raises
        ------
        ValueError
            If validation is enabled (``validate_on_patch=True``) and the
            patched data doesn't match the node type's schema.

        Examples
        --------
        Update a single property:

        >>> flow = ReactFlow()
        >>> flow.add_node(NodeSpec(
        ...     id="n1",
        ...     position={"x": 0, "y": 0},
        ...     data={"threshold": 0.5, "name": "Filter"}
        ... ))
        >>>
        >>> # Update just the threshold
        >>> flow.patch_node_data("n1", {"threshold": 0.8})

        Update multiple properties:

        >>> flow.patch_node_data("n1", {
        ...     "threshold": 0.9,
        ...     "name": "Updated Filter"
        ... })

        Notes
        -----
        This method is typically called automatically by editors when users
        modify node properties in the UI. The patch is also sent to the
        frontend to keep the visualization in sync.

        A ``label`` (or ``_label``) key is kept in ``data`` *and* mirrored onto
        the node's top-level label, since that is where the node components
        read it from. Every other key is treated as opaque data; use
        :meth:`patch_node_props` for the remaining presentational fields.

        See Also
        --------
        patch_edge_data : Update edge data properties
        patch_node_props : Update top-level node properties
        add_node : Add a new node to the graph
        """
        self._apply_data_patch(
            items=self.nodes,
            item_id=node_id,
            patch=patch,
            get_id=self._node_id,
            get_data=self._node_data,
            set_data=self._node_set_data,
            get_schema=lambda node: self._get_node_schema(self._node_type(node)),
            sync_from_data=self._sync_node_data_params_from_data,
            instance_cls=Node,
        )
        self._send_msg({"type": "patch_node_data", "node_id": node_id, "patch": patch})
        self._emit("node_data_changed", {"type": "node_data_changed", "node_id": node_id, "patch": patch})
        mirrored = self._mirrored_props(patch, Node._mirrored_data_keys)
        if mirrored:
            self.patch_node_props(node_id, mirrored)

    def patch_edge_data(self, edge_id: str, patch: dict[str, Any]) -> None:
        """Update specific properties in an edge's data dictionary.

        Merges the provided patch dictionary into the edge's existing ``data``
        dict, allowing you to update individual properties without replacing
        the entire data object.

        Parameters
        ----------
        edge_id : str
            Unique identifier of the edge to update.
        patch : dict
            Dictionary of key-value pairs to merge into the edge's ``data``.
            Existing keys will be updated, new keys will be added.

        Raises
        ------
        ValueError
            If validation is enabled (``validate_on_patch=True``) and the
            patched data doesn't match the edge type's schema.

        Examples
        --------
        Update edge properties:

        >>> flow = ReactFlow()
        >>> flow.add_edge(EdgeSpec(
        ...     id="e1",
        ...     source="n1",
        ...     target="n2",
        ...     data={"weight": 0.5, "label": "weak"}
        ... ))
        >>>
        >>> # Update just the weight
        >>> flow.patch_edge_data("e1", {"weight": 0.9, "label": "strong"})

        Notes
        -----
        This method is typically called automatically by editors when users
        modify edge properties in the UI. The patch is also sent to the
        frontend to keep the visualization in sync.

        A ``label`` key is kept in ``data`` *and* mirrored onto the edge's
        top-level label, which is what React Flow renders. Every other key is
        treated as opaque data; use :meth:`patch_edge_props` for the remaining
        presentational fields.

        See Also
        --------
        patch_node_data : Update node data properties
        patch_edge_props : Update top-level edge properties
        add_edge : Add a new edge to the graph
        """
        self._apply_data_patch(
            items=self.edges,
            item_id=edge_id,
            patch=patch,
            get_id=self._edge_id,
            get_data=self._edge_data,
            set_data=self._edge_set_data,
            get_schema=lambda edge: self._get_edge_schema(self._edge_type(edge)) if self._edge_type(edge) else None,
            sync_from_data=self._sync_edge_data_params_from_data,
            instance_cls=Edge,
        )
        self._send_msg({"type": "patch_edge_data", "edge_id": edge_id, "patch": patch})
        self._emit("edge_data_changed", {"type": "edge_data_changed", "edge_id": edge_id, "patch": patch})
        mirrored = self._mirrored_props(patch, Edge._mirrored_data_keys)
        if mirrored:
            self.patch_edge_props(edge_id, mirrored)

    @staticmethod
    def _mirrored_props(patch: dict[str, Any], mirrored: dict[str, str]) -> dict[str, Any]:
        return {prop: patch[key] for key, prop in mirrored.items() if key in patch}

    def _validate_prop_patch(self, patch: dict[str, Any], *, kind: str, allowed: tuple[str, ...]) -> None:
        unknown = [key for key in patch if key not in allowed]
        if not unknown:
            return
        hint = f"Use patch_{kind}_data to update the {kind}'s data dictionary."
        prop_name = "property" if len(unknown) == 1 else "properties"
        raise ValueError(f"Cannot patch {kind} {prop_name} {unknown!r}; expected one of {list(allowed)!r}. {hint}")

    def _apply_prop_patch(self, obj: dict[str, Any] | Node | Edge, patch: dict[str, Any]) -> None:
        """Apply a top-level property patch to the Python-side node/edge."""
        if isinstance(obj, (Node, Edge)):
            # The watchers already sent (or are about to send) the patch, so
            # applying it here must not trigger a second message.
            with self._suppressed_prop_sync():
                for key, value in patch.items():
                    setattr(obj, key, value)
        else:
            for key, value in patch.items():
                if value is None:
                    obj.pop(key, None)
                else:
                    obj[key] = value

    def patch_node_props(self, node_id: str, patch: dict[str, Any]) -> None:
        """Update top-level properties of a node.

        Sends an incremental patch to the frontend, updating fields that live
        outside the node's ``data`` dictionary (``label``, ``style``, ``type``,
        ``position``, ...) without re-serializing the whole ``nodes`` list.

        Assigning to the corresponding parameter of a :class:`Node` instance
        calls this method for you, so this is mainly useful for nodes defined
        as plain dictionaries and for the frontend-driven ``position`` and
        ``selected`` fields.

        Parameters
        ----------
        node_id : str
            Unique identifier of the node to update.
        patch : dict
            Mapping of property names to new values. Supported keys are
            ``position``, ``type``, ``label``, ``selected``, ``draggable``,
            ``connectable``, ``deletable``, ``style`` and ``className``.
            Passing ``None`` clears the property so the node falls back to
            the CSS/theme default.

        Raises
        ------
        ValueError
            If *patch* contains a key that is not a top-level node property.

        Examples
        --------
        Restyle a node and rename it:

        >>> flow.patch_node_props("n1", {"style": {"border": "2px solid red"}, "label": "Failed"})

        Clear a style so the theme default applies again:

        >>> flow.patch_node_props("n1", {"style": None})

        Move a node programmatically:

        >>> flow.patch_node_props("n1", {"position": {"x": 120, "y": 40}})

        See Also
        --------
        patch_node_data : Update the node's ``data`` dictionary
        patch_edge_props : Update top-level edge properties
        """
        self._validate_prop_patch(patch, kind="node", allowed=Node._props)
        for node in self.nodes:
            if self._node_id(node) == node_id:
                self._apply_prop_patch(node, patch)
                break
        self._send_msg({"type": "patch_node_props", "node_id": node_id, "patch": patch})
        self._emit("node_props_changed", {"type": "node_props_changed", "node_id": node_id, "patch": patch})

    def patch_edge_props(self, edge_id: str, patch: dict[str, Any]) -> None:
        """Update top-level properties of an edge.

        Sends an incremental patch to the frontend, updating fields that live
        outside the edge's ``data`` dictionary (``label``, ``style``, ``type``,
        ``markerEnd``, ...) without re-serializing the whole ``edges`` list.

        Assigning to the corresponding parameter of an :class:`Edge` instance
        calls this method for you, so this is mainly useful for edges defined
        as plain dictionaries and for the frontend-driven ``selected`` field.

        Parameters
        ----------
        edge_id : str
            Unique identifier of the edge to update.
        patch : dict
            Mapping of property names to new values. Supported keys are
            ``source``, ``target``, ``label``, ``type``, ``selected``,
            ``style``, ``markerEnd``, ``sourceHandle`` and ``targetHandle``.
            Passing ``None`` clears the property so the edge falls back to
            the CSS/theme default.

        Raises
        ------
        ValueError
            If *patch* contains a key that is not a top-level edge property.

        Examples
        --------
        Highlight an edge and switch it to a step router:

        >>> flow.patch_edge_props("e1", {"style": {"stroke": "#ef4444", "strokeWidth": 6}, "type": "step"})

        Clear the style so the theme default applies again:

        >>> flow.patch_edge_props("e1", {"style": None})

        See Also
        --------
        patch_edge_data : Update the edge's ``data`` dictionary
        patch_node_props : Update top-level node properties
        """
        self._validate_prop_patch(patch, kind="edge", allowed=Edge._props)
        for edge in self.edges:
            if self._edge_id(edge) == edge_id:
                self._apply_prop_patch(edge, patch)
                break
        self._send_msg({"type": "patch_edge_props", "edge_id": edge_id, "patch": patch})
        self._emit("edge_props_changed", {"type": "edge_props_changed", "edge_id": edge_id, "patch": patch})

    def to_networkx(self, *, multigraph: bool = False):
        """Convert the current graph to NetworkX format.

        Converts the ReactFlow graph state into a NetworkX graph object,
        preserving node positions, types, labels, and data. Useful for
        graph analysis, algorithms, and integration with the NetworkX
        ecosystem.

        Parameters
        ----------
        multigraph : bool, default False
            If ``True``, returns a ``MultiDiGraph`` allowing multiple edges
            between the same node pair. If ``False``, returns a ``DiGraph``
            with single edges between nodes.

        Returns
        -------
        networkx.DiGraph or networkx.MultiDiGraph
            NetworkX graph representation with node and edge data preserved.

            Node attributes include:
            - All properties from ``node["data"]``
            - ``position``: Node position dict
            - ``type``: Node type string
            - ``label``: Node label (if present)

            Edge attributes include:
            - All properties from ``edge["data"]``
            - ``label``: Edge label (if present)
            - ``type``: Edge type string (if present)
            - For MultiDiGraphs, ``key`` is the edge ID

        Raises
        ------
        ImportError
            If NetworkX is not installed.

        Examples
        --------
        Convert to NetworkX and run graph algorithms:

        >>> import networkx as nx
        >>> from panel_reactflow import ReactFlow, NodeSpec, EdgeSpec
        >>>
        >>> flow = ReactFlow()
        >>> flow.add_node(NodeSpec(id="A", position={"x": 0, "y": 0}))
        >>> flow.add_node(NodeSpec(id="B", position={"x": 100, "y": 0}))
        >>> flow.add_node(NodeSpec(id="C", position={"x": 50, "y": 100}))
        >>> flow.add_edge(EdgeSpec(id="e1", source="A", target="B"))
        >>> flow.add_edge(EdgeSpec(id="e2", source="B", target="C"))
        >>> flow.add_edge(EdgeSpec(id="e3", source="A", target="C"))
        >>>
        >>> G = flow.to_networkx()
        >>>
        >>> # Run NetworkX algorithms
        >>> shortest = nx.shortest_path(G, "A", "C")
        >>> print(shortest)  # ['A', 'C']
        >>>
        >>> centrality = nx.betweenness_centrality(G)
        >>> print(centrality)

        Convert with edge data:

        >>> flow = ReactFlow()
        >>> flow.add_node(NodeSpec(id="1", position={"x": 0, "y": 0}))
        >>> flow.add_node(NodeSpec(id="2", position={"x": 100, "y": 0}))
        >>> flow.add_edge(EdgeSpec(
        ...     id="e1",
        ...     source="1",
        ...     target="2",
        ...     data={"weight": 0.75, "distance": 10}
        ... ))
        >>>
        >>> G = flow.to_networkx()
        >>> print(G["1"]["2"]["weight"])  # 0.75

        See Also
        --------
        from_networkx : Create ReactFlow from NetworkX graph
        """
        try:
            import networkx as nx  # type: ignore[import-not-found]
        except Exception as exc:  # pragma: no cover
            raise ImportError("networkx is required for to_networkx.") from exc

        graph = nx.MultiDiGraph() if multigraph else nx.DiGraph()
        for node in self.nodes:
            payload = self._node_payload(node)
            data = dict(payload.get("data", {}))
            data.update({"position": payload.get("position"), "type": payload.get("type")})
            if payload.get("label") is not None:
                data["label"] = payload.get("label")
            graph.add_node(payload["id"], **data)
        for edge in self.edges:
            payload = self._edge_payload(edge)
            data = dict(payload.get("data", {}))
            if payload.get("label") is not None:
                data["label"] = payload["label"]
            if payload.get("type") is not None:
                data["type"] = payload["type"]
            if payload.get("sourceHandle") is not None:
                data["sourceHandle"] = payload["sourceHandle"]
            if payload.get("targetHandle") is not None:
                data["targetHandle"] = payload["targetHandle"]
            if multigraph:
                graph.add_edge(payload["source"], payload["target"], key=payload.get("id"), **data)
            else:
                graph.add_edge(payload["source"], payload["target"], **data)
        return graph

    @classmethod
    def from_networkx(
        cls,
        graph,
        *,
        node_type: str = "panel",
        default_position: tuple[float, float] = (0.0, 0.0),
    ) -> "ReactFlow":
        """Create a ReactFlow instance from a NetworkX graph.

        Converts a NetworkX graph into a ReactFlow component, extracting
        node positions, labels, and data from node/edge attributes. This
        enables seamless integration with NetworkX's graph creation and
        analysis capabilities.

        Parameters
        ----------
        graph : networkx.Graph
            A NetworkX graph instance (directed or undirected). Node attributes
            are converted to node data, and edge attributes to edge data.
        node_type : str, default "panel"
            Default node type assigned to all nodes. Use a custom type if you
            want schema validation or custom rendering.
        default_position : tuple of float, default (0.0, 0.0)
            Default (x, y) position used when a node doesn't have a ``position``
            attribute. Nodes can specify position via a ``position`` attribute
            as either a dict ``{"x": ..., "y": ...}`` or tuple/list ``[x, y]``.

        Returns
        -------
        ReactFlow
            A new ReactFlow instance populated with nodes and edges from the
            NetworkX graph.

        Examples
        --------
        Create from a simple NetworkX graph:

        >>> import networkx as nx
        >>> from panel_reactflow import ReactFlow
        >>>
        >>> G = nx.DiGraph()
        >>> G.add_node("A", position={"x": 0, "y": 0}, label="Start")
        >>> G.add_node("B", position={"x": 100, "y": 0}, label="Process")
        >>> G.add_node("C", position={"x": 200, "y": 0}, label="End")
        >>> G.add_edge("A", "B", weight=0.5)
        >>> G.add_edge("B", "C", weight=0.8)
        >>>
        >>> flow = ReactFlow.from_networkx(G)

        Use with NetworkX graph generators:

        >>> G = nx.karate_club_graph()
        >>> # Add positions using a layout algorithm
        >>> pos = nx.spring_layout(G, scale=500)
        >>> for node_id, (x, y) in pos.items():
        ...     G.nodes[node_id]["position"] = {"x": x, "y": y}
        >>>
        >>> flow = ReactFlow.from_networkx(G)

        Custom node type and attributes:

        >>> G = nx.DiGraph()
        >>> G.add_node("filter1", position=[0, 0], threshold=0.5, op="gt")
        >>> G.add_node("filter2", position=[100, 0], threshold=0.7, op="lt")
        >>> G.add_edge("filter1", "filter2", label="pipe")
        >>>
        >>> flow = ReactFlow.from_networkx(G, node_type="filter")

        Notes
        -----
        Node attributes are converted as follows:
        - ``position``: Used directly (converted to dict if tuple/list)
        - ``label``: Used as node label
        - ``type``: Overrides the default ``node_type`` parameter
        - ``data``: Merged with other attributes as node data
        - All other attributes become node data properties

        Edge attributes are converted as follows:
        - ``label``: Used as edge label
        - ``type``: Used as edge type
        - ``data``: Merged with other attributes as edge data
        - All other attributes become edge data properties
        - For MultiDiGraphs, the edge key becomes the edge ID

        See Also
        --------
        to_networkx : Convert ReactFlow to NetworkX graph
        """
        nodes: list[dict[str, Any]] = []
        edges: list[dict[str, Any]] = []
        for node_id, attrs in graph.nodes(data=True):
            attrs = dict(attrs)  # avoids mutating the original graph
            position = attrs.pop("position", {"x": default_position[0], "y": default_position[1]})
            if isinstance(position, (tuple, list)):
                position = {"x": position[0], "y": position[1]}
            label = attrs.pop("label", None)
            node_data = dict(attrs)
            node_data.pop("type", None)
            embedded_data = node_data.pop("data", None)
            if isinstance(embedded_data, dict):
                node_data = {**embedded_data, **node_data}
            node_payload = {"id": str(node_id), "position": position, "type": node_type, "data": node_data}
            if label is not None:
                node_payload["label"] = label
            nodes.append(node_payload)
        if graph.is_multigraph():
            edge_iter = graph.edges(keys=True, data=True)
        else:
            edge_iter = ((source, target, None, attrs) for source, target, attrs in graph.edges(data=True))
        for source, target, key, attrs in edge_iter:
            edge_data = dict(attrs)
            embedded_edge_data = edge_data.pop("data", None)
            if isinstance(embedded_edge_data, dict):
                edge_data = {**embedded_edge_data, **edge_data}
            label = edge_data.pop("label", None)
            edge_type = edge_data.pop("type", None)
            source_handle = edge_data.pop("sourceHandle", None)
            target_handle = edge_data.pop("targetHandle", None)
            edge_id = key if key is not None else f"{source}->{target}"
            edge = {
                "id": str(edge_id),
                "source": str(source),
                "target": str(target),
                "data": edge_data,
            }
            if label is not None:
                edge["label"] = label
            if edge_type is not None:
                edge["type"] = edge_type
            if source_handle is not None:
                edge["sourceHandle"] = source_handle
            if target_handle is not None:
                edge["targetHandle"] = target_handle
            edges.append(edge)
        return cls(nodes=nodes, edges=edges)

    def show_popup(self, content: Any, position: dict[str, float]) -> None:
        """Show a Panel viewable in a floating overlay at a screen position.

        Intended for use from ``"handle_clicked"`` and ``"edge_clicked"``
        callbacks to display, e.g., the current value flowing through a port
        or connection, but can be called for any reason.

        Parameters
        ----------
        content
            A Panel viewable (or anything ``pn.panel()`` accepts) to render
            inside the popup.
        position
            Screen position with ``x``/``y`` keys, typically taken straight
            from the ``"position"`` field of the triggering event payload.

        Examples
        --------
        >>> def on_handle_clicked(payload, flow):
        ...     value = compute_value(payload["node_id"], payload["handle_id"])
        ...     flow.show_popup(pn.pane.Markdown(f"Value: {value}"), payload["position"])
        >>>
        >>> flow.on("handle_clicked", on_handle_clicked)

        See Also
        --------
        close_popup : Dismiss the popup programmatically.

        Notes
        -----
        Set ``popup_trigger="hover"`` to use the configured dwell delay
        and movement distance before and after opening a value popup. Set it to
        ``"none"`` to disable automatic inspection events.
        """
        self._value_popup = content
        self._value_popup_position = position

    def close_popup(self) -> None:
        """Dismiss the popup shown by :meth:`show_popup`, if any."""
        self._value_popup = None
        self._value_popup_position = None

    def on(self, event_type: str, callback) -> None:
        """Register a callback for graph events.

        Subscribe to events emitted by the ReactFlow component. Events are
        triggered by user interactions (node moves, selections, etc.) and
        programmatic changes (adding/removing nodes/edges).

        Parameters
        ----------
        event_type : str
            Type of event to listen for. Use ``"*"`` to listen to all events.
            Available event types:

            - ``"node_added"``: Node was added to the graph
            - ``"node_deleted"``: Node was removed from the graph
            - ``"node_moved"``: Node was dragged to a new position
            - ``"node_clicked"``: Node was clicked
            - ``"handle_clicked"``: A node's input/output handle was clicked.
              Payload has ``node_id``, ``handle_id`` (``None`` for a node's
              unnamed default handle), ``direction`` (``"input"`` or
              ``"output"``) and a screen ``position`` suitable for
              :meth:`show_popup`.
            - ``"edge_clicked"``: An edge was clicked. Payload has
              ``edge_id`` and a screen ``position`` suitable for
              :meth:`show_popup`.
            - ``"handle_hovered"`` / ``"edge_hovered"``: A port or edge was
              entered while ``popup_trigger="hover"``.
            - ``"handle_unhovered"`` / ``"edge_unhovered"``: The pointer left
              the inspected port or edge.
            - ``"node_data_changed"``: Node data was modified
            - ``"node_props_changed"``: Top-level node properties (``label``,
              ``style``, ``type``, ...) were modified
            - ``"edge_added"``: Edge was added to the graph
            - ``"edge_deleted"``: Edge was removed from the graph
            - ``"edge_data_changed"``: Edge data was modified
            - ``"edge_props_changed"``: Top-level edge properties (``label``,
              ``style``, ``type``, ...) were modified
            - ``"selection_changed"``: Selection changed
            - ``"sync"``: Full graph sync from frontend
            - ``"drop"``: Data of one of the ``drop_types`` was dropped onto
              the canvas. Payload has the matched ``drop_type``, the dropped
              ``data`` (parsed from JSON when possible, otherwise the raw
              string; for ``"Files"`` a list of ``{"name", "type", "size",
              "content"}`` with each file read as text), the drop
              ``position`` in flow coordinates, and a
              ``target`` of ``{"node_id", "handle_id", "direction"}`` when
              dropped on a node or handle (``handle_id`` and ``direction``
              are ``None`` for a node), else ``None``.
            - ``"client_error"``: The graph view hit a rendering error in the
              browser. The payload carries ``source``, ``message``, ``stack``,
              ``component_stack``, ``attempt`` and ``mode``, or for
              ``source="safe_mode"`` the list of hidden ``issues``.
            - ``"*"``: All events (wildcard)
        callback : callable
            Function called when the event occurs. Receives the event payload
            dictionary as the first argument. The callback may optionally
            accept the ``ReactFlow`` instance as a second argument, e.g.
            ``callback(payload, flow)``.

        Examples
        --------
        Listen for node movements:

        >>> from panel_reactflow import ReactFlow
        >>>
        >>> flow = ReactFlow()
        >>>
        >>> def on_move(payload, flow):
        ...     node_id = payload["node_id"]
        ...     position = payload["position"]
        ...     print(f"Node {node_id} moved to ({position['x']}, {position['y']})")
        ...     print(f"Graph currently has {len(flow.nodes)} nodes")
        >>>
        >>> flow.on("node_moved", on_move)

        Track all graph changes:

        >>> def on_any_event(payload):
        ...     event_type = payload["type"]
        ...     print(f"Event: {event_type}")
        >>>
        >>> flow.on("*", on_any_event)

        Build a workflow tracker:

        >>> nodes_added = []
        >>> edges_added = []
        >>>
        >>> def track_node(event):
        ...     nodes_added.append(event["node"])
        >>>
        >>> def track_edge(event):
        ...     edges_added.append(event["edge"])
        >>>
        >>> flow.on("node_added", track_node)
        >>> flow.on("edge_added", track_edge)

        React to selection changes:

        >>> def on_selection(event):
        ...     selected_nodes = event["nodes"]
        ...     selected_edges = event["edges"]
        ...     print(f"Selected {len(selected_nodes)} nodes and {len(selected_edges)} edges")
        >>>
        >>> flow.on("selection_changed", on_selection)

        Update analytics on data changes:

        >>> def on_data_change(event):
        ...     node_id = event["node_id"]
        ...     patch = event["patch"]
        ...     print(f"Node {node_id} updated: {patch}")
        ...     # Update database, trigger recalculation, etc.
        >>>
        >>> flow.on("node_data_changed", on_data_change)

        Show the current value of a port when its handle is clicked:

        >>> import panel as pn
        >>> def on_handle_clicked(payload, flow):
        ...     value = my_values[payload["node_id"]][payload["handle_id"]]
        ...     flow.show_popup(pn.pane.Markdown(f"**Value:** {value}"), payload["position"])
        >>>
        >>> flow.on("handle_clicked", on_handle_clicked)

        Notes
        -----
        Multiple callbacks can be registered for the same event type.
        They will be called in the order they were registered.

        The ``"*"`` wildcard receives all events, making it useful for
        logging, debugging, or implementing undo/redo functionality.

        Event payloads always include a ``"type"`` field indicating the
        event type, plus event-specific fields.
        """
        self._event_handlers.setdefault(event_type, []).append(callback)

    def _emit(self, event_type: str, payload: dict[str, Any]) -> None:
        # schedule=False: see the matching comment on _invoke_node_callback.
        # This runs the message handling that triggered the event, so
        # deferring to the next tick would break Child-param updates (e.g.
        # via show_popup) made from inside a registered callback.
        for callback in self._event_handlers.get(event_type, []):
            if len(inspect.signature(callback).parameters) == 2:
                cb = partial(callback, payload, self)
            else:
                cb = partial(callback, payload)
            pn.state.execute(cb, schedule=False)
        for callback in self._event_handlers.get("*", []):
            if len(inspect.signature(callback).parameters) == 2:
                cb = partial(callback, payload, self)
            else:
                cb = partial(callback, payload)
            pn.state.execute(cb, schedule=False)
        self._dispatch_node_hooks(event_type, payload)
        self._dispatch_edge_hooks(event_type, payload)

    def _update_selection_from_graph(self, *_: param.parameterized.Event) -> None:
        selected_node_ids: list[str] = []
        for node in self.nodes:
            node_id = self._node_id(node)
            if node_id is None:
                continue
            is_selected = node.selected if isinstance(node, Node) else node.get("selected")
            if is_selected:
                selected_node_ids.append(node_id)
        selected_edge_ids: list[str] = []
        for edge in self.edges:
            edge_id = self._edge_id(edge)
            if edge_id is None:
                continue
            is_selected = edge.selected if isinstance(edge, Edge) else edge.get("selected")
            if is_selected:
                selected_edge_ids.append(edge_id)
        selection = {
            "nodes": selected_node_ids,
            "edges": selected_edge_ids,
        }
        if selection != self.selection:
            self.selection = selection
            self._emit(
                "selection_changed",
                {"type": "selection_changed", "nodes": selection["nodes"], "edges": selection["edges"]},
            )

    def _normalize_specs(self, *events: param.parameterized.Event) -> None:
        for event in events:
            normalized = _coerce_spec_map(event.new, edge=event.name == "edge_types")
            if normalized != event.new:
                setattr(self, event.name, normalized)

    def _normalize_nodes(self, event: param.parameterized.Event) -> None:
        """Normalize nodes list by converting NodeSpec objects to dicts."""
        normalized = [self._coerce_node(node) for node in event.new]
        # Only update if there were actual changes to avoid infinite recursion
        if any(n1 is not n2 for n1, n2 in zip(normalized, event.new, strict=False)):
            self.nodes = normalized

    def _normalize_edges(self, event: param.parameterized.Event) -> None:
        """Normalize edges list by converting EdgeSpec objects to dicts."""
        normalized = [self._coerce_edge(edge) for edge in event.new]
        # Only update if there were actual changes to avoid infinite recursion
        if any(e1 is not e2 for e1, e2 in zip(normalized, event.new, strict=False)):
            self.edges = normalized

    @staticmethod
    def _generate_edge_id(source: str, target: str) -> str:
        existing = f"{source}->{target}"
        return f"{existing}-{uuid4().hex[:8]}"

    @staticmethod
    def _coerce_node(node: dict[str, Any] | NodeSpec | Node):
        if isinstance(node, Node):
            return node
        if isinstance(node, NodeSpec):
            return node.to_dict()
        return node.to_dict() if hasattr(node, "to_dict") else node

    @staticmethod
    def _coerce_edge(edge: dict[str, Any] | EdgeSpec | Edge):
        if isinstance(edge, Edge):
            return edge
        if isinstance(edge, EdgeSpec):
            return edge.to_dict()
        return edge.to_dict() if hasattr(edge, "to_dict") else edge

    def _validate_graph_payload(self, payload: dict[str, Any], *, kind: str) -> None:
        required = {"node": ["id", "position", "data"], "edge": ["id", "source", "target"]}[kind]
        for key in required:
            if key not in payload:
                raise ValueError(f"Missing '{key}' in {kind} payload.")

allow_edge_loops = param.Boolean(default=False, doc='Allow to have edge loops in the graph (can lead to update infinite loops).') class-attribute instance-attribute

bottom_panel = Children(default=[], doc='Children rendered in a bottom-center panel.') class-attribute instance-attribute

color_mode = param.ObjectSelector(default=None, objects=['light', 'dark'], doc='Color mode for the graph.') class-attribute instance-attribute

connection_validation = param.Dict(default={}, doc='Opt-in frontend connection policies (direction, cycles, duplicates, types, capacity).') class-attribute instance-attribute

debounce_ms = param.Integer(default=150, bounds=(0, None), doc="Debounce delay in milliseconds when sync_mode='debounce'.") class-attribute instance-attribute

default_edge_editor = param.Parameter(default=None, doc='Default edge editor factory.', precedence=-1) class-attribute instance-attribute

default_edge_options = param.Dict(default={}, doc='Default React Flow edge options.') class-attribute instance-attribute

default_node_editor = param.Parameter(default=None, doc='Default node editor factory.', precedence=-1) class-attribute instance-attribute

display_side_bar = param.Boolean(default=True, doc='Display the side bar to drag and drop new nodes.') class-attribute instance-attribute

drop_types = param.List(default=[], item_type=str, doc='\n MIME types accepted when data is dropped onto the canvas, e.g. the\n ``drag_type`` of a draggable ``panel_material_ui.MenuList``. Include\n ``"Files"`` to accept files dragged in from the operating system.\n Each accepted drop emits a ``"drop"`` event; drops of other types are\n ignored, as are all drops while ``editable`` is False.') class-attribute instance-attribute

edge_editors = param.Dict(default={}, doc='Edge editor factories keyed by type name.', precedence=-1) class-attribute instance-attribute

edge_types = param.Dict(default={}, doc='Edge type descriptors keyed by type name.') class-attribute instance-attribute

edges = param.List(default=[], doc='Canonical list of edge dictionaries or Edge instances.') class-attribute instance-attribute

editable = param.Boolean(default=True, doc='Enable interactive editing on the canvas.') class-attribute instance-attribute

editor_mode = param.ObjectSelector(default='toolbar', objects=['toolbar', 'node', 'side'], doc='Where to render node editors: toolbar, node, or side panel.') class-attribute instance-attribute

enable_connect = param.Boolean(default=True, doc='Allow connecting nodes to create edges.') class-attribute instance-attribute

enable_delete = param.Boolean(default=True, doc='Allow deleting selected nodes or edges.') class-attribute instance-attribute

enable_multiselect = param.Boolean(default=True, doc='Allow multiselect with modifier key.') class-attribute instance-attribute

error_recovery = param.ObjectSelector(default='auto', objects=['auto', 'manual', 'off'], doc="How to handle a rendering error in the graph view. 'auto' silently remounts the canvas, then retries in safe mode, before showing a recovery panel; 'manual' shows the recovery panel immediately; 'off' disables the error boundary so exceptions propagate.") class-attribute instance-attribute

has_connection_validators = param.Boolean(default=False, doc='Whether Python connection validators are registered.') class-attribute instance-attribute

left_panel = Children(default=[], doc='Children rendered in a center-left panel.') class-attribute instance-attribute

max_zoom = param.Number(default=2, bounds=(0, None), inclusive_bounds=(False, True), doc='Maximum zoom level of the viewport.') class-attribute instance-attribute

min_zoom = param.Number(default=0.5, bounds=(0, None), inclusive_bounds=(False, True), doc='Minimum zoom level of the viewport.') class-attribute instance-attribute

node_editors = param.Dict(default={}, doc='Node editor factories keyed by type name.', precedence=-1) class-attribute instance-attribute

node_types = param.Dict(default={}, doc='Node type descriptors keyed by type name.') class-attribute instance-attribute

nodes = param.List(default=[], doc='Canonical list of node dictionaries or Node instances.') class-attribute instance-attribute

popup_hover_delay = param.Integer(default=500, bounds=(0, None), doc='Delay in milliseconds before a hover inspection event is emitted.') class-attribute instance-attribute

popup_trigger = param.ObjectSelector(default='click', objects=['click', 'hover', 'none'], doc='Whether port and edge inspection events are triggered on click, hover, or not automatically.') class-attribute instance-attribute

right_panel = Children(default=[], doc='Children rendered in a center-right panel.') class-attribute instance-attribute

selection = param.Dict(default={'nodes': [], 'edges': []}, doc='Derived selection state for node and edge ids.') class-attribute instance-attribute

show_minimap = param.Boolean(default=False, doc='Show the minimap overlay.') class-attribute instance-attribute

sync_mode = param.ObjectSelector(default='event', objects=['event', 'debounce'], doc='Sync mode for JS->Python updates.') class-attribute instance-attribute

top_panel = Children(default=[], doc='Children rendered in a top-center panel.') class-attribute instance-attribute

validate_on_add = param.Boolean(default=True, doc='Validate data against schema on add_node/add_edge.') class-attribute instance-attribute

validate_on_patch = param.Boolean(default=False, doc='Validate data against schema on patch_node_data/patch_edge_data.') class-attribute instance-attribute

viewport = param.Dict(default=None, allow_None=True, doc='Optional persisted viewport state.') class-attribute instance-attribute

add_connection_validator(callback)

Register a validator returning None to allow or a reason to reject.

Callbacks accept either a connection payload or (payload, flow). They run in registration order for each candidate during a drag.

Source code in src/panel_reactflow/base.py
def add_connection_validator(self, callback: Callable) -> None:
    """Register a validator returning None to allow or a reason to reject.

    Callbacks accept either a connection payload or (payload, flow).
    They run in registration order for each candidate during a drag.
    """
    if not callable(callback):
        raise TypeError("Connection validator must be callable.")
    self._connection_validators.append(callback)
    self.has_connection_validators = True

add_edge(edge)

Add an edge to the graph.

Adds a new edge connecting two nodes with optional validation. If no id is provided, one will be automatically generated based on the source and target nodes.

Parameters:

Name Type Description Default
edge dict or EdgeSpec or Edge

Edge dictionary, :class:EdgeSpec, or :class:Edge instance to add. Required fields are source and target. Other fields have defaults:

  • source: ID of the source node (required)
  • target: ID of the target node (required)
  • id: Unique edge identifier (auto-generated if not provided)
  • data: Custom data dict (defaults to {})
required

Raises:

Type Description
ValueError

If the edge is missing required fields (source, target) or if validation is enabled and the data doesn't match the schema.

Examples:

Add a simple edge:

>>> flow = ReactFlow()
>>> flow.add_edge({
...     "id": "e1",
...     "source": "n1",
...     "target": "n2"
... })

Add an edge using EdgeSpec:

>>> from panel_reactflow import EdgeSpec
>>> flow.add_edge(EdgeSpec(
...     id="e2",
...     source="n2",
...     target="n3",
...     label="Connection"
... ))

Add a typed edge with data:

>>> flow.add_edge(EdgeSpec(
...     id="weighted1",
...     source="n1",
...     target="n3",
...     type="weighted",
...     data={"weight": 0.75}
... ))

Add an edge with styling:

>>> flow.add_edge(EdgeSpec(
...     id="e3",
...     source="n3",
...     target="n4",
...     style={"stroke": "#ff0000", "strokeWidth": 3},
...     markerEnd={"type": "arrowclosed", "color": "#ff0000"}
... ))
See Also

remove_edge : Remove an edge from the graph EdgeSpec : Helper for constructing edge dictionaries

Source code in src/panel_reactflow/base.py
def add_edge(self, edge: dict[str, Any] | EdgeSpec | Edge) -> None:
    """Add an edge to the graph.

    Adds a new edge connecting two nodes with optional validation. If no
    ``id`` is provided, one will be automatically generated based on the
    source and target nodes.

    Parameters
    ----------
    edge : dict or EdgeSpec or Edge
        Edge dictionary, :class:`EdgeSpec`, or :class:`Edge` instance to add. Required
        fields are ``source`` and ``target``. Other fields have defaults:

        - ``source``: ID of the source node (required)
        - ``target``: ID of the target node (required)
        - ``id``: Unique edge identifier (auto-generated if not provided)
        - ``data``: Custom data dict (defaults to ``{}``)

    Raises
    ------
    ValueError
        If the edge is missing required fields (``source``, ``target``)
        or if validation is enabled and the data doesn't match the schema.

    Examples
    --------
    Add a simple edge:

    >>> flow = ReactFlow()
    >>> flow.add_edge({
    ...     "id": "e1",
    ...     "source": "n1",
    ...     "target": "n2"
    ... })

    Add an edge using EdgeSpec:

    >>> from panel_reactflow import EdgeSpec
    >>> flow.add_edge(EdgeSpec(
    ...     id="e2",
    ...     source="n2",
    ...     target="n3",
    ...     label="Connection"
    ... ))

    Add a typed edge with data:

    >>> flow.add_edge(EdgeSpec(
    ...     id="weighted1",
    ...     source="n1",
    ...     target="n3",
    ...     type="weighted",
    ...     data={"weight": 0.75}
    ... ))

    Add an edge with styling:

    >>> flow.add_edge(EdgeSpec(
    ...     id="e3",
    ...     source="n3",
    ...     target="n4",
    ...     style={"stroke": "#ff0000", "strokeWidth": 3},
    ...     markerEnd={"type": "arrowclosed", "color": "#ff0000"}
    ... ))

    See Also
    --------
    remove_edge : Remove an edge from the graph
    EdgeSpec : Helper for constructing edge dictionaries
    """
    raw_edge = self._coerce_edge(edge)
    payload = self._edge_payload(raw_edge)
    payload.setdefault("data", {})
    if not payload.get("id"):
        payload["id"] = self._generate_edge_id(payload["source"], payload["target"])
    if isinstance(raw_edge, Edge):
        raw_edge.id = payload["id"]
        raw_edge.data = dict(payload["data"])
        raw_edge.flow = self
        self._sync_edge_data_params_from_data(raw_edge)
    self._validate_graph_payload(payload, kind="edge")
    if self.validate_on_add:
        edge_type = payload.get("type")
        schema = self._get_edge_schema(edge_type) if edge_type else None
        _validate_data(payload.get("data", {}), schema)
    self.edges = self.edges + [raw_edge if isinstance(raw_edge, Edge) else payload]
    self._emit("edge_added", {"type": "edge_added", "edge": payload})

add_node(node)

Add a node to the graph.

Adds a new node to the graph with optional validation. If a view is included in the node dict or :class:NodeSpec, it will be embedded inside the node and rendered as Panel content.

Parameters:

Name Type Description Default
node dict or NodeSpec or Node

Node dictionary, :class:NodeSpec, or :class:Node instance to add. The only required field is id. Other fields have defaults:

  • id: Unique node identifier (required)
  • position: Dict with x and y coordinates (defaults to {"x": 0.0, "y": 0.0})
  • type: Node type (defaults to "panel")
  • data: Custom data dict (defaults to {})
required

Raises:

Type Description
ValueError

If the node is missing the required id field or if validation is enabled and the data doesn't match the schema.

Examples:

Add a simple node:

>>> flow = ReactFlow()
>>> flow.add_node({
...     "id": "n1",
...     "position": {"x": 0, "y": 0},
...     "type": "panel",
...     "label": "My Node",
...     "data": {}
... })

Add a node using NodeSpec:

>>> from panel_reactflow import NodeSpec
>>> flow.add_node(NodeSpec(
...     id="n2",
...     position={"x": 100, "y": 100},
...     label="Another Node"
... ))

Add a node with embedded view via NodeSpec:

>>> import panel as pn
>>> flow.add_node(NodeSpec(
...     id="plot1",
...     position={"x": 200, "y": 0},
...     view=pn.pane.Markdown("# Hello World")
... ))

Add a typed node with data:

>>> flow.add_node(NodeSpec(
...     id="filter1",
...     type="filter",
...     position={"x": 300, "y": 100},
...     data={"threshold": 0.7, "operation": "gt"}
... ))
See Also

remove_node : Remove a node from the graph NodeSpec : Helper for constructing node dictionaries

Source code in src/panel_reactflow/base.py
def add_node(self, node: dict[str, Any] | NodeSpec | Node) -> None:
    """Add a node to the graph.

    Adds a new node to the graph with optional validation. If a ``view``
    is included in the node dict or :class:`NodeSpec`, it will be embedded
    inside the node and rendered as Panel content.

    Parameters
    ----------
    node : dict or NodeSpec or Node
        Node dictionary, :class:`NodeSpec`, or :class:`Node` instance to add. The only
        required field is ``id``. Other fields have defaults:

        - ``id``: Unique node identifier (required)
        - ``position``: Dict with ``x`` and ``y`` coordinates
          (defaults to ``{"x": 0.0, "y": 0.0}``)
        - ``type``: Node type (defaults to ``"panel"``)
        - ``data``: Custom data dict (defaults to ``{}``)

    Raises
    ------
    ValueError
        If the node is missing the required ``id`` field or if
        validation is enabled and the data doesn't match the schema.

    Examples
    --------
    Add a simple node:

    >>> flow = ReactFlow()
    >>> flow.add_node({
    ...     "id": "n1",
    ...     "position": {"x": 0, "y": 0},
    ...     "type": "panel",
    ...     "label": "My Node",
    ...     "data": {}
    ... })

    Add a node using NodeSpec:

    >>> from panel_reactflow import NodeSpec
    >>> flow.add_node(NodeSpec(
    ...     id="n2",
    ...     position={"x": 100, "y": 100},
    ...     label="Another Node"
    ... ))

    Add a node with embedded view via NodeSpec:

    >>> import panel as pn
    >>> flow.add_node(NodeSpec(
    ...     id="plot1",
    ...     position={"x": 200, "y": 0},
    ...     view=pn.pane.Markdown("# Hello World")
    ... ))

    Add a typed node with data:

    >>> flow.add_node(NodeSpec(
    ...     id="filter1",
    ...     type="filter",
    ...     position={"x": 300, "y": 100},
    ...     data={"threshold": 0.7, "operation": "gt"}
    ... ))

    See Also
    --------
    remove_node : Remove a node from the graph
    NodeSpec : Helper for constructing node dictionaries
    """
    raw_node = self._coerce_node(node)
    payload = self._node_payload(raw_node)
    payload.setdefault("type", "panel")
    payload.setdefault("data", {})
    payload.setdefault("position", {"x": 0.0, "y": 0.0})
    payload.setdefault("selected", False)
    payload.setdefault("draggable", True)
    payload.setdefault("connectable", True)
    payload.setdefault("deletable", True)
    if isinstance(raw_node, Node):
        raw_node.type = payload["type"]
        raw_node.data = dict(payload["data"])
        raw_node.position = dict(payload["position"])
        raw_node.selected = payload["selected"]
        raw_node.draggable = payload["draggable"]
        raw_node.connectable = payload["connectable"]
        raw_node.deletable = payload["deletable"]
        raw_node.flow = self
        self._sync_node_data_params_from_data(raw_node)
    self._validate_graph_payload(payload, kind="node")
    if self.validate_on_add:
        schema = self._get_node_schema(payload.get("type", "panel"))
        _validate_data(payload.get("data", {}), schema)
    self.nodes = self.nodes + [raw_node if isinstance(raw_node, Node) else payload]
    self._emit("node_added", {"type": "node_added", "node": payload})

close_popup()

Dismiss the popup shown by :meth:show_popup, if any.

Source code in src/panel_reactflow/base.py
def close_popup(self) -> None:
    """Dismiss the popup shown by :meth:`show_popup`, if any."""
    self._value_popup = None
    self._value_popup_position = None

from_networkx(graph, *, node_type='panel', default_position=(0.0, 0.0)) classmethod

Create a ReactFlow instance from a NetworkX graph.

Converts a NetworkX graph into a ReactFlow component, extracting node positions, labels, and data from node/edge attributes. This enables seamless integration with NetworkX's graph creation and analysis capabilities.

Parameters:

Name Type Description Default
graph Graph

A NetworkX graph instance (directed or undirected). Node attributes are converted to node data, and edge attributes to edge data.

required
node_type str

Default node type assigned to all nodes. Use a custom type if you want schema validation or custom rendering.

"panel"
default_position tuple of float

Default (x, y) position used when a node doesn't have a position attribute. Nodes can specify position via a position attribute as either a dict {"x": ..., "y": ...} or tuple/list [x, y].

(0.0, 0.0)

Returns:

Type Description
ReactFlow

A new ReactFlow instance populated with nodes and edges from the NetworkX graph.

Examples:

Create from a simple NetworkX graph:

>>> import networkx as nx
>>> from panel_reactflow import ReactFlow
>>>
>>> G = nx.DiGraph()
>>> G.add_node("A", position={"x": 0, "y": 0}, label="Start")
>>> G.add_node("B", position={"x": 100, "y": 0}, label="Process")
>>> G.add_node("C", position={"x": 200, "y": 0}, label="End")
>>> G.add_edge("A", "B", weight=0.5)
>>> G.add_edge("B", "C", weight=0.8)
>>>
>>> flow = ReactFlow.from_networkx(G)

Use with NetworkX graph generators:

>>> G = nx.karate_club_graph()
>>> # Add positions using a layout algorithm
>>> pos = nx.spring_layout(G, scale=500)
>>> for node_id, (x, y) in pos.items():
...     G.nodes[node_id]["position"] = {"x": x, "y": y}
>>>
>>> flow = ReactFlow.from_networkx(G)

Custom node type and attributes:

>>> G = nx.DiGraph()
>>> G.add_node("filter1", position=[0, 0], threshold=0.5, op="gt")
>>> G.add_node("filter2", position=[100, 0], threshold=0.7, op="lt")
>>> G.add_edge("filter1", "filter2", label="pipe")
>>>
>>> flow = ReactFlow.from_networkx(G, node_type="filter")
Notes

Node attributes are converted as follows: - position: Used directly (converted to dict if tuple/list) - label: Used as node label - type: Overrides the default node_type parameter - data: Merged with other attributes as node data - All other attributes become node data properties

Edge attributes are converted as follows: - label: Used as edge label - type: Used as edge type - data: Merged with other attributes as edge data - All other attributes become edge data properties - For MultiDiGraphs, the edge key becomes the edge ID

See Also

to_networkx : Convert ReactFlow to NetworkX graph

Source code in src/panel_reactflow/base.py
@classmethod
def from_networkx(
    cls,
    graph,
    *,
    node_type: str = "panel",
    default_position: tuple[float, float] = (0.0, 0.0),
) -> "ReactFlow":
    """Create a ReactFlow instance from a NetworkX graph.

    Converts a NetworkX graph into a ReactFlow component, extracting
    node positions, labels, and data from node/edge attributes. This
    enables seamless integration with NetworkX's graph creation and
    analysis capabilities.

    Parameters
    ----------
    graph : networkx.Graph
        A NetworkX graph instance (directed or undirected). Node attributes
        are converted to node data, and edge attributes to edge data.
    node_type : str, default "panel"
        Default node type assigned to all nodes. Use a custom type if you
        want schema validation or custom rendering.
    default_position : tuple of float, default (0.0, 0.0)
        Default (x, y) position used when a node doesn't have a ``position``
        attribute. Nodes can specify position via a ``position`` attribute
        as either a dict ``{"x": ..., "y": ...}`` or tuple/list ``[x, y]``.

    Returns
    -------
    ReactFlow
        A new ReactFlow instance populated with nodes and edges from the
        NetworkX graph.

    Examples
    --------
    Create from a simple NetworkX graph:

    >>> import networkx as nx
    >>> from panel_reactflow import ReactFlow
    >>>
    >>> G = nx.DiGraph()
    >>> G.add_node("A", position={"x": 0, "y": 0}, label="Start")
    >>> G.add_node("B", position={"x": 100, "y": 0}, label="Process")
    >>> G.add_node("C", position={"x": 200, "y": 0}, label="End")
    >>> G.add_edge("A", "B", weight=0.5)
    >>> G.add_edge("B", "C", weight=0.8)
    >>>
    >>> flow = ReactFlow.from_networkx(G)

    Use with NetworkX graph generators:

    >>> G = nx.karate_club_graph()
    >>> # Add positions using a layout algorithm
    >>> pos = nx.spring_layout(G, scale=500)
    >>> for node_id, (x, y) in pos.items():
    ...     G.nodes[node_id]["position"] = {"x": x, "y": y}
    >>>
    >>> flow = ReactFlow.from_networkx(G)

    Custom node type and attributes:

    >>> G = nx.DiGraph()
    >>> G.add_node("filter1", position=[0, 0], threshold=0.5, op="gt")
    >>> G.add_node("filter2", position=[100, 0], threshold=0.7, op="lt")
    >>> G.add_edge("filter1", "filter2", label="pipe")
    >>>
    >>> flow = ReactFlow.from_networkx(G, node_type="filter")

    Notes
    -----
    Node attributes are converted as follows:
    - ``position``: Used directly (converted to dict if tuple/list)
    - ``label``: Used as node label
    - ``type``: Overrides the default ``node_type`` parameter
    - ``data``: Merged with other attributes as node data
    - All other attributes become node data properties

    Edge attributes are converted as follows:
    - ``label``: Used as edge label
    - ``type``: Used as edge type
    - ``data``: Merged with other attributes as edge data
    - All other attributes become edge data properties
    - For MultiDiGraphs, the edge key becomes the edge ID

    See Also
    --------
    to_networkx : Convert ReactFlow to NetworkX graph
    """
    nodes: list[dict[str, Any]] = []
    edges: list[dict[str, Any]] = []
    for node_id, attrs in graph.nodes(data=True):
        attrs = dict(attrs)  # avoids mutating the original graph
        position = attrs.pop("position", {"x": default_position[0], "y": default_position[1]})
        if isinstance(position, (tuple, list)):
            position = {"x": position[0], "y": position[1]}
        label = attrs.pop("label", None)
        node_data = dict(attrs)
        node_data.pop("type", None)
        embedded_data = node_data.pop("data", None)
        if isinstance(embedded_data, dict):
            node_data = {**embedded_data, **node_data}
        node_payload = {"id": str(node_id), "position": position, "type": node_type, "data": node_data}
        if label is not None:
            node_payload["label"] = label
        nodes.append(node_payload)
    if graph.is_multigraph():
        edge_iter = graph.edges(keys=True, data=True)
    else:
        edge_iter = ((source, target, None, attrs) for source, target, attrs in graph.edges(data=True))
    for source, target, key, attrs in edge_iter:
        edge_data = dict(attrs)
        embedded_edge_data = edge_data.pop("data", None)
        if isinstance(embedded_edge_data, dict):
            edge_data = {**embedded_edge_data, **edge_data}
        label = edge_data.pop("label", None)
        edge_type = edge_data.pop("type", None)
        source_handle = edge_data.pop("sourceHandle", None)
        target_handle = edge_data.pop("targetHandle", None)
        edge_id = key if key is not None else f"{source}->{target}"
        edge = {
            "id": str(edge_id),
            "source": str(source),
            "target": str(target),
            "data": edge_data,
        }
        if label is not None:
            edge["label"] = label
        if edge_type is not None:
            edge["type"] = edge_type
        if source_handle is not None:
            edge["sourceHandle"] = source_handle
        if target_handle is not None:
            edge["targetHandle"] = target_handle
        edges.append(edge)
    return cls(nodes=nodes, edges=edges)

on(event_type, callback)

Register a callback for graph events.

Subscribe to events emitted by the ReactFlow component. Events are triggered by user interactions (node moves, selections, etc.) and programmatic changes (adding/removing nodes/edges).

Parameters:

Name Type Description Default
event_type str

Type of event to listen for. Use "*" to listen to all events. Available event types:

  • "node_added": Node was added to the graph
  • "node_deleted": Node was removed from the graph
  • "node_moved": Node was dragged to a new position
  • "node_clicked": Node was clicked
  • "handle_clicked": A node's input/output handle was clicked. Payload has node_id, handle_id (None for a node's unnamed default handle), direction ("input" or "output") and a screen position suitable for :meth:show_popup.
  • "edge_clicked": An edge was clicked. Payload has edge_id and a screen position suitable for :meth:show_popup.
  • "handle_hovered" / "edge_hovered": A port or edge was entered while popup_trigger="hover".
  • "handle_unhovered" / "edge_unhovered": The pointer left the inspected port or edge.
  • "node_data_changed": Node data was modified
  • "node_props_changed": Top-level node properties (label, style, type, ...) were modified
  • "edge_added": Edge was added to the graph
  • "edge_deleted": Edge was removed from the graph
  • "edge_data_changed": Edge data was modified
  • "edge_props_changed": Top-level edge properties (label, style, type, ...) were modified
  • "selection_changed": Selection changed
  • "sync": Full graph sync from frontend
  • "drop": Data of one of the drop_types was dropped onto the canvas. Payload has the matched drop_type, the dropped data (parsed from JSON when possible, otherwise the raw string; for "Files" a list of {"name", "type", "size", "content"} with each file read as text), the drop position in flow coordinates, and a target of {"node_id", "handle_id", "direction"} when dropped on a node or handle (handle_id and direction are None for a node), else None.
  • "client_error": The graph view hit a rendering error in the browser. The payload carries source, message, stack, component_stack, attempt and mode, or for source="safe_mode" the list of hidden issues.
  • "*": All events (wildcard)
required
callback callable

Function called when the event occurs. Receives the event payload dictionary as the first argument. The callback may optionally accept the ReactFlow instance as a second argument, e.g. callback(payload, flow).

required

Examples:

Listen for node movements:

>>> from panel_reactflow import ReactFlow
>>>
>>> flow = ReactFlow()
>>>
>>> def on_move(payload, flow):
...     node_id = payload["node_id"]
...     position = payload["position"]
...     print(f"Node {node_id} moved to ({position['x']}, {position['y']})")
...     print(f"Graph currently has {len(flow.nodes)} nodes")
>>>
>>> flow.on("node_moved", on_move)

Track all graph changes:

>>> def on_any_event(payload):
...     event_type = payload["type"]
...     print(f"Event: {event_type}")
>>>
>>> flow.on("*", on_any_event)

Build a workflow tracker:

>>> nodes_added = []
>>> edges_added = []
>>>
>>> def track_node(event):
...     nodes_added.append(event["node"])
>>>
>>> def track_edge(event):
...     edges_added.append(event["edge"])
>>>
>>> flow.on("node_added", track_node)
>>> flow.on("edge_added", track_edge)

React to selection changes:

>>> def on_selection(event):
...     selected_nodes = event["nodes"]
...     selected_edges = event["edges"]
...     print(f"Selected {len(selected_nodes)} nodes and {len(selected_edges)} edges")
>>>
>>> flow.on("selection_changed", on_selection)

Update analytics on data changes:

>>> def on_data_change(event):
...     node_id = event["node_id"]
...     patch = event["patch"]
...     print(f"Node {node_id} updated: {patch}")
...     # Update database, trigger recalculation, etc.
>>>
>>> flow.on("node_data_changed", on_data_change)

Show the current value of a port when its handle is clicked:

>>> import panel as pn
>>> def on_handle_clicked(payload, flow):
...     value = my_values[payload["node_id"]][payload["handle_id"]]
...     flow.show_popup(pn.pane.Markdown(f"**Value:** {value}"), payload["position"])
>>>
>>> flow.on("handle_clicked", on_handle_clicked)
Notes

Multiple callbacks can be registered for the same event type. They will be called in the order they were registered.

The "*" wildcard receives all events, making it useful for logging, debugging, or implementing undo/redo functionality.

Event payloads always include a "type" field indicating the event type, plus event-specific fields.

Source code in src/panel_reactflow/base.py
def on(self, event_type: str, callback) -> None:
    """Register a callback for graph events.

    Subscribe to events emitted by the ReactFlow component. Events are
    triggered by user interactions (node moves, selections, etc.) and
    programmatic changes (adding/removing nodes/edges).

    Parameters
    ----------
    event_type : str
        Type of event to listen for. Use ``"*"`` to listen to all events.
        Available event types:

        - ``"node_added"``: Node was added to the graph
        - ``"node_deleted"``: Node was removed from the graph
        - ``"node_moved"``: Node was dragged to a new position
        - ``"node_clicked"``: Node was clicked
        - ``"handle_clicked"``: A node's input/output handle was clicked.
          Payload has ``node_id``, ``handle_id`` (``None`` for a node's
          unnamed default handle), ``direction`` (``"input"`` or
          ``"output"``) and a screen ``position`` suitable for
          :meth:`show_popup`.
        - ``"edge_clicked"``: An edge was clicked. Payload has
          ``edge_id`` and a screen ``position`` suitable for
          :meth:`show_popup`.
        - ``"handle_hovered"`` / ``"edge_hovered"``: A port or edge was
          entered while ``popup_trigger="hover"``.
        - ``"handle_unhovered"`` / ``"edge_unhovered"``: The pointer left
          the inspected port or edge.
        - ``"node_data_changed"``: Node data was modified
        - ``"node_props_changed"``: Top-level node properties (``label``,
          ``style``, ``type``, ...) were modified
        - ``"edge_added"``: Edge was added to the graph
        - ``"edge_deleted"``: Edge was removed from the graph
        - ``"edge_data_changed"``: Edge data was modified
        - ``"edge_props_changed"``: Top-level edge properties (``label``,
          ``style``, ``type``, ...) were modified
        - ``"selection_changed"``: Selection changed
        - ``"sync"``: Full graph sync from frontend
        - ``"drop"``: Data of one of the ``drop_types`` was dropped onto
          the canvas. Payload has the matched ``drop_type``, the dropped
          ``data`` (parsed from JSON when possible, otherwise the raw
          string; for ``"Files"`` a list of ``{"name", "type", "size",
          "content"}`` with each file read as text), the drop
          ``position`` in flow coordinates, and a
          ``target`` of ``{"node_id", "handle_id", "direction"}`` when
          dropped on a node or handle (``handle_id`` and ``direction``
          are ``None`` for a node), else ``None``.
        - ``"client_error"``: The graph view hit a rendering error in the
          browser. The payload carries ``source``, ``message``, ``stack``,
          ``component_stack``, ``attempt`` and ``mode``, or for
          ``source="safe_mode"`` the list of hidden ``issues``.
        - ``"*"``: All events (wildcard)
    callback : callable
        Function called when the event occurs. Receives the event payload
        dictionary as the first argument. The callback may optionally
        accept the ``ReactFlow`` instance as a second argument, e.g.
        ``callback(payload, flow)``.

    Examples
    --------
    Listen for node movements:

    >>> from panel_reactflow import ReactFlow
    >>>
    >>> flow = ReactFlow()
    >>>
    >>> def on_move(payload, flow):
    ...     node_id = payload["node_id"]
    ...     position = payload["position"]
    ...     print(f"Node {node_id} moved to ({position['x']}, {position['y']})")
    ...     print(f"Graph currently has {len(flow.nodes)} nodes")
    >>>
    >>> flow.on("node_moved", on_move)

    Track all graph changes:

    >>> def on_any_event(payload):
    ...     event_type = payload["type"]
    ...     print(f"Event: {event_type}")
    >>>
    >>> flow.on("*", on_any_event)

    Build a workflow tracker:

    >>> nodes_added = []
    >>> edges_added = []
    >>>
    >>> def track_node(event):
    ...     nodes_added.append(event["node"])
    >>>
    >>> def track_edge(event):
    ...     edges_added.append(event["edge"])
    >>>
    >>> flow.on("node_added", track_node)
    >>> flow.on("edge_added", track_edge)

    React to selection changes:

    >>> def on_selection(event):
    ...     selected_nodes = event["nodes"]
    ...     selected_edges = event["edges"]
    ...     print(f"Selected {len(selected_nodes)} nodes and {len(selected_edges)} edges")
    >>>
    >>> flow.on("selection_changed", on_selection)

    Update analytics on data changes:

    >>> def on_data_change(event):
    ...     node_id = event["node_id"]
    ...     patch = event["patch"]
    ...     print(f"Node {node_id} updated: {patch}")
    ...     # Update database, trigger recalculation, etc.
    >>>
    >>> flow.on("node_data_changed", on_data_change)

    Show the current value of a port when its handle is clicked:

    >>> import panel as pn
    >>> def on_handle_clicked(payload, flow):
    ...     value = my_values[payload["node_id"]][payload["handle_id"]]
    ...     flow.show_popup(pn.pane.Markdown(f"**Value:** {value}"), payload["position"])
    >>>
    >>> flow.on("handle_clicked", on_handle_clicked)

    Notes
    -----
    Multiple callbacks can be registered for the same event type.
    They will be called in the order they were registered.

    The ``"*"`` wildcard receives all events, making it useful for
    logging, debugging, or implementing undo/redo functionality.

    Event payloads always include a ``"type"`` field indicating the
    event type, plus event-specific fields.
    """
    self._event_handlers.setdefault(event_type, []).append(callback)

patch_edge_data(edge_id, patch)

Update specific properties in an edge's data dictionary.

Merges the provided patch dictionary into the edge's existing data dict, allowing you to update individual properties without replacing the entire data object.

Parameters:

Name Type Description Default
edge_id str

Unique identifier of the edge to update.

required
patch dict

Dictionary of key-value pairs to merge into the edge's data. Existing keys will be updated, new keys will be added.

required

Raises:

Type Description
ValueError

If validation is enabled (validate_on_patch=True) and the patched data doesn't match the edge type's schema.

Examples:

Update edge properties:

>>> flow = ReactFlow()
>>> flow.add_edge(EdgeSpec(
...     id="e1",
...     source="n1",
...     target="n2",
...     data={"weight": 0.5, "label": "weak"}
... ))
>>>
>>> # Update just the weight
>>> flow.patch_edge_data("e1", {"weight": 0.9, "label": "strong"})
Notes

This method is typically called automatically by editors when users modify edge properties in the UI. The patch is also sent to the frontend to keep the visualization in sync.

A label key is kept in data and mirrored onto the edge's top-level label, which is what React Flow renders. Every other key is treated as opaque data; use :meth:patch_edge_props for the remaining presentational fields.

See Also

patch_node_data : Update node data properties patch_edge_props : Update top-level edge properties add_edge : Add a new edge to the graph

Source code in src/panel_reactflow/base.py
def patch_edge_data(self, edge_id: str, patch: dict[str, Any]) -> None:
    """Update specific properties in an edge's data dictionary.

    Merges the provided patch dictionary into the edge's existing ``data``
    dict, allowing you to update individual properties without replacing
    the entire data object.

    Parameters
    ----------
    edge_id : str
        Unique identifier of the edge to update.
    patch : dict
        Dictionary of key-value pairs to merge into the edge's ``data``.
        Existing keys will be updated, new keys will be added.

    Raises
    ------
    ValueError
        If validation is enabled (``validate_on_patch=True``) and the
        patched data doesn't match the edge type's schema.

    Examples
    --------
    Update edge properties:

    >>> flow = ReactFlow()
    >>> flow.add_edge(EdgeSpec(
    ...     id="e1",
    ...     source="n1",
    ...     target="n2",
    ...     data={"weight": 0.5, "label": "weak"}
    ... ))
    >>>
    >>> # Update just the weight
    >>> flow.patch_edge_data("e1", {"weight": 0.9, "label": "strong"})

    Notes
    -----
    This method is typically called automatically by editors when users
    modify edge properties in the UI. The patch is also sent to the
    frontend to keep the visualization in sync.

    A ``label`` key is kept in ``data`` *and* mirrored onto the edge's
    top-level label, which is what React Flow renders. Every other key is
    treated as opaque data; use :meth:`patch_edge_props` for the remaining
    presentational fields.

    See Also
    --------
    patch_node_data : Update node data properties
    patch_edge_props : Update top-level edge properties
    add_edge : Add a new edge to the graph
    """
    self._apply_data_patch(
        items=self.edges,
        item_id=edge_id,
        patch=patch,
        get_id=self._edge_id,
        get_data=self._edge_data,
        set_data=self._edge_set_data,
        get_schema=lambda edge: self._get_edge_schema(self._edge_type(edge)) if self._edge_type(edge) else None,
        sync_from_data=self._sync_edge_data_params_from_data,
        instance_cls=Edge,
    )
    self._send_msg({"type": "patch_edge_data", "edge_id": edge_id, "patch": patch})
    self._emit("edge_data_changed", {"type": "edge_data_changed", "edge_id": edge_id, "patch": patch})
    mirrored = self._mirrored_props(patch, Edge._mirrored_data_keys)
    if mirrored:
        self.patch_edge_props(edge_id, mirrored)

patch_edge_props(edge_id, patch)

Update top-level properties of an edge.

Sends an incremental patch to the frontend, updating fields that live outside the edge's data dictionary (label, style, type, markerEnd, ...) without re-serializing the whole edges list.

Assigning to the corresponding parameter of an :class:Edge instance calls this method for you, so this is mainly useful for edges defined as plain dictionaries and for the frontend-driven selected field.

Parameters:

Name Type Description Default
edge_id str

Unique identifier of the edge to update.

required
patch dict

Mapping of property names to new values. Supported keys are source, target, label, type, selected, style, markerEnd, sourceHandle and targetHandle. Passing None clears the property so the edge falls back to the CSS/theme default.

required

Raises:

Type Description
ValueError

If patch contains a key that is not a top-level edge property.

Examples:

Highlight an edge and switch it to a step router:

>>> flow.patch_edge_props("e1", {"style": {"stroke": "#ef4444", "strokeWidth": 6}, "type": "step"})

Clear the style so the theme default applies again:

>>> flow.patch_edge_props("e1", {"style": None})
See Also

patch_edge_data : Update the edge's data dictionary patch_node_props : Update top-level node properties

Source code in src/panel_reactflow/base.py
def patch_edge_props(self, edge_id: str, patch: dict[str, Any]) -> None:
    """Update top-level properties of an edge.

    Sends an incremental patch to the frontend, updating fields that live
    outside the edge's ``data`` dictionary (``label``, ``style``, ``type``,
    ``markerEnd``, ...) without re-serializing the whole ``edges`` list.

    Assigning to the corresponding parameter of an :class:`Edge` instance
    calls this method for you, so this is mainly useful for edges defined
    as plain dictionaries and for the frontend-driven ``selected`` field.

    Parameters
    ----------
    edge_id : str
        Unique identifier of the edge to update.
    patch : dict
        Mapping of property names to new values. Supported keys are
        ``source``, ``target``, ``label``, ``type``, ``selected``,
        ``style``, ``markerEnd``, ``sourceHandle`` and ``targetHandle``.
        Passing ``None`` clears the property so the edge falls back to
        the CSS/theme default.

    Raises
    ------
    ValueError
        If *patch* contains a key that is not a top-level edge property.

    Examples
    --------
    Highlight an edge and switch it to a step router:

    >>> flow.patch_edge_props("e1", {"style": {"stroke": "#ef4444", "strokeWidth": 6}, "type": "step"})

    Clear the style so the theme default applies again:

    >>> flow.patch_edge_props("e1", {"style": None})

    See Also
    --------
    patch_edge_data : Update the edge's ``data`` dictionary
    patch_node_props : Update top-level node properties
    """
    self._validate_prop_patch(patch, kind="edge", allowed=Edge._props)
    for edge in self.edges:
        if self._edge_id(edge) == edge_id:
            self._apply_prop_patch(edge, patch)
            break
    self._send_msg({"type": "patch_edge_props", "edge_id": edge_id, "patch": patch})
    self._emit("edge_props_changed", {"type": "edge_props_changed", "edge_id": edge_id, "patch": patch})

patch_node_data(node_id, patch)

Update specific properties in a node's data dictionary.

Merges the provided patch dictionary into the node's existing data dict, allowing you to update individual properties without replacing the entire data object.

Parameters:

Name Type Description Default
node_id str

Unique identifier of the node to update.

required
patch dict

Dictionary of key-value pairs to merge into the node's data. Existing keys will be updated, new keys will be added.

required

Raises:

Type Description
ValueError

If validation is enabled (validate_on_patch=True) and the patched data doesn't match the node type's schema.

Examples:

Update a single property:

>>> flow = ReactFlow()
>>> flow.add_node(NodeSpec(
...     id="n1",
...     position={"x": 0, "y": 0},
...     data={"threshold": 0.5, "name": "Filter"}
... ))
>>>
>>> # Update just the threshold
>>> flow.patch_node_data("n1", {"threshold": 0.8})

Update multiple properties:

>>> flow.patch_node_data("n1", {
...     "threshold": 0.9,
...     "name": "Updated Filter"
... })
Notes

This method is typically called automatically by editors when users modify node properties in the UI. The patch is also sent to the frontend to keep the visualization in sync.

A label (or _label) key is kept in data and mirrored onto the node's top-level label, since that is where the node components read it from. Every other key is treated as opaque data; use :meth:patch_node_props for the remaining presentational fields.

See Also

patch_edge_data : Update edge data properties patch_node_props : Update top-level node properties add_node : Add a new node to the graph

Source code in src/panel_reactflow/base.py
def patch_node_data(self, node_id: str, patch: dict[str, Any]) -> None:
    """Update specific properties in a node's data dictionary.

    Merges the provided patch dictionary into the node's existing ``data``
    dict, allowing you to update individual properties without replacing
    the entire data object.

    Parameters
    ----------
    node_id : str
        Unique identifier of the node to update.
    patch : dict
        Dictionary of key-value pairs to merge into the node's ``data``.
        Existing keys will be updated, new keys will be added.

    Raises
    ------
    ValueError
        If validation is enabled (``validate_on_patch=True``) and the
        patched data doesn't match the node type's schema.

    Examples
    --------
    Update a single property:

    >>> flow = ReactFlow()
    >>> flow.add_node(NodeSpec(
    ...     id="n1",
    ...     position={"x": 0, "y": 0},
    ...     data={"threshold": 0.5, "name": "Filter"}
    ... ))
    >>>
    >>> # Update just the threshold
    >>> flow.patch_node_data("n1", {"threshold": 0.8})

    Update multiple properties:

    >>> flow.patch_node_data("n1", {
    ...     "threshold": 0.9,
    ...     "name": "Updated Filter"
    ... })

    Notes
    -----
    This method is typically called automatically by editors when users
    modify node properties in the UI. The patch is also sent to the
    frontend to keep the visualization in sync.

    A ``label`` (or ``_label``) key is kept in ``data`` *and* mirrored onto
    the node's top-level label, since that is where the node components
    read it from. Every other key is treated as opaque data; use
    :meth:`patch_node_props` for the remaining presentational fields.

    See Also
    --------
    patch_edge_data : Update edge data properties
    patch_node_props : Update top-level node properties
    add_node : Add a new node to the graph
    """
    self._apply_data_patch(
        items=self.nodes,
        item_id=node_id,
        patch=patch,
        get_id=self._node_id,
        get_data=self._node_data,
        set_data=self._node_set_data,
        get_schema=lambda node: self._get_node_schema(self._node_type(node)),
        sync_from_data=self._sync_node_data_params_from_data,
        instance_cls=Node,
    )
    self._send_msg({"type": "patch_node_data", "node_id": node_id, "patch": patch})
    self._emit("node_data_changed", {"type": "node_data_changed", "node_id": node_id, "patch": patch})
    mirrored = self._mirrored_props(patch, Node._mirrored_data_keys)
    if mirrored:
        self.patch_node_props(node_id, mirrored)

patch_node_props(node_id, patch)

Update top-level properties of a node.

Sends an incremental patch to the frontend, updating fields that live outside the node's data dictionary (label, style, type, position, ...) without re-serializing the whole nodes list.

Assigning to the corresponding parameter of a :class:Node instance calls this method for you, so this is mainly useful for nodes defined as plain dictionaries and for the frontend-driven position and selected fields.

Parameters:

Name Type Description Default
node_id str

Unique identifier of the node to update.

required
patch dict

Mapping of property names to new values. Supported keys are position, type, label, selected, draggable, connectable, deletable, style and className. Passing None clears the property so the node falls back to the CSS/theme default.

required

Raises:

Type Description
ValueError

If patch contains a key that is not a top-level node property.

Examples:

Restyle a node and rename it:

>>> flow.patch_node_props("n1", {"style": {"border": "2px solid red"}, "label": "Failed"})

Clear a style so the theme default applies again:

>>> flow.patch_node_props("n1", {"style": None})

Move a node programmatically:

>>> flow.patch_node_props("n1", {"position": {"x": 120, "y": 40}})
See Also

patch_node_data : Update the node's data dictionary patch_edge_props : Update top-level edge properties

Source code in src/panel_reactflow/base.py
def patch_node_props(self, node_id: str, patch: dict[str, Any]) -> None:
    """Update top-level properties of a node.

    Sends an incremental patch to the frontend, updating fields that live
    outside the node's ``data`` dictionary (``label``, ``style``, ``type``,
    ``position``, ...) without re-serializing the whole ``nodes`` list.

    Assigning to the corresponding parameter of a :class:`Node` instance
    calls this method for you, so this is mainly useful for nodes defined
    as plain dictionaries and for the frontend-driven ``position`` and
    ``selected`` fields.

    Parameters
    ----------
    node_id : str
        Unique identifier of the node to update.
    patch : dict
        Mapping of property names to new values. Supported keys are
        ``position``, ``type``, ``label``, ``selected``, ``draggable``,
        ``connectable``, ``deletable``, ``style`` and ``className``.
        Passing ``None`` clears the property so the node falls back to
        the CSS/theme default.

    Raises
    ------
    ValueError
        If *patch* contains a key that is not a top-level node property.

    Examples
    --------
    Restyle a node and rename it:

    >>> flow.patch_node_props("n1", {"style": {"border": "2px solid red"}, "label": "Failed"})

    Clear a style so the theme default applies again:

    >>> flow.patch_node_props("n1", {"style": None})

    Move a node programmatically:

    >>> flow.patch_node_props("n1", {"position": {"x": 120, "y": 40}})

    See Also
    --------
    patch_node_data : Update the node's ``data`` dictionary
    patch_edge_props : Update top-level edge properties
    """
    self._validate_prop_patch(patch, kind="node", allowed=Node._props)
    for node in self.nodes:
        if self._node_id(node) == node_id:
            self._apply_prop_patch(node, patch)
            break
    self._send_msg({"type": "patch_node_props", "node_id": node_id, "patch": patch})
    self._emit("node_props_changed", {"type": "node_props_changed", "node_id": node_id, "patch": patch})

remove_connection_validator(callback)

Unregister a previously added connection validator.

Source code in src/panel_reactflow/base.py
def remove_connection_validator(self, callback: Callable) -> None:
    """Unregister a previously added connection validator."""
    self._connection_validators.remove(callback)
    self.has_connection_validators = bool(self._connection_validators)

remove_edge(*edge_ids)

Remove one or more edges from the graph by their ID.

Ids may be passed as separate arguments or as a single sequence. All of them are removed in one update, i.e. edges is only assigned once, so the browser renders a single update instead of one per edge.

Parameters:

Name Type Description Default
*edge_ids str or sequence of str

Unique identifiers of the edges to remove, either as separate arguments or as a single sequence. Ids that are not part of the graph are ignored.

()

Examples:

Remove an edge:

>>> flow = ReactFlow()
>>> flow.add_edge(EdgeSpec(id="e1", source="n1", target="n2"))
>>> flow.remove_edge("e1")

Remove several edges in a single update:

>>> flow.remove_edge("e1", "e2")
>>> flow.remove_edge(["e1", "e2"])
See Also

add_edge : Add an edge to the graph remove_node : Remove one or more nodes from the graph

Source code in src/panel_reactflow/base.py
def remove_edge(self, *edge_ids: str | Sequence[str]) -> None:
    """Remove one or more edges from the graph by their ID.

    Ids may be passed as separate arguments or as a single sequence. All
    of them are removed in one update, i.e. ``edges`` is only assigned
    once, so the browser renders a single update instead of one per edge.

    Parameters
    ----------
    *edge_ids : str or sequence of str
        Unique identifiers of the edges to remove, either as separate
        arguments or as a single sequence. Ids that are not part of the
        graph are ignored.

    Examples
    --------
    Remove an edge:

    >>> flow = ReactFlow()
    >>> flow.add_edge(EdgeSpec(id="e1", source="n1", target="n2"))
    >>> flow.remove_edge("e1")

    Remove several edges in a single update:

    >>> flow.remove_edge("e1", "e2")
    >>> flow.remove_edge(["e1", "e2"])

    See Also
    --------
    add_edge : Add an edge to the graph
    remove_node : Remove one or more nodes from the graph
    """
    ids = list(dict.fromkeys(_flatten_ids(edge_ids)))
    if not ids:
        return
    id_set = set(ids)
    removed_edges = {}
    remaining_edges = []
    for edge in self.edges:
        edge_id = self._edge_id(edge)
        if edge_id in id_set:
            removed_edges.setdefault(edge_id, edge)
        else:
            remaining_edges.append(edge)
    if removed_edges:
        self.edges = remaining_edges
    for edge_id in ids:
        removed_edge = removed_edges.get(edge_id)
        if removed_edge is None:
            continue
        payload = {"type": "edge_deleted", "edge_id": edge_id}
        self._emit("edge_deleted", payload)
        if isinstance(removed_edge, Edge):
            removed_edge.flow = None
            self._invoke_edge_hook(removed_edge, "on_delete", dict(payload))
            self._invoke_edge_hook(removed_edge, "on_event", dict(payload))

remove_node(*node_ids)

Remove one or more nodes and all connected edges from the graph.

Removes the specified nodes and automatically removes any edges that are connected to them (either as source or target). This ensures the graph remains consistent.

Ids may be passed as separate arguments or as a single sequence. All of them are removed in one update, i.e. nodes and edges are each assigned once. Removing nodes one at a time instead syncs an intermediate graph to the browser per node, which React Flow renders as the nodes disappearing one by one.

Parameters:

Name Type Description Default
*node_ids str or sequence of str

Unique identifiers of the nodes to remove, either as separate arguments or as a single sequence. Ids that are not part of the graph are ignored.

()

Examples:

Remove a node:

>>> flow = ReactFlow()
>>> flow.add_node(NodeSpec(id="n1", position={"x": 0, "y": 0}))
>>> flow.add_node(NodeSpec(id="n2", position={"x": 100, "y": 0}))
>>> flow.add_edge(EdgeSpec(id="e1", source="n1", target="n2"))
>>>
>>> flow.remove_node("n1")  # Also removes edge "e1"

Remove several nodes in a single update:

>>> flow.remove_node("n1", "n2")
>>> flow.remove_node(["n1", "n2"])
See Also

add_node : Add a node to the graph remove_edge : Remove one or more edges from the graph

Source code in src/panel_reactflow/base.py
def remove_node(self, *node_ids: str | Sequence[str]) -> None:
    """Remove one or more nodes and all connected edges from the graph.

    Removes the specified nodes and automatically removes any edges that
    are connected to them (either as source or target). This ensures the
    graph remains consistent.

    Ids may be passed as separate arguments or as a single sequence. All
    of them are removed in one update, i.e. ``nodes`` and ``edges`` are
    each assigned once. Removing nodes one at a time instead syncs an
    intermediate graph to the browser per node, which React Flow renders
    as the nodes disappearing one by one.

    Parameters
    ----------
    *node_ids : str or sequence of str
        Unique identifiers of the nodes to remove, either as separate
        arguments or as a single sequence. Ids that are not part of the
        graph are ignored.

    Examples
    --------
    Remove a node:

    >>> flow = ReactFlow()
    >>> flow.add_node(NodeSpec(id="n1", position={"x": 0, "y": 0}))
    >>> flow.add_node(NodeSpec(id="n2", position={"x": 100, "y": 0}))
    >>> flow.add_edge(EdgeSpec(id="e1", source="n1", target="n2"))
    >>>
    >>> flow.remove_node("n1")  # Also removes edge "e1"

    Remove several nodes in a single update:

    >>> flow.remove_node("n1", "n2")
    >>> flow.remove_node(["n1", "n2"])

    See Also
    --------
    add_node : Add a node to the graph
    remove_edge : Remove one or more edges from the graph
    """
    ids = list(dict.fromkeys(_flatten_ids(node_ids)))
    if not ids:
        return
    id_set = set(ids)
    removed_nodes = {}
    remaining_nodes = []
    for node in self.nodes:
        node_id = self._node_id(node)
        if node_id in id_set:
            removed_nodes.setdefault(node_id, node)
        else:
            remaining_nodes.append(node)
    removed_edges = [edge for edge in self.edges if self._edge_endpoints(edge) & id_set]
    updates: dict[str, Any] = {}
    if removed_nodes:
        updates["nodes"] = remaining_nodes
    if removed_edges:
        updates["edges"] = [edge for edge in self.edges if edge not in removed_edges]
    if updates:
        self.param.update(**updates)
    # Report each edge under the first node that removed it, matching the
    # payloads emitted when removing the nodes sequentially.
    reported_edges: set[str | None] = set()
    for node_id in ids:
        deleted_edges = []
        for edge in removed_edges:
            edge_id = self._edge_id(edge)
            if edge_id in reported_edges or node_id not in self._edge_endpoints(edge):
                continue
            reported_edges.add(edge_id)
            deleted_edges.append(edge_id)
        payload = {
            "type": "node_deleted",
            "node_id": node_id,
            "deleted_edges": deleted_edges,
        }
        self._emit("node_deleted", payload)
        removed_node = removed_nodes.get(node_id)
        if isinstance(removed_node, Node):
            removed_node.flow = None
            self._invoke_node_hook(removed_node, "on_delete", dict(payload))
            self._invoke_node_hook(removed_node, "on_event", dict(payload))

show_popup(content, position)

Show a Panel viewable in a floating overlay at a screen position.

Intended for use from "handle_clicked" and "edge_clicked" callbacks to display, e.g., the current value flowing through a port or connection, but can be called for any reason.

Parameters:

Name Type Description Default
content Any

A Panel viewable (or anything pn.panel() accepts) to render inside the popup.

required
position dict[str, float]

Screen position with x/y keys, typically taken straight from the "position" field of the triggering event payload.

required

Examples:

>>> def on_handle_clicked(payload, flow):
...     value = compute_value(payload["node_id"], payload["handle_id"])
...     flow.show_popup(pn.pane.Markdown(f"Value: {value}"), payload["position"])
>>>
>>> flow.on("handle_clicked", on_handle_clicked)
See Also

close_popup : Dismiss the popup programmatically.

Notes

Set popup_trigger="hover" to use the configured dwell delay and movement distance before and after opening a value popup. Set it to "none" to disable automatic inspection events.

Source code in src/panel_reactflow/base.py
def show_popup(self, content: Any, position: dict[str, float]) -> None:
    """Show a Panel viewable in a floating overlay at a screen position.

    Intended for use from ``"handle_clicked"`` and ``"edge_clicked"``
    callbacks to display, e.g., the current value flowing through a port
    or connection, but can be called for any reason.

    Parameters
    ----------
    content
        A Panel viewable (or anything ``pn.panel()`` accepts) to render
        inside the popup.
    position
        Screen position with ``x``/``y`` keys, typically taken straight
        from the ``"position"`` field of the triggering event payload.

    Examples
    --------
    >>> def on_handle_clicked(payload, flow):
    ...     value = compute_value(payload["node_id"], payload["handle_id"])
    ...     flow.show_popup(pn.pane.Markdown(f"Value: {value}"), payload["position"])
    >>>
    >>> flow.on("handle_clicked", on_handle_clicked)

    See Also
    --------
    close_popup : Dismiss the popup programmatically.

    Notes
    -----
    Set ``popup_trigger="hover"`` to use the configured dwell delay
    and movement distance before and after opening a value popup. Set it to
    ``"none"`` to disable automatic inspection events.
    """
    self._value_popup = content
    self._value_popup_position = position

to_networkx(*, multigraph=False)

Convert the current graph to NetworkX format.

Converts the ReactFlow graph state into a NetworkX graph object, preserving node positions, types, labels, and data. Useful for graph analysis, algorithms, and integration with the NetworkX ecosystem.

Parameters:

Name Type Description Default
multigraph bool

If True, returns a MultiDiGraph allowing multiple edges between the same node pair. If False, returns a DiGraph with single edges between nodes.

False

Returns:

Type Description
DiGraph or MultiDiGraph

NetworkX graph representation with node and edge data preserved.

Node attributes include: - All properties from node["data"] - position: Node position dict - type: Node type string - label: Node label (if present)

Edge attributes include: - All properties from edge["data"] - label: Edge label (if present) - type: Edge type string (if present) - For MultiDiGraphs, key is the edge ID

Raises:

Type Description
ImportError

If NetworkX is not installed.

Examples:

Convert to NetworkX and run graph algorithms:

>>> import networkx as nx
>>> from panel_reactflow import ReactFlow, NodeSpec, EdgeSpec
>>>
>>> flow = ReactFlow()
>>> flow.add_node(NodeSpec(id="A", position={"x": 0, "y": 0}))
>>> flow.add_node(NodeSpec(id="B", position={"x": 100, "y": 0}))
>>> flow.add_node(NodeSpec(id="C", position={"x": 50, "y": 100}))
>>> flow.add_edge(EdgeSpec(id="e1", source="A", target="B"))
>>> flow.add_edge(EdgeSpec(id="e2", source="B", target="C"))
>>> flow.add_edge(EdgeSpec(id="e3", source="A", target="C"))
>>>
>>> G = flow.to_networkx()
>>>
>>> # Run NetworkX algorithms
>>> shortest = nx.shortest_path(G, "A", "C")
>>> print(shortest)  # ['A', 'C']
>>>
>>> centrality = nx.betweenness_centrality(G)
>>> print(centrality)

Convert with edge data:

>>> flow = ReactFlow()
>>> flow.add_node(NodeSpec(id="1", position={"x": 0, "y": 0}))
>>> flow.add_node(NodeSpec(id="2", position={"x": 100, "y": 0}))
>>> flow.add_edge(EdgeSpec(
...     id="e1",
...     source="1",
...     target="2",
...     data={"weight": 0.75, "distance": 10}
... ))
>>>
>>> G = flow.to_networkx()
>>> print(G["1"]["2"]["weight"])  # 0.75
See Also

from_networkx : Create ReactFlow from NetworkX graph

Source code in src/panel_reactflow/base.py
def to_networkx(self, *, multigraph: bool = False):
    """Convert the current graph to NetworkX format.

    Converts the ReactFlow graph state into a NetworkX graph object,
    preserving node positions, types, labels, and data. Useful for
    graph analysis, algorithms, and integration with the NetworkX
    ecosystem.

    Parameters
    ----------
    multigraph : bool, default False
        If ``True``, returns a ``MultiDiGraph`` allowing multiple edges
        between the same node pair. If ``False``, returns a ``DiGraph``
        with single edges between nodes.

    Returns
    -------
    networkx.DiGraph or networkx.MultiDiGraph
        NetworkX graph representation with node and edge data preserved.

        Node attributes include:
        - All properties from ``node["data"]``
        - ``position``: Node position dict
        - ``type``: Node type string
        - ``label``: Node label (if present)

        Edge attributes include:
        - All properties from ``edge["data"]``
        - ``label``: Edge label (if present)
        - ``type``: Edge type string (if present)
        - For MultiDiGraphs, ``key`` is the edge ID

    Raises
    ------
    ImportError
        If NetworkX is not installed.

    Examples
    --------
    Convert to NetworkX and run graph algorithms:

    >>> import networkx as nx
    >>> from panel_reactflow import ReactFlow, NodeSpec, EdgeSpec
    >>>
    >>> flow = ReactFlow()
    >>> flow.add_node(NodeSpec(id="A", position={"x": 0, "y": 0}))
    >>> flow.add_node(NodeSpec(id="B", position={"x": 100, "y": 0}))
    >>> flow.add_node(NodeSpec(id="C", position={"x": 50, "y": 100}))
    >>> flow.add_edge(EdgeSpec(id="e1", source="A", target="B"))
    >>> flow.add_edge(EdgeSpec(id="e2", source="B", target="C"))
    >>> flow.add_edge(EdgeSpec(id="e3", source="A", target="C"))
    >>>
    >>> G = flow.to_networkx()
    >>>
    >>> # Run NetworkX algorithms
    >>> shortest = nx.shortest_path(G, "A", "C")
    >>> print(shortest)  # ['A', 'C']
    >>>
    >>> centrality = nx.betweenness_centrality(G)
    >>> print(centrality)

    Convert with edge data:

    >>> flow = ReactFlow()
    >>> flow.add_node(NodeSpec(id="1", position={"x": 0, "y": 0}))
    >>> flow.add_node(NodeSpec(id="2", position={"x": 100, "y": 0}))
    >>> flow.add_edge(EdgeSpec(
    ...     id="e1",
    ...     source="1",
    ...     target="2",
    ...     data={"weight": 0.75, "distance": 10}
    ... ))
    >>>
    >>> G = flow.to_networkx()
    >>> print(G["1"]["2"]["weight"])  # 0.75

    See Also
    --------
    from_networkx : Create ReactFlow from NetworkX graph
    """
    try:
        import networkx as nx  # type: ignore[import-not-found]
    except Exception as exc:  # pragma: no cover
        raise ImportError("networkx is required for to_networkx.") from exc

    graph = nx.MultiDiGraph() if multigraph else nx.DiGraph()
    for node in self.nodes:
        payload = self._node_payload(node)
        data = dict(payload.get("data", {}))
        data.update({"position": payload.get("position"), "type": payload.get("type")})
        if payload.get("label") is not None:
            data["label"] = payload.get("label")
        graph.add_node(payload["id"], **data)
    for edge in self.edges:
        payload = self._edge_payload(edge)
        data = dict(payload.get("data", {}))
        if payload.get("label") is not None:
            data["label"] = payload["label"]
        if payload.get("type") is not None:
            data["type"] = payload["type"]
        if payload.get("sourceHandle") is not None:
            data["sourceHandle"] = payload["sourceHandle"]
        if payload.get("targetHandle") is not None:
            data["targetHandle"] = payload["targetHandle"]
        if multigraph:
            graph.add_edge(payload["source"], payload["target"], key=payload.get("id"), **data)
        else:
            graph.add_edge(payload["source"], payload["target"], **data)
    return graph

SchemaEditor

Bases: Editor

Smart schema-driven editor with automatic form generation.

This is the default editor used by ReactFlow. When a JSON Schema with properties is available, it automatically generates an appropriate form with widgets for each property based on the schema definition. If no schema is available or form generation fails, it gracefully falls back to a JSON editor.

The editor uses the panel_reactflow.schema.JSONSchema component to render widgets based on JSON Schema property definitions, supporting various types including strings, numbers, booleans, enums, dates, and more.

Parameters:

Name Type Description Default
data dict

Initial node or edge data dictionary. Defaults to {}.

None
schema dict

JSON Schema dictionary with a properties field defining the form fields. Each property's schema determines the widget type.

None
**kwargs

Additional keyword arguments passed to the :class:Editor base class.

{}

Examples:

The SchemaEditor is used automatically when you define node types:

>>> from panel_reactflow import ReactFlow, NodeType
>>> flow = ReactFlow(
...     node_types={
...         "transform": NodeType(
...             type="transform",
...             schema={
...                 "type": "object",
...                 "properties": {
...                     "operation": {
...                         "type": "string",
...                         "enum": ["filter", "map", "reduce"],
...                         "title": "Operation"
...                     },
...                     "threshold": {
...                         "type": "number",
...                         "minimum": 0,
...                         "maximum": 1,
...                         "title": "Threshold"
...                     }
...                 }
...             }
...         )
...     }
... )

The editor will automatically generate: - A Select widget for the "operation" property (due to enum) - A Slider widget for the "threshold" property (due to min/max)

Set as default editor explicitly:

>>> from panel_reactflow import SchemaEditor
>>> flow = ReactFlow(default_node_editor=SchemaEditor)
Notes

The editor falls back to :class:JsonEditor if: - No schema is provided - Schema has no properties field - Form generation fails (e.g., missing dependencies)

Source code in src/panel_reactflow/base.py
class SchemaEditor(Editor):
    """Smart schema-driven editor with automatic form generation.

    This is the default editor used by ReactFlow. When a JSON Schema with
    properties is available, it automatically generates an appropriate form
    with widgets for each property based on the schema definition. If no
    schema is available or form generation fails, it gracefully falls back
    to a JSON editor.

    The editor uses the ``panel_reactflow.schema.JSONSchema`` component to
    render widgets based on JSON Schema property definitions, supporting
    various types including strings, numbers, booleans, enums, dates, and
    more.

    Parameters
    ----------
    data : dict, optional
        Initial node or edge data dictionary. Defaults to ``{}``.
    schema : dict, optional
        JSON Schema dictionary with a ``properties`` field defining the
        form fields. Each property's schema determines the widget type.
    **kwargs
        Additional keyword arguments passed to the :class:`Editor` base class.

    Examples
    --------
    The SchemaEditor is used automatically when you define node types:

    >>> from panel_reactflow import ReactFlow, NodeType
    >>> flow = ReactFlow(
    ...     node_types={
    ...         "transform": NodeType(
    ...             type="transform",
    ...             schema={
    ...                 "type": "object",
    ...                 "properties": {
    ...                     "operation": {
    ...                         "type": "string",
    ...                         "enum": ["filter", "map", "reduce"],
    ...                         "title": "Operation"
    ...                     },
    ...                     "threshold": {
    ...                         "type": "number",
    ...                         "minimum": 0,
    ...                         "maximum": 1,
    ...                         "title": "Threshold"
    ...                     }
    ...                 }
    ...             }
    ...         )
    ...     }
    ... )

    The editor will automatically generate:
    - A Select widget for the "operation" property (due to enum)
    - A Slider widget for the "threshold" property (due to min/max)

    Set as default editor explicitly:

    >>> from panel_reactflow import SchemaEditor
    >>> flow = ReactFlow(default_node_editor=SchemaEditor)

    Notes
    -----
    The editor falls back to :class:`JsonEditor` if:
    - No schema is provided
    - Schema has no ``properties`` field
    - Form generation fails (e.g., missing dependencies)
    """

    def __init__(self, data=None, schema=None, **kwargs):
        super().__init__(data, schema, **kwargs)
        if self._schema and self._schema.get("properties"):
            try:
                from .schema import JSONSchema

                self._form = JSONSchema(
                    self._data,
                    schema=self._schema["properties"],
                    multi=False,
                )
                for name, widget in self._form._widgets.items():
                    widget.param.watch(
                        lambda event, _n=name: self._on_widget_change(_n, event),
                        "value",
                    )
                self._panel = self._form.layout
            except Exception:
                # Graceful fallback if JSONSchema rendering fails
                # (e.g. missing pandas dependency).
                self._init_json_fallback()
        else:
            self._init_json_fallback()

    def _init_json_fallback(self) -> None:
        self._json_editor = JSONEditor(value=self._data)
        self._json_editor.param.watch(self._on_json_change, "value")
        self._panel = self._json_editor

    def _on_widget_change(self, name: str, event: param.parameterized.Event) -> None:
        if self._on_patch is not None:
            self._on_patch({name: event.new})

    def _on_json_change(self, event: param.parameterized.Event) -> None:
        if self._on_patch is not None and event.new != self._data:
            self._data = event.new
            self._on_patch(event.new)

    def __panel__(self):
        return self._panel

SchemaSource dataclass

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:

Name Type Description Default
kind ('jsonschema', 'param', 'pydantic')

The schema format type:

  • "jsonschema": A standard JSON Schema dictionary
  • "param": A param.Parameterized class
  • "pydantic": A Pydantic BaseModel class
"jsonschema"
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
required

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)
Source code in src/panel_reactflow/base.py
@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

kind instance-attribute

value instance-attribute