Skip to content

AnnotatedText[source]

The AnnotatedText is a rich text viewer that supports span-level annotations, nested token highlights, and various user event callbacks.

Examples

from pret import (
    component,
    create_store,
    use_store_snapshot,
    use_event_callback,
    use_state,
)
from pret.ui.metanno import AnnotatedText
from pret.ui.joy import Button, Box

txt = (
    "Metanno brings annotation components to Pret\n"
    "to build tailored annotation tools."
)

# One span covering the word “Metanno”
spans = create_store(
    [
        {
            "id": f"span-0-7",
            "begin": 0,
            "end": 7,
            "label": "OBJ",
            "highlighted": False,
        }
    ]
)

txt_annotation_styles = create_store(
    {
        "OBJ": {
            "color": "red",
            "shape": "underline",
        }
    }
)


@component
def MyText():
    tracked_spans = use_store_snapshot(spans)
    tracked_styles = use_store_snapshot(txt_annotation_styles)

    @use_event_callback
    def handle_select(ranges, modkeys):
        for sp in ranges:
            spans.extend(
                [
                    {
                        "id": f"span-{sp['begin']}-{sp['end']}",
                        "begin": sp["begin"],
                        "end": sp["end"],
                        "label": "OBJ",
                    }
                ]
            )

    def on_mouse_enter_span(span_id, modkeys):
        for i, sp in enumerate(spans):
            if sp["id"] == span_id:
                spans[i]["highlighted"] = True

    def on_mouse_leave_span(span_id, modkeys):
        for i, sp in enumerate(spans):
            if sp["id"] == span_id:
                spans[i]["highlighted"] = False

    def on_span_style_change():
        old_style = txt_annotation_styles["OBJ"]["shape"]
        new_style = "box" if old_style == "underline" else "underline"
        txt_annotation_styles["OBJ"]["shape"] = new_style

    return Box(
        Button("Change style", on_click=on_span_style_change),
        Button("Remove annotations", on_click=lambda: spans.clear()),
        AnnotatedText(
            text=txt,
            spans=tracked_spans,
            annotation_styles=tracked_styles,
            on_mouse_select=handle_select,
            on_mouse_enter_span=on_mouse_enter_span,
            on_mouse_leave_span=on_mouse_leave_span,
            style={"gridColumn": "1 / -1"},
        ),
        sx={
            "p": 1,
            "display": "grid",
            "gridTemplateColumns": "repeat(2, auto)",
            "gap": 1,
        },
    )


MyText()

Parameters

PARAMETER DESCRIPTION
text

Raw text content shown in the viewer.

TYPE: str

spans

Span-level annotations over text. Each span must include begin and end character offsets, with optional fields:

  • id: Optional unique identifier.
  • label: Category name displayed next to / above the span.
  • style: Key referencing annotation_styles.
  • selected (bool): styled as selected by the user.
  • highlighted (bool): styled as highlighted by the user.

TYPE: List[Dict[str, Any]]

annotation_styles

Named style presets that control span background color, border, label placement, etc. Each style may define properties such as:

  • color (str): Color of the span. Will be overridden by backgroundColor and borderColor.
  • shape ("underline" | "box"): Visual style of the span.
  • backgroundColor (str): Background color of the span (e.g. "#0000ff80").
  • borderColor (str): Border color of the span (e.g. "#000000").
  • autoNestingLayout (bool): Whether to automatically nest overlapping spans, rather than rendering them on top of each other.

TYPE: Dict[str, Dict[str, Any]]

mouse_selection

Current mouse drag selection expressed as character‐offset ranges. Passed to on_mouse_select when the action completes.

TYPE: List[Dict[str, int]]

style

CSS style overrides for the outer element.

TYPE: Dict[str, Any]

actions

Optional imperative helpers (scroll_to_span …, clear_current_mouse_selection).

TYPE: Dict[str, Any]

key

React reconciliation key.

TYPE: Union[str, int]

on_click_span

Called when the user clicks on a span.

  • span_id – Identifier of the clicked annotation
  • modkeys – Pressed modifier keys

TYPE: Callable[[str, List[str]], None]

on_key_press

Called when a key is pressed with focus inside the component.

  • key – Key name
  • ranges – Current selection ranges
  • modkeys – Modifier keys

TYPE: Callable[[str, List[Dict[str, int]], List[str]], None]

on_mouse_enter_span

Called when the mouse pointer enters a span.

  • span_id – Identifier of the span entered
  • modkeys – Pressed modifier keys

TYPE: Callable[[str, List[str]], None]

on_mouse_leave_span

Called when the mouse pointer leaves a span.

  • span_id – Identifier of the span left
  • modkeys – Pressed modifier keys

TYPE: Callable[[str, List[str]], None]

on_mouse_select

Triggered when the user finishes selecting text with the mouse.

  • ranges – Final list of selected ranges
  • modkeys – Modifier keys

TYPE: Callable[[List[Dict[str, int]], List[str]], None]