diff --git a/clips/consumers.py b/clips/consumers.py index aafccc0..26425dc 100644 --- a/clips/consumers.py +++ b/clips/consumers.py @@ -5,7 +5,7 @@ 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. A party — people following each other — is worked out in -the browsers from that gossip (`arthur.domain.party`); nothing here knows of it. +the browsers from that gossip (`arthur.follow`); nothing here knows of it. """ import json import uuid @@ -33,10 +33,10 @@ def broadcast(project_id, delta, kind="delta"): class ProjectConsumer(AsyncWebsocketConsumer): - # `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") + # `state` is what each of us says about ourselves, and is remembered for the + # next joiner. The rest are `arthur.follow`'s — where a party is looking — + # and are stale the moment the next is sent, so they are only passed on. + RELAYED = ("state", "nav", "cursor", "scroll") # follow: all but "state" @property def room(self): diff --git a/frontend/src/arthur/core.cljs b/frontend/src/arthur/core.cljs index af33ac6..a7724e2 100644 --- a/frontend/src/arthur/core.cljs +++ b/frontend/src/arthur/core.cljs @@ -11,6 +11,7 @@ [arthur.events.paint] [arthur.events.project :as project] [arthur.events.ui] + [arthur.follow :as follow] [arthur.subs.playback] [arthur.subs.render] [arthur.subs.ui] @@ -45,6 +46,7 @@ (rf/dispatch [::project/list-symbols]) ;; After the blank document, so an address that names a project opens it over ;; the blank one, and the blank one is what a bad address leaves on screen. + (follow/install!) ; following someone: arthur.follow (collab/start!) (shortcuts/install!) (reset! root (rdc/create-root (js/document.getElementById "app"))) diff --git a/frontend/src/arthur/domain/nest.cljs b/frontend/src/arthur/domain/nest.cljs index c6f084c..f35b775 100644 --- a/frontend/src/arthur/domain/nest.cljs +++ b/frontend/src/arthur/domain/nest.cljs @@ -498,7 +498,9 @@ (span/claim clip (:sid here) moved id :grow-symbol (random-uuid)))))) (defn slide-many - "Move a selection simultaneously. Lane collisions refuse the entire edit." + "Move a selection simultaneously: `slide`, for all of it at once. What it + lands on is claimed as `slide` claims it; among themselves the moved nodes + keep their places." [document open paths df] (let [paths (vec (distinct (filter seq paths))) entries (mapv (fn [path] @@ -528,9 +530,10 @@ {} roots)] (reduce (fn [result [sid changed]] (if (:refused result) (reduced result) - (span/finish (:clip result) sid - (merge (get-in (:clip result) [:symbols sid :nodes]) changed) - nil :grow-symbol))) + (span/claim-each (:clip result) sid + (merge (get-in (:clip result) [:symbols sid :nodes]) changed) + (update-vals changed (fn [_] (random-uuid))) + :grow-symbol))) {:clip document} changes))))) (defn resize-out @@ -566,6 +569,19 @@ :else (span/resize-in clip sid id (dragged here nodes id (first (node/placed-span n)) df))))) +(defn resize-many + "Move the `kind` edge, `:in` or `:out`, of every node at `paths` by `df` + frames of `open`: each one's own edit, in turn, so each claims what it claims + alone. One eaten by an earlier one has no edge left to move." + [clip open paths kind df ripple?] + (reduce (fn [result path] + (let [c (:clip result)] + (cond + (nil? (get-in c [:symbols (:sid (down c open (pop path))) :nodes (peek path)])) result + (= :out kind) (let [r (resize-out c open path df ripple?)] (if (:refused r) (reduced r) r)) + :else (let [r (resize-in c open path df)] (if (:refused r) (reduced r) r))))) + {:clip clip} (distinct paths))) + (defn roll "Move the shared boundary at `right-path` and the adjacent `left-path`." [clip open left-path right-path df] @@ -583,6 +599,17 @@ (span/roll clip sid left-id right-id (dragged here nodes right-id (first (node/placed-span right)) df))))) +(defn drag + "What a timeline gesture does to `clip`: `kind` is the handle — `:slide` the + body, `:in` and `:out` an edge, `:roll` a cut — and `paths` the selection it + carries when there is one." + [clip open {:keys [path df kind ripple? other paths]}] + (case kind + :out (if (seq paths) (resize-many clip open paths :out df ripple?) (resize-out clip open path df ripple?)) + :in (if (seq paths) (resize-many clip open paths :in df false) (resize-in clip open path df)) + :roll (roll clip open other path df) + (if (seq paths) (slide-many clip open paths df) (slide clip open path df)))) + (defn restack "Put the node at row path `from` just in front of the one at `to` when `front?`, or just behind it — side by side in one symbol, as the timeline lists diff --git a/frontend/src/arthur/domain/span.cljs b/frontend/src/arthur/domain/span.cljs index 2863b6d..2636897 100644 --- a/frontend/src/arthur/domain/span.cljs +++ b/frontend/src/arthur/domain/span.cljs @@ -144,6 +144,41 @@ [n which f] (assoc-in n [:span (case which :in 0 :out 1)] (local n f))) +(defn- eaten + "`nodes` with lane clip `id`'s interval taken from every clip not in `keep`: + those it covers are removed and those crossing an edge trimmed. A clip crossing + both edges is split, and its remainder is `remainder-id`. Nil where that split + has no free id." + [nodes id keep remainder-id] + (let [[a b] (node/placed-span (get nodes id)) + others (remove #(contains? keep (:id %)) (symbol/children nodes)) + spanning (some #(let [[lo hi] (node/placed-span %)] (and (< lo a) (> hi b))) others)] + (when-not (and spanning (or (nil? remainder-id) (contains? nodes remainder-id))) + (reduce + (fn [ns other] + (let [oid (:id other) + [lo hi] (node/placed-span other)] + (cond + (or (<= hi a) (>= lo b)) ns + (and (< lo a) (> hi b)) + (-> ns + (assoc oid (edged other :out a)) + (assoc remainder-id + (assoc (edged other :in b) :id remainder-id + :z (str "a-" remainder-id)))) + (and (>= lo a) (<= hi b)) (dissoc ns oid) + (< lo a) (assoc ns oid (edged other :out a)) + :else (assoc ns oid (edged other :in b))))) + nodes others)))) + +(defn- lane-child? [clip sid nodes id] + (let [n (get nodes id)] + (and (symbol/lane? (clip/symbol clip sid)) + n (nil? (:parent n)) (node/placed-span n)))) + +(def ^:private split-refusal + {:refused "claiming time inside one clip needs a free ID for its remainder"}) + (defn claim "Commit proposed `nodes`, with `id` claiming its interval in lane mode. @@ -153,37 +188,24 @@ edge are trimmed. A clip crossing both edges is split and therefore needs a caller-supplied `remainder-id`." [clip sid nodes id extent remainder-id] - (let [n (get nodes id) - lane-child? (and (symbol/lane? (clip/symbol clip sid)) - n (nil? (:parent n)) (node/placed-span n))] - (if-not lane-child? - (finish clip sid nodes id extent) - (let [[a b] (node/placed-span n) - others (remove #(= id (:id %)) (symbol/children nodes)) - spanning (first (filter #(let [[lo hi] (node/placed-span %)] - (and (< lo a) (> hi b))) - others))] - (if (and spanning (or (nil? remainder-id) (contains? nodes remainder-id))) - {:refused "claiming time inside one clip needs a free ID for its remainder"} - (finish - clip sid - (reduce - (fn [ns other] - (let [oid (:id other) - [lo hi] (node/placed-span other)] - (cond - (or (<= hi a) (>= lo b)) ns - (and (< lo a) (> hi b)) - (-> ns - (assoc oid (edged other :out a)) - (assoc remainder-id - (assoc (edged other :in b) :id remainder-id - :z (str "a-" remainder-id)))) - (and (>= lo a) (<= hi b)) (dissoc ns oid) - (< lo a) (assoc ns oid (edged other :out a)) - :else (assoc ns oid (edged other :in b))))) - nodes others) - id extent)))))) + (if-not (lane-child? clip sid nodes id) + (finish clip sid nodes id extent) + (if-let [ns (eaten nodes id #{id} remainder-id)] + (finish clip sid ns id extent) + split-refusal))) + +(defn claim-each + "`claim` for clips edited together, `remainders` mapping each one's id to a + free id for a split. Each takes its interval from the clips that are NOT among + them; among themselves they keep the places the edit gave them." + [clip sid nodes remainders extent] + (let [keep (set (keys remainders)) + ns (reduce (fn [ns [id remainder-id]] + (if (lane-child? clip sid ns id) + (or (eaten ns id keep remainder-id) (reduced nil)) + ns)) + nodes remainders)] + (if ns (finish clip sid ns nil extent) split-refusal))) (defn host-frame "Symbol frame `f` as a frame of the space node `id` is POSITIONED in — its diff --git a/frontend/src/arthur/events/collab.cljs b/frontend/src/arthur/events/collab.cljs index 9770e79..6e828b4 100644 --- a/frontend/src/arthur/events/collab.cljs +++ b/frontend/src/arthur/events/collab.cljs @@ -16,7 +16,6 @@ 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] @@ -24,8 +23,7 @@ [arthur.footage.store :as store] [arthur.fx.http :as http] [clojure.string :as str] - [re-frame.core :as rf] - [re-frame.db :as rf-db])) + [re-frame.core :as rf])) ;; --------------------------------------------------------------------------- ;; the address @@ -126,30 +124,14 @@ (rf/dispatch [::peers-reset :elsewhere]) (when id (open! id))) -(defn- send! [msg] +(defn send! + "Say `msg` to the room, if we are in it; otherwise it is dropped." + [msg] (when-let [^js s @socket] - (when (= 1 (.-readyState s)) ; OPEN; otherwise it is dropped + (when (= 1 (.-readyState s)) ; OPEN (.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! @@ -203,225 +185,80 @@ [:dispatch [::events.project/save]])))))) ;; --------------------------------------------------------------------------- -;; presence, and following +;; presence ;; -;; `: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. +;; `:peers` is the roster, us included, as the room gossips it: cid → `{:cid +;; :user}` and whatever else each of us says about ourselves. `:presence` is +;; what WE say, and it is said again on every welcome, so a dropped socket comes +;; back as it left. Nothing here reads past `:cid` and `:user`: what the rest +;; means belongs to whoever `listen!`s. -(def ^:private followable-key "arthur/followable") +(defonce ^:private listeners (atom #{})) -(defn- followable? [db] - (get-in db [:party :joinable] - (try (not= "0" (.getItem js/localStorage followable-key)) - (catch :default _ true)))) +(defn listen! + "Hear the room: every message it sends, as `[event-id message]` once the roster + has it, and `#js {:kind \"reset\" :elsewhere bool}` when the room is lost." + [event-id] + (swap! listeners conj event-id)) -(rf/reg-fx - ::remember-followable - (fn [on?] (try (.setItem js/localStorage followable-key (if on? "1" "0")) - (catch :default _ nil)))) +(defn- heard [fx ^js m] + (update fx :fx (fnil into []) (map (fn [l] [:dispatch [l m]])) @listeners)) -(defn- mine [db] (party/party-of (:peers db) (:peer-cid db))) +(defn say + "`db` with `fields` part of what we say about ourselves, and the effects that + say it. `once` rides along on this message only." + ([db fields] (say db fields nil)) + ([db fields once] + (let [db (cond-> (update db :presence merge fields) + (:peer-cid db) (update-in [:peers (:peer-cid db)] merge fields))] + {:db db ::send! (merge {:kind "state"} (:presence db) once)}))) -(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 colour + "A collaborator's colour, the same on their face and anywhere else they show, + and the same in every browser that sees them: it is read off their cid." + [cid] + (str "hsl(" (mod (reduce #(+ (* 31 %1) (.charCodeAt %2 0)) 0 cid) 360) " 60% 42%)")) (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." + "A peer's message laid over what we knew of them: one that does not mention a + field must not take it 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))))))) + (update-in db [:peers (.-cid m)] merge + (dissoc (js->clj m :keywordize-keys true) :kind))) -(rf/reg-event-db +(rf/reg-event-fx ::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)))) + ;; Off the wire, everyone we could see is a guess. `elsewhere?` is another room. + (fn [{:keys [db]} [_ elsewhere?]] + (heard {:db (assoc db :peers {})} #js {:kind "reset" :elsewhere elsewhere?}))) (rf/reg-event-fx ::message (fn [{:keys [db]} [_ ^js m]] - (case (.-kind 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)])))))) + (heard + (case (.-kind m) + "welcome" (let [cid (.-cid m)] + {:db (assoc db :peer-cid cid + :peers {cid (merge {:cid cid :user (.-user m)} (:presence db))}) + ::send! (merge {:kind "state"} (:presence db)) + ;; 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 (reduce upsert db (array-seq (.-peers m)))} + ("join" "state") {:db (upsert db m)} + "leave" {:db (update db :peers dissoc (.-cid m))} + "delta" {:dispatch [::delta m]} + "access" {:dispatch [::catch-up]} + {}) + m))) (rf/reg-sub ::peers - ;; Everyone else in the room: our party first, then by name. + ;; Everyone else in the room, by name. (fn [db _] - (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])})))) + (->> (vals (:peers db)) + (remove #(= (:cid %) (:peer-cid db))) + (sort-by (juxt (comp nil? :user) :user :cid))))) ;; --------------------------------------------------------------------------- ;; their writes @@ -500,10 +337,7 @@ {: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])]) - ;; 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])]))))))) + (assoc ::pb/seek! [(:fps clip) (pb/frames db') (get-in db [:playback :frame])]))))))) (defn- ours "The clip in a delta or a document that is the one open here." @@ -668,7 +502,6 @@ 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/edit.cljs b/frontend/src/arthur/events/edit.cljs index a900ad4..70f5f27 100644 --- a/frontend/src/arthur/events/edit.cljs +++ b/frontend/src/arthur/events/edit.cljs @@ -46,12 +46,22 @@ (update :project merge {:status "edited · unsaved"})) db))) +(defn read-only? + "Somebody else's project that we may look at and not write." + [db] + (false? (get-in db [:project :can-edit?]))) + (defn edit-entry "Apply `f` to the loaded ENTRY — the document and the blocks, footage and source tracks beside it — and return the new db. For an edit that brings tier-2 - data in with it, which a document edit alone cannot." + data in with it, which a document edit alone cannot. + + NOTHING, IN A PROJECT YOU MAY ONLY LOOK AT. It used to take the edit and then + never save it, so a drawing stayed until the next reload and was gone after. + Here, as the one way a person changes the document, it is one rule rather + than one per command." [db f] - (replace-entry db (recorded f))) + (if (read-only? db) db (replace-entry db (recorded f)))) (defn transport "App-db's copy of what the transport reads off the clip, after the clip was diff --git a/frontend/src/arthur/events/project.cljs b/frontend/src/arthur/events/project.cljs index 860fcc7..c46c848 100644 --- a/frontend/src/arthur/events/project.cljs +++ b/frontend/src/arthur/events/project.cljs @@ -532,7 +532,8 @@ (fn [{:keys [db]} [_ edit]] (let [id (:clip/current db) entry (store/entry id)] - (if (or (get-in db [:project :busy?]) (empty? (:analyses (:clip entry)))) + (if (or (get-in db [:project :busy?]) (empty? (:analyses (:clip entry))) + (edit/read-only? db)) {} (let [plan (regenerate/plan (:clip entry) edit) report (select-keys plan [:features :roles]) @@ -656,8 +657,10 @@ (rf/reg-event-fx ::rename (fn [{:keys [db]} [_ value]] - {:db (assoc-in db [:project :name] (not-empty (str/trim value))) - :dispatch [::save {:auto? true :force? true}]})) + (if (edit/read-only? db) + {} + {:db (assoc-in db [:project :name] (not-empty (str/trim value))) + :dispatch [::save {:auto? true :force? true}]}))) (rf/reg-event-fx ::project-setting diff --git a/frontend/src/arthur/events/ui.cljs b/frontend/src/arthur/events/ui.cljs index c7093a8..1954534 100644 --- a/frontend/src/arthur/events/ui.cljs +++ b/frontend/src/arthur/events/ui.cljs @@ -1380,11 +1380,8 @@ (let [db (update db :ui dissoc :sliding) clip (:clip (store/entry (:clip/current db))) open (or owner (get-in db [:ui :open])) - r (case kind - :out (nest/resize-out clip open path df ripple?) - :in (nest/resize-in clip open path df) - :roll (nest/roll clip open other path df) - (if (seq paths) (nest/slide-many clip open paths df) (nest/slide clip open path df)))] + r (nest/drag clip open {:path path :df df :kind kind :ripple? ripple? + :other other :paths paths})] (cond (zero? df) db (:refused r) (refused db (:refused r)) @@ -1476,45 +1473,60 @@ (when (js/confirm message) (rf/dispatch then)))) (rf/reg-event-fx - ::delete-symbol - ;; Out of the library, with its placements; see `nest/delete-symbol`. Its tab - ;; closes, and if it was on screen the root takes its place. + ::delete-symbols + ;; Out of the library, with their placements; see `nest/delete-symbol`. Their + ;; tabs close, and if one was on screen the root takes its place. ;; - ;; ASKED FIRST WHEN IT IS PLACED, because then the delete reaches past the row - ;; you pointed at, into every symbol that uses it. One placed nowhere goes - ;; without a question; undo is there either way. - (fn [{:keys [db]} [_ sid sure?]] + ;; ASKED FIRST WHEN ANY IS PLACED, because then the delete reaches past the + ;; rows you pointed at, into every symbol that uses them. Ones placed nowhere + ;; go without a question; undo is there either way. + (fn [{:keys [db]} [_ sids sure?]] (let [clip (:clip (store/entry (:clip/current db))) - {gone :clip why :refused} (nest/delete-symbol clip sid) - uses (clip/uses clip sid)] + sids (vec (distinct sids)) + {gone :clip why :refused} (reduce (fn [r sid] + (let [r (nest/delete-symbol (:clip r) sid)] + (if (:refused r) (reduced r) r))) + {:clip clip} sids) + gone? (set sids) + ;; Uses from outside what is being deleted: those are what reach past. + placed (for [sid sids + :let [owners (remove gone? (clip/owners clip sid))] + :when (seq owners)] + [sid owners])] (cond why {:db (refused db why)} - (and (pos? uses) (not sure?)) - {::confirm {:message (str "Delete " (clip/symbol-name clip sid) "? It is used " - (if (= 1 uses) "once" (str uses " times")) ", in " - (str/join ", " (map #(clip/symbol-name clip %) - (clip/owners clip sid))) - ", and every use of it goes too.") - :then [::delete-symbol sid true]}} + (and (seq placed) (not sure?)) + {::confirm {:message (str "Delete " + (if (= 1 (count sids)) + (clip/symbol-name clip (first sids)) + (str (count sids) " symbols")) + "? " + (str/join "; " (for [[sid owners] placed] + (str (clip/symbol-name clip sid) " is used in " + (str/join ", " (map #(clip/symbol-name clip %) owners))))) + ", and every use goes too.") + :then [::delete-symbols sids true]}} :else (cond-> {:db (-> db (edit/transaction (constantly gone)) - (update-in [:ui :tabs] #(vec (remove #{sid} %))) + (update-in [:ui :tabs] #(vec (remove gone? %))) (update :ui (fn [ui] - (cond-> ui - (= [:symbol sid] (:selection ui)) - (assoc :selection nil :selections [])))))} - (= sid (get-in db [:ui :open])) + (let [left (vec (remove #(and (= :symbol (first %)) (gone? (second %))) + (:selections ui)))] + (assoc ui :selections left + :selection (when (some #{(:selection ui)} left) + (:selection ui)))))))} + (gone? (get-in db [:ui :open])) (assoc :dispatch [::playback/open-symbol (clip/opens-on gone)])))))) (rf/reg-event-fx ::delete-selected ;; Backspace while drawing takes the last point back, as in Illustrator; on - ;; the pen, with a point of the selected shape picked, it takes that point. A - ;; symbol picked in the pool is deleted from the library. + ;; the pen, with a point of the selected shape picked, it takes that point. + ;; Symbols picked in the pool are deleted from the library. (fn [{:keys [db]} _] (let [[vsid vid i] (get-in db [:ui :vertex]) primary (get-in db [:ui :selection])] @@ -1526,7 +1538,8 @@ {:db (deleting-vertex db vsid vid i)} (= :symbol (first primary)) - {:dispatch [::delete-symbol (second primary)]} + {:dispatch [::delete-symbols (keep (fn [[kind sid]] (when (= :symbol kind) sid)) + (cons primary (get-in db [:ui :selections])))]} :else (let [many (vec (get-in db [:ui :selections])) diff --git a/frontend/src/arthur/follow.cljs b/frontend/src/arthur/follow.cljs new file mode 100644 index 0000000..f035eef --- /dev/null +++ b/frontend/src/arthur/follow.cljs @@ -0,0 +1,317 @@ +(ns arthur.follow + "Following someone: click their face and go where they go, and see each + other's pointers wherever they are — on the stage, over a button, in a list. + + A LAYER, NOT A PART OF WHAT IT FOLLOWS. It reaches the rest of the app through + doors that are open anyway — the room's messages (`collab/listen!`, + `collab/say`, `collab/send!`), app-db, and the page's DOM — and it is switched + on by `install!` in `arthur.core`. Taking it out is that line, this namespace + and `follow/`, and the lines marked `follow` in `ui/share`, `app.css` and + `clips/consumers.py`. + + WHAT IS FOLLOWED is a short list, `facets`, and each can be let go of on its + own from the popover beside the faces — Live Share's and Figma's answer to + wanting to look around without leaving: stay together on the tab and frame, + say, and keep your own selection. Letting go works both ways. What you do not + take from them you do not send them either, so looking around never drags the + party along. + + Everyone in a party drives — see `follow/party`, tl's parties — so the moves + that go out are the deliberate ones. Every member plays the document off its + own clock, and a play goes out once with its frame rather than streamed." + (:require [arthur.events.collab :as collab] + [arthur.events.playback :as pb] + [arthur.follow.page :as page] + [arthur.follow.party :as party] + [arthur.ui.menu :as menu] + [arthur.ui.icon :as icon] + [cognitect.transit :as t] + [re-frame.core :as rf] + [re-frame.db :as rf-db])) + +(def facets + "What following someone takes from them: a key, what it is called, and the + app-db paths it carries. In a path, `::open` stands for the open tab and + `::clip` for the loaded document, which is a different handle in every + browser. The two with no paths are the page's, not the db's." + [[:place "tab, frame & play" [[:ui :open] [:playback :frame] [:playback :playing?] + [:playback :rate] [:playback :loop?] + [:playback :range ::open]]] + ;; So that the inspector under their pointer shows what it shows for them. + [:selection "selection" [[:ui :selection] [:ui :selections]]] + ;; So that the row under their pointer is the same row. + [:rows "timeline rows" [[:ui :expanded]]] + ;; Ways of looking at the stage. Each person's own until they are following + ;; — and then watching someone set the onion up is how you learn it. + [:looks "onion, tracing & mat" [[:ui :onion ::clip ::open] [:ui :tracing] + [:ui :passepartout]]] + [:tools "tool & brush" [[:ui :tool] [:ui :brush] [:ui :tone] [:ui :auto-key?]]] + ;; Which panes are shut, so the panel under their pointer is on screen here. + [:panels "panels" [[:ui :layout :shut]]] + [:scroll "panel scroll" nil] + [:pointers "pointers" nil]]) + +;; --------------------------------------------------------------------------- +;; what we keep +;; +;; `[:presence :party]` and `[:presence :joinable]` are what we tell the room; +;; `collab` says them again when the socket comes back, which is the rejoin. +;; `:follow` is ours alone: the facets let go of, a move we could not take yet +;; (`:parked`), and the last move a mate made, to catch up to on taking a facet +;; back. + +(def ^:private stored {:joinable "arthur/followable" :off "arthur/follow-off"}) + +(defn- recall [k] + (try (.getItem js/localStorage (stored k)) (catch :default _ nil))) + +(rf/reg-fx + ::remember + (fn [[k v]] (try (.setItem js/localStorage (stored k) v) (catch :default _ nil)))) + +(defn- off [db] (get-in db [:follow :off] #{})) + +(defn- me [db] (:peer-cid db)) +(defn- mine [db] (party/party-of (:peers db) (me db))) +(defn- together? [db] (party/in-party? (:peers db) (me db))) + +(rf/reg-event-db + ::init + (fn [db _] + (-> db + (assoc-in [:presence :joinable] (not= "0" (recall :joinable))) + (assoc-in [:follow :off] (into #{} (keep keyword) (some-> (recall :off) (.split ","))))))) + +;; --------------------------------------------------------------------------- +;; the view a party shares + +(def ^:private writer (t/writer :json)) +(def ^:private reader (t/reader :json)) + +(defn- paths [db] + (into [] (comp (remove (fn [[k]] (contains? (off db) k))) (mapcat last)) facets)) + +(defn- at + "Path template `p` in `db`." + [db p] + (mapv #(case % ::open (get-in db [:ui :open]) ::clip (:clip/current db) %) p)) + +(defn- view + "The part of `db` a party shares, as far as we are following — or as far as + `along` says, so that letting go of a facet is not itself a move." + ([db] (view db (paths db))) + ([db along] (into {} (map (juxt identity #(get-in db (at db %)))) along))) + +(defn- view-msg + "A move, and the tab it was made on whether or not it moves us there: a + selection, a row or a mark only means something on its own tab." + [db] + {:kind "nav" :view (t/write writer (assoc (view db) ::tab (get-in db [:ui :open])))}) + +(rf/reg-fx ::nav! (page/every 120 collab/send!)) + +(rf/reg-event-fx + ::moved + ;; A mate moved, and we take what we follow of it. 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 `steer`) rather than leaving us somewhere they are not. The rest is + ;; taken only on the tab it was made on. + (fn [{:keys [db]} [_ cid v]] + (let [open (get v [:ui :open]) + place? (and (contains? v [:ui :open]) (not (contains? (off db) :place))) + taken (select-keys v (remove #{[:ui :open]} (paths db)))] + (cond + (not (party/mirrors? (:peers db) (me db) cid)) {} + (and place? (not (pb/openable? db open))) + {:db (update db :follow assoc :parked [cid v] :last [cid v])} + :else + (let [switch? (and place? (not= open (get-in db [:ui :open]))) + db (cond-> (update db :follow assoc :parked nil :last [cid v]) + switch? (pb/open open)) + db (cond-> db + (= (get v ::tab) (get-in db [:ui :open])) + (as-> db (reduce-kv #(assoc-in %1 (at %1 %2) %3) db taken))) + n (pb/frames db) + f (-> (get-in db [:playback :frame] 0) (max 0) (min (dec n))) + db (assoc-in db [:playback :frame] f)] + {:db db + ;; A new tab's sound arrives later, and `::pb/clock-ready` seeks it to + ;; the frame, sets its rate and plays it if the db says so. + :fx (when place? + (if switch? + [[::pb/pause! nil] + [::pb/clock! {:id (:clip/current db) :sid open}]] + [[::pb/rate! (get-in db [:playback :rate] 1.0)] + [::pb/loop! (boolean (get-in db [:playback :loop?]))] + [::pb/seek! [(get-in db [:clip :fps]) n f]] + [(if (get-in db [:playback :playing?]) ::pb/play! ::pb/pause!) nil]]))}))))) + +(def ^:private steer + "When an event changes what a party shares, the party hears where we are now. + + NOT ON A TICK, 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. And a move a mate made before its tab reached us is taken as soon + as the write that brings it does." + (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]) + [_ v :as parked] (get-in after [:follow :parked])] + (cond-> ctx + (and parked (pb/openable? after (get v [:ui :open]))) + (update-in [:effects :fx] (fnil conj []) [:dispatch (into [::moved] parked)]) + + (not (or (nil? after) (#{::pb/tick ::moved} event) + (= (view before (paths after)) (view after)) + (not= (get-in before [:project :id]) (get-in after [:project :id])) + (not (together? after)))) + (update-in [:effects :fx] (fnil conj []) [::nav! (view-msg after)])))))) + +;; --------------------------------------------------------------------------- +;; the room + +(defn- wire-sid [sid] (some-> sid str (subs 1))) + +(defn- who [db cid] + {:who (or (get-in db [:peers cid :user]) "guest") :colour (collab/colour cid)}) + +(rf/reg-fx ::point (fn [[cid who m]] (page/seen! cid who m))) +(rf/reg-fx ::scroll (fn [m] (page/scrolled! m))) +(rf/reg-fx ::forget (fn [cid] (if (= :all cid) (page/clear!) (page/gone! cid)))) + +(rf/reg-event-fx + ::heard + (fn [{:keys [db]} [_ ^js m]] + (let [cid (.-cid m) + mate (party/mirrors? (:peers db) (me db) cid)] + (case (.-kind m) + "reset" {:db (cond-> (assoc-in db [:follow :parked] nil) + (.-elsewhere m) (update :presence dissoc :party)) + ::forget :all} + "leave" {::forget cid} + "state" (let [joining (.-joining m) + ;; They followed us while we were on our own: take on the + ;; id they made of our cid. Nobody hosts — we both carry it. + adopt? (and (me db) (= (me db) joining) (nil? (mine db)) + (get-in db [:presence :joinable])) + fx (if adopt? (collab/say db {:party (.-party m)}) {:db db}) + db (:db fx) + r (:peers db) + ours (mine db)] + (cond-> fx + (not (party/mirrors? r (me db) cid)) (assoc ::forget cid) + ;; 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 db) (party/responder r ours cid))) + (assoc ::nav! (view-msg db)))) + "nav" {:dispatch [::moved cid (t/read reader (.-view m))]} + "cursor" (if (and mate (not (contains? (off db) :pointers)) + (= (.-open m) (wire-sid (get-in db [:ui :open])))) + {::point [cid (who db cid) (js->clj m :keywordize-keys true)]} + {::forget cid}) + "scroll" (if (and mate (not (contains? (off db) :scroll))) + {::scroll (js->clj m :keywordize-keys true)} + {}) + {})))) + +;; --------------------------------------------------------------------------- +;; what you do + +(rf/reg-event-fx + ::follow + (fn [{:keys [db]} [_ cid]] + (if (party/joinable? (:peers db) (me db) cid) + (collab/say db {:party (party/join-id (:peers db) cid)} {:joining cid}) + {}))) + +(rf/reg-event-fx + ::leave + (fn [{:keys [db]} _] + (-> (collab/say (update db :follow dissoc :parked :last) {:party nil}) + (assoc ::forget :all)))) + +(rf/reg-event-fx + ::set-joinable + (fn [{:keys [db]} [_ on?]] + (assoc (collab/say db {:joinable on?}) ::remember [:joinable (if on? "1" "0")]))) + +(rf/reg-event-fx + ::toggle + ;; Taking a facet back catches up to where the party last was. + (fn [{:keys [db]} [_ k]] + (let [was (off db) + now (if (contains? was k) (disj was k) (conj was k)) + db (assoc-in db [:follow :off] now)] + (cond-> {:db db ::remember [:off (.join (to-array (map name now)) ",")]} + (= :pointers k) (assoc ::forget :all) + (and (contains? was k) (get-in db [:follow :last])) + (assoc :dispatch (into [::moved] (get-in db [:follow :last]))))))) + +(rf/reg-sub ::joinable? (fn [db _] (get-in db [:presence :joinable] true))) +(rf/reg-sub ::together? (fn [db _] (together? db))) +(rf/reg-sub ::off (fn [db _] (off db))) +(rf/reg-sub ::mates (fn [db _] (party/peers (:peers db) (me db)))) +(rf/reg-sub ::may? (fn [db [_ cid]] (party/joinable? (:peers db) (me db) cid))) + +(defn face + "What following adds to a face in the roster: it is the whole control — + follow them, or, once you are together, leave, which is the same one click." + [{:keys [cid user]}] + (let [who (or user "guest") + mate? (contains? @(rf/subscribe [::mates]) cid) + may? @(rf/subscribe [::may? cid])] + {:class (when mate? "mate") + :disabled (not (or mate? may?)) + :title (cond mate? (str "following " who " — click to stop") + may? (str "follow " who) + :else (str who " isn't letting anyone follow")) + :on-click #(rf/dispatch (if mate? [::leave] [::follow cid]))})) + +(defn controls + "The eye — whether others may follow you — and, while you are together, what + you follow of them, each a switch." + [] + (let [open? @(rf/subscribe [::joinable?]) + off @(rf/subscribe [::off])] + [:<> + [: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 [::set-joinable (not open?)])} + [icon/view :eye]] + (when @(rf/subscribe [::together?]) + [menu/popover {:label "▾" :title "what you follow" :class "follow-what"} + (fn [_] + [:div.view-popout + (for [[k label] facets] + ^{:key k} + [:label [:input {:type "checkbox" :checked (not (contains? off k)) + :on-change #(rf/dispatch [::toggle k])}] + label]) + [:small "Unticked, you look around on your own — and don't move them either."]])])])) + +;; --------------------------------------------------------------------------- + +(defn- sharing + "What the page layer sends right now, or nil when there is nobody to send it + to. Read off app-db rather than subscribed: it is asked on a pointer move." + [] + (let [db @rf-db/app-db] + (when (together? db) + {:open (wire-sid (get-in db [:ui :open])) + :scroll? (not (contains? (off db) :scroll))}))) + +(defn install! + "Follow from now on. The one line in `arthur.core`." + [] + (rf/dispatch-sync [::init]) + (rf/reg-global-interceptor steer) + (collab/listen! ::heard) + (page/install! {:send! collab/send! :sharing sharing})) diff --git a/frontend/src/arthur/follow/page.cljs b/frontend/src/arthur/follow/page.cljs new file mode 100644 index 0000000..f2d56f7 --- /dev/null +++ b/frontend/src/arthur/follow/page.cljs @@ -0,0 +1,250 @@ +(ns arthur.follow.page + "A party's pointers and panel scroll, anywhere on the page. + + A POINTER IS WHAT IT POINTS AT, NOT WHERE IT IS. Two windows are never laid + out alike — another size, a pane dragged wider, the stage zoomed — so a pixel + lands on something else. What goes out instead is the element under the + pointer, as a path down from , and where it is inside each element + along the way; a mate finds the same element on their page and puts the + pointer at the same place in it. Over a button, it is over their button. + Google Docs anchors a caret to the text rather than to the screen, and + Liveblocks recommends this for cursors on a responsive page; this is that, + for a page of panels. + + IN AN SVG — the stage, the timeline's curves — the point is in the SVG's own + units instead, so a pointer on the drawing stays on the drawing at any zoom + and scroll. + + A path that only partly resolves — a menu open there and not here — falls + back to the deepest element both pages have, and the pointer shows dimmed. + One scrolled out of a pane waits at its edge. + + Plain DOM and no React: drawn once a frame, and only while one is showing.") + +;; --------------------------------------------------------------------------- +;; addresses + +(defn- classes [^js el] (.getAttribute el "class")) +(defn- kind [^js el] [(.-localName el) (.. el -classList (item 0))]) + +(defn- nth-like + "Which of `el`'s siblings that `same?` says are like it, it is." + [^js el same?] + (count (take-while #(not (identical? % el)) + (filter same? (array-seq (.. el -parentElement -children)))))) + +(defn- step + "`el` as one step of a path: its tag and classes, which of its siblings with + those it is, and which of those with its tag and FIRST class. The pool and the + inspector are both a `section.pane`, so the first class alone takes one for + the other whenever a pane is shut on one page and not the other; but the rest + come and go with state — `on`, `selected` — and a row lit on one page is still + the same row on the other, so that is what a step falls back to." + [^js el] + (let [tag (.-localName el) cls (classes el) k (kind el)] + [tag cls + (nth-like el #(and (= tag (.-localName %)) (= cls (classes %)))) + (nth-like el #(= k (kind %)))])) + +(defn- child [^js parent [tag cls n m]] + (let [kids (array-seq (.-children parent)) + k [tag (not-empty (first (some-> cls (.split " "))))]] + (or (nth (filter #(and (= tag (.-localName %)) (= cls (classes %))) kids) n nil) + (nth (filter #(= k (kind %)) kids) m nil)))) + +(defn- lineage + "The elements from below down to `el`." + [^js el] + (->> (iterate #(.-parentElement ^js %) el) + (take-while #(and % (not (identical? % js/document.body)))) + reverse)) + +(defn- svg-root [^js el] + (when (instance? js/SVGElement el) + (last (take-while some? (iterate #(.-ownerSVGElement ^js %) el))))) + +(defn- round [x] (/ (js/Math.round (* 1000 x)) 1000)) + +(defn- through [^js svg m x y] + (let [p (.matrixTransform (js/DOMPoint. x y) m)] [(round (.-x p)) (round (.-y p))])) + +(defn- address + "Where client point `x` `y` is, as a mate's page can find it." + [x y] + (when-let [hit (.elementFromPoint js/document x y)] + (let [svg (svg-root hit) + els (lineage (or svg hit))] + {:path (mapv step els) + :at (mapv (fn [^js e] + (let [r (.getBoundingClientRect e)] + [(round (/ (- x (.-left r)) (max 1 (.-width r)))) + (round (/ (- y (.-top r)) (max 1 (.-height r))))])) + els) + :page [(round (/ x (.-innerWidth js/window))) (round (/ y (.-innerHeight js/window)))] + :svg (some-> svg .getScreenCTM .inverse (as-> m (through svg m x y)))}))) + +(defn- find-path + "The elements `path` names on this page, first, as deep as they go." + [path] + (reduce (fn [found s] + (if-let [c (child (peek found) s)] (conj found c) (reduced found))) + [js/document.body] path)) + +;; --------------------------------------------------------------------------- +;; drawing them + +(defonce ^:private shown (atom {})) ; cid → {:msg :found :clip :xy :el} +(defonce ^:private raf (atom nil)) + +(defn- layer [] + (or (.getElementById js/document "follow-layer") + (doto (.createElement js/document "div") + (set! -id "follow-layer") + (->> (.appendChild js/document.body))))) + +(defn- arrow [{:keys [who colour]}] + (doto (.createElement js/document "div") + (set! -className "follow-pointer") + (-> .-style (.setProperty "--who" colour)) + (set! -innerHTML (str "" + "" + "")) + (-> (.querySelector "span") (set! -textContent who)) + (->> (.appendChild (layer))))) + +(defn- clips + "The ancestors of the last of `found` that cut off what overflows them." + [found] + (filter #(not= "visible" (.-overflow (js/getComputedStyle %))) (rest (pop found)))) + +(defn- resolved [{:keys [path] :as m}] + (let [found (find-path path)] (assoc m :found found :clip (clips found)))) + +(defn- target + "Where a pointer goes on this page, and whether it is lost (only part of its + path is here) or away (scrolled out of view, so held at the edge)." + [{:keys [path at page svg found clip]}] + (let [d (dec (count found)) + ^js el (peek found) + [x y] (cond + (and svg (= d (count path))) + (if-let [m (.getScreenCTM el)] (through el m (svg 0) (svg 1)) [-99 -99]) + (pos? d) + (let [r (.getBoundingClientRect el) [fx fy] (nth at (dec d))] + [(+ (.-left r) (* fx (.-width r))) (+ (.-top r) (* fy (.-height r)))]) + :else [(* (page 0) (.-innerWidth js/window)) (* (page 1) (.-innerHeight js/window))]) + [l t r b] (reduce (fn [[l t r b] ^js c] + (let [q (.getBoundingClientRect c)] + [(max l (.-left q)) (max t (.-top q)) + (min r (.-right q)) (min b (.-bottom q))])) + [0 0 (.-innerWidth js/window) (.-innerHeight js/window)] clip) + cx (max l (min r x)) cy (max t (min b y))] + {:xy [cx cy] :lost? (< d (count path)) :away? (not= [x y] [cx cy])})) + +(defn- frame! [_] + (doseq [[cid {:keys [found xy ^js el] :as s}] @shown] + (let [s (cond-> s (not (.-isConnected ^js (peek found))) resolved) + {[tx ty] :xy :keys [lost? away?]} (target s) + ;; Halfway there each frame: messages come every 40ms, frames every + ;; 16, and a pointer that jumps between them looks like it stutters. + [x y] (if xy [(+ (xy 0) (* 0.5 (- tx (xy 0)))) (+ (xy 1) (* 0.5 (- ty (xy 1))))] [tx ty])] + (set! (.. el -style -transform) (str "translate(" x "px," y "px)")) + (.toggle (.-classList el) "lost" lost?) + (.toggle (.-classList el) "away" away?) + (swap! shown assoc cid (assoc s :xy [x y])))) + (reset! raf (when (seq @shown) (js/requestAnimationFrame frame!)))) + +(defn gone! [cid] + (some-> (get-in @shown [cid :el]) .remove) + (swap! shown dissoc cid)) + +(defn clear! [] (run! gone! (keys @shown))) + +(defn seen! + "A mate's pointer message, `{:path :at :page :svg :clicks}` — or no path, + when it has left their window." + [cid who {:keys [path clicks] :as m}] + (if-not path + (gone! cid) + (let [was (get @shown cid) + el (or (:el was) (arrow who))] + ;; A press, as a ring: the one thing you cannot tell from the pointer alone. + (when (and was (not= clicks (get-in was [:msg :clicks]))) + (.animate (.querySelector el "i") + #js [#js {:transform "scale(.3)" :opacity 1} #js {:transform "scale(1.6)" :opacity 0}] + 450)) + (swap! shown assoc cid (-> (resolved m) (assoc :msg m :el el :xy (:xy was)))) + (when-not @raf (reset! raf (js/requestAnimationFrame frame!)))))) + +;; --------------------------------------------------------------------------- +;; scroll + +(defonce ^:private applied (js/WeakMap.)) + +(defn- scrolled-to [^js el] [(.-scrollTop el) (.-scrollLeft el)]) + +(defn scrolled! + "A mate scrolled a panel. Only on a whole path: half a path is some other + panel. In pixels, because a list's rows are the same height on both pages." + [{:keys [path top left]}] + (let [found (find-path path)] + (when (= (count found) (inc (count path))) + (let [^js el (peek found)] + (set! (.-scrollTop el) top) + (set! (.-scrollLeft el) left) + (.set applied el (scrolled-to el)))))) + +;; --------------------------------------------------------------------------- + +(defn every + "`f` with the latest arguments, at most once every `gap` ms: the first at + once, and the last always, so a mate sees where a move ENDED." + [gap f] + (let [timer (atom nil) pending (atom nil)] + (fn [& args] + (reset! pending args) + (when-not @timer + (apply f args) + (reset! pending nil) + (reset! timer (js/setTimeout (fn self [] + (if-let [a @pending] + (do (reset! pending nil) (apply f a) + (reset! timer (js/setTimeout self gap))) + (reset! timer nil))) + gap)))))) + +(defonce ^:private installed? (atom false)) + +(defn install! + "Watch the page for a party: `sharing` says whether there is one, and what + tab we are on; `send!` tells it." + [{:keys [send! sharing]}] + (when-not @installed? + (reset! installed? true) + (let [clicks (atom 0) + point! (every 40 (fn [x y] + (when-let [{:keys [open]} (sharing)] + (send! (merge {:kind "cursor" :open open :clicks @clicks} + (when x (address x y))))))) + scroll! (every 60 (fn [^js el] + (when (:scroll? (sharing)) + (let [[top left] (scrolled-to el)] + (send! {:kind "scroll" :path (mapv step (lineage el)) + :top top :left left}))))) + on (fn [target kind f] (.addEventListener target kind f #js {:capture true :passive true}))] + (on js/document "pointermove" (fn [^js e] (when (.-isPrimary e) (point! (.-clientX e) (.-clientY e))))) + (on js/document "pointerdown" (fn [^js e] + (when (.-isPrimary e) + (swap! clicks inc) + (point! (.-clientX e) (.-clientY e))))) + (on js/document.documentElement "mouseleave" (fn [_] (point! nil nil))) + (on js/document "visibilitychange" (fn [_] (when (.-hidden js/document) (point! nil nil)))) + (on js/document "scroll" + (fn [^js e] + (let [el (.-target e)] + ;; Not the stage's: how far in it is scrolled depends on its zoom, + ;; which is each person's own. A pointer on it is in stage units. + (when (and (instance? js/Element el) (not (.closest el ".stage-area"))) + (if (= (.get applied el) (scrolled-to el)) + (.delete applied el) ; ours, from a mate's + (scroll! el))))))))) diff --git a/frontend/src/arthur/domain/party.cljs b/frontend/src/arthur/follow/party.cljs similarity index 99% rename from frontend/src/arthur/domain/party.cljs rename to frontend/src/arthur/follow/party.cljs index 1f157ee..cab9cc7 100644 --- a/frontend/src/arthur/domain/party.cljs +++ b/frontend/src/arthur/follow/party.cljs @@ -1,4 +1,4 @@ -(ns arthur.domain.party +(ns arthur.follow.party "Following someone, worked out from the presence roster. tl's parties, nearly line for line. diff --git a/frontend/src/arthur/subs/render.cljs b/frontend/src/arthur/subs/render.cljs index be13ff6..aad177f 100644 --- a/frontend/src/arthur/subs/render.cljs +++ b/frontend/src/arthur/subs/render.cljs @@ -43,13 +43,8 @@ ;; lets go, so the stage and the rows follow the pointer. Nothing is written ;; until then: one drag is one undo step and one write to collaborators. (let [{c :clip st :store} (footage/entry id)] - (or (when-let [{:keys [path df kind ripple? other owner paths]} sliding] - (let [root (or owner open)] - (:clip (case kind - :out (nest/resize-out c root path df ripple?) - :in (nest/resize-in c root path df) - :roll (nest/roll c root other path df) - (if (seq paths) (nest/slide-many c root paths df) (nest/slide c root path df)))))) + (or (when sliding + (:clip (nest/drag c (or (:owner sliding) open) sliding))) (when-let [{:keys [sid id frame values edits]} gesture] ;; A held stage control owns the touched parameters completely. Make ;; them temporary static channels for the preview, so their existing diff --git a/frontend/src/arthur/subs/ui.cljs b/frontend/src/arthur/subs/ui.cljs index 25fd988..a80faa1 100644 --- a/frontend/src/arthur/subs/ui.cljs +++ b/frontend/src/arthur/subs/ui.cljs @@ -11,6 +11,7 @@ [arthur.domain.node :as node] [arthur.domain.pick :as pick] [arthur.domain.symbol :as symbol] + [arthur.events.edit :as edit] [arthur.footage.store :as store] [arthur.subs.playback :as playback] [arthur.subs.render :as render] @@ -31,7 +32,9 @@ (rf/reg-sub ::clipboard (fn [db _] (get-in db [:ui :clipboard]))) (rf/reg-sub ::retry (fn [db _] (get-in db [:ui :retry]))) (rf/reg-sub ::tone (fn [db _] (get-in db [:ui :tone]))) -(rf/reg-sub ::tool (fn [db _] (or (get-in db [:ui :tool]) :select))) +(rf/reg-sub ::read-only? (fn [db _] (edit/read-only? db))) +;; Looking is all a read-only project allows, so it is all the stage does. +(rf/reg-sub ::tool (fn [db _] (if (edit/read-only? db) :select (or (get-in db [:ui :tool]) :select)))) (rf/reg-sub ::auto-key? (fn [db _] (boolean (get-in db [:ui :auto-key?])))) (rf/reg-sub ::draft (fn [db _] (get-in db [:ui :draft]))) (rf/reg-sub ::vertex (fn [db _] (get-in db [:ui :vertex]))) diff --git a/frontend/src/arthur/ui/pool.cljs b/frontend/src/arthur/ui/pool.cljs index 65f32c5..6634186 100644 --- a/frontend/src/arthur/ui/pool.cljs +++ b/frontend/src/arthur/ui/pool.cljs @@ -204,7 +204,7 @@ `inside` is `{:count :open? :flip!}` for a row with rows under it; a row with none keeps the twisty's room, so names line up down a level. - `delete!` puts a cross beside the pencil, on hover as the pencil is." + `delete!` puts a cross beside the pencil while the row is picked." [{:keys [label sub sub2 title thumb on? open? main? disabled? rename depth inside delete!] :as opts}] (let [{:keys [key value begin! commit!]} rename @@ -255,25 +255,53 @@ ;; the browser test finds a row by the name a person reads. [:span.name label] (when (and main? sub2) [:span.detail sub2])] - (when begin! - [:span.pool-rename - {:title (str "rename " label " (F2)") - ;; Mouse-only by design — see the docstring. A `tabindex` here would - ;; make it interactive content inside a button, which is the thing - ;; being avoided, and F2 already reaches it from the keyboard. - :on-click (fn [^js e] (.stopPropagation e) (begin! key))} - "\u270E"]) - (when delete! - [:span.pool-rename.pool-delete - {:title (str "delete " label " (Delete)") - :on-click (fn [^js e] (.stopPropagation e) (delete!))} - "\u00D7"]) ;; The main row says both its facts under the name instead. - (when (and sub (not main?)) [:span.sub sub])]])])) + (when (and sub (not main?)) [:span.sub sub]) + ;; At the row's end, together, as a timeline row has them: the pencil + ;; on every row and the cross on what is picked. Two quick clicks on + ;; either are two clicks, not a double-click that opens the row. + [:span.pool-actions {:on-double-click (fn [^js e] (.stopPropagation e))} + (when begin! + [:span.pool-rename + {:title (str "rename " label " (F2)") + ;; Mouse-only by design — see the docstring. A `tabindex` here would + ;; make it interactive content inside a button, which is the thing + ;; being avoided, and F2 already reaches it from the keyboard. + :on-click (fn [^js e] (.stopPropagation e) (begin! key))} + "\u270E"]) + (when (and delete! on?) + [:span.pool-rename.pool-delete + {:title (str "delete " label " (Delete)") + :on-click (fn [^js e] (.stopPropagation e) (delete!))} + "\u00D7"])]]])])) ;; --------------------------------------------------------------------------- ;; the rows of each kind +(defonce ^:private anchor (atom nil)) + +(defn- pick! + "A click picks `what`, as a click on a timeline row does: with ⌘ it is added + to the picked or taken out of them, and with shift every row shown from the + last one clicked to this one is picked." + [^js e what] + (let [shown (vec (keep #(aget % "arthurPick") + (array-seq (.querySelectorAll (.closest (.-currentTarget e) ".pane.pool") + ".pool-item")))) + a (.indexOf shown @anchor) + b (.indexOf shown what)] + (cond + (or (.-metaKey e) (.-ctrlKey e)) (rf/dispatch [::ui/toggle-selection what]) + (and (.-shiftKey e) (<= 0 a) (<= 0 b)) + (rf/dispatch [::ui/select-many (subvec shown (min a b) (inc (max a b)))]) + :else (rf/dispatch [::ui/select what])) + (when-not (.-shiftKey e) (reset! anchor what)))) + +(defn- pickable + "The ref that tells `pick!` which rows are shown, in order." + [what] + (fn [^js el] (when el (aset el "arthurPick" what)))) + (defn- symbol-row [document sid {:keys [clip-id store palette selection open main rename depth inside]}] (let [sym (clip/symbol document sid) @@ -292,19 +320,20 @@ [tracing-thumb (:media sym)] [picture (symbol-thumb document sid store palette)]) :sub2 (str (:frames sym) "f · " nodes (if (= 1 nodes) " node" " nodes")) - :on? (= selection [:symbol sid]) + :on? (contains? selection [:symbol sid]) :open? (= sid open) :main? (= sid main) :depth depth :inside inside - :delete! (when-not (= sid main) #(rf/dispatch [::ui/delete-symbol sid])) + :delete! (when-not (= sid main) #(rf/dispatch [::ui/delete-symbols [sid]])) :rename (assoc rename :key [:symbol sid] :value label :commit! (fn [value] ((:begin! rename) nil) (rf/dispatch [::project/rename-symbol sid value]))) - :on-click #(rf/dispatch [::ui/select [:symbol sid]]) + :on-click #(pick! % [:symbol sid]) + :ref (pickable [:symbol sid]) :on-double-click #(rf/dispatch [::pb/open-symbol sid])} (carrying (str "symbol:" (subs (str sid) 1)) #(drag/symbol! clip-id sid open)))])) @@ -316,14 +345,15 @@ [row {:label (clip/symbol-name document sid) :sub (str "uses " (or (:name p) (:palette-ref sym))) :title "Palette transition definition" - :on? (= selection [:symbol sid]) + :on? (contains? selection [:symbol sid]) :rename (assoc rename :key [:symbol sid] :value (clip/symbol-name document sid) :commit! (fn [value] ((:begin! rename) nil) (rf/dispatch [::project/rename-symbol sid value]))) - :on-click #(rf/dispatch [::ui/select [:symbol sid]])}])) + :on-click #(pick! % [:symbol sid]) + :ref (pickable [:symbol sid])}])) (defn- footage-row [{:keys [id label frames fps video width height] :as f} chosen rename] ^{:key id} @@ -632,7 +662,7 @@ clip-id @(rf/subscribe [::render/clip-id]) store @(rf/subscribe [::render/store]) palette @(rf/subscribe [::render/palette]) - selection @(rf/subscribe [::sub/selection]) + selection (set @(rf/subscribe [::sub/selections])) open @(rf/subscribe [::render/open]) media @(rf/subscribe [::sub/project-footage]) {:keys [symbols palettes]} @(rf/subscribe [::project/assets]) diff --git a/frontend/src/arthur/ui/share.cljs b/frontend/src/arthur/ui/share.cljs index 5a2c79f..c2b983e 100644 --- a/frontend/src/arthur/ui/share.cljs +++ b/frontend/src/arthur/ui/share.cljs @@ -1,16 +1,15 @@ (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`. + A face is also how you follow someone — see `arthur.follow`, whose lines here + are marked. 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.follow :as follow] ; follow [arthur.subs.playback :as playback] [clojure.string :as str] [re-frame.core :as rf] @@ -27,60 +26,25 @@ (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]))} +(defn- face [{:keys [cid user] :as p}] + (let [f (follow/face p)] ; follow + [:button.peer (merge {:style {:background (collab/colour cid)} + :aria-label (or user "guest") :title (or user "guest") + :disabled true} + f + {:class [(when-not user "guest") (:class f)]}) (initial user)])) (defn- roster [] - (let [peers @(rf/subscribe [::collab/peers]) - open? @(rf/subscribe [::collab/followable?])] + (let [peers @(rf/subscribe [::collab/peers])] (when (seq peers) [: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]] + [follow/controls] ; follow (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) draft (r/atom "")] diff --git a/frontend/src/arthur/ui/shell.cljs b/frontend/src/arthur/ui/shell.cljs index 20015d7..65c659d 100644 --- a/frontend/src/arthur/ui/shell.cljs +++ b/frontend/src/arthur/ui/shell.cljs @@ -12,6 +12,7 @@ [arthur.events.playback :as pb] [arthur.subs.playback :as playback] [arthur.subs.render :as render] + [arthur.subs.ui :as sub] [arthur.ui.layout :as layout] [arthur.ui.location :as location] [arthur.ui.params :as params] @@ -69,7 +70,10 @@ ;; pane's contents. (let [{:keys [pool params shut] :as state} @(rf/subscribe [::layout/state]) gone? #(contains? shut %)] - [:div.app {:style (layout/vars state)} + ;; `read-only`: somebody else's project. The edits themselves are refused + ;; in `events/edit`; this greys out the controls that would make them. + [:div.app {:style (layout/vars state) + :class (when @(rf/subscribe [::sub/read-only?]) "read-only")} [topbar/view] [shortcuts/sheet] (when-not (gone? :pool) [pool/view]) diff --git a/frontend/src/arthur/ui/stage.cljs b/frontend/src/arthur/ui/stage.cljs index 6de05b1..3a2461a 100644 --- a/frontend/src/arthur/ui/stage.cljs +++ b/frontend/src/arthur/ui/stage.cljs @@ -18,7 +18,6 @@ [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] @@ -28,7 +27,6 @@ [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] @@ -719,13 +717,12 @@ ;; 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) (collab/point! nil)) + :on-pointer-leave (fn [_] (reset! pointer 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. @@ -773,8 +770,7 @@ (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]) - [share/cursors zoom]])) + (when paints? [cursor tool])])) (defonce pan (atom nil)) (defonce navigation-blur diff --git a/frontend/src/arthur/ui/timeline.cljs b/frontend/src/arthur/ui/timeline.cljs index 73dd02b..cfa473b 100644 --- a/frontend/src/arthur/ui/timeline.cljs +++ b/frontend/src/arthur/ui/timeline.cljs @@ -790,8 +790,10 @@ ;; The palette row is the symbol's one palette lane: "palette" says all ;; there is to say, and it has no name of its own to change. named-lane? (and lane? (not= :palette kind)) + ;; A node row renames what it shows: an instance, its symbol. + renamable? (or named-lane? (and node? (some? (nth select 2 nil)))) selected? (contains? selections select) - editing? (and lane? (= select @renaming)) + editing? (and renamable? (= select @renaming)) begin-rename! (fn [] (reset! draft label) (reset! renaming select)) commit-rename! (fn [] (when (= select @renaming) @@ -827,7 +829,7 @@ ;; grouped with it into a new one; onto an edge of either, to be ;; restacked in front of it or behind it, in whichever symbol it is ;; in. All of them keep the picture as it is, but for the stacking. - node? (merge {:draggable true + node? (merge {:draggable (not editing?) :on-drag-start (fn [^js e] (.stopPropagation e) (.setData (.-dataTransfer e) "text/plain" "row") @@ -868,6 +870,7 @@ ;; is then suppressed by the browser). :draggable false :on-pointer-down (fn [^js e] (.stopPropagation e)) + :on-double-click (fn [^js e] (.stopPropagation e)) :on-click (fn [^js e] (.stopPropagation e) (rf/dispatch [::ui/set-row-expanded path (not expanded?)]))} @@ -880,7 +883,7 @@ (when lane? [:span.tl-ico {:aria-hidden true} [icon/view :lane]]) (if editing? [:input.tl-name-input - {:value @draft :auto-focus true :aria-label "lane name" + {:value @draft :auto-focus true :aria-label "name" :on-click #(.stopPropagation %) :on-double-click #(.stopPropagation %) :on-change #(reset! draft (.. % -target -value)) @@ -899,40 +902,43 @@ (cond named-lane? [:span.kind "·lane"] node? [:span.kind (if via (str "· in " via) (str "·" (name node-kind)))]) - (when named-lane? - [:button.tl-rename - {:title "rename lane" - :on-click (fn [^js e] (.stopPropagation e) (begin-rename!))} - "✎"]) - ;; A tracing layer's row switches it on and off, next to solo because the - ;; two are the same kind of thing: what this row shows, here, now, and - ;; nothing the picture keeps. A face's row switches its footage — its - ;; plate — which is the same switch wherever the face is placed. - (when-let [layer (cond (contains? (:traces tracing) of) [(second select) (nth select 2)] - (contains? (:plated tracing) of) [of :plate])] - (let [{:keys [on? hidden]} (:state tracing) - shown? (and on? (not (contains? hidden layer)))] - [:button {:class (str "tl-trace" (when shown? " on")) - :title (if (contains? (:traces tracing) of) - "show this tracing layer · never exported" - "show the footage this face was traced from") - :on-click (fn [^js e] - (.stopPropagation e) - (rf/dispatch [::ui/show-trace layer (not shown?)]))} - "T"])) - (when (= :instance node-kind) - [:button {:class (str "tl-solo" (when (contains? solo path) " on")) - :title "show only this on the stage (⇧ for more than one)" - :on-click (fn [^js e] - (.stopPropagation e) - (rf/dispatch [::ui/solo path (.-shiftKey e)]))} - "S"]) - (when (and node? (= select selection)) - [:button.tl-delete {:title "delete, with everything in it (⌫)" - :on-click (fn [^js e] - (.stopPropagation e) - (rf/dispatch [::ui/delete-selected]))} - "×"])])) + ;; The row's buttons sit together at its right end. Two quick clicks on + ;; one of them are two clicks, not a double-click that opens the row. + [:span.tl-actions {:on-double-click (fn [^js e] (.stopPropagation e))} + (when (and renamable? (not editing?)) + [:button.tl-rename + {:title (if (= :instance node-kind) "rename symbol · every placement follows" "rename") + :on-click (fn [^js e] (.stopPropagation e) (begin-rename!))} + "✎"]) + ;; A tracing layer's row switches it on and off, next to solo because the + ;; two are the same kind of thing: what this row shows, here, now, and + ;; nothing the picture keeps. A face's row switches its footage — its + ;; plate — which is the same switch wherever the face is placed. + (when-let [layer (cond (contains? (:traces tracing) of) [(second select) (nth select 2)] + (contains? (:plated tracing) of) [of :plate])] + (let [{:keys [on? hidden]} (:state tracing) + shown? (and on? (not (contains? hidden layer)))] + [:button {:class (str "tl-trace" (when shown? " on")) + :title (if (contains? (:traces tracing) of) + "show this tracing layer · never exported" + "show the footage this face was traced from") + :on-click (fn [^js e] + (.stopPropagation e) + (rf/dispatch [::ui/show-trace layer (not shown?)]))} + "T"])) + (when (= :instance node-kind) + [:button {:class (str "tl-solo" (when (contains? solo path) " on")) + :title "show only this on the stage (⇧ for more than one)" + :on-click (fn [^js e] + (.stopPropagation e) + (rf/dispatch [::ui/solo path (.-shiftKey e)]))} + "S"]) + (when (and node? (= select selection)) + [:button.tl-delete {:title "delete, with everything in it (⌫)" + :on-click (fn [^js e] + (.stopPropagation e) + (rf/dispatch [::ui/delete-selected]))} + "×"])]])) (defn- paint-key-selection! "Selection and preview are transient DOM state. Update them in one pass, @@ -1193,7 +1199,7 @@ ;; gesture; what it meant is known on release. (reset! sliding {:row path :path actual-path :kind gesture-kind :other other - :paths (when (and (= :slide gesture-kind) (not owner) + :paths (when (and (#{:slide :in :out} gesture-kind) (not owner) (contains? selected-set actual-select) (< 1 (count selections))) (mapv #(nth % 3) (filter #(= :node (first %)) selections))) @@ -1389,8 +1395,14 @@ [:span.tl-junction {:title "Drag the cut · the clip before it ends here and the one after it starts here" :on-pointer-down + ;; Between two clips of a selection, it is the end of the one + ;; before, and every selected end moves with it. (fn [^js e] - (begin! e (nth select 3) :roll select (nth (:select prev) 3) nil))}] + (if (and (< 1 (count selections)) + (contains? selected-set select) + (contains? selected-set (:select prev))) + (begin! e (nth (:select prev) 3) :out (:select prev) nil nil) + (begin! e (nth select 3) :roll select (nth (:select prev) 3) nil)))}] [:span.tl-edge.in {:title "Drag start" :on-pointer-down #(begin! % (nth select 3) :in select nil nil)}])) (when select diff --git a/frontend/src/arthur/ui/tools.cljs b/frontend/src/arthur/ui/tools.cljs index f4823ce..8ee3f02 100644 --- a/frontend/src/arthur/ui/tools.cljs +++ b/frontend/src/arthur/ui/tools.cljs @@ -37,10 +37,10 @@ [:aside.toolbox [:div.tools (doall - (for [{t :tool :keys [key name tip icon]} kit] + (for [{t :tool label :name :keys [key tip icon]} kit] ^{:key t} - [:button {:class (str "tool" (when (= t tool) " on")) - :title (str name " (" (.toUpperCase key) ") — " tip) + [:button {:class (str "tool tool-" (name t) (when (= t tool) " on")) + :title (str label " (" (.toUpperCase key) ") — " tip) :on-click #(rf/dispatch [::ui/set-tool t])} [:svg {:view-box "0 0 18 18" :width 18 :height 18} icon]]))] [palette/grid] diff --git a/frontend/test/arthur/domain/clipboard_test.cljs b/frontend/test/arthur/domain/clipboard_test.cljs index 8e8f94b..4491f4a 100644 --- a/frontend/test/arthur/domain/clipboard_test.cljs +++ b/frontend/test/arthur/domain/clipboard_test.cljs @@ -3,7 +3,8 @@ [arthur.domain.clip :as clip] [arthur.domain.clipboard :as clipboard] [arthur.domain.node :as node] - [arthur.domain.sequence-test :as fixture])) + [arthur.domain.sequence-test :as fixture] + [arthur.domain.symbol :as symbol])) (defn- ids [] (let [n (atom 0)] @@ -187,15 +188,18 @@ (is (:refused r)) (is (nil? (:clip r))))) -(deftest reparenting-into-a-lane-refuses-collision-atomically +(deftest reparenting-into-a-lane-claims-what-it-lands-on + ;; As one clip dropped into a lane does: the forest takes its frames from the + ;; clip already there. (let [doc (-> (reparent-document) (assoc-in [:symbols :box :display] :lane) (assoc-in [:symbols :box :nodes :occupied] (fixture/cel :occupied :drawing-a 4 4 0))) r (clipboard/move-many doc {} :main [(address :main :a [:a]) (address :main :b [:b])] [:target] 6 0)] - (is (:refused r)) - (is (nil? (:clip r))))) + (is (nil? (:refused r)) (str (:refused r))) + (is (nil? (get-in r [:clip :symbols :box :nodes :occupied])) "covered, it is gone") + (is (empty? (symbol/overlaps (get-in r [:clip :symbols :box])))))) (deftest dropping-the-forest-shifts-it-as-a-unit (let [r (clipboard/move-many (reparent-document) {} :main diff --git a/frontend/test/arthur/domain/sequence_test.cljs b/frontend/test/arthur/domain/sequence_test.cljs index bd90ddd..88187b2 100644 --- a/frontend/test/arthur/domain/sequence_test.cljs +++ b/frontend/test/arthur/domain/sequence_test.cljs @@ -858,12 +858,34 @@ (is (empty? (symbol/overlaps (get-in mixed [:symbols :main])))) (is (empty? (clip/problems mixed)))))) -(deftest moving-a-selection-in-a-lane-is-simultaneous - (let [doc (document) - moved (:clip (nest/slide-many doc :main [[:a] [:b]] 1))] - (is (nil? moved)) - (is (:refused (nest/slide-many doc :main [[:a] [:b]] 1)) - "the whole group refuses collision with the unselected insert"))) +(deftest moving-a-selection-in-a-lane-claims-what-it-lands-on + ;; One clip slid onto another takes its frames; a selection slid together does + ;; the same, and the clips in it keep their places among themselves. + (let [moved (:clip (nest/slide-many (document) :main [[:a] [:b]] 1)) + spans (into {} (map (juxt :id node/placed-span)) + (symbol/children (get-in moved [:symbols :main :nodes])))] + (is (= {:a [1 5] :b [5 9] :insert [9 12]} spans)) + (is (empty? (clip/problems moved))))) + +(defn- spans-after [result] + (is (nil? (:refused result)) (str (:refused result))) + (into {} (map (juxt :id node/placed-span)) + (symbol/children (get-in result [:clip :symbols :main :nodes])))) + +(deftest every-selected-clip-trims-by-the-same-drag + (let [all [[:a] [:b] [:insert]]] + (is (= {:a [0 6] :b [6 10] :insert [10 14]} + (spans-after (nest/resize-many (document) :main all :out 2 false))) + "each end moves two frames and eats the start of the clip after it") + (is (= {:a [0 6] :b [6 12] :insert [12 18]} + (spans-after (nest/resize-many (document) :main all :out 2 true))) + "rippled, every clip is two frames longer and nothing is eaten") + (is (= {:a [0 2] :b [4 6] :insert [8 10]} + (spans-after (nest/resize-many (document) :main all :out -2 false))) + "shortened, each leaves a gap") + (is (= {:a [0 9] :insert [9 17]} + (spans-after (nest/resize-many (document) :main all :out 5 false))) + "a clip eaten whole by an earlier one has no edge left to move"))) (deftest moving-all-lane-clips-preserves-their-spans (let [doc (document) diff --git a/frontend/test/arthur/events/read_only_test.cljs b/frontend/test/arthur/events/read_only_test.cljs new file mode 100644 index 0000000..839f0ba --- /dev/null +++ b/frontend/test/arthur/events/read_only_test.cljs @@ -0,0 +1,27 @@ +(ns arthur.events.read-only-test + (:require [cljs.test :refer [deftest is]] + [arthur.domain.clip :as clip] + [arthur.domain.paint :as paint] + [arthur.events.ui :as ui] + [arthur.footage.store :as store] + [arthur.subs.ui :as sub] + [re-frame.core :as rf] + [re-frame.db :as rf-db])) + +(deftest a-project-you-may-only-look-at-takes-no-edit + (let [doc (paint/new-shape (clip/blank) :main :s 0 [0 0 10 0 20 10 10 20 0 20] 1) + id (store/install! {:clip doc :store {}} "read-only") + shape #(get-in (:clip (store/entry (:clip/current @rf-db/app-db))) [:symbols :main :nodes :s])] + (reset! rf-db/app-db {:clip/current id :paint/revision 0 + :project {:can-edit? false} + :ui {:open :main :tool :brush :selection [:node :main :s [:s]] + :selections [[:node :main :s [:s]]]} + :playback {:frame 0}}) + (is (= :select @(rf/subscribe [::sub/tool])) "the stage only selects") + (rf/dispatch-sync [::ui/delete-selected]) + (is (some? (shape)) "Delete deletes nothing") + (is (= 0 (:paint/revision @rf-db/app-db)) "and nothing became unsaved") + (swap! rf-db/app-db #(-> % (assoc-in [:project :can-edit?] true) (update :ui assoc :tool :select :selection [:node :main :s [:s]] + :selections [[:node :main :s [:s]]]))) + (rf/dispatch-sync [::ui/delete-selected]) + (is (nil? (shape)) "an editor's Delete does"))) diff --git a/frontend/test/arthur/domain/party_test.cljs b/frontend/test/arthur/follow/party_test.cljs similarity index 96% rename from frontend/test/arthur/domain/party_test.cljs rename to frontend/test/arthur/follow/party_test.cljs index 61e3238..78a7658 100644 --- a/frontend/test/arthur/domain/party_test.cljs +++ b/frontend/test/arthur/follow/party_test.cljs @@ -1,6 +1,6 @@ -(ns arthur.domain.party-test +(ns arthur.follow.party-test (:require [cljs.test :refer [deftest is]] - [arthur.domain.party :as party])) + [arthur.follow.party :as party])) (defn- roster [& entries] (into {} (map (fn [[cid p joinable]] diff --git a/frontend/test/browser/lane.mjs b/frontend/test/browser/lane.mjs index 29b2fab..b402fe4 100644 --- a/frontend/test/browser/lane.mjs +++ b/frontend/test/browser/lane.mjs @@ -110,7 +110,7 @@ try { assert.equal((await shot()).clip.symbols.main.display, undefined, 'a blank document starts as an ordinary symbol'); - await clickNew('symbol'); + await clickNew('+ symbol'); let s = await shot(); let placed = mainInstances(s); assert.equal(placed.length, 1, 'new symbol places one instance'); @@ -124,7 +124,7 @@ try { // create the lane inside that symbol. await evaluate(`re_frame.core.dispatch_sync(cljs.core.vector( cljs.core.keyword('arthur.events.ui/select'), null))`); - await clickNew('lane'); + await clickNew('+ lane'); s = await shot(); placed = mainInstances(s); assert.equal(placed.length, 2, 'explicit lane places a second symbol'); @@ -132,9 +132,9 @@ try { assert.equal(await evaluate('[...document.querySelectorAll(".tl-track:not(.palette)")].filter(t => t.arthurLane).length'), 1, 'the explicit lane is drawn as one linear track'); - assert.equal(await evaluate('document.querySelectorAll(".tl-label:not(.palette) .tl-rename").length'), 1, + assert.equal(await evaluate('document.querySelectorAll(".tl-label.lane:not(.palette) .tl-rename").length'), 1, 'the lane exposes its rename control'); - await evaluate('document.querySelector(".tl-label:not(.palette) .tl-rename").click()'); + await evaluate('document.querySelector(".tl-label.lane:not(.palette) .tl-rename").click()'); await sleep(80); assert(await evaluate(`(() => { const input = document.querySelector('.tl-name-input'); @@ -190,7 +190,7 @@ try { // that leaving a symbol selected creates the lane inside that symbol. await evaluate(`re_frame.core.dispatch_sync(cljs.core.vector( cljs.core.keyword('arthur.events.ui/select'), null))`); - await clickNew('lane'); + await clickNew('+ lane'); s = await shot(); assert.equal(laneSymbols(s).length, 2, 'a second explicit command creates a second lane'); const move = await evaluate(`(() => { @@ -220,7 +220,7 @@ try { await evaluate(`re_frame.core.dispatch_sync(cljs.core.vector( cljs.core.keyword('arthur.events.project/new'))) `); await sleep(250); - await clickNew('symbol'); + await clickNew('+ symbol'); const clipboardBaseline = (await shot()).clip; await shortcut('d', 'KeyD'); assert.equal(mainInstances(await shot()).length, 2, 'duplicate copies the selected instance'); diff --git a/static/arthur/app.css b/static/arthur/app.css index 4108148..71420ad 100644 --- a/static/arthur/app.css +++ b/static/arthur/app.css @@ -474,16 +474,44 @@ button.peer { display: inline-grid; place-items: center; background: var(--sel); color: #fff; font-size: 10px; font-weight: 600; } +button.peer:disabled { cursor: default; } + +/* follow — arthur.follow. A face you can follow lights on hover, one that will + not let you is dimmed, and the ones you are following wear a ring. The eye + says whether you may be followed; ▾ beside it is what you follow. */ button.peer:hover:not(:disabled) { filter: brightness(1.15); } -button.peer:disabled { opacity: .45; cursor: default; } +button.peer:disabled:not(.mate) { opacity: .45; } 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; } +.follow-what .view-popout { min-width: 190px; max-width: 240px; } +.follow-what .view-popout label { + display: flex; gap: 8px; align-items: center; margin: 0; padding: 3px 0; + white-space: nowrap; cursor: pointer; +} +.follow-what .view-popout input { width: auto; margin: 0; flex: none; } +.follow-what .view-popout small { display: block; margin-top: 8px; color: var(--dim); white-space: normal; } -/* 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; } +/* A mate's pointer, over everything and catching nothing. `lost` is a pointer + on something this page does not have open, `away` one scrolled out of view + and waiting at the edge. */ +#follow-layer { position: fixed; inset: 0; pointer-events: none; z-index: 2147483000; overflow: hidden; } +.follow-pointer { position: absolute; left: 0; top: 0; will-change: transform; transition: opacity .15s; } +.follow-pointer svg { width: 11px; height: 15px; display: block; overflow: visible; } +.follow-pointer path { fill: var(--who); stroke: #fff; stroke-width: 1; stroke-linejoin: round; } +.follow-pointer span { + position: absolute; left: 9px; top: 13px; white-space: nowrap; + padding: 1px 5px; border-radius: 3px; background: var(--who); + color: #fff; font: 600 10px/12px system-ui, sans-serif; +} +.follow-pointer i { + position: absolute; left: -9px; top: -9px; width: 18px; height: 18px; + border-radius: 50%; border: 2px solid var(--who); opacity: 0; +} +.follow-pointer.lost { opacity: .45; } +.follow-pointer.away { opacity: .6; } +/* end follow */ /* -------------------------------------------------------------------------- media pool @@ -651,9 +679,8 @@ button.followable svg { width: 12px; height: 12px; display: block; } cursor: grab; } -/* Shrinks to the name, so the pencil sits against the end of the word rather - than out at the edge of the pane — and ellipses rather than pushing the - number off the row. */ +/* Shrinks to the name, and ellipses rather than pushing the number off the + row. */ .pool-item .text { display: flex; flex-direction: column; flex: 0 1 auto; min-width: 0; } .pool-item .name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } @@ -721,13 +748,12 @@ button.followable svg { width: 12px; height: 12px; display: block; } white-space: nowrap; } -/* The pencil. A span and not a button — see `ui/pool`'s `row` — so it needs its - own centring and cursor rather than inheriting a control's. - - Hidden until the row is under the pointer or holds focus, because a column of - twenty pencils is a column of twenty pencils; `visibility` rather than - `display`, so it keeps its width and the name beside it does not reflow as the - pointer crosses the list. */ +/* The pencil and the cross, at the row's end as a timeline row has them. Two + slots wide whether or not the cross is there, so the numbers beside them stay + in one column. Spans and not buttons — see `ui/pool`'s `row` — so they need + their own centring and cursor rather than inheriting a control's. */ +.pool-actions { display: flex; flex: 0 0 30px; justify-content: flex-start; } +.pool-item > .text + .pool-actions { margin-left: auto; } .pool-rename { display: flex; align-items: center; @@ -739,11 +765,8 @@ button.followable svg { width: 12px; height: 12px; display: block; } color: var(--dim); line-height: 1; cursor: pointer; - visibility: hidden; } -.pool-row:hover .pool-rename, -.pool-row:focus-within .pool-rename { visibility: visible; } .pool-rename:hover { background: var(--hair); color: var(--fg); } /* Renaming. The input REPLACES the row at the same height, so a list does not @@ -1182,7 +1205,8 @@ button.followable svg { width: 12px; height: 12px; display: block; } .tl-label.lane:hover:not(.on) { background: #f8f6f0; } .tl-track.lane { background: rgba(0, 0, 0, 0.035); } .tl-name-input { min-width: 0; flex: 1; font: inherit; } -.tl-rename { margin-left: auto; padding: 0 3px; border: 0; background: none; color: var(--dim); } +.tl-actions { display: flex; align-items: center; margin-left: auto; } +.tl-rename { padding: 0 3px; border: 0; background: none; color: var(--dim); } .tl-rename:hover { color: var(--fg); } /* A fixed-width cell whether or not there is a triangle in it, so names at the @@ -1200,12 +1224,11 @@ button.followable svg { width: 12px; height: 12px; display: block; } .tl-twist:hover:not(:disabled) { background: none; color: var(--fg); } .tl-twist:disabled { opacity: 0; cursor: default; } -.tl-delete { margin-left: auto; padding: 0 4px; border: 0; background: none; color: var(--dim); } +.tl-delete { padding: 0 4px; border: 0; background: none; color: var(--dim); } .tl-delete:hover { color: var(--fg); } -.tl-solo, .tl-trace { margin-left: auto; padding: 0 4px; border: 0; background: none; color: var(--dim); font-size: 10px; } +.tl-solo, .tl-trace { padding: 0 4px; border: 0; background: none; color: var(--dim); font-size: 10px; } .tl-solo:hover, .tl-trace:hover { color: var(--fg); } .tl-solo.on, .tl-trace.on { color: var(--sel); font-weight: 600; } -.tl-solo + .tl-delete, .tl-trace + .tl-solo { margin-left: 0; } /* The ruler and the corner above the labels stay at the top of the body while the rows scroll under them: the ruler is the scrubber, and scrolling down to @@ -2039,3 +2062,14 @@ button.tl-key.selected { background: var(--pick); box-shadow: 0 0 0 2px var(--pi cursor: ew-resize; touch-action: none; background: linear-gradient(var(--sel), var(--sel)) center / 2px 100% no-repeat; } + +/* -------------------------------------------------------------------------- + read-only — somebody else's project. `events/edit` refuses the edits; this + greys out what would make them, so nothing offers what it cannot do. + Selecting, inspecting, playing and the view's own settings stay. */ +.app.read-only :is( + .toolbox .tool:not(.tool-select), .toolbox > :not(.tools), + .context-controls, .creation-controls, button.auto-key, + .params .inspect :is(input, select, textarea, button), + .pool-foot +) { opacity: .4; pointer-events: none; }