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,
        )
        self._is_updating = False

    def _report_patch(self, patch: dict[str, Any], remove: Sequence[str] = ()) -> bool:
        """Report an edit through ``on_patch``, returning ``False`` if it was rejected.

        A ``ValueError`` (e.g. a failed ``validate_on_patch`` check) is
        logged instead of propagating out of the widget watcher that made
        the edit, so the caller can revert the widget.
        """
        if self._on_patch is None:
            return True
        try:
            if remove and _accepts_keyword(self._on_patch, "remove"):
                self._on_patch(patch, remove=list(remove))
            else:
                self._on_patch(patch)
        except ValueError as exc:
            _LOGGER.warning("Rejected edit of %s %r: %s", self._node_type or "item", self._node_id, exc)
            return False
        return True

    def _handle_json_edit(self, new: Any, editor: JSONEditor) -> None:
        """Report an edit made in a JSON editor, reverting it if rejected.

        Keys deleted in the editor are reported as ``remove`` so they are
        deleted from the graph data instead of surviving the merge.
        """
        if self._is_updating or new == self._data:
            return
        if isinstance(new, dict):
            patch, removed = _json_data_patch(self._data, new)
            if self._report_patch(patch, removed):
                with self._updating():
                    self._data = dict(new)
                return
        else:
            _LOGGER.warning("Rejected edit of %s %r: data must be a JSON object.", self._node_type or "item", self._node_id)
        with self._updating():
            editor.value = dict(self._data)

    @contextmanager
    def _updating(self):
        """Apply a change without reporting it back through ``on_patch``."""
        self._is_updating = True
        try:
            yield
        finally:
            self._is_updating = False

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=dict(self._data))
        self._editor.param.watch(self._on_json_change, "value")

    def _on_json_change(self, event: param.parameterized.Event) -> None:
        self._handle_json_edit(event.new, self._editor)

    @param.depends("_data", watch=True)
    def _sync_from_data(self) -> None:
        if self._is_updating:
            return
        with self._updating():
            self._editor.value = dict(self._data)

    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",
        "parentId",
        "extent",
        "expandParent",
        "hidden",
        "zIndex",
    )

    # 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",
        "parentId",
        "extent",
        "expandParent",
        "hidden",
        "zIndex",
    )

    # ``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.")
    parentId = param.String(default=None, allow_None=True, doc="Id of the parent (group) node; the position is relative to it.")
    extent = param.Parameter(default=None, allow_None=True, doc="'parent' or [[x0, y0], [x1, y1]] bounds the node is kept in.")
    expandParent = param.Boolean(default=None, allow_None=True, doc="Grow the parent when dragged against its edge.")
    hidden = param.Boolean(default=None, allow_None=True, doc="Hide the node and its edges.")
    zIndex = param.Integer(default=None, allow_None=True, doc="Stacking order of the node.")
    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."""
        payload = self._payload()
        view = self.__panel__()
        if view is not None:
            payload["view"] = view
        return payload

    def _payload(self) -> dict[str, Any]:
        """Return the node's dictionary without building its view."""
        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
        payload.update(_optional_props(self))
        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

expandParent = param.Boolean(default=None, allow_None=True, doc='Grow the parent when dragged against its edge.') class-attribute instance-attribute

extent = param.Parameter(default=None, allow_None=True, doc="'parent' or [[x0, y0], [x1, y1]] bounds the node is kept in.") class-attribute instance-attribute

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

hidden = param.Boolean(default=None, allow_None=True, doc='Hide the node and its edges.') 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

parentId = param.String(default=None, allow_None=True, doc='Id of the parent (group) node; the position is relative to it.') 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

zIndex = param.Integer(default=None, allow_None=True, doc='Stacking order of the node.') 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."""
    payload = self._payload()
    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
parentId str

Id of the node this node is nested in, usually a "group" node. The position of a child node is relative to its parent and the child moves with it.

None
extent str or list

"parent" keeps the node inside its parent's bounds, a [[x0, y0], [x1, y1]] pair keeps it inside that rectangle.

None
expandParent bool

Grow the parent when the node is dragged against its edge.

None
hidden bool

Hide the node and its edges.

None
zIndex int

Stacking order of the node.

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.
    parentId : str, optional
        Id of the node this node is nested in, usually a ``"group"`` node.
        The position of a child node is relative to its parent and the
        child moves with it.
    extent : str or list, optional
        ``"parent"`` keeps the node inside its parent's bounds, a
        ``[[x0, y0], [x1, y1]]`` pair keeps it inside that rectangle.
    expandParent : bool, optional
        Grow the parent when the node is dragged against its edge.
    hidden : bool, optional
        Hide the node and its edges.
    zIndex : int, optional
        Stacking order of the node.

    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
    parentId: str | None = None
    extent: str | list[list[float]] | None = None
    expandParent: bool | None = None
    hidden: bool | None = None
    zIndex: int | 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
        payload.update(_optional_props(self))
        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

expandParent = None class-attribute instance-attribute

extent = None class-attribute instance-attribute

hidden = None class-attribute instance-attribute

id instance-attribute

label = None class-attribute instance-attribute

parentId = 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

zIndex = 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
    payload.update(_optional_props(self))
    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. An optional "top" places the handle's centre that far down the node's left edge, in px for a number or as any CSS length for a string (e.g. "25%"); without one, handles are spread evenly over the node's height.

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", "type" and "top" keys, as for inputs, on the right edge. 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. An optional ``"top"``
        places the handle's centre that far down the node's left edge, in px
        for a number or as any CSS length for a string (e.g. ``"25%"``);
        without one, handles are spread evenly over the node's height.
    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"``,
        ``"type"`` and ``"top"`` keys, as for ``inputs``, on the right edge.
        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. When unset, a :class:SchemaEditor is shown only for edge types that declare a schema; other edges are selectable without opening an editor. Set to :class:SchemaEditor or :class:JsonEditor to give every edge an editor.

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, drop and node/edge editors). Set to False for read-only visualization; nodes and edges stay selectable unless selectable is also False. Context menus and popups supplied by the application are not affected and must respect this flag themselves.

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_drop_size int

Maximum total size in bytes of the data in one drop. Larger files are not read and are reported in the drop event's rejected list, so a big drop cannot exceed the websocket message limit and disconnect the session. Binary files are sent base64 encoded, which adds a third on the wire, so keep this well below Bokeh's websocket_max_message_size (20 MiB by default). 0 disables the limit.

10_000_000
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
selectable bool

Allow clicking nodes and edges to select them, independently of editable. Setting it to False clears the current selection.

True
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. Use :meth:fit_view to fit the graph into view again.

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

ReactFlow is not thread-safe. Methods such as add_node read, modify and reassign nodes/edges, so concurrent calls from several threads lose updates. Modify a flow only from the thread that owns its session, e.g. from Panel callbacks; work done in a background thread should hand its result back with pn.state.execute(callback) or doc.add_next_tick_callback(callback).

Source code in src/panel_reactflow/base.py
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
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
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.
        When unset, a :class:`SchemaEditor` is shown only for edge types
        that declare a schema; other edges are selectable without opening
        an editor. Set to :class:`SchemaEditor` or :class:`JsonEditor` to
        give every edge an editor.
    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,
        drop and node/edge editors). Set to ``False`` for read-only
        visualization; nodes and edges stay selectable unless
        ``selectable`` is also ``False``. Context menus and popups supplied
        by the application are not affected and must respect this flag
        themselves.
    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_drop_size : int, default 10_000_000
        Maximum total size in bytes of the data in one drop. Larger files
        are not read and are reported in the drop event's ``rejected``
        list, so a big drop cannot exceed the websocket message limit and
        disconnect the session. Binary files are sent base64 encoded, which
        adds a third on the wire, so keep this well below Bokeh's
        ``websocket_max_message_size`` (20 MiB by default). ``0`` disables
        the limit.
    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.
    selectable : bool, default True
        Allow clicking nodes and edges to select them, independently of
        ``editable``. Setting it to ``False`` clears the current selection.
    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.
        Use :meth:`fit_view` to fit the graph into view again.
    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

    ReactFlow is not thread-safe. Methods such as ``add_node`` read, modify
    and reassign ``nodes``/``edges``, so concurrent calls from several
    threads lose updates. Modify a flow only from the thread that owns its
    session, e.g. from Panel callbacks; work done in a background thread
    should hand its result back with ``pn.state.execute(callback)`` or
    ``doc.add_next_tick_callback(callback)``.
    """

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

    selectable = param.Boolean(default=True, doc="Allow selecting nodes and edges, even when not editable.")

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

    max_drop_size = param.Integer(
        default=10_000_000,
        bounds=(0, None),
        doc="""
        Maximum total size in bytes of one drop. Files beyond the limit are
        not read and are listed in the drop event's ``rejected`` entries.
        Binary files are sent base64 encoded (a third larger on the wire),
        so keep this below Bokeh's ``websocket_max_message_size``. ``0``
        disables the limit.""",
    )

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

    group_delete = param.Selector(
        default="cascade",
        objects=["cascade", "ungroup"],
        doc="""
        What deleting a node that contains other nodes does, in the browser
        and in remove_node(). 'cascade' deletes the nodes nested in it as
        well; 'ungroup' deletes only that node and moves its children to its
        parent, keeping their place on the canvas and their edges.""",
    )

    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, in the order of _node_editor_ids.")
    _node_editor_ids = param.List(default=[], doc="Ids of the nodes whose editors are in _node_editor_views.")
    _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._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]] = {}
        # id -> node/edge indexes, rebuilt once per structural change so that
        # lookups by id do not scan the graph.
        self._node_index: dict[str, dict[str, Any] | Node] = {}
        self._edge_index: dict[str, dict[str, Any] | Edge] = {}
        self._first_node_by_type: dict[str, Node] = {}
        self._first_edge_by_type: dict[str, Edge] = {}
        self._schema_cache: dict[tuple[str, str], dict[str, Any] | None] = {}
        # Editors are built lazily and cached under a key describing what
        # they were built from, so that a replaced node or a type change
        # builds a fresh editor.
        self._editor_keys: dict[tuple[str, str], tuple[Any, ...]] = {}
        self._requested_node_editors: dict[str, None] = {}
        self._editor_data: dict[tuple[str, str], dict[str, Any]] = {}
        self._view_refs: list[int] = []
        self._patched_view_models: weakref.WeakSet[UIElement] = weakref.WeakSet()
        self._editor_view_refs: list[int] = []
        self._patching_editor: tuple[str, str] | None = None
        self._selected_editor_source: Any = None
        # 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"]]
        self._check_graph(params.get("nodes", []), params.get("edges", []))
        super().__init__(**params)
        self._event_handlers: dict[str, list[Callable]] = {"*": []}
        self._connection_validators: list[Callable] = []
        with param.discard_events(self):
            self._node_editors = {}
            self._edge_editors = {}
        # A single watcher handles every structural change: param deep
        # compares old and new values once per watcher, which for large
        # graphs costs more than the bookkeeping itself. The handler does
        # its own (identity based) change detection instead.
        self.param.watch(self._on_graph_change, ["nodes", "edges"], onlychanged=False)
        self.param.watch(self._normalize_specs, ["node_types", "edge_types"])
        self.param.watch(
            self._on_editor_config_change,
            ["editor_mode", "node_types", "edge_types", "node_editors", "edge_editors", "default_node_editor", "default_edge_editor"],
        )
        self.param.watch(self._update_selected_editor, ["selection", "editable"])
        self.param.watch(self._clear_selection_if_unselectable, ["selectable"])
        self._on_graph_change()

    @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")
        key = ("node", node_type)
        if key not in self._schema_cache:
            node = self._first_node_by_type.get(node_type)
            schema = node._data_schema() if node is not None else None
            self._schema_cache[key] = schema if schema and schema.get("properties") else None
        return self._schema_cache[key]

    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")
        key = ("edge", edge_type)
        if key not in self._schema_cache:
            edge = self._first_edge_by_type.get(edge_type)
            schema = edge._data_schema() if edge is not None else None
            self._schema_cache[key] = schema if schema and schema.get("properties") else None
        return self._schema_cache[key]

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

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

        Patches reported by the editor are applied with ``patch_node_data``
        for nodes and ``patch_edge_data`` for edges, without echoing the
        resulting data back into the editor that produced them.
        """
        patch_fn = self.patch_node_data if kind == "node" else self.patch_edge_data

        def on_patch(patch: dict, *, remove: Sequence[str] | None = None) -> None:
            previous = self._patching_editor
            self._patching_editor = (kind, item_id)
            try:
                if remove:
                    patch_fn(item_id, patch, remove=remove)
                else:
                    patch_fn(item_id, patch)
            finally:
                self._patching_editor = previous

        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_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]:
        # A Node's view is left out: building it is expensive and callers
        # that need it go through the view cache.
        if isinstance(node, Node):
            return node._payload()
        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_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 _rebuild_node_index(self) -> None:
        index: dict[str, dict[str, Any] | Node] = {}
        first_by_type: dict[str, Node] = {}
        for node in self.nodes:
            node_id = self._node_id(node)
            if node_id is not None:
                index.setdefault(node_id, node)
            if isinstance(node, Node):
                first_by_type.setdefault(node.type, node)
        self._node_index = index
        self._first_node_by_type = first_by_type

    def _rebuild_edge_index(self) -> None:
        index: dict[str, dict[str, Any] | Edge] = {}
        first_by_type: dict[str, Edge] = {}
        for edge in self.edges:
            edge_id = self._edge_id(edge)
            if edge_id is not None:
                index.setdefault(edge_id, edge)
            if isinstance(edge, Edge):
                first_by_type.setdefault(edge.type or "", edge)
        self._edge_index = index
        self._first_edge_by_type = first_by_type

    def _get_node(self, node_id: str, *, scan: bool = True) -> dict[str, Any] | Node | None:
        node = self._node_index.get(node_id)
        if node is not None and self._node_id(node) == node_id:
            return node
        # The index misses nodes added or re-identified in place (e.g.
        # ``flow.nodes.append(...)`` or ``node["id"] = ...``), which do not
        # trigger the watcher, so fall back to a scan and reindex.
        if scan and any(self._node_id(item) == node_id for item in self.nodes):
            self._rebuild_node_index()
            return self._node_index.get(node_id)
        return None

    def _get_edge(self, edge_id: str, *, scan: bool = True) -> dict[str, Any] | Edge | None:
        edge = self._edge_index.get(edge_id)
        if edge is not None and self._edge_id(edge) == edge_id:
            return edge
        if scan and any(self._edge_id(item) == edge_id for item in self.edges):
            self._rebuild_edge_index()
            return self._edge_index.get(edge_id)
        return None

    def _get_node_instance(self, node_id: str) -> Node | None:
        node = self._get_node(node_id)
        return node if isinstance(node, Node) else None

    def _get_edge_instance(self, edge_id: str) -> Edge | None:
        edge = self._get_edge(edge_id)
        return edge if isinstance(edge, Edge) else 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 _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:
        """Run an event callback or hook, logging instead of raising.

        The graph change that triggered the event has already been applied,
        so letting one failing callback raise would skip every later callback
        and hook for the same event (and, for multi-id operations such as
        ``remove_node("a", "b")``, every later id) while the state stays
        committed.
        """
        if _accepts_flow(callback):
            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.
        try:
            pn.state.execute(cb, schedule=False)
        except Exception:
            _LOGGER.exception(
                "panel-reactflow %r callback %r failed",
                payload.get("type") if isinstance(payload, dict) else None,
                getattr(callback, "__qualname__", callback),
            )

    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)
        # Deleted edges are gone from the graph (remove_edge runs their hooks
        # itself), so do not scan for them.
        scan = event_type != "edge_deleted"
        for edge_id in edge_ids:
            edge = self._get_edge(edge_id, scan=scan)
            if not isinstance(edge, Edge):
                continue
            if hook_name is not None:
                self._invoke_edge_hook(edge, hook_name, payload)
            self._invoke_edge_hook(edge, "on_event", payload)

    def _on_graph_change(self, *events: param.parameterized.Event) -> None:
        """Bring all derived state up to date after ``nodes``/``edges`` change.

        Everything derived from the graph (indexes, instance bookkeeping,
        selection, editors and views) is updated here, in one pass, instead
        of in a watcher per concern.
        """
        if events:
            names = {event.name for event in events if event.type == "triggered" or not self._same_items(event.old, event.new)}
            if not names:
                return
        else:
            names = {"nodes", "edges"}
        updates: dict[str, list[Any]] = {}
        if "nodes" in names:
            normalized_nodes = [self._coerce_node(node) for node in self.nodes]
            if any(n1 is not n2 for n1, n2 in zip(normalized_nodes, self.nodes, strict=False)):
                updates["nodes"] = normalized_nodes
        if "edges" in names:
            normalized_edges = [self._coerce_edge(edge) for edge in self.edges]
            if any(e1 is not e2 for e1, e2 in zip(normalized_edges, self.edges, strict=False)):
                updates["edges"] = normalized_edges
        if updates:
            # Re-enters this handler with the normalized lists.
            self.param.update(**updates)
            names -= set(updates)
            if not names:
                return
        self._schema_cache.clear()
        if "nodes" in names:
            self._rebuild_node_index()
        if "edges" in names:
            self._rebuild_edge_index()
        self._sync_instance_flow_refs()
        if "nodes" in names:
            self._update_node_data_param_watchers()
        if "edges" in names:
            self._update_edge_data_param_watchers()
        self._update_selection_from_graph()
        self._prune_editors()
        if "nodes" in names:
            self._update_views()
            self._refresh_node_editor_views()
        self._update_selected_editor()

    @staticmethod
    def _same_items(old: Any, new: Any) -> bool:
        return old is new or (isinstance(old, list) and isinstance(new, list) and len(old) == len(new) and all(o is n for o, n in zip(old, new, strict=True)))

    def _on_editor_config_change(self, *events: param.parameterized.Event) -> None:
        names = {event.name for event in events}
        self._schema_cache.clear()
        if names & {"editor_mode", "node_types", "node_editors", "default_node_editor"}:
            self._drop_editors("node")
        if names & {"edge_types", "edge_editors", "default_edge_editor"}:
            self._drop_editors("edge")
        if "editor_mode" in names:
            # Node components remount when the mode changes, which closes
            # every open toolbar.
            self._requested_node_editors.clear()
        self._refresh_node_editor_views()
        self._update_selected_editor()

    def _editor_cache(self, kind: str) -> dict[str, Any]:
        return self._node_editors if kind == "node" else self._edge_editors

    def _drop_editors(self, kind: str, item_ids: Sequence[str] | None = None) -> None:
        cache = self._editor_cache(kind)
        for item_id in list(cache) if item_ids is None else item_ids:
            cache.pop(item_id, None)
            self._editor_keys.pop((kind, item_id), None)
            self._editor_data.pop((kind, item_id), None)

    def _editor_key(self, kind: str, item: dict[str, Any] | Node | Edge) -> tuple[Any, ...]:
        """Describe what an editor is built from; a change requires a new editor."""
        if kind == "node":
            return (id(item) if isinstance(item, Node) else None, self._node_type(item))
        return (id(item) if isinstance(item, Edge) else None, self._edge_type(item))

    def _prune_editors(self) -> None:
        """Drop cached editors whose node/edge was removed, replaced or retyped."""
        for kind, index in (("node", self._node_index), ("edge", self._edge_index)):
            stale = []
            for item_id in self._editor_cache(kind):
                item = index.get(item_id)
                if item is None or self._editor_key(kind, item) != self._editor_keys.get((kind, item_id)):
                    stale.append(item_id)
                else:
                    self._sync_editor_data(kind, item_id, item)
            self._drop_editors(kind, stale)
        for node_id in [node_id for node_id in self._requested_node_editors if node_id not in self._node_index]:
            del self._requested_node_editors[node_id]

    def _sync_editor_data(self, kind: str, item_id: str, item: dict[str, Any] | Node | Edge) -> None:
        """Push data changed outside an editor into the cached editor.

        :class:`Editor` instances receive the new data on ``_data``; editors
        returned by other factories cannot be updated, so they are dropped and
        rebuilt the next time they are displayed.
        """
        key = (kind, item_id)
        if key not in self._editor_data:
            return
        data = self._node_data(item) if kind == "node" else self._edge_data(item)
        if data == self._editor_data[key]:
            return
        self._editor_data[key] = data
        if key == self._patching_editor:
            return
        editor = self._editor_cache(kind).get(item_id)
        if isinstance(editor, Editor):
            editor._data = dict(data)
        elif editor is not None:
            self._drop_editors(kind, [item_id])
            if kind == "node":
                self._refresh_node_editor_views()
            self._update_selected_editor()

    def _build_node_editor(self, node: dict[str, Any] | Node) -> Any:
        node_id = self._node_id(node)
        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
        if not callable(editor_factory):
            return editor_factory
        schema = self._get_node_schema(node_type)
        return self._create_editor(editor_factory, node_id, self._node_data(node), schema, node_type, kind="node")

    def _build_edge_editor(self, edge: dict[str, Any] | Edge) -> Any:
        edge_id = self._edge_id(edge)
        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
        schema = self._get_edge_schema(edge_type) if edge_type else None
        if not (schema and schema.get("properties")) and isinstance(edge, Edge):
            instance_schema = edge._data_schema()
            if instance_schema.get("properties"):
                schema = instance_schema
        if editor_factory is None:
            # Edges are usually selected for their own sake, so unlike
            # nodes (whose editor sits behind a toolbar toggle) only pop
            # up an editor when there is a schema to build a form from.
            if not (schema and schema.get("properties")):
                return None
            editor_factory = SchemaEditor
        if not callable(editor_factory):
            return editor_factory
        return self._create_editor(editor_factory, edge_id, self._edge_data(edge), schema, edge_type, kind="edge")

    def _get_editor(self, kind: str, item_id: str) -> Any:
        """Return the (lazily built and cached) editor for a node or edge."""
        item = self._get_node(item_id) if kind == "node" else self._get_edge(item_id)
        if item is None:
            return None
        cache = self._editor_cache(kind)
        key = self._editor_key(kind, item)
        if item_id in cache and self._editor_keys.get((kind, item_id)) == key:
            return cache[item_id]
        editor = self._build_node_editor(item) if kind == "node" else self._build_edge_editor(item)
        cache[item_id] = editor
        self._editor_keys[(kind, item_id)] = key
        self._editor_data[(kind, item_id)] = self._node_data(item) if kind == "node" else self._edge_data(item)
        return editor

    def _get_node_editor(self, node_id: str) -> Any:
        return self._get_editor("node", node_id)

    def _get_edge_editor(self, edge_id: str) -> Any:
        return self._get_editor("edge", edge_id)

    def _refresh_node_editor_views(self) -> None:
        """Ship the node editors the frontend can currently display.

        In ``"node"`` mode every node shows its editor inline. In
        ``"toolbar"`` mode only editors whose toolbar was opened are built
        (the frontend sends ``editor_requested``), and in ``"side"`` mode the
        editor is rendered through ``_selected_editor`` instead.
        """
        if self.editor_mode == "node":
            node_ids = list(self._node_index)
        elif self.editor_mode == "toolbar":
            node_ids = [node_id for node_id in self._requested_node_editors if node_id in self._node_index]
        else:
            node_ids = []
        refs = [id(self._get_node_editor(node_id)) for node_id in node_ids]
        if node_ids == self._node_editor_ids and refs == self._editor_view_refs:
            return
        self._editor_view_refs = refs
        with param.discard_events(self):
            self._node_editor_ids = node_ids
        self.param.trigger("_node_editor_ids", "_node_editor_views")

    def _request_node_editor(self, node_id: str | None) -> None:
        if node_id is None or node_id in self._requested_node_editors or node_id not in self._node_index:
            return
        try:
            self._get_node_editor(node_id)
        except Exception:
            # A broken editor factory must not take down message handling.
            _LOGGER.exception("Failed to build the editor for node %r", node_id)
            return
        # Requested editors are kept (and shipped) until their node is removed
        # or the editor mode changes, so reopening a toolbar is instant. This
        # is bounded by the number of toolbars the user opened.
        self._requested_node_editors[node_id] = None
        self._refresh_node_editor_views()

    def _on_retyped(self, kind: str) -> None:
        """Rebuild what depends on node/edge types after a type patch."""
        self._schema_cache.clear()
        if kind == "node":
            self._rebuild_node_index()
        else:
            self._rebuild_edge_index()
        self._prune_editors()
        if kind == "node":
            self._refresh_node_editor_views()
        self._update_selected_editor()

    def _clear_selection_if_unselectable(self, *_: param.parameterized.Event) -> None:
        if self.selectable or self.selection == {"nodes": [], "edges": []}:
            return
        self._handle_msg({"type": "selection_changed", "nodes": [], "edges": []})

    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 self.editable and selected_nodes and self.editor_mode == "side":
            editor = self._get_node_editor(selected_nodes[0])
        elif self.editable and selected_edges and not selected_nodes:
            editor = self._get_edge_editor(selected_edges[0])
        if editor is not None and editor is self._selected_editor_source:
            return
        self._selected_editor_source = editor
        self._selected_editor = None if editor is None else self._resolve_editor_view(editor)

    @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, old_view_models = self._get_child_model(views, doc, root, parent, comm)
        self._patch_views(views)
        children["_views"] = views
        old_models += old_view_models

        if self.editor_mode == "side":
            children["_node_editor_views"] = []
        else:
            node_editors = [self._resolve_editor_view(self._get_node_editor(node_id)) for node_id in self._node_editor_ids]
            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:
        # Every change to a child, e.g. selecting a node, re-renders all
        # children, and searching every node's models each time made a
        # selection cost time proportional to the graph.
        for model in view_models:
            if model in self._patched_view_models:
                continue
            self._patched_view_models.add(model)
            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) -> None:
        self._node_view_cache = {node_id: cached for node_id, cached in self._node_view_cache.items() if node_id in self._node_index}
        refs = [id(view) for view in map(self._node_view, self.nodes) if view is not None]
        # Rebuilding the children is expensive, so only do it when the views
        # themselves (or their order) changed.
        if refs != self._view_refs:
            self._view_refs = refs
            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"]:
                view = self._node_view(node) if isinstance(node, Node) else None
                node = self._node_payload(node)
                view = node.pop("view", view)
                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, a node with
            the same ``id`` already exists, any field other than ``view`` is
            not JSON-serializable, or 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
        """
        self.add_nodes([node])

    def add_nodes(self, nodes: Sequence[dict[str, Any] | NodeSpec | Node]) -> None:
        """Add several nodes to the graph in a single update.

        Equivalent to calling :meth:`add_node` for each node, but ``nodes`` is
        assigned only once, so the graph is synced to the browser once
        instead of once per node. Use it to build or load large graphs.

        Every node is validated before any of them is added, so if one of
        them is invalid none are added. A ``node_added`` event is emitted per
        node, in order, after all of them were added.

        Parameters
        ----------
        nodes : sequence of dict or NodeSpec or Node
            The nodes to add, in any form accepted by :meth:`add_node`.

        Raises
        ------
        ValueError
            If any node is missing a required field or, with
            ``validate_on_add``, its data does not match its type's schema.

        Examples
        --------
        >>> flow = ReactFlow()
        >>> flow.add_nodes([
        ...     NodeSpec(id=f"n{i}", position={"x": 100 * i, "y": 0})
        ...     for i in range(100)
        ... ])

        See Also
        --------
        add_node : Add a single node
        add_edges : Add several edges in a single update
        remove_node : Remove one or more nodes in a single update
        """
        # One id set for the whole batch, grown as nodes are accepted, so that
        # duplicates within the batch are caught without rescanning the graph.
        node_ids = {self._node_id(node) for node in self.nodes}
        prepared = [self._prepare_node(node, node_ids) for node in nodes]
        if not prepared:
            return
        self._check_parents([payload for _, payload in prepared], node_ids)
        for raw_node, payload in prepared:
            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.nodes = self.nodes + [raw_node if isinstance(raw_node, Node) else payload for raw_node, payload in prepared]
        for _, payload in prepared:
            self._emit("node_added", {"type": "node_added", "node": payload})

    def _prepare_node(self, node: dict[str, Any] | NodeSpec | Node, node_ids: set[Any]) -> tuple[dict[str, Any] | Node, dict[str, Any]]:
        """Coerce and validate a node to add, returning it with its payload.

        *node_ids* holds the ids of the graph plus the nodes accepted earlier
        in the batch; the node's id is added to it once it passes.
        """
        raw_node = self._coerce_node(node)
        payload = self._node_payload(raw_node)
        if isinstance(raw_node, Node):
            view = self._node_view(raw_node)
            if view is not None:
                payload["view"] = view
        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)
        self._check_node_payload(payload, node_ids)
        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)
        node_ids.add(payload["id"])
        return raw_node, payload

    def _apply_selection(self, node_ids: Sequence[str], edge_ids: Sequence[str]) -> None:
        """Set the ``selected`` flag of every node and edge from the browser selection.

        Only items whose flag actually changes are touched, and unselected
        dict items that never had the key are left alone, so that selecting
        one node in a large graph does not rewrite every node and edge.
        """
        node_set, edge_set = set(node_ids), set(edge_ids)
        with self._suppressed_prop_sync():
            for items, get_id, selected_ids in ((self.nodes, self._node_id, node_set), (self.edges, self._edge_id, edge_set)):
                for item in items:
                    selected = get_id(item) in selected_ids
                    if isinstance(item, (Node, Edge)):
                        if item.selected != selected:
                            item.selected = selected
                    elif item.get("selected", False) != selected:
                        item["selected"] = selected

    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")
                for name in _OPTIONAL_NODE_PROPS:
                    if name in payload:
                        setattr(node, name, payload[name])
                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": (_decode_dropped_files(msg.get("data")) if msg.get("drop_type") == "Files" else msg.get("data")),
                        "position": msg.get("position"),
                        "target": msg.get("target"),
                        "rejected": msg.get("rejected") or [],
                    },
                )
            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
                node = self._get_node(node_id)
                if node is not None:
                    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 []
                self._apply_selection(node_ids, edge_ids)
                self.selection = {"nodes": list(node_ids), "edges": list(edge_ids)}
                self._emit("selection_changed", msg)
            case "edge_added":
                self._add_edge_from_browser(msg.get("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 "connection_refused":
                if msg.get("source") is not None and msg.get("target") is not None:
                    self._emit("connection_refused", 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 = self._get_node_instance(node_id)
                if node is None:
                    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 "group_toggled":
                node_id = msg.get("node_id")
                if node_id is not None and self._get_node(node_id) is not None:
                    self.collapse_group(node_id, bool(msg.get("collapsed")))
            case "editor_requested":
                self._request_node_editor(msg.get("node_id"))
            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_edge_from_browser(self, edge: Any) -> None:
        """Add an edge the user connected, or undo it in the browser.

        The browser draws a new connection before Python sees it. Validators
        are re-run on the final connection since the graph may have changed
        since the drag started, and a client is not trusted to have applied
        them. A rejected edge is removed from the browser again instead of
        lingering there without existing in ``edges``.
        """
        if not isinstance(edge, dict):
            return
        edge_id = edge.get("id")
        if edge_id:
            # Rejecting a colliding id would make the browser remove every edge
            # with that id, including the one Python already owns.
            edge_ids = {self._edge_id(e) for e in self.edges}
            new_id, suffix = edge_id, 1
            while new_id in edge_ids:
                new_id, suffix = f"{edge_id}:{suffix}", suffix + 1
            edge = {**edge, "id": new_id}
        reason = None
        if self._connection_validators:
            reason = self._connection_reason(
                {
                    "source": edge.get("source"),
                    "target": edge.get("target"),
                    "sourceHandle": edge.get("sourceHandle"),
                    "targetHandle": edge.get("targetHandle"),
                }
            )
        if reason is None:
            try:
                self.add_edge(edge)
                return
            except ValueError as exc:
                reason = str(exc)
        _LOGGER.warning("panel-reactflow rejected edge %r from the browser: %s", edge.get("id"), reason)
        self._send_msg({"type": "edge_rejected", "edge_id": edge.get("id"), "reason": reason})

    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 when a drag starts,
        and again for the final connection when the browser reports the new
        edge; an edge rejected then is removed from the browser. Edges added
        from Python with :meth:`add_edge` or ``edges`` are not checked.
        """
        if not callable(callback):
            raise TypeError("Connection validator must be callable.")
        _accepts_flow(callback)
        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 _connection_reason(self, payload: dict[str, Any]) -> str | None:
        """Run the connection validators for one candidate connection."""
        for callback in self._connection_validators:
            try:
                if _accepts_flow(callback):
                    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:
                return reason
        return None

    @staticmethod
    def _handle_ids(handles: Any) -> list[Any]:
        if handles is None:
            return [None]
        if isinstance(handles, (str, dict)):
            handles = [handles]
        return [handle.get("id") if isinstance(handle, dict) else handle for handle in handles]

    def _validate_connection_request(self, msg: dict[str, Any]) -> None:
        # The browser blocks every connection until this reply arrives (or
        # times out after three seconds), so always answer, with an ``error``
        # the browser can show if the request could not be evaluated.
        reply: dict[str, Any] = {"type": "connection_validation_result", "request_id": msg.get("request_id"), "results": []}
        handle_type = msg.get("handle_type")
        if msg.get("node_id") is None or handle_type not in ("source", "target"):
            reply["error"] = "Malformed connection validation request."
            self._send_msg(reply)
            return
        try:
            reply["results"] = self._connection_candidates(msg["node_id"], msg.get("handle_id"), handle_type)
        except Exception:
            _LOGGER.exception("Connection validation failed")
            reply["results"] = []
            reply["error"] = "Connection validation failed."
        self._send_msg(reply)

    @staticmethod
    def _group_entry_side(entry: dict[str, Any], data: dict[str, Any]) -> str | None:
        """Return the side a handle_map entry applies to, None for both."""
        if entry.get("direction") is not None:
            return entry["direction"]
        for side, key in (("input", "inputs"), ("output", "outputs")):
            if entry.get("group_handle") in ReactFlow._handle_ids(data.get(key) or []):
                return side
        return None

    def _inner_ends(self, node: dict[str, Any] | Node, handle_id: str | None, direction: str) -> list[tuple[str, str | None]]:
        """Return the (node, handle) pairs a connection to this handle creates edges to.

        A handle of a collapsed group stands for the inner handles its
        ``handle_map`` maps to it; any other handle stands for itself.
        """
        node_id = self._node_id(node)
        data = self._node_data(node)
        if self._node_type(node) != "group" or not data.get("collapsed"):
            return [(node_id, handle_id)]
        ends = [
            (entry.get("node"), entry.get("handle"))
            for entry in data.get("handle_map") or []
            if entry.get("group_handle") == handle_id and self._group_entry_side(entry, data) in (None, direction)
        ]
        return ends or [(node_id, handle_id)]

    def _connection_candidates(self, node_id: str, handle_id: str | None, handle_type: str) -> list[dict[str, Any]]:
        opposite_type = "target" if handle_type == "source" else "source"
        port_key = "inputs" if opposite_type == "target" else "outputs"
        prefix = "input" if opposite_type == "target" else "output"
        dragged = self._get_node(node_id)
        dragged_ends = self._inner_ends(dragged, handle_id, "output" if handle_type == "source" else "input") if dragged is not None else [(node_id, handle_id)]
        results = []
        for node in self.nodes:
            connectable = node.connectable if isinstance(node, Node) else node.get("connectable", True)
            if connectable is False:
                continue
            candidate_id = self._node_id(node)
            if self._node_type(node) == "group":
                # A group declares its handles per node, in its data.
                node_type = self._node_data(node)
            else:
                node_type = self.node_types.get(self._node_type(node), {})
            # Handles the browser never lets a connection end on need no answer.
            if node_type.get(f"{prefix}Connectable") is False or node_type.get(f"{prefix}ConnectableEnd") is False:
                continue
            for candidate_handle in self._handle_ids(node_type.get(port_key)):
                # A connection that fans out through a collapsed group is
                # valid only if every edge it creates is.
                reason = None
                for candidate_end in self._inner_ends(node, candidate_handle, prefix):
                    for dragged_end in dragged_ends:
                        if handle_type == "source":
                            (source, source_handle), (target, target_handle) = dragged_end, candidate_end
                        else:
                            (source, source_handle), (target, target_handle) = candidate_end, dragged_end
                        payload = {"source": source, "target": target, "sourceHandle": source_handle, "targetHandle": target_handle}
                        reason = self._connection_reason(payload)
                        if reason is not None:
                            break
                    if reason is not None:
                        break
                results.append({"node_id": candidate_id, "handle_id": candidate_handle, "handle_type": opposite_type, "reason": reason})
        return 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. Nodes nested in a removed node (through
        ``parentId``) are removed with it, unless ``group_delete`` is
        ``"ungroup"``: then they move to the removed node's parent, keep
        their place on the canvas and their edges, and a ``nodes_ungrouped``
        event is emitted for the removed node right before its
        ``node_deleted``. Nested nodes removed along with their parent are
        reported first, so the events can be undone in reverse order.

        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
        released: dict[str, list[str]] = {}
        if self.group_delete == "ungroup":
            # Nested nodes are reported before their parents, and a parent's
            # nodes_ungrouped right before its node_deleted, so undoing the
            # events in reverse order restores parents before their contents.
            ids.sort(key=self._depth, reverse=True)
            released = self._release_children(ids)
        else:
            # Children go with their parent, as when deleting in the browser.
            ids += [node_id for node_id in self._descendants(ids) if node_id not in ids]
        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:
            removed_refs = {id(edge) for edge in removed_edges}
            updates["edges"] = [edge for edge in self.edges if id(edge) not in removed_refs]
        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:
            if node_id in released:
                self._emit("nodes_ungrouped", {"type": "nodes_ungrouped", "group_id": node_id, "node_ids": released[node_id]})
            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``),
            either endpoint is not a node of the graph, an edge with the same
            ``id`` already exists, the edge is not JSON-serializable, or
            validation is enabled and the data doesn't match the schema.
            Self-loops are allowed.

        Notes
        -----
        Connection validators (:meth:`add_connection_validator`) only check
        connections made in the browser, not edges added from Python.

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

        >>> flow = ReactFlow(nodes=[NodeSpec(id=f"n{i}") for i in range(1, 5)])
        >>> 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
        """
        self.add_edges([edge])

    def add_edges(self, edges: Sequence[dict[str, Any] | EdgeSpec | Edge]) -> None:
        """Add several edges to the graph in a single update.

        Equivalent to calling :meth:`add_edge` for each edge, but ``edges`` is
        assigned only once, so the graph is synced to the browser once
        instead of once per edge.

        Every edge is validated before any of them is added, so if one of
        them is invalid none are added. An ``edge_added`` event is emitted per
        edge, in order, after all of them were added.

        Parameters
        ----------
        edges : sequence of dict or EdgeSpec or Edge
            The edges to add, in any form accepted by :meth:`add_edge`.

        Raises
        ------
        ValueError
            If any edge is missing a required field or, with
            ``validate_on_add``, its data does not match its type's schema.

        Examples
        --------
        >>> flow.add_edges([
        ...     EdgeSpec(source=f"n{i}", target=f"n{i + 1}")
        ...     for i in range(99)
        ... ])

        See Also
        --------
        add_edge : Add a single edge
        add_nodes : Add several nodes in a single update
        remove_edge : Remove one or more edges in a single update
        """
        node_ids = {self._node_id(node) for node in self.nodes}
        edge_ids = {self._edge_id(edge) for edge in self.edges}
        prepared = [self._prepare_edge(edge, node_ids, edge_ids) for edge in edges]
        if not prepared:
            return
        for raw_edge, payload in prepared:
            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.edges = self.edges + [raw_edge if isinstance(raw_edge, Edge) else payload for raw_edge, payload in prepared]
        for _, payload in prepared:
            self._emit("edge_added", {"type": "edge_added", "edge": payload})

    def _prepare_edge(self, edge: dict[str, Any] | EdgeSpec | Edge, node_ids: set[Any], edge_ids: set[Any]) -> tuple[dict[str, Any] | Edge, dict[str, Any]]:
        """Coerce and validate an edge to add, returning it with its payload.

        *node_ids* are the ids of the graph's nodes and *edge_ids* those of its
        edges plus the edges accepted earlier in the batch; the edge's id is
        added to *edge_ids* once it passes.
        """
        raw_edge = self._coerce_edge(edge)
        payload = self._edge_payload(raw_edge)
        payload.setdefault("data", {})
        self._check_edge_payload(payload, node_ids, edge_ids)
        if not payload.get("id"):
            payload["id"] = self._generate_edge_id(payload["source"], payload["target"])
        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)
        edge_ids.add(payload["id"])
        return raw_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(nodes=[NodeSpec(id="n1"), NodeSpec(id="n2")])
        >>> 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,
        *,
        kind: str,
        item_id: str,
        patch: dict[str, Any],
        get_item: Callable[[str], Any],
        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,
        remove: Sequence[str] = (),
    ) -> 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``.
        """
        _ensure_jsonable(patch, f"patch for {item_id!r}")
        item = get_item(item_id)
        if item is None:
            return
        data = get_data(item)
        for key in remove:
            data.pop(key, None)
        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)
        self._sync_editor_data(kind, item_id, item)

    def patch_node_data(self, node_id: str, patch: dict[str, Any], *, remove: Sequence[str] | None = None) -> 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.
        remove : list of str, optional
            Keys to delete from the node's ``data`` before *patch* is
            merged in. Used by the JSON editors to apply deleted keys.

        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(
            kind="node",
            item_id=node_id,
            patch=patch,
            get_item=self._get_node,
            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,
            remove=remove or (),
        )
        msg = {"type": "patch_node_data", "node_id": node_id, "patch": patch, "revision": self._node_update_count}
        event = {"type": "node_data_changed", "node_id": node_id, "patch": patch}
        if remove:
            msg["remove"] = event["remove"] = list(remove)
        self._send_msg(msg)
        self._emit("node_data_changed", event)
        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], *, remove: Sequence[str] | None = None) -> 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.
        remove : list of str, optional
            Keys to delete from the edge's ``data`` before *patch* is
            merged in. Used by the JSON editors to apply deleted keys.

        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(
            kind="edge",
            item_id=edge_id,
            patch=patch,
            get_item=self._get_edge,
            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,
            remove=remove or (),
        )
        msg = {"type": "patch_edge_data", "edge_id": edge_id, "patch": patch}
        event = {"type": "edge_data_changed", "edge_id": edge_id, "patch": patch}
        if remove:
            msg["remove"] = event["remove"] = list(remove)
        self._send_msg(msg)
        self._emit("edge_data_changed", event)
        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:
            _ensure_jsonable(patch, f"{kind} property patch")
            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``, ``className``,
            ``parentId``, ``extent``, ``expandParent``, ``hidden`` and
            ``zIndex``. A new ``parentId`` does not move the node, its
            position is read relative to the new parent; use
            :meth:`set_parent` to keep it in place.
            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)
        node = self._get_node(node_id)
        if node is not None:
            self._apply_prop_patch(node, patch)
            if "type" in patch:
                self._on_retyped("node")
        self._send_msg({"type": "patch_node_props", "node_id": node_id, "patch": patch, "revision": self._node_update_count})
        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)
        edge = self._get_edge(edge_id)
        if edge is not None:
            self._apply_prop_patch(edge, patch)
            if "type" in patch:
                self._on_retyped("edge")
        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})

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

    @staticmethod
    def _node_position(node: dict[str, Any] | Node) -> dict[str, float]:
        position = (node.position if isinstance(node, Node) else node.get("position")) or {}
        return {"x": float(position.get("x", 0)), "y": float(position.get("y", 0))}

    def _descendants(self, node_ids: Sequence[str]) -> list[str]:
        """Return the ids of all nodes nested in *node_ids*, at any depth."""
        children: dict[str, list[str]] = {}
        for node in self.nodes:
            parent = self._node_parent(node)
            if parent is not None:
                children.setdefault(parent, []).append(self._node_id(node))
        if not children:
            return []
        found: dict[str, None] = {}
        stack = list(node_ids)
        while stack:
            for child in children.get(stack.pop(), ()):
                if child not in found:
                    found[child] = None
                    stack.append(child)
        return list(found)

    def _check_parents(self, payloads: Sequence[dict[str, Any]], node_ids: set[Any]) -> None:
        """Raise ValueError if a new node's parent is missing or nesting would cycle."""
        parents = {self._node_id(node): self._node_parent(node) for node in self.nodes}
        parents.update({payload["id"]: payload.get("parentId") for payload in payloads})
        for payload in payloads:
            parent = payload.get("parentId")
            if parent is None:
                continue
            if parent not in node_ids:
                raise ValueError(f"Node {payload['id']!r} references unknown parent node {parent!r}.")
            seen = {payload["id"]}
            while parent is not None:
                if parent in seen:
                    raise ValueError(f"Node {payload['id']!r} is nested in itself through parentId.")
                seen.add(parent)
                parent = parents.get(parent)

    def absolute_position(self, node_id: str) -> dict[str, float]:
        """Return the position of a node in flow coordinates.

        The ``position`` of a node nested in a group is relative to its
        parent; this adds up the positions of all of its ancestors.

        Parameters
        ----------
        node_id : str
            Id of the node.

        Returns
        -------
        dict
            The ``{"x": ..., "y": ...}`` position of the node on the canvas.

        Raises
        ------
        KeyError
            If there is no node with that id.
        """
        node = self._get_node(node_id)
        if node is None:
            raise KeyError(f"No node with id {node_id!r}.")
        x = y = 0.0
        seen: set[str] = set()
        while node is not None and self._node_id(node) not in seen:
            seen.add(self._node_id(node))
            position = self._node_position(node)
            x += position["x"]
            y += position["y"]
            parent = self._node_parent(node)
            node = self._get_node(parent) if parent is not None else None
        return {"x": x, "y": y}

    def _reparent(self, node_ids: Sequence[str], parent_id: str | None, props: dict[str, Any]) -> None:
        """Move *node_ids* into *parent_id* keeping their place on the canvas.

        Updates the nodes in place without syncing; the caller syncs ``nodes``.
        """
        origin = self.absolute_position(parent_id) if parent_id is not None else {"x": 0.0, "y": 0.0}
        absolute = {node_id: self.absolute_position(node_id) for node_id in node_ids}
        patch = {"parentId": parent_id, **props}
        with self._suppressed_prop_sync():
            for node_id in node_ids:
                node = self._get_node(node_id)
                position = {"x": absolute[node_id]["x"] - origin["x"], "y": absolute[node_id]["y"] - origin["y"]}
                if isinstance(node, Node):
                    node.position = position
                    for key, value in patch.items():
                        setattr(node, key, value)
                else:
                    node["position"] = position
                    for key, value in patch.items():
                        if value is None:
                            node.pop(key, None)
                        else:
                            node[key] = value

    def _check_reparent(self, node_ids: Sequence[str], parent_id: str | None) -> None:
        for node_id in node_ids:
            if self._get_node(node_id) is None:
                raise ValueError(f"No node with id {node_id!r}.")
        if parent_id is None:
            return
        if self._get_node(parent_id) is None:
            raise ValueError(f"No node with id {parent_id!r}.")
        if parent_id in node_ids or parent_id in self._descendants(node_ids):
            raise ValueError(f"Cannot nest node {parent_id!r} in itself.")

    def set_parent(
        self,
        node_ids: str | Sequence[str],
        parent_id: str | None,
        *,
        extent: str | list[list[float]] | None = None,
        expand_parent: bool | None = None,
    ) -> None:
        """Nest nodes in another node, or take them out of their parent.

        The nodes keep their place on the canvas: their positions are
        converted to be relative to the new parent.

        Parameters
        ----------
        node_ids : str or sequence of str
            Ids of the nodes to move.
        parent_id : str or None
            Id of the new parent, or ``None`` to put the nodes at the top
            level.
        extent : str or list, optional
            New ``extent`` of the nodes, e.g. ``"parent"``. Cleared when
            ``None``.
        expand_parent : bool, optional
            New ``expandParent`` of the nodes. Cleared when ``None``.

        Raises
        ------
        ValueError
            If a node does not exist or would be nested in itself.
        """
        ids = [node_ids] if isinstance(node_ids, str) else list(dict.fromkeys(node_ids))
        self._check_reparent(ids, parent_id)
        self._reparent(ids, parent_id, {"extent": extent, "expandParent": expand_parent})
        self.param.trigger("nodes")

    def group_nodes(
        self,
        node_ids: Sequence[str] | None = None,
        *,
        group_id: str | None = None,
        label: str | None = None,
        padding: float = 20,
        data: dict[str, Any] | None = None,
        style: dict[str, Any] | None = None,
        extent: str | list[list[float]] | None = None,
        expand_parent: bool | None = True,
    ) -> str:
        """Put nodes into a new ``"group"`` node.

        The group is placed around the nodes, which keep their place on the
        canvas and from then on move with the group. A group can be
        collapsed into a single compact node, see :meth:`collapse_group`.

        Parameters
        ----------
        node_ids : sequence of str, optional
            Ids of the nodes to group. Defaults to the selected nodes. They
            must all have the same parent, which becomes the parent of the
            group, so groups can be nested.
        group_id : str, optional
            Id of the new group. Generated when omitted.
        label : str, optional
            Label shown in the group's header.
        padding : float, default 20
            Space between the nodes and the group's border.
        data : dict, optional
            Data of the group node, e.g. ``collapsed``, ``inputs``,
            ``outputs`` and ``handle_map`` (see :meth:`collapse_group`).
        style : dict, optional
            Style of the group node. Setting both ``width`` and ``height``
            gives the group a fixed size; otherwise it grows to fit its
            children.
        extent : str or list, optional
            ``extent`` given to the grouped nodes, e.g. ``"parent"`` to keep
            them inside a fixed-size group (see ``style``). React Flow
            ignores ``"parent"`` while ``expand_parent`` is set.
        expand_parent : bool, optional, default True
            ``expandParent`` given to the grouped nodes, so dragging one
            past the border grows the group.

        Returns
        -------
        str
            The id of the new group.

        Raises
        ------
        ValueError
            If there are no nodes to group, a node does not exist, the nodes
            have different parents or the group id is taken.
        """
        ids = list(dict.fromkeys(self.selection.get("nodes", []) if node_ids is None else node_ids))
        if not ids:
            raise ValueError("No nodes to group.")
        self._check_reparent(ids, None)
        parents = {self._node_parent(self._get_node(node_id)) for node_id in ids}
        if len(parents) > 1:
            raise ValueError("Only nodes with the same parent can be grouped.")
        (parent,) = parents
        if group_id is None:
            group_id = f"group-{uuid4().hex[:8]}"
        positions = [self._node_position(self._get_node(node_id)) for node_id in ids]
        group: dict[str, Any] = {
            "id": group_id,
            "type": "group",
            "label": label,
            "position": {
                "x": min(p["x"] for p in positions) - padding,
                "y": min(p["y"] for p in positions) - padding - GROUP_HEADER_HEIGHT,
            },
            "data": dict(data or {}),
        }
        if parent is not None:
            group["parentId"] = parent
        if style is not None:
            group["style"] = style
        node_ids_in_graph = {self._node_id(node) for node in self.nodes}
        _, payload = self._prepare_node(group, node_ids_in_graph)
        self._check_parents([payload], node_ids_in_graph)
        # The group goes before its first child, React Flow draws (and
        # needs) parents before their children.
        first = min(i for i, node in enumerate(self.nodes) if self._node_id(node) in ids)
        nodes = list(self.nodes)
        nodes.insert(first, payload)
        with param.discard_events(self):
            self.nodes = nodes
        self._rebuild_node_index()
        self._reparent(ids, group_id, {"extent": extent, "expandParent": expand_parent})
        self.param.trigger("nodes")
        self._emit("node_added", {"type": "node_added", "node": payload})
        self._emit("nodes_grouped", {"type": "nodes_grouped", "group_id": group_id, "node_ids": ids})
        return group_id

    def _release_children(self, removed_ids: Sequence[str]) -> dict[str, list[str]]:
        """Move the children of nodes about to be removed to their nearest kept ancestor.

        Returns the moved children by the removed parent they were in.
        """
        removed = set(removed_ids)
        moves: dict[str | None, list[str]] = {}
        released: dict[str, list[str]] = {}
        for node in self.nodes:
            node_id, parent = self._node_id(node), self._node_parent(node)
            if node_id in removed or parent not in removed:
                continue
            target = parent
            seen: set[str] = set()
            while target in removed and target not in seen:
                seen.add(target)
                target_node = self._get_node(target)
                target = self._node_parent(target_node) if target_node is not None else None
            moves.setdefault(None if target in removed else target, []).append(node_id)
            released.setdefault(parent, []).append(node_id)
        for target, children in moves.items():
            self._reparent(children, target, {"extent": None, "expandParent": None})
        return released

    def _depth(self, node_id: str) -> int:
        depth, seen = 0, {node_id}
        node = self._get_node(node_id)
        parent = self._node_parent(node) if node is not None else None
        while parent is not None and parent not in seen:
            seen.add(parent)
            depth += 1
            node = self._get_node(parent)
            parent = self._node_parent(node) if node is not None else None
        return depth

    def ungroup(self, group_id: str) -> list[str]:
        """Dissolve a group, keeping its children where they are.

        The children of the group are moved to the group's own parent, keep
        their place on the canvas and lose the ``extent`` and
        ``expandParent`` that tied them to the group. The group node and
        edges connected to it are removed. ``nodes_ungrouped`` is emitted
        before the group's ``node_deleted``.

        Parameters
        ----------
        group_id : str
            Id of the group to dissolve.

        Returns
        -------
        list of str
            The ids of the former children.

        Raises
        ------
        ValueError
            If there is no node with that id.
        """
        group = self._get_node(group_id)
        if group is None:
            raise ValueError(f"No node with id {group_id!r}.")
        children = [self._node_id(node) for node in self.nodes if self._node_parent(node) == group_id]
        self._reparent(children, self._node_parent(group), {"extent": None, "expandParent": None})
        self._emit("nodes_ungrouped", {"type": "nodes_ungrouped", "group_id": group_id, "node_ids": children})
        # The children no longer refer to the group, so they stay, and the
        # nodes sync that removes the group carries their new positions.
        self.remove_node(group_id)
        return children

    def collapse_group(self, group_id: str, collapsed: bool = True) -> None:
        """Collapse a group into one compact node, or expand it again.

        Collapsing only changes what is drawn: the group's descendants are
        hidden and edges between them and the rest of the graph are drawn to
        the collapsed group instead. ``nodes`` and ``edges`` keep the real
        graph. The state is kept in the group's ``data["collapsed"]``.

        A collapsed group shows one input and one output handle, or the
        handles listed in ``data["inputs"]`` and ``data["outputs"]`` (in the
        format of :class:`NodeType` ``inputs``/``outputs``). An edge into a
        hidden node is drawn to the group handle that ``data["handle_map"]``
        maps it to, a list of ``{"node": ..., "handle": ..., "group_handle":
        ...}`` entries (omit ``handle`` to map every handle of the node),
        and to the group's first handle on that side otherwise. An entry
        applies to the side its group handle is declared on; set
        ``"direction"`` to ``"input"`` or ``"output"`` to choose explicitly,
        e.g. when a node has an input and an output with the same id.
        Connection validators and policies check each edge such a
        connection creates. Nodes hidden by a collapse are deselected.

        In a flow with ``editable=False`` the header chevron collapses a
        group for that viewer only and does not change ``data``. Connecting
        to a mapped group handle in the browser creates an edge to each
        node it maps to.

        Parameters
        ----------
        group_id : str
            Id of the group node.
        collapsed : bool, default True
            Whether to collapse (``True``) or expand (``False``) the group.

        Raises
        ------
        ValueError
            If there is no node with that id.
        """
        node = self._get_node(group_id)
        if node is None:
            raise ValueError(f"No node with id {group_id!r}.")
        if bool(self._node_data(node).get("collapsed", False)) == collapsed:
            return
        self.patch_node_data(group_id, {"collapsed": collapsed})
        self._emit("group_toggled", {"type": "group_toggled", "node_id": group_id, "collapsed": collapsed})

    def expand_group(self, group_id: str) -> None:
        """Expand a collapsed group, see :meth:`collapse_group`."""
        self.collapse_group(group_id, False)

    def fit_view(
        self,
        *node_ids: str | Sequence[str],
        padding: float | None = None,
        duration: int | None = None,
        min_zoom: float | None = None,
        max_zoom: float | None = None,
        include_hidden_nodes: bool = False,
    ) -> None:
        """Pan and zoom the viewport so that the graph fits into view.

        The canvas fits the view once when it is first rendered. Call this
        method to fit it again, e.g. after adding nodes or loading a new graph.
        The resulting viewport is synced back to the ``viewport`` parameter.

        Parameters
        ----------
        *node_ids : str or sequence of str
            Only fit these nodes into view, either as separate arguments or as
            a single sequence. Fits every node when omitted.
        padding : float, optional
            Space around the fitted nodes as a fraction of the viewport size.
            Defaults to React Flow's ``0.1``.
        duration : int, optional
            Length of the animated transition in milliseconds. Jumps to the
            new viewport when omitted.
        min_zoom : float, optional
            Lower zoom bound for this fit, defaults to ``min_zoom``.
        max_zoom : float, optional
            Upper zoom bound for this fit, defaults to ``max_zoom``.
        include_hidden_nodes : bool, default False
            Whether hidden nodes are included in the fitted bounds.

        Raises
        ------
        ValueError
            If a node id is not part of the graph or an option is out of range.

        Examples
        --------
        Load a new graph and fit it into view:

        >>> flow.nodes = new_nodes
        >>> flow.fit_view()

        Zoom to two nodes with an animated transition:

        >>> flow.fit_view("n1", "n2", padding=0.2, duration=500)

        Notes
        -----
        A fit requested right after ``nodes`` changed waits until the browser
        has rendered and measured those nodes, so it fits the new graph rather
        than the previous one, even when the change is held back by
        ``pn.io.hold``.

        Calling this before the component is displayed does nothing, there is
        no canvas to fit yet and the first render fits the view anyway.
        """
        ids = _flatten_ids(node_ids)
        known = {self._node_id(node) for node in self.nodes}
        unknown = [node_id for node_id in ids if node_id not in known]
        if unknown:
            raise ValueError(f"Cannot fit view to unknown node ids: {unknown}")
        if padding is not None and padding < 0:
            raise ValueError("padding must be non-negative.")
        if duration is not None and duration < 0:
            raise ValueError("duration must be non-negative.")
        for name, zoom in (("min_zoom", min_zoom), ("max_zoom", max_zoom)):
            if zoom is not None and zoom <= 0:
                raise ValueError(f"{name} must be positive.")
        options: dict[str, Any] = {}
        if ids:
            options["nodes"] = [{"id": node_id} for node_id in ids]
        if padding is not None:
            options["padding"] = padding
        if duration is not None:
            options["duration"] = duration
        if min_zoom is not None:
            options["minZoom"] = min_zoom
        if max_zoom is not None:
            options["maxZoom"] = max_zoom
        if include_hidden_nodes:
            options["includeHiddenNodes"] = True
        # The fit may reach the browser before a held ``nodes`` change does, so
        # it names the node revision it has to wait for.
        self._send_msg({"type": "fit_view", "node_revision": self._node_update_count, "options": options})

    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]] = []
        original_ids: dict[str, Any] = {}
        for node_id, attrs in graph.nodes(data=True):
            # Ids are stringified for the browser, so e.g. 1 and "1" would
            # silently become one node.
            if str(node_id) in original_ids:
                raise ValueError(
                    f"Nodes {original_ids[str(node_id)]!r} and {node_id!r} both map to the id {str(node_id)!r}; relabel the graph so node ids are unique as strings."
                )
            original_ids[str(node_id)] = node_id
            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)
        edge_ids: set[str] = set()
        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 = str(key if key is not None else f"{source}->{target}")
            if edge_id in edge_ids:
                # Multigraph keys are only unique per node pair (networkx
                # numbers parallel edges 0, 1, ...).
                edge_id = f"{source}->{target}:{key}"
            edge_ids.add(edge_id)
            edge = {
                "id": 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. Payload has ``node_id``
              and a screen ``position`` suitable for :meth:`show_popup`.
              Clicks on the node's embedded view or editor are not reported,
              and a double click emits two events. Also fires when
              ``editable=False``.
            - ``"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
            - ``"connection_refused"``: A connection dragged in the browser
              was dropped onto a handle that refuses it, so no edge was
              drawn. Payload has ``source``, ``sourceHandle``, ``target``,
              ``targetHandle`` and the ``reason`` the frontend policies or
              connection validators gave.
            - ``"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
            - ``"nodes_grouped"``: :meth:`group_nodes` put nodes into a new
              group. Payload has ``group_id`` and ``node_ids``.
            - ``"nodes_ungrouped"``: :meth:`ungroup` dissolved a group, or a
              group was deleted with ``group_delete="ungroup"``. Payload has ``group_id`` and ``node_ids`` (its former children).
            - ``"group_toggled"``: A group was collapsed or expanded, from
              its header or :meth:`collapse_group`. Payload has ``node_id``
              and ``collapsed``.
            - ``"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"}``, where ``content`` is a ``str`` for a file that
              decodes as UTF-8 text, whatever its reported MIME type, and
              ``bytes`` for any other file), the
              drop ``position`` in flow coordinates, 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``, and a ``rejected`` list of
              ``{"name", "type", "size", "reason"}`` for files that were
              not sent because they exceed ``max_drop_size`` or could not
              be read. A non-file drop larger than ``max_drop_size`` is
              sent with ``data=None`` and one ``rejected`` entry.
            - ``"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)``. An exception raised by a callback
            is logged and does not stop the remaining callbacks or hooks;
            the change that triggered the event is applied either way.

        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.
        """
        _accepts_flow(callback)
        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.
        # Callbacks are isolated from each other: a raising callback is
        # logged and the remaining callbacks and hooks still run.
        for callback in list(self._event_handlers.get(event_type, [])):
            self._invoke_node_callback(callback, payload, self)
        for callback in list(self._event_handlers.get("*", [])):
            self._invoke_node_callback(callback, payload, self)
        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)

    @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 _check_node_payload(self, payload: dict[str, Any], node_ids: set[Any] | None = None) -> None:
        """Raise ValueError if *payload* cannot be added as a new node.

        Rejects a missing or duplicate id and data that cannot be synced to
        the browser. *node_ids* are the ids already in the graph; pass a set
        when checking many nodes to avoid rebuilding it per node.
        """
        node_id = payload.get("id")
        if node_id is None or node_id == "":
            raise ValueError("Missing 'id' in node payload.")
        # The view is rendered as a Bokeh model, everything else is sent as JSON.
        _ensure_jsonable({key: value for key, value in payload.items() if key != "view"}, f"node {node_id!r}")
        if node_ids is None:
            node_ids = {self._node_id(node) for node in self.nodes}
        if node_id in node_ids:
            raise _GraphConflictError(f"A node with id {node_id!r} already exists.")

    def _check_edge_payload(
        self,
        payload: dict[str, Any],
        node_ids: set[Any] | None = None,
        edge_ids: set[Any] | None = None,
    ) -> None:
        """Raise ValueError if *payload* cannot be added as a new edge.

        Rejects a missing ``source``/``target``, endpoints that are not nodes
        of the graph, a duplicate id and data that cannot be synced to the
        browser. Self-loops are allowed. *node_ids* and *edge_ids* are the ids
        already in the graph; pass sets when checking many edges.
        """
        for key in ("source", "target"):
            if payload.get(key) is None:
                raise ValueError(f"Missing '{key}' in edge payload.")
        edge_id = payload.get("id")
        _ensure_jsonable(payload, f"edge {edge_id!r}")
        if node_ids is None:
            node_ids = {self._node_id(node) for node in self.nodes}
        for key in ("source", "target"):
            if payload[key] not in node_ids:
                raise _GraphConflictError(f"Edge {payload.get('id')!r} references unknown {key} node {payload[key]!r}.")
        if edge_id:
            if edge_ids is None:
                edge_ids = {self._edge_id(edge) for edge in self.edges}
            if edge_id in edge_ids:
                raise _GraphConflictError(f"An edge with id {edge_id!r} already exists.")

    def _check_graph(self, nodes: list[Any], edges: list[Any]) -> None:
        """Validate a complete graph passed to the constructor.

        Malformed or non-JSON items raise, since they break every sync.
        Duplicate ids and edges pointing at missing nodes only warn, to keep
        accepting graphs that rendered before these checks existed.
        """
        node_ids: set[Any] = set()
        for node in nodes:
            if isinstance(node, Node):
                # Node.to_dict() would build the node's view just for the check.
                data = dict(node.data or {})
                data.update({name: getattr(node, name) for name in node._data_param_names()})
                payload = {"id": node.id, "position": node.position, "label": node.label, "style": node.style, "data": data}
            else:
                payload = self._node_payload(node)
            try:
                self._check_node_payload(payload, node_ids)
            except _GraphConflictError as exc:
                _LOGGER.warning("panel-reactflow %s", exc)
            node_ids.add(payload["id"])
        edge_ids: set[Any] = set()
        for edge in edges:
            payload = self._edge_payload(edge)
            try:
                self._check_edge_payload(payload, node_ids, edge_ids)
            except _GraphConflictError as exc:
                _LOGGER.warning("panel-reactflow %s", exc)
            edge_ids.add(payload.get("id"))

    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

group_delete = param.Selector(default='cascade', objects=['cascade', 'ungroup'], doc="\n What deleting a node that contains other nodes does, in the browser\n and in remove_node(). 'cascade' deletes the nodes nested in it as\n well; 'ungroup' deletes only that node and moves its children to its\n parent, keeping their place on the canvas and their edges.") 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_drop_size = param.Integer(default=10000000, bounds=(0, None), doc="\n Maximum total size in bytes of one drop. Files beyond the limit are\n not read and are listed in the drop event's ``rejected`` entries.\n Binary files are sent base64 encoded (a third larger on the wire),\n so keep this below Bokeh's ``websocket_max_message_size``. ``0``\n disables the limit.") 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

selectable = param.Boolean(default=True, doc='Allow selecting nodes and edges, even when not editable.') 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

absolute_position(node_id)

Return the position of a node in flow coordinates.

The position of a node nested in a group is relative to its parent; this adds up the positions of all of its ancestors.

Parameters:

Name Type Description Default
node_id str

Id of the node.

required

Returns:

Type Description
dict

The {"x": ..., "y": ...} position of the node on the canvas.

Raises:

Type Description
KeyError

If there is no node with that id.

Source code in src/panel_reactflow/base.py
def absolute_position(self, node_id: str) -> dict[str, float]:
    """Return the position of a node in flow coordinates.

    The ``position`` of a node nested in a group is relative to its
    parent; this adds up the positions of all of its ancestors.

    Parameters
    ----------
    node_id : str
        Id of the node.

    Returns
    -------
    dict
        The ``{"x": ..., "y": ...}`` position of the node on the canvas.

    Raises
    ------
    KeyError
        If there is no node with that id.
    """
    node = self._get_node(node_id)
    if node is None:
        raise KeyError(f"No node with id {node_id!r}.")
    x = y = 0.0
    seen: set[str] = set()
    while node is not None and self._node_id(node) not in seen:
        seen.add(self._node_id(node))
        position = self._node_position(node)
        x += position["x"]
        y += position["y"]
        parent = self._node_parent(node)
        node = self._get_node(parent) if parent is not None else None
    return {"x": x, "y": y}

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 when a drag starts, and again for the final connection when the browser reports the new edge; an edge rejected then is removed from the browser. Edges added from Python with :meth:add_edge or edges are not checked.

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 when a drag starts,
    and again for the final connection when the browser reports the new
    edge; an edge rejected then is removed from the browser. Edges added
    from Python with :meth:`add_edge` or ``edges`` are not checked.
    """
    if not callable(callback):
        raise TypeError("Connection validator must be callable.")
    _accepts_flow(callback)
    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), either endpoint is not a node of the graph, an edge with the same id already exists, the edge is not JSON-serializable, or validation is enabled and the data doesn't match the schema. Self-loops are allowed.

Notes

Connection validators (:meth:add_connection_validator) only check connections made in the browser, not edges added from Python.

Examples:

Add a simple edge:

>>> flow = ReactFlow(nodes=[NodeSpec(id=f"n{i}") for i in range(1, 5)])
>>> 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``),
        either endpoint is not a node of the graph, an edge with the same
        ``id`` already exists, the edge is not JSON-serializable, or
        validation is enabled and the data doesn't match the schema.
        Self-loops are allowed.

    Notes
    -----
    Connection validators (:meth:`add_connection_validator`) only check
    connections made in the browser, not edges added from Python.

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

    >>> flow = ReactFlow(nodes=[NodeSpec(id=f"n{i}") for i in range(1, 5)])
    >>> 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
    """
    self.add_edges([edge])

add_edges(edges)

Add several edges to the graph in a single update.

Equivalent to calling :meth:add_edge for each edge, but edges is assigned only once, so the graph is synced to the browser once instead of once per edge.

Every edge is validated before any of them is added, so if one of them is invalid none are added. An edge_added event is emitted per edge, in order, after all of them were added.

Parameters:

Name Type Description Default
edges sequence of dict or EdgeSpec or Edge

The edges to add, in any form accepted by :meth:add_edge.

required

Raises:

Type Description
ValueError

If any edge is missing a required field or, with validate_on_add, its data does not match its type's schema.

Examples:

>>> flow.add_edges([
...     EdgeSpec(source=f"n{i}", target=f"n{i + 1}")
...     for i in range(99)
... ])
See Also

add_edge : Add a single edge add_nodes : Add several nodes in a single update remove_edge : Remove one or more edges in a single update

Source code in src/panel_reactflow/base.py
def add_edges(self, edges: Sequence[dict[str, Any] | EdgeSpec | Edge]) -> None:
    """Add several edges to the graph in a single update.

    Equivalent to calling :meth:`add_edge` for each edge, but ``edges`` is
    assigned only once, so the graph is synced to the browser once
    instead of once per edge.

    Every edge is validated before any of them is added, so if one of
    them is invalid none are added. An ``edge_added`` event is emitted per
    edge, in order, after all of them were added.

    Parameters
    ----------
    edges : sequence of dict or EdgeSpec or Edge
        The edges to add, in any form accepted by :meth:`add_edge`.

    Raises
    ------
    ValueError
        If any edge is missing a required field or, with
        ``validate_on_add``, its data does not match its type's schema.

    Examples
    --------
    >>> flow.add_edges([
    ...     EdgeSpec(source=f"n{i}", target=f"n{i + 1}")
    ...     for i in range(99)
    ... ])

    See Also
    --------
    add_edge : Add a single edge
    add_nodes : Add several nodes in a single update
    remove_edge : Remove one or more edges in a single update
    """
    node_ids = {self._node_id(node) for node in self.nodes}
    edge_ids = {self._edge_id(edge) for edge in self.edges}
    prepared = [self._prepare_edge(edge, node_ids, edge_ids) for edge in edges]
    if not prepared:
        return
    for raw_edge, payload in prepared:
        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.edges = self.edges + [raw_edge if isinstance(raw_edge, Edge) else payload for raw_edge, payload in prepared]
    for _, payload in prepared:
        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, a node with the same id already exists, any field other than view is not JSON-serializable, or 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, a node with
        the same ``id`` already exists, any field other than ``view`` is
        not JSON-serializable, or 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
    """
    self.add_nodes([node])

add_nodes(nodes)

Add several nodes to the graph in a single update.

Equivalent to calling :meth:add_node for each node, but nodes is assigned only once, so the graph is synced to the browser once instead of once per node. Use it to build or load large graphs.

Every node is validated before any of them is added, so if one of them is invalid none are added. A node_added event is emitted per node, in order, after all of them were added.

Parameters:

Name Type Description Default
nodes sequence of dict or NodeSpec or Node

The nodes to add, in any form accepted by :meth:add_node.

required

Raises:

Type Description
ValueError

If any node is missing a required field or, with validate_on_add, its data does not match its type's schema.

Examples:

>>> flow = ReactFlow()
>>> flow.add_nodes([
...     NodeSpec(id=f"n{i}", position={"x": 100 * i, "y": 0})
...     for i in range(100)
... ])
See Also

add_node : Add a single node add_edges : Add several edges in a single update remove_node : Remove one or more nodes in a single update

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

    Equivalent to calling :meth:`add_node` for each node, but ``nodes`` is
    assigned only once, so the graph is synced to the browser once
    instead of once per node. Use it to build or load large graphs.

    Every node is validated before any of them is added, so if one of
    them is invalid none are added. A ``node_added`` event is emitted per
    node, in order, after all of them were added.

    Parameters
    ----------
    nodes : sequence of dict or NodeSpec or Node
        The nodes to add, in any form accepted by :meth:`add_node`.

    Raises
    ------
    ValueError
        If any node is missing a required field or, with
        ``validate_on_add``, its data does not match its type's schema.

    Examples
    --------
    >>> flow = ReactFlow()
    >>> flow.add_nodes([
    ...     NodeSpec(id=f"n{i}", position={"x": 100 * i, "y": 0})
    ...     for i in range(100)
    ... ])

    See Also
    --------
    add_node : Add a single node
    add_edges : Add several edges in a single update
    remove_node : Remove one or more nodes in a single update
    """
    # One id set for the whole batch, grown as nodes are accepted, so that
    # duplicates within the batch are caught without rescanning the graph.
    node_ids = {self._node_id(node) for node in self.nodes}
    prepared = [self._prepare_node(node, node_ids) for node in nodes]
    if not prepared:
        return
    self._check_parents([payload for _, payload in prepared], node_ids)
    for raw_node, payload in prepared:
        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.nodes = self.nodes + [raw_node if isinstance(raw_node, Node) else payload for raw_node, payload in prepared]
    for _, payload in prepared:
        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

collapse_group(group_id, collapsed=True)

Collapse a group into one compact node, or expand it again.

Collapsing only changes what is drawn: the group's descendants are hidden and edges between them and the rest of the graph are drawn to the collapsed group instead. nodes and edges keep the real graph. The state is kept in the group's data["collapsed"].

A collapsed group shows one input and one output handle, or the handles listed in data["inputs"] and data["outputs"] (in the format of :class:NodeType inputs/outputs). An edge into a hidden node is drawn to the group handle that data["handle_map"] maps it to, a list of {"node": ..., "handle": ..., "group_handle": ...} entries (omit handle to map every handle of the node), and to the group's first handle on that side otherwise. An entry applies to the side its group handle is declared on; set "direction" to "input" or "output" to choose explicitly, e.g. when a node has an input and an output with the same id. Connection validators and policies check each edge such a connection creates. Nodes hidden by a collapse are deselected.

In a flow with editable=False the header chevron collapses a group for that viewer only and does not change data. Connecting to a mapped group handle in the browser creates an edge to each node it maps to.

Parameters:

Name Type Description Default
group_id str

Id of the group node.

required
collapsed bool

Whether to collapse (True) or expand (False) the group.

True

Raises:

Type Description
ValueError

If there is no node with that id.

Source code in src/panel_reactflow/base.py
def collapse_group(self, group_id: str, collapsed: bool = True) -> None:
    """Collapse a group into one compact node, or expand it again.

    Collapsing only changes what is drawn: the group's descendants are
    hidden and edges between them and the rest of the graph are drawn to
    the collapsed group instead. ``nodes`` and ``edges`` keep the real
    graph. The state is kept in the group's ``data["collapsed"]``.

    A collapsed group shows one input and one output handle, or the
    handles listed in ``data["inputs"]`` and ``data["outputs"]`` (in the
    format of :class:`NodeType` ``inputs``/``outputs``). An edge into a
    hidden node is drawn to the group handle that ``data["handle_map"]``
    maps it to, a list of ``{"node": ..., "handle": ..., "group_handle":
    ...}`` entries (omit ``handle`` to map every handle of the node),
    and to the group's first handle on that side otherwise. An entry
    applies to the side its group handle is declared on; set
    ``"direction"`` to ``"input"`` or ``"output"`` to choose explicitly,
    e.g. when a node has an input and an output with the same id.
    Connection validators and policies check each edge such a
    connection creates. Nodes hidden by a collapse are deselected.

    In a flow with ``editable=False`` the header chevron collapses a
    group for that viewer only and does not change ``data``. Connecting
    to a mapped group handle in the browser creates an edge to each
    node it maps to.

    Parameters
    ----------
    group_id : str
        Id of the group node.
    collapsed : bool, default True
        Whether to collapse (``True``) or expand (``False``) the group.

    Raises
    ------
    ValueError
        If there is no node with that id.
    """
    node = self._get_node(group_id)
    if node is None:
        raise ValueError(f"No node with id {group_id!r}.")
    if bool(self._node_data(node).get("collapsed", False)) == collapsed:
        return
    self.patch_node_data(group_id, {"collapsed": collapsed})
    self._emit("group_toggled", {"type": "group_toggled", "node_id": group_id, "collapsed": collapsed})

expand_group(group_id)

Expand a collapsed group, see :meth:collapse_group.

Source code in src/panel_reactflow/base.py
def expand_group(self, group_id: str) -> None:
    """Expand a collapsed group, see :meth:`collapse_group`."""
    self.collapse_group(group_id, False)

fit_view(*node_ids, padding=None, duration=None, min_zoom=None, max_zoom=None, include_hidden_nodes=False)

Pan and zoom the viewport so that the graph fits into view.

The canvas fits the view once when it is first rendered. Call this method to fit it again, e.g. after adding nodes or loading a new graph. The resulting viewport is synced back to the viewport parameter.

Parameters:

Name Type Description Default
*node_ids str or sequence of str

Only fit these nodes into view, either as separate arguments or as a single sequence. Fits every node when omitted.

()
padding float

Space around the fitted nodes as a fraction of the viewport size. Defaults to React Flow's 0.1.

None
duration int

Length of the animated transition in milliseconds. Jumps to the new viewport when omitted.

None
min_zoom float

Lower zoom bound for this fit, defaults to min_zoom.

None
max_zoom float

Upper zoom bound for this fit, defaults to max_zoom.

None
include_hidden_nodes bool

Whether hidden nodes are included in the fitted bounds.

False

Raises:

Type Description
ValueError

If a node id is not part of the graph or an option is out of range.

Examples:

Load a new graph and fit it into view:

>>> flow.nodes = new_nodes
>>> flow.fit_view()

Zoom to two nodes with an animated transition:

>>> flow.fit_view("n1", "n2", padding=0.2, duration=500)
Notes

A fit requested right after nodes changed waits until the browser has rendered and measured those nodes, so it fits the new graph rather than the previous one, even when the change is held back by pn.io.hold.

Calling this before the component is displayed does nothing, there is no canvas to fit yet and the first render fits the view anyway.

Source code in src/panel_reactflow/base.py
def fit_view(
    self,
    *node_ids: str | Sequence[str],
    padding: float | None = None,
    duration: int | None = None,
    min_zoom: float | None = None,
    max_zoom: float | None = None,
    include_hidden_nodes: bool = False,
) -> None:
    """Pan and zoom the viewport so that the graph fits into view.

    The canvas fits the view once when it is first rendered. Call this
    method to fit it again, e.g. after adding nodes or loading a new graph.
    The resulting viewport is synced back to the ``viewport`` parameter.

    Parameters
    ----------
    *node_ids : str or sequence of str
        Only fit these nodes into view, either as separate arguments or as
        a single sequence. Fits every node when omitted.
    padding : float, optional
        Space around the fitted nodes as a fraction of the viewport size.
        Defaults to React Flow's ``0.1``.
    duration : int, optional
        Length of the animated transition in milliseconds. Jumps to the
        new viewport when omitted.
    min_zoom : float, optional
        Lower zoom bound for this fit, defaults to ``min_zoom``.
    max_zoom : float, optional
        Upper zoom bound for this fit, defaults to ``max_zoom``.
    include_hidden_nodes : bool, default False
        Whether hidden nodes are included in the fitted bounds.

    Raises
    ------
    ValueError
        If a node id is not part of the graph or an option is out of range.

    Examples
    --------
    Load a new graph and fit it into view:

    >>> flow.nodes = new_nodes
    >>> flow.fit_view()

    Zoom to two nodes with an animated transition:

    >>> flow.fit_view("n1", "n2", padding=0.2, duration=500)

    Notes
    -----
    A fit requested right after ``nodes`` changed waits until the browser
    has rendered and measured those nodes, so it fits the new graph rather
    than the previous one, even when the change is held back by
    ``pn.io.hold``.

    Calling this before the component is displayed does nothing, there is
    no canvas to fit yet and the first render fits the view anyway.
    """
    ids = _flatten_ids(node_ids)
    known = {self._node_id(node) for node in self.nodes}
    unknown = [node_id for node_id in ids if node_id not in known]
    if unknown:
        raise ValueError(f"Cannot fit view to unknown node ids: {unknown}")
    if padding is not None and padding < 0:
        raise ValueError("padding must be non-negative.")
    if duration is not None and duration < 0:
        raise ValueError("duration must be non-negative.")
    for name, zoom in (("min_zoom", min_zoom), ("max_zoom", max_zoom)):
        if zoom is not None and zoom <= 0:
            raise ValueError(f"{name} must be positive.")
    options: dict[str, Any] = {}
    if ids:
        options["nodes"] = [{"id": node_id} for node_id in ids]
    if padding is not None:
        options["padding"] = padding
    if duration is not None:
        options["duration"] = duration
    if min_zoom is not None:
        options["minZoom"] = min_zoom
    if max_zoom is not None:
        options["maxZoom"] = max_zoom
    if include_hidden_nodes:
        options["includeHiddenNodes"] = True
    # The fit may reach the browser before a held ``nodes`` change does, so
    # it names the node revision it has to wait for.
    self._send_msg({"type": "fit_view", "node_revision": self._node_update_count, "options": options})

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]] = []
    original_ids: dict[str, Any] = {}
    for node_id, attrs in graph.nodes(data=True):
        # Ids are stringified for the browser, so e.g. 1 and "1" would
        # silently become one node.
        if str(node_id) in original_ids:
            raise ValueError(
                f"Nodes {original_ids[str(node_id)]!r} and {node_id!r} both map to the id {str(node_id)!r}; relabel the graph so node ids are unique as strings."
            )
        original_ids[str(node_id)] = node_id
        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)
    edge_ids: set[str] = set()
    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 = str(key if key is not None else f"{source}->{target}")
        if edge_id in edge_ids:
            # Multigraph keys are only unique per node pair (networkx
            # numbers parallel edges 0, 1, ...).
            edge_id = f"{source}->{target}:{key}"
        edge_ids.add(edge_id)
        edge = {
            "id": 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)

group_nodes(node_ids=None, *, group_id=None, label=None, padding=20, data=None, style=None, extent=None, expand_parent=True)

Put nodes into a new "group" node.

The group is placed around the nodes, which keep their place on the canvas and from then on move with the group. A group can be collapsed into a single compact node, see :meth:collapse_group.

Parameters:

Name Type Description Default
node_ids sequence of str

Ids of the nodes to group. Defaults to the selected nodes. They must all have the same parent, which becomes the parent of the group, so groups can be nested.

None
group_id str

Id of the new group. Generated when omitted.

None
label str

Label shown in the group's header.

None
padding float

Space between the nodes and the group's border.

20
data dict

Data of the group node, e.g. collapsed, inputs, outputs and handle_map (see :meth:collapse_group).

None
style dict

Style of the group node. Setting both width and height gives the group a fixed size; otherwise it grows to fit its children.

None
extent str or list

extent given to the grouped nodes, e.g. "parent" to keep them inside a fixed-size group (see style). React Flow ignores "parent" while expand_parent is set.

None
expand_parent bool

expandParent given to the grouped nodes, so dragging one past the border grows the group.

True

Returns:

Type Description
str

The id of the new group.

Raises:

Type Description
ValueError

If there are no nodes to group, a node does not exist, the nodes have different parents or the group id is taken.

Source code in src/panel_reactflow/base.py
def group_nodes(
    self,
    node_ids: Sequence[str] | None = None,
    *,
    group_id: str | None = None,
    label: str | None = None,
    padding: float = 20,
    data: dict[str, Any] | None = None,
    style: dict[str, Any] | None = None,
    extent: str | list[list[float]] | None = None,
    expand_parent: bool | None = True,
) -> str:
    """Put nodes into a new ``"group"`` node.

    The group is placed around the nodes, which keep their place on the
    canvas and from then on move with the group. A group can be
    collapsed into a single compact node, see :meth:`collapse_group`.

    Parameters
    ----------
    node_ids : sequence of str, optional
        Ids of the nodes to group. Defaults to the selected nodes. They
        must all have the same parent, which becomes the parent of the
        group, so groups can be nested.
    group_id : str, optional
        Id of the new group. Generated when omitted.
    label : str, optional
        Label shown in the group's header.
    padding : float, default 20
        Space between the nodes and the group's border.
    data : dict, optional
        Data of the group node, e.g. ``collapsed``, ``inputs``,
        ``outputs`` and ``handle_map`` (see :meth:`collapse_group`).
    style : dict, optional
        Style of the group node. Setting both ``width`` and ``height``
        gives the group a fixed size; otherwise it grows to fit its
        children.
    extent : str or list, optional
        ``extent`` given to the grouped nodes, e.g. ``"parent"`` to keep
        them inside a fixed-size group (see ``style``). React Flow
        ignores ``"parent"`` while ``expand_parent`` is set.
    expand_parent : bool, optional, default True
        ``expandParent`` given to the grouped nodes, so dragging one
        past the border grows the group.

    Returns
    -------
    str
        The id of the new group.

    Raises
    ------
    ValueError
        If there are no nodes to group, a node does not exist, the nodes
        have different parents or the group id is taken.
    """
    ids = list(dict.fromkeys(self.selection.get("nodes", []) if node_ids is None else node_ids))
    if not ids:
        raise ValueError("No nodes to group.")
    self._check_reparent(ids, None)
    parents = {self._node_parent(self._get_node(node_id)) for node_id in ids}
    if len(parents) > 1:
        raise ValueError("Only nodes with the same parent can be grouped.")
    (parent,) = parents
    if group_id is None:
        group_id = f"group-{uuid4().hex[:8]}"
    positions = [self._node_position(self._get_node(node_id)) for node_id in ids]
    group: dict[str, Any] = {
        "id": group_id,
        "type": "group",
        "label": label,
        "position": {
            "x": min(p["x"] for p in positions) - padding,
            "y": min(p["y"] for p in positions) - padding - GROUP_HEADER_HEIGHT,
        },
        "data": dict(data or {}),
    }
    if parent is not None:
        group["parentId"] = parent
    if style is not None:
        group["style"] = style
    node_ids_in_graph = {self._node_id(node) for node in self.nodes}
    _, payload = self._prepare_node(group, node_ids_in_graph)
    self._check_parents([payload], node_ids_in_graph)
    # The group goes before its first child, React Flow draws (and
    # needs) parents before their children.
    first = min(i for i, node in enumerate(self.nodes) if self._node_id(node) in ids)
    nodes = list(self.nodes)
    nodes.insert(first, payload)
    with param.discard_events(self):
        self.nodes = nodes
    self._rebuild_node_index()
    self._reparent(ids, group_id, {"extent": extent, "expandParent": expand_parent})
    self.param.trigger("nodes")
    self._emit("node_added", {"type": "node_added", "node": payload})
    self._emit("nodes_grouped", {"type": "nodes_grouped", "group_id": group_id, "node_ids": ids})
    return group_id

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. Payload has node_id and a screen position suitable for :meth:show_popup. Clicks on the node's embedded view or editor are not reported, and a double click emits two events. Also fires when editable=False.
  • "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
  • "connection_refused": A connection dragged in the browser was dropped onto a handle that refuses it, so no edge was drawn. Payload has source, sourceHandle, target, targetHandle and the reason the frontend policies or connection validators gave.
  • "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
  • "nodes_grouped": :meth:group_nodes put nodes into a new group. Payload has group_id and node_ids.
  • "nodes_ungrouped": :meth:ungroup dissolved a group, or a group was deleted with group_delete="ungroup". Payload has group_id and node_ids (its former children).
  • "group_toggled": A group was collapsed or expanded, from its header or :meth:collapse_group. Payload has node_id and collapsed.
  • "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"}, where content is a str for a file that decodes as UTF-8 text, whatever its reported MIME type, and bytes for any other file), the drop position in flow coordinates, 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, and a rejected list of {"name", "type", "size", "reason"} for files that were not sent because they exceed max_drop_size or could not be read. A non-file drop larger than max_drop_size is sent with data=None and one rejected entry.
  • "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). An exception raised by a callback is logged and does not stop the remaining callbacks or hooks; the change that triggered the event is applied either way.

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. Payload has ``node_id``
          and a screen ``position`` suitable for :meth:`show_popup`.
          Clicks on the node's embedded view or editor are not reported,
          and a double click emits two events. Also fires when
          ``editable=False``.
        - ``"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
        - ``"connection_refused"``: A connection dragged in the browser
          was dropped onto a handle that refuses it, so no edge was
          drawn. Payload has ``source``, ``sourceHandle``, ``target``,
          ``targetHandle`` and the ``reason`` the frontend policies or
          connection validators gave.
        - ``"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
        - ``"nodes_grouped"``: :meth:`group_nodes` put nodes into a new
          group. Payload has ``group_id`` and ``node_ids``.
        - ``"nodes_ungrouped"``: :meth:`ungroup` dissolved a group, or a
          group was deleted with ``group_delete="ungroup"``. Payload has ``group_id`` and ``node_ids`` (its former children).
        - ``"group_toggled"``: A group was collapsed or expanded, from
          its header or :meth:`collapse_group`. Payload has ``node_id``
          and ``collapsed``.
        - ``"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"}``, where ``content`` is a ``str`` for a file that
          decodes as UTF-8 text, whatever its reported MIME type, and
          ``bytes`` for any other file), the
          drop ``position`` in flow coordinates, 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``, and a ``rejected`` list of
          ``{"name", "type", "size", "reason"}`` for files that were
          not sent because they exceed ``max_drop_size`` or could not
          be read. A non-file drop larger than ``max_drop_size`` is
          sent with ``data=None`` and one ``rejected`` entry.
        - ``"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)``. An exception raised by a callback
        is logged and does not stop the remaining callbacks or hooks;
        the change that triggered the event is applied either way.

    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.
    """
    _accepts_flow(callback)
    self._event_handlers.setdefault(event_type, []).append(callback)

patch_edge_data(edge_id, patch, *, remove=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:

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
remove list of str

Keys to delete from the edge's data before patch is merged in. Used by the JSON editors to apply deleted keys.

None

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], *, remove: Sequence[str] | None = None) -> 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.
    remove : list of str, optional
        Keys to delete from the edge's ``data`` before *patch* is
        merged in. Used by the JSON editors to apply deleted keys.

    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(
        kind="edge",
        item_id=edge_id,
        patch=patch,
        get_item=self._get_edge,
        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,
        remove=remove or (),
    )
    msg = {"type": "patch_edge_data", "edge_id": edge_id, "patch": patch}
    event = {"type": "edge_data_changed", "edge_id": edge_id, "patch": patch}
    if remove:
        msg["remove"] = event["remove"] = list(remove)
    self._send_msg(msg)
    self._emit("edge_data_changed", event)
    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)
    edge = self._get_edge(edge_id)
    if edge is not None:
        self._apply_prop_patch(edge, patch)
        if "type" in patch:
            self._on_retyped("edge")
    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, *, remove=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:

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
remove list of str

Keys to delete from the node's data before patch is merged in. Used by the JSON editors to apply deleted keys.

None

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], *, remove: Sequence[str] | None = None) -> 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.
    remove : list of str, optional
        Keys to delete from the node's ``data`` before *patch* is
        merged in. Used by the JSON editors to apply deleted keys.

    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(
        kind="node",
        item_id=node_id,
        patch=patch,
        get_item=self._get_node,
        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,
        remove=remove or (),
    )
    msg = {"type": "patch_node_data", "node_id": node_id, "patch": patch, "revision": self._node_update_count}
    event = {"type": "node_data_changed", "node_id": node_id, "patch": patch}
    if remove:
        msg["remove"] = event["remove"] = list(remove)
    self._send_msg(msg)
    self._emit("node_data_changed", event)
    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, className, parentId, extent, expandParent, hidden and zIndex. A new parentId does not move the node, its position is read relative to the new parent; use :meth:set_parent to keep it in place. 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``, ``className``,
        ``parentId``, ``extent``, ``expandParent``, ``hidden`` and
        ``zIndex``. A new ``parentId`` does not move the node, its
        position is read relative to the new parent; use
        :meth:`set_parent` to keep it in place.
        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)
    node = self._get_node(node_id)
    if node is not None:
        self._apply_prop_patch(node, patch)
        if "type" in patch:
            self._on_retyped("node")
    self._send_msg({"type": "patch_node_props", "node_id": node_id, "patch": patch, "revision": self._node_update_count})
    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(nodes=[NodeSpec(id="n1"), NodeSpec(id="n2")])
>>> 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(nodes=[NodeSpec(id="n1"), NodeSpec(id="n2")])
    >>> 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. Nodes nested in a removed node (through parentId) are removed with it, unless group_delete is "ungroup": then they move to the removed node's parent, keep their place on the canvas and their edges, and a nodes_ungrouped event is emitted for the removed node right before its node_deleted. Nested nodes removed along with their parent are reported first, so the events can be undone in reverse order.

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. Nodes nested in a removed node (through
    ``parentId``) are removed with it, unless ``group_delete`` is
    ``"ungroup"``: then they move to the removed node's parent, keep
    their place on the canvas and their edges, and a ``nodes_ungrouped``
    event is emitted for the removed node right before its
    ``node_deleted``. Nested nodes removed along with their parent are
    reported first, so the events can be undone in reverse order.

    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
    released: dict[str, list[str]] = {}
    if self.group_delete == "ungroup":
        # Nested nodes are reported before their parents, and a parent's
        # nodes_ungrouped right before its node_deleted, so undoing the
        # events in reverse order restores parents before their contents.
        ids.sort(key=self._depth, reverse=True)
        released = self._release_children(ids)
    else:
        # Children go with their parent, as when deleting in the browser.
        ids += [node_id for node_id in self._descendants(ids) if node_id not in ids]
    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:
        removed_refs = {id(edge) for edge in removed_edges}
        updates["edges"] = [edge for edge in self.edges if id(edge) not in removed_refs]
    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:
        if node_id in released:
            self._emit("nodes_ungrouped", {"type": "nodes_ungrouped", "group_id": node_id, "node_ids": released[node_id]})
        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))

set_parent(node_ids, parent_id, *, extent=None, expand_parent=None)

Nest nodes in another node, or take them out of their parent.

The nodes keep their place on the canvas: their positions are converted to be relative to the new parent.

Parameters:

Name Type Description Default
node_ids str or sequence of str

Ids of the nodes to move.

required
parent_id str or None

Id of the new parent, or None to put the nodes at the top level.

required
extent str or list

New extent of the nodes, e.g. "parent". Cleared when None.

None
expand_parent bool

New expandParent of the nodes. Cleared when None.

None

Raises:

Type Description
ValueError

If a node does not exist or would be nested in itself.

Source code in src/panel_reactflow/base.py
def set_parent(
    self,
    node_ids: str | Sequence[str],
    parent_id: str | None,
    *,
    extent: str | list[list[float]] | None = None,
    expand_parent: bool | None = None,
) -> None:
    """Nest nodes in another node, or take them out of their parent.

    The nodes keep their place on the canvas: their positions are
    converted to be relative to the new parent.

    Parameters
    ----------
    node_ids : str or sequence of str
        Ids of the nodes to move.
    parent_id : str or None
        Id of the new parent, or ``None`` to put the nodes at the top
        level.
    extent : str or list, optional
        New ``extent`` of the nodes, e.g. ``"parent"``. Cleared when
        ``None``.
    expand_parent : bool, optional
        New ``expandParent`` of the nodes. Cleared when ``None``.

    Raises
    ------
    ValueError
        If a node does not exist or would be nested in itself.
    """
    ids = [node_ids] if isinstance(node_ids, str) else list(dict.fromkeys(node_ids))
    self._check_reparent(ids, parent_id)
    self._reparent(ids, parent_id, {"extent": extent, "expandParent": expand_parent})
    self.param.trigger("nodes")

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

ungroup(group_id)

Dissolve a group, keeping its children where they are.

The children of the group are moved to the group's own parent, keep their place on the canvas and lose the extent and expandParent that tied them to the group. The group node and edges connected to it are removed. nodes_ungrouped is emitted before the group's node_deleted.

Parameters:

Name Type Description Default
group_id str

Id of the group to dissolve.

required

Returns:

Type Description
list of str

The ids of the former children.

Raises:

Type Description
ValueError

If there is no node with that id.

Source code in src/panel_reactflow/base.py
def ungroup(self, group_id: str) -> list[str]:
    """Dissolve a group, keeping its children where they are.

    The children of the group are moved to the group's own parent, keep
    their place on the canvas and lose the ``extent`` and
    ``expandParent`` that tied them to the group. The group node and
    edges connected to it are removed. ``nodes_ungrouped`` is emitted
    before the group's ``node_deleted``.

    Parameters
    ----------
    group_id : str
        Id of the group to dissolve.

    Returns
    -------
    list of str
        The ids of the former children.

    Raises
    ------
    ValueError
        If there is no node with that id.
    """
    group = self._get_node(group_id)
    if group is None:
        raise ValueError(f"No node with id {group_id!r}.")
    children = [self._node_id(node) for node in self.nodes if self._node_parent(node) == group_id]
    self._reparent(children, self._node_parent(group), {"extent": None, "expandParent": None})
    self._emit("nodes_ungrouped", {"type": "nodes_ungrouped", "group_id": group_id, "node_ids": children})
    # The children no longer refer to the group, so they stay, and the
    # nodes sync that removes the group carries their new positions.
    self.remove_node(group_id)
    return children

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, which is logged as a warning

A property the form cannot represent with a dedicated widget is shown as a literal input rather than turning the whole form into JSON. Widgets are drawn from panel_material_ui when it is installed (pip install panel-reactflow[material]) and from panel.widgets otherwise. Date and datetime values are written back as ISO 8601 strings so the data stays JSON serializable.

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, which is logged as a warning

    A property the form cannot represent with a dedicated widget is shown
    as a literal input rather than turning the whole form into JSON.
    Widgets are drawn from ``panel_material_ui`` when it is installed
    (``pip install panel-reactflow[material]``) and from ``panel.widgets``
    otherwise. Date and datetime values are written back as ISO 8601
    strings so the data stays JSON serializable.
    """

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

                self._form = JSONSchema(
                    dict(self._data),
                    schema=properties,
                    definitions=_schema_definitions(self._schema),
                    multi=False,
                )
            except Exception:
                _LOGGER.warning(
                    "Could not build a form from the schema of %s %r, falling back to a JSON editor.",
                    self._node_type or "item",
                    self._node_id,
                    exc_info=True,
                )
        if self._form is None:
            self._init_json_fallback()
            return
        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

    def _init_json_fallback(self) -> None:
        self._json_editor = JSONEditor(value=dict(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._is_updating:
            return
        from .schema import to_json_value

        value = to_json_value(event.new)
        if self._report_patch({name: value}):
            with self._updating():
                self._data = {**self._data, name: value}
        else:
            with self._updating():
                event.obj.value = event.old

    def _on_json_change(self, event: param.parameterized.Event) -> None:
        self._handle_json_edit(event.new, self._json_editor)

    @param.depends("_data", watch=True)
    def _sync_from_data(self) -> None:
        if self._is_updating:
            return
        with self._updating():
            if self._form is not None:
                self._form._set_widget_values(self._data)
            else:
                self._json_editor.value = dict(self._data)

    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