module public import LeanUI public import LeanUI.Sync.App meta import LeanUI.Syntax /-! # Together: a sign-up sheet several visitors share A few shifts, each with a fixed number of seats. A visitor takes one seat, or leaves theirs, or clears the whole sheet. The sheet is shared by replay (`LeanUI.Sync`): a sequencer orders the messages, every tab replays the log and shows its own unconfirmed messages on top. A visitor is the id the sequencer gave their tab ("Visitor 3"); there is no name to type. The shared step is told who sent each message, so a take or a leave moves a seat only for its own sender. A visitor is a tab, not a person: someone who opens the page twice, or reloads it, is two visitors, and nobody can leave the seat of a tab that is gone. That is what `clear` is for: any visitor may empty the sheet, for everybody. (The sheet also starts empty when the server restarts, or when the room reaches one of its limits: `LeanUI.Sync.Room`.) The shared logic is the pure function `Seats.step`. `examples/TogetherProofs.lean` proves that after every list of (sender, message) entries no shift has more people than seats and nobody holds two seats, and that this holds for what `Together.program` shows after every list of its messages. The round trips belong to `LeanUI.Sync.Shared.program`: this file has no networking in it. Its second half is the page at `/together/` on the site (`examples/SiteServer.lean`; the page around the app is `examples/together.html`). -/ @[expose] public section open LeanUI Attr namespace Together /-! ## The shared machine -/ namespace Seats /-- The shifts: label and number of seats. -/ def shifts : List (String × Nat) := [("Door, 18:00", 1), ("Bar, 18:00", 2), ("Bar, 21:00", 2), ("Clean-up, 23:00", 3)] /-- The number of seats of shift `k`; 0 if there is no such shift. -/ def cap (k : Nat) : Nat := (shifts[k]?.map (·.2)).getD 0 /-- Who holds a seat: (shift, visitor), in the order the seats were taken. -/ structure State where seats : List (Nat × Nat) := [] inductive Msg where /-- The sender takes a seat in `shift`. -/ | take (shift : Nat) /-- The sender leaves the seat they hold. -/ | leave /-- The sheet is emptied, whoever sends this. -/ | clear /-- The visitors in shift `k`, in the order they took their seats. -/ def taken (k : Nat) (s : State) : List Nat := (s.seats.filter (·.1 == k)).map (·.2) /-- Everyone who holds a seat. -/ def holders (s : State) : List Nat := s.seats.map (·.2) /-- `who` takes a seat, leaves theirs, or clears the sheet. A take in a full shift, or by a visitor who already holds a seat, does nothing. -/ def step (who : Nat) : Msg → State → State | .take k, s => if (taken k s).length < cap k && !(holders s).contains who then { seats := s.seats ++ [(k, who)] } else s | .leave, s => { seats := s.seats.filter (·.2 != who) } | .clear, _ => {} def machine : Sync.Machine State Msg := { init := {}, step } /-- A message in the log: `t `, `l` or `c`. -/ def enc : Msg → String | .take k => s!"t {k}" | .leave => "l" | .clear => "c" /-- A shift number of more than three digits is not read: there are few shifts, a take in a shift that does not exist does nothing anyway, and a long number would cost every tab that replays the entry the time to read it. -/ def dec (s : String) : Option Msg := match s.splitOn " " with | ["t", k] => if k.length ≤ 3 then k.toNat?.map .take else none | ["l"] => some .leave | ["c"] => some .clear | _ => none def codec : Sync.Codec Msg := { enc, dec } /-- What every tab runs: the machine over the strings in the log. -/ def wire : Sync.Machine State String := machine.wire codec /-- The sheet as text, for tests: `0: 3; 1: 1, 4; 2: ; 3: 2`. -/ def State.render (s : State) : String := "; ".intercalate <| (List.range shifts.length).map fun k => s!"{k}: " ++ ", ".intercalate ((taken k s).map toString) end Seats /-! ## The program What stays in the tab is the shift its visitor last asked for, until their next take, leave or clear. With it the page can say that a request left its visitor without the seat (`missed`). What the view decides is in three pure functions, `canSend`, `row` and `missed`, and the view reads the sheet through `row` and `missed` only (`view_reads` in `examples/TogetherProofs.lean`). One more decision is made from them in the view itself: "Clear the sheet" is enabled while the tab can send and one of its rows holds a visitor. That module has theorems about the values of `row` and `missed` for the sheet the program shows after every list of its messages. That the DOM a browser builds holds those values is not proved: `tests/browser/together.mjs` checks it. -/ inductive Ui where | take (k : Nat) | leave | clear /-- Nothing shared and nothing local: any input resumes a tab that has stopped asking. -/ | resume abbrev Msg := Sync.Msg Ui /-- A take, a leave or a clear is a shared message. The tab keeps the shift its visitor last asked for, until their next take, leave or clear. -/ def uiUpdate : Ui → Option Nat → Seats.State → Option Nat × List Seats.Msg | .take k, _, _ => (some k, [.take k]) | .leave, _, _ => (none, [.leave]) | .clear, _, _ => (none, [.clear]) | .resume, asked, _ => (asked, []) def visitor (i : Nat) : String := s!"Visitor {i}" /-- This tab's buttons can send: the tab has joined, its log is not lost and its queue has room. Otherwise the program drops a shared message (`LeanUI.Sync.Shared.step`), so the page disables every button that sends one. That this is the program's own rule is tested, not proved (`tests/browser/together.mjs`: a click on an enabled button is queued). -/ def canSend (st : Sync.Status) : Bool := st.id.isSome && !st.lost && !st.full /-- What the page shows of one shift. -/ structure Row where /-- The visitors who hold a seat in the shift, in the order they took their seats. -/ who : List Nat /-- How many seats the shift has. -/ cap : Nat /-- This tab's visitor holds a seat in the shift. -/ mine : Bool /-- The button "Take a seat" is enabled. -/ canTake : Bool /-- The button "Leave" is enabled. -/ canLeave : Bool /-- Shift `k` of the sheet `s`, for the tab with status `st`. A take is offered where the tab's sheet has a free seat and its visitor holds no seat; a leave, where its visitor holds one. -/ def row (st : Sync.Status) (s : Seats.State) (k : Nat) : Row := let who := Seats.taken k s let mine := st.id.any who.contains { who, cap := Seats.cap k, mine, canTake := canSend st && who.length < Seats.cap k && !st.id.any (Seats.holders s).contains, canLeave := canSend st && mine } /-- The shift this tab's visitor last asked for (`asked`), if they hold no seat in it, nothing of the tab is pending and its log is not lost (`missed_spec` in `examples/TogetherProofs.lean`). This is a function of the local state, the sheet and the status: it knows nothing of a log. In the model with one honest log (`LeanUI.Sync.Sys.nothing_lost`), and for a click the program queued, the request is then an entry of the log the tab has replayed, and did not leave its visitor a seat there. Why not is `take_missed`: the shift was full or the visitor already held a seat when the request was applied, or a later entry cleared the sheet. -/ def missed (asked : Option Nat) (s : Seats.State) (st : Sync.Status) : Option Nat := asked.filter fun k => st.pending == 0 && !st.lost && st.id.isSome && !(row st s k).mine /-- The name of shift `k`. -/ def label (k : Nat) : String := (Seats.shifts[k]?.map (·.1)).getD s!"shift {k}" def seat (me : Option Nat) (v : Nat) : Html Msg :=
  • {if me == some v then s!"{visitor v} (you)" else visitor v}
  • def shiftRow (me : Option Nat) (k : Nat) (r : Row) : Html Msg := {label k} {r.who.length} of {r.cap} {" "} /-- Where the controls are. Above a control, only seats that wrap onto another line change the height of anything: the first paragraph is one short line in every state, and the sentences that come and go stand below the switch and the buttons, the one that brings a button of its own ("Resume") first. And every control is above, or beside, what its own click changes in size: "Clear the sheet" is above the table; the two buttons of a shift have places of their own beside its seats, and above them on a narrow screen (the page's stylesheet: fixed columns, cells aligned at the top). So no control moves when it is clicked, and a second click at the same place meets the same control. By then a take, a leave or a clear has disabled its own button ("Clear the sheet" is off while the sheet the tab shows is empty), so a double click, or a key that is held down, writes one message; and "Resume" is gone. This rests on the order here and on the stylesheet of `examples/together.html`; nothing proves it. `tests/browser/together.mjs` asks at every look, in windows of two widths, that every control is where it was when the tab first showed the same seats, and it double-clicks a take, a leave, a clear and the switch with the pointer in the wide one. It asks nothing of seats that wrap: whether they do depends on the font. Every child has a key, so that each stays the element it is when a sentence comes or goes. -/ def view (asked : Option Nat) (s : Seats.State) (st : Sync.Status) : Html Msg := let rows := (List.range Seats.shifts.length).map fun k => (k, row st s k);

    {if st.lost then "This sheet is gone." else match st.id with | none => "Not joined yet." | some i => s!"You are {visitor i}."}

    {" "} for everybody. A visitor is a tab, so the seat of a tab that was closed stays taken until somebody clears the sheet.

    {...(rows.map fun (k, r) => shiftRow st.id k r).toArray}
    ShiftSeatsTaken

    A visitor holds one seat at most: to take another one, leave yours first.

    .{" "} This switch is the tab's own, not your network. Switch it off, do something, and switch it back: what you did waits in this tab and is sent then.

    This tab has stopped asking the server, after {Sync.idleMs / 60000} minutes without input: the sheet above may be out of date.{" "} {" "} Any other button here that is not off resumes it too.

    This tab has not joined the sheet yet: its buttons are off until the server has given it a visitor number.

    The server has started a new sheet, because it was restarted or this sheet reached one of its limits. The table above is what this tab last showed of the old one. Reload this page to join the new one.

    This tab is offline: it sends nothing and takes no changes from the server. What you do here waits in this tab, and is sent once you switch it back on.

    This tab holds {st.pending} changes that are not confirmed yet, and takes no more until some are.

    {...(missed asked s st).toArray.map fun k =>

    You asked for a seat in “{label k}” and do not hold one there: when your request reached the log the shift was full or you already held a seat, or the sheet was cleared after it.

    }

    Log entries this tab has read: {st.seen}.{" "} {if st.lost then "Changes of yours that were never confirmed: " else "Changes of yours that are not confirmed yet: "} {st.pending}.

    def app : Sync.Shared Seats.State Seats.Msg (Option Nat) Ui := { machine := Seats.machine, codec := Seats.codec, initLocal := fun _ => none, update := uiUpdate, view } def program : Program (Sync.Model Seats.State (Option Nat)) Msg := app.program end Together