diff --git a/clips/consumers.py b/clips/consumers.py index 98de12f..aafccc0 100644 --- a/clips/consumers.py +++ b/clips/consumers.py @@ -4,7 +4,8 @@ Two things ride it. DELTAS, which the server sends after a write commits — the socket is read-only for the document, and a dropped socket cannot lose a write. PRESENCE, which peers gossip between themselves: all the server does is hand out a connection id and stamp the sender's identity onto every message, so nobody can -post as somebody else. +post as somebody else. A party — people following each other — is worked out in +the browsers from that gossip (`arthur.domain.party`); nothing here knows of it. """ import json import uuid @@ -32,7 +33,10 @@ def broadcast(project_id, delta, kind="delta"): class ProjectConsumer(AsyncWebsocketConsumer): - RELAYED = ("state",) + # `state` is who you are and which party you carry, and is remembered for + # the next joiner. `nav` and `cursor` are where a party is looking, and are + # stale the moment the next one is sent, so they are only passed on. + RELAYED = ("state", "nav", "cursor") @property def room(self): @@ -68,7 +72,7 @@ class ProjectConsumer(AsyncWebsocketConsumer): return if not isinstance(msg, dict) or msg.get("kind") not in self.RELAYED: return - if self.cid in self.room: + if msg["kind"] == "state" and self.cid in self.room: self.room[self.cid].update( {k: v for k, v in msg.items() if k not in ("kind", "cid", "user")} ) diff --git a/clips/tests/test_api.py b/clips/tests/test_api.py index 84fed0b..6165988 100644 --- a/clips/tests/test_api.py +++ b/clips/tests/test_api.py @@ -1227,3 +1227,37 @@ class SocketTests(TestCase): await peer.disconnect() async_to_sync(scenario)() + + def test_where_a_party_looks_is_passed_on_and_not_remembered(self): + from asgiref.sync import async_to_sync + from channels.testing import WebsocketCommunicator + from server.asgi import application + + from django.contrib.auth import get_user_model + project = Project.objects.create( + name="shared", owner=get_user_model().objects.create_user("host")) + + async def join(): + peer = WebsocketCommunicator(application, f"/ws/projects/{project.id}", + headers=[(b"origin", b"http://localhost")]) + self.assertTrue((await peer.connect())[0]) + welcome = await peer.receive_json_from() + roster = (await peer.receive_json_from())["peers"] + await peer.receive_json_from() # our own join + return peer, welcome["cid"], roster + + async def scenario(): + a, a_cid, _ = await join() + await a.send_json_to({"kind": "state", "party": a_cid, "joinable": True}) + await a.receive_json_from() + await a.send_json_to({"kind": "nav", "open": "main", "frame": 7, "playing": True}) + self.assertEqual(7, (await a.receive_json_from())["frame"]) + await a.send_json_to({"kind": "cursor", "open": "main", "at": [3, 4]}) + self.assertEqual([3, 4], (await a.receive_json_from())["at"]) + + b, _, roster = await join() + self.assertEqual([{"cid": a_cid, "user": None, "party": a_cid, "joinable": True}], + roster) + await a.disconnect(); await b.disconnect() + + async_to_sync(scenario)() diff --git a/frontend/src/arthur/domain/party.cljs b/frontend/src/arthur/domain/party.cljs new file mode 100644 index 0000000..1f157ee --- /dev/null +++ b/frontend/src/arthur/domain/party.cljs @@ -0,0 +1,64 @@ +(ns arthur.domain.party + "Following someone, worked out from the presence roster. tl's parties, nearly + line for line. + + The roster is a flat map of cid → {:cid :user :party :joinable}, gossiped over + the project socket. A party is nothing but an id its members carry: nobody + hosts one, you only follow someone into one. Following someone on their own + adopts THEIR CID as the id, so two people following each other in the same + instant land in the same party, and the party outlives whoever was followed + first. Everyone in a party drives everyone else — a tab, a seek or a play from + any member moves all the others — which is why being followed needs consent + (`:joinable`), and why leaving is one click. + + Every peer computes the same answer from the same gossip, so the server never + has to know any of it.") + +(defn party-of [roster cid] (get-in roster [cid :party])) + +(defn members + "cids carrying party id `pid`. nil is not a party, so it has no members." + [roster pid] + (if pid + (into #{} (keep (fn [[cid p]] (when (= pid (:party p)) cid))) roster) + #{})) + +(defn peers + "The OTHER members of `cid`'s party." + [roster cid] + (disj (members roster (party-of roster cid)) cid)) + +(defn in-party? + "A party id nobody else carries is not a party — a follow that went + unanswered, or the last one left. Either way: on your own." + [roster cid] + (boolean (seq (peers roster cid)))) + +(defn join-id + "The party id you take on by following `cid`: theirs if they are in one, else + their own cid. Derived from the one followed rather than minted, which is what + makes simultaneous follows converge on one party." + [roster cid] + (or (party-of roster cid) cid)) + +(defn joinable? + "May `me` follow `cid`? Someone else, letting people follow, and not already + in the party we are in." + [roster me cid] + (boolean (and me cid (not= me cid) + (get-in roster [cid :joinable]) + (let [theirs (party-of roster cid)] + (or (nil? theirs) (not= theirs (party-of roster me))))))) + +(defn mirrors? + "Does `me` take a move broadcast by `sender`? Same party, different person." + [roster me sender] + (let [mine (party-of roster me)] + (boolean (and me (not= me sender) mine (= mine (party-of roster sender)))))) + +(defn responder + "The one member of `pid` who shows `newcomer` where the party is, so a follow + draws one reply instead of one per member: the lowest cid among those already + there. Deterministic, and still hostless — recomputed from whoever is present." + [roster pid newcomer] + (first (sort (disj (members roster pid) newcomer)))) diff --git a/frontend/src/arthur/events/collab.cljs b/frontend/src/arthur/events/collab.cljs index eb5ed37..9770e79 100644 --- a/frontend/src/arthur/events/collab.cljs +++ b/frontend/src/arthur/events/collab.cljs @@ -16,6 +16,7 @@ The next save sends ours, and if theirs moved since, it answers 409 and we catch up, and the save after that is ours." (:require [arthur.domain.leaf :as leaf] + [arthur.domain.party :as party] [arthur.domain.project :as project] [arthur.events.edit :as edit] [arthur.events.playback :as pb] @@ -23,7 +24,8 @@ [arthur.footage.store :as store] [arthur.fx.http :as http] [clojure.string :as str] - [re-frame.core :as rf])) + [re-frame.core :as rf] + [re-frame.db :as rf-db])) ;; --------------------------------------------------------------------------- ;; the address @@ -120,9 +122,35 @@ (when-let [s @socket] (set! (.-onclose s) nil) (.close s)) (reset! socket nil) (reset! conn {:id id :tries 0 :timer nil}) - (rf/dispatch [::peers-reset]) + ;; Another room: whoever we were following is not in it. + (rf/dispatch [::peers-reset :elsewhere]) (when id (open! id))) +(defn- send! [msg] + (when-let [^js s @socket] + (when (= 1 (.-readyState s)) ; OPEN; otherwise it is dropped + (.send s (js/JSON.stringify (clj->js msg)))))) + +(defn- throttled + "`send!`, at most once every `gap` ms: the first at once, so a move feels + immediate, and the last always, so a party lands where a scrub ENDED rather + than wherever the last message let through happened to be." + [gap] + (let [sent (atom 0) timer (atom nil) pending (atom nil) + flush! (fn [] + (reset! timer nil) + (reset! sent (js/Date.now)) + (when-let [m @pending] (reset! pending nil) (send! m)))] + (fn [msg] + (reset! pending msg) + (when-not @timer + (let [due (- gap (- (js/Date.now) @sent))] + (if (pos? due) (reset! timer (js/setTimeout flush! due)) (flush!))))))) + +(rf/reg-fx ::send! send!) +(rf/reg-fx ::nav! (throttled 120)) +(def ^:private cursor! (throttled 40)) + (rf/reg-fx ::follow! (fn [{:keys [id name]}] @@ -175,34 +203,225 @@ [:dispatch [::events.project/save]])))))) ;; --------------------------------------------------------------------------- -;; presence +;; presence, and following +;; +;; `:peers` is the roster, us included, as the room gossips it; `arthur.domain. +;; party` works out from it who is following whom. `:party` is ours alone: +;; whether we let people follow us, the party to say again after a dropped +;; socket, and a move we could not take yet. `:cursors` are where our party's +;; pointers are on the stage. -(rf/reg-event-db ::peers-reset (fn [db _] (assoc db :peers {}))) +(def ^:private followable-key "arthur/followable") -(defn- peer [^js m] {:cid (.-cid m) :user (.-user m)}) +(defn- followable? [db] + (get-in db [:party :joinable] + (try (not= "0" (.getItem js/localStorage followable-key)) + (catch :default _ true)))) + +(rf/reg-fx + ::remember-followable + (fn [on?] (try (.setItem js/localStorage followable-key (if on? "1" "0")) + (catch :default _ nil)))) + +(defn- mine [db] (party/party-of (:peers db) (:peer-cid db))) + +(defn- state-msg + "What we say about ourselves. `joining` names whoever we just followed: they + take on the party if they are on their own, and everyone else reads it as us + being the newcomer." + ([db] (state-msg db nil)) + ([db joining] + {:kind "state" :party (mine db) :joinable (followable? db) :joining joining})) + +(defn- sid->wire [sid] (subs (str sid) 1)) + +(defn- nav-msg + "Where we are, as the party sees it: the open tab, the frame, and whether it + plays." + [db] + {:kind "nav" :open (sid->wire (get-in db [:ui :open])) + :frame (get-in db [:playback :frame] 0) + :playing (boolean (get-in db [:playback :playing?]))}) + +(defn- upsert + "A peer's message laid over what we knew of them: a `join` says nothing of a + party, and must not take one away." + [db ^js m] + (let [cid (.-cid m)] + (update-in db [:peers cid] merge + (cond-> {:cid cid :user (.-user m)} + (js-in "party" m) (assoc :party (.-party m)) + (js-in "joinable" m) (assoc :joinable (boolean (.-joinable m))))))) + +(rf/reg-event-db + ::peers-reset + ;; Off the wire, everyone we could see is a guess. Our party id is kept when it + ;; is the same room coming back: it is only a name the members still carry, so + ;; rejoining is saying it again. Another room forgets it. + (fn [db [_ elsewhere?]] + (-> db + (assoc :peers {} :cursors {}) + (assoc-in [:party :rejoin] (when-not elsewhere? + (or (mine db) (get-in db [:party :rejoin])))) + (assoc-in [:party :parked] nil)))) (rf/reg-event-fx ::message (fn [{:keys [db]} [_ ^js m]] (case (.-kind m) - "welcome" {:db (assoc db :peers {} :peer-cid (.-cid m)) - ;; Anything written between our GET and our joining the room - ;; was broadcast to a room we were not in yet. - :dispatch [::catch-up]} - "roster" {:db (update db :peers into (map (fn [^js p] [(.-cid p) (peer p)])) - (array-seq (.-peers m)))} - ("join" "state") {:db (assoc-in db [:peers (.-cid m)] (peer m))} - "leave" {:db (update db :peers dissoc (.-cid m))} + "welcome" (let [cid (.-cid m) + db (-> db + (assoc :peers {} :peer-cid cid) + (assoc-in [:peers cid] {:cid cid :user (.-user m) + :party (get-in db [:party :rejoin]) + :joinable (followable? db)}) + (assoc-in [:party :rejoin] nil))] + ;; Anything written between our GET and our joining the room + ;; was broadcast to a room we were not in yet. + {:db db ::send! (state-msg db) :dispatch [::catch-up]}) + "roster" {:db (reduce upsert db (array-seq (.-peers m)))} + "join" {:db (upsert db m)} + "state" {:dispatch [::peer-state m]} + "leave" {:db (-> db + (update :peers dissoc (.-cid m)) + (update :cursors dissoc (.-cid m)))} + "nav" {:dispatch [::peer-nav {:cid (.-cid m) :open (keyword (.-open m)) + :frame (.-frame m) :playing (boolean (.-playing m))}]} + "cursor" {:db (if (party/mirrors? (:peers db) (:peer-cid db) (.-cid m)) + (assoc-in db [:cursors (.-cid m)] + {:open (keyword (.-open m)) :at (some-> (.-at m) vec)}) + db)} "delta" {:dispatch [::delta m]} "access" {:dispatch [::catch-up]} {}))) +(rf/reg-event-fx + ::peer-state + (fn [{:keys [db]} [_ ^js m]] + (let [me (:peer-cid db) + cid (.-cid m) + joining (.-joining m) + db (upsert db m) + ;; They followed us while we were on our own: take on the id they made + ;; of our cid. Nobody hosts — we both just carry it. + adopt? (and me (= me joining) (nil? (mine db)) (followable? db)) + db (cond-> db adopt? (assoc-in [:peers me :party] (.-party m))) + r (:peers db) + ours (mine db)] + (cond-> {:db db} + adopt? (assoc ::send! (state-msg db)) + ;; A newcomer in our party, and we drew the short straw: show them where + ;; we are, rather than leave them where they were until somebody moves. + (and joining ours (= ours (party/party-of r cid)) (= me (party/responder r ours cid))) + (assoc ::nav! (nav-msg db)))))) + +(rf/reg-event-fx + ::follow-peer + (fn [{:keys [db]} [_ cid]] + (let [me (:peer-cid db)] + (if (party/joinable? (:peers db) me cid) + (let [db (assoc-in db [:peers me :party] (party/join-id (:peers db) cid))] + {:db db ::send! (state-msg db cid)}) + {})))) + +(rf/reg-event-fx + ::go-solo + (fn [{:keys [db]} _] + (if-let [me (:peer-cid db)] + (let [db (-> db + (assoc-in [:peers me :party] nil) + (assoc :cursors {}) + (assoc-in [:party :parked] nil))] + {:db db ::send! (state-msg db)}) + {}))) + +(rf/reg-event-fx + ::set-followable + (fn [{:keys [db]} [_ on?]] + (let [db (cond-> (assoc-in db [:party :joinable] on?) + (:peer-cid db) (assoc-in [:peers (:peer-cid db) :joinable] on?))] + {:db db ::send! (state-msg db) ::remember-followable on?}))) + +(rf/reg-event-fx + ::peer-nav + ;; A party-mate moved, and we take their whole view: the tab, the frame, and + ;; whether it plays — in a party anyone drives. A tab we do not have is one + ;; they made a moment ago whose write is still on its way, so the move waits + ;; for it (see `::remote`) rather than leaving us somewhere they are not. + (fn [{:keys [db]} [_ {:keys [cid open frame playing] :as move}]] + (cond + (not (party/mirrors? (:peers db) (:peer-cid db) cid)) {} + (not (pb/openable? db open)) {:db (assoc-in db [:party :parked] move)} + :else + (let [switch? (not= open (get-in db [:ui :open])) + db (cond-> (assoc-in db [:party :parked] nil) switch? (pb/open open)) + n (pb/frames db) + f (-> (or frame 0) (max 0) (min (dec n))) + db (update db :playback assoc :frame f :playing? playing) + fps (get-in db [:clip :fps])] + {:db db + ;; A new tab's sound arrives later, and `::pb/clock-ready` seeks it to + ;; the frame and plays it if the db says so. + :fx (if switch? + [[::pb/pause! nil] + [::pb/clock! {:id (:clip/current db) :sid open}]] + [[::pb/seek! [fps n f]] + [(if playing ::pb/play! ::pb/pause!) nil]])})))) + +(defn point! + "Our pointer on the stage, in stage pixels, or nil when it leaves — for our + party to see. Called from the pointer handler, so it is not an event: it is + sixty a second and changes nothing here." + [p] + (let [db @rf-db/app-db] + (when (party/in-party? (:peers db) (:peer-cid db)) + (cursor! {:kind "cursor" :open (sid->wire (get-in db [:ui :open])) :at p})))) + +(def ^:private steer + "A party moves together. When an event changes the open tab, the frame, or + whether it plays, the party hears where we are now. + + NOT ON A TICK. Every member plays the same document off its own clock, so a + stream of positions would only fight them: a play goes out once, with the + frame it started from. Nor a move a mate made us make, which would only bounce + back at them — nor one made by opening another document, which is a room the + party is not in." + (rf/->interceptor + :id ::steer + :after (fn [ctx] + (let [event (first (get-in ctx [:coeffects :event])) + before (get-in ctx [:coeffects :db]) + after (get-in ctx [:effects :db]) + where (juxt #(get-in % [:ui :open]) #(get-in % [:playback :frame]) + #(get-in % [:playback :playing?]))] + (if (or (nil? after) (#{::pb/tick ::peer-nav} event) + (= (where before) (where after)) + (not= (get-in before [:project :id]) (get-in after [:project :id])) + (not (party/in-party? (:peers after) (:peer-cid after)))) + ctx + (update-in ctx [:effects :fx] (fnil conj []) [::nav! (nav-msg after)])))))) + (rf/reg-sub ::peers + ;; Everyone else in the room: our party first, then by name. (fn [db _] - (->> (vals (:peers db)) - (remove #(= (:cid %) (:peer-cid db))) - (sort-by (juxt (comp nil? :user) :user))))) + (let [r (:peers db) me (:peer-cid db) mates (party/peers r me)] + (->> (vals r) + (remove #(= (:cid %) me)) + (map #(assoc % :mate? (contains? mates (:cid %)) + :followable? (party/joinable? r me (:cid %)))) + (sort-by (juxt (complement :mate?) (comp nil? :user) :user :cid)))))) + +(rf/reg-sub ::followable? (fn [db _] (followable? db))) + +(rf/reg-sub + ::cursors + ;; Our party's pointers on the tab we have open. + (fn [db _] + (let [r (:peers db) mates (party/peers r (:peer-cid db)) open (get-in db [:ui :open])] + (for [[cid {at :at on :open}] (:cursors db) + :when (and at (= on open) (contains? mates cid))] + {:cid cid :at at :user (get-in r [cid :user])})))) ;; --------------------------------------------------------------------------- ;; their writes @@ -281,7 +500,10 @@ {:seq at :status (status now synced)}))] (cond-> {:db db'} (not= (:fps clip) (get-in db [:clip :fps])) - (assoc ::pb/seek! [(:fps clip) (pb/frames db') (get-in db [:playback :frame])]))))))) + (assoc ::pb/seek! [(:fps clip) (pb/frames db') (get-in db [:playback :frame])]) + ;; The tab a party-mate went into may be in this write. + (get-in db [:party :parked]) + (assoc :dispatch [::peer-nav (get-in db [:party :parked])]))))))) (defn- ours "The clip in a delta or a document that is the one open here." @@ -446,6 +668,7 @@ index, or a project — and answer the back button." [] (rf/reg-global-interceptor follow) + (rf/reg-global-interceptor steer) (rf/dispatch [::who]) (route!) (.addEventListener js/window "popstate" route!)) diff --git a/frontend/src/arthur/events/playback.cljs b/frontend/src/arthur/events/playback.cljs index d96a40f..9e3596c 100644 --- a/frontend/src/arthur/events/playback.cljs +++ b/frontend/src/arthur/events/playback.cljs @@ -262,29 +262,37 @@ (fn [{:keys [db]} _] {::clock! {:id (:clip/current db) :sid (get-in db [:ui :open])}})) +(defn openable? + "Can symbol `sid` be opened as a tab? It has to exist — and a tracing symbol + has no inside to open: it is footage, which is seen by placing it." + [db sid] + (let [clip (:clip (footage/entry (:clip/current db)))] + (boolean (and (clip/symbol clip sid) (not (clip/trace? (clip/symbol clip sid))))))) + +(defn open + "`db` with symbol `sid` the open tab, stopped at its first frame." + [db sid] + (-> db + (update-in [:ui :tabs] #(if (some #{sid} %) % (conj (vec %) sid))) + (assoc-in [:ui :open] sid) + ;; A node address is relative to the tab being left. Opening a symbol + ;; therefore arrives at its root; a pool `[:symbol _]` selection is not an + ;; occurrence address and may survive. + (update :ui (fn [ui] + (cond-> ui + (= :node (first (:selection ui))) + (dissoc :selection :selections)))) + (assoc-in [:playback :frame] 0) + (assoc-in [:playback :playing?] false))) + (rf/reg-event-fx ::open-symbol (fn [{:keys [db]} [_ sid]] - (let [clip (:clip (footage/entry (:clip/current db)))] - ;; A tracing symbol has no inside to open: it is footage, which is seen by - ;; placing it. - (if (or (nil? (clip/symbol clip sid)) (= sid (get-in db [:ui :open])) - (clip/trace? (clip/symbol clip sid))) - {} - {:db (-> db - (update-in [:ui :tabs] #(if (some #{sid} %) % (conj (vec %) sid))) - (assoc-in [:ui :open] sid) - ;; A node address is relative to the tab being left. Opening a - ;; symbol therefore arrives at its root; a pool `[:symbol _]` - ;; selection is not an occurrence address and may survive. - (update :ui (fn [ui] - (cond-> ui - (= :node (first (:selection ui))) - (dissoc :selection :selections)))) - (assoc-in [:playback :frame] 0) - (assoc-in [:playback :playing?] false)) - ::pause! nil - ::clock! {:id (:clip/current db) :sid sid}})))) + (if (or (not (openable? db sid)) (= sid (get-in db [:ui :open]))) + {} + {:db (open db sid) + ::pause! nil + ::clock! {:id (:clip/current db) :sid sid}}))) (rf/reg-event-fx ::close-tab diff --git a/frontend/src/arthur/ui/icon.cljs b/frontend/src/arthur/ui/icon.cljs index 056836f..a80a026 100644 --- a/frontend/src/arthur/ui/icon.cljs +++ b/frontend/src/arthur/ui/icon.cljs @@ -73,7 +73,10 @@ "M7 9a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0 -3 0" "M4.4 7.8 8.5 2" "M7.6 7.8 3.5 2"]} :paste {:stroke ["M3.8 2.5H2.5v8h7v-8H8.2" "M4.5 1.5h3v2h-3z"]} - :duplicate {:stroke ["M4.5 4.5h5v5h-5z" "M2.5 7.5v-5h5" "M7 5.8v2.4" "M5.8 7h2.4"]}}) + :duplicate {:stroke ["M4.5 4.5h5v5h-5z" "M2.5 7.5v-5h5" "M7 5.8v2.4" "M5.8 7h2.4"]} + ;; Whether others may follow you: an eye, open to being watched. + :eye {:stroke ["M1.5 6C2.8 3.8 4.3 2.8 6 2.8S9.2 3.8 10.5 6C9.2 8.2 7.7 9.2 6 9.2S2.8 8.2 1.5 6z"] + :fill ["M4.8 6a1.2 1.2 0 1 0 2.4 0a1.2 1.2 0 1 0 -2.4 0z"]}}) (defn view "The glyph named `k`, sized by CSS and inked in `currentColor` — so a button's diff --git a/frontend/src/arthur/ui/share.cljs b/frontend/src/arthur/ui/share.cljs index 8f86cef..5a2c79f 100644 --- a/frontend/src/arthur/ui/share.cljs +++ b/frontend/src/arthur/ui/share.cljs @@ -1,11 +1,16 @@ (ns arthur.ui.share "Who is here, who may write, and who you are: the top bar's right-hand end. + A face is how you follow someone: click it and you go where they go — the tab + they open, the frame they are on, play when they play — and they see your + pointer as you see theirs. See `arthur.domain.party`. + The same drop-down as `openmenu` — a button, a scrim, a panel — because these are the same kind of thing: a few rows about the document, gone on the next click." (:require [arthur.events.collab :as collab] [arthur.events.project :as project] + [arthur.ui.icon :as icon] [arthur.subs.playback :as playback] [clojure.string :as str] [re-frame.core :as rf] @@ -22,13 +27,59 @@ (defn- initial [user] (str/upper-case (subs (or user "?") 0 1))) +(defn colour + "A collaborator's colour, the same on their face and on their cursor, and the + same in every browser that sees them: it is read off their connection id." + [cid] + (str "hsl(" (mod (reduce #(+ (* 31 %1) (.charCodeAt %2 0)) 0 cid) 360) " 60% 42%)")) + +(defn- face [{:keys [cid user mate? followable?]}] + (let [who (or user "guest")] + [:button.peer {:class [(when-not user "guest") (when mate? "mate")] + :style {:background (colour cid)} + :disabled (not (or mate? followable?)) + :aria-label who + ;; A face is the whole control: follow them, or — once you + ;; are together — leave, which is the same one click. + :title (cond mate? (str "following " who " — click to stop") + followable? (str "follow " who) + :else (str who " isn't letting anyone follow")) + :on-click #(rf/dispatch (if mate? [::collab/go-solo] [::collab/follow-peer cid]))} + (initial user)])) + (defn- roster [] - (let [peers @(rf/subscribe [::collab/peers])] + (let [peers @(rf/subscribe [::collab/peers]) + open? @(rf/subscribe [::collab/followable?])] (when (seq peers) - [:span.roster {:title (str/join ", " (map #(or (:user %) "guest") peers))} - (doall (for [{:keys [cid user]} (take 5 peers)] - ^{:key cid} [:span.peer {:class (when-not user "guest")} (initial user)])) - (when (< 5 (count peers)) [:span.dim (str "+" (- (count peers) 5))])]))) + [:span.roster + [:button.followable {:class (when open? "on") + :aria-label "let others follow me" + :title (if open? + "others can follow you — click to stop them" + "nobody can follow you — click to let them") + :on-click #(rf/dispatch [::collab/set-followable (not open?)])} + [icon/view :eye]] + (doall (for [p (take 5 peers)] ^{:key (:cid p)} [face p])) + (when (< 5 (count peers)) + [:span.dim {:title (str/join ", " (map #(or (:user %) "guest") (drop 5 peers)))} + (str "+" (- (count peers) 5))])]))) + +(defn cursors + "Our party's pointers, drawn in the stage's own SVG so they sit on what they + point at however the stage is zoomed or scrolled — and scaled back by `zoom`, + so an arrow is the same size on screen at any zoom." + [zoom] + [:g.peer-cursors {:pointer-events "none"} + (doall (for [{:keys [cid at user]} @(rf/subscribe [::collab/cursors]) + :let [[x y] at c (colour cid) who (or user "guest")]] + ^{:key cid} + [:g {:transform (str "translate(" x " " y ") scale(" (/ 1 zoom) ")")} + [:path.arrow {:d "M0 0V13L3.4 9.9 5.6 14.6 7.6 13.7 5.4 9.1H10z" :fill c}] + ;; Sized by a guess at the name's width rather than measured: a + ;; tag a few pixels long or short is fine, a layout pass per move + ;; is not. + [:rect {:x 9 :y 12 :rx 3 :height 14 :width (+ 10 (* 6 (count who))) :fill c}] + [:text {:x 14 :y 22} who]]))]) (defn- sharing [] (r/with-let [open? (r/atom false) diff --git a/frontend/src/arthur/ui/stage.cljs b/frontend/src/arthur/ui/stage.cljs index 3a2461a..6de05b1 100644 --- a/frontend/src/arthur/ui/stage.cljs +++ b/frontend/src/arthur/ui/stage.cljs @@ -18,6 +18,7 @@ [arthur.domain.paint :as paint] [arthur.domain.pick :as pick] [arthur.domain.symbol :as symbol] + [arthur.events.collab :as collab] [arthur.events.paint :as paint-events] [arthur.events.ui :as ui] [arthur.footage.store :as store] @@ -27,6 +28,7 @@ [arthur.ui.drag :as drag] [arthur.ui.layout :as layout] [arthur.ui.player :as player] + [arthur.ui.share :as share] [arthur.ui.tracing :as tracing] [arthur.ui.shortcuts :as shortcuts] [arthur.ui.tools :as tools] @@ -717,12 +719,13 @@ ;; holds what is selected, then nothing. (when (and (= "Escape" (.-key event)) selected (= :select tool)) (select! ctx (pop selected)))) - :on-pointer-leave (fn [_] (reset! pointer nil)) + :on-pointer-leave (fn [_] (reset! pointer nil) (collab/point! nil)) :on-pointer-move (fn [^js event] (when (.-isPrimary event) (let [p (xy (.-currentTarget event) event w h)] (reset! pointer p) + (collab/point! p) (cond ;; Back through the inverse of what the handle was drawn ;; through, into the shape's own coordinates. @@ -770,7 +773,8 @@ (if (> (count placements) 1) [group-handles ctx placements] [handles ctx])) (when pen? [points ctx draft]) (when pen? [draft-lines draft hover]) - (when paints? [cursor tool])])) + (when paints? [cursor tool]) + [share/cursors zoom]])) (defonce pan (atom nil)) (defonce navigation-blur diff --git a/frontend/test/arthur/domain/party_test.cljs b/frontend/test/arthur/domain/party_test.cljs new file mode 100644 index 0000000..61e3238 --- /dev/null +++ b/frontend/test/arthur/domain/party_test.cljs @@ -0,0 +1,47 @@ +(ns arthur.domain.party-test + (:require [cljs.test :refer [deftest is]] + [arthur.domain.party :as party])) + +(defn- roster [& entries] + (into {} (map (fn [[cid p joinable]] + [cid {:cid cid :party p :joinable (not (false? joinable))}])) + entries)) + +(def ^:private solo (roster ["a" nil] ["b" nil] ["c" nil])) + +(deftest following-someone-on-their-own-takes-their-cid-as-the-party + ;; so two people following each other at once converge on one party + (is (= "a" (party/join-id solo "a"))) + (is (= "a" (party/join-id (assoc-in solo ["b" :party] "a") "b")))) + +(deftest a-party-nobody-else-carries-is-not-a-party + (let [r (assoc-in solo ["b" :party] "a")] ; b followed a; a has not answered + (is (not (party/in-party? r "b"))) + (is (empty? (party/peers r "b"))))) + +(deftest members-drive-each-other-and-nobody-else + (let [r (-> solo (assoc-in ["a" :party] "a") (assoc-in ["b" :party] "a"))] + (is (= #{"b"} (party/peers r "a"))) + (is (party/mirrors? r "a" "b")) + (is (party/mirrors? r "b" "a")) + (is (not (party/mirrors? r "a" "a")) "never our own broadcast") + (is (not (party/mirrors? r "c" "a")) "an outsider stays put") + (is (not (party/mirrors? r "a" "c"))))) + +(deftest following-needs-consent-and-is-not-offered-twice + (let [r (-> solo (assoc-in ["a" :party] "a") (assoc-in ["b" :party] "a") + (assoc-in ["c" :joinable] false))] + (is (party/joinable? r "c" "a")) + (is (not (party/joinable? r "a" "c")) "c is not letting anyone follow") + (is (not (party/joinable? r "a" "b")) "already together") + (is (not (party/joinable? r "a" "a"))))) + +(deftest one-member-answers-a-newcomer-and-never-the-newcomer + (let [r (-> solo (assoc-in ["a" :party] "a") (assoc-in ["b" :party] "a") + (assoc-in ["c" :party] "a"))] + (is (= "a" (party/responder r "a" "c"))) + (is (= "a" (party/responder r "a" "b"))) + (is (= "b" (party/responder (-> solo (assoc-in ["a" :party] "b") + (assoc-in ["b" :party] "b")) + "b" "a")) + "the one followed answers, though the follower named the party"))) diff --git a/static/arthur/app.css b/static/arthur/app.css index 25d17cb..4108148 100644 --- a/static/arthur/app.css +++ b/static/arthur/app.css @@ -466,14 +466,24 @@ a.brand { text-decoration: none; } button.share-button { background: var(--sel); color: #fff; border-color: var(--sel); font-weight: 600; padding: 1px 12px; } button.share-button:hover, button.share-button.on { filter: brightness(1.1); } -/* Who else has this document open. */ -.roster { display: flex; gap: 2px; align-items: center; } -.peer { - width: 18px; height: 18px; border-radius: 50%; +/* Who else has this document open. A face is a button: it follows them. The + ones you are following wear a ring; the eye says whether you may be followed. */ +.roster { display: flex; gap: 3px; align-items: center; } +button.peer { + width: 18px; height: 18px; border-radius: 50%; padding: 0; border: 0; display: inline-grid; place-items: center; background: var(--sel); color: #fff; font-size: 10px; font-weight: 600; } -.peer.guest { background: var(--dim); } +button.peer:hover:not(:disabled) { filter: brightness(1.15); } +button.peer:disabled { opacity: .45; cursor: default; } +button.peer.mate { outline: 1.5px solid var(--fg); outline-offset: 1px; } +button.followable { padding: 0 3px; color: var(--dim); border-color: transparent; background: none; } +button.followable.on { color: var(--fg); } +button.followable svg { width: 12px; height: 12px; display: block; } + +/* A party-mate's pointer on the stage, in screen pixels whatever the zoom. */ +.peer-cursors .arrow { stroke: #fff; stroke-width: 1; stroke-linejoin: round; } +.peer-cursors text { font-size: 10px; font-weight: 600; fill: #fff; } /* -------------------------------------------------------------------------- media pool @@ -1668,6 +1678,7 @@ button.tl-gap:hover { background: rgba(47, 111, 192, .28); } /* Touch targets, in the strips that are all buttons. */ .pane-head, .options-bar { gap: 7px; } .options-bar button, .pane-head button, .top button { min-height: 24px; } + .top button.peer { width: 24px; height: 24px; } /* A STRIP OF CONTROLS SCROLLS AS A STRIP. Flexbox's instinct when a row does not fit is to shrink every item and then push the last ones off the end —