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 metanno import AnnotatedText
from pret_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",
            "start": 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']}",
                        "start": 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"},
            begin_key="start",  # Custom field names
        ),
        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 (or the value of begin_key): Begin character offset (inclusive).
  • end (or the value of end_key): End character offset (exclusive).

and may optionally include:

  • id (or the value of primary_key): Optional unique span identifier.
  • label (or the value of label_key): Category name displayed next to / above the span.
  • style (or the value of style_key): Key referencing annotation_styles.
  • selected (or the value of selected_key): styled as selected by the user.
  • highlighted (or the value of label_key): 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]

handle

Imperative handle for actions that can be performed on the component:

  • scroll_to_line(line_idx: int, behavior: "smooth" | "instant" | "auto"): Scrolls to the given line index.
  • scroll_to_span(span_id: str, behavior: "smooth" | "instant" | "auto"): Scrolls to the given span.
  • clear_current_mouse_selection(): Clears the current mouse selection.

TYPE: Dict[str, Any]

begin_key

Name of the field in spans that contains the begin character offset.

TYPE: str DEFAULT: 'begin'

end_key

Name of the field in spans that contains the end character offset.

TYPE: str DEFAULT: 'end'

primary_key

Name of the field in spans that contains the unique span identifier.

TYPE: str DEFAULT: 'id'

label_key

Name of the field in spans that contains the human-readable label.

TYPE: str DEFAULT: 'label'

style_key

Name of the field in spans that contains the style key. This key will be used to look up visual properties in annotation_styles. If no style field is provided for a span, the style key will default to label.

TYPE: str DEFAULT: 'style'

highlighted_key

Name of the field in spans that indicates whether the span is highlighted.

TYPE: str DEFAULT: 'highlighted'

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_hover_spans

Triggered every time the set of hovered spans changes.

  • span_ids: List of currently hovered span identifiers
  • modkeys: Pressed modifier keys

TYPE: Callable[[List[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]

key

React reconciliation key (not the same as the previous _key props), this should be used to uniquely identify the component instance if there are multiple instances next to each other.

TYPE: Union[str, int]