The ecosystem · packages/presence
Who is here, who is typing, and where they point
An avatar stack, a typing line and live cursors for a shared page, fed by a room the server keeps. Tabs come and go cleanly: a reload doesn't flicker, and a laptop that shuts is swept out.
Use it when people share a page (a board, a document, a quiz) and should see who else is there. A room is the set of people on that page right now, each with a name, a colour and a status. The package has three components that show a room (<AvatarStack>, <TypingIndicator> and <LiveCursors>), a browser side that joins one (Presence.join!), and a server side that keeps it (PresenceServer), all on a route's channel.
A room, in your browser#
This site has no server, so the demo plays its part: it keeps a list of who is here and tells the package's stores what a room's channel would. Press a button, or let Auto (on from the start) act every 1.5 seconds.
3 here
Faces grow in and fade out. A typing line runs out on its own; no message says the person stopped. A cursor glides to each place it is sent, fades once still (press Auto to stop them), and is forgotten later. The demo's times are short (four seconds for typing, three to fade, twenty to forget); Presence.join! uses seven, five and thirty.
Using it#
Name the package in the app's header, as for any package. It isn't a plugin, so the program needs nothing more:
app [program] { pf: platform "…/server/platform/main.roc", presence: "…/packages/presence/main.roc" }rocx generate (which rocx dev and rocx build run first) copies the components and browser stores into the app, so both halves compile them. Each component takes its data as an accessor (a function ending in ! that reads a value), so it shows whatever feeds it: a room's channel, or here, the demo.
import presence.AvatarStack
import presence.Cursors
import presence.LiveCursors
import presence.TypingIndicator
import presence.Presence
import presence.Room
import presence.Stack
import presence.Wire
(members!, set_members!) = create_signal!(cast.take_first(3))
…
typing = Presence.create_typing!(4000)
cursors = Presence.create_cursors!({ idle: 3000, forget: 20000 })
<AvatarStack faces!={members!().map(Wire.face)} max={5} />
<LiveCursors cursors!={Wire.pointers(members!(), (cursors.shown!)())} on_move!={pointer.moved!} on_leave!={pointer.away!}>
<div class="note" aria-hidden="true">
<p class="note-title">Notes for Friday</p>
<p class="line"></p>
<p class="line short"></p>
<p class="line"></p>
<p class="line shorter"></p>
</div>
</LiveCursors>
<TypingIndicator names!={Wire.names(members!(), (typing.who!)())} />In an app, a room is a route's channel under api/, named by its URL. The channel's check admits a member as the person the middleware says they are: key and metadata come from the server, never the page. Its hooks are PresenceServer's, so a tab joins as it subscribes and leaves when the subscription ends. The whole route from examples/board:
import pf.Server
import pf.Endpoint
import pf.Channel
import presence.PresenceServer
import presence.Wire
import ../../../../../../Board
import ../../../../../../Middlewares
## /api/b/<board>/presence: who is on the board (packages/presence), as a channel (D-020). A tab is in
## the board's room while it subscribes, as the person the middleware says, in the colour they
## picked; its `data` is the card it has open (`Board.Viewing`, none to start), which its page says
## and every tile shows. The room's hooks are the package's.
channel! : { request : Server.Request, params : { board : Str }, context : Middlewares.Member } => Try(Channel(Wire.Member(Board.Viewing), Wire.Event(Wire.Meta(Board.Viewing)), Wire.Said(Board.Viewing)), Endpoint.Refusal)
channel! = |{ context, .. }| Ok(Channel.allow({ key: context.me.id, meta: { ..Wire.meta(context.me.name, { card: "" }), color: context.me.color } }))
on_open! = PresenceServer.on_open!
on_close! = PresenceServer.on_close!
receive! = PresenceServer.receive!The page joins with Presence.join!, given the channel. It subscribes, tells the room every 15 seconds that the tab is still here, and returns the accessors the components read (members!, others!, typing!, cursors!) and the functions that tell the room about this tab (status!, update!, typed!, moved!…). It all goes over the tab's one live stream, with its other channels; presence needs no other endpoint.
# Who is here (packages/presence): the board's room, on its channel (one stream with the board's
# own), and the card this tab has open as its `data`, said whenever that changes; `Away` while
# the tab is hidden (`<Document on:visibilitychange.visible>`, below: D-055).
here = Presence.join!(Api.channel_api_b_board_presence({ board: board }))
create_effect!(|| open!(), |card| (here.update!)({ card: card }))
…
<Document on:visibilitychange.visible={here.visible!} />A status is Online (the start), Away, Busy or Offline: a typo is a compile error, and the avatar stack knows how to show each. Set it from a handler or an effect with (here.status!)(Busy). To show a hidden tab as away, add <Document on:visibilitychange.visible={here.visible!} />: while hidden, the tab is Away and its cursor gone; shown again, its status comes back.
A member's metadata, Wire.Meta(d), is what the components show (name, picture, colour, status) plus data: the app's own, of any type JSON can carry and == can compare ({} for none). The channel's check sets it first; the page changes data with (here.update!)(data), up to a kibibyte of JSON. On the board it is the card a person has open ({ card : Str }), shown on each tile. Name, picture and colour stay the server's. A room where only the server may set data refuses Update in its own receive!. Wire.meta(name, data) makes metadata, leaving the rest to the components.
<AvatarStack>#
| Prop | Is |
|---|---|
faces! : () => List(Stack.Face) | who is here, in order: { key, name, image, color, status }, made from a member by Wire.face. With no image, a face shows its initials on its color; with no color either, on one picked from its key, the same every time |
max : U64 ?? 5 | how many places the stack takes, counting the +N |
label : Str ?? "" | what a screen reader hears for the stack; when empty, it says who is here: "Ann, Bo and 2 others are here" |
Each face gets its status as a class, such as status-away. Online needs no mark (being in the stack says it); Away dims the face and adds an orange dot; Busy adds a red dot; Offline greys the face (as examples/quiz shows a player who dropped). A screen reader hears the status after the name: "Alan Turing (away)". The +N's tooltip names who it stands for.
<TypingIndicator>#
Ada Lovelace and Alan Turing are typing…
| Prop | Is |
|---|---|
names! : () => List(Str) | who is typing; Wire.names(members, keys) turns the room's keys into names |
say : (List(Str) -> Str) ?? Typing.sentence | writes the sentence: "Ann is typing…", "Ann and Bo are typing…", "Ann, Bo and 2 others are typing…". Give your own for another language |
Three bobbing dots and the sentence. With no one typing, the line keeps its height, so nothing below jumps. A screen reader hears it change (aria-live="polite").
<LiveCursors>#
What everyone points at
| Prop | Is |
|---|---|
cursors! : () => List(LiveCursors.Pointer) | others' cursors, { key, name, color, x, y, idle }, made by Wire.pointers(members, cursors). x and y are fractions of the area (0 to 1), so a place is the same on any screen |
children : List(Html) | the area they point at |
on_move! : (Html.Point => {}) ?? |_| {} | called with your own pointer's place over the area (fractions of it), at most once a frame. Pass a room's here.moved!, which sends it at most 20 times a second |
on_leave! : (() => {}) ?? || {} | called when your pointer leaves the area. Pass a room's here.away! |
Each cursor is an arrow in its member's colour, with their name. Cursors take no pointer events, so clicks reach what is under them. To send your own, write <LiveCursors … on_move!={here.moved!} on_leave!={here.away!}>; over the demo's note, yours shows as the others would see it, labelled You. Since it listens to the pointer, <LiveCursors> must be outside a <NoHydration>, as the sample above is.
A room only some may see#
Everyone on a room's channel hears who is here. When the people in a room mustn't see each other (an app whose customers are in organizations of their own, with operators who want to see who has it open), keep the room on a channel only the watchers may subscribe to. The members come in through a channel of their own, whose hooks call PresenceServer's with the watchers' channel (PresenceServer.on_open!({ who, tab, channel: watched }), and the same for on_close! and receive!) and send their tabs nothing of the room. The watchers' route answers with on_open! = PresenceServer.watch!, which sends who is here without joining the watcher, and their page reads the room with Presence.watch!(channel). The package's README has both routes in full.
How a room works#
The server keeps the room in its own memory: no broker to run. Room is the room's state: who is here, with their metadata, since when, and from which tabs. join, leave, update (new metadata) and sweep return the changes others should hear (Joined, Left or Changed), numbering the state with each. Room never reads a clock: the caller passes the time in, so tests check a timeout without waiting:
Meta : { name : Str, status : Str }
ann : Meta
ann = { name: "Ann", status: "here" }
start : Room(Meta)
start = Room.empty(Room.defaults)
# Leaving with grace: still here until the sweep after it.
expect {
(room, _) = start.join({ key: "ann", tab: "a1", meta: ann, now: 1000 })
(left, changes) = room.leave("ann", "a1", 2000)
(early, before) = left.sweep(6999)
(_, after) = early.sweep(7000)
changes == [] and before == [] and after == [Left({ key: "ann", meta: ann, since: 1000 })]
}- Leaving has a grace period. A member with two tabs is one face, and leaves with the last. A tab whose stream ends leaves after five seconds unless it is back, so a reload or reconnect doesn't flicker out and in. A page that drops the room while the tab stays open (it went to another room) leaves at once: its
on_close!hook is toldDropped. - Vanishing has a timeout. A page says it is here every 15 seconds; a tab unheard for 75 seconds (a laptop shut, a network gone) is swept out, however long its connection lingers. Browsers may slow a hidden tab's timers to once a minute, so 75 seconds is that minute plus a beat. The live stream usually notices first: the server writes a beat on it every 15 seconds, and drops a connection that leaves it unacknowledged for 20. That ends the tab's subscription (
Gone), and the grace runs from there. - Changes are numbered. A page's copy of the room (
Mirror) takes a snapshot, then each change in order, ignoring any older than the snapshot. A skipped number means a missed change, and the page asks for a fresh snapshot. - Kept in memory, swapped in. Each room lives in the server's Kv store. A change reads the room, sweeps it, changes it, and writes it back only if no one else changed it meanwhile (
Kv.swap!), else reads it again. So two tabs joining at once both count, and nothing is written to the database. The change is then published on the room's channel, numbered. Since each change sweeps first, a tab past its grace goes at the room's next change, another tab's beat at the latest. A room silent for a quarter of an hour is forgotten. - Typing and cursors are passed on, never kept. The server forwards them to the other tabs. Only a cursor's latest place counts, so a tab that falls behind skips to it.
The stores#
The browser's side is a set of Solid-style stores: functions you call in a component, like create_signal!, that keep state in signals. join! is a whole room on its channel; the others are its parts, and take what a room says however it arrives, so you can feed them from elsewhere, as the demo does.
| Store | Gives |
|---|---|
Presence.join!(channel) | the room on a route's channel, joined while the component is on the page: everything create_room! gives, fed by the channel, plus others! (everyone but you) and what this tab says: status!(status), update!(data), typed!() and done!(), moved!(point) and away!(), visible!(shown). Every 15 seconds it tells the room this tab is here, and repeats its data if the room has other data for it |
Presence.watch!(channel) | the room on a route's channel, watched but never joined (the route's on_open! is PresenceServer.watch!): members! and synced!, as the channel says. This tab says nothing to the room |
Presence.create_room!(on_gap!) | all the parts at once, fed a room's events with heard!(event): members!, synced!, me! (this tab's key and id), typing! (others' keys), cursors! (others'), and lost! for when the stream drops. Someone who leaves stops typing, and their cursor goes |
Presence.create_presence!(on_gap!) | who is here: members!, synced!, receive!(message), lost!. on_gap! runs when a change was missed |
Presence.create_typing!(ttl) | who is typing: who!, started!(key), stopped!(key). A ping lasts ttl milliseconds |
Presence.create_typist!(every, send!) | your own typing: call typed!() on each key and done!() when the text is sent or left. send! is given Started (at once, then at most every every milliseconds) or Stopped |
Presence.create_cursors!({ idle, forget }) | others' cursors: shown!, moved!(move), gone!(key) |
Presence.create_pointer!(every, send!) | your own pointer: moved!(point) and away!(). send! is given Moved(point) at once, then at most every every milliseconds (the latest place held and sent when due, so a cursor ends where the pointer stopped), or Away |
Call each store at most once per handler. As in Solid 2.0, a handler's writes apply when it is done, so a second call sees the store as it was before the first, and the first change is lost. A channel gives each event its own handler, so a page fed by one is safe. A store whose entries expire (typing, idle cursors) runs a quarter-second timer only while something can expire.
The demo, with no channel, does what one would: a press tells the stores what happened, one call each, and each cursor move comes from its own timeout.
did! = |step| {
set_members!(step.members)
set_seed!(step.seed)
if (!step.typed.is_empty()) (typing.started!)(step.typed)
if !step.left.is_empty() {
(typing.stopped!)(step.left)
(cursors.gone!)(step.left)
}
var $after = 0
for move in step.moves {
_ = set_timeout!($after, || (cursors.moved!)(move))
$after = $after + 150
}
}
act! = |action| did!(PresenceDemo.act(members!(), seed!(), action))The modules#
Under the components and stores is plain Roc on no platform, so the server's hooks and the browser's stores run the same code. The browser sees these modules through the package's browser.roc; the server also sees PresenceServer. roc test packages/presence/main.roc runs their expects. The package's README lists every function.
| Module | What it does |
|---|---|
Room | a room, as the server keeps it: join, update, heartbeat, leave, quit, sweep, signal; members, version, and deadline (when the next sweep could find someone); save and load for JSON; Room.defaults and beat_every |
Mirror | a page's copy of a room: receive a Snapshot or a numbered Delta (Err(Gap) when one was missed), members, is_synced |
Diff | between(before, after): who left, joined and changed; apply one change |
Throttle | at most one send every every milliseconds: the first at once, the latest held until it is due. A cursor sent 20 times a second ends where the pointer stopped |
Cursors | place (a pointer's pixels as fractions of the area), moved, gone, shown, sweep, coalesce (a burst, one move per member), percent |
Typing | who is typing: started, stopped, who, deadline, sentence |
Typist | your own typing: typed(now) says when to ping, done when to say it stopped |
Stack | split (who fits, and the +N), initials ("Ada Lovelace" is "AL"), color (the same key always gets the same colour), names, label; a face's Status and its status_word |
Wire | what a room's channel carries: to a page, an Event (Welcome, Presence, Typing, Moved, Away); from one, a Said (Here with its status, Update with its data, Typing, Moved, Away); who is in it, a Member (a key and a Meta: name, image, color, status, data); meta(name, data); and face, names and pointers to feed the components |
PresenceServer | the server's side: a room channel's hooks, on_open!, on_close! and receive!, with the room kept in Kv |
Styling#
Sizes and colours come from CSS custom properties. The avatar stack: --avatar-size (2rem), --avatar-overlap (0.375rem), --avatar-ring (the ring between faces; set it to the page's background), --avatar-font, --avatar-more, --avatar-away, --avatar-busy and --avatar-offline (an offline face's opacity, 0.5). The typing line: --typing-color and --typing-size. Cursors: --cursor-glide (0.12s; the demo's is 1.4s) and --cursor-font. Under prefers-reduced-motion, the dots stop bobbing and cursors jump instead of gliding.
Status#
Everything above works today. In examples/board, two people in their own browsers see each other, which card each has open, one going away while their tab is hidden, and a third leaving when they close their browser.
Not yet (the package's PROPOSALS.md has details): a room that trusts the live stream's end and drops the page's 15-second beats, and a room named by the page's path with no route of its own (a "who's viewing this page" stack).
The demo: site/Demos/PresenceDemo.rocx
import pf.Html
import pf.Solid exposing [create_signal!, create_signal_with!, set_interval!, set_timeout!]
import presence.AvatarStack
import presence.Cursors
import presence.LiveCursors
import presence.TypingIndicator
import presence.Presence
import presence.Room
import presence.Stack
import presence.Wire
import Random
## A room on the presence page, kept in the browser. The site is static files, with no server to keep
## a room, so the demo plays the server's part: it keeps who is here as a page's copy of the room has
## them (`Room.Here`, what `members!` gives), and tells the package's stores and components what a
## room's stream would: someone joins, leaves or types at a press, or every 1.5 s with Auto, on from
## the start; and the others' cursors wander over the note they share. Your own pointer over the
## note is sent as a room's `here.moved!` sends it (`create_pointer!`: at most 20 times a second,
## the last place kept), and shown as the others see it, as "You" (D-055).
PresenceDemo := [].{
## What a press or a tick did: who is here after it, the seed for the next pick, who started
## typing and who left (`""`: no one), and where the others' cursors go.
Step : { members : List(Room.Here(Wire.Meta({}))), seed : U64, typed : Str, left : Str, moves : List(Cursors.Move) }
Auto : [Off, On(() => {})]
view! : {} => Html
view! = |{}| {
(members!, set_members!) = create_signal!(cast.take_first(3))
(seed!, set_seed!) = create_signal!(2026)
typing = Presence.create_typing!(4000)
cursors = Presence.create_cursors!({ idle: 3000, forget: 20000 })
# Your pointer, sent as a room sends it, and heard back as the others would hear it.
pointer = Presence.create_pointer!(
50,
|said|
match said {
Moved(point) => (cursors.moved!)({ key: "you", x: point.x, y: point.y })
Away => (cursors.gone!)("you")
},
)
# A write applies when its handler is done, so a step is worked out first, then told to each
# store once; and each cursor's move goes as a stream would send it, an event a handler, a
# little after the one before.
did! = |step| {
set_members!(step.members)
set_seed!(step.seed)
if (!step.typed.is_empty()) (typing.started!)(step.typed)
if !step.left.is_empty() {
(typing.stopped!)(step.left)
(cursors.gone!)(step.left)
}
var $after = 0
for move in step.moves {
_ = set_timeout!($after, || (cursors.moved!)(move))
$after = $after + 150
}
}
act! = |action| did!(PresenceDemo.act(members!(), seed!(), action))
(auto!, set_auto!) = create_signal_with!(On(set_interval!(every, || act!(Tick))), { equals: |_, _| Bool.False })
toggle! = ||
match auto!() {
On(clear!) => {
clear!()
set_auto!(off)
}
Off => set_auto!(On(set_interval!(every, || act!(Tick))))
}
<div class="presence-demo">
<div class="top">
<AvatarStack faces!={members!().map(Wire.face)} max={5} />
<p class="here">{"${members!().len().to_str()} here"}</p>
</div>
<LiveCursors cursors!={Wire.pointers(members!(), (cursors.shown!)())} on_move!={pointer.moved!} on_leave!={pointer.away!}>
<div class="note" aria-hidden="true">
<p class="note-title">Notes for Friday</p>
<p class="line"></p>
<p class="line short"></p>
<p class="line"></p>
<p class="line shorter"></p>
</div>
</LiveCursors>
<TypingIndicator names!={Wire.names(members!(), (typing.who!)())} />
<div class="buttons">
<button type="button" class="join" on:click={|| act!(Join)} disabled?={members!().len() >= cast.len()}>Someone joins</button>
<button type="button" class="leave" on:click={|| act!(Leave)} disabled?={members!().len() <= 1}>Someone leaves</button>
<button type="button" class="type" on:click={|| act!(Type)} disabled?={members!().len() <= 1}>Someone types</button>
<button type="button" class="auto" aria-pressed={if (PresenceDemo.is_on(auto!())) "true" else "false"} on:click={toggle!}>Auto</button>
</div>
</div>
}
## What `action` does to the room: the next of the cast who isn't here joins; one of the others
## (you are first, and never go), picked at random, leaves or types; or, for Auto, one of these
## (typing three times in ten, joining two, leaving two, or nothing), then the others' cursors
## wander.
act : List(Room.Here(Wire.Meta({}))), U64, [Join, Leave, Type, Tick] -> PresenceDemo.Step
act = |members, seed, action| {
others = members.drop_first(1)
roll = Random.below(seed, U64.max(others.len(), 1))
picked =
match others.get(roll.value) {
Ok(member) => member.key
Err(_) => ""
}
same = { members, seed: roll.seed, typed: "", left: "", moves: [] }
match action {
Join =>
match cast.find_first(|member| !members.any(|here| here.key == member.key)) {
Ok(member) => { ..same, members: members.append(member) }
Err(_) => same
}
Leave => { ..same, members: members.drop_if(|member| member.key == picked), left: picked }
Type => { ..same, typed: picked }
Tick => {
dice = Random.below(roll.seed, 10)
acted =
if dice.value < 3 {
PresenceDemo.act(members, dice.seed, Type)
} else if dice.value < 5 {
PresenceDemo.act(members, dice.seed, Join)
} else if dice.value < 7 {
PresenceDemo.act(members, dice.seed, Leave)
} else {
{ ..same, seed: dice.seed }
}
PresenceDemo.wander(acted)
}
}
}
## A new place on the note for each of the others' cursors: in its top left, so that a name, to the
## right of and under its arrow, is never cut off, even on a phone.
wander : PresenceDemo.Step -> PresenceDemo.Step
wander = |step| {
var $seed = step.seed
var $moves = []
for member in step.members.drop_first(1) {
x = Random.below($seed, 560)
y = Random.below(x.seed, 620)
$seed = y.seed
$moves = $moves.append({ key: member.key, x: 0.04 + x.value.to_dec() / 1000.0, y: 0.08 + y.value.to_dec() / 1000.0 })
}
{ ..step, seed: $seed, moves: $moves }
}
is_on : PresenceDemo.Auto -> Bool
is_on = |auto|
match auto {
On(_) => Bool.True
Off => Bool.False
}
<style>
.presence-demo {
--avatar-ring: var(--bg-raised);
--avatar-more: var(--rule-strong);
--avatar-away: var(--warn);
--avatar-busy: var(--bad);
--typing-color: var(--text-muted);
--cursor-glide: 1.4s;
display: grid;
gap: var(--space-3);
}
.top {
display: flex;
align-items: center;
gap: var(--space-3);
}
.here {
margin: 0;
color: var(--text-muted);
font-size: var(--size-sm);
}
.note {
display: grid;
gap: var(--space-3);
min-height: 11rem;
padding: var(--space-4) var(--space-5);
border: 1px solid var(--rule-strong);
border-radius: var(--radius);
background: var(--bg-sunken);
}
.note-title {
margin: 0;
font-weight: 600;
}
.line {
height: 0.6rem;
margin: 0;
border-radius: var(--pill);
background: var(--fill-strong);
}
.short {
width: 70%;
}
.shorter {
width: 45%;
}
.buttons {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
}
button {
padding: var(--space-1) var(--space-3);
font-size: var(--size-sm);
}
.auto[aria-pressed="true"] {
background: var(--accent-soft);
color: var(--accent);
}
</style>
}
## How often Auto does something, in milliseconds.
every : U64
every = 1500
off : PresenceDemo.Auto
off = Off
## Who may be here, in the order they come: you, here from the start and never leaving, then Ada and
## Alan, also here from the start, then the others.
cast : List(Room.Here(Wire.Meta({})))
cast = [
member("you", "You", "#2e8fa3", Online),
member("ada", "Ada Lovelace", "", Online),
member("alan", "Alan Turing", "", Away),
member("grace", "Grace Hopper", "", Online),
member("edsger", "Edsger Dijkstra", "", Busy),
member("barbara", "Barbara Liskov", "", Online),
member("donald", "Donald Knuth", "", Online),
]
member : Str, Str, Str, Stack.Status -> Room.Here(Wire.Meta({}))
member = |key, name, color, status| { key, meta: { ..Wire.meta(name, {}), color, status }, since: 0 }
keys : PresenceDemo.Step -> List(Str)
keys = |step| step.members.map(|here| here.key)
start : PresenceDemo.Step
start = { members: cast.take_first(3), seed: 2026, typed: "", left: "", moves: [] }
then : PresenceDemo.Step, [Join, Leave, Type, Tick] -> PresenceDemo.Step
then = |step, action| PresenceDemo.act(step.members, step.seed, action)
expect keys(then(start, Join)) == ["you", "ada", "alan", "grace"]
# Leaving takes one of the others, never you; once only you are here, no one leaves.
expect {
one = then(start, Leave)
two = then(one, Leave)
three = then(two, Leave)
one.left != "" and two.left != "" and three.left == "" and keys(three) == ["you"]
}
# Typing is one of the others, and changes no one.
expect {
typed = then(start, Type)
typed.typed != "" and typed.typed != "you" and keys(typed) == keys(start)
}
# Everyone in the cast here, the next join is no change.
expect {
full = [1, 2, 3, 4, 5].fold(start, |step, _| then(step, Join))
keys(full) == ["you", "ada", "alan", "grace", "edsger", "barbara", "donald"] and keys(then(full, Join)) == keys(full)
}
# Auto, many times over: you are always here, someone comes or goes, and each of the others' cursors
# goes somewhere on the note, with room for its name.
expect {
steps = List.repeat({}, 40).fold([start], |seen, _| seen.append(then(seen.last() ?? start, Tick)))
here = steps.all(|step| keys(step).first() == Ok("you") and step.members.len() <= 7) and steps.any(|step| step.members.len() != 3)
moved = steps.drop_first(1).all(|step| step.moves.map(|move| move.key) == keys(step).drop_first(1) and step.moves.all(|move| move.x >= 0.04 and move.x <= 0.6 and move.y >= 0.08 and move.y <= 0.7))
here and moved
}The avatar stack: packages/presence/components/AvatarStack.rocx
import pf.Html
import pf.Solid exposing [create_memo!]
import pf.Transition
import presence.Stack
## Who is here, as a row of overlapping avatars: a picture, or initials on a colour of their own,
## and their status (`Stack.Status`, a class each: `status-away`): `Online` as it is, `Away` dimmed
## with an orange dot, `Busy` with a red one, `Offline` greyed. Past `max`, the last place says how
## many more (`+3`). One who comes grows in, one who goes fades out. A screen reader hears who is
## here (`Stack.label`), or `label` when one is given, and each face's status after its name.
##
## A "who's viewing this page" stack needs a room for the page: a route's channel today
## (PROPOSALS.md, question 1).
AvatarStack := [].{
Props := {
faces! : () => List(Stack.Face),
max : U64 ?? 5,
label : Str ?? "",
}
view! : Props => Html
view! = |{ faces!, max, label }| {
split! = create_memo!(|| Stack.split(faces!(), max))
<div class="avatar-stack" role="group" aria-label={if (label.is_empty()) Stack.label(faces!()) else label}>
{...split!().shown.map(|face|
<span key={face.key}
class={"avatar status-${Stack.status_word(face.status)}"}
role="img"
aria-label={Stack.said(face)}
title={face.name}
style:--avatar-color={Stack.color_of(face)}
transition={Transition.scale(0.5).plus(Transition.fade)}
>
{if (face.image.is_empty()) <span class="initials" aria-hidden="true">{Stack.initials(face.name)}</span> else <img src={face.image} alt="" />}
</span>
)}
{if split!().more > 0 {
<span class="avatar more" role="img" aria-label={"and ${split!().more.to_str()} more"} title={more_names(faces!(), split!().shown.len())}>
+{split!().more.to_str()}
</span>
}}
</div>
}
<story name="Three here">
<AvatarStack faces!={|| [sample("ada", "Ada Lovelace", Online), sample("alan", "Alan Turing", Away), sample("grace", "Grace Hopper", Online)]} />
</story>
<story name="More than fit">
<AvatarStack
faces!={|| [sample("ada", "Ada Lovelace", Online), sample("alan", "Alan Turing", Online), sample("grace", "Grace Hopper", Busy), sample("edsger", "Edsger Dijkstra", Online), sample("barbara", "Barbara Liskov", Online), sample("donald", "Donald Knuth", Away), sample("frances", "Frances Allen", Online)]}
max={4}
/>
</story>
<story name="One dropped">
<AvatarStack faces!={|| [sample("ada", "Ada Lovelace", Online), sample("alan", "Alan Turing", Offline), sample("grace", "Grace Hopper", Online)]} />
</story>
<style>
.avatar-stack {
display: inline-flex;
flex-direction: row;
align-items: center;
padding-left: var(--avatar-overlap, 0.375rem);
}
.avatar {
position: relative;
display: inline-grid;
place-items: center;
width: var(--avatar-size, 2rem);
height: var(--avatar-size, 2rem);
margin-left: calc(-1 * var(--avatar-overlap, 0.375rem));
border-radius: 50%;
background: var(--avatar-color, #4f6bed);
box-shadow: 0 0 0 2px var(--avatar-ring, Canvas);
color: #fff;
/* Longhands: `inherit` inside the `font` shorthand would drop the whole of it. With no
--avatar-font, font-family has no value, and so inherits. */
font-family: var(--avatar-font);
font-size: calc(var(--avatar-size, 2rem) * 0.38);
font-weight: 600;
line-height: 1;
letter-spacing: 0.02em;
user-select: none;
}
.avatar img {
width: 100%;
height: 100%;
border-radius: 50%;
object-fit: cover;
}
.avatar.status-away img,
.avatar.status-away .initials {
opacity: 0.55;
}
.avatar.status-offline {
filter: grayscale(1);
opacity: var(--avatar-offline, 0.5);
}
/* A dot for away and busy: the stack is who is here, so being here needs none. */
.avatar.status-away::after,
.avatar.status-busy::after {
content: "";
position: absolute;
right: -1px;
bottom: -1px;
width: 30%;
height: 30%;
border-radius: 50%;
background: var(--avatar-away, #f08c00);
box-shadow: 0 0 0 2px var(--avatar-ring, Canvas);
}
.avatar.status-busy::after {
background: var(--avatar-busy, #e03131);
}
.avatar.more {
background: var(--avatar-more, color-mix(in srgb, currentColor 18%, Canvas));
color: inherit;
}
</style>
}
## The names past those shown: the `+N`'s tooltip.
more_names : List(Stack.Face), U64 -> Str
more_names = |faces, shown| Str.join_with(faces.drop_first(shown).map(|face| face.name), ", ")
sample : Str, Str, Stack.Status -> Stack.Face
sample = |key, name, status| { key, name, image: "", color: "", status }The typing indicator: packages/presence/components/TypingIndicator.rocx
import pf.Html
import presence.Typing
## Who is typing, as a line under a conversation: three dots that bob, and `Ann is typing…`. It says
## nothing (and takes no room's worth of change: its line keeps its height) when no one is. A screen
## reader hears it as it changes (`aria-live`). `say` writes the sentence from the names:
## `Typing.sentence`, in English, unless the app gives its own.
TypingIndicator := [].{
Props := {
names! : () => List(Str),
say : (List(Str) -> Str) ?? Typing.sentence,
}
view! : Props => Html
view! = |{ names!, say }|
<p class="typing-indicator" aria-live="polite">
{if !names!().is_empty() {
<>
<span class="dots" aria-hidden="true"><i></i><i></i><i></i></span>
<span class="said">{say(names!())}</span>
</>
}}
</p>
<story name="One">
<TypingIndicator names!={|| ["Ada"]} />
</story>
<story name="Several">
<TypingIndicator names!={|| ["Ada", "Alan", "Grace", "Edsger"]} />
</story>
<style>
.typing-indicator {
display: flex;
align-items: center;
gap: 0.5em;
min-height: 1.5em;
margin: 0;
color: var(--typing-color, color-mix(in srgb, currentColor 65%, transparent));
font-size: var(--typing-size, 0.875em);
}
.dots {
display: inline-flex;
gap: 0.2em;
}
.dots i {
width: 0.4em;
height: 0.4em;
border-radius: 50%;
background: currentColor;
animation: typing-bob 1.2s ease-in-out infinite;
}
.dots i:nth-child(2) {
animation-delay: 0.15s;
}
.dots i:nth-child(3) {
animation-delay: 0.3s;
}
@keyframes typing-bob {
0%,
60%,
100% {
transform: translateY(0);
opacity: 0.4;
}
30% {
transform: translateY(-0.25em);
opacity: 1;
}
}
@media (prefers-reduced-motion: reduce) {
.dots i {
animation: none;
}
}
</style>
}The cursors: packages/presence/components/LiveCursors.rocx
import pf.Html
import pf.Transition
import presence.Cursors
## Others' cursors over an area: what is inside (`children`), and over it, each cursor where its
## member's pointer is, an arrow in their colour with their name beside it. A place is a share of
## the area (`Cursors.place`), so the area may be any size on each screen. A cursor glides between
## the places it is sent (sends are throttled: `Throttle`), fades when idle, and fades out when its
## member leaves. The cursors take no pointer events: what is under them is clicked as before. This
## page's own pointer over the area is `on_move!`'s (`on:pointermove.point`: shares of the area, at
## most once a frame), and its leaving `on_leave!`'s: a room's `here.moved!` and `here.away!`. It
## listens to the pointer, so it goes outside a `<NoHydration>`, which runs no handler.
LiveCursors := [].{
## A cursor, as drawn: whose, their name and colour, where (shares of the area), and whether it
## has been still a while.
Pointer : { key : Str, name : Str, color : Str, x : Dec, y : Dec, idle : Bool }
Props := {
cursors! : () => List(LiveCursors.Pointer),
children : List(Html),
on_move! : (Html.Point => {}) ?? |_| {},
on_leave! : (() => {}) ?? || {},
}
view! : Props => Html
view! = |{ cursors!, children, on_move!, on_leave! }|
<div class="live-cursors" on:pointermove.point={on_move!} on:pointerleave={on_leave!}>
{...children}
<div class="cursor-layer" aria-hidden="true">
{...cursors!().map(|cursor|
<div key={cursor.key}
class="cursor"
class:idle={cursor.idle}
style:--x={Cursors.percent(cursor.x)}
style:--y={Cursors.percent(cursor.y)}
style:--cursor-color={cursor.color}
transition={Transition.fade}
>
<svg viewBox="0 0 16 20" width="16" height="20"><path d="M1 1 L1 16 L5 12 L8 19 L10.5 18 L7.5 11 L13 11 Z" /></svg>
<span class="cursor-name">{cursor.name}</span>
</div>
)}
</div>
</div>
<story name="Two cursors">
<LiveCursors cursors!={|| [{ key: "ada", name: "Ada", color: "#b4235a", x: 0.25, y: 0.3, idle: Bool.False }, { key: "alan", name: "Alan", color: "#1f62b8", x: 0.7, y: 0.6, idle: Bool.True }]}>
<div style="height: 12rem; border: 1px dashed currentColor; border-radius: 8px"></div>
</LiveCursors>
</story>
<style>
.live-cursors {
position: relative;
}
.cursor-layer {
position: absolute;
inset: 0;
overflow: hidden;
pointer-events: none;
}
.cursor {
position: absolute;
left: var(--x);
top: var(--y);
display: flex;
align-items: flex-start;
gap: 2px;
transition: left var(--cursor-glide, 0.12s) linear, top var(--cursor-glide, 0.12s) linear, opacity 0.3s;
will-change: left, top;
}
.cursor svg {
fill: var(--cursor-color, #4f6bed);
stroke: #fff;
stroke-width: 1.2;
filter: drop-shadow(0 1px 1px rgb(0 0 0 / 0.25));
}
.cursor-name {
margin-top: 14px;
padding: 1px 6px;
border-radius: 4px;
background: var(--cursor-color, #4f6bed);
color: #fff;
/* Longhands, as in AvatarStack: with no --cursor-font, font-family inherits. */
font-family: var(--cursor-font);
font-size: 11px;
font-weight: 600;
line-height: 1.4;
white-space: nowrap;
}
.cursor.idle {
opacity: 0.35;
}
@media (prefers-reduced-motion: reduce) {
.cursor {
transition: opacity 0.3s;
}
}
</style>
}The stores: packages/presence/components/Presence.rocx
import pf.Solid exposing [create_effect!, create_signal!, create_signal_with!, on_settled!, set_interval!, set_timeout!]
import pf.Endpoint
import pf.Channel
import pf.Html
import pf.Time
import presence.Cursors
import presence.Mirror
import presence.Room
import presence.Stack
import presence.Throttle
import presence.Typing
import presence.Typist
import presence.Wire
## The browser's side of presence, as Solid primitives: each is called in a component (as
## `create_signal!` is), and keeps its state in signals the components read. `join!` is a room on
## its channel (`PresenceServer`'s hooks on a route's `channel!`): the stores below, fed what the
## channel says, and what this tab says to it. The stores take what a room says however it comes.
## Typing and cursors expire on a clock of their own: a timer that ticks every quarter second, and
## only while something can expire.
##
## Call a store once a handler. A write applies when its handler is done (Solid 2.0's batching), so
## a second call in the same handler sees the store as it was before the first, and the first is
## lost: moving two cursors in one handler moves only the second. A stream hands each event to a
## handler of its own, so a page fed by one never does; a page that makes several events at once
## sends each from a handler of its own (`set_timeout!(0, …)`).
Presence := [].{
## The room on `channel` (a route's `channel!` with `PresenceServer`'s hooks), joined for as long
## as the component is: subscribed to, so this tab is in the room, as the member the channel's
## check says, until the component goes; and told this tab is still here every `Room.beat_every`.
## Who is here (`members!`, `synced!`; `others!`, everyone but this tab's member), this tab's key
## and tab (`me!`), who is typing (`typing!`, keys) and others' cursors (`cursors!`), as
## `create_room!` has them. From a handler or an effect's apply: `status!(status)` says this tab's
## status (`Online` until it says another); `update!(data)` says its member's `data`, the app's
## own (the card it has open), said again at a beat when the room has another (it swept this tab
## out, or another tab of the member's said its own); `typed!()` and `done!()` say it is typing
## (`create_typist!`); `moved!` and `away!` say where its cursor is, at most 20 times a second
## (`create_pointer!`: `<LiveCursors on_move!={here.moved!} on_leave!={here.away!}>`).
## `visible!(shown)` says whether its page shows: while it is hidden the tab is `Away` (and its
## cursor gone), and the status the app said comes back when it shows again:
## `<Document on:visibilitychange.visible={here.visible!} />`.
##
## here = Presence.join!(Api.channel_rooms_room({ room: room }))
## <AvatarStack faces!={(here.others!)().map(Wire.face)} />
join! : Endpoint(c, {}, Channel(Wire.Member(d), Wire.Event(Wire.Meta(d)), Wire.Said(d))) => { members! : () => List(Room.Here(Wire.Meta(d))), others! : () => List(Room.Here(Wire.Meta(d))), synced! : () => Bool, me! : () => { key : Str, tab : Str }, typing! : () => List(Str), cursors! : () => List(Cursors.Shown), status! : Stack.Status => {}, update! : d => {}, typed! : () => {}, done! : () => {}, moved! : Html.Point => {}, away! : () => {}, visible! : Bool => {} }
where [d.is_eq : d, d -> Bool, d.Json.Encodable([]), d.Json.Parseable([InvalidJson(Str)])]
join! = |channel| {
# A missed number: the server sends who is here again (its on_open!'s, after a resync).
room = Presence.create_room!(|| Endpoint.resync!(channel))
heard! = room.heard!
lost! = room.lost!
(status!, set_status!) = create_signal!(Online)
(hidden!, set_hidden!) = create_signal!(Bool.False)
# The member's `data` as this tab said it last, if it said it.
(data!, set_data!) = create_signal!(Err(NotSaid))
said! = |said| {
out : Wire.Said(d)
out = said
Endpoint.say!(channel, out)
}
# What the room hears of this tab's status: `Away` while its page is hidden.
shown! = |status| if (hidden!()) Away else status
# The data this tab said, when the room has other data for its member, or doesn't have them.
stale! = || {
key = (room.me!)().key
match data!() {
Ok(data) =>
match (room.members!)().find_first(|member| member.key == key) {
Ok(member) if member.meta.data == data => Err(Same)
_ => Ok(data)
}
Err(NotSaid) => Err(Same)
}
}
create_effect!(
|| {},
|{}|
Endpoint.subscribe!(
channel,
|event|
match event {
# Who is here comes next, as the channel's first messages.
Resync => {}
Message(message) => heard!(message)
Refused(_, _) => lost!()
Ended(_) => lost!()
},
),
)
beat! = || {
said!(Here({ status: shown!(status!()) }))
match stale!() {
Ok(data) => said!(Update(data))
Err(Same) => {}
}
}
on_settled!(
|| {
_ = set_interval!(Room.beat_every(Room.defaults), beat!)
{}
},
)
typist = Presence.create_typist!(3000, |typing| said!(Typing(typing == Started)))
pointer = Presence.create_pointer!(
cursor_every,
|said|
match said {
Moved(point) => said!(Moved(point))
Away => said!(Away)
},
)
{
members!: room.members!,
others!: || {
key = (room.me!)().key
(room.members!)().drop_if(|member| member.key == key)
},
synced!: room.synced!,
me!: room.me!,
typing!: room.typing!,
cursors!: room.cursors!,
status!: |status| {
set_status!(status)
said!(Here({ status: shown!(status) }))
},
update!: |data| {
set_data!(Ok(data))
said!(Update(data))
},
typed!: typist.typed!,
done!: typist.done!,
moved!: pointer.moved!,
away!: pointer.away!,
visible!: |visible| {
set_hidden!(!visible)
said!(Here({ status: if (visible) status!() else Away }))
if (visible) {} else (pointer.away!)()
},
}
}
## The room on `channel` watched, never joined: who is here (`members!`, `synced!`), as the
## channel says, for a page that shows a room it isn't in (an operators' list of who is online).
## The route's `on_open!` is `PresenceServer.watch!`. This tab says nothing to the room, and is
## not in it.
##
## online = Presence.watch!(Api.channel_api_online({}))
## <AvatarStack faces!={(online.members!)().map(Wire.face)} />
watch! : Endpoint(c, {}, Channel(Wire.Member(d), Wire.Event(Wire.Meta(d)), Wire.Said(d))) => { members! : () => List(Room.Here(Wire.Meta(d))), synced! : () => Bool }
where [d.is_eq : d, d -> Bool, d.Json.Encodable([]), d.Json.Parseable([InvalidJson(Str)])]
watch! = |channel| {
presence = Presence.create_presence!(|| Endpoint.resync!(channel))
receive! = presence.receive!
lost! = presence.lost!
create_effect!(
|| {},
|{}|
Endpoint.subscribe!(
channel,
|event|
match event {
Resync => {}
Message(Presence(message)) => receive!(message)
Message(_) => {}
Refused(_, _) => lost!()
Ended(_) => lost!()
},
),
)
{ members!: presence.members!, synced!: presence.synced! }
}
## This page's pointer, told to others with `send!`: `moved!(point)` for each place
## (`on:pointermove.point`), sent at once, then at most once every `every` milliseconds, the
## latest kept and sent when its time comes (`Throttle`), so a cursor ends where the pointer
## stopped; `away!()` when it leaves the area (what is held is dropped, and `Away` sent).
create_pointer! : U64, ([Moved(Html.Point), Away] => {}) => { moved! : Html.Point => {}, away! : () => {} }
create_pointer! = |every, send!| {
(throttle!, set_throttle!) = create_signal_with!(Throttle.new(every), { equals: |_, _| Bool.False })
(waiting!, set_waiting!) = create_signal!(Bool.False)
# The held place, sent when it is due (the timer was set for then).
due! = |at| {
(next, out) = throttle!().flush(at)
set_throttle!(next)
set_waiting!(Bool.False)
match out {
Send(point) => send!(Moved(point))
_ => {}
}
}
{
moved!: |point| {
now = Time.now_millis!({})
(next, out) = throttle!().push(point, now)
set_throttle!(next)
match out {
Send(sent) => send!(Moved(sent))
Hold(at) =>
if waiting!() {
{}
} else {
set_waiting!(Bool.True)
_ = set_timeout!(at - U64.min(at, now), || due!(at))
{}
}
}
},
away!: || {
set_throttle!(throttle!().drop())
send!(Away)
},
}
}
## A room, as its channel says (`Wire.Event`, from `PresenceServer`'s hooks): who is here
## (`members!`, `synced!`), this page's own key and tab (`me!`, from the channel's `Welcome`), the
## keys of who is typing (`typing!`), and others' cursors (`cursors!`). `heard!` takes each event,
## `lost!` says the stream dropped. Its own typing and cursor come back from the room, and are
## left out; one who leaves stops typing, and their cursor goes. A message after a missed one calls
## `on_gap!`.
create_room! : (() => {}) => { members! : () => List(Room.Here(meta)), synced! : () => Bool, me! : () => { key : Str, tab : Str }, typing! : () => List(Str), cursors! : () => List(Cursors.Shown), heard! : Wire.Event(meta) => {}, lost! : () => {} }
where [meta.is_eq : meta, meta -> Bool]
create_room! = |on_gap!| {
presence = Presence.create_presence!(on_gap!)
typing = Presence.create_typing!(typing_ttl)
cursors = Presence.create_cursors!({ idle: cursor_idle, forget: cursor_forget })
(me!, set_me!) = create_signal!({ key: "", tab: "" })
mine! = |key| key == me!().key
heard! = |event|
match event {
Welcome(you) => set_me!(you)
Presence(message) => {
(presence.receive!)(message)
match message {
Delta(delta) =>
match delta.change {
Left(here) => {
(typing.stopped!)(here.key)
(cursors.gone!)(here.key)
}
_ => {}
}
Snapshot(_) => {}
}
}
Typing(said) => if (mine!(said.key)) {} else if (said.typing) (typing.started!)(said.key) else (typing.stopped!)(said.key)
Moved(move) => if (mine!(move.key)) {} else (cursors.moved!)(move)
Away(key) => (cursors.gone!)(key)
}
{
members!: presence.members!,
synced!: presence.synced!,
me!,
typing!: typing.who!,
cursors!: cursors.shown!,
heard!,
lost!: presence.lost!,
}
}
## Who is here, as a room's channel says: `members!` (in the order they came), `synced!`
## (whether the copy follows the server), `receive!` for each message the channel sends, and
## `lost!` for when it drops (who was here stays on show until the next snapshot). A message
## after a missed one calls `on_gap!`, which should get a snapshot again (`Endpoint.resync!`).
create_presence! : (() => {}) => { members! : () => List(Room.Here(meta)), synced! : () => Bool, receive! : Mirror.Message(meta) => {}, lost! : () => {} }
where [meta.is_eq : meta, meta -> Bool]
create_presence! = |on_gap!| {
(mirror!, set_mirror!) = create_signal_with!(Mirror.empty({}), { equals: |_, _| Bool.False })
receive! = |message|
match mirror!().receive(message) {
Ok((next, _)) => set_mirror!(next)
Err(Gap) => {
set_mirror!(mirror!().unsynced())
on_gap!()
}
}
{
members!: || mirror!().members(),
synced!: || mirror!().is_synced(),
receive!,
lost!: || set_mirror!(mirror!().unsynced()),
}
}
## Who is typing, as others' pings say: `who!` (their keys, in the order they started),
## `started!(key)` for a ping, `stopped!(key)` for a stop (or a member who left). A ping lasts
## `ttl` milliseconds.
create_typing! : U64 => { who! : () => List(Str), started! : Str => {}, stopped! : Str => {} }
create_typing! = |ttl| {
(now!, set_now!) = create_signal!(0)
(typing!, set_typing!) = create_signal_with!(Typing.new(ttl), { equals: |_, _| Bool.False })
(ticking!, set_ticking!) = create_signal!(Bool.False)
tick! = || {
next = now!() + tick
set_now!(next)
match typing!().deadline() {
Ok(at) if at <= next => {
swept = typing!().sweep(next)
set_typing!(swept)
if (swept.deadline().is_err()) set_ticking!(Bool.False) else {}
}
_ => {}
}
}
create_effect!(|| ticking!(), |on| clock!(on, tick!))
{
who!: || typing!().who(now!()),
started!: |key| {
set_typing!(typing!().started(key, now!()))
if (ticking!()) {} else set_ticking!(Bool.True)
},
stopped!: |key| set_typing!(typing!().stopped(key)),
}
}
## This page's typing, told to others with `send!`: `typed!()` on each key (a ping when typing
## starts, then at most every `every` milliseconds), `done!()` when the text is sent or cleared
## or the field is left (a stop, if it had pinged).
create_typist! : U64, ([Started, Stopped] => {}) => { typed! : () => {}, done! : () => {} }
create_typist! = |every, send!| {
(now!, set_now!) = create_signal!(0)
(typist!, set_typist!) = create_signal_with!(Typist.new(every), { equals: |_, _| Bool.False })
(ticking!, set_ticking!) = create_signal!(Bool.False)
tick! = || {
next = now!() + tick
set_now!(next)
rested = typist!().rest(next)
if rested.is_pinging() {
{}
} else {
set_typist!(rested)
set_ticking!(Bool.False)
}
}
create_effect!(|| ticking!(), |on| clock!(on, tick!))
{
typed!: || {
(next, ping) = typist!().typed(now!())
set_typist!(next)
if ping {
send!(Started)
if (ticking!()) {} else set_ticking!(Bool.True)
} else {
{}
}
},
done!: || {
(next, stop) = typist!().done()
set_typist!(next)
if (stop) send!(Stopped) else {}
},
}
}
## Others' cursors, as their moves say: `shown!` (each idle once still for `idle` milliseconds),
## `moved!` for a move, `gone!(key)` for one whose pointer left the area, or who left. One still
## for `forget` milliseconds is forgotten.
create_cursors! : { idle : U64, forget : U64 } => { shown! : () => List(Cursors.Shown), moved! : Cursors.Move => {}, gone! : Str => {} }
create_cursors! = |{ idle, forget }| {
(now!, set_now!) = create_signal!(0)
(cursors!, set_cursors!) = create_signal_with!(Cursors.none, { equals: |_, _| Bool.False })
(ticking!, set_ticking!) = create_signal!(Bool.False)
tick! = || {
next = now!() + tick
set_now!(next)
swept = cursors!().sweep(next, forget)
if swept.count() == cursors!().count() {
{}
} else {
set_cursors!(swept)
if (swept.count() == 0) set_ticking!(Bool.False) else {}
}
}
create_effect!(|| ticking!(), |on| clock!(on, tick!))
{
shown!: || cursors!().shown(now!(), idle),
moved!: |move| {
set_cursors!(cursors!().moved(move, now!()))
if (ticking!()) {} else set_ticking!(Bool.True)
},
gone!: |key| set_cursors!(cursors!().gone(key)),
}
}
}
## How long a typing ping lasts: twice a typist's 3 s (`create_typist!(3000, …)`), and a little
## more for the way there.
typing_ttl : U64
typing_ttl = 7000
## A page's cursor is sent at most every 50 ms: 20 times a second.
cursor_every : U64
cursor_every = 50
## A cursor still for 5 s is idle (faded); one still for 30 s is forgotten.
cursor_idle : U64
cursor_idle = 5000
cursor_forget : U64
cursor_forget = 30000
## A store's clock ticks this often, in milliseconds.
tick : U64
tick = 250
## A store's clock: ticking while `on`, stopped (by the effect's cleanup) when not.
clock! : Bool, (() => {}) => {}
clock! = |on, tick!|
if on {
_ = set_interval!(tick, tick!)
{}
} else {
{}
}The server's side: packages/presence/PresenceServer.roc
import pf.Channel
import pf.Endpoint
import pf.Kv
import pf.Log
import pf.Time
import Mirror
import Room
import Wire
## A room's presence on the server: the hooks of a route's channel (D-020), whose URL is the room.
## Its check lets a member in (`Channel.allow`, with who they are: their key and metadata, from the
## middleware's context, never from the page), and these three are its hooks:
##
## on_open! = PresenceServer.on_open!
## on_close! = PresenceServer.on_close!
## receive! = PresenceServer.receive!
##
## A tab joins as its subscription opens (and gets its key and tab, then who is here), and leaves
## when it ends: at once when its page dropped the room (`Dropped`: it went to another room), after
## the room's grace when its stream went (`Gone`: a reload or a reconnect comes back within it). The
## host tells a tab's hooks in order, an old subscription's end before a new one's start.
## A page says it is here every `Room.beat_every`, with its status (`Here`), so a tab whose page
## vanished without a word (a laptop shut, a network gone) is swept out 75 s after its last word,
## however long its connection lingers. A page may change its member's `data` (`Update`), up to
## `max_data` bytes of JSON; the name, picture and colour stay the check's. Typing and cursors are
## said, and passed on, never kept.
##
## The room is kept in the server's memory (`Kv`, under `presence:<the channel's URL>`), as a
## `Room`: each change reads it, sweeps it, changes it and swaps it back (`Kv.swap!`), so two tabs
## joining at once both count, and nothing is written to the database. What changed is published on the
## channel, numbered; a page that misses a number asks for a snapshot again (`Endpoint.resync!`).
## A room nobody beats in for a quarter of an hour is forgotten; one made again numbers on from the
## time, so a page's copy sees the gap and asks again. The members' metadata is `Wire.Meta(d)`, the
## app's own `data` in it of any type JSON carries both ways and that compares (`{}` for none).
##
## The page's say over `data` is the app's to take away: a room whose `data` only the server may
## set (a role, a team) refuses `Update` in its own `receive!` and hands the rest on:
##
## receive! = |heard|
## match heard.said {
## Update(_) => Err(Forbidden)
## _ => PresenceServer.receive!(heard)
## }
PresenceServer := [].{
## A room's channel: who its members are, what they hear, and what they say.
RoomChannel(c, d) : Endpoint(c, {}, Channel(Wire.Member(d), Wire.Event(Wire.Meta(d)), Wire.Said(d)))
## The most a page's `data` may be, as JSON: a kibibyte. Each change of it goes to everyone in the
## room, and the room holds it for each member.
max_data : U64
max_data = 1024
## A tab subscribed (or asked for a resync): it is in the room, with the member's metadata (the
## status and `data` the member had, if they were here already), and it is sent its key and tab,
## then who is here.
on_open! : { who : Wire.Member(d), tab : Str, channel : PresenceServer.RoomChannel(c, d), .. } => List(Wire.Event(Wire.Meta(d)))
where [d.is_eq : d, d -> Bool, d.Json.Encodable([]), d.Json.Parseable([InvalidJson(Str)])]
on_open! = |{ who, tab, channel, .. }| {
room = changed!(channel, |before, now| before.join({ key: who.key, tab, meta: own(before, who), now }))
[Welcome({ key: who.key, tab }), Presence(Mirror.snapshot(room))]
}
## A tab's subscription ended: it leaves at once if its page dropped the room (`Dropped`), else
## after the room's grace (a page reloading or reconnecting doesn't flicker out and in).
on_close! : { who : Wire.Member(d), tab : Str, why : Channel.Closed, channel : PresenceServer.RoomChannel(c, d), .. } => {}
where [d.is_eq : d, d -> Bool, d.Json.Encodable([]), d.Json.Parseable([InvalidJson(Str)])]
on_close! = |{ who, tab, why, channel, .. }| {
_ = changed!(
channel,
|before, now|
match why {
Dropped => before.quit(who.key, tab, now)
_ => before.leave(who.key, tab, now)
},
)
{}
}
## A tab that watches the room without being in it (an operators' list of who is online): sent who
## is here, the room swept first, then each change as it is published. A room only some may see
## is kept on their channel and joined from another: the members' route hands this channel to the
## hooks (`PresenceServer.on_open!({ who, tab, channel: watched })`, and its own `on_close!` and
## `receive!` the same way) and sends its subscribers nothing of the room, so who joins never
## hears who else is here. The watchers' route:
##
## on_open! = PresenceServer.watch!
watch! : { channel : PresenceServer.RoomChannel(c, d), .. } => List(Wire.Event(Wire.Meta(d)))
where [d.is_eq : d, d -> Bool, d.Json.Encodable([]), d.Json.Parseable([InvalidJson(Str)])]
watch! = |{ channel, .. }| {
room = changed!(channel, |before, _now| (before, []))
[Presence(Mirror.snapshot(room))]
}
## What a page said: its tab is here, with its status; its member's `data` is new (refused, 413,
## past `max_data` bytes of JSON); either way its tab is here (and back, if the room had swept it
## out). Its member is typing, or stopped; its cursor moved (latest wins); its pointer left.
receive! : { who : Wire.Member(d), tab : Str, said : Wire.Said(d), channel : PresenceServer.RoomChannel(c, d), .. } => Try({}, Endpoint.Refusal)
where [d.is_eq : d, d -> Bool, d.Json.Encodable([]), d.Json.Parseable([InvalidJson(Str)])]
receive! = |{ who, tab, said, channel, .. }|
match said {
Here({ status }) => {
_ = changed!(channel, |before, now| before.join({ key: who.key, tab, meta: { ..own(before, who), status }, now }))
Ok({})
}
Update(data) => {
size = Json.to_str(data).count_utf8_bytes()
if size > PresenceServer.max_data {
Err(Status(413, "presence: data of ${size.to_str()} bytes, over ${PresenceServer.max_data.to_str()}"))
} else {
_ = changed!(channel, |before, now| before.join({ key: who.key, tab, meta: { ..own(before, who), data }, now }))
Ok({})
}
}
Typing(typing) => {
Endpoint.publish!(channel, Typing({ key: who.key, typing }))
Ok({})
}
Moved({ x, y }) => {
Endpoint.publish_latest!(channel, who.key, Moved({ key: who.key, x, y }))
Ok({})
}
Away => {
Endpoint.publish!(channel, Away(who.key))
Ok({})
}
}
}
## `who`'s metadata as the channel's check gives it (their name, picture and colour), with the status
## and `data` the room has for them if they are here (said by a page), else the check's.
own : Room(Wire.Meta(d)), Wire.Member(d) -> Wire.Meta(d)
own = |room, who|
match room.members().find_first(|member| member.key == who.key) {
Ok(member) => { ..who.meta, status: member.meta.status, data: member.meta.data }
Err(_) => who.meta
}
## How many times a change reads the room again when another changed it first.
tries : U64
tries = 50
## How long a room is kept after its last change: a quarter of an hour.
keep_ms : U64
keep_ms = 900_000
## Where the room on `channel` is kept.
key_of : PresenceServer.RoomChannel(c, d) -> Str
key_of = |channel| "presence:${Endpoint.url_of(channel)}"
## The room kept, or a new one, numbering on from `now`.
stored! : Try(Str, [NotFound, BadValue(Str)]), U64 => Room(Wire.Meta(d))
where [d.is_eq : d, d -> Bool, d.Json.Encodable([]), d.Json.Parseable([InvalidJson(Str)])]
stored! = |kept, now| {
text = kept ?? ""
parsed : Try(Room.Saved(Wire.Meta(d)), [InvalidJson(Str)])
parsed = Json.parse(text)
match parsed {
Ok(saved) => Room.load(saved)
Err(_) => Room.load({ members: [], version: now, settings: Room.defaults })
}
}
## The room on `channel`, swept, then changed by `step`, kept, and what changed published on the
## channel: the room as it is now.
changed! : PresenceServer.RoomChannel(c, d), (Room(Wire.Meta(d)), U64 -> (Room(Wire.Meta(d)), List(Room.Change(Wire.Meta(d))))) => Room(Wire.Meta(d))
where [d.is_eq : d, d -> Bool, d.Json.Encodable([]), d.Json.Parseable([InvalidJson(Str)])]
changed! = |channel, step| {
at = key_of(channel)
var $left = tries
var $last = Room.empty(Room.defaults)
while $left > 0 {
was : Try(Str, [NotFound, BadValue(Str)])
was = Kv.get!(at)
now = Time.now_millis!({})
(swept, gone) = stored!(was, now).sweep(now)
(after, said) = step(swept, now)
next = Json.to_str(after.save())
kept =
match was {
Ok(text) => Kv.swap!(at, text, next, { ttl_ms: keep_ms })
Err(_) => Kv.add!(at, next, { ttl_ms: keep_ms }).map_err(|_| Changed)
}
if kept.is_ok() {
for message in Mirror.deltas(after, gone.concat(said)) {
event : Wire.Event(Wire.Meta(d))
event = Presence(message)
Endpoint.publish!(channel, event)
}
return after
}
$last = after
$left = $left - 1
}
Log.warn!("presence: a room changed under each try", { room: at, tries })
$last
}