✨ Draw review activity cards as each sitting left the layer

A card of the review activity drew its layer from the open file, so
every card showed the layer as it is now. A new read-only command,
get-branch-layer-at-revision, rebuilds a layer and its children at a
branch revision with the replay every branch read uses, so a revision
written before a file migration comes back exact. A revision before
the last update from the source, which squashes the log, comes back
as the current layer marked approximate. A deleted layer comes back as
it stood before its deletion.

Each sitting of the activity now carries the revn of its last save,
and its cards fetch the layer at that revn once and cache it, falling
back to the open file while loading or on error.

AI-assisted-by: claude-opus-5-5
This commit is contained in:
Álvaro Tejero Cantero 2026-11-24 22:55:14 +01:00
parent b7e6a89485
commit 1d484e276d
No known key found for this signature in database
17 changed files with 830 additions and 91 deletions

View File

@ -208,6 +208,19 @@
:get-branch-review-activity/global
{:permits 4 :queue 10 :timeout 60000}
;; Rebuilding a layer at a branch revision costs at most one branch
;; read: the base and the op log replayed up to the revision, one
;; document where the listing holds three, so it takes the listing's
;; six. A review card asks for its layer when it is shown, so opening
;; the activity sends one request per visible card: the per-profile
;; entry runs two of them at once and lets the rest of the cards queue.
;; Provisional.
:get-branch-layer-at-revision/global
{:permits 6 :queue 20 :timeout 60000}
:get-branch-layer-at-revision/by-profile
{:permits 2 :queue 20 :timeout 60000}
;; Moving a thread left behind realizes the target document, then moves
;; the thread, its tasks and their events: the one document
;; `create-branch-review` realizes, so it takes the anchor's numbers,

View File

@ -465,6 +465,81 @@
(:data (migrate-detached cfg base fmg/migrate-file))
data)))
(defn- get-branch-replay-start
"What a replay of the op log of the branch `file` starts from: the
`file_branch` row (`:branch`), the merge-base snapshot realized to
plain maps (`:base`), the fragment ids the base named before the
realize (`:base-ids`), and the document the replay works on (`:doc`).
That document is the merge base at the base's data version, under the
branch file's identity, so a migration on the way resolves the
branch's libraries, and a change or migration that compares a
reference with the document's own `:id` sees the branch."
[{:keys [::db/conn] :as cfg} {:keys [id] :as file}]
(let [branch (db/get* conn :file-branch {:branch-file-id id})
_ (when (nil? branch)
(ex/raise :type :not-found
:code :branch-metadata-missing
:hint "branch metadata not found for branch file"
:file-id id))
base (db/get-with-sql cfg
[sql:get-branch-base-snapshot
(:source-file-id branch)
(:base-snapshot-id branch)
(ct/now)]
{::db/remove-deleted false})
_ (when (nil? base)
(ex/raise :type :not-found
:code :base-snapshot-missing
:hint "the branch merge-base snapshot cannot be resolved"
:file-id id))
;; same decode `fsnap/get-snapshot` applies: storage-backed
;; snapshots carry the storage ref inside :metadata, so it must
;; be decoded before `resolve-file-data` can fetch the object.
;; NOTE the (cfg file) argument order of both fdata fns: the
;; snapshot row is the FILE argument, never the cfg.
base (-> base
(d/update-when :metadata fdata/decode-metadata))
base (if (nil? (:migrations base))
(dissoc base :migrations)
(update base :migrations db/pgarray->set))
base (fdata/resolve-file-data cfg base)
base (fdata/decode-file-data cfg base)
;; the fragment ids the base names, read before the realize
;; drops them: a comparison skips every page the source still shares
base-ids (fdata/get-page-pointer-ids (:data base))
;; the base shares the source file's fragments; past this point
;; the replay, the migrations and every caller see plain data
base (realize-branch-base cfg base)]
{:branch branch
:base base
:base-ids base-ids
:doc (-> file
(assoc :data (assoc (:data base) :id id))
(assoc :version (or (:version base) (:version file)))
(assoc :migrations (:migrations base)))}))
(defn- replay-branch-row
"Apply one op log `row` to the replayed document `doc`. A row's
`data_version` is the version its changes were written at: the
document migrates to it before the row applies, and in the steady
state that check is one set lookup. Returns the document after the row
and the number of changes the row held."
[cfg doc {:keys [changes data-version]}]
(let [changes (blob/decode changes)
doc (if (fmg/need-migration-to? doc data-version)
(migrate-detached cfg doc #(fmg/migrate-file-to %1 %2 data-version))
doc)]
[(update doc :data cpc/process-changes changes)
(count changes)]))
(defn- branch-file-data
"Derive the `:data` of a branch file: the merge-base snapshot plus
every op appended to the branch's log, replayed in revn order.
@ -511,78 +586,18 @@
[{:keys [::db/conn] :as cfg} {:keys [id] :as file} decode? include-base-data?]
(let [tpoint (ct/tpoint)
branch (db/get* conn :file-branch {:branch-file-id id})
_ (when (nil? branch)
(ex/raise :type :not-found
:code :branch-metadata-missing
:hint "branch metadata not found for branch file"
:file-id id))
base (db/get-with-sql cfg
[sql:get-branch-base-snapshot
(:source-file-id branch)
(:base-snapshot-id branch)
(ct/now)]
{::db/remove-deleted false})
_ (when (nil? base)
(ex/raise :type :not-found
:code :base-snapshot-missing
:hint "the branch merge-base snapshot cannot be resolved"
:file-id id))
;; same decode `fsnap/get-snapshot` applies: storage-backed
;; snapshots carry the storage ref inside :metadata, so it must
;; be decoded before `resolve-file-data` can fetch the object.
;; NOTE the (cfg file) argument order of both fdata fns: the
;; snapshot row is the FILE argument, never the cfg.
base (-> base
(d/update-when :metadata fdata/decode-metadata))
base (if (nil? (:migrations base))
(dissoc base :migrations)
(update base :migrations db/pgarray->set))
base (fdata/resolve-file-data cfg base)
base (fdata/decode-file-data cfg base)
;; the fragment ids the base names, read before the realize
;; drops them: a comparison skips every page the source still shares
base-ids (fdata/get-page-pointer-ids (:data base))
;; the base shares the source file's fragments; past this point
;; the replay, the migrations and every caller see plain data
base (realize-branch-base cfg base)
{:keys [branch base base-ids doc]} (get-branch-replay-start cfg file)
rows (db/exec! conn [sql:get-branch-changes id])
;; the document the replay works on: the merge base at the
;; base's data version, under the branch file's identity, so a
;; migration on the way resolves the branch's libraries, and a
;; change or migration that compares a reference with the
;; document's own `:id` sees the branch
doc (-> file
(assoc :data (assoc (:data base) :id id))
(assoc :version (or (:version base) (:version file)))
(assoc :migrations (:migrations base)))
;; the derive replays the log batch by batch, so each batch is
;; decoded exactly once. `depth` is the flattened op count, the
;; quantity `files_branch.clj::check-oplog-depth-limit!` limits,
;; and the one that predicts the cost of the replay.
;;
;; A row's `data_version` is the version its changes were
;; written at; the document migrates to it before the row
;; applies, and in the steady state that check is one set
;; lookup.
[doc depth]
(reduce (fn [[doc depth] {:keys [changes data-version]}]
(let [changes (blob/decode changes)
doc (if (fmg/need-migration-to? doc data-version)
(migrate-detached cfg doc #(fmg/migrate-file-to %1 %2 data-version))
doc)]
[(update doc :data cpc/process-changes changes)
(+ depth (count changes))]))
(reduce (fn [[doc depth] row]
(let [[doc n] (replay-branch-row cfg doc row)]
[doc (+ depth n)]))
[doc 0]
rows)
@ -756,6 +771,117 @@
(db/run! cfg get-file* file-id opts)
(db/tx-run! cfg get-file* file-id opts)))
;; --- A layer of a branch at one of its revisions
(def ^:private sql:get-branch-changes-up-to
"SELECT changes, data_version
FROM file_branch_change
WHERE file_id = ?
AND deleted_at IS NULL
AND revn <= ?
ORDER BY revn ASC")
(defn- layer-present?
[doc page-id shape-id]
(-> doc :data :pages-index (get page-id) :objects (contains? shape-id)))
(defn- layer-subtree
"The shape `shape-id` of page `page-id` of `data` with its whole
subtree, as an `{id -> shape}` map, or an empty map when the page does
not hold the shape."
[data page-id shape-id]
(let [objects (-> data :pages-index (get page-id) :objects)]
(if (contains? objects shape-id)
(select-keys objects (cfh/get-children-ids-with-self objects shape-id))
{})))
(defn- squashed-revn?
"Whether the branch revision `revn` predates the last update of the
branch from its source, which the op log can no longer rebuild. An
update moves the merge base to the source and replaces the log with
one squashed row (`files_branch.clj::persist-branch-update!`), and it
stores in `base_branch_revn` the branch revn it ran at, one less when
the branch carried work of its own. Every save before the update
produced a revn at or below that counter, and every save after it a
revn above. A branch never updated keeps the counter at 0, the revn of
the empty file it was cut as, whose state is the base itself."
[{:keys [base-branch-revn]} revn]
(and (pos? base-branch-revn)
(<= revn base-branch-revn)))
(defn get-branch-layer-at-revision
"The shape `shape-id` of page `page-id` of the branch file `file-id`,
with its whole subtree, as the branch revision `revn` left it. Returns
`{:objects :approximate :deleted}`, `:objects` an `{id -> shape}` map
at the current data version with the ids unchanged, empty when the
shape is unknown.
The replay is the one `branch-file-data` runs, stopped after the last
op log row at or below `revn`: each row applies at the data version it
was written at, and the result migrates to the current version. A
revision older than the last update from the source is gone from the
log (`squashed-revn?`): the whole log replays and `:approximate` is
true. A branch detached into an ordinary file has no log left, so its
current layer comes back approximate as well.
When the shape is absent at the end of the replay but stood in it
earlier, `:deleted` is true and the shape comes back as it stood just
before the row that removed it."
[{:keys [::db/conn] :as cfg} file-id page-id shape-id revn]
(let [row (db/get conn :file {:id file-id}
{:columns [:is-branch]
::db/remove-deleted false})]
(if-not (:is-branch row)
{:objects (-> (get-file cfg file-id
:realize? true
:read-only? true
:include-deleted? true)
(:data)
(layer-subtree page-id shape-id))
:approximate true
:deleted false}
(let [file (get-file cfg file-id
:load-data? false
:migrate? false
:read-only? true
:include-deleted? true)
{:keys [branch doc]} (get-branch-replay-start cfg file)
approximate? (squashed-revn? branch revn)
rows (if approximate?
(db/exec! conn [sql:get-branch-changes file-id])
(db/exec! conn [sql:get-branch-changes-up-to file-id revn]))
;; `removed` is the document just before the last row that
;; took the shape away, nil while the shape stands
[doc removed]
(reduce (fn [[before removed] row]
(let [[after _] (replay-branch-row cfg before row)]
[after (cond
(layer-present? after page-id shape-id) nil
(layer-present? before page-id shape-id) before
:else removed)]))
[doc nil]
rows)
deleted? (some? removed)
doc (if deleted? removed doc)
doc (if (fmg/need-migration? doc)
(migrate-detached cfg doc fmg/migrate-file)
doc)
;; the base and early op log rows name the source; the
;; branch reads name itself, as `branch-file-data` does
id-map {(:source-file-id branch) file-id}
objects (layer-subtree (:data doc) page-id shape-id)]
{:objects (:objects (cfh/relink-page {:objects objects} #(get id-map % %)))
:approximate approximate?
:deleted deleted?}))))
(defn clean-file-features
[file]
(update file :features (fn [features]

View File

@ -2263,6 +2263,38 @@
(db/exec! conn [sql:get-branch-change-marks
branch-id profile-id (name direction)]))))
;; --- COMMAND QUERY: get-branch-layer-at-revision
(def ^:private schema:get-branch-layer-at-revision
[:map {:title "get-branch-layer-at-revision" :closed true}
[:branch-id ::sm/uuid]
[:revn ::sm/int]
[:page-id ::sm/uuid]
[:shape-id ::sm/uuid]])
(sv/defmethod ::get-branch-layer-at-revision
"A layer of the branch `branch-id` with its whole subtree as the branch
revision `revn` left it, rebuilt from the branch's op log
(`app.binfile.common/get-branch-layer-at-revision`). Returns `{:revn
:objects :approximate :deleted}`: `:objects` maps each id to its shape
and is empty when the shape is unknown, `:approximate` says the
revision predates the last update from the source and the layer is
the current one, and `:deleted` says the layer was gone at that
revision and comes back as it stood just before its removal. Reading
the branch is enough."
{::doc/added "2.16"
::sm/params schema:get-branch-layer-at-revision
::climit/id [[:get-branch-layer-at-revision/by-profile ::rpc/profile-id]
[:get-branch-layer-at-revision/global]]}
[cfg {:keys [::rpc/profile-id branch-id revn page-id shape-id]}]
(check-branching-enabled!)
(db/tx-run! (assoc cfg ::db/read-only true)
(fn [cfg]
(let [branch (get-readable-branch cfg profile-id branch-id)]
(-> (bfc/get-branch-layer-at-revision cfg (:branch-file-id branch)
page-id shape-id revn)
(assoc :revn revn))))))
(def ^:private schema:set-branch-change-mark
[:map {:title "set-branch-change-mark"}
[:branch-id ::sm/uuid]

View File

@ -531,7 +531,7 @@
500)
(def ^:private sql:get-branch-review-activity
"SELECT a.id, a.profile_id, a.entries, a.created_at
"SELECT a.id, a.profile_id, a.revn, a.entries, a.created_at
FROM file_branch_review_activity AS a
WHERE a.review_id = ?
ORDER BY a.created_at ASC, a.id ASC")
@ -609,9 +609,11 @@
"What the saves of the branch did to its layers since the branch review
opened, folded on the server: `:entries` what each layer ends up as
(`app.common.files.review-activity/net-entries`), `:sessions` the
sittings of saves the activity lists, `:people` how many people saved
and `:last-save` the newest save. Every row of the review is read, so
the oldest change still counts in what a layer ends up as."
sittings of saves the activity lists, each with the branch `:revn` its
last save produced (what `get-branch-layer-at-revision` takes),
`:people` how many people saved, and `:last-save` the newest save.
Every row of the review is read, so the oldest change still counts in
what a layer ends up as."
{::doc/added "2.16"
::sm/params schema:get-branch-review-activity
::climit/id [[:get-branch-review-activity/global]]}

View File

@ -6,9 +6,12 @@
(ns backend-tests.rpc-file-branch-review-test
(:require
[app.common.data :as d]
[app.common.features :as cfeat]
[app.common.files.branch-merge :as bm]
[app.common.files.migrations :as fmg]
[app.common.time :as ct]
[app.common.types.shape :as cts]
[app.common.uuid :as uuid]
[app.config :as cf]
[app.db :as db]
@ -17,6 +20,7 @@
[app.rpc :as-alias rpc]
[app.util.blob :as blob]
[backend-tests.helpers :as th]
[clojure.string :as str]
[clojure.test :as t]))
(t/use-fixtures :once th/state-init)
@ -817,3 +821,218 @@
(t/is (= 2 (count (:sessions result))))
(t/is (= 1 (:people result)))
(t/is (= (:id author) (-> result :last-save :profile-id)))))))
;; --- A layer at a branch revision
(defn- page-id-of
[profile file-id]
(-> (th/command! {::th/type :get-file
::rpc/profile-id (:id profile)
:id file-id})
:result :data :pages first))
(defn- add-shape*
[profile file-id page-id {:keys [id parent-id frame-id] :as attrs}]
(apply-change* profile file-id
{:type :add-obj
:page-id page-id
:id id
:parent-id parent-id
:frame-id frame-id
:obj (cts/setup-shape attrs)}))
(defn- rename*
[profile file-id page-id id name]
(let [out (apply-change* profile file-id
{:type :mod-obj
:page-id page-id
:id id
:operations [{:type :set :attr :name :val name}]})]
(t/is (nil? (:error out)))
out))
(defn- revn-of
[file-id]
(:revn (th/db-get :file {:id file-id})))
(defn- layer-at*
[profile branch-id revn page-id shape-id]
(th/command! {::th/type :get-branch-layer-at-revision
::rpc/profile-id (:id profile)
:branch-id branch-id
:revn revn
:page-id page-id
:shape-id shape-id}))
(defn- names-of
[result]
(update-vals (:objects result) :name))
(defn- setup-board-branch
"A source file holding a board with a rect inside, and a branch of it.
Returns the ids the tests need."
[]
(let [author (th/create-profile* 1 {:is-active true})
file (th/create-file* 1 {:profile-id (:id author)
:project-id (:default-project-id author)})
page-id (page-id-of author (:id file))
board-id (uuid/random)
rect-id (uuid/random)]
(add-shape* author (:id file) page-id
{:id board-id :name "Checkout" :type :frame
:x 0 :y 0 :width 400 :height 800
:parent-id uuid/zero :frame-id uuid/zero})
(add-shape* author (:id file) page-id
{:id rect-id :name "Pay button" :type :rect
:x 10 :y 10 :width 100 :height 40
:parent-id board-id :frame-id board-id})
(let [branch (create-branch* author file "feature")]
{:author author
:file file
:page-id page-id
:board-id board-id
:rect-id rect-id
:branch branch
:branch-file-id (:branch-file-id branch)})))
(t/deftest layer-at-revision-follows-each-save
(with-redefs [cf/flags (pr-flags)]
(let [{:keys [author page-id board-id rect-id branch branch-file-id]} (setup-board-branch)
_ (rename* author branch-file-id page-id board-id "Checkout A")
r1 (revn-of branch-file-id)
_ (rename* author branch-file-id page-id rect-id "Pay")
r2 (revn-of branch-file-id)
_ (rename* author branch-file-id page-id board-id "Checkout C")
r3 (revn-of branch-file-id)]
(t/testing "each save comes back as it left the board and its child"
(doseq [[revn expected] [[r1 {board-id "Checkout A" rect-id "Pay button"}]
[r2 {board-id "Checkout A" rect-id "Pay"}]
[r3 {board-id "Checkout C" rect-id "Pay"}]]]
(let [out (layer-at* author (:id branch) revn page-id board-id)
result (:result out)]
(t/is (nil? (:error out)))
(t/is (= revn (:revn result)))
(t/is (= expected (names-of result)))
(t/is (false? (:approximate result)))
(t/is (false? (:deleted result))))))
(t/testing "an unknown shape comes back empty"
(let [result (:result (layer-at* author (:id branch) r3 page-id (uuid/random)))]
(t/is (= {} (:objects result)))
(t/is (false? (:deleted result))))))))
(def ^:private layer-test-migration
"9999-test-upper-layer-names")
;; A file migration that rewrites every layer name, so a name tells
;; whether the document crossed it before or after a change applied.
(defmethod fmg/migrate-data "9999-test-upper-layer-names"
[data _]
(d/update-when data :pages-index update-vals
(fn [page]
(d/update-when page :objects update-vals
(fn [shape]
(d/update-when shape :name str/upper-case))))))
(t/deftest layer-at-revision-replays-across-a-file-migration
;; An ordinary file saved "Pay" before the upgrade holds "PAY" after
;; it; a name saved after the upgrade stays as written.
(with-redefs [cf/flags (pr-flags)]
(let [{:keys [author page-id board-id rect-id branch branch-file-id]} (setup-board-branch)
_ (rename* author branch-file-id page-id rect-id "Pay")
r1 (revn-of branch-file-id)
v1 (fmg/data-version)]
(with-redefs [fmg/available-migrations (conj fmg/available-migrations layer-test-migration)]
(rename* author branch-file-id page-id rect-id "Pay now")
(let [r2 (revn-of branch-file-id)]
(t/testing "the rows straddle the upgrade"
(t/is (= [v1 layer-test-migration]
(->> (th/db-query :file-branch-change {:file-id branch-file-id})
(sort-by :revn)
(mapv :data-version)))))
(t/testing "a revision before the upgrade migrates after its row applies"
(let [result (:result (layer-at* author (:id branch) r1 page-id board-id))]
(t/is (= {board-id "CHECKOUT" rect-id "PAY"} (names-of result)))
(t/is (false? (:approximate result)))))
(t/testing "a revision after the upgrade keeps what its row wrote"
(let [result (:result (layer-at* author (:id branch) r2 page-id board-id))]
(t/is (= {board-id "CHECKOUT" rect-id "Pay now"} (names-of result)))
(t/is (false? (:approximate result))))))))))
(t/deftest layer-before-an-update-from-source-is-approximate
(with-redefs [cf/flags (pr-flags)]
(let [{:keys [author file page-id rect-id branch branch-file-id]} (setup-board-branch)]
(rename* author branch-file-id page-id rect-id "Mine")
(let [before (revn-of branch-file-id)]
(add-color* author (:id file) "Source color")
(let [out (th/command! {::th/type :update-file-branch-from-source
::rpc/profile-id (:id author)
:branch-id (:id branch)})]
(t/is (nil? (:error out)))
(t/is (= :updated (-> out :result :status))))
(rename* author branch-file-id page-id rect-id "Later")
(let [after (revn-of branch-file-id)
earlier (:result (layer-at* author (:id branch) before page-id rect-id))
latest (:result (layer-at* author (:id branch) after page-id rect-id))]
(t/testing "a revision the squash took comes back as the current layer"
(t/is (true? (:approximate earlier)))
(t/is (= {rect-id "Later"} (names-of earlier))))
(t/testing "a revision after the update comes back exact"
(t/is (false? (:approximate latest)))
(t/is (= {rect-id "Later"} (names-of latest)))))))))
(t/deftest deleted-layer-comes-back-as-it-stood-before
(with-redefs [cf/flags (pr-flags)]
(let [{:keys [author page-id board-id rect-id branch branch-file-id]} (setup-board-branch)
_ (rename* author branch-file-id page-id board-id "Going")
r1 (revn-of branch-file-id)
_ (t/is (nil? (:error (apply-change* author branch-file-id
{:type :del-obj :page-id page-id :id board-id}))))
r2 (revn-of branch-file-id)]
(t/testing "the deleting revision returns the board as it stood before"
(let [result (:result (layer-at* author (:id branch) r2 page-id board-id))]
(t/is (true? (:deleted result)))
(t/is (false? (:approximate result)))
(t/is (= {board-id "Going" rect-id "Pay button"} (names-of result)))))
(t/testing "the revision before it is not deleted"
(let [result (:result (layer-at* author (:id branch) r1 page-id board-id))]
(t/is (false? (:deleted result)))
(t/is (= {board-id "Going" rect-id "Pay button"} (names-of result))))))))
(t/deftest layer-at-revision-needs-read-rights
(with-redefs [cf/flags (pr-flags)]
(let [{:keys [page-id board-id branch branch-file-id]} (setup-board-branch)
stranger (th/create-profile* 2 {:is-active true})]
(t/testing "a profile that cannot read the source is refused"
(let [out (layer-at* stranger (:id branch) (revn-of branch-file-id) page-id board-id)]
(t/is (= :not-found (-> out :error ex-data :type)))
(t/is (= :object-not-found (-> out :error ex-data :code)))))
(t/testing "an unknown branch is refused"
(let [out (layer-at* stranger (uuid/random) 0 page-id board-id)]
(t/is (= :branch-not-found (-> out :error ex-data :code))))))))
(t/deftest activity-sittings-carry-the-revn-of-their-last-save
(with-redefs [cf/flags (pr-flags)]
(let [{:keys [author page-id board-id rect-id branch branch-file-id]} (setup-board-branch)
review-id (-> (create-review* author (:id branch) {}) :result :id)]
(rename* author branch-file-id page-id board-id "Checkout A")
(rename* author branch-file-id page-id rect-id "Pay")
(let [out (th/command! {::th/type :get-branch-review-activity
::rpc/profile-id (:id author)
:id review-id})
result (:result out)]
(t/is (nil? (:error out)))
(t/is (= 1 (count (:sessions result))))
(t/is (= (revn-of branch-file-id)
(-> result :sessions first :revn)))))))

View File

@ -257,11 +257,19 @@
milliseconds, belong to different sittings."
(* 30 60 1000))
(defn- last-revn
"The newest branch revn among `rows`: the revn the last save of a
sitting produced. Nil when no row carries one."
[rows]
(some->> (seq (keep :revn rows))
(reduce max)))
(defn sessions
"Cut `rows` into sittings: runs of saves of one person with no gap
longer than `gap-ms` milliseconds between two of them, newest first.
Each sitting has the person (`:profile-id`), when it started and ended
and its own `net-entries`."
Each sitting has the person (`:profile-id`), when it started and ended,
the branch revn its last save produced (`:revn`, the highest revn of
its rows), and its own `net-entries`."
([rows] (sessions rows default-session-gap-ms))
([rows gap-ms]
(->> rows
@ -285,6 +293,7 @@
(when (seq entries)
(-> session
(dissoc :rows)
(assoc :revn (last-revn rows))
(assoc :entries entries))))))
(reverse)
(vec))))

View File

@ -140,3 +140,14 @@
result (ra/sessions rows)]
(t/is (= [marc marc ana] (mapv :profile-id result)))
(t/is (= {:r1 [8 12]} (-> result last :entries first :attrs)))))
(t/deftest sessions-carry-the-revn-of-their-last-save
(let [minute (* 60 1000)
rows [(assoc (row ana 0 [(assoc modified-entry :attrs {:r1 [8 10]})]) :revn 3)
(assoc (row ana (* 10 minute) [(assoc modified-entry :attrs {:r1 [10 12]})]) :revn 5)
(assoc (row marc (* 20 minute) [(assoc modified-entry :attrs {:r1 [12 14]})]) :revn 6)
(assoc (row marc (* 90 minute) [(assoc modified-entry :attrs {:r1 [14 16]})]) :revn 9)]
result (ra/sessions rows)]
(t/is (= [9 6 5] (mapv :revn result)))
(t/testing "a sitting whose rows carry no revn has none"
(t/is (nil? (:revn (first (ra/sessions [(row ana 0 [(assoc modified-entry :attrs {:r1 [8 10]})])]))))))))

View File

@ -0,0 +1,45 @@
{
"~:revn": 7,
"~:approximate": true,
"~:deleted": false,
"~:objects": {
"~uc7ce0794-0992-8105-8004-38f280443a01": {
"~#shape": {
"~:id": "~uc7ce0794-0992-8105-8004-38f280443a01",
"~:name": "Checkout button",
"~:type": "~:rect",
"~:x": 40,
"~:y": 30,
"~:width": 120,
"~:height": 54,
"~:rotation": 0,
"~:r1": 0,
"~:r2": 0,
"~:r3": 0,
"~:r4": 0,
"~:parent-id": "~u00000000-0000-0000-0000-000000000000",
"~:frame-id": "~u00000000-0000-0000-0000-000000000000",
"~:transform": {
"~#matrix": { "~:a": 1.0, "~:b": 0.0, "~:c": 0.0, "~:d": 1.0, "~:e": 0.0, "~:f": 0.0 }
},
"~:transform-inverse": {
"~#matrix": { "~:a": 1.0, "~:b": 0.0, "~:c": 0.0, "~:d": 1.0, "~:e": 0.0, "~:f": 0.0 }
},
"~:selrect": {
"~#rect": {
"~:x": 40, "~:y": 30, "~:width": 120, "~:height": 54,
"~:x1": 40, "~:y1": 30, "~:x2": 160, "~:y2": 84
}
},
"~:points": [
{ "~#point": { "~:x": 40, "~:y": 30 } },
{ "~#point": { "~:x": 160, "~:y": 30 } },
{ "~#point": { "~:x": 160, "~:y": 84 } },
{ "~#point": { "~:x": 40, "~:y": 84 } }
],
"~:fills": [{ "~:fill-color": "#B1B2B5", "~:fill-opacity": 1 }],
"~:strokes": []
}
}
}
}

View File

@ -0,0 +1,43 @@
{
"~:entries": [
{
"~:id": "~uc7ce0794-0992-8105-8004-38f280443a01",
"~:page-id": "~uc7ce0794-0992-8105-8004-38f280443a02",
"~:name": "Checkout button",
"~:type": "~:rect",
"~:frame-id": "~u00000000-0000-0000-0000-000000000000",
"~:frame-name": null,
"~:kind": "~:modified",
"~:attrs": {},
"~:profile-id": "~uc7ce0794-0992-8105-8004-38e630f29a9c",
"~:changed-at": "~m1713873823633"
}
],
"~:sessions": [
{
"~:profile-id": "~uc7ce0794-0992-8105-8004-38e630f29a9c",
"~:start": "~m1713873000000",
"~:end": "~m1713873823633",
"~:revn": 7,
"~:entries": [
{
"~:id": "~uc7ce0794-0992-8105-8004-38f280443a01",
"~:page-id": "~uc7ce0794-0992-8105-8004-38f280443a02",
"~:name": "Checkout button",
"~:type": "~:rect",
"~:frame-id": "~u00000000-0000-0000-0000-000000000000",
"~:frame-name": null,
"~:kind": "~:modified",
"~:attrs": {},
"~:profile-id": "~uc7ce0794-0992-8105-8004-38e630f29a9c",
"~:changed-at": "~m1713873823633"
}
]
}
],
"~:people": 1,
"~:last-save": {
"~:created-at": "~m1713873823633",
"~:profile-id": "~uc7ce0794-0992-8105-8004-38e630f29a9c"
}
}

View File

@ -305,3 +305,39 @@ test("on a branch, the all-branches dialog offers no new branch", async ({
// branches only grow from main: the button stays, disabled
await expect(page.getByRole("button", { name: "New branch" })).toBeDisabled();
});
test("a card of the activity draws the layer as its sitting left it", async ({
page,
}) => {
const workspacePage = new WorkspacePage(page);
await setupBranchReview(workspacePage);
await workspacePage.mockRPCs({
"get-branch-review-activity?id=*":
"branch-reviews/get-branch-review-activity.json",
"get-branch-layer-at-revision?*":
"branch-reviews/get-branch-layer-at-revision-approximate.json",
});
const layerRequest = page.waitForRequest(/get-branch-layer-at-revision/);
await workspacePage.goToWorkspace({ extraParams: `&pr-id=${PR_ID}` });
await reviewBar(page).getByRole("button", { name: "Details" }).click();
const dialog = page.getByRole("dialog");
await dialog.getByRole("tab", { name: "Activity (1)" }).click();
// the layer is not in the open file: the card draws the one the
// command rebuilt at the revision of the sitting
await dialog.getByText("Checkout button").hover();
const request = await layerRequest;
const params = new URL(request.url()).searchParams;
expect(params.get("revn")).toBe("7");
expect(params.get("branch-id")).toBe(
"c7ce0794-0992-8105-8004-38f280443998",
);
const card = page.getByRole("tooltip");
await expect(card.locator('svg[viewBox="40 30 120 54"]')).toBeVisible();
// the branch no longer keeps that save, so the card says it shows the
// layer as it is now
await expect(card.getByText("Shown as it is now")).toBeVisible();
});

View File

@ -288,7 +288,8 @@
(ptk/reify ::exit-branch-review-preview
ptk/UpdateEvent
(update [_ state]
(dissoc state :workspace-pr-preview :workspace-review-local :workspace-review-activity))
(dissoc state :workspace-pr-preview :workspace-review-local :workspace-review-activity
:workspace-review-layers))
ptk/WatchEvent
(watch [_ state _]

View File

@ -14,7 +14,9 @@
`:workspace-review-local` keeps the tool in use, the tab and filters of
the review panel and the change shown on the canvas;
`:workspace-review-activity` the activity of the review, folded by the
backend from the saves of the branch since the review opened."
backend from the saves of the branch since the review opened;
`:workspace-review-layers` the layers the cards of that activity draw,
each as the save of its sitting left it."
(:require
[app.common.geom.point :as gpt]
[app.common.uuid :as uuid]
@ -230,6 +232,48 @@
(assoc state :workspace-review-activity
{:pr-id pr-id :status :error})))))))))
;; --- Layers as a sitting left them
(defn layer-key
"The key a layer drawn at a revision of the branch is cached under:
the review, the revision and the layer."
[pr-id revn shape-id]
[pr-id revn shape-id])
(defn- set-layer
[cache-key value]
(ptk/reify ::set-layer
ptk/UpdateEvent
(update [_ state]
(assoc-in state [:workspace-review-layers cache-key] value))))
(defn fetch-layer-at-revision
"Load the layer `shape-id` of the page `page-id` as the save of the
revision `revn` of the branch `branch-id` (the `file_branch` row) left
it, for the cards of the review `pr-id`. A layer is asked once: a key
already loading, loaded or failed is not asked again, and a failure
leaves the card on the workspace drawing."
[{:keys [pr-id branch-id revn page-id shape-id]}]
(assert (uuid? pr-id) "expected a valid uuid for `pr-id`")
(assert (uuid? branch-id) "expected a valid uuid for `branch-id`")
(assert (int? revn) "expected an integer `revn`")
(assert (uuid? page-id) "expected a valid uuid for `page-id`")
(assert (uuid? shape-id) "expected a valid uuid for `shape-id`")
(ptk/reify ::fetch-layer-at-revision
ptk/WatchEvent
(watch [_ state _]
(let [cache-key (layer-key pr-id revn shape-id)]
(if (contains? (:workspace-review-layers state) cache-key)
(rx/empty)
(rx/concat
(rx/of (set-layer cache-key {:status :loading}))
(->> (rp/cmd! :get-branch-layer-at-revision {:branch-id branch-id
:revn revn
:page-id page-id
:shape-id shape-id})
(rx/map #(set-layer cache-key {:status :loaded :layer %}))
(rx/catch (fn [_] (rx/of (set-layer cache-key {:status :error})))))))))))
;; --- Details
(defn open-details
@ -341,4 +385,4 @@
(ptk/reify ::reset-review-local
ptk/UpdateEvent
(update [_ state]
(dissoc state :workspace-review-local :workspace-review-activity))))
(dissoc state :workspace-review-local :workspace-review-activity :workspace-review-layers))))

View File

@ -90,6 +90,11 @@
(def review-activity
(l/derived :workspace-review-activity st/state))
(def review-layers
"The layers the activity cards draw as their sitting left them, by
`app.main.data.workspace.review/layer-key`."
(l/derived :workspace-review-layers st/state))
(def pending-reviews
;; dashboard: open branch reviews awaiting the current profile's review
(l/derived #(get % :dashboard-pending-reviews) st/state))

View File

@ -304,27 +304,73 @@
#js {:left (dm/str x "px")
:top (dm/str (max gap y) "px")}))
(defn- card-layer
"What the card of `entry` draws: the layer as the save of its sitting
left it, from `fetched` (a `get-branch-layer-at-revision` result) when
that holds the layer, even a layer the sitting deleted; otherwise the
layer as the workspace `objects` have it now, and nothing for a deleted
layer. Returns `{:shape :objects :approximate}` or nil."
[entry objects fetched]
(let [id (:id entry)
saved (:objects fetched)
shape (get saved id)
now (get objects id)]
(cond
(some? shape)
{:shape shape :objects saved :approximate (true? (:approximate fetched))}
(and (some? now) (not= :deleted (:kind entry)))
{:shape now :objects objects :approximate false})))
(mf/defc card-preview*
"The drawing of the layer of a card (`card-layer`), marked when the
branch no longer keeps the save of its sitting and the drawing is the
layer as it is now."
{::mf/private true}
[{:keys [layer]}]
[:*
[:div {:class (stl/css :change-card-preview)}
(if (some? layer)
[:> shape-preview* {:shape (:shape layer) :objects (:objects layer)}]
[:div {:class (stl/css :deleted-preview)}])]
(when (:approximate layer)
[:> text* {:as "span" :typography t/body-small :class (stl/css :muted)}
(tr "workspace.review.activity.drawn-as-now")])])
(mf/defc change-card*
"What a change did, beside its row. It goes in a portal so the scroll of
the dialog never cuts it."
the dialog never cuts it. The layer is drawn as the save of the sitting
`revn` left it, once fetched; until then, or when it cannot be, as the
workspace has it now."
{::mf/private true}
[{:keys [entry tasks rect]}]
(let [profiles (mf/deref refs/profiles)
data (mf/deref refs/workspace-data)
objects (dm/get-in data [:pages-index (:page-id entry) :objects])
shape (get objects (:id entry))
attrs (:attrs entry)
tokens (:applied-tokens attrs)
linked (filterv #(= (:id entry) (:shape-id %)) tasks)]
[{:keys [pr revn entry tasks rect]}]
(let [profiles (mf/deref refs/profiles)
data (mf/deref refs/workspace-data)
layers (mf/deref refs/review-layers)
objects (dm/get-in data [:pages-index (:page-id entry) :objects])
pr-id (:id pr)
branch-id (:file-branch-id pr)
cache-key (dwrv/layer-key pr-id revn (:id entry))
fetched (when (= :loaded (dm/get-in layers [cache-key :status]))
(dm/get-in layers [cache-key :layer]))
layer (card-layer entry objects fetched)
attrs (:attrs entry)
tokens (:applied-tokens attrs)
linked (filterv #(= (:id entry) (:shape-id %)) tasks)]
(mf/with-effect [cache-key branch-id]
(when (and (some? revn) (uuid? branch-id))
(st/emit! (dwrv/fetch-layer-at-revision {:pr-id pr-id
:branch-id branch-id
:revn revn
:page-id (:page-id entry)
:shape-id (:id entry)}))))
[:div {:class (stl/css :change-card) :role "tooltip" :style (card-style rect)}
[:div {:class (stl/css :change-card-head)}
[:> text* {:as "span" :typography t/body-small :class (stl/css :strong)} (:name entry)]
[:> tag* {:tone (kind-tone (:kind entry))} (rvc/change-kind-label (:kind entry))]]
[:div {:class (stl/css :change-card-preview)}
(if (and (some? shape) (not= :deleted (:kind entry)))
[:> shape-preview* {:shape shape :objects objects}]
[:div {:class (stl/css :deleted-preview)}])]
[:> card-preview* {:layer layer}]
(when (seq attrs)
[:dl {:class (stl/css :attrs)}
(for [[attr diff] (dissoc attrs :applied-tokens :parent-id)]
@ -364,7 +410,7 @@
"One change of a group: a click shows it on the canvas, and hovering it
shows what it did."
{::mf/private true}
[{:keys [entry tasks portal]}]
[{:keys [pr revn entry tasks portal]}]
(let [id (:id entry)
tone (kind-tone (:kind entry))
rect* (mf/use-state nil)
@ -386,12 +432,12 @@
:on-click on-show}]
(when (some? rect)
(mf/portal
(mf/html [:> change-card* {:entry entry :tasks tasks :rect rect}])
(mf/html [:> change-card* {:pr pr :revn revn :entry entry :tasks tasks :rect rect}])
portal))]))
(mf/defc change-group*
{::mf/private true}
[{:keys [session tasks is-open]}]
[{:keys [pr session tasks is-open]}]
(let [profiles (mf/deref refs/profiles)
open* (mf/use-state is-open)
open? (deref open*)
@ -422,6 +468,8 @@
[:ul {:class (stl/css :change-rows)}
(for [entry shown]
[:> change-item* {:key (dm/str (:id entry))
:pr pr
:revn (:revn session)
:entry entry
:tasks tasks
:portal portal}])
@ -433,7 +481,7 @@
(mf/defc day-group*
"The changes of one day: only the group of its last session opens."
{::mf/private true}
[{:keys [sessions tasks]}]
[{:keys [pr sessions tasks]}]
(let [sessions (mf/with-memo [sessions]
(into [] d/xf:add-index sessions))]
[:section {:class (stl/css :section)}
@ -441,6 +489,7 @@
(day-label (:end (first sessions)))]
(for [session sessions]
[:> change-group* {:key (dm/str (inst-ms (:start session)) (:profile-id session))
:pr pr
:session session
:tasks tasks
:is-open (zero? (::d/index session))}])]))
@ -497,6 +546,7 @@
:text (tr "workspace.review.activity.empty")}]
(for [day by-day]
[:> day-group* {:key (day-label (:end (first day)))
:pr pr
:sessions day
:tasks tasks}]))

View File

@ -6,17 +6,30 @@
(ns frontend-tests.ui.review-details-test
(:require
["react-dom/server" :as rds]
[app.common.types.shape :as cts]
[app.common.uuid :as uuid]
[app.main.data.workspace.review :as dwrv]
[app.main.repo :as rp]
[app.main.ui.workspace.review.common :as rvc]
[app.main.ui.workspace.review.details :as details]
[app.util.i18n :as i18n]
[beicon.v2.core :as rx]
[cljs.test :as t :include-macros true]
[potok.v2.core :as ptk]))
[cuerdas.core :as str]
[frontend-tests.helpers.async :as async]
[frontend-tests.helpers.mock :as mock]
[potok.v2.core :as ptk]
[rumext.v2 :as mf]))
(def ^:private display-attr @#'details/display-attr)
(def ^:private activity-fetched @#'dwrv/activity-fetched)
(def ^:private card-layer @#'details/card-layer)
(def ^:private card-preview* @#'details/card-preview*)
(t/deftest a-fill-without-tokens-shows-its-value
(let [fill-a [{:fill-color "#ff0000" :fill-opacity 1}]
fill-b [{:fill-color "#00ff00" :fill-opacity 1}]
@ -70,3 +83,85 @@
(t/is (= [session] (:sessions activity)))
(t/is (= 2 (:people activity)))
(t/is (= last-save (:last-save activity)))))
;; --- Cards drawn as their sitting left the layer
(defn- rect
[id x]
(cts/setup-shape {:id id :type :rect :name "Card" :x x :y 20 :width 100 :height 50}))
(defn- render-card-preview
"Markup of the drawing of a card for `layer` (`card-layer`), with each
translation shown as its key."
[layer]
;; multi-arity stub: the call site dispatches on the arity-1 property
(with-redefs [i18n/tr (fn ([msgid] msgid) ([msgid & _] msgid))]
(rds/renderToStaticMarkup
(mf/element card-preview* #js {:layer layer}))))
(t/deftest a-card-draws-the-layer-as-its-sitting-left-it
(let [id (uuid/random)
entry {:id id :page-id (uuid/random) :kind :modified}
now {id (rect id 500)}
saved {id (rect id 10)}
layer (card-layer entry now {:revn 3 :objects saved :approximate false :deleted false})
markup (render-card-preview layer)]
(t/is (= (get saved id) (:shape layer)))
(t/is (str/includes? markup "viewBox=\"10 20 100 50\""))
(t/is (not (str/includes? markup "viewBox=\"500 20 100 50\"")))
(t/is (not (str/includes? markup "workspace.review.activity.drawn-as-now")))))
(t/deftest a-card-without-a-fetched-layer-draws-the-workspace-one
(let [id (uuid/random)
entry {:id id :page-id (uuid/random) :kind :modified}
now {id (rect id 500)}]
(t/is (= (get now id) (:shape (card-layer entry now nil))))
(t/is (= (get now id) (:shape (card-layer entry now {:revn 3 :objects {}}))))))
(t/deftest an-approximate-card-carries-its-marker
(let [id (uuid/random)
entry {:id id :page-id (uuid/random) :kind :modified}
now {id (rect id 10)}
layer (card-layer entry now {:revn 1 :objects now :approximate true :deleted false})
markup (render-card-preview layer)]
(t/is (true? (:approximate layer)))
(t/is (str/includes? markup "workspace.review.activity.drawn-as-now"))))
(t/deftest a-deleted-layer-card-draws-the-fetched-layer
(let [id (uuid/random)
entry {:id id :page-id (uuid/random) :kind :deleted}
saved {id (rect id 10)}
layer (card-layer entry {} {:revn 4 :objects saved :approximate false :deleted true})
markup (render-card-preview layer)]
(t/is (nil? (card-layer entry {} nil)))
(t/is (= (get saved id) (:shape layer)))
(t/is (str/includes? markup "viewBox=\"10 20 100 50\""))))
(t/deftest ^:async a-layer-at-a-revision-is-asked-once
(let [calls (atom [])
pr-id (uuid/random)
params {:pr-id pr-id
:branch-id (uuid/random)
:revn 3
:page-id (uuid/random)
:shape-id (uuid/random)}
result {:revn 3 :objects {} :approximate false :deleted false}
cache-key (dwrv/layer-key pr-id 3 (:shape-id params))
events (atom [])]
(await
(mock/with-mocks*
{rp/cmd! (mock/stub
(fn [cmd cmd-params]
(swap! calls conj [cmd cmd-params])
(rx/of result)))}
(await (async/observe (ptk/watch (dwrv/fetch-layer-at-revision params) {} nil)
:on-next #(swap! events conj %)))))
(let [state (reduce #(ptk/update %2 %1) {} @events)]
(t/is (= [[:get-branch-layer-at-revision (dissoc params :pr-id)]] @calls))
(t/is (= {:status :loaded :layer result}
(get-in state [:workspace-review-layers cache-key])))
(t/is (= :empty
(let [seen (atom :empty)]
(->> (ptk/watch (dwrv/fetch-layer-at-revision params) state nil)
(rx/subs! #(reset! seen %)))
@seen))))))

View File

@ -11919,6 +11919,10 @@ msgstr "All"
msgid "workspace.review.activity.click-to-show"
msgstr "Click to show it on the canvas"
#: src/app/main/ui/workspace/review/details.cljs
msgid "workspace.review.activity.drawn-as-now"
msgstr "Shown as it is now"
#: src/app/main/ui/workspace/review/details.cljs
msgid "workspace.review.activity.empty"
msgstr "Nothing has changed since the review opened."

View File

@ -12071,6 +12071,10 @@ msgstr "Todo"
msgid "workspace.review.activity.click-to-show"
msgstr "Haz clic para verlo en el lienzo"
#: src/app/main/ui/workspace/review/details.cljs
msgid "workspace.review.activity.drawn-as-now"
msgstr "Se muestra como está ahora"
#: src/app/main/ui/workspace/review/details.cljs
msgid "workspace.review.activity.empty"
msgstr "No ha cambiado nada desde que se abrió la revisión."