Rook
РусскийRU
// A topic sends a copy from its worker to every listening thread.
const progress = topic<number>("scene-progress")
async func show(t topic number) {
for value in t {
console.log("progress:", value)
}
}
func work(t topic number) number {
t <- 1
t <- 2
return 2
}
show(progress)
console.log("done:", await go work(progress))
<-after(20)
close(progress)
move 12 of 16 · main

Async task 1 resumes on the same thread.

Topics

topic<T>(name) passes values between the tabs of a site, over the BroadcastChannel of that name. cart <- e sends to every other tab that listens and goes on at once, so it is allowed in any function and event handler; the tab that sends does not get its own value. <-cart, for e in cart and select receive, as from a channel.

A topic listens from its first receive on and keeps what comes until it is received. Two topics of the same name each get every value, and close(cart) stops one, so a component closes its topic with defer close(cart) in mount. The values go to other tabs as copies, so they are data, as the arguments of go are; a goroutine that gets a topic sends to the tabs too.

When one tab changes the task board, a topic can publish that board update to the other open tabs. Each tab listens independently and applies the update to its own view.

// topic<T>(name) passes values between the tabs of a site. Open this page in two tabs and run
// the example in both: what one tab adds, the other shows
interface CartEvent {
    kind "add" | "clear"
    title string
}

comp Cart() {
    state items string[] = []
    const cart = topic<CartEvent>("guide-cart")

    func apply(e CartEvent) {
        if e.kind == "add" {
            items.push(e.title)
        } else {
            items = []
        }
    }

    // A tab does not hear what it sends, so it applies its own change
    func change(e CartEvent) {
        apply(e)
        cart <- e
    }

    // What the other tabs send, from the first receive on
    async func follow() {
        for e in cart {
            apply(e)
        }
    }

    mount {
        follow()
        defer close(cart)
    }

    return <div class="card">
        <button onClick={change({ kind: "add", title: `Book ${items.length + 1}` })}>Add a book</button>
        <button onClick={change({ kind: "clear", title: "" })}>Clear</button>
        <p>In the cart: {items.length == 0 ? "nothing" : items.join(", ")}</p>
    </div>
}

document.body.append(<Cart />)