Skip to content

SegmentedControl

Accessible single-choice control for compact filters, view modes, and time ranges. It accepts existing Button or link elements, so HTMX and ordinary navigation remain available without custom JavaScript.

from faststrap import Button, SegmentedControl

SegmentedControl(
    Button("Overview", variant="outline-primary"),
    Button("Metrics", variant="outline-primary"),
    name="view",
    values=["overview", "metrics"],
    active_index=1,
)
Parameter Type Default Description
*options Any required Buttons, links, or other option elements.
name str \| None None Optional hidden-input name for form submission.
values list[str] \| None None Values aligned with the options.
active_index int 0 Server-rendered active option index.
orientation str "horizontal" horizontal or vertical.
active_cls str "active" Class added to the active option.
hidden_input bool True Add the hidden input when name is provided.

For HTMX-driven filters, put hx_get, hx_target, and hx_push_url on the option elements and render the selected state from the request parameters.

faststrap.components.forms.segmented_control.SegmentedControl(*options, name=None, values=None, active_index=0, orientation='horizontal', active_cls='active', hidden_input=True, **kwargs)

Render a single-choice control from buttons, links, or HTMX options.

The active state is server-rendered. A hidden input can carry the selected value through a surrounding form; links and HTMX attributes remain fully usable for route-driven navigation.

Source code in src/faststrap/components/forms/segmented_control.py
@register(category="forms")
@beta
def SegmentedControl(
    *options: Any,
    name: str | None = None,
    values: list[str] | None = None,
    active_index: int = 0,
    orientation: Literal["horizontal", "vertical"] = "horizontal",
    active_cls: str = "active",
    hidden_input: bool = True,
    **kwargs: Any,
) -> Div:
    """Render a single-choice control from buttons, links, or HTMX options.

    The active state is server-rendered. A hidden input can carry the selected
    value through a surrounding form; links and HTMX attributes remain fully
    usable for route-driven navigation.
    """
    option_list = list(options)
    if not option_list:
        raise ValueError("SegmentedControl requires at least one option")
    if values is not None and len(values) != len(option_list):
        raise ValueError("values length must match number of options")
    if orientation not in {"horizontal", "vertical"}:
        raise ValueError("orientation must be horizontal or vertical")

    safe_index = max(0, min(active_index, len(option_list) - 1))
    input_id = f"fs-segmented-{uuid4().hex[:8]}"
    for index, option in enumerate(option_list):
        if not hasattr(option, "attrs"):
            continue
        option_attrs = option.attrs
        is_active = index == safe_index
        option_tag = getattr(option, "tag", "")
        option_attrs.pop("role", None)
        option_attrs.pop("aria-checked", None)
        if option_tag == "a":
            option_attrs.pop("aria-pressed", None)
            if is_active:
                option_attrs["aria-current"] = "true"
            else:
                option_attrs.pop("aria-current", None)
        elif option_tag == "button":
            option_attrs.pop("aria-current", None)
            option_attrs.setdefault("type", "button")
            option_attrs["aria-pressed"] = "true" if is_active else "false"
        if index == safe_index:
            current_cls = option_attrs.get("class", option_attrs.get("cls", ""))
            option_attrs["class"] = merge_classes(current_cls, active_cls)
            if "cls" in option_attrs:
                del option_attrs["cls"]
        elif active_cls:
            current_cls = option_attrs.get("class", option_attrs.get("cls", ""))
            inactive_tokens = set(str(active_cls).split())
            option_attrs["class"] = " ".join(
                token for token in str(current_cls).split() if token not in inactive_tokens
            )
            option_attrs.pop("cls", None)
        if values is not None:
            option_attrs["data-fs-value"] = values[index]

    user_cls = kwargs.pop("cls", "")
    attrs: dict[str, Any] = {
        "cls": merge_classes(
            "faststrap-segmented-control btn-group",
            "flex-column" if orientation == "vertical" else "",
            user_cls,
        ),
        "role": "group",
        "data_fs_segmented_control": "true",
    }
    if name:
        attrs["data_fs_input_id"] = input_id
    attrs.update(convert_attrs(kwargs))

    children = list(option_list)
    if name and hidden_input:
        selected = values[safe_index] if values else str(safe_index)
        children.append(Input(type="hidden", name=name, value=selected, id=input_id))
    return Div(*children, **attrs)

The control is a server-rendered group, not a keyboard-managed ARIA radio group. Button options retain native button semantics and expose aria-pressed; link options remain links and use aria-current when active. The component does not claim radio-arrow-key behavior or add client-side selection JavaScript.

When name is provided, the optional hidden input contains the currently rendered selection. It is not automatically updated when a user clicks an ordinary button. For submissions, use HTMX/server rendering to return the updated selected state, or use native links/forms appropriate to the workflow.