pysxLearn by building

Navigation · Lesson 16 of 28

Accessible keyboard and DOM capabilities

Operate an accessible chooser with keys and an owned focus command.

Accessibility comes from behavior as well as attributes. A combobox needs an expanded state, an active option and predictable keys. A roving control needs one tab stop and actual focus movement, not only a highlighted background.

The server cannot synchronously inspect arbitrary browser nodes. Dom gives an owned ref, and its handle exposes bounded asynchronous capabilities after mount. A command must stay inside the component's ownership boundary.

Understand the moving parts

The chooser below keeps input focus while ArrowUp/ArrowDown changes the active option. Enter selects, and Escape closes. ARIA state follows the same sources as the visible state so the two cannot drift apart.

A focus button awaits the ref's handle. Preventing the arrow key's native default is declared in on_event, before the callback travels to Python. Try Tab and Shift+Tab as well as the chooser's own keys.

Walk through the code

from dataclasses import dataclass
from pysx import BrowserEvent, Dom, Fragment, derived, each, on_event, pysx, signal


@dataclass(frozen=True)
class TreeEntry:
    key: str
    label: str
    children: tuple[TreeEntry, ...] = ()


def tree_controls() -> Fragment:
    root = TreeEntry("root", "Projects", (TreeEntry("read", "Read"), TreeEntry("build", "Build")))
    dom = Dom()
    refs = {key: dom.ref() for key in ("root", "read", "build")}
    opened = signal(False)
    active = signal("root")
    chosen = signal("")
    labels = {"root": "Projects", "read": "Read", "build": "Build", "": "None"}
    selection = derived(lambda: labels[chosen()])

    def node(entry: TreeEntry, level: int = 1) -> Fragment:
        async def keyboard_event(event: BrowserEvent) -> None:
            shown = ["root", "read", "build"] if opened() else ["root"]
            index = shown.index(entry.key)
            destination = entry.key

            if event.key == "ArrowRight" and entry.children:
                if opened():
                    destination = entry.children[0].key
                else:
                    opened.set(True)
            elif event.key == "ArrowLeft":
                if entry.key == "root":
                    opened.set(False)
                destination = "root"
            elif event.key in ("ArrowDown", "ArrowUp"):
                destination = shown[
                    max(0, min(len(shown) - 1, index + (1 if event.key == "ArrowDown" else -1)))
                ]
            elif event.key in ("Home", "End"):
                destination = shown[0 if event.key == "Home" else -1]
            elif event.key == "Enter":
                chosen.set(entry.key)
            active.set(destination)
            await refs[destination].handle().focus()

        key_handler = on_event(
            keyboard_event,
            keys=(
                "ArrowRight",
                "ArrowLeft",
                "ArrowDown",
                "ArrowUp",
                "Home",
                "End",
                "Enter",
            ),
            prevent_default=True,
            stop_propagation=True,
        )
        tab_stop = derived(lambda: 0 if active() == entry.key else -1)
        expanded = opened if entry.children else None
        selected = derived(lambda: chosen() == entry.key)
        children = each(
            derived(lambda: entry.children),
            lambda child: node(child, level + 1),
            key=lambda child: child.key,
        )

        return pysx(t"""
            li(id={"lesson-tree-" + entry.key} ref={refs[entry.key]} role="treeitem"
                tabindex={tab_stop} aria-expanded={expanded} aria-level={level}
                aria-selected={selected} onKeydown={key_handler})
                span: {entry.label}
                if {bool(entry.children)}:
                    if {opened}:
                        ul(role="group")
                            {children}
        """)

    return pysx(t"""
        ul(id="lesson-tree" role="tree" aria-label="Project learning tree")
            {node(root)}
        output(id="tree-selection"): {selection}
    """)


def app() -> Fragment:
    dom = Dom()
    ref = dom.ref()
    active = signal(0)
    opened = signal(False)
    selected = signal("None")
    labels = ("Read", "Build", "Ship")
    descendant = derived(lambda: f"choice-{active()}")

    def key(event: BrowserEvent) -> None:
        if event.key in ("ArrowDown", "ArrowUp"):
            active.set((active() + (1 if event.key == "ArrowDown" else -1)) % len(labels))
            opened.set(True)
        elif event.key == "Enter":
            selected.set(labels[active()])
            opened.set(False)
        elif event.key == "Escape":
            opened.set(False)

    async def focus(_: object) -> None:
        await ref.handle().focus()

    key_handler = on_event(
        key, keys=("ArrowDown", "ArrowUp", "Enter", "Escape"), prevent_default=True
    )
    tree = tree_controls()

    return pysx(t"""
        label(for="chooser"): "Choose a project stage"
        input(id="chooser" role="combobox" ref={ref} ariaControls="choices"
            ariaExpanded={opened} ariaActivedescendant={descendant}
            onKeydown={key_handler})
        ul(id="choices" role="listbox" hidden={derived(lambda: not opened())})
            li(id="choice-0" role="option"
                ariaSelected={derived(lambda: active() == 0)}):
                "Read"
            li(id="choice-1" role="option"
                ariaSelected={derived(lambda: active() == 1)}):
                "Build"
            li(id="choice-2" role="option"
                ariaSelected={derived(lambda: active() == 2)}):
                "Ship"
        button(id="focus-chooser" onClick={focus}): "Focus chooser"
        output(id="chooser-selection"): {selected}
        h3: "A recursive tree with one tab stop"
        {tree}
    """)

The chooser keeps focus on its input while arrow keys update the active option, Enter selects and Escape closes it. ARIA attributes read the same state. The awaited ref command focuses the input. The second control applies owned refs and a single roving tab stop to a recursive tree.

Try it live

Focus the chooser, press Down, Escape, Down again, then Enter.

What to observe

Selection, active-descendant and expanded state agree, and the focus button focuses the input.

None

A recursive tree with one tab stop

None

Take this with you

Test keyboard focus and ARIA together; an owned ref grants only bounded browser access.