Sequence

D3Blocks.sequence(df, participants=None, groups: list = None, steps: list = None, message_spacing: int = 44, wrap: int = 28, cmap: str = 'Set2', font: dict = {'size': 13}, title: str = 'Sequence - D3blocks', filepath: str = 'sequence.html', figsize=[None, None], showfig: bool = True, overwrite: bool = True, notebook: bool = False, save_button: bool = True, show_side_panel: bool = True, show_top_panel: bool = True, dark_mode=True, color_background=None, return_html: bool = False, reset_properties: bool = True)

Sequence block: request/response flows between participants.

Participants are columns with lifelines and messages are rows in time order: calls are solid with a filled arrowhead, replies dashed with an open arrowhead. Regions highlight a run of messages. The input is a Mermaid sequenceDiagram or a DataFrame of messages.

Parameters:
  • df (pd.DataFrame, str or path-like) –

    • DataFrame with one row per message, in time order. Required columns: ‘source’, ‘target’. Optional columns: ‘label’, ‘style’ (‘sync’ or ‘reply’) and ‘variant’ (‘default’, ‘emphasis’, ‘security’, ‘async’, ‘error’; sets the colour and width as in flowgraph).

    • str: a Mermaid sequenceDiagram, or Markdown text with a fenced mermaid block.

    • Path to a Markdown file (.md, .markdown) or a .mmd / .mermaid file. From Markdown, the first sequenceDiagram block is used.

    Supported Mermaid: ‘participant A’, ‘participant A as Label’, ‘actor A’, ‘A->>B: text’ (call), ‘A–>>B: text’ (reply), ‘rect rgb(…)’ … ‘end’ (a region) and ‘%%’ comments. Other statements raise a ValueError naming the line.

  • participants (pd.DataFrame or dict, (default: None)) –

    Per-participant attributes keyed by participant id (a ‘name’ column or the index):
    • ’label’: display text; use ‘n’ for line breaks.

    • ’kind’: ‘participant’ or ‘actor’ (drawn with a stick figure).

    • ’color’: participant colour; overrides cmap.

    • ’tooltip’: text shown on hover.

    Participants that are not listed are created in order of first appearance.

  • groups (list of dict, (default: None)) – Highlighted regions: [{‘label’: str, ‘from’: i, ‘to’: j, ‘color’: hex}], where i and j are message indexes (0-based, inclusive). Mermaid ‘rect’ blocks fill this list; a list passed here replaces them.

  • steps (list of dict, (default: None)) – Captioned walkthrough; “Walk through” in the top panel steps through it: [{‘title’: str, ‘caption’: str, ‘highlight’: {‘messages’: [i, …], ‘participants’: […]}}]. None: one step per message, captioned with the message label. []: no walkthrough.

  • message_spacing (int, (default: 44)) – Minimum pixels per message row; long labels make a row taller.

  • wrap (int, (default: 28)) – Wrap message labels at this many characters.

  • cmap (str, (default: 'Set2')) – Colormap for participant colours.

  • font (dict, (default: {'size': 13})) – Font properties.

  • title (str, (default: 'Sequence - D3blocks')) – Title of the figure.

  • filepath (str, (default: 'sequence.html')) – File path to save the output. None: return HTML only.

  • figsize (list, (default: [None, None])) – [width, height] in pixels. None: full window.

  • showfig (bool, (default: True)) – Open the chart in the browser.

  • overwrite (bool, (default: True)) – Overwrite an existing file.

  • notebook (bool, (default: False)) – Display inline in a Jupyter notebook, isolated in an iframe sized by figsize (default: full width x 650 px).

  • save_button (bool, (default: True)) – Show the SVG/PNG save buttons.

  • show_side_panel (bool, (default: True)) – Show the left side panels (Export / Save, Layout, Legend).

  • show_top_panel (bool, (default: True)) – Show the top bar (logo, search, walk through, fit, theme).

  • dark_mode (bool or 'auto', (default: True)) –

    Initial theme; the theme button switches at runtime in every mode.
    • True: start in the dark theme.

    • False: start in the light theme.

    • ’auto’: follow the operating system theme until the theme button is used.

  • color_background (list of str, str, or None, (default: None)) – Backgrounds for center / top / side panels as [dark_hex, light_hex]. Named themes: 'streamlit', 'darkblue'. None → ['#222222', '#ffffff'].

  • return_html (bool, (default: False)) – Return the HTML string.

  • reset_properties (bool, (default: True)) – Recompute participant and message properties from the input.

Returns:

  • d3.node_properties (DataFrame of dictionary) – Participant properties; edit and call d3.show() to update.

  • d3.edge_properties (DataFrame) – Message properties; edit and call d3.show() to update.

  • d3.config (dictionary) – Configuration, including ‘groups’ and ‘steps’.

Examples

>>> from d3blocks import D3Blocks
>>> d3 = D3Blocks(frame=False)
>>> d3.sequence('''
... sequenceDiagram
...     actor User
...     participant API
...     participant DB as Database
...     rect rgb(220, 252, 231)
...         User->>API: GET /orders
...         API->>DB: SELECT orders
...         DB-->>API: rows
...     end
...     API-->>User: 200 JSON
... ''')
>>>
>>> # DataFrame input with a captioned walkthrough
>>> import pandas as pd
>>> df = pd.DataFrame({'source': ['app', 'auth', 'app'], 'target': ['auth', 'app', 'api'],
...                    'label': ['login', 'token', 'call with token'], 'style': ['sync', 'reply', 'sync']})
>>> steps = [{'title': 'Sign in', 'caption': 'The app gets a token.', 'highlight': {'messages': [0, 1]}},
...          {'title': 'Call', 'caption': 'The token authorizes the call.', 'highlight': {'messages': [2]}}]
>>> d3.sequence(df, steps=steps)

References

Input Data

The input is either a Mermaid sequenceDiagram (string, Markdown or file) or a DataFrame with one row per message, in time order. The DataFrame needs the columns source and target; all other columns are optional.

#   source target            label  style   variant
# 0    app   auth            login   sync  security
# 1   auth    app            token  reply   default
# 2    app    api  call with token   sync  emphasis
  • style: sync (a call: solid line, filled arrowhead) or reply (dashed line, open arrowhead).

  • variant: default, emphasis, security, async, error; sets the colour and width, as in flowgraph.

Per-participant attributes (label, kind, color, tooltip) are passed with participants. kind='actor' draws a stick figure; the layout is the same. Participants that are not listed are added in order of first appearance. Regions are passed with groups as [{'label': str, 'from': i, 'to': j, 'color': hex}] with message indexes.

Mermaid input

Supported: participant A, participant A as Label, actor A, A->>B: text (call), A-->>B: text (reply), rect rgb(...) / rect rgba(...) … end (a region) and %% comments. Other statements (activations, notes, alt/loop, autonumber, self-messages, …) raise a ValueError naming the line, so nothing is dropped silently (see Mermaid errors on the Flowgraph page).

from d3blocks import D3Blocks

d3 = D3Blocks(frame=False)
d3.sequence('''
sequenceDiagram
    actor Operator
    participant UI as Trade App (UI)
    participant API as Trade API
    participant Schwab as Schwab OAuth

    rect rgb(236, 254, 255)
        Operator->>UI: Click "Connect Schwab"
        UI->>API: GET /api/v1/brokers/schwab/authorize
        API-->>UI: Redirect to Schwab authorization URL
    end
    rect rgb(220, 252, 231)
        Schwab->>API: GET /callback?code=…
        API->>Schwab: POST token exchange
        Schwab-->>API: access_token + refresh_token
        API-->>UI: Settings shows "Connected"
    end
''')

The diagram can also live in a Markdown file as a fenced mermaid block; the first sequenceDiagram block is used, so one file can hold several diagram kinds.

d3.sequence('docs/schwab-connection.md')

DataFrame input

import pandas as pd

df = pd.DataFrame({
    'source': ['app', 'auth', 'app', 'api'],
    'target': ['auth', 'app', 'api', 'app'],
    'label': ['login', 'token', 'GET /orders with token', '200 JSON'],
    'style': ['sync', 'reply', 'sync', 'reply'],
})
participants = {'app': {'label': 'Mobile app', 'kind': 'actor'}, 'auth': {'label': 'Auth server'}}
d3.sequence(df, participants=participants, groups=[{'label': 'Sign in', 'from': 0, 'to': 1}])

Walkthrough

▶ Walk through steps through the messages with a caption bar at the bottom: the step title, the caption, “Step 3 of 9”, a row of step stops and Prev / Play / Next. By default there is one step per message, captioned with the message label. Pass steps to write your own; a step highlights messages (by index) and participants, dims the rest and scrolls them into view.

steps = [
    {'title': 'Sign in', 'caption': 'The app exchanges credentials for a token.',
     'highlight': {'messages': [0, 1]}},
    {'title': 'Call the API', 'caption': 'The token authorizes the request.',
     'highlight': {'messages': [2, 3], 'participants': ['api']}},
]
d3.sequence(df, steps=steps)

Keys: ← and → move, Space plays or pauses, Esc closes. steps=[] removes the walkthrough.

Theme

The theme button switches between dark and light at runtime; every colour (lines, arrowheads, regions, the caption bar) follows the theme. dark_mode='auto' follows the operating system theme until the theme button is used. Exports keep the theme shown.

Interaction

  • Hover a participant to highlight its lifeline and every message touching it; click to pin.

  • Hover a message to highlight it and see its index and text.

  • Search finds participants and message text.

  • Fit fits the diagram to the window width; wide diagrams keep a readable text size and pan. The participant headers stay visible when scrolling down a long sequence.

  • The Layout panel changes message spacing, label wrapping and font size.

  • Export to SVG, PNG or JSON (including computed positions).

Jupyter and Streamlit

In a notebook, pass notebook=True. In Streamlit, generate the HTML with return_html=True and embed it with st.iframe; see streamlit/sequence_streamlit_demo.py.

html = D3Blocks().sequence(diagram, filepath=None, showfig=False, return_html=True)
st.iframe(html, height=700, width="stretch")