pysxLearn by building

Compose an interface · Lesson 8 of 28

Conditional views

Choose a live branch and observe when its owned state is created or released.

A conditional view is more than hidden text. Its branch may own inputs, state and effects. Hiding a DOM node and disposing a component are different operations. A lazy branch creates only the content that is currently selected.

Use a readable condition in the template. Reading it eagerly into a plain bool before returning the fragment freezes that decision, just as an eager counter read froze the snapshot in lesson three.

Understand the moving parts

The DSL supports if/elif/else and matching, while when provides an explicit lazy construction helper. Do not build both expensive alternatives in Python and then choose between the already-built results.

The demo keeps a parent count while mounting and removing a child. The child has its own local count and cleanup. Increment both, remove the child and restore it: the parent should retain its count while the new child starts fresh.

Walk through the code

from pysx import Fragment, local_state, on_cleanup, pysx, signal


def app() -> Fragment:
    visible = signal(True)
    parent = signal(0)
    cleanups = signal(0)

    def Child() -> Fragment:
        count = local_state("child-count", 0)
        on_cleanup(lambda: cleanups.update(lambda value: value + 1))

        def increment(_: object) -> None:
            count.update(lambda value: value + 1)

        return pysx(t"""
            section(id="conditional-child")
                button(id="child-increment" onClick={increment}): "Increment child"
                output(id="child-count"): {count}
        """)

    def toggle(_: object) -> None:
        visible.set(not visible())

    def increment(_: object) -> None:
        parent.update(lambda value: value + 1)

    return pysx(t"""
        div:
            button(id="branch-toggle" onClick={toggle}): "Hide or show child"
            button(id="parent-increment" onClick={increment}): "Increment parent"
        output(id="parent-count"): {parent}
        output(id="branch-cleanups"): {cleanups}
        if {visible}:
            Child:
        else:
            p(id="child-absent"): "The child owner has been disposed."
    """)

visible selects the child lifetime. The parent count lives outside that branch. Removing the child runs its cleanup; showing it again creates a new local count at zero while the parent retains its value.

Try it live

Increment the parent and child, hide the child, show it again, and inspect the cleanup count.

What to observe

The child restarts at zero; the parent count stays. Cleanup increases when the child leaves.

00
0

Take this with you

Choose branches lazily and make their lifetime boundaries explicit.