diff --git a/backend/resources/app/email/task-assigned/en.html b/backend/resources/app/email/task-assigned/en.html new file mode 100644 index 0000000000..cae7a077f1 --- /dev/null +++ b/backend/resources/app/email/task-assigned/en.html @@ -0,0 +1,244 @@ + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + +
+ +
+ + + + +
+ + + + + + +
+ +
+
+
+ +
+
+ +
+ + + + + + +
+ +
+ + + + + + + + + + + + + + + + +
+
+ Hello {{name|abbreviate:25}}!
+
+
+ {{ source-user }} assigned you a task:
+
+
+ {{ task-title }} +
+
+ + + + +
+ OPEN THE TASK +
+
+
+ The Penpot team.
+
+
+ +
+
+ + {% include "app/email/includes/footer.html" %} + +
+ + + diff --git a/backend/resources/app/email/task-assigned/en.subj b/backend/resources/app/email/task-assigned/en.subj new file mode 100644 index 0000000000..b474c10057 --- /dev/null +++ b/backend/resources/app/email/task-assigned/en.subj @@ -0,0 +1 @@ +You have a new task diff --git a/backend/resources/app/email/task-assigned/en.txt b/backend/resources/app/email/task-assigned/en.txt new file mode 100644 index 0000000000..20f449589a --- /dev/null +++ b/backend/resources/app/email/task-assigned/en.txt @@ -0,0 +1,9 @@ +Hello {{name|abbreviate:25}}! + +{{ source-user }} assigned you a task: + +{{ task-title }} + +{{ task-url }} + +The Penpot team. diff --git a/backend/resources/app/email/tasks-moved/en.html b/backend/resources/app/email/tasks-moved/en.html new file mode 100644 index 0000000000..02665f6458 --- /dev/null +++ b/backend/resources/app/email/tasks-moved/en.html @@ -0,0 +1,244 @@ + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + +
+ +
+ + + + +
+ + + + + + +
+ +
+
+
+ +
+
+ +
+ + + + + + +
+ +
+ + + + + + + + + + + + + + + + +
+
+ Hello {{name|abbreviate:25}}!
+
+
+ {{ source-user }} merged the branch "{{ branch-name }}" into "{{ file-name }}". Your open tasks moved to main as they were:
+
+
+ {{ task-titles }} +
+
+ + + + +
+ OPEN THE FILE +
+
+
+ The Penpot team.
+
+
+ +
+
+ + {% include "app/email/includes/footer.html" %} + +
+ + + diff --git a/backend/resources/app/email/tasks-moved/en.subj b/backend/resources/app/email/tasks-moved/en.subj new file mode 100644 index 0000000000..1c1f080367 --- /dev/null +++ b/backend/resources/app/email/tasks-moved/en.subj @@ -0,0 +1 @@ +Your tasks moved to main diff --git a/backend/resources/app/email/tasks-moved/en.txt b/backend/resources/app/email/tasks-moved/en.txt new file mode 100644 index 0000000000..bacdadd883 --- /dev/null +++ b/backend/resources/app/email/tasks-moved/en.txt @@ -0,0 +1,9 @@ +Hello {{name|abbreviate:25}}! + +{{ source-user }} merged the branch "{{ branch-name }}" into "{{ file-name }}". Your open tasks moved to main as they were: + +{{ task-titles }} + +{{ file-url }} + +The Penpot team. diff --git a/backend/src/app/email.clj b/backend/src/app/email.clj index 3cc78ec02b..c19bda23be 100644 --- a/backend/src/app/email.clj +++ b/backend/src/app/email.clj @@ -577,6 +577,35 @@ :id ::review-request :schema schema:review-request)) +(def ^:private schema:task-assigned + [:map + [:name ::sm/text] + [:source-user ::sm/text] + [:task-title ::sm/text] + [:task-url ::sm/text]]) + +(def task-assigned + "Email sent to the person a task is assigned to." + (template-factory + :id ::task-assigned + :schema schema:task-assigned)) + +(def ^:private schema:tasks-moved + [:map + [:name ::sm/text] + [:source-user ::sm/text] + [:branch-name ::sm/text] + [:file-name ::sm/text] + [:task-titles ::sm/text] + [:file-url ::sm/text]]) + +(def tasks-moved + "Email sent to the assignees of the open tasks of a branch when the + merge of the branch moves them into main." + (template-factory + :id ::tasks-moved + :schema schema:tasks-moved)) + (def ^:private schema:comment-mention [:map [:name ::sm/text] @@ -656,7 +685,9 @@ "comment-mention" (template-entry comment-mention schema:comment-mention) "comment-thread" (template-entry comment-thread schema:comment-thread) "comment-notification" (template-entry comment-notification schema:comment-notification) - "review-request" (template-entry review-request schema:review-request)}) + "review-request" (template-entry review-request schema:review-request) + "task-assigned" (template-entry task-assigned schema:task-assigned) + "tasks-moved" (template-entry tasks-moved schema:tasks-moved)}) (defn render-template "Render the templated email `template-id` from its JSON-decoded data, diff --git a/backend/src/app/migrations.clj b/backend/src/app/migrations.clj index dfe36c2503..0f68a807f9 100644 --- a/backend/src/app/migrations.clj +++ b/backend/src/app/migrations.clj @@ -566,7 +566,25 @@ :fn (mg/resource "app/migrations/sql/0807-del-file-branch-profile-rels.sql")} {:name "0808-mod-file-branch-project" - :fn (mg/resource "app/migrations/sql/0808-mod-file-branch-project.sql")}]) + :fn (mg/resource "app/migrations/sql/0808-mod-file-branch-project.sql")} + + {:name "0809-mod-comment-thread-add-review-fields" + :fn (mg/resource "app/migrations/sql/0809-mod-comment-thread-add-review-fields.sql")} + + {:name "0810-add-file-task-tables" + :fn (mg/resource "app/migrations/sql/0810-add-file-task-tables.sql")} + + {:name "0811-add-file-pull-request-activity-table" + :fn (mg/resource "app/migrations/sql/0811-add-file-pull-request-activity-table.sql")} + + {:name "0812-mod-file-task-add-position" + :fn (mg/resource "app/migrations/sql/0812-mod-file-task-add-position.sql")} + + {:name "0813-mod-file-task-add-comment" + :fn (mg/resource "app/migrations/sql/0813-mod-file-task-add-comment.sql")} + + {:name "0814-mod-file-task-give-thread" + :fn (mg/resource "app/migrations/sql/0814-mod-file-task-give-thread.sql")}]) (defn apply-migrations! [pool name migrations] diff --git a/backend/src/app/migrations/sql/0809-mod-comment-thread-add-review-fields.sql b/backend/src/app/migrations/sql/0809-mod-comment-thread-add-review-fields.sql new file mode 100644 index 0000000000..554409f812 --- /dev/null +++ b/backend/src/app/migrations/sql/0809-mod-comment-thread-add-review-fields.sql @@ -0,0 +1,27 @@ +-- A comment thread can belong to a design review (a pull request) and can +-- point at more than a spot of the canvas. +-- +-- `pull_request_id` names the design review the thread was written in. +-- It carries no foreign key: the merge of a branch moves the threads of +-- its tasks into main (`files_task.clj::move-branch-tasks!`) and the +-- objects GC later deletes the branch file, which takes the pull request +-- row with it. The thread keeps saying it came from a review. +-- +-- `anchor_type` says what the thread points at: +-- * `canvas`: a spot of a board, as every thread did before (`position` +-- and `frame_id`); +-- * `layer`: a layer, named by `shape_id`; `position` is where it was, +-- the fallback when the layer goes away; +-- * `area`: a rectangle of a board, `area` holds its `x`, `y`, `width` +-- and `height` in canvas coordinates. + +ALTER TABLE comment_thread + ADD COLUMN pull_request_id uuid NULL, + ADD COLUMN anchor_type text NOT NULL DEFAULT 'canvas' + CHECK (anchor_type IN ('canvas', 'layer', 'area')), + ADD COLUMN shape_id uuid NULL, + ADD COLUMN area jsonb NULL; + +CREATE INDEX comment_thread__pull_request_id__idx + ON comment_thread(pull_request_id) + WHERE pull_request_id IS NOT NULL; diff --git a/backend/src/app/migrations/sql/0810-add-file-task-tables.sql b/backend/src/app/migrations/sql/0810-add-file-task-tables.sql new file mode 100644 index 0000000000..ff4be42c8e --- /dev/null +++ b/backend/src/app/migrations/sql/0810-add-file-task-tables.sql @@ -0,0 +1,104 @@ +-- Tasks: a piece of work on a file, assigned to someone and tied to a +-- layer. A task is born open, its assignee marks it done, someone +-- verifies it (or reopens it), and it may be dropped as "won't do": +-- +-- open -> done -> verified +-- done | verified | wont-do -> reopened -> done +-- open | reopened -> wont-do +-- +-- Anyone who can read the file may move a task between states; every +-- move is recorded in `file_task_event` with who made it. +-- +-- A task may come from a comment thread (`thread_id`, the thread stays +-- attached to it) and from a design review (`pull_request_id`). Neither +-- column has a foreign key to the pull request: the merge of a branch +-- moves its tasks into main and the objects GC later deletes the branch +-- file and its pull request rows. The task keeps the names it shows +-- (`review_title`, `branch_name`) and the merge that moved it +-- (`merge_id`, a `file_branch_merge` row), so the tasks of a merged +-- branch remain as its history. +-- +-- `shape_id` is the layer the task points at, inside `frame_id` on +-- `page_id`. When that layer is deleted the task moves to the board +-- that held it and keeps the name of the lost layer in +-- `lost_shape_name`, until it is linked to another layer. + +CREATE TABLE file_task ( + id uuid PRIMARY KEY, + + file_id uuid NOT NULL REFERENCES file(id) ON DELETE CASCADE DEFERRABLE, + + pull_request_id uuid NULL, + review_title text NULL, + thread_id uuid NULL REFERENCES comment_thread(id) ON DELETE SET NULL DEFERRABLE, + + title text NOT NULL, + status text NOT NULL DEFAULT 'open' + CHECK (status IN ('open', 'done', 'reopened', 'verified', 'wont-do')), + + assignee_id uuid NULL REFERENCES profile(id) ON DELETE SET NULL DEFERRABLE, + created_by uuid NULL REFERENCES profile(id) ON DELETE SET NULL DEFERRABLE, + + page_id uuid NOT NULL, + frame_id uuid NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'::uuid, + shape_id uuid NULL, + lost_shape_name text NULL, + + merge_id uuid NULL, + branch_name text NULL, + + status_changed_at timestamptz NULL, + status_changed_by uuid NULL REFERENCES profile(id) ON DELETE SET NULL DEFERRABLE, + + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + updated_at timestamptz NOT NULL DEFAULT clock_timestamp(), + deleted_at timestamptz NULL +); + +CREATE INDEX file_task__file_id__idx + ON file_task(file_id) WHERE deleted_at IS NULL; + +CREATE INDEX file_task__pull_request_id__idx + ON file_task(pull_request_id) WHERE pull_request_id IS NOT NULL; + +CREATE INDEX file_task__thread_id__idx + ON file_task(thread_id) WHERE thread_id IS NOT NULL; + +CREATE INDEX file_task__assignee_id__idx + ON file_task(assignee_id); + +CREATE INDEX file_task__created_by__idx + ON file_task(created_by); + +CREATE INDEX file_task__status_changed_by__idx + ON file_task(status_changed_by); + +CREATE INDEX file_task__merge_id__idx + ON file_task(merge_id) WHERE merge_id IS NOT NULL; + +-- What happened to a task, in order: the lines a thread shows between its +-- comments ("Ana made this a task for you", "Marc marked it as done"). +-- +-- created {} +-- assigned {:assignee-id} +-- status {:from :to} +-- renamed {:title} +-- relinked {:shape-id :shape-name} +-- layer-deleted {:shape-id :shape-name :frame-id :frame-name :objects} +-- layer-restored {:shape-id :shape-name} +-- moved-to-main {:merge-id :branch-name} + +CREATE TABLE file_task_event ( + id uuid PRIMARY KEY, + task_id uuid NOT NULL REFERENCES file_task(id) ON DELETE CASCADE DEFERRABLE, + profile_id uuid NULL REFERENCES profile(id) ON DELETE SET NULL DEFERRABLE, + type text NOT NULL, + payload jsonb NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); + +CREATE INDEX file_task_event__task_id__idx + ON file_task_event(task_id, created_at); + +CREATE INDEX file_task_event__profile_id__idx + ON file_task_event(profile_id); diff --git a/backend/src/app/migrations/sql/0811-add-file-pull-request-activity-table.sql b/backend/src/app/migrations/sql/0811-add-file-pull-request-activity-table.sql new file mode 100644 index 0000000000..eb78b62b79 --- /dev/null +++ b/backend/src/app/migrations/sql/0811-add-file-pull-request-activity-table.sql @@ -0,0 +1,39 @@ +-- The activity of a design review: one row per save of its branch while +-- the review is open, with who saved and what the save did to each +-- layer it touched. +-- +-- The branch op log (`file_branch_change`) cannot answer that: it keeps +-- no author and an update from main squashes it into one row. This table +-- is written by the branch save alone (`files_update.clj`), so the work +-- an update brings in from main never counts as anybody's change. +-- +-- `entries` is a blob-encoded vector, one map per touched layer +-- (`app.common.files.review-activity/entries`): its id, page, board, +-- name and type, the kind of change (`:added`, `:modified`, +-- `:deleted`) and, for a modified layer, the value before and after of +-- each property a person reads. + +CREATE TABLE file_pull_request_activity ( + id uuid PRIMARY KEY, + + pull_request_id uuid NOT NULL REFERENCES file_pull_request(id) ON DELETE CASCADE DEFERRABLE, + profile_id uuid NULL REFERENCES profile(id) ON DELETE SET NULL DEFERRABLE, + + -- the branch file's revn the save produced + revn bigint NOT NULL, + entries bytea NOT NULL, + + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); + +CREATE INDEX file_pull_request_activity__pull_request_id__idx + ON file_pull_request_activity(pull_request_id, created_at); + +CREATE INDEX file_pull_request_activity__profile_id__idx + ON file_pull_request_activity(profile_id); + +-- A branch save asks whether its branch is under review: find the open +-- pull request by its source (the branch file). +CREATE INDEX file_pull_request__source_file_id__open__idx + ON file_pull_request(source_file_id) + WHERE status = 'open' AND deleted_at IS NULL; diff --git a/backend/src/app/migrations/sql/0812-mod-file-task-add-position.sql b/backend/src/app/migrations/sql/0812-mod-file-task-add-position.sql new file mode 100644 index 0000000000..3a263d2929 --- /dev/null +++ b/backend/src/app/migrations/sql/0812-mod-file-task-add-position.sql @@ -0,0 +1,7 @@ +-- Where the mark of a task goes when it points at no layer: a task on the +-- canvas itself, or one made from a comment thread on the canvas. A task +-- on a layer keeps the spot too, as the fallback when the layer and its +-- board are gone. + +ALTER TABLE file_task + ADD COLUMN position point NULL; diff --git a/backend/src/app/migrations/sql/0813-mod-file-task-add-comment.sql b/backend/src/app/migrations/sql/0813-mod-file-task-add-comment.sql new file mode 100644 index 0000000000..66b1e60802 --- /dev/null +++ b/backend/src/app/migrations/sql/0813-mod-file-task-add-comment.sql @@ -0,0 +1,20 @@ +-- The message of a comment thread a task comes from: each message may be +-- a task, so a thread may hold several. A task has no message when it +-- comes from no thread or when its message was deleted; it then keeps its +-- thread. + +ALTER TABLE file_task + ADD COLUMN comment_id uuid NULL REFERENCES comment(id) ON DELETE SET NULL DEFERRABLE; + +CREATE INDEX file_task__comment_id__idx + ON file_task(comment_id) WHERE comment_id IS NOT NULL; + +-- Until now a task came from a whole thread, with the title of its first +-- message. +UPDATE file_task AS t + SET comment_id = (SELECT c.id + FROM comment AS c + WHERE c.thread_id = t.thread_id + ORDER BY c.created_at ASC + LIMIT 1) + WHERE t.thread_id IS NOT NULL; diff --git a/backend/src/app/migrations/sql/0814-mod-file-task-give-thread.sql b/backend/src/app/migrations/sql/0814-mod-file-task-give-thread.sql new file mode 100644 index 0000000000..fdfd492dbb --- /dev/null +++ b/backend/src/app/migrations/sql/0814-mod-file-task-give-thread.sql @@ -0,0 +1,63 @@ +-- Every task lives in a message of a comment thread, so its thread can go +-- on: a task created on the canvas gets a thread whose first message is +-- its title, as if it had been a comment turned into a task. +-- +-- Until now such a task had no thread. Give one to each of them: the +-- thread points at the layer of the task (at its spot of the canvas when +-- it has none), belongs to its design review and takes the next number of +-- its file. A task whose author is gone keeps no thread: a thread needs an +-- owner. The spot of a task on a layer was optional; the thread falls back +-- to the origin of the canvas, and its mark follows the layer anyway. + +CREATE TEMPORARY TABLE task_thread ON COMMIT DROP AS +SELECT t.id AS task_id, + gen_random_uuid() AS thread_id, + gen_random_uuid() AS comment_id, + t.file_id, + t.created_by, + t.page_id, + t.frame_id, + t.shape_id, + t.pull_request_id, + t.title, + t.created_at, + coalesce(t.position, point(0, 0)) AS position, + f.comment_thread_seqn + + row_number() OVER (PARTITION BY t.file_id ORDER BY t.created_at) AS seqn + FROM file_task AS t + JOIN file AS f ON (f.id = t.file_id) + WHERE t.thread_id IS NULL + AND t.created_by IS NOT NULL + AND t.deleted_at IS NULL; + +INSERT INTO comment_thread + (id, file_id, owner_id, created_at, modified_at, page_id, participants, + seqn, position, frame_id, pull_request_id, anchor_type, shape_id) +SELECT thread_id, file_id, created_by, created_at, created_at, page_id, + jsonb_build_object('~#set', jsonb_build_array('~u' || created_by::text)), + seqn, position, frame_id, pull_request_id, + CASE WHEN shape_id IS NULL THEN 'canvas' ELSE 'layer' END, + shape_id + FROM task_thread; + +INSERT INTO comment (id, thread_id, owner_id, created_at, modified_at, content) +SELECT comment_id, thread_id, created_by, created_at, created_at, title + FROM task_thread; + +-- the author has read the thread they wrote +INSERT INTO comment_thread_status (thread_id, profile_id, created_at, modified_at) +SELECT thread_id, created_by, created_at, created_at + FROM task_thread; + +UPDATE file AS f + SET comment_thread_seqn = tt.seqn + FROM (SELECT file_id, max(seqn) AS seqn + FROM task_thread + GROUP BY file_id) AS tt + WHERE f.id = tt.file_id; + +UPDATE file_task AS t + SET thread_id = tt.thread_id, + comment_id = tt.comment_id + FROM task_thread AS tt + WHERE t.id = tt.task_id; diff --git a/backend/src/app/rpc.clj b/backend/src/app/rpc.clj index 86585c2edf..a08538d41c 100644 --- a/backend/src/app/rpc.clj +++ b/backend/src/app/rpc.clj @@ -434,6 +434,7 @@ 'app.rpc.commands.files-snapshot 'app.rpc.commands.files-branch 'app.rpc.commands.files-pull-request + 'app.rpc.commands.files-task 'app.rpc.commands.files-thumbnails 'app.rpc.commands.jobs 'app.rpc.commands.ldap diff --git a/backend/src/app/rpc/commands/comments.clj b/backend/src/app/rpc/commands/comments.clj index a61e1cb3c1..a0103086e5 100644 --- a/backend/src/app/rpc/commands/comments.clj +++ b/backend/src/app/rpc/commands/comments.clj @@ -22,6 +22,7 @@ [app.features.fdata :as feat.fdata] [app.loggers.audit :as-alias audit] [app.loggers.webhooks :as-alias webhooks] + [app.msgbus :as mbus] [app.rpc :as-alias rpc] [app.rpc.commands.files :as files] [app.rpc.commands.profile :as profile] @@ -174,10 +175,12 @@ :comment-url comment-url})))))) (defn- decode-row - [{:keys [participants position mentions] :as row}] + [{:keys [participants position mentions area anchor-type] :as row}] (cond-> row (db/pgpoint? position) (assoc :position (db/decode-pgpoint position)) (db/pgobject? participants) (assoc :participants (db/decode-transit-pgobject participants)) + (db/pgobject? area) (assoc :area (db/decode-transit-pgobject area)) + (string? anchor-type) (assoc :anchor-type (keyword anchor-type)) (db/pgarray? mentions) (assoc :mentions (db/decode-pgarray mentions #{})))) (def xf-decode-row @@ -267,6 +270,8 @@ p.team_id AS team_id, f.name AS file_name, f.project_id AS project_id, + fpr.title AS pull_request_title, + fpr.status AS pull_request_status, first_value(c.content) OVER w AS content, (SELECT count(1) FROM comment AS c @@ -281,6 +286,7 @@ INNER JOIN project AS p ON (p.id = f.project_id) LEFT JOIN comment_thread_status AS cts ON (cts.thread_id = ct.id AND cts.profile_id = ?) LEFT JOIN profile AS pf ON (ct.owner_id = pf.id) + LEFT JOIN file_pull_request AS fpr ON (fpr.id = ct.pull_request_id) WHERE f.deleted_at IS NULL AND p.deleted_at IS NULL %1 @@ -468,10 +474,30 @@ ;; MUTATION COMMANDS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -(declare ^:private create-comment-thread) +(declare ^:private insert-comment-thread) ;; --- COMMAND: Create Comment Thread +(def schema:area + "A rectangle of the canvas a thread points at, in canvas coordinates." + [:map {:title "CommentThreadArea"} + [:x ::sm/safe-number] + [:y ::sm/safe-number] + [:width ::sm/safe-number] + [:height ::sm/safe-number]]) + +(def ^:private schema:anchor + "What a thread points at: a spot of a board (`:canvas`, the default), + a layer or a rectangle." + [:multi {:dispatch :type :title "CommentThreadAnchor"} + [:canvas [:map [:type [:= :canvas]]]] + [:layer [:map + [:type [:= :layer]] + [:shape-id ::sm/uuid]]] + [:area [:map + [:type [:= :area]] + [:area schema:area]]]]) + (def ^:private schema:create-comment-thread [:map {:title "create-comment-thread"} @@ -481,7 +507,28 @@ [:page-id ::sm/uuid] [:frame-id ::sm/uuid] [:share-id {:optional true} [:maybe ::sm/uuid]] - [:mentions {:optional true} [::sm/set ::sm/uuid]]]) + [:mentions {:optional true} [::sm/set ::sm/uuid]] + ;; the design review the thread is written in: an open pull request + ;; of this file (the branch file it reviews) + [:pull-request-id {:optional true} ::sm/uuid] + [:anchor {:optional true} schema:anchor]]) + +(def ^:private sql:get-open-pull-request-of-file + "SELECT id FROM file_pull_request + WHERE id = ? + AND source_file_id = ? + AND status = 'open' + AND deleted_at IS NULL") + +(defn- check-review-of-file + "Refuse a thread for a design review that is not an open review of the + file the thread is written on." + [conn pull-request-id file-id] + (when-not (db/exec-one! conn [sql:get-open-pull-request-of-file pull-request-id file-id]) + (ex/raise :type :validation + :code :pull-request-not-open + :hint "the thread names a design review that is not open on this file" + :pull-request-id pull-request-id))) (defn- update-thread-seqn [conn file-id seqn] @@ -497,6 +544,26 @@ (assoc :owner-email (:email profile)) (assoc :owner-photo-id (:photo-id profile)))) +(defn create-comment-thread + "Create a thread with its first message on the page `page-id` of + `file-id`, once the quotes of threads and comments allow it. It joins + the transaction of `cfg` when there is one: a task created on the canvas + gets its thread this way (`app.rpc.commands.files-task`). The caller + checks the permissions. Returns the thread with the id of its first + message (`:comment-id`)." + [cfg {:keys [::rpc/profile-id file-id page-id] :as params}] + (let [{:keys [team-id project-id] :as file} (get-file cfg file-id page-id)] + (-> cfg + (assoc ::quotes/profile-id profile-id) + (assoc ::quotes/team-id team-id) + (assoc ::quotes/project-id project-id) + (assoc ::quotes/file-id file-id) + (quotes/check! {::quotes/id ::quotes/comment-threads-per-file} + {::quotes/id ::quotes/comments-per-file})) + + (let [thread (db/tx-run! cfg insert-comment-thread (assoc params ::file file))] + (vary-meta thread assoc ::audit/props (assoc thread :team-id team-id))))) + (sv/defmethod ::create-comment-thread {::doc/added "1.15" ::webhooks/event? true @@ -506,24 +573,12 @@ [cfg {:keys [::rpc/profile-id file-id page-id share-id] :as params}] (let [perms (files/check-comment-permissions! cfg profile-id file-id share-id)] (check-page-scope perms page-id) + (create-comment-thread cfg params))) - (let [{:keys [team-id project-id] :as file} (get-file cfg file-id page-id)] - (-> cfg - (assoc ::quotes/profile-id profile-id) - (assoc ::quotes/team-id team-id) - (assoc ::quotes/project-id project-id) - (assoc ::quotes/file-id file-id) - (quotes/check! {::quotes/id ::quotes/comment-threads-per-file} - {::quotes/id ::quotes/comments-per-file})) - - (let [params (assoc params ::file file) - thread (db/tx-run! cfg create-comment-thread params)] - - (vary-meta thread assoc ::audit/props (assoc thread :team-id team-id)))))) - -(defn- create-comment-thread +(defn- insert-comment-thread [{:keys [::db/conn] :as cfg} - {:keys [::rpc/profile-id ::rpc/request-at ::file position content mentions frame-id] :as params}] + {:keys [::rpc/profile-id ::rpc/request-at ::file position content mentions frame-id + pull-request-id anchor]}] (let [;; NOTE: we take the next seq number from a separate query ;; because we need to lock the file for avoid race conditions @@ -534,6 +589,9 @@ ;; different storage (example: redis) for alivate the update ;; pression on the file table + _ (when pull-request-id + (check-review-of-file conn pull-request-id (:id file))) + profile (profile/get-profile conn profile-id) seqn (get-next-seqn conn (:id file)) @@ -552,7 +610,11 @@ :seqn seqn :frame-id frame-id :position (db/pgpoint position) - :mentions (db/encode-pgarray mentions conn "uuid")}) + :mentions (db/encode-pgarray mentions conn "uuid") + :pull-request-id pull-request-id + :anchor-type (d/name (get anchor :type :canvas)) + :shape-id (:shape-id anchor) + :area (some-> (:area anchor) db/tjson)}) (decode-row)) comment (-> (db/insert! conn :comment {:id (uuid/next) @@ -747,7 +809,37 @@ [:id ::sm/uuid] [:share-id {:optional true} [:maybe ::sm/uuid]]]) +;; The thread delete that follows clears `thread_id` and `comment_id` of +;; the task rows through two ON DELETE SET NULL actions, whose order +;; Postgres picks by trigger name. A row this statement already updated +;; gets its FK rechecked by the first of them, and when that is the +;; `thread_id` one, `comment_id` still names a message the cascade has +;; deleted. Clearing both here leaves the delete no referencing row. +(def ^:private sql:delete-thread-tasks + "UPDATE file_task + SET deleted_at = ?, + updated_at = ?, + thread_id = NULL, + comment_id = NULL + WHERE thread_id = ? + AND deleted_at IS NULL") + +(defn- delete-thread-tasks + "Delete the tasks of the thread `thread-id`, which live in its messages, + and tell the open clients of `file-id` once the transaction commits." + [{:keys [::db/conn ::mbus/msgbus]} profile-id file-id thread-id] + (let [ts (ct/now) + result (db/exec-one! conn [sql:delete-thread-tasks ts ts thread-id])] + (when (pos? (db/get-update-count result)) + (db/after-commit + #(mbus/pub! msgbus + :topic file-id + :message {:type :file-tasks-change + :file-id file-id + :profile-id profile-id}))))) + (sv/defmethod ::delete-comment-thread + "Delete a thread with its messages and the tasks they hold." {::doc/added "1.15" ::sm/params schema:delete-comment-thread ::db/transaction true} @@ -763,6 +855,7 @@ (ex/raise :type :validation :code :not-allowed)) + (delete-thread-tasks cfg profile-id file-id id) (db/delete! conn :comment-thread {:id id} {::db/return-keys false}) nil)) diff --git a/backend/src/app/rpc/commands/files_branch.clj b/backend/src/app/rpc/commands/files_branch.clj index 1348e8445c..7af39af58b 100644 --- a/backend/src/app/rpc/commands/files_branch.clj +++ b/backend/src/app/rpc/commands/files_branch.clj @@ -43,6 +43,7 @@ [app.rpc.commands.files :as files] [app.rpc.commands.files-branch-policies :as bp] [app.rpc.commands.files-create :as fcreate] + [app.rpc.commands.files-task :as ftask] [app.rpc.commands.files-update :as fupd] [app.rpc.commands.teams :as teams] [app.rpc.doc :as-alias doc] @@ -499,12 +500,13 @@ `file_branch_merge` migration). The open pull request of the branch is the design review the merge accepts, so it is read here, before the merge closes it. A blank comment is stored as no comment. Must run - inside the merge transaction." + inside the merge transaction. Returns the id of the record." [conn {:keys [id source-file-id name]} {:keys [profile-id comment created-at]}] - (let [pr (db/exec-one! conn [sql:get-open-branch-pull-request id]) - comment (when-not (str/blank? comment) (str/trim comment))] + (let [pr (db/exec-one! conn [sql:get-open-branch-pull-request id]) + comment (when-not (str/blank? comment) (str/trim comment)) + merge-id (uuid/next)] (db/insert! conn :file-branch-merge - {:id (uuid/next) + {:id merge-id :created-at created-at :file-id source-file-id :file-branch-id id @@ -513,7 +515,8 @@ :comment comment :pull-request-id (:id pr) :pull-request-title (:title pr)} - {::db/return-keys false}))) + {::db/return-keys false}) + merge-id)) ;; --- COMMAND: create-file-branch @@ -1092,7 +1095,10 @@ [:expected-main-revn {:optional true} ::sm/int] ;; what the user says about the merge; kept in its record ;; (`file_branch_merge`), shown in the list of merges of main - [:comment {:optional true} [:string {:max 4000}]]]) + [:comment {:optional true} [:string {:max 4000}]] + ;; tell the assignees of the open tasks of the branch, by email, that + ;; the merge moved their tasks into main + [:notify-assignees {:optional true} ::sm/boolean]]) (sv/defmethod ::merge-file-branch "Merge a branch into its source file (main). @@ -1120,7 +1126,8 @@ ::climit/id [[:merge-file-branch/by-profile ::rpc/profile-id] [:merge-file-branch/global]]} [{:keys [::mbus/msgbus] :as cfg} - {:keys [::rpc/profile-id ::rpc/session-id branch-id resolutions expected-main-revn comment excluded]}] + {:keys [::rpc/profile-id ::rpc/session-id branch-id resolutions expected-main-revn comment excluded + notify-assignees]}] (bp/with-policies (check-branching-enabled!) (let [branch (db/get* cfg :file-branch {:id branch-id})] @@ -1219,9 +1226,17 @@ ;; releases the pinned base snapshot. The record is ;; written first: it reads the open pull request the ;; lines below close. - (record-merge! conn branch {:profile-id profile-id - :comment comment - :created-at ts}) + (let [merge-id (record-merge! conn branch {:profile-id profile-id + :comment comment + :created-at ts})] + ;; the tasks of the branch outlive it: the open ones + ;; keep going on main, the closed ones are its history + (ftask/move-branch-tasks cfg {:branch-file-id branch-file-id + :main-id main-id + :merge-id merge-id + :branch-name (:name branch) + :profile-id profile-id + :notify-assignees notify-assignees})) (db/update! conn :file-branch {:status "merged" :merged-at ts diff --git a/backend/src/app/rpc/commands/files_pull_request.clj b/backend/src/app/rpc/commands/files_pull_request.clj index ab1d8e449b..7f54e004dd 100644 --- a/backend/src/app/rpc/commands/files_pull_request.clj +++ b/backend/src/app/rpc/commands/files_pull_request.clj @@ -36,11 +36,13 @@ [app.rpc.climit :as-alias climit] [app.rpc.commands.files :as files] [app.rpc.commands.files-branch :as fbranch] + [app.rpc.commands.files-task :as ftask] [app.rpc.commands.profile :as profile] [app.rpc.commands.teams :as teams] [app.rpc.doc :as-alias doc] [app.rpc.permissions :as perms] [app.rpc.quotes :as quotes] + [app.util.blob :as blob] [app.util.services :as sv] [clojure.string :as str])) @@ -169,9 +171,9 @@ the branches listing uses, so ten open pull requests on one file cost one computation per branch and nothing at all once that panel has been opened." - [cfg main-data reviews-map {:keys [id status file-branch-id source-file-id target-file-id - review-revn branch-revn] - :as row}] + [cfg main-data reviews-map counts-map {:keys [id status file-branch-id source-file-id target-file-id + review-revn branch-revn] + :as row}] (let [reviews (get reviews-map id []) open? (= "open" status) [ahead behind conflicts] @@ -187,6 +189,8 @@ (assoc :review-state (review-state reviews)) (assoc :outdated (and open? (> branch-revn review-revn))) (assoc :ahead ahead :behind behind :conflicts conflicts) + ;; the comments and tasks of the review, for its overview + (assoc :counts (get counts-map id {:tasks {} :comments-open 0 :comments-resolved 0})) (dissoc :branch-revn :source-revn :base-snapshot-id :base-revn :base-branch-revn :review-snapshot-id)))) @@ -454,8 +458,9 @@ (let [[a b] (fbranch/revn-deltas r)] (or (pos? a) (pos? b))))) rows) - main-data (when need? (:data (bfc/get-file cfg target-id :realize? true)))] - (mapv (partial decorate-pull-request cfg main-data reviews-map) rows)))))) + main-data (when need? (:data (bfc/get-file cfg target-id :realize? true))) + counts-map (ftask/get-review-counts conn (mapv :id rows))] + (mapv (partial decorate-pull-request cfg main-data reviews-map counts-map) rows)))))) ;; --- COMMAND QUERY: get-pull-request @@ -508,7 +513,45 @@ :code :pull-request-not-found :pull-request-id id)) (files/check-read-permissions! cfg profile-id (:target-file-id row)) - (decorate-pull-request cfg nil (get-reviews-map cfg [row]) row))))) + (decorate-pull-request cfg nil + (get-reviews-map cfg [row]) + (ftask/get-review-counts conn [id]) + row))))) + +;; --- COMMAND QUERY: get-pull-request-activity + +(def ^:private schema:get-pull-request-activity + [:map {:title "get-pull-request-activity"} + [:id ::sm/uuid]]) + +(def ^:private max-activity-rows + "The newest saves the activity of a review reads. A review that runs + for months keeps its history; the list shows the recent part of it." + 2000) + +(def ^:private sql:get-pull-request-activity + "SELECT a.id, a.profile_id, a.revn, a.entries, a.created_at + FROM file_pull_request_activity AS a + WHERE a.pull_request_id = ? + ORDER BY a.created_at DESC + LIMIT ?") + +(sv/defmethod ::get-pull-request-activity + "What the saves of the branch did to its layers since the design review + opened: one row per save, newest first, each with who saved and its + entries (`app.common.files.review-activity/entries`). The client folds + them into the activity list." + {::doc/added "2.16" + ::sm/params schema:get-pull-request-activity} + [cfg {:keys [::rpc/profile-id id]}] + (check-pull-requests-enabled!) + (db/run! cfg + (fn [{:keys [::db/conn] :as cfg}] + (let [pr (get-pull-request* conn id)] + (files/check-read-permissions! cfg profile-id (:target-file-id pr)) + (into [] + (map (fn [row] (update row :entries blob/decode))) + (db/exec! conn [sql:get-pull-request-activity id max-activity-rows])))))) ;; --- COMMAND QUERY: get-pull-request-bundle diff --git a/backend/src/app/rpc/commands/files_task.clj b/backend/src/app/rpc/commands/files_task.clj new file mode 100644 index 0000000000..62b274c83a --- /dev/null +++ b/backend/src/app/rpc/commands/files_task.clj @@ -0,0 +1,735 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. +;; +;; Copyright (c) KALEIDOS INC Sucursal en España SL + +(ns app.rpc.commands.files-task + "RPC commands for tasks: a piece of work on a file, assigned to someone + and tied to a layer (see the `file_task` migration). + + Every task lives in a message of a comment thread, so its thread can + go on: a task made from a message keeps that thread, and a task + created on the canvas gets a thread whose first message is its title. + A task may also belong to a design review. Everybody who can read the + file may create a task and move it between states; every move is + recorded as an event of the task with who made it, which is what the + thread of the task shows between its comments. + + The merge of a branch moves its tasks into main (`move-branch-tasks`, + called from `app.rpc.commands.files-branch`): the open ones keep going + on main and the closed ones stay as the history of the branch." + (:require + [app.common.data :as d] + [app.common.exceptions :as ex] + [app.common.geom.point :as gpt] + [app.common.schema :as sm] + [app.common.time :as ct] + [app.common.uri :as uri] + [app.common.uuid :as uuid] + [app.config :as cf] + [app.db :as db] + [app.db.sql :as-alias sql] + [app.email :as eml] + [app.loggers.webhooks :as-alias webhooks] + [app.msgbus :as mbus] + [app.rpc :as-alias rpc] + [app.rpc.commands.comments :as comments] + [app.rpc.commands.files :as files] + [app.rpc.commands.profile :as profile] + [app.rpc.commands.teams :as teams] + [app.rpc.doc :as-alias doc] + [app.rpc.permissions :as perms] + [app.util.services :as sv] + [clojure.string :as str])) + +(def statuses + #{"open" "done" "reopened" "verified" "wont-do"}) + +(def closed-statuses + "A closed task is finished: verified, or dropped as won't do." + #{"verified" "wont-do"}) + +(def ^:private transitions + "The moves a task can make, from each state." + {"open" #{"done" "wont-do"} + "reopened" #{"done" "wont-do"} + "done" #{"verified" "reopened"} + "verified" #{"reopened"} + "wont-do" #{"reopened"}}) + +(def ^:private title-max-length 250) + +;; --- Helpers + +(defn- check-tasks-enabled + "Tasks ride on the branching feature, like design reviews." + [] + (when-not (contains? cf/flags :branching) + (ex/raise :type :restriction + :code :branching-disabled + :hint "the branching feature is not enabled on this instance"))) + +(defn- decode-row + [{:keys [payload position] :as row}] + (cond-> row + (db/pgobject? payload) (assoc :payload (db/decode-transit-pgobject payload)) + (db/pgpoint? position) (assoc :position (db/decode-pgpoint position)))) + +(defn- get-task + "Fetch a task row or raise :not-found." + [conn id & {:as opts}] + (let [task (db/get* conn :file-task {:id id} opts)] + (when (or (nil? task) (some? (:deleted-at task))) + (ex/raise :type :not-found + :code :task-not-found + :hint "unable to find a task with the provided id" + :task-id id)) + (decode-row task))) + +(defn- insert-event + [conn task-id profile-id type payload] + (db/insert! conn :file-task-event + {:id (uuid/next) + :task-id task-id + :profile-id profile-id + :type type + :payload (some-> payload db/tjson) + :created-at (ct/now)} + {::db/return-keys false})) + +(defn- check-assignee + "Refuse an assignee who is not a member of the team of the file." + [conn team-id assignee-id] + (when (some? assignee-id) + (let [members (into #{} (map :id) (teams/get-team-members conn team-id))] + (when-not (contains? members assignee-id) + (ex/raise :type :validation + :code :assignee-not-team-member + :hint "the assignee must be a member of the team" + :profile-id assignee-id))))) + +(defn- run-and-notify + "Run `f` in a transaction, then tell the open clients of `file-id` that + its tasks changed: the message leaves once the transaction committed, + so a client that reloads on it reads the committed state." + [{:keys [::mbus/msgbus] :as cfg} file-id profile-id f] + (let [result (db/tx-run! cfg f)] + (mbus/pub! msgbus + :topic file-id + :message {:type :file-tasks-change + :file-id file-id + :profile-id profile-id}) + result)) + +;; --- Helpers: emails + +(defn- format-task-url + [{:keys [id file-id page-id]} team-id] + (str/join [(cf/get :public-uri) + "/#/workspace?" + (uri/map->query-string {:file-id file-id + :page-id page-id + :team-id team-id + :task-id id})])) + +(defn- send-task-assigned-email + "Tell `assignee-id` that `actor-id` assigned the task to them. Nobody is + told about the tasks they assign to themselves." + [{:keys [::db/conn] :as cfg} team-id actor-id {:keys [assignee-id title] :as task}] + (when (and (some? assignee-id) (not= assignee-id actor-id)) + (let [users (->> (teams/get-users+props conn team-id) + (map profile/decode-row) + (d/index-by :id))] + (when-let [{:keys [fullname email]} (get users assignee-id)] + (eml/send-template + cfg + {::eml/reuse-conn true + ::eml/template "task-assigned" + :public-uri (cf/get :public-uri) + :to email + :name fullname + :source-user (get-in users [actor-id :fullname] "") + :task-title title + :task-url (format-task-url task team-id)}))))) + +;; --- COMMAND QUERY: get-file-tasks + +(def ^:private schema:get-file-tasks + [:map {:title "get-file-tasks"} + [:file-id ::sm/uuid]]) + +(def ^:private sql:get-file-tasks + "SELECT t.id, + t.file_id, + t.pull_request_id, + coalesce(fpr.title, t.review_title) AS review_title, + fpr.status AS review_status, + t.thread_id, + t.comment_id, + ct.seqn AS thread_seqn, + t.title, + t.status, + t.assignee_id, + t.created_by, + t.page_id, + t.frame_id, + t.shape_id, + t.lost_shape_name, + t.position, + t.merge_id, + t.branch_name, + t.status_changed_at, + t.status_changed_by, + t.created_at, + t.updated_at + FROM file_task AS t + LEFT JOIN file_pull_request AS fpr ON (fpr.id = t.pull_request_id) + LEFT JOIN comment_thread AS ct ON (ct.id = t.thread_id) + WHERE t.file_id = ? + AND t.deleted_at IS NULL + ORDER BY t.created_at ASC") + +(defn get-file-tasks + [conn file-id] + (into [] (map decode-row) (db/exec! conn [sql:get-file-tasks file-id]))) + +(sv/defmethod ::get-file-tasks + "List the tasks of a file, oldest first: the open ones and the history + of the closed ones, the tasks of the branches merged into it included + (those carry the merge that moved them, `merge-id`)." + {::doc/added "2.16" + ::sm/params schema:get-file-tasks} + [cfg {:keys [::rpc/profile-id file-id]}] + (check-tasks-enabled) + (db/run! cfg (fn [{:keys [::db/conn] :as cfg}] + (files/check-read-permissions! cfg profile-id file-id) + (get-file-tasks conn file-id)))) + +;; --- COMMAND QUERY: get-task-events + +(def ^:private schema:get-task-events + [:map {:title "get-task-events"} + [:id ::sm/uuid]]) + +(def ^:private sql:get-task-events + "SELECT e.id, e.task_id, e.profile_id, e.type, e.payload, e.created_at + FROM file_task_event AS e + WHERE e.task_id = ? + ORDER BY e.created_at ASC") + +(sv/defmethod ::get-task-events + "What happened to a task, oldest first." + {::doc/added "2.16" + ::sm/params schema:get-task-events} + [cfg {:keys [::rpc/profile-id id]}] + (check-tasks-enabled) + (db/run! cfg (fn [{:keys [::db/conn] :as cfg}] + (let [task (get-task conn id)] + (files/check-read-permissions! cfg profile-id (:file-id task)) + (into [] (map decode-row) (db/exec! conn [sql:get-task-events id])))))) + +;; --- COMMAND: create-task + +(def ^:private schema:create-task + [:map {:title "create-task" :closed true} + [:file-id ::sm/uuid] + [:title [:string {:max title-max-length}]] + [:page-id ::sm/uuid] + [:frame-id ::sm/uuid] + [:shape-id {:optional true} [:maybe ::sm/uuid]] + ;; where its mark goes when it points at no layer, and where its + ;; thread sits + [:position ::gpt/point] + [:assignee-id {:optional true} [:maybe ::sm/uuid]] + ;; the design review the task is created in: an open pull request + ;; of this file (the branch file it reviews) + [:pull-request-id {:optional true} [:maybe ::sm/uuid]] + ;; the comment thread the task comes from, which stays attached, and + ;; the message of that thread it was made from; without them the + ;; task gets a thread of its own + [:thread-id {:optional true} [:maybe ::sm/uuid]] + [:comment-id {:optional true} [:maybe ::sm/uuid]]]) + +(def ^:private sql:get-open-review-of-file + "SELECT id, title FROM file_pull_request + WHERE id = ? + AND source_file_id = ? + AND status = 'open' + AND deleted_at IS NULL") + +(def ^:private sql:get-task-of-comment + "SELECT id FROM file_task + WHERE comment_id = ? + AND deleted_at IS NULL") + +(defn- check-thread + "Refuse a thread of another file." + [conn thread-id file-id] + (let [thread (db/get* conn :comment-thread {:id thread-id})] + (when (or (nil? thread) (not= file-id (:file-id thread))) + (ex/raise :type :validation + :code :thread-not-in-file + :hint "the comment thread does not belong to the file" + :thread-id thread-id)))) + +(defn- check-comment + "Refuse a message of another thread, and a message that already has a + task: each message of a thread may be one task." + [conn comment-id thread-id] + (let [comment (db/get* conn :comment {:id comment-id})] + (when (or (nil? comment) (not= thread-id (:thread-id comment))) + (ex/raise :type :validation + :code :comment-not-in-thread + :hint "the comment does not belong to the thread" + :comment-id comment-id)) + (when (db/exec-one! conn [sql:get-task-of-comment comment-id]) + (ex/raise :type :validation + :code :comment-already-has-task + :hint "the comment already has a task" + :comment-id comment-id)))) + +(defn- create-task-thread + "The thread of a task created on the canvas: its first message is the + title, it points at the layer of the task (at the spot of the canvas + when there is none) and belongs to the design review of the task." + [cfg profile-id {:keys [file-id title page-id frame-id shape-id position pull-request-id]}] + (comments/create-comment-thread + cfg + (cond-> {::rpc/profile-id profile-id + ::rpc/request-at (ct/now) + :file-id file-id + :page-id page-id + :frame-id frame-id + :position position + :content title + :anchor (if (some? shape-id) + {:type :layer :shape-id shape-id} + {:type :canvas})} + (some? pull-request-id) (assoc :pull-request-id pull-request-id)))) + +(sv/defmethod ::create-task + "Create an open task on a file, in a message of a comment thread: the + message it was made from (`thread-id` and `comment-id`), or the first + message of a new thread that carries its title. A task created in a + design review belongs to it. The assignee, when there is one, must be + a member of the team and is told by email." + {::doc/added "2.16" + ::webhooks/event? true + ::sm/params schema:create-task} + [cfg {:keys [::rpc/profile-id file-id title page-id frame-id shape-id position assignee-id + pull-request-id thread-id comment-id] :as params}] + (check-tasks-enabled) + (when (str/blank? title) + (ex/raise :type :validation + :code :invalid-task-title + :hint "task title cannot be blank")) + (files/check-read-permissions! cfg profile-id file-id) + (run-and-notify + cfg file-id profile-id + (fn [{:keys [::db/conn] :as cfg}] + (let [team-id (perms/get-team-id-for-file conn file-id) + review (when pull-request-id + (or (db/exec-one! conn [sql:get-open-review-of-file pull-request-id file-id]) + (ex/raise :type :validation + :code :pull-request-not-open + :hint "the task names a design review that is not open on this file" + :pull-request-id pull-request-id))) + _ (when thread-id + (check-thread conn thread-id file-id)) + _ (when comment-id + (check-comment conn comment-id thread-id)) + _ (check-assignee conn team-id assignee-id) + thread (when (nil? thread-id) + (create-task-thread cfg profile-id (update params :title str/trim))) + ts (ct/now) + task {:id (uuid/next) + :position position + :file-id file-id + :pull-request-id pull-request-id + :review-title (:title review) + :thread-id (or thread-id (:id thread)) + :comment-id (or comment-id (:comment-id thread)) + :title (str/trim title) + :status "open" + :assignee-id assignee-id + :created-by profile-id + :page-id page-id + :frame-id frame-id + :shape-id shape-id + :created-at ts + :updated-at ts}] + (db/insert! conn :file-task + (assoc task :position (db/pgpoint position)) + {::db/return-keys false}) + (insert-event conn (:id task) profile-id "created" nil) + (when (some? assignee-id) + (insert-event conn (:id task) profile-id "assigned" {:assignee-id assignee-id})) + (send-task-assigned-email cfg team-id profile-id task) + task)))) + +;; --- COMMAND: update-task + +(def ^:private schema:update-task + [:map {:title "update-task" :closed true} + [:id ::sm/uuid] + [:title {:optional true} [:string {:max title-max-length}]] + ;; nil leaves the task without an assignee + [:assignee-id {:optional true} [:maybe ::sm/uuid]]]) + +(sv/defmethod ::update-task + "Rename a task or change its assignee. Each change is an event of the + task; a new assignee is told by email." + {::doc/added "2.16" + ::sm/params schema:update-task} + [cfg {:keys [::rpc/profile-id id title] :as params}] + (check-tasks-enabled) + (when (and (some? title) (str/blank? title)) + (ex/raise :type :validation + :code :invalid-task-title + :hint "task title cannot be blank")) + (let [task (db/run! cfg (fn [{:keys [::db/conn]}] (get-task conn id)))] + (files/check-read-permissions! cfg profile-id (:file-id task)) + (run-and-notify + cfg (:file-id task) profile-id + (fn [{:keys [::db/conn] :as cfg}] + (let [task (get-task conn id {::sql/for-update true}) + team-id (perms/get-team-id-for-file conn (:file-id task)) + reassign? (and (contains? params :assignee-id) + (not= (:assignee-id params) (:assignee-id task))) + rename? (and (some? title) (not= (str/trim title) (:title task))) + changes (cond-> {:updated-at (ct/now)} + rename? (assoc :title (str/trim title)) + reassign? (assoc :assignee-id (:assignee-id params))) + task (merge task changes)] + (when reassign? + (check-assignee conn team-id (:assignee-id params))) + (db/update! conn :file-task changes {:id id} {::db/return-keys false}) + (when rename? + (insert-event conn id profile-id "renamed" {:title (:title task)})) + (when reassign? + (insert-event conn id profile-id "assigned" {:assignee-id (:assignee-id task)}) + (send-task-assigned-email cfg team-id profile-id task)) + task))))) + +;; --- COMMAND: set-task-status + +(def ^:private schema:set-task-status + [:map {:title "set-task-status" :closed true} + [:id ::sm/uuid] + [:status (into [:enum] statuses)]]) + +(sv/defmethod ::set-task-status + "Move a task to another state (see `transitions`). Anybody who can read + the file may do it; the event records who did." + {::doc/added "2.16" + ::webhooks/event? true + ::sm/params schema:set-task-status} + [cfg {:keys [::rpc/profile-id id status]}] + (check-tasks-enabled) + (let [task (db/run! cfg (fn [{:keys [::db/conn]}] (get-task conn id)))] + (files/check-read-permissions! cfg profile-id (:file-id task)) + (run-and-notify + cfg (:file-id task) profile-id + (fn [{:keys [::db/conn]}] + (let [task (get-task conn id {::sql/for-update true}) + from (:status task) + ts (ct/now)] + (when-not (contains? (get transitions from) status) + (ex/raise :type :validation + :code :invalid-task-transition + :hint "the task cannot move to that state from the one it is in" + :from from + :to status)) + (db/update! conn :file-task + {:status status + :status-changed-at ts + :status-changed-by profile-id + :updated-at ts} + {:id id} + {::db/return-keys false}) + (insert-event conn id profile-id "status" {:from from :to status}) + (assoc task + :status status + :status-changed-at ts + :status-changed-by profile-id)))))) + +;; --- COMMAND: relink-task + +(def ^:private schema:relink-task + [:map {:title "relink-task" :closed true} + [:id ::sm/uuid] + [:page-id ::sm/uuid] + [:frame-id ::sm/uuid] + [:shape-id ::sm/uuid] + ;; the name the layer has now, kept in the event + [:shape-name [:string {:max 250}]]]) + +(sv/defmethod ::relink-task + "Point a task at another layer. A task whose layer was deleted stops + being lost." + {::doc/added "2.16" + ::sm/params schema:relink-task} + [cfg {:keys [::rpc/profile-id id page-id frame-id shape-id shape-name]}] + (check-tasks-enabled) + (let [task (db/run! cfg (fn [{:keys [::db/conn]}] (get-task conn id)))] + (files/check-read-permissions! cfg profile-id (:file-id task)) + (run-and-notify + cfg (:file-id task) profile-id + (fn [{:keys [::db/conn]}] + (let [changes {:page-id page-id + :frame-id frame-id + :shape-id shape-id + :lost-shape-name nil + :updated-at (ct/now)}] + (db/update! conn :file-task changes {:id id} {::db/return-keys false}) + (insert-event conn id profile-id "relinked" {:shape-id shape-id :shape-name shape-name}) + (merge (get-task conn id) changes)))))) + +;; --- COMMAND: mark-tasks-layer-deleted + +(def ^:private schema:deleted-layer + [:map {:title "DeletedTaskLayer"} + [:shape-id ::sm/uuid] + [:shape-name [:string {:max 250}]] + ;; the board the task moves to, and its name for the event + [:frame-id ::sm/uuid] + [:frame-name {:optional true} [:maybe [:string {:max 250}]]] + ;; the layer as it was (the shape and its children), what "restore + ;; layer" puts back + [:objects {:optional true} [:vector {:max 500} :map]]]) + +(def ^:private schema:mark-tasks-layer-deleted + [:map {:title "mark-tasks-layer-deleted" :closed true} + [:file-id ::sm/uuid] + [:layers [:vector {:min 1 :max 200} schema:deleted-layer]]]) + +(def ^:private sql:get-tasks-of-layers + "SELECT * FROM file_task + WHERE file_id = ? + AND shape_id = ANY(?) + AND lost_shape_name IS NULL + AND status NOT IN ('verified', 'wont-do') + AND deleted_at IS NULL + FOR UPDATE") + +(sv/defmethod ::mark-tasks-layer-deleted + "Tell the server that layers with open tasks were deleted: each task + moves to the board that held its layer and keeps the name of the lost + layer until it is linked to another one. The event of each task keeps + the deleted layer, so it can be restored later. Returns the tasks it + moved." + {::doc/added "2.16" + ::sm/params schema:mark-tasks-layer-deleted} + [cfg {:keys [::rpc/profile-id file-id layers]}] + (check-tasks-enabled) + (files/check-read-permissions! cfg profile-id file-id) + (run-and-notify + cfg file-id profile-id + (fn [{:keys [::db/conn]}] + (let [by-shape (d/index-by :shape-id layers) + ids (db/create-array conn "uuid" (vec (keys by-shape))) + tasks (into [] (map decode-row) (db/exec! conn [sql:get-tasks-of-layers file-id ids])) + ts (ct/now)] + (into [] + (map (fn [{:keys [id shape-id] :as task}] + (let [{:keys [shape-name frame-id frame-name objects]} (get by-shape shape-id) + changes {:lost-shape-name shape-name + :frame-id frame-id + :updated-at ts}] + (db/update! conn :file-task changes {:id id} {::db/return-keys false}) + (insert-event conn id profile-id "layer-deleted" + {:shape-id shape-id + :shape-name shape-name + :frame-id frame-id + :frame-name frame-name + :objects objects}) + (merge task changes)))) + tasks))))) + +;; --- COMMAND: mark-task-layer-restored + +(def ^:private schema:mark-task-layer-restored + [:map {:title "mark-task-layer-restored" :closed true} + [:id ::sm/uuid] + [:frame-id ::sm/uuid]]) + +(sv/defmethod ::mark-task-layer-restored + "The deleted layer of a task is back (undone, or restored from the + task): the task points at it again." + {::doc/added "2.16" + ::sm/params schema:mark-task-layer-restored} + [cfg {:keys [::rpc/profile-id id frame-id]}] + (check-tasks-enabled) + (let [task (db/run! cfg (fn [{:keys [::db/conn]}] (get-task conn id)))] + (files/check-read-permissions! cfg profile-id (:file-id task)) + (run-and-notify + cfg (:file-id task) profile-id + (fn [{:keys [::db/conn]}] + (let [changes {:lost-shape-name nil + :frame-id frame-id + :updated-at (ct/now)}] + (db/update! conn :file-task changes {:id id} {::db/return-keys false}) + (insert-event conn id profile-id "layer-restored" + {:shape-id (:shape-id task) + :shape-name (:lost-shape-name task)}) + (merge task changes)))))) + +;; --- COMMAND: delete-task + +(def ^:private schema:delete-task + [:map {:title "delete-task" :closed true} + [:id ::sm/uuid]]) + +(sv/defmethod ::delete-task + "Delete a task. Its thread stays: the message the task lived in goes + on as a plain comment." + {::doc/added "2.16" + ::sm/params schema:delete-task} + [cfg {:keys [::rpc/profile-id id]}] + (check-tasks-enabled) + (let [task (db/run! cfg (fn [{:keys [::db/conn]}] (get-task conn id)))] + (files/check-read-permissions! cfg profile-id (:file-id task)) + (run-and-notify + cfg (:file-id task) profile-id + (fn [{:keys [::db/conn]}] + (db/update! conn :file-task + {:deleted-at (ct/now) :updated-at (ct/now)} + {:id id} + {::db/return-keys false}) + nil)))) + +;; --- Review counts + +(def ^:private sql:get-review-task-counts + "SELECT pull_request_id, status, count(*) AS total + FROM file_task + WHERE pull_request_id = ANY(?) + AND deleted_at IS NULL + GROUP BY pull_request_id, status") + +(def ^:private sql:get-review-comment-counts + "SELECT pull_request_id, is_resolved, count(*) AS total + FROM comment_thread + WHERE pull_request_id = ANY(?) + GROUP BY pull_request_id, is_resolved") + +(defn get-review-counts + "{pull-request-id {:tasks {status count} :comments-open n + :comments-resolved n}} for the given design reviews." + [conn pull-request-ids] + (if (empty? pull-request-ids) + {} + (let [ids (db/create-array conn "uuid" (vec pull-request-ids)) + empty {:tasks {} :comments-open 0 :comments-resolved 0} + by-tasks (reduce (fn [acc {:keys [pull-request-id status total]}] + (assoc-in acc [pull-request-id :tasks status] total)) + {} + (db/exec! conn [sql:get-review-task-counts ids]))] + (reduce (fn [acc {:keys [pull-request-id is-resolved total]}] + (update acc pull-request-id + (fn [counts] + (assoc (merge empty counts) + (if is-resolved :comments-resolved :comments-open) + total)))) + (update-vals by-tasks #(merge empty %)) + (db/exec! conn [sql:get-review-comment-counts ids]))))) + +;; --- Merge: move the tasks of a branch into main + +(def ^:private sql:get-branch-tasks + "SELECT * FROM file_task + WHERE file_id = ? + AND deleted_at IS NULL + ORDER BY created_at ASC + FOR UPDATE") + +(def ^:private sql:lock-thread-seqn + "SELECT comment_thread_seqn FROM file WHERE id = ? FOR UPDATE") + +(defn- move-threads + "Move the comment threads `thread-ids` of the branch into main. The + number of a thread is unique in its file, so each one takes the next + number of main." + [conn main-id thread-ids] + (when (seq thread-ids) + (let [seqn (-> (db/exec-one! conn [sql:lock-thread-seqn main-id]) + (:comment-thread-seqn 0))] + (doseq [[index thread-id] (d/enumerate thread-ids)] + (db/update! conn :comment-thread + {:file-id main-id + :seqn (+ seqn index 1)} + {:id thread-id} + {::db/return-keys false})) + (db/update! conn :file + {:comment-thread-seqn (+ seqn (count thread-ids))} + {:id main-id} + {::db/return-keys false})))) + +(defn- send-tasks-moved-emails + [{:keys [::db/conn] :as cfg} {:keys [team-id main-id actor-id branch-name file-name]} tasks] + (let [users (->> (teams/get-users+props conn team-id) + (map profile/decode-row) + (d/index-by :id)) + actor (get-in users [actor-id :fullname] "")] + (doseq [[assignee-id tasks] (group-by :assignee-id tasks)] + (when-let [{:keys [fullname email]} (and (some? assignee-id) + (not= assignee-id actor-id) + (get users assignee-id))] + (eml/send-template + cfg + {::eml/reuse-conn true + ::eml/template "tasks-moved" + :public-uri (cf/get :public-uri) + :to email + :name fullname + :source-user actor + :branch-name branch-name + :file-name file-name + :task-titles (str/join "\n" (map #(str "- " (:title %)) tasks)) + :file-url (str/join [(cf/get :public-uri) + "/#/workspace?" + (uri/map->query-string {:file-id main-id + :team-id team-id})])}))))) + +(defn move-branch-tasks + "Move every task of the branch file into main, inside the merge + transaction: the open ones keep going on main, the closed ones stay as + the history of the branch. Each task keeps the names it shows (the + review title is refreshed from its pull request, which goes away with + the branch), records the merge and gets a `moved-to-main` event. The + threads of the tasks move with them. When `notify-assignees` is set, + the assignees of the open tasks are told by email. Returns the moved + tasks." + [{:keys [::db/conn] :as cfg} + {:keys [branch-file-id main-id merge-id branch-name profile-id notify-assignees]}] + (let [tasks (db/exec! conn [sql:get-branch-tasks branch-file-id])] + (when (seq tasks) + (let [reviews (->> (keep :pull-request-id tasks) + (distinct) + (map #(db/get* conn :file-pull-request {:id %})) + (remove nil?) + (d/index-by :id)) + ts (ct/now)] + (move-threads conn main-id (into [] (comp (keep :thread-id) (distinct)) tasks)) + (doseq [{:keys [id pull-request-id review-title] :as task} tasks] + (db/update! conn :file-task + {:file-id main-id + :merge-id merge-id + :branch-name branch-name + :review-title (or (get-in reviews [pull-request-id :title]) review-title) + :updated-at ts} + {:id id} + {::db/return-keys false}) + (insert-event conn (:id task) profile-id "moved-to-main" + {:merge-id merge-id :branch-name branch-name})) + (when notify-assignees + (let [main (db/get conn :file {:id main-id} {::sql/columns [:name]})] + (send-tasks-moved-emails cfg + {:team-id (perms/get-team-id-for-file conn main-id) + :main-id main-id + :actor-id profile-id + :branch-name branch-name + :file-name (:name main)} + (remove #(contains? closed-statuses (:status %)) tasks)))) + tasks)))) diff --git a/backend/src/app/rpc/commands/files_update.clj b/backend/src/app/rpc/commands/files_update.clj index 9b5d00b9eb..f73670bac2 100644 --- a/backend/src/app/rpc/commands/files_update.clj +++ b/backend/src/app/rpc/commands/files_update.clj @@ -14,6 +14,7 @@ [app.common.files.changes :as cpc] [app.common.files.migrations :as fmg] [app.common.files.repair :as cfr] + [app.common.files.review-activity :as ra] [app.common.files.validate :as val] [app.common.logging :as l] [app.common.schema :as sm] @@ -329,6 +330,47 @@ :reprocess-changes-ms (get timings :reprocess-changes-ms))) (throw cause)))))) +;; --- Design review activity + +(def ^:private sql:get-open-review-of-branch-file + "SELECT id FROM file_pull_request + WHERE source_file_id = ? + AND status = 'open' + AND deleted_at IS NULL") + +(defn- get-open-review-id + "The open design review of a branch file, if it has one." + [conn file-id] + (:id (db/exec-one! conn [sql:get-open-review-of-branch-file file-id]))) + +(defn- track-review-activity + "Wrap the changes application of a save so it also works out what the + save did to each layer it touched, into the volatile `activity`: the + touched layers are read before the changes apply and again after (see + `app.common.files.review-activity`). Only the changes the save + accepted (`::changes`) count: a rejected commit touched nothing." + [update-fn activity] + (fn [cfg file changes commits skip-validate] + (let [before (ra/collect-before (:data file) (ra/touched changes)) + result (update-fn cfg file changes commits skip-validate)] + (vreset! activity (ra/entries before (:data result) (ra/touched (::changes result)))) + result))) + +(defn- record-review-activity + "Record the activity of a save of a branch under design review: who + saved, the revn the save produced and what it did to each layer. A save + that changed no layer records nothing." + [conn review-id profile-id {:keys [revn]} entries timestamp] + (when (seq entries) + (db/insert! conn :file-pull-request-activity + {:id (uuid/next) + :pull-request-id review-id + :profile-id profile-id + :revn revn + :entries (blob/encode entries) + :created-at timestamp} + {::db/return-keys false}))) + (defn- update-file* "Internal function, part of the update-file process, that encapsulates the changes application offload to a separated thread and emit all @@ -358,11 +400,22 @@ revn (get file :revn) + ;; A save of a branch under design review records what it did + ;; to each layer, for the activity of the review. + review-id + (when (:is-branch file) + (get-open-review-id conn (:id file))) + + activity + (volatile! nil) + file (binding [cfeat/*current* features cfeat/*previous* (:features file)] (update-file-data! cfg file - process-changes-and-validate + (if review-id + (track-review-activity process-changes-and-validate activity) + process-changes-and-validate) changes commits skip-validate)) ;; Only the accepted changes are stored and broadcast. The xlog @@ -469,6 +522,10 @@ (when (contains? cf/flags :redis-cache) (invalidate-caches! cfg file)) + (when review-id + (record-review-activity conn review-id profile-id file @activity + (or timestamp (ct/now)))) + ;; Send asynchronous notifications (when repair (send-repair-notifications cfg params file repair)) diff --git a/backend/test/backend_tests/climit_test.clj b/backend/test/backend_tests/climit_test.clj index 090ae4d6b8..9a40857d55 100644 --- a/backend/test/backend_tests/climit_test.clj +++ b/backend/test/backend_tests/climit_test.clj @@ -22,21 +22,28 @@ (def ^:private calls (atom [])) (defn- record-metrics - "Run `f` recording every metrics call it makes." + "Run `f` recording every metrics call made while it runs, with the thread + that made it: `with-redefs` is global, so other threads of the test JVM + record into the same atom." [f] (reset! calls []) (with-redefs [mtx/run! (fn [_ & {:keys [id labels val]}] - (swap! calls conj {:id id :labels (vec labels) :val val}))] + (swap! calls conj {:id id :labels (vec labels) :val val + :thread (Thread/currentThread)}))] (f))) (defn- acquired-in-order - "Limiter names acquired so far, in acquisition order." + "Limiter names the calling thread acquired so far, in acquisition order. A + call of another thread, such as an RPC left running by an earlier test, can + take a root limiter inside the window and must not count." [] - (->> @calls - (filter #(= :rpc-climit-timing (:id %))) - (mapcat :labels) - (vec))) + (let [thread (Thread/currentThread)] + (->> @calls + (filter #(= :rpc-climit-timing (:id %))) + (filter #(identical? thread (:thread %))) + (mapcat :labels) + (vec)))) (defn- invoke! "Run `f` under the limits the cfg declares, the way a command does: the key diff --git a/backend/test/backend_tests/email_sending_test.clj b/backend/test/backend_tests/email_sending_test.clj index 36b602441f..8f54bb023a 100644 --- a/backend/test/backend_tests/email_sending_test.clj +++ b/backend/test/backend_tests/email_sending_test.clj @@ -174,7 +174,7 @@ "request-file-access" "request-file-access-yourpenpot" "request-file-access-yourpenpot-view" "request-team-access" "comment-mention" "comment-thread" "comment-notification" - "review-request"} + "review-request" "task-assigned" "tasks-moved"} (set (keys emails/templates))))) (t/deftest send-template-validation diff --git a/backend/test/backend_tests/rpc_file_task_test.clj b/backend/test/backend_tests/rpc_file_task_test.clj new file mode 100644 index 0000000000..fefe1de104 --- /dev/null +++ b/backend/test/backend_tests/rpc_file_task_test.clj @@ -0,0 +1,426 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. +;; +;; Copyright (c) KALEIDOS INC Sucursal en España SL + +(ns backend-tests.rpc-file-task-test + (:require + [app.common.features :as cfeat] + [app.common.geom.point :as gpt] + [app.common.types.shape :as cts] + [app.common.uuid :as uuid] + [app.config :as cf] + [app.db :as db] + [app.email :as eml] + [app.rpc :as-alias rpc] + [backend-tests.helpers :as th] + [clojure.test :as t])) + +(t/use-fixtures :once th/state-init) +(t/use-fixtures :each th/database-reset) + +(defn- task-flags + "The test flags plus `:branching`. Read at run time, inside the + `th/state-init` fixture, so the flags it turns off (the admin + console among them) stay off: a value captured when the namespace + loads would carry the production defaults instead." + [] + (conj cf/flags :branching)) + +(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- update-file* + [profile file-id changes] + (let [f (th/db-get :file {:id file-id})] + (th/command! {::th/type :update-file + ::rpc/profile-id (:id profile) + :id file-id + :session-id (uuid/random) + :revn (:revn f) + :vern (:vern f) + :features cfeat/supported-features + :changes changes}))) + +(defn- add-rect* + [profile file-id page-id rect-id name] + (update-file* profile file-id + [{:type :add-obj + :page-id page-id + :id rect-id + :parent-id uuid/zero + :frame-id uuid/zero + :obj (cts/setup-shape + {:id rect-id :name name :type :rect + :parent-id uuid/zero :frame-id uuid/zero})}])) + +(defn- setup-review + "A file with a rect on main, a branch of it and an open design review of + the branch. Returns the ids the tests need." + [] + (let [author (th/create-profile* 1 {:is-active true}) + reviewer (th/create-profile* 2 {: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)) + rect-id (uuid/random)] + (th/create-team-role* {:team-id (:default-team-id author) + :profile-id (:id reviewer) + :role :editor}) + (add-rect* author (:id file) page-id rect-id "Pay button") + (let [branch (:result (th/command! {::th/type :create-file-branch + ::rpc/profile-id (:id author) + :file-id (:id file) + :name "feature-login"})) + review (:result (th/command! {::th/type :create-pull-request + ::rpc/profile-id (:id author) + :branch-id (:id branch) + :title "Checkout redesign" + :reviewers [(:id reviewer)]}))] + {:author author + :reviewer reviewer + :file file + :page-id page-id + :rect-id rect-id + :branch branch + :branch-file-id (:branch-file-id branch) + :review review}))) + +(defn- create-task* + [profile params] + (th/command! (merge {::th/type :create-task + ::rpc/profile-id (:id profile) + :frame-id uuid/zero + :position (gpt/point 0) + :title "Use the secondary token on the pay button"} + params))) + +(defn- set-status* + [profile task-id status] + (th/command! {::th/type :set-task-status + ::rpc/profile-id (:id profile) + :id task-id + :status status})) + +(t/deftest task-lifecycle-records-who-made-each-move + (with-redefs [cf/flags (task-flags) + eml/send-template (fn [_ _] nil)] + (let [{:keys [author reviewer page-id rect-id branch-file-id review]} (setup-review) + out (create-task* reviewer {:file-id branch-file-id + :page-id page-id + :shape-id rect-id + :assignee-id (:id author) + :pull-request-id (:id review)}) + task (:result out)] + (t/is (nil? (:error out))) + (t/is (= "open" (:status task))) + (t/is (= "Checkout redesign" (:review-title task))) + + (t/testing "the assignee marks it done and the reviewer verifies it" + (t/is (nil? (:error (set-status* author (:id task) "done")))) + (t/is (nil? (:error (set-status* reviewer (:id task) "verified"))))) + + (t/testing "every move is an event with who made it" + (let [events (:result (th/command! {::th/type :get-task-events + ::rpc/profile-id (:id author) + :id (:id task)}))] + (t/is (= ["created" "assigned" "status" "status"] (mapv :type events))) + (t/is (= [(:id reviewer) (:id reviewer) (:id author) (:id reviewer)] + (mapv :profile-id events))) + (t/is (= {:from "done" :to "verified"} (:payload (last events)))))) + + (t/testing "the review counts its tasks" + (let [row (:result (th/command! {::th/type :get-pull-request + ::rpc/profile-id (:id author) + :id (:id review)}))] + (t/is (= {"verified" 1} (-> row :counts :tasks)))))))) + +(t/deftest task-refuses-a-move-its-state-does-not-allow + (with-redefs [cf/flags (task-flags)] + (let [{:keys [author page-id branch-file-id]} (setup-review) + task (:result (create-task* author {:file-id branch-file-id :page-id page-id})) + out (set-status* author (:id task) "verified")] + (t/is (= :invalid-task-transition (-> out :error ex-data :code)))))) + +(t/deftest task-assignee-must-be-a-team-member + (with-redefs [cf/flags (task-flags)] + (let [{:keys [author page-id branch-file-id]} (setup-review) + stranger (th/create-profile* 3 {:is-active true}) + out (create-task* author {:file-id branch-file-id + :page-id page-id + :assignee-id (:id stranger)})] + (t/is (= :assignee-not-team-member (-> out :error ex-data :code)))))) + +(t/deftest deleted-layer-moves-its-task-to-the-board + (with-redefs [cf/flags (task-flags)] + (let [{:keys [author page-id rect-id branch-file-id]} (setup-review) + board-id (uuid/random) + task (:result (create-task* author {:file-id branch-file-id + :page-id page-id + :shape-id rect-id})) + out (th/command! {::th/type :mark-tasks-layer-deleted + ::rpc/profile-id (:id author) + :file-id branch-file-id + :layers [{:shape-id rect-id + :shape-name "Pay button" + :frame-id board-id + :frame-name "Checkout / Mobile" + :objects [{:id rect-id :name "Pay button" :type :rect}]}]})] + (t/is (nil? (:error out))) + (t/is (= 1 (count (:result out)))) + (let [row (th/db-get :file-task {:id (:id task)})] + (t/is (= "Pay button" (:lost-shape-name row))) + (t/is (= board-id (:frame-id row)))) + + (t/testing "restoring the layer clears the loss" + (th/command! {::th/type :mark-task-layer-restored + ::rpc/profile-id (:id author) + :id (:id task) + :frame-id uuid/zero}) + (t/is (nil? (:lost-shape-name (th/db-get :file-task {:id (:id task)})))))))) + +(t/deftest review-thread-points-at-a-layer + (with-redefs [cf/flags (task-flags)] + (let [{:keys [reviewer page-id rect-id branch-file-id review]} (setup-review) + out (th/command! {::th/type :create-comment-thread + ::rpc/profile-id (:id reviewer) + :file-id branch-file-id + :page-id page-id + :frame-id uuid/zero + :position (gpt/point 10 20) + :content "The pay button loses contrast" + :pull-request-id (:id review) + :anchor {:type :layer :shape-id rect-id}})] + (t/is (nil? (:error out))) + (let [[thread] (:result (th/command! {::th/type :get-comment-threads + ::rpc/profile-id (:id reviewer) + :file-id branch-file-id}))] + (t/is (= (:id review) (:pull-request-id thread))) + (t/is (= "Checkout redesign" (:pull-request-title thread))) + (t/is (= :layer (:anchor-type thread))) + (t/is (= rect-id (:shape-id thread))))))) + +(t/deftest review-thread-refuses-a-review-of-another-file + (with-redefs [cf/flags (task-flags)] + (let [{:keys [reviewer page-id file review]} (setup-review) + out (th/command! {::th/type :create-comment-thread + ::rpc/profile-id (:id reviewer) + :file-id (:id file) + :page-id page-id + :frame-id uuid/zero + :position (gpt/point 0) + :content "on main" + :pull-request-id (:id review)})] + (t/is (= :pull-request-not-open (-> out :error ex-data :code)))))) + +(t/deftest branch-save-under-review-records-its-activity + (with-redefs [cf/flags (task-flags)] + (let [{:keys [author page-id rect-id branch-file-id review]} (setup-review)] + (update-file* author branch-file-id + [{:type :mod-obj :page-id page-id :id rect-id + :operations [{:type :set :attr :name :val "Pay"}]}]) + (let [[row :as rows] (:result (th/command! {::th/type :get-pull-request-activity + ::rpc/profile-id (:id author) + :id (:id review)}))] + (t/is (= 1 (count rows))) + (t/is (= (:id author) (:profile-id row))) + (t/is (= [{:id rect-id :kind :modified :attrs {:name ["Pay button" "Pay"]}}] + (mapv #(select-keys % [:id :kind :attrs]) (:entries row)))))))) + +(t/deftest merge-moves-the-tasks-and-their-threads-into-main + (with-redefs [cf/flags (task-flags) + eml/send-template (fn [_ _] nil)] + (let [{:keys [author page-id rect-id file branch branch-file-id review]} (setup-review) + ;; main has a thread of its own already: the moved one must not + ;; take its number + _ (th/command! {::th/type :create-comment-thread + ::rpc/profile-id (:id author) + :file-id (:id file) + :page-id page-id + :frame-id uuid/zero + :position (gpt/point 0) + :content "on main"}) + thread (:result (th/command! {::th/type :create-comment-thread + ::rpc/profile-id (:id author) + :file-id branch-file-id + :page-id page-id + :frame-id uuid/zero + :position (gpt/point 0) + :content "fix the radius" + :pull-request-id (:id review)})) + open (:result (create-task* author {:file-id branch-file-id + :page-id page-id + :shape-id rect-id + :thread-id (:id thread) + :pull-request-id (:id review)})) + closed (:result (create-task* author {:file-id branch-file-id + :page-id page-id + :title "Drop the promo"}))] + (set-status* author (:id closed) "wont-do") + (update-file* author branch-file-id + [{:type :mod-obj :page-id page-id :id rect-id + :operations [{:type :set :attr :name :val "Pay"}]}]) + + (let [out (th/command! {::th/type :merge-file-branch + ::rpc/profile-id (:id author) + :branch-id (:id branch) + :notify-assignees true})] + (t/is (nil? (:error out)))) + + (let [tasks (:result (th/command! {::th/type :get-file-tasks + ::rpc/profile-id (:id author) + :file-id (:id file)})) + [merge-row] (th/db-query :file-branch-merge {:file-id (:id file)})] + (t/is (= #{(:id open) (:id closed)} (into #{} (map :id) tasks))) + (t/is (every? #(= (:id merge-row) (:merge-id %)) tasks)) + (t/is (every? #(= "feature-login" (:branch-name %)) tasks)) + (t/is (= "Checkout redesign" + (:review-title (th/db-get :file-task {:id (:id open)}))))) + + (t/testing "the threads move with their tasks and take the next numbers of main" + (let [moved (th/db-get :comment-thread {:id (:id thread)}) + closed (th/db-get :comment-thread {:id (:thread-id closed)})] + (t/is (= (:id file) (:file-id moved))) + (t/is (= (:id file) (:file-id closed))) + (t/is (= [2 3] [(:seqn moved) (:seqn closed)])) + (t/is (= 3 (:comment-thread-seqn (th/db-get :file {:id (:id file)} + {::db/remove-deleted false}))))))))) + +(t/deftest each-message-of-a-thread-may-be-a-task + (with-redefs [cf/flags (task-flags)] + (let [{:keys [author page-id branch-file-id]} (setup-review) + thread (:result (th/command! {::th/type :create-comment-thread + ::rpc/profile-id (:id author) + :file-id branch-file-id + :page-id page-id + :frame-id uuid/zero + :position (gpt/point 0) + :content "fix the radius"})) + reply (:result (th/command! {::th/type :create-comment + ::rpc/profile-id (:id author) + :thread-id (:id thread) + :content "and the shadow"})) + messages (:result (th/command! {::th/type :get-comments + ::rpc/profile-id (:id author) + :thread-id (:id thread)})) + first-id (:id (first (sort-by :created-at messages))) + from (fn [comment-id] + (create-task* author {:file-id branch-file-id + :page-id page-id + :thread-id (:id thread) + :comment-id comment-id}))] + + (t/testing "a thread holds a task per message" + (t/is (nil? (:error (from first-id)))) + (t/is (nil? (:error (from (:id reply))))) + (let [tasks (:result (th/command! {::th/type :get-file-tasks + ::rpc/profile-id (:id author) + :file-id branch-file-id}))] + (t/is (= #{first-id (:id reply)} (into #{} (map :comment-id) tasks))))) + + (t/testing "a message holds one task" + (t/is (= :comment-already-has-task (-> (from first-id) :error ex-data :code)))) + + (t/testing "a message of another thread is refused" + (let [other (:result (th/command! {::th/type :create-comment-thread + ::rpc/profile-id (:id author) + :file-id branch-file-id + :page-id page-id + :frame-id uuid/zero + :position (gpt/point 0) + :content "another one"})) + out (create-task* author {:file-id branch-file-id + :page-id page-id + :thread-id (:id other) + :comment-id (:id reply)})] + (t/is (= :comment-not-in-thread (-> out :error ex-data :code)))))))) + +(t/deftest task-on-the-canvas-keeps-its-position + (with-redefs [cf/flags (task-flags)] + (let [{:keys [author page-id branch-file-id]} (setup-review) + out (create-task* author {:file-id branch-file-id + :page-id page-id + :position (gpt/point 120 340)}) + task (:result out)] + (t/is (nil? (:error out))) + (t/is (nil? (:shape-id task))) + (let [[row] (:result (th/command! {::th/type :get-file-tasks + ::rpc/profile-id (:id author) + :file-id branch-file-id}))] + (t/is (= {:x 120.0 :y 340.0} (into {} (:position row))))) + (t/testing "a move of its state answers with the task" + (t/is (nil? (:error (set-status* author (:id task) "done")))))))) + +(t/deftest task-created-on-the-canvas-gets-a-thread + (with-redefs [cf/flags (task-flags) + eml/send-template (fn [_ _] nil)] + (let [{:keys [author reviewer page-id rect-id branch-file-id review]} (setup-review) + out (create-task* reviewer {:file-id branch-file-id + :page-id page-id + :shape-id rect-id + :position (gpt/point 30 40) + :title " Use the secondary token " + :pull-request-id (:id review)}) + task (:result out)] + (t/is (nil? (:error out))) + (t/is (some? (:thread-id task))) + (t/is (some? (:comment-id task))) + + (t/testing "the thread points at the layer of the task, in its review" + (let [thread (th/db-get :comment-thread {:id (:thread-id task)})] + (t/is (= branch-file-id (:file-id thread))) + (t/is (= (:id reviewer) (:owner-id thread))) + (t/is (= (:id review) (:pull-request-id thread))) + (t/is (= "layer" (:anchor-type thread))) + (t/is (= rect-id (:shape-id thread))))) + + (t/testing "its first message is the title and holds the task" + (let [[message] (:result (th/command! {::th/type :get-comments + ::rpc/profile-id (:id author) + :thread-id (:thread-id task)}))] + (t/is (= (:comment-id task) (:id message))) + (t/is (= "Use the secondary token" (:content message))))) + + (t/testing "anybody can go on commenting in it" + (let [out (th/command! {::th/type :create-comment + ::rpc/profile-id (:id author) + :thread-id (:thread-id task) + :content "On it"})] + (t/is (nil? (:error out))) + (t/is (= 2 (count (th/db-query :comment {:thread-id (:thread-id task)}))))))))) + +(t/deftest task-on-the-empty-canvas-gets-a-thread-on-its-spot + (with-redefs [cf/flags (task-flags)] + (let [{:keys [author page-id branch-file-id]} (setup-review) + task (:result (create-task* author {:file-id branch-file-id + :page-id page-id + :position (gpt/point 120 340)})) + thread (th/db-get :comment-thread {:id (:thread-id task)})] + (t/is (= "canvas" (:anchor-type thread))) + (t/is (nil? (:shape-id thread))) + (t/is (nil? (:pull-request-id thread))) + (t/is (= {:x 120.0 :y 340.0} (into {} (db/decode-pgpoint (:position thread)))))))) + +(t/deftest deleting-a-thread-deletes-its-tasks + (with-redefs [cf/flags (task-flags)] + (let [{:keys [author page-id branch-file-id]} (setup-review) + task (:result (create-task* author {:file-id branch-file-id :page-id page-id})) + other (:result (create-task* author {:file-id branch-file-id + :page-id page-id + :title "Another one"})) + out (th/command! {::th/type :delete-comment-thread + ::rpc/profile-id (:id author) + :id (:thread-id task)})] + (t/is (nil? (:error out))) + (t/is (nil? (th/db-get :comment-thread {:id (:thread-id task)}))) + (t/is (some? (:deleted-at (th/db-get :file-task {:id (:id task)} + {::db/remove-deleted false})))) + (t/is (= [(:id other)] + (mapv :id (:result (th/command! {::th/type :get-file-tasks + ::rpc/profile-id (:id author) + :file-id branch-file-id})))))))) diff --git a/common/src/app/common/files/review_activity.cljc b/common/src/app/common/files/review_activity.cljc new file mode 100644 index 0000000000..4a1791a688 --- /dev/null +++ b/common/src/app/common/files/review_activity.cljc @@ -0,0 +1,290 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. +;; +;; Copyright (c) KALEIDOS INC Sucursal en España SL + +(ns app.common.files.review-activity + "What the saves of a branch under design review did to its layers. + + The backend records one row per branch save while a review is open + (`file_pull_request_activity`). `entries` builds that row from the + change vector of the save and the file data before and after it: one + entry per touched layer, with the kind of change and, for a modified + layer, the value before and after of each property a person reads. + + The reading side folds those rows: `net-entries` gives what each layer + ends up as since the review opened (a layer added and then deleted is + no change at all), and `sessions` cuts the rows into the runs of saves + one person made in one sitting, the groups the activity list shows." + (:require + [app.common.data :as d] + [app.common.uuid :as uuid])) + +(def tracked-attrs + "The properties whose value before and after a modified entry keeps: + the ones a person reads in the review, plus the applied tokens, which + tell that a value now comes from a token." + #{:name :fills :strokes :r1 :r2 :r3 :r4 :x :y :width :height :rotation + :opacity :hidden :blocked :blend-mode :content :shadow :blur + :layout-gap :layout-padding :layout-flex-dir :layout-item-h-sizing + :layout-item-v-sizing :constraints-h :constraints-v :grow-type + :applied-tokens :parent-id}) + +(def ^:private derived-attrs + "The properties the editor recomputes from others. A save that touches + only these (the text position data recomputed after an edit, the + geometry kept in sync) is not a change a person made." + #{:position-data :selrect :points :transform :transform-inverse :touched}) + +;; --- Building a row + +(defn- add-touch + "Fold one more touch of a layer into what the save did to it so far." + [prev kind attrs] + (case [(:kind prev) kind] + [nil :added] {:kind :added} + [nil :deleted] {:kind :deleted} + [nil :modified] {:kind :modified :attrs attrs} + [:added :modified] prev + [:added :deleted] {:kind :dropped} + [:added :added] prev + [:modified :modified] (update prev :attrs into attrs) + [:modified :deleted] {:kind :deleted} + [:modified :added] prev + [:deleted :added] {:kind :modified :attrs #{}} + [:deleted :modified] {:kind :modified :attrs attrs} + [:deleted :deleted] prev + [:dropped :added] {:kind :added} + prev)) + +(defn- set-attrs + [operations] + (into #{} + (keep (fn [{:keys [type attr]}] + (when (= :set type) attr))) + operations)) + +(defn touched + "What `changes` did to each layer of a page: `{[page-id id] {:kind + :attrs}}`, `:kind` one of `:added`, `:modified`, `:deleted` and + `:attrs` the properties a modification set. Changes to component + definitions and to file-level assets are not layers of a page and are + left out." + [changes] + (->> changes + (reduce + (fn [acc {:keys [type page-id id] :as change}] + (if (nil? page-id) + acc + (case type + :add-obj + (update acc [page-id id] add-touch :added nil) + + :del-obj + (update acc [page-id id] add-touch :deleted nil) + + :mod-obj + (update acc [page-id id] add-touch :modified (set-attrs (:operations change))) + + :mov-objects + (reduce (fn [acc shape-id] + (update acc [page-id shape-id] add-touch :modified #{:parent-id})) + acc + (:shapes change)) + + acc))) + {}) + (into {} (remove (fn [[_ {:keys [kind]}]] (= :dropped kind)))))) + +(defn- get-object + [data page-id id] + (-> data + (get :pages-index) + (get page-id) + (get :objects) + (get id))) + +(defn- frame-name + [data page-id frame-id] + (when (and (some? frame-id) (not= uuid/zero frame-id)) + (:name (get-object data page-id frame-id)))) + +(defn collect-before + "The state before the save of every layer the save touches: the part + of each object `entries` needs, read from the file data the save + starts from. Only the touched layers are read, so a page the save does + not touch is never loaded." + [data touched] + (reduce-kv + (fn [acc [page-id id :as key] _] + (if-let [obj (get-object data page-id id)] + (assoc acc key (-> (select-keys obj tracked-attrs) + (assoc :type (:type obj)) + (assoc :frame-id (:frame-id obj)) + (assoc :frame-name (frame-name data page-id (:frame-id obj))))) + acc)) + {} + touched)) + +(defn- summary + [obj page-id id frame-name] + {:id id + :page-id page-id + :name (:name obj) + :type (:type obj) + :frame-id (:frame-id obj) + :frame-name frame-name}) + +(defn- attr-diff + [before after attrs] + (into {} + (keep (fn [attr] + (let [b (get before attr) + a (get after attr)] + (when (not= b a) + [attr [b a]])))) + (filter tracked-attrs attrs))) + +(defn- root-of-kind? + "Whether the layer is the top of what the save added (or deleted): a + layer whose parent was added in the same save comes with it, and the + entry of its parent stands for both." + [touched kind page-id parent-id] + (not= kind (get-in touched [[page-id parent-id] :kind]))) + +(defn entries + "The activity entries of one save, from the state `before` it + (`collect-before`), the file data `after` it and what it `touched`. + + Every layer gets one entry, except the root layer, the children of a + layer the same save added or deleted, and a layer whose only change is + one the editor derives (`derived-attrs`)." + [before after touched] + (into [] + (keep + (fn [[[page-id id :as key] {:keys [kind attrs]}]] + (when (not= uuid/zero id) + (let [prev (get before key) + obj (get-object after page-id id)] + (case kind + :added + (when (and (some? obj) + (root-of-kind? touched :added page-id (:parent-id obj))) + (-> (summary obj page-id id (frame-name after page-id (:frame-id obj))) + (assoc :kind :added))) + + :deleted + (when (and (some? prev) + (root-of-kind? touched :deleted page-id (:parent-id prev))) + (-> (summary prev page-id id (:frame-name prev)) + (assoc :kind :deleted))) + + :modified + (when (and (some? obj) (some? prev)) + (let [diff (attr-diff prev obj attrs)] + (when (or (seq diff) + (seq (remove derived-attrs attrs))) + (-> (summary obj page-id id (frame-name after page-id (:frame-id obj))) + (assoc :kind :modified) + (assoc :attrs diff))))) + + nil))))) + touched)) + +;; --- Reading the rows + +(defn- fold-entry + "Fold a later `entry` of a layer into what the layer is so far." + [prev {:keys [kind] :as entry}] + (case [(:kind prev) kind] + [nil :added] entry + [nil :deleted] entry + [nil :modified] entry + [:added :modified] (merge entry {:kind :added :attrs nil}) + [:added :deleted] nil + [:modified :modified] (assoc entry :attrs + (merge-with (fn [[b _] [_ a]] [b a]) + (:attrs prev) + (:attrs entry))) + [:modified :deleted] entry + [:deleted :added] (assoc entry :kind :modified :attrs {}) + [:deleted :modified] entry + entry)) + +(defn- drop-unchanged + "A modification undone later (the value is back where it was) is no + change: drop those attrs, and the entry when nothing else is left of + it and it never had a visible attr." + [{:keys [kind attrs] :as entry}] + (if (= :modified kind) + (let [attrs' (into {} (remove (fn [[_ [b a]]] (= b a))) attrs)] + (when (or (seq attrs') (empty? attrs)) + (assoc entry :attrs attrs'))) + entry)) + +(defn net-entries + "What each layer ends up as across `rows` (activity rows, each with + `:profile-id`, `:created-at` and `:entries`), oldest first: one entry + per layer, carrying who made its last change and when (`:profile-id`, + `:changed-at`). A layer added and then deleted is gone; a modified + property keeps its first value before and its last value after." + [rows] + (->> rows + (sort-by :created-at) + (reduce + (fn [acc {:keys [profile-id created-at entries]}] + (reduce + (fn [acc {:keys [page-id id] :as entry}] + (let [key [page-id id] + entry (assoc entry + :profile-id profile-id + :changed-at created-at) + next (fold-entry (get acc key) entry)] + (if (nil? next) + (dissoc acc key) + (assoc acc key next)))) + acc + entries)) + (d/ordered-map)) + (vals) + (keep drop-unchanged) + (sort-by :changed-at #(compare %2 %1)) + (vec))) + +(def default-session-gap-ms + "Two saves of the same person further apart than this, in + milliseconds, belong to different sittings." + (* 30 60 1000)) + +(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`." + ([rows] (sessions rows default-session-gap-ms)) + ([rows gap-ms] + (->> rows + (sort-by :created-at) + (reduce + (fn [acc {:keys [profile-id created-at] :as row}] + (let [last-session (peek acc)] + (if (and (some? last-session) + (= profile-id (:profile-id last-session)) + (<= (- (inst-ms created-at) (inst-ms (:end last-session))) gap-ms)) + (conj (pop acc) (-> last-session + (assoc :end created-at) + (update :rows conj row))) + (conj acc {:profile-id profile-id + :start created-at + :end created-at + :rows [row]})))) + []) + (keep (fn [{:keys [rows] :as session}] + (let [entries (net-entries rows)] + (when (seq entries) + (-> session + (dissoc :rows) + (assoc :entries entries)))))) + (reverse) + (vec)))) diff --git a/common/test/common_tests/files/review_activity_test.cljc b/common/test/common_tests/files/review_activity_test.cljc new file mode 100644 index 0000000000..540d644bca --- /dev/null +++ b/common/test/common_tests/files/review_activity_test.cljc @@ -0,0 +1,142 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. +;; +;; Copyright (c) KALEIDOS INC Sucursal en España SL + +(ns common-tests.files.review-activity-test + (:require + [app.common.files.review-activity :as ra] + [app.common.uuid :as uuid] + [clojure.test :as t])) + +(def ^:private page-id (uuid/custom 1 1)) +(def ^:private board-id (uuid/custom 2 1)) +(def ^:private button-id (uuid/custom 2 2)) +(def ^:private label-id (uuid/custom 2 3)) + +(defn- data + [& objects] + {:pages-index + {page-id + {:objects (into {uuid/zero {:id uuid/zero :type :frame :name "Root"}} + (map (juxt :id identity)) + objects)}}}) + +(def ^:private board + {:id board-id :type :frame :name "Checkout / Mobile" + :parent-id uuid/zero :frame-id uuid/zero}) + +(def ^:private button + {:id button-id :type :rect :name "Pay button" :r1 8 :height 48 + :parent-id board-id :frame-id board-id}) + +(def ^:private label + {:id label-id :type :text :name "Label" + :parent-id button-id :frame-id board-id}) + +(defn- save-entries + "The entries of a save that turns `before` into `after` with `changes`." + [before after changes] + (let [touched (ra/touched changes)] + (ra/entries (ra/collect-before before touched) after touched))) + +(t/deftest modified-layer-keeps-the-values-before-and-after + (let [after (assoc button :r1 12 :height 52) + entries (save-entries (data board button) + (data board after) + [{:type :mod-obj :page-id page-id :id button-id + :operations [{:type :set :attr :r1 :val 12} + {:type :set :attr :height :val 52}]}])] + (t/is (= [{:id button-id + :page-id page-id + :name "Pay button" + :type :rect + :frame-id board-id + :frame-name "Checkout / Mobile" + :kind :modified + :attrs {:r1 [8 12] :height [48 52]}}] + entries)))) + +(t/deftest added-group-gives-one-entry-for-its-top-layer + (let [entries (save-entries (data board) + (data board button label) + [{:type :add-obj :page-id page-id :id button-id + :frame-id board-id :obj button} + {:type :add-obj :page-id page-id :id label-id + :frame-id board-id :obj label}])] + (t/is (= [[button-id :added]] + (mapv (juxt :id :kind) entries))))) + +(t/deftest deleted-layer-keeps-its-name-and-board + (let [entries (save-entries (data board button) + (data board) + [{:type :del-obj :page-id page-id :id button-id}])] + (t/is (= [{:id button-id + :page-id page-id + :name "Pay button" + :type :rect + :frame-id board-id + :frame-name "Checkout / Mobile" + :kind :deleted}] + entries)))) + +(t/deftest layer-added-and-deleted-in-one-save-is-no-change + (let [entries (save-entries (data board) + (data board) + [{:type :add-obj :page-id page-id :id button-id + :frame-id board-id :obj button} + {:type :del-obj :page-id page-id :id button-id}])] + (t/is (empty? entries)))) + +(t/deftest derived-only-change-is-not-an-entry + (let [entries (save-entries (data board button) + (data board button) + [{:type :mod-obj :page-id page-id :id button-id + :operations [{:type :set :attr :position-data :val []}]}])] + (t/is (empty? entries)))) + +(t/deftest component-changes-are-left-out + (t/is (empty? (ra/touched [{:type :mod-obj :component-id (uuid/next) :id button-id + :operations [{:type :set :attr :r1 :val 4}]}])))) + +(defn- row + [profile-id ms entries] + {:profile-id profile-id + :created-at #?(:clj (java.time.Instant/ofEpochMilli ms) + :cljs (js/Date. ms)) + :entries entries}) + +(def ^:private ana (uuid/custom 9 1)) +(def ^:private marc (uuid/custom 9 2)) + +(def ^:private modified-entry + {:id button-id :page-id page-id :name "Pay button" :kind :modified}) + +(t/deftest net-entries-fold-the-values-across-saves + (let [rows [(row ana 1000 [(assoc modified-entry :attrs {:r1 [8 10]})]) + (row marc 2000 [(assoc modified-entry :attrs {:r1 [10 12]})])] + [entry & others] (ra/net-entries rows)] + (t/is (empty? others)) + (t/is (= {:r1 [8 12]} (:attrs entry))) + (t/is (= marc (:profile-id entry))))) + +(t/deftest net-entries-drop-a-layer-added-and-later-deleted + (let [rows [(row ana 1000 [{:id button-id :page-id page-id :kind :added}]) + (row ana 2000 [{:id button-id :page-id page-id :kind :deleted}])]] + (t/is (empty? (ra/net-entries rows))))) + +(t/deftest net-entries-drop-a-change-undone-later + (let [rows [(row ana 1000 [(assoc modified-entry :attrs {:r1 [8 12]})]) + (row ana 2000 [(assoc modified-entry :attrs {:r1 [12 8]})])]] + (t/is (empty? (ra/net-entries rows))))) + +(t/deftest sessions-cut-by-person-and-by-gap + (let [minute (* 60 1000) + rows [(row ana 0 [(assoc modified-entry :attrs {:r1 [8 10]})]) + (row ana (* 10 minute) [(assoc modified-entry :attrs {:r1 [10 12]})]) + (row marc (* 20 minute) [(assoc modified-entry :attrs {:r1 [12 14]})]) + (row marc (* 90 minute) [(assoc modified-entry :attrs {:r1 [14 16]})])] + result (ra/sessions rows)] + (t/is (= [marc marc ana] (mapv :profile-id result))) + (t/is (= {:r1 [8 12]} (-> result last :entries first :attrs))))) diff --git a/common/test/common_tests/runner.cljc b/common/test/common_tests/runner.cljc index 3f95ecaa54..c293cffe1b 100644 --- a/common/test/common_tests/runner.cljc +++ b/common/test/common_tests/runner.cljc @@ -31,6 +31,7 @@ [common-tests.files.helpers-test] [common-tests.files.page-diff-test] [common-tests.files.repair-test] + [common-tests.files.review-activity-test] [common-tests.files.shapes-builder-test] [common-tests.files.tokens-test] [common-tests.files.validate-test] @@ -147,6 +148,7 @@ 'common-tests.files.helpers-test 'common-tests.files.page-diff-test 'common-tests.files.repair-test + 'common-tests.files.review-activity-test 'common-tests.files.shapes-builder-test 'common-tests.files.tokens-test 'common-tests.files.validate-test diff --git a/frontend/playwright/ui/specs/pull-requests.spec.js b/frontend/playwright/ui/specs/pull-requests.spec.js index 14d484457a..9735caad4d 100644 --- a/frontend/playwright/ui/specs/pull-requests.spec.js +++ b/frontend/playwright/ui/specs/pull-requests.spec.js @@ -3,8 +3,9 @@ import { WorkspacePage } from "../pages/WorkspacePage"; const PR_ID = "c7ce0794-0992-8105-8004-38f280443999"; -const reviewTitle = (page) => - page.getByText("Reviewing the design review", { exact: true }); +// The review bar at the bottom of the canvas: the review's own chrome, +// which replaces the branch bar while a design review is open. +const reviewBar = (page) => page.getByRole("region", { name: "Design review" }); test.beforeEach(async ({ page }) => { await WorkspacePage.init(page); @@ -26,31 +27,37 @@ const setupPullRequestSandbox = async (workspacePage) => { }); }; -test("opening a file with pr-id shows the review sandbox banner", async ({ - page, -}) => { +test("opening a file with pr-id enters the design review", async ({ page }) => { const workspacePage = new WorkspacePage(page); await setupPullRequestSandbox(workspacePage); await workspacePage.goToWorkspace({ extraParams: `&pr-id=${PR_ID}` }); - await expect(reviewTitle(page)).toBeVisible(); - await expect(page.getByText("Checkout redesign").first()).toBeVisible(); + // the review bar names the review being read, and the header trades the + // file name for the title of the review + const bar = reviewBar(page); + await expect(bar).toBeVisible(); + await expect( + bar.getByText("Reviewing the design review", { exact: true }), + ).toBeVisible(); + await expect( + bar.getByText("Checkout redesign", { exact: true }), + ).toBeVisible(); + await expect(page.getByTitle("Review: Checkout redesign")).toBeVisible(); - // the route reads as two pills: the branch under review, then main - const banner = reviewTitle(page).locator("../../.."); - await expect(banner.getByText("checkout", { exact: true })).toBeVisible(); - await expect(banner.getByText("Main", { exact: true })).toBeVisible(); + // the essentials are visible buttons: the details, the verdict of an + // assigned reviewer, and the way out + await expect(bar.getByRole("button", { name: "Details" })).toBeVisible(); + await expect( + bar.getByRole("button", { name: "Submit review" }), + ).toBeVisible(); + await expect(bar.getByRole("button", { name: "Exit review" })).toBeVisible(); - // only the essential actions are visible buttons... - await expect(page.getByRole("button", { name: "Compare" })).toBeVisible(); - await expect(page.getByRole("button", { name: "Details" })).toBeHidden(); - - // ...the rest live behind the kebab menu - await banner.getByRole("button", { name: "Options" }).click(); - await expect(page.getByText("Details")).toBeVisible(); + // comparing, merging and cancelling live behind the kebab menu + await expect(bar.getByRole("button", { name: "Compare" })).toBeHidden(); + await bar.getByRole("button", { name: "Options" }).click(); + await expect(page.getByText("Compare", { exact: true })).toBeVisible(); await expect(page.getByText("Merge to main")).toBeVisible(); - await expect(page.getByText("Exit review")).toBeVisible(); - await expect(page.getByText("Try interactions")).toBeHidden(); + await expect(page.getByText("Cancel review")).toBeVisible(); }); test("the compare dialog shows the proposed changes", async ({ page }) => { @@ -58,7 +65,9 @@ test("the compare dialog shows the proposed changes", async ({ page }) => { await setupPullRequestSandbox(workspacePage); await workspacePage.goToWorkspace({ extraParams: `&pr-id=${PR_ID}` }); - await page.getByRole("button", { name: "Compare" }).click(); + // comparing is one of the review bar's options + await reviewBar(page).getByRole("button", { name: "Options" }).click(); + await page.getByText("Compare", { exact: true }).click(); // the branching compare dialog is reused to inspect the changes await expect(page.getByText("Review changes")).toBeVisible(); @@ -69,7 +78,7 @@ test("accepting the pull request opens the merge dialog", async ({ page }) => { await setupPullRequestSandbox(workspacePage); await workspacePage.goToWorkspace({ extraParams: `&pr-id=${PR_ID}` }); - const banner = reviewTitle(page).locator("../../.."); + const banner = reviewBar(page); await banner.getByRole("button", { name: "Options" }).click(); await page.getByText("Merge to main").click(); @@ -78,33 +87,60 @@ test("accepting the pull request opens the merge dialog", async ({ page }) => { await expect(page.getByText("checkout").first()).toBeVisible(); }); -test("the review behaves like a normal, editable file", async ({ page }) => { +test("the review is read-only", async ({ page }) => { const workspacePage = new WorkspacePage(page); await setupPullRequestSandbox(workspacePage); await workspacePage.goToWorkspace({ extraParams: `&pr-id=${PR_ID}` }); - await expect(reviewTitle(page)).toBeVisible(); - // the file is the live branch, opened normally: the design toolbar is - // available so reviewers can try and validate anything... - await expect(workspacePage.rectShapeButton).toBeVisible(); - // ...and none of the read-only / inspect affordances kick in - await expect(page.getByText("Inspecting code")).toBeHidden(); - await expect(page.getByText("View only")).toBeHidden(); + await expect(reviewBar(page)).toBeVisible(); + + // the review toolbar replaces the design tools: moving around, + // commenting and tasks only, so the canvas offers no way to draw + const toolbar = page.getByRole("toolbar", { name: "Review tools" }); + await expect(toolbar).toBeVisible(); + for (const tool of [ + "Move", + "Comment", + "Comment an area", + "Create a task", + "Show changes", + ]) { + await expect( + toolbar.getByRole("button", { name: tool, exact: true }), + ).toBeVisible(); + } + await expect(workspacePage.rectShapeButton).toBeHidden(); + + // and the sidebar flags the file as view only + await expect(page.getByText("View only")).toBeVisible(); + + // the right panel is the review's: the inspect of the selection, the + // comments and the tasks of the review + await expect(page.getByRole("tab", { name: "Inspect" })).toBeVisible(); + await expect(page.getByRole("tab", { name: "Comments (0)" })).toBeVisible(); + await expect(page.getByRole("tab", { name: "Tasks (0)" })).toBeVisible(); }); -test("an assigned reviewer can submit a verdict from the banner", async ({ +test("an assigned reviewer can submit a verdict from the review bar", async ({ page, }) => { const workspacePage = new WorkspacePage(page); await setupPullRequestSandbox(workspacePage); await workspacePage.goToWorkspace({ extraParams: `&pr-id=${PR_ID}` }); - // the logged-in profile is an assigned reviewer in the fixture - await page.getByRole("button", { name: "Review", exact: true }).click(); + // the logged-in profile is an assigned reviewer in the fixture, so the + // bar offers the verdict + const bar = reviewBar(page); + await bar.getByRole("button", { name: "Submit review" }).click(); - await expect(page.getByText("Submit review").first()).toBeVisible(); - await page.getByText("Request changes", { exact: true }).click(); - await page.getByRole("button", { name: "Submit review" }).click(); + const dialog = page.getByRole("dialog"); + await expect(dialog).toBeVisible(); + await expect( + dialog.getByRole("heading", { name: "Submit review" }), + ).toBeVisible(); + + await dialog.getByRole("button", { name: "Request changes" }).click(); + await dialog.getByRole("button", { name: "Submit review" }).click(); await expect(page.getByText("Review submitted")).toBeVisible(); }); @@ -118,7 +154,7 @@ test("closing the pull request asks for confirmation", async ({ page }) => { ); await workspacePage.goToWorkspace({ extraParams: `&pr-id=${PR_ID}` }); - const banner = reviewTitle(page).locator("../../.."); + const banner = reviewBar(page); await banner.getByRole("button", { name: "Options" }).click(); await page.getByText("Cancel review").click(); @@ -164,15 +200,15 @@ test("exiting the review takes the user back to the file", async ({ page }) => { await setupPullRequestSandbox(workspacePage); await workspacePage.goToWorkspace({ extraParams: `&pr-id=${PR_ID}` }); - await expect(reviewTitle(page)).toBeVisible(); - const banner = reviewTitle(page).locator("../../.."); + const banner = reviewBar(page); + await expect(banner).toBeVisible(); await banner.getByRole("button", { name: "Options" }).click(); await page.getByText("Exit review").click(); // exiting drops the review context and the pr-id param; the file (the // live branch) stays as it was await expect(page).not.toHaveURL(/pr-id/); - await expect(reviewTitle(page)).toBeHidden(); + await expect(reviewBar(page)).toBeHidden(); }); test("during a review the header names the branch under review", async ({ @@ -187,9 +223,9 @@ test("during a review the header names the branch under review", async ({ ); await workspacePage.goToWorkspace({ extraParams: `&pr-id=${PR_ID}` }); - // the review banner replaces the branch banner, so the header loads the + // the review bar replaces the branch bar, so the header loads the // branch context itself - await expect(reviewTitle(page)).toBeVisible(); + await expect(reviewBar(page)).toBeVisible(); await expect(page.getByTitle("On branch checkout from main")).toBeVisible(); }); diff --git a/frontend/resources/images/cursors/create-task.svg b/frontend/resources/images/cursors/create-task.svg new file mode 100644 index 0000000000..113a7ca3de --- /dev/null +++ b/frontend/resources/images/cursors/create-task.svg @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/frontend/resources/images/icons/comment-area.svg b/frontend/resources/images/icons/comment-area.svg new file mode 100644 index 0000000000..2132801c5a --- /dev/null +++ b/frontend/resources/images/icons/comment-area.svg @@ -0,0 +1,3 @@ + + + diff --git a/frontend/src/app/main/data/changes.cljs b/frontend/src/app/main/data/changes.cljs index e114ed26b7..6a0d8f6540 100644 --- a/frontend/src/app/main/data/changes.cljs +++ b/frontend/src/app/main/data/changes.cljs @@ -298,13 +298,15 @@ features (get state :features) permissions (get state :permissions)] - ;; Historical previews must not create edits to the live file. Check - ;; this when creating commits so previously queued edits can still save. - ;; While saves fail, a user edit would queue behind the failed save. - ;; Refusals answer with an empty stream (never nil) so callers can - ;; uniformly subscribe and observe termination. + ;; Historical previews must not create edits to the live file, and + ;; a design review is read-only (the branch is edited outside it). + ;; Check this when creating commits so previously queued edits can + ;; still save. While saves fail, a user edit would queue behind the + ;; failed save. Refusals answer with an empty stream (never nil) so + ;; callers can uniformly subscribe and observe termination. (if (and (:can-edit permissions) (not (dm/get-in state [:workspace-global :preview-id])) + (not (contains? state :workspace-pr-preview)) (or ignore-save-lock (not (plk/locked? state)))) (do (log/trace :hint "commit-changes" :redo-changes redo-changes) diff --git a/frontend/src/app/main/data/workspace.cljs b/frontend/src/app/main/data/workspace.cljs index 6764e3e86e..659a46be9b 100644 --- a/frontend/src/app/main/data/workspace.cljs +++ b/frontend/src/app/main/data/workspace.cljs @@ -689,6 +689,8 @@ ;; --- Layout Flags (dm/export layout/toggle-layout-flag) +(dm/export layout/open-bottom-bar) +(dm/export layout/toggle-bottom-bar) (dm/export layout/remove-layout-flag) ;; --- Profile diff --git a/frontend/src/app/main/data/workspace/branches.cljs b/frontend/src/app/main/data/workspace/branches.cljs index 725a388849..c0260171ab 100644 --- a/frontend/src/app/main/data/workspace/branches.cljs +++ b/frontend/src/app/main/data/workspace/branches.cljs @@ -753,6 +753,8 @@ resolve conflicts before integrating. - `:comment` — what the user says about the merge, kept with its record and shown in the reviews dialog. + - `:notify-assignees` — tell the assignees of the open tasks of the + branch, by email, that the merge moved their tasks into main. - `:excluded` — the per-change selection (change keys, `app.common.files.branch-merge/change-key`) naming the changes the user deselected, which main keeps its own value for. @@ -764,7 +766,7 @@ before that diff has loaded carry the revn of the conflict answer instead (`conflict-main-revn`). Unresolved conflicts open the resolution modal." ([branch] (merge-branch branch nil)) - ([branch {:keys [resolutions comment excluded]}] + ([branch {:keys [resolutions comment excluded notify-assignees]}] (assert (uuid? (:id branch)) "expected a branch row with a valid `:id`") (ptk/reify ::merge-branch ptk/WatchEvent @@ -781,6 +783,7 @@ (cond-> {:branch-id branch-id} (seq resolutions) (assoc :resolutions resolutions) (seq excluded) (assoc :excluded excluded) + notify-assignees (assoc :notify-assignees true) (not (str/blank? comment)) (assoc :comment (str/trim comment)) (some? main-revn) (assoc :expected-main-revn main-revn))) (rx/mapcat diff --git a/frontend/src/app/main/data/workspace/comments.cljs b/frontend/src/app/main/data/workspace/comments.cljs index 656fdaa651..3bfb1b2711 100644 --- a/frontend/src/app/main/data/workspace/comments.cljs +++ b/frontend/src/app/main/data/workspace/comments.cljs @@ -25,6 +25,8 @@ [app.main.data.workspace.drawing :as dwd] [app.main.data.workspace.edition :as dwe] [app.main.data.workspace.layout :as dwlo] + [app.main.data.workspace.review :as dwrv] + [app.main.data.workspace.tasks :as dwtk] [app.main.data.workspace.viewport-wasm :as dwvw] [app.main.data.workspace.zoom :as dwz] [app.main.repo :as rp] @@ -82,6 +84,10 @@ (cond (:draft local) (rx/of (dcmt/close-thread)) (:open local) (rx/of (dcmt/close-thread)) + (some? (get-in state [:workspace-tasks-local :new])) + (rx/of (dwtk/cancel-new-task)) + (some? (get-in state [:workspace-tasks-local :open])) + (rx/of (dwtk/close-task)) (:expanded local) (rx/of (dcmt/collapse-comment-group)) ;; Only clear edition / deselect on interrupt while the comments ;; tool is active. When comments are merely visible during design, @@ -114,6 +120,23 @@ (some? (:open local)) (rx/of (dcmt/close-thread)) + (some? (get-in state [:workspace-tasks-local :new])) + (rx/of (dwtk/cancel-new-task)) + + (some? (get-in state [:workspace-tasks-local :open])) + (rx/of (dwtk/close-task)) + + ;; inside a design review the review tool says what a click does; + ;; the area tool draws with the pointer instead + (dwrv/reviewing? state) + (if (= :comment-area (dwrv/get-tool state)) + (rx/empty) + (rx/of (dwrv/handle-canvas-click position))) + + ;; outside a review, "New task" arms the task tool for one click + (= :task (dwrv/get-tool state)) + (rx/of (dwrv/handle-canvas-click position)) + :else (let [page-id (:current-page-id state) file-id (:current-file-id state) diff --git a/frontend/src/app/main/data/workspace/layout.cljs b/frontend/src/app/main/data/workspace/layout.cljs index c0f1a125c2..2199750ebc 100644 --- a/frontend/src/app/main/data/workspace/layout.cljs +++ b/frontend/src/app/main/data/workspace/layout.cljs @@ -122,6 +122,45 @@ (let [flags (:workspace-layout state)] (persist-layout-flags! flags))))) +;; --- The bars at the bottom of the canvas of a branch + +;; A branch has two bars at the same level, the one of the branch and the +;; palettes, and only one of them is open at a time. `:bottom-bar` says which: +;; `:branch`, `:palette` or `:none`. It only exists while the bar of the branch +;; is there: without it the palettes follow their own layout flags. + +(defn mount-bottom-bars + "The bar of the branch is there, and comes open." + [] + (ptk/reify ::mount-bottom-bars + ptk/UpdateEvent + (update [_ state] + (assoc-in state [:workspace-global :bottom-bar] :branch)))) + +(defn unmount-bottom-bars + [] + (ptk/reify ::unmount-bottom-bars + ptk/UpdateEvent + (update [_ state] + (update state :workspace-global dissoc :bottom-bar)))) + +(defn open-bottom-bar + "Open `bar`, which folds the other one." + [bar] + (ptk/reify ::open-bottom-bar + ptk/UpdateEvent + (update [_ state] + (d/update-in-when state [:workspace-global :bottom-bar] (constantly bar))))) + +(defn toggle-bottom-bar + "Open `bar`, or fold it when it is open and leave both folded." + [bar] + (ptk/reify ::toggle-bottom-bar + ptk/UpdateEvent + (update [_ state] + (d/update-in-when state [:workspace-global :bottom-bar] + #(if (= bar %) :none bar))))) + (defn set-options-mode [mode] (dm/assert! diff --git a/frontend/src/app/main/data/workspace/notifications.cljs b/frontend/src/app/main/data/workspace/notifications.cljs index 2c07fb1962..5abddee2d4 100644 --- a/frontend/src/app/main/data/workspace/notifications.cljs +++ b/frontend/src/app/main/data/workspace/notifications.cljs @@ -25,6 +25,7 @@ [app.main.data.workspace.layout :as dwly] [app.main.data.workspace.libraries :as dwl] [app.main.data.workspace.pull-requests :as dwpr] + [app.main.data.workspace.tasks :as dwtk] [app.main.data.workspace.texts :as dwt] [app.main.router :as rt] [app.util.globals :refer [global]] @@ -169,6 +170,7 @@ :pull-request-updated (handle-pull-request-change msg) :pull-request-review-submitted (handle-pull-request-change msg) :pull-request-closed (handle-pull-request-change msg) + :file-tasks-change (dwtk/handle-tasks-change msg) :notification (dc/handle-notification msg) :team-role-change (handle-change-team-role msg) :team-membership-change (dc/team-membership-change msg) diff --git a/frontend/src/app/main/data/workspace/pull_requests.cljs b/frontend/src/app/main/data/workspace/pull_requests.cljs index 5bd2bd6d19..04e38d9be4 100644 --- a/frontend/src/app/main/data/workspace/pull_requests.cljs +++ b/frontend/src/app/main/data/workspace/pull_requests.cljs @@ -15,9 +15,12 @@ `app.main.data.workspace.branches`." (:require [app.config :as cf] + [app.main.data.comments :as dcmt] [app.main.data.event :as ev] [app.main.data.notifications :as ntf] [app.main.data.persistence :as dwp] + [app.main.data.workspace.drawing.common :as dwdc] + [app.main.data.workspace.layout :as dwl] [app.main.repo :as rp] [app.main.router :as rt] [app.util.i18n :refer [tr]] @@ -159,7 +162,8 @@ (defn update-pull-request-snapshot "Publish the branch's current state to the reviewers (repositions the review snapshot). When the branch is the currently open file, pending - local changes are force-persisted first." + local changes are force-persisted first. Once published, the review + open in the workspace learns it is up to date." [id] (assert (uuid? id) "expected valid uuid for `id`") (ptk/reify ::update-pull-request-snapshot @@ -178,7 +182,8 @@ (rx/of (if updated (ntf/success (tr "workspace.pull-requests.publish.success")) (ntf/info (tr "workspace.pull-requests.publish.up-to-date"))) - (fetch-pull-requests)))) + (fetch-pull-requests) + (refresh-pull-request-preview-info id)))) (rx/catch (fn [_] (rx/of (ntf/error (tr "workspace.pull-requests.lifecycle.error"))))))))))) @@ -311,13 +316,15 @@ (ptk/reify ::exit-pull-request-preview ptk/UpdateEvent (update [_ state] - (dissoc state :workspace-pr-preview)) + (dissoc state :workspace-pr-preview :workspace-review-local :workspace-review-activity)) ptk/WatchEvent (watch [_ state _] (let [params (-> (rt/get-params state) (dissoc :pr-id))] - (rx/of (rt/nav :workspace params)))))) + (rx/of (dwdc/clear-drawing) + (dcmt/close-thread) + (rt/nav :workspace params)))))) (defn- enter-pull-request-preview "Worker for `initialize-pull-request-preview`: load the pull request @@ -353,7 +360,12 @@ (rx/of (exit-pull-request-preview)) :else - (rx/of (set-pull-request-preview {:status :loaded :info info}))))) + (rx/of (set-pull-request-preview {:status :loaded :info info}) + ;; the review opens on the inspect of the selection: + ;; the move tool picks layers, and the comments and + ;; tasks show on the canvas + (dwdc/clear-drawing) + (dwl/toggle-layout-flag :display-comments :force? true))))) (rx/catch (fn [_] (rx/of (ntf/warn (tr "workspace.pull-requests.preview.unavailable")) diff --git a/frontend/src/app/main/data/workspace/review.cljs b/frontend/src/app/main/data/workspace/review.cljs new file mode 100644 index 0000000000..d83410d16f --- /dev/null +++ b/frontend/src/app/main/data/workspace/review.cljs @@ -0,0 +1,341 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. +;; +;; Copyright (c) KALEIDOS INC Sucursal en España SL + +(ns app.main.data.workspace.review + "Data layer of the review mode: what the reviewer does inside a design + review. The review is read-only (the branch is edited outside it), so + the toolbar offers only the review tools: move around, comment on a + spot or a layer, comment on an area, create a task, and show the + changes of the branch on the canvas. + + `: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, one row per + save of the branch since the review opened." + (:require + [app.common.files.review-activity :as ra] + [app.common.geom.point :as gpt] + [app.common.uuid :as uuid] + [app.main.data.comments :as dcmt] + [app.main.data.helpers :as dsh] + [app.main.data.modal :as modal] + [app.main.data.workspace.common :as dwc] + [app.main.data.workspace.drawing :as dwd] + [app.main.data.workspace.drawing.common :as dwdc] + [app.main.data.workspace.layout :as dwl] + [app.main.data.workspace.tasks :as dwtk] + [app.main.repo :as rp] + [app.main.router :as rt] + [beicon.v2.core :as rx] + [potok.v2.core :as ptk])) + +(def tools + #{:move :comment :comment-area :task}) + +(defn reviewing? + [state] + (some? (:workspace-pr-preview state))) + +(defn review-id + "The id of the design review open now." + [state] + (get-in state [:workspace-pr-preview :pr-id])) + +;; --- Tools + +(defn- forget-task-tool + [] + (ptk/reify ::forget-task-tool + ptk/UpdateEvent + (update [_ state] + (update state :workspace-review-local dissoc :tool)))) + +(defn set-tool + "Use one of the review `tools`. The commenting tools and the task tool + take the clicks of the canvas, so they all ride on the comments drawing + tool; the review tool says what a click does." + [tool] + (assert (contains? tools tool) "expected a review tool") + (ptk/reify ::set-tool + ptk/UpdateEvent + (update [_ state] + (-> state + (update :workspace-review-local assoc :tool tool) + (update :comments-local dissoc :draft))) + + ptk/WatchEvent + (watch [_ state stream] + (if (= tool :move) + (rx/of (dwdc/clear-drawing)) + ;; what the tool makes must be seen: comments and tasks show + (rx/merge + (rx/of (dwd/select-for-drawing :comments) + (dwl/toggle-layout-flag :display-comments :force? true)) + ;; outside a review the task tool is for one task: leaving it + ;; gives the clicks back to the comments + (when (and (= tool :task) (not (reviewing? state))) + (->> stream + (rx/filter #(or (dwc/interrupt? %) + (ptk/type? ::dwdc/clear-drawing %))) + (rx/take 1) + (rx/map (fn [_] (forget-task-tool)))))))))) + +(defn get-tool + [state] + (if (= :comments (get-in state [:workspace-drawing :tool])) + (get-in state [:workspace-review-local :tool] :comment) + :move)) + +;; --- Panel + +(defn set-panel-tab + [tab] + (assert (contains? #{:inspect :comments :tasks} tab) "expected a panel tab") + (ptk/reify ::set-panel-tab + ptk/UpdateEvent + (update [_ state] + (update state :workspace-review-local assoc :panel-tab tab)))) + +(defn set-task-filter + [filter] + (assert (contains? #{:all :open :mine :to-verify} filter) "expected a task filter") + (ptk/reify ::set-task-filter + ptk/UpdateEvent + (update [_ state] + (update state :workspace-review-local assoc :task-filter filter)))) + +(def task-statuses + "The states a task can be in, in the order the filters show them." + ["open" "done" "reopened" "verified" "wont-do"]) + +(defn set-task-status-filter + "Show the tasks of the details of a review in one state (`:all` for + every one)." + [status] + (assert (or (= :all status) (contains? (set task-statuses) status)) + "expected a task status or :all") + (ptk/reify ::set-task-status-filter + ptk/UpdateEvent + (update [_ state] + (update state :workspace-review-local assoc :task-status-filter status)))) + +(defn toggle-hide-closed-tasks + [] + (ptk/reify ::toggle-hide-closed-tasks + ptk/UpdateEvent + (update [_ state] + (update-in state [:workspace-review-local :hide-closed-tasks] not)))) + +;; --- Creating from the canvas + +(defn- draft-params + [state position] + {:position position + :page-id (:current-page-id state) + :file-id (:current-file-id state)}) + +(defn handle-canvas-click + "A click on the canvas with a review tool: the comment tool starts a + thread on the layer under the pointer (on the spot of the board when + there is no layer), the task tool starts a task on that layer. The + area tool draws with the pointer instead (`start-area-comment`). + Outside a review the task tool is also in use for one click." + [position] + (ptk/reify ::handle-canvas-click + ptk/WatchEvent + (watch [_ state _] + (let [page-id (:current-page-id state) + objects (dsh/lookup-page-objects state page-id) + shape (dwtk/shape-at-position objects position) + pr-id (review-id state)] + (case (get-tool state) + :comment + (rx/of (dcmt/create-draft + (cond-> (assoc (draft-params state position) :pull-request-id pr-id) + (and (some? shape) (not= :frame (:type shape))) + (assoc :anchor {:type :layer :shape-id (:id shape)}) + + (or (nil? shape) (= :frame (:type shape))) + (assoc :anchor {:type :canvas})))) + + ;; on the empty canvas the task points at the canvas itself + :task + (rx/concat + (rx/of (dwtk/start-new-task + {:page-id page-id + :frame-id (cond + (nil? shape) uuid/zero + (= :frame (:type shape)) (:id shape) + :else (:frame-id shape)) + :shape-id (:id shape) + :position position + :pull-request-id pr-id})) + (if (nil? pr-id) + (rx/of (forget-task-tool)) + (rx/empty))) + + (rx/empty)))))) + +(defn create-area-draft + "The pointer drew `area` (canvas coordinates) with the area tool: start + a thread on it. The thread sits at the top right corner of the area, + just inside it so it belongs to the board the area is on." + [{:keys [x y width] :as area}] + (ptk/reify ::create-area-draft + ptk/WatchEvent + (watch [_ state _] + (let [position {:x (- (+ x width) 1) :y (+ y 1)}] + (rx/of (dcmt/create-draft + (-> (draft-params state (gpt/point position)) + (assoc :pull-request-id (review-id state)) + (assoc :anchor {:type :area :area area})))))))) + +;; --- Activity + +(defn- activity-fetched + [pr-id rows] + (ptk/reify ::activity-fetched + ptk/UpdateEvent + (update [_ state] + (assoc state :workspace-review-activity + {:pr-id pr-id + :status :loaded + :rows rows + :entries (ra/net-entries rows) + :sessions (ra/sessions rows)})))) + +(defn fetch-activity + "Load what the saves of the branch did since the review `pr-id` opened." + [pr-id] + (assert (uuid? pr-id) "expected a valid uuid for `pr-id`") + (ptk/reify ::fetch-activity + ptk/UpdateEvent + (update [_ state] + (if (= pr-id (get-in state [:workspace-review-activity :pr-id])) + state + (assoc state :workspace-review-activity {:pr-id pr-id :status :loading}))) + + ptk/WatchEvent + (watch [_ _ _] + (->> (rp/cmd! :get-pull-request-activity {:id pr-id}) + (rx/map (partial activity-fetched pr-id)) + (rx/catch (fn [_] + (rx/of (fn [state] + (assoc state :workspace-review-activity + {:pr-id pr-id :status :error}))))))))) + +;; --- Details + +(defn open-details + "Open the details of the review on `tab` (\"overview\", \"activity\" or + \"tasks\")." + ([] (open-details "overview")) + ([tab] + (ptk/reify ::open-details + ptk/WatchEvent + (watch [_ state _] + (if-let [pr (get-in state [:workspace-pr-preview :info])] + (rx/of (modal/show :review-details {:pr pr :tab tab})) + (rx/empty)))))) + +;; --- Changes on the canvas + +(defn- change-entries + [state] + (let [filter (get-in state [:workspace-review-local :change-filter] :all)] + (cond->> (get-in state [:workspace-review-activity :entries]) + (not= :all filter) (filterv #(= filter (:kind %)))))) + +(defn set-change-filter + [filter] + (assert (contains? #{:all :added :modified :deleted} filter) "expected a change filter") + (ptk/reify ::set-change-filter + ptk/UpdateEvent + (update [_ state] + (update state :workspace-review-local assoc :change-filter filter)))) + +(defn- center-on-entry + [{:keys [page-id id] :as entry}] + (ptk/reify ::center-on-entry + ptk/WatchEvent + (watch [_ state _] + (rx/concat + (if (not= page-id (:current-page-id state)) + (rx/of (rt/nav :workspace (assoc (rt/get-params state) :page-id page-id) + {::rt/replace true})) + (rx/empty)) + (->> (rx/of (dwtk/center-to-task {:page-id page-id + :shape-id id + :frame-id (:frame-id entry)})) + (rx/observe-on :async)))))) + +(defn show-change + "Show the changes of the branch on the canvas, with the one at `index` + (of the filtered activity) in front, and take the viewport to it." + [index] + (ptk/reify ::show-change + ptk/UpdateEvent + (update [_ state] + (let [total (count (change-entries state)) + index (if (pos? total) (mod index total) 0)] + (update state :workspace-review-local assoc :show-changes {:index index}))) + + ptk/WatchEvent + (watch [_ state _] + (let [index (get-in state [:workspace-review-local :show-changes :index])] + (if-let [entry (get (change-entries state) index)] + (rx/of (modal/hide) + (center-on-entry entry)) + (rx/of (modal/hide))))))) + +(defn show-change-of + "Show on the canvas the change of the layer `id`." + [id] + (ptk/reify ::show-change-of + ptk/WatchEvent + (watch [_ state _] + (let [entries (change-entries state) + index (or (first (keep-indexed (fn [i e] (when (= id (:id e)) i)) entries)) 0)] + (rx/of (show-change index)))))) + +(declare hide-changes) + +(defn toggle-changes + "The show changes tool: show the changes on the canvas, or stop." + [] + (ptk/reify ::toggle-changes + ptk/WatchEvent + (watch [_ state _] + (if (some? (get-in state [:workspace-review-local :show-changes])) + (rx/of (hide-changes)) + (let [pr-id (review-id state)] + (rx/concat + (if (some? pr-id) (rx/of (fetch-activity pr-id)) (rx/empty)) + (rx/of (fn [state] + (update state :workspace-review-local assoc :show-changes {:index 0}))))))))) + +(defn hide-changes + [] + (ptk/reify ::hide-changes + ptk/UpdateEvent + (update [_ state] + (update state :workspace-review-local dissoc :show-changes)))) + +(defn back-to-details + "Leave the changes on the canvas and go back to the activity." + [] + (ptk/reify ::back-to-details + ptk/WatchEvent + (watch [_ _ _] + (rx/of (hide-changes) + (open-details "activity"))))) + +(defn reset-review-local + [] + (ptk/reify ::reset-review-local + ptk/UpdateEvent + (update [_ state] + (dissoc state :workspace-review-local :workspace-review-activity)))) diff --git a/frontend/src/app/main/data/workspace/shapes.cljs b/frontend/src/app/main/data/workspace/shapes.cljs index 82691dfad9..c87d779a5e 100644 --- a/frontend/src/app/main/data/workspace/shapes.cljs +++ b/frontend/src/app/main/data/workspace/shapes.cljs @@ -26,6 +26,7 @@ [app.main.data.workspace.reflow :as wrf] [app.main.data.workspace.reflow.signals :as wrfs] [app.main.data.workspace.selection :as dws] + [app.main.data.workspace.tasks :as dwtk] [app.main.data.workspace.undo :as dwu] [beicon.v2.core :as rx] [potok.v2.core :as ptk])) @@ -401,6 +402,8 @@ (wrf/cancel-shapes! deleted-ids) (rx/of (dwu/start-undo-transaction undo-id) (dc/detach-comment-thread ids) + ;; the open tasks of the deleted layers move to their board + (dwtk/handle-deleted-shapes objects ids) (dch/commit-changes changes) (ptk/data-event :layout/update {:ids all-parents :undo-group (:undo-group options)}) (dwu/commit-undo-transaction undo-id))))))) diff --git a/frontend/src/app/main/data/workspace/shortcuts.cljs b/frontend/src/app/main/data/workspace/shortcuts.cljs index 0adf37788b..b322ae01a0 100644 --- a/frontend/src/app/main/data/workspace/shortcuts.cljs +++ b/frontend/src/app/main/data/workspace/shortcuts.cljs @@ -674,6 +674,7 @@ :section [:workspace] :fn #(do (r/set-resize-type! :bottom) (emit-when-no-readonly (dw/remove-layout-flag :hide-palettes) + (dw/open-bottom-bar :palette) (dw/remove-layout-flag :textpalette) (toggle-layout-flag :colorpalette)))} @@ -684,6 +685,7 @@ :section [:workspace] :fn #(do (r/set-resize-type! :bottom) (emit-when-no-readonly (dw/remove-layout-flag :hide-palettes) + (dw/open-bottom-bar :palette) (dw/remove-layout-flag :colorpalette) (toggle-layout-flag :textpalette)))} diff --git a/frontend/src/app/main/data/workspace/tasks.cljs b/frontend/src/app/main/data/workspace/tasks.cljs new file mode 100644 index 0000000000..e35d96277c --- /dev/null +++ b/frontend/src/app/main/data/workspace/tasks.cljs @@ -0,0 +1,652 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. +;; +;; Copyright (c) KALEIDOS INC Sucursal en España SL + +(ns app.main.data.workspace.tasks + "Data layer for tasks: a piece of work on a file, assigned to someone + and tied to a layer. Every task lives in a message of a comment thread, + so its thread can go on (a thread may hold several tasks): a task made + from a message keeps that thread, and a task created on the canvas gets + a thread whose first message is its title. A task may also belong to a + design review. + + The tasks of the open file live in `:workspace-tasks`, the events of a + task (what the thread of the task shows between its comments) in + `:workspace-task-events`, and what the user is doing with them (the + task open on the canvas, the new task being written, the task being + linked to another layer) in `:workspace-tasks-local`." + (:require + [app.common.data :as d] + [app.common.data.macros :as dm] + [app.common.files.changes-builder :as pcb] + [app.common.files.helpers :as cfh] + [app.common.geom.point :as gpt] + [app.common.geom.shapes :as gsh] + [app.common.types.shape-tree :as ctst] + [app.common.uuid :as uuid] + [app.config :as cf] + [app.main.data.changes :as dch] + [app.main.data.comments :as dcmt] + [app.main.data.event :as ev] + [app.main.data.helpers :as dsh] + [app.main.data.notifications :as ntf] + [app.main.data.workspace.undo :as dwu] + [app.main.data.workspace.viewport-wasm :as dwvw] + [app.main.repo :as rp] + [app.main.router :as rt] + [app.util.i18n :refer [tr]] + [beicon.v2.core :as rx] + [cuerdas.core :as str] + [potok.v2.core :as ptk])) + +(defn enabled? + "Tasks ride on the branching feature, like design reviews." + [] + (contains? cf/flags :branching)) + +;; --- Task predicates + +(def closed-statuses + "A closed task is finished: verified, or dropped as won't do." + #{"verified" "wont-do"}) + +(defn closed? + [task] + (contains? closed-statuses (:status task))) + +(defn to-do? + "The task needs work: open or reopened." + [task] + (contains? #{"open" "reopened"} (:status task))) + +(defn to-verify? + "The task is done and waits for someone to verify it." + [task] + (= "done" (:status task))) + +(defn lost? + "The layer of the task was deleted." + [task] + (some? (:lost-shape-name task))) + +(defn history? + "The task came with a merged branch and is already closed: it is part + of the history of that branch, not of the work on this file." + [task] + (and (some? (:merge-id task)) (closed? task))) + +(defn get-tasks-of-thread + "The tasks a comment thread is attached to, oldest first." + [tasks thread-id] + (->> (vals tasks) + (filter #(= thread-id (:thread-id %))) + (sort-by :created-at))) + +(defn get-task-of-comment + "The task a message of a comment thread became, if any." + [tasks comment-id] + (d/seek #(= comment-id (:comment-id %)) (vals tasks))) + +;; --- Locating a task on the canvas + +(defn shape-at-position + "The topmost visible layer under `position` that is not a board, or + the innermost board when no other layer is there; nil on the empty + canvas." + [objects position] + (let [hits (->> (vals objects) + (remove cfh/root?) + (remove :hidden) + (filter #(gsh/has-point? % position)))] + (when (seq hits) + (let [sorted (ctst/sort-z-index-objects objects hits {:bottom-frames? true}) + shapes (remove cfh/frame-shape? sorted)] + (or (last shapes) (last sorted)))))) + +(defn anchor-shape + "The layer a task points at, or its board when the layer is gone. None + when it points at the canvas itself." + [objects {:keys [shape-id frame-id]}] + (->> [(get objects shape-id) (get objects frame-id)] + (remove nil?) + (remove cfh/root?) + (first))) + +(defn anchor-position + "Where the mark of a task goes on the canvas, as a point: the top right + corner of its layer, or of its board when the layer is gone, or the + spot it was made on when it points at the canvas itself (`position`). + The thread of a layer opens there too, and a thread keeps its position + as a point." + [objects {:keys [position] :as task}] + (let [shape (anchor-shape objects task)] + (if (some? shape) + (let [{:keys [x y width]} (:selrect shape)] + (gpt/point (+ x width) y)) + (some-> position (gpt/point))))) + +;; --- Fetching + +(defn- tasks-fetched + [tasks] + (ptk/reify ::tasks-fetched + ptk/UpdateEvent + (update [_ state] + (assoc state :workspace-tasks {:status :loaded + :data (d/index-by :id tasks)})))) + +(defn fetch-tasks + "Load the tasks of the open file." + [] + (ptk/reify ::fetch-tasks + ptk/WatchEvent + (watch [_ state _] + (if-let [file-id (and (enabled?) (:current-file-id state))] + (->> (rp/cmd! :get-file-tasks {:file-id file-id}) + (rx/map tasks-fetched) + (rx/catch (fn [_] (rx/of (tasks-fetched []))))) + (rx/empty))))) + +(defn- task-events-fetched + [task-id events] + (ptk/reify ::task-events-fetched + ptk/UpdateEvent + (update [_ state] + (assoc-in state [:workspace-task-events task-id] events)))) + +(defn fetch-task-events + [task-id] + (assert (uuid? task-id) "expected a valid uuid for `task-id`") + (ptk/reify ::fetch-task-events + ptk/WatchEvent + (watch [_ _ _] + (->> (rp/cmd! :get-task-events {:id task-id}) + (rx/map (partial task-events-fetched task-id)) + (rx/catch (fn [_] (rx/empty))))))) + +(defn- refresh + "Reload the tasks and the events of the task open now, after a change + made here or by somebody else." + [] + (ptk/reify ::refresh + ptk/WatchEvent + (watch [_ state _] + (let [open-id (get-in state [:workspace-tasks-local :open])] + (rx/concat + (rx/of (fetch-tasks)) + (if (some? open-id) + (rx/of (fetch-task-events open-id)) + (rx/empty))))))) + +(defn handle-tasks-change + "Another session changed the tasks of the open file." + [{:keys [file-id]}] + (ptk/reify ::handle-tasks-change + ptk/WatchEvent + (watch [_ state _] + (if (= file-id (:current-file-id state)) + (rx/of (refresh)) + (rx/empty))))) + +;; --- Opening a task + +(defn open-task + "Open the task `task-id` on the canvas, as the thread it lives in." + [task-id] + (ptk/reify ::open-task + ptk/UpdateEvent + (update [_ state] + (-> state + (update :workspace-tasks-local assoc :open task-id) + (update :workspace-tasks-local dissoc :new) + (update :comments-local dissoc :open :draft :expanded))) + + ptk/WatchEvent + (watch [_ state _] + (let [task (get-in state [:workspace-tasks :data task-id]) + thread (some->> (:thread-id task) (get (:comment-threads state)))] + (rx/concat + (rx/of (fetch-task-events task-id)) + (if (some? thread) + (rx/of (dcmt/open-thread thread)) + (rx/empty))))))) + +(defn close-task + [] + (ptk/reify ::close-task + ptk/UpdateEvent + (update [_ state] + (update state :workspace-tasks-local dissoc :open)))) + +(declare center-to-task) + +(defn navigate-to-task + "Take the viewport to the layer of `task` and open it." + [task] + (ptk/reify ::navigate-to-task + ptk/WatchEvent + (watch [_ state _] + (let [page-id (:page-id task)] + (rx/concat + (if (not= page-id (:current-page-id state)) + (rx/of (rt/nav :workspace + (-> (rt/get-params state) + (assoc :page-id page-id)) + {::rt/replace true})) + (rx/empty)) + (->> (rx/of (center-to-task task) + (open-task (:id task))) + (rx/observe-on :async))))))) + +(defn open-task-link + "Open the task of a link (`task-id` query param): load the tasks, take + the viewport to it, open it and drop the param." + [task-id] + (ptk/reify ::open-task-link + ptk/WatchEvent + (watch [_ state _] + (let [file-id (:current-file-id state)] + (->> (rp/cmd! :get-file-tasks {:file-id file-id}) + (rx/mapcat + (fn [tasks] + (let [task (d/seek #(= task-id (:id %)) tasks)] + (rx/concat + (rx/of (tasks-fetched tasks) + (rt/nav :workspace (dissoc (rt/get-params state) :task-id) + {::rt/replace true})) + (if (some? task) + (rx/of (navigate-to-task task)) + (rx/empty)))))) + (rx/catch (fn [_] (rx/empty)))))))) + +;; --- Writing a new task + +(defn start-new-task + "Open the form of a new task linked to a layer: `params` carries the + page, board and layer (`page-id`, `frame-id`, `shape-id`) and, + optionally, the message of a comment thread the task comes from + (`thread-id` and `comment-id`, with its text as the first `title`) and + the design review it belongs to." + [params] + (ptk/reify ::start-new-task + ptk/UpdateEvent + (update [_ state] + (-> state + (update :workspace-tasks-local assoc :new params) + (update :workspace-tasks-local dissoc :open))))) + +(defn cancel-new-task + [] + (ptk/reify ::cancel-new-task + ptk/UpdateEvent + (update [_ state] + (update state :workspace-tasks-local dissoc :new)))) + +(defn- task-created + "Keep a new task right away: opening it needs to know its thread, before + the tasks of the file are fetched again." + [task] + (ptk/reify ::task-created + ptk/UpdateEvent + (update [_ state] + (assoc-in state [:workspace-tasks :data (:id task)] task)))) + +(defn- fetch-task-thread + "The thread a new task created on the canvas got: keep it before the + task opens as that thread." + [{:keys [file-id thread-id]}] + (->> (rp/cmd! :get-comment-thread {:file-id file-id :id thread-id}) + (rx/map #(dcmt/created-thread-on-workspace % false)))) + +(defn create-task + "Create a task from the form. A task made from a message lives in it; + any other gets a thread of its own, whose first message is its title, + on the spot of its mark. It opens once created." + [{:keys [title] :as params}] + (assert (string? title) "expected a string `title`") + (ptk/reify ::create-task + ptk/WatchEvent + (watch [_ state _] + (let [file-id (:current-file-id state) + objects (dsh/lookup-page-objects state (:page-id params)) + params (-> params + (select-keys [:title :page-id :frame-id :shape-id :assignee-id + :pull-request-id :thread-id :comment-id :position]) + ;; the root of the page is the canvas: no layer + (update :shape-id #(when (not= uuid/zero %) %)) + (update :frame-id #(or % uuid/zero)) + (assoc :file-id file-id)) + ;; a task on a selected layer comes with no spot: its thread + ;; sits where its mark goes + params (-> params + (assoc :position (some-> (or (:position params) + (anchor-position objects params)) + (gpt/point))) + (d/without-nils)) + thread? (some? (:thread-id params))] + (rx/concat + (rx/of (ev/event {::ev/name "create-task" + :from-thread thread? + :in-review (some? (:pull-request-id params))})) + (->> (rp/cmd! :create-task params) + (rx/mapcat (fn [task] + (rx/concat + (if thread? + (rx/empty) + (fetch-task-thread task)) + (rx/of (task-created task) + (cancel-new-task) + (ntf/success (tr "workspace.tasks.created")) + (fetch-tasks) + (open-task (:id task)))))) + (rx/catch (fn [cause] + (if (= :comment-already-has-task (:code (ex-data cause))) + (rx/of (ntf/warn (tr "workspace.tasks.error.comment-has-task"))) + (rx/of (ntf/error (tr "workspace.tasks.error.generic")))))))))))) + +;; --- Changing a task + +(defn update-task + "Rename a task or change its assignee (`nil` leaves it without one)." + [task-id params] + (assert (uuid? task-id) "expected a valid uuid for `task-id`") + (ptk/reify ::update-task + ptk/UpdateEvent + (update [_ state] + (d/update-in-when state [:workspace-tasks :data task-id] + merge (select-keys params [:title :assignee-id]))) + + ptk/WatchEvent + (watch [_ _ _] + (->> (rp/cmd! :update-task (-> (select-keys params [:title :assignee-id]) + (assoc :id task-id))) + ;; a thread may show the task without having opened it + (rx/mapcat (fn [_] (rx/of (refresh) (fetch-task-events task-id)))) + (rx/catch (fn [_] (rx/of (ntf/error (tr "workspace.tasks.error.generic")) + (refresh)))))))) + +(defn- status-toast + [state {:keys [created-by]} status] + (let [profile-id (:profile-id state) + creator (get-in state [:profiles created-by :fullname])] + (case status + "done" (if (and (some? creator) (not= created-by profile-id)) + (tr "workspace.tasks.toast.done-verify" creator) + (tr "workspace.tasks.toast.done")) + "verified" (tr "workspace.tasks.toast.verified") + "reopened" (tr "workspace.tasks.toast.reopened") + "wont-do" (tr "workspace.tasks.toast.wont-do") + nil))) + +(defn set-task-status + "Move a task to another state; the server records who did it." + [task status] + (assert (uuid? (:id task)) "expected a task with a valid `:id`") + (ptk/reify ::set-task-status + ptk/UpdateEvent + (update [_ state] + (d/update-in-when state [:workspace-tasks :data (:id task)] assoc :status status)) + + ptk/WatchEvent + (watch [_ state _] + (rx/concat + (rx/of (ev/event {::ev/name "set-task-status" :status status})) + (->> (rp/cmd! :set-task-status {:id (:id task) :status status}) + (rx/mapcat (fn [_] + (let [message (status-toast state task status)] + (rx/concat + (if message + (rx/of (ntf/success message)) + (rx/empty)) + (rx/of (refresh)))))) + (rx/catch (fn [_] + (rx/of (ntf/error (tr "workspace.tasks.error.generic")) + (refresh))))))))) + +(defn delete-task + [task-id] + (assert (uuid? task-id) "expected a valid uuid for `task-id`") + (ptk/reify ::delete-task + ptk/UpdateEvent + (update [_ state] + (-> state + (d/update-in-when [:workspace-tasks :data] dissoc task-id) + (update :workspace-tasks-local + (fn [local] + (cond-> local + (= task-id (:open local)) (dissoc :open)))))) + + ptk/WatchEvent + (watch [_ _ _] + (->> (rp/cmd! :delete-task {:id task-id}) + (rx/map (fn [_] (fetch-tasks))) + (rx/catch (fn [_] (rx/of (ntf/error (tr "workspace.tasks.error.generic")) + (fetch-tasks)))))))) + +;; --- Linking a task to another layer + +(defn start-relink + "Wait for the user to pick the layer the task points at from now on." + [task-id] + (ptk/reify ::start-relink + ptk/UpdateEvent + (update [_ state] + (-> state + (update :workspace-tasks-local assoc :relink task-id) + (update :workspace-tasks-local dissoc :open))))) + +(defn cancel-relink + [] + (ptk/reify ::cancel-relink + ptk/UpdateEvent + (update [_ state] + (update state :workspace-tasks-local dissoc :relink)))) + +(defn relink-task + "Point the task being linked (`:relink`) at `shape`." + [shape] + (ptk/reify ::relink-task + ptk/WatchEvent + (watch [_ state _] + (if-let [task-id (get-in state [:workspace-tasks-local :relink])] + (let [page-id (:current-page-id state)] + (rx/concat + (rx/of (cancel-relink)) + (->> (rp/cmd! :relink-task {:id task-id + :page-id page-id + :frame-id (if (cfh/frame-shape? shape) + (:id shape) + (:frame-id shape)) + :shape-id (:id shape) + :shape-name (:name shape)}) + (rx/mapcat (fn [_] + (rx/of (ntf/success (tr "workspace.tasks.toast.relinked" (:name shape))) + (refresh)))) + (rx/catch (fn [_] (rx/of (ntf/error (tr "workspace.tasks.error.generic")))))))) + (rx/empty))))) + +;; --- Deleted layers + +(defn- surviving-frame + "The board that keeps a task whose layer `shape-id` is deleted with + `deleted-ids`: the nearest board above the layer that stays." + [objects deleted-ids shape-id] + (let [frame (->> (cfh/get-parent-ids objects shape-id) + (map #(get objects %)) + (filter cfh/frame-shape?) + (d/seek #(not (contains? deleted-ids (:id %)))))] + (or frame (get objects uuid/zero)))) + +(defn- subtree-objects + "The layer and its children, parents before children, as they are now: + what restoring the layer puts back." + [objects shape-id] + (into [] + (comp (map #(get objects %)) + (remove nil?) + (map #(dissoc % :shapes))) + (cfh/get-children-ids-with-self objects shape-id))) + +(declare mark-layer-restored) +(declare layer-deleted-dialog) + +(defn handle-deleted-shapes + "Some layers are about to be deleted (`ids`, with their children) from + `objects`: move their open tasks to the board that held them, and + offer to undo the deletion or to mark the tasks as done, in case the + deletion was the fix." + [objects ids] + (ptk/reify ::handle-deleted-shapes + ptk/WatchEvent + (watch [_ state _] + (let [tasks (vals (get-in state [:workspace-tasks :data])) + deleted-ids (into #{} (mapcat #(cfh/get-children-ids-with-self objects %)) ids) + affected (->> tasks + (remove closed?) + (remove lost?) + (filter #(contains? deleted-ids (:shape-id %))))] + (if (or (not (enabled?)) (empty? affected)) + (rx/empty) + (let [file-id (:current-file-id state) + layers (->> affected + (map :shape-id) + (distinct) + (mapv (fn [shape-id] + (let [shape (get objects shape-id) + frame (surviving-frame objects deleted-ids shape-id)] + {:shape-id shape-id + :shape-name (:name shape) + :frame-id (:id frame) + :frame-name (when-not (cfh/root? frame) (:name frame)) + :objects (subtree-objects objects shape-id)})))) + first-layer (first layers) + message (if (= 1 (count affected)) + (tr "workspace.tasks.layer-deleted.one" + (:shape-name first-layer) + (or (:frame-name first-layer) (tr "workspace.tasks.canvas"))) + (tr "workspace.tasks.layer-deleted.many" (count affected)))] + (->> (rp/cmd! :mark-tasks-layer-deleted {:file-id file-id :layers layers}) + (rx/mapcat + (fn [moved] + (rx/of (refresh) + (layer-deleted-dialog moved message)))) + (rx/catch (fn [_] (rx/empty)))))))))) + +(defn- layer-deleted-dialog + "The dialog that follows the deletion of layers with open tasks: undo + the deletion, or mark the tasks as done." + [moved message] + (ptk/reify ::layer-deleted-dialog + ptk/WatchEvent + (watch [_ _ _] + (let [output-s (rx/subject) + close (fn [& events] + (rx/push! output-s (ntf/hide :tag :task-layer-deleted)) + (run! #(rx/push! output-s %) events) + (rx/end! output-s))] + (rx/merge + output-s + (rx/of (ntf/dialog + :content message + :controls :inline-actions + :tag :task-layer-deleted + :cancel {:label (tr "workspace.tasks.layer-deleted.undo") + :callback #(apply close dwu/undo (map mark-layer-restored moved))} + :accept {:label (tr "workspace.tasks.actions.mark-done") + :callback #(apply close (map (fn [task] (set-task-status task "done")) moved))}))))))) + +(defn- mark-layer-restored + "The layer of the task is back: the task points at it again." + [task] + (ptk/reify ::mark-layer-restored + ptk/WatchEvent + (watch [_ state _] + (let [objects (dsh/lookup-page-objects state (:page-id task)) + shape (get objects (:shape-id task))] + (->> (rp/cmd! :mark-task-layer-restored + {:id (:id task) + :frame-id (or (some-> shape :frame-id) uuid/zero)}) + (rx/map (fn [_] (refresh))) + (rx/catch (fn [_] (rx/empty)))))))) + +(defn restore-task-layer + "Put back the deleted layer of `task`, as it was when it was deleted + (the event of the deletion keeps it), and point the task at it again. + The layer goes back into its parent when the parent is still there, + into the board that keeps the task otherwise." + [task] + (ptk/reify ::restore-task-layer + ptk/WatchEvent + (watch [it state _] + (let [page-id (:page-id task) + objects (dsh/lookup-page-objects state page-id) + events (get-in state [:workspace-task-events (:id task)]) + deleted (->> events + (filter #(= "layer-deleted" (:type %))) + (last)) + [root & children :as shapes] (get-in deleted [:payload :objects])] + (if (or (empty? shapes) (contains? objects (:id root))) + (rx/of (mark-layer-restored task)) + (let [parent-id (if (contains? objects (:parent-id root)) + (:parent-id root) + (:frame-id task)) + parent (get objects parent-id) + frame-id (if (cfh/frame-shape? parent) parent-id (:frame-id parent)) + root (assoc root :parent-id parent-id :frame-id frame-id) + changes (-> (pcb/empty-changes it page-id) + (pcb/with-objects objects) + (pcb/add-objects (into [root] children)))] + (rx/of (dch/commit-changes changes) + (mark-layer-restored task) + (ntf/success (tr "workspace.tasks.toast.layer-restored" (:name root)))))))))) + +;; --- Viewport + +(defn center-to-task + "Center the viewport on the mark of `task`." + [task] + (ptk/reify ::center-to-task + ptk/UpdateEvent + (update [_ state] + (let [objects (dsh/lookup-page-objects state (:page-id task)) + position (anchor-position objects task)] + (if (nil? position) + state + (update state :workspace-local + (fn [{:keys [vbox] :as local}] + (update local :vbox assoc + :x (- (:x position) (/ (:width vbox) 2)) + :y (- (:y position) (/ (:height vbox) 2)))))))) + + ptk/EffectEvent + (effect [_ state _] + (dwvw/maybe-sync-workspace-local-viewport! state)))) + +;; --- Counting + +(defn tasks-for + "The tasks that still need work from `profile-id`." + [tasks profile-id] + (filter #(and (to-do? %) (= profile-id (:assignee-id %))) tasks)) + +(defn review-tasks + "The tasks of the design review `pull-request-id`." + [tasks pull-request-id] + (filter #(= pull-request-id (:pull-request-id %)) tasks)) + +(defn sort-tasks + "Open work first (oldest first), then the tasks to verify, then the + closed ones." + [tasks] + (sort-by (juxt #(cond (to-do? %) 0 (to-verify? %) 1 :else 2) + #(dm/get-prop % :created-at)) + tasks)) + +(defn search + [tasks text] + (if (str/blank? text) + tasks + (let [text (str/lower text)] + (filter #(str/includes? (str/lower (:title %)) text) tasks)))) diff --git a/frontend/src/app/main/refs.cljs b/frontend/src/app/main/refs.cljs index 877cb65b83..489867fb6c 100644 --- a/frontend/src/app/main/refs.cljs +++ b/frontend/src/app/main/refs.cljs @@ -55,6 +55,27 @@ ;; the review banner/actions. nil when no review is active. (l/derived #(get % :workspace-pr-preview) st/state)) +(def tasks + "The tasks of the open file, by id." + (l/derived #(get-in % [:workspace-tasks :data]) st/state)) + +(def task-events + "The events of the tasks opened so far, by task id." + (l/derived :workspace-task-events st/state)) + +(def tasks-local + "What the user is doing with the tasks: the one open (`:open`), the + new one being written (`:new`), the one being linked to another layer + (`:relink`)." + (l/derived :workspace-tasks-local st/state)) + +(def review-local + "The tool, panel tab, filters and shown change of the review mode." + (l/derived :workspace-review-local st/state)) + +(def review-activity + (l/derived :workspace-review-activity st/state)) + (def pending-reviews ;; dashboard: open pull requests awaiting the current profile's review (l/derived #(get % :dashboard-pending-reviews) st/state)) @@ -83,11 +104,19 @@ (and (contains? #{"merged" "archived"} (get-in ctx [:info :status])) (= (:file-id ctx) (:current-file-id state))))) +(defn- reviewing? + "True while the open file is shown inside a design review: the review + is read-only, the branch is edited outside it." + [state] + (some? (:workspace-pr-preview state))) + (def permissions - "The team permissions, without edition on a merged or archived branch." + "The team permissions, without edition on a merged or archived branch + nor inside a design review." (l/derived (fn [state] (cond-> (:permissions (dsh/lookup-team state)) - (open-closed-branch? state) + (or (open-closed-branch? state) + (reviewing? state)) (assoc :can-edit false))) st/state)) @@ -100,6 +129,18 @@ (def threads (l/derived :comment-threads st/state)) +(def layer-comment-counts + "How many open comment threads point at each layer, by layer id: the + count the layers panel shows next to a layer." + (l/derived (fn [threads] + (reduce (fn [acc {:keys [anchor-type shape-id is-resolved]}] + (if (and (= :layer anchor-type) (some? shape-id) (not is-resolved)) + (update acc shape-id (fnil inc 0)) + acc)) + {} + (vals threads))) + threads)) + (def share-links (l/derived :share-links st/state)) @@ -197,6 +238,11 @@ (def workspace-global (l/derived :workspace-global st/state)) +(def bottom-bar + "Which bar at the bottom of the canvas of a branch is open, without a branch + nil (see `app.main.data.workspace.layout`)." + (l/derived :bottom-bar workspace-global)) + (def mcp (l/derived :mcp st/state)) diff --git a/frontend/src/app/main/ui.cljs b/frontend/src/app/main/ui.cljs index 9c1c581668..7e0e98c168 100644 --- a/frontend/src/app/main/ui.cljs +++ b/frontend/src/app/main/ui.cljs @@ -197,12 +197,14 @@ file-id (some-> params :file-id uuid/parse*) page-id (some-> params :page-id uuid/parse*) pr-id (some-> params :pr-id uuid/parse*) + task-id (some-> params :task-id uuid/parse*) layout (some-> params :layout keyword)] [:> team-container* {:team-id team-id} [:> workspace-page* {:team-id team-id :file-id file-id :page-id page-id :pr-id pr-id + :task-id task-id :layout-name layout :key file-id}]]) diff --git a/frontend/src/app/main/ui/comments.cljs b/frontend/src/app/main/ui/comments.cljs index 706e41c72e..fa524a6c74 100644 --- a/frontend/src/app/main/ui/comments.cljs +++ b/frontend/src/app/main/ui/comments.cljs @@ -18,6 +18,7 @@ [app.main.data.comments :as dcm] [app.main.data.modal :as modal] [app.main.data.workspace.comments :as dwcm] + [app.main.data.workspace.tasks :as dwtk] [app.main.refs :as refs] [app.main.store :as st] [app.main.ui.components.dropdown :refer [dropdown]] @@ -25,6 +26,8 @@ [app.main.ui.ds.buttons.icon-button :refer [icon-button*]] [app.main.ui.ds.controls.checkbox :refer [checkbox*]] [app.main.ui.ds.foundations.assets.icon :refer [icon*] :as i] + [app.main.ui.ds.product.review-label :refer [review-label*]] + [app.main.ui.ds.tooltip :refer [tooltip*]] [app.main.ui.hooks :as h] [app.util.dom :as dom] [app.util.i18n :as i18n :refer [tr]] @@ -206,7 +209,6 @@ ;; Component that renders the component content (mf/defc comment-content* - {::mf/private true} [{:keys [content]}] (let [comment-elements (mf/use-memo (mf/deps content) #(parse-comment content))] (for [[idx {:keys [type content]}] (d/enumerate comment-elements)] @@ -657,7 +659,6 @@ :avatar-darken (= variant "solved"))}]])) (mf/defc comment-info* - {::mf/private true} [{:keys [item profile]}] [:* [:div {:class (stl/css :author)} @@ -921,23 +922,39 @@ (dom/stop-propagation event) (st/emit! (dcm/toggle-comment-options uuid/zero)))) + ;; the tasks of the thread live in its messages and go with it + tasks (mf/deref refs/tasks) + tasks? (mf/with-memo [tasks thread] + (boolean (seq (dwtk/get-tasks-of-thread tasks (:id thread))))) + delete-thread (mf/use-fn + (mf/deps thread origin tasks?) (fn [] (st/emit! (dcm/close-thread) - (if (= origin :viewer) + (cond + (= origin :viewer) (dcm/delete-comment-thread-on-viewer thread) + + tasks? + (dcm/delete-comment-thread-on-workspace + thread #(st/emit! (dwtk/fetch-tasks))) + + :else (dcm/delete-comment-thread-on-workspace thread))))) on-delete-thread (mf/use-fn + (mf/deps delete-thread tasks?) (fn [event] (dom/stop-propagation event) (st/emit! (dcm/hide-comment-options)) (st/emit! (modal/show {:type :confirm :title (tr "modals.delete-comment-thread.title") - :message (tr "modals.delete-comment-thread.message") + :message (if tasks? + (tr "modals.delete-comment-thread.message-tasks") + (tr "modals.delete-comment-thread.message")) :accept-label (tr "modals.delete-comment-thread.accept") :on-accept delete-thread})))) @@ -953,9 +970,14 @@ (tr "labels.comment") " " [:span {:class (stl/css :grayed-text)} "#" (:seqn thread)]] [:div {:class (stl/css :floating-thread-header-right)} (when (some? thread) - [:> checkbox* {:class (stl/css :checkbox-wrapper) - :checked (:is-resolved thread) - :on-change toggle-resolved}]) + (let [label (if (:is-resolved thread) + (tr "labels.mark-as-unresolved") + (tr "labels.mark-as-resolved"))] + [:> tooltip* {:content label :placement "top"} + [:div {:class (stl/css :checkbox-wrapper)} + [:> checkbox* {:checked (:is-resolved thread) + :aria-label label + :on-change toggle-resolved}]]])) (when (= (:id profile) (:id owner)) [:> icon-button* {:variant "ghost" :aria-label (tr "labels.options") @@ -969,8 +991,12 @@ (tr "labels.delete-comment-thread")]]]])) (mf/defc comment-floating-thread-item* + "A message of a thread. `thread` comes only with its first message, the + one that cannot be deleted on its own; `parent` is the thread of any + message. Each message may become a task, which `task-section` shows + under it." {::mf/private true} - [{:keys [comment thread]}] + [{:keys [comment thread parent origin task task-section]}] (let [owner (dcm/get-owner comment) profile (mf/deref refs/profile) options (mf/deref ref:comments-local-options) @@ -1000,7 +1026,15 @@ on-delete-comment (mf/use-fn (mf/deps comment) - #(st/emit! (dcm/delete-comment comment))) + (fn [event] + (dom/stop-propagation event) + (st/emit! (dcm/hide-comment-options) + (modal/show + {:type :confirm + :title (tr "modals.delete-comment.title") + :message (tr "modals.delete-comment.message") + :accept-label (tr "modals.delete-comment.accept") + :on-accept #(st/emit! (dcm/delete-comment comment))})))) on-submit (mf/use-fn @@ -1010,7 +1044,33 @@ (st/emit! (dcm/update-comment (assoc comment :content content))))) on-cancel - (mf/use-fn #(reset! edition? false))] + (mf/use-fn #(reset! edition? false)) + + can-task? (and (dwtk/enabled?) + (not= origin :viewer) + (nil? task)) + + ;; "Make it a task": the title comes from the message, the layer is + ;; the one the thread points at (its board otherwise) + on-make-task + (mf/use-fn + (mf/deps comment parent) + (fn [event] + (dom/stop-propagation event) + (let [text (str/trim (str/replace (or (:content comment) "") + #"@\[([^\]]*)\]\([^\)]*\)" "@$1"))] + (st/emit! (dwtk/start-new-task + {:page-id (:page-id parent) + :frame-id (:frame-id parent) + :shape-id (if (= :layer (:anchor-type parent)) + (:shape-id parent) + (:frame-id parent)) + :position (:position parent) + :thread-id (:id parent) + :comment-id (:id comment) + :pull-request-id (when (= "open" (:pull-request-status parent)) + (:pull-request-id parent)) + :title (subs text 0 (min 250 (count text)))})))))] [:div {:class (stl/css :floating-thread-item-wrapper)} [:div {:class (stl/css :floating-thread-item)} @@ -1021,19 +1081,29 @@ [:div {:class (stl/css :author-timeago)} (ct/timeago (:modified-at comment))]] + (when ^boolean can-task? + [:> icon-button* {:variant "ghost" + :aria-label (tr "workspace.tasks.make-task") + :on-click on-make-task + :icon i/view-as-list}]) + (when (= (:id profile) (:id owner)) [:> icon-button* {:variant "ghost" :aria-label (tr "labels.options") :on-click on-toggle-options :icon i/menu}])] - [:div {:class (stl/css :item)} + [:div {:class (stl/css-case :item true + :message (not @edition?))} (if @edition? [:> comment-edit-form* {:content (:content comment) :on-submit on-submit :on-cancel on-cancel}] [:span {:class (stl/css :text)} - [:> comment-content* {:content (:content comment)}]])]] + [:> comment-content* {:content (:content comment)}]])] + + (when (and (some? task) (some? task-section)) + [:> task-section {:task task}])] [:& dropdown {:show (= options (:id comment)) :on-close on-hide-options} @@ -1052,7 +1122,7 @@ (mf/defc comment-floating-thread* {::mf/wrap [mf/memo]} - [{:keys [thread zoom origin position-modifier viewport]}] + [{:keys [thread zoom origin position-modifier viewport task-section]}] (let [ref (mf/use-ref) mentions-s (mf/use-memo #(rx/subject)) thread-id (:id thread) @@ -1077,12 +1147,19 @@ (make-comments-ref thread-id)) comments-map (mf/deref comments-ref) + tasks (mf/deref refs/tasks) + comments (mf/with-memo [comments-map] (->> (vals comments-map) (sort-by :created-at))) first-comment (first comments) + ;; the tasks whose message is gone stay at the end of their thread + loose-tasks (mf/with-memo [tasks thread-id comments-map] + (->> (dwtk/get-tasks-of-thread tasks thread-id) + (remove #(contains? comments-map (:comment-id %))))) + on-submit (mf/use-fn (mf/deps thread) @@ -1129,12 +1206,29 @@ [:> comment-floating-thread-header* {:thread thread :origin origin}]] + (when (some? (:pull-request-id thread)) + [:> review-label* {:label (or (:pull-request-title thread) + (tr "workspace.review.design-review"))}]) + + ;; the workspace passes what a message shows about its task [:div {:class (stl/css :floating-thread-main)} [:> comment-floating-thread-item* {:comment first-comment - :thread thread}] + :thread thread + :parent thread + :origin origin + :task (dwtk/get-task-of-comment tasks (:id first-comment)) + :task-section task-section}] (for [item (rest comments)] [:* {:key (dm/str (:id item))} - [:> comment-floating-thread-item* {:comment item}]])] + [:> comment-floating-thread-item* {:comment item + :parent thread + :origin origin + :task (dwtk/get-task-of-comment tasks (:id item)) + :task-section task-section}]]) + + (when (some? task-section) + (for [task loose-tasks] + [:> task-section {:key (dm/str (:id task)) :task task}]))] [:> comment-reply-form* {:on-submit on-submit :on-cancel (when (= origin :viewer) on-cancel)}] @@ -1259,6 +1353,23 @@ :variant "read"} num-threads]])) +(mf/defc preview-card* + "The small card that hovering a mark on the canvas shows." + [{:keys [children]}] + [:div {:class (stl/css :floating-thread-wrapper + :floating-preview-displacement + :floating-preview-hover-card)} + [:div {:class (stl/css :floating-thread-item-wrapper)} + [:div {:class (stl/css :floating-thread-item)} + children]]]) + +(mf/defc thread-preview* + "The small card of a comment thread." + [{:keys [thread owner]}] + [:> preview-card* {} + [:> comment-info* {:item thread + :profile owner}]]) + (mf/defc comment-floating-bubble* {::mf/wrap [mf/memo]} [{:keys [thread zoom is-open on-click origin position-modifier offset ring]}] @@ -1427,13 +1538,7 @@ :else "read")}]] (when (:is-hover @state) - [:div {:class (stl/css :floating-thread-wrapper - :floating-preview-displacement - :floating-preview-hover-card)} - [:div {:class (stl/css :floating-thread-item-wrapper)} - [:div {:class (stl/css :floating-thread-item)} - [:> comment-info* {:item thread - :profile owner}]]]])])) + [:> thread-preview* {:thread thread :owner owner}])])) (mf/defc comment-sidebar-thread-item* {::mf/private true} diff --git a/frontend/src/app/main/ui/comments.scss b/frontend/src/app/main/ui/comments.scss index 547d6e95ef..67c8555e1c 100644 --- a/frontend/src/app/main/ui/comments.scss +++ b/frontend/src/app/main/ui/comments.scss @@ -57,6 +57,7 @@ .author-identity { flex-grow: 1; + min-inline-size: 0; } .author-fullname { @@ -144,6 +145,14 @@ white-space: pre-wrap; } +// a message of a thread sits in a box, apart from its author and what comes +// after it +.message { + padding: var(--sp-s) var(--sp-m); + border-radius: $br-8; + background-color: var(--color-background-tertiary); +} + .replies { @include use-typography("body-small"); @@ -160,6 +169,7 @@ } .floating-preview-wrapper { + // TODO: no DS z-index token for 1. z-index: 1; position: absolute; user-select: none; @@ -179,6 +189,7 @@ } .floating-preview-expanded { + // TODO: no DS z-index token for 2. z-index: 2; animation: comment-bubble-fan-out 0.18s ease-out; } @@ -196,10 +207,12 @@ } .floating-preview-hovered { + // TODO: no DS z-index token for 10. z-index: 10; } .floating-preview-ghost { + // TODO: no DS z-index token for 1. z-index: 1; opacity: 0.6; pointer-events: none; @@ -297,12 +310,19 @@ .floating-thread-header-left { @include use-typography("body-small"); + display: flex; + align-items: center; + gap: var(--sp-xs); + min-inline-size: 0; color: var(--color-foreground-primary); } +// the same gap as the author of a message, so the checkbox and the menu +// line up with its buttons .floating-thread-header-right { display: flex; align-items: center; + gap: var(--sp-s); } .floating-thread-main { @@ -325,9 +345,17 @@ gap: var(--sp-s); } -// .checkbox-wrapper { -// margin-inline-end: var(--sp-s); -// } +// the resolve checkbox takes the box of an icon button, so it lines up +// with the buttons of the messages under it. The DS checkbox keeps an +// empty column for its label after the box: centering the whole would move +// the box to the left, so the box sits at the middle from the start. +.checkbox-wrapper { + display: flex; + align-items: center; + inline-size: $sz-32; + block-size: $sz-32; + padding-inline-start: calc(($sz-32 - $sz-16) / 2); +} .dropdown-menu { position: absolute; @@ -338,8 +366,8 @@ border-radius: $br-8; z-index: var(--z-index-dropdown); overflow: hidden auto; - background-color: var(--menu-background-color); - color: var(--menu-foreground-color); + background-color: var(--color-background-tertiary); + color: var(--color-foreground-primary); border: $b-2 solid var(--color-background-quaternary); box-shadow: 0 0 var(--sp-m) 0 var(--color-shadow-dark); max-inline-size: $sz-200; @@ -350,6 +378,10 @@ } .dropdown-menu-option { + --dropdown-menu-option-bg-color: transparent; + --dropdown-menu-option-fg-color: var(--color-foreground-secondary); + --dropdown-menu-option-icon-color: var(--color-foreground-secondary); + @include use-typography("body-small"); display: flex; @@ -358,9 +390,11 @@ block-size: $sz-32; padding: 0 var(--sp-s); border-radius: $br-6; + background-color: var(--dropdown-menu-option-bg-color); cursor: pointer; - color: var(--menu-foreground-color-rest); + color: var(--dropdown-menu-option-fg-color); + // span: the text of an option has no class in comments.cljs span { justify-content: center; align-items: center; @@ -370,24 +404,22 @@ text-overflow: ellipsis; white-space: nowrap; + // svg: the icon of an option has no class in comments.cljs svg { display: flex; justify-content: center; align-items: center; block-size: $sz-12; inline-size: $sz-12; - stroke-width: 1.33px; - stroke: var(--icon-foreground); + stroke-width: px2rem(1.33); + stroke: var(--dropdown-menu-option-icon-color); } } &:hover { - background-color: var(--menu-background-color-hover); - color: var(--menu-foreground-color); - - svg { - stroke: var(--menu-foreground-color-hover); - } + --dropdown-menu-option-bg-color: var(--color-background-quaternary); + --dropdown-menu-option-fg-color: var(--color-foreground-primary); + --dropdown-menu-option-icon-color: var(--color-foreground-primary); } } @@ -465,7 +497,7 @@ } .comments-mentions-entry.is-selected { - border: 1px solid var(--color-accent-primary-muted); + border: $b-1 solid var(--color-accent-primary-muted); background: var(--color-background-quaternary); } diff --git a/frontend/src/app/main/ui/css_cursors.cljs b/frontend/src/app/main/ui/css_cursors.cljs index 8541d7bedf..471d92cf3d 100644 --- a/frontend/src/app/main/ui/css_cursors.cljs +++ b/frontend/src/app/main/ui/css_cursors.cljs @@ -40,6 +40,7 @@ (init-static-cursor-style style "create-polygon" cur/create-polygon) (init-static-cursor-style style "create-rectangle" cur/create-rectangle) (init-static-cursor-style style "create-shape" cur/create-shape) + (init-static-cursor-style style "create-task" cur/create-task) (init-static-cursor-style style "draw" cur/draw) (init-static-cursor-style style "draw-add" cur/draw-add) (init-static-cursor-style style "draw-node" cur/draw-node) diff --git a/frontend/src/app/main/ui/cursors.cljs b/frontend/src/app/main/ui/cursors.cljs index 9453f285d5..76b59a5102 100644 --- a/frontend/src/app/main/ui/cursors.cljs +++ b/frontend/src/app/main/ui/cursors.cljs @@ -14,6 +14,7 @@ (def ^:cursor create-polygon (cursor-ref :create-polygon)) (def ^:cursor create-rectangle (cursor-ref :create-rectangle)) (def ^:cursor create-shape (cursor-ref :create-shape)) +(def ^:cursor create-task (cursor-ref :create-task 0 2 20)) (def ^:cursor draw (cursor-ref :draw 0 0 0)) (def ^:cursor draw-add (cursor-ref :draw-add 0 0 0 25 25)) (def ^:cursor draw-node (cursor-ref :draw-node 0 0 0 25 25)) diff --git a/frontend/src/app/main/ui/ds.cljs b/frontend/src/app/main/ui/ds.cljs index 162d2877a5..640f5c133f 100644 --- a/frontend/src/app/main/ui/ds.cljs +++ b/frontend/src/app/main/ui/ds.cljs @@ -8,6 +8,7 @@ (:require [app.main.ui.ds.buttons.button :refer [button*]] [app.main.ui.ds.buttons.icon-button :refer [icon-button*]] + [app.main.ui.ds.buttons.link-button :refer [link-button*]] [app.main.ui.ds.controls.checkbox :refer [checkbox*]] [app.main.ui.ds.controls.combobox :refer [combobox*]] [app.main.ui.ds.controls.input :refer [input*]] @@ -15,6 +16,7 @@ [app.main.ui.ds.controls.radio-buttons :refer [radio-buttons*]] [app.main.ui.ds.controls.select :refer [select*]] [app.main.ui.ds.controls.switch :refer [switch*]] + [app.main.ui.ds.controls.textarea :refer [textarea*]] [app.main.ui.ds.controls.utilities.hint-message :refer [hint-message*]] [app.main.ui.ds.controls.utilities.input-field :refer [input-field*]] [app.main.ui.ds.controls.utilities.label :refer [label*]] @@ -38,17 +40,24 @@ [app.main.ui.ds.product.branch-row :refer [branch-row*]] [app.main.ui.ds.product.branch-status :refer [branch-status*]] [app.main.ui.ds.product.change-row :refer [change-row*]] + [app.main.ui.ds.product.comment-card :refer [comment-card*]] [app.main.ui.ds.product.cta :refer [cta*]] [app.main.ui.ds.product.empty-placeholder :refer [empty-placeholder*]] [app.main.ui.ds.product.empty-state :refer [empty-state*]] [app.main.ui.ds.product.filter-chip :refer [filter-chip*]] [app.main.ui.ds.product.input-with-meta :refer [input-with-meta*]] + [app.main.ui.ds.product.layer-chip :refer [layer-chip*]] [app.main.ui.ds.product.loader :refer [loader*]] [app.main.ui.ds.product.milestone :refer [milestone*]] [app.main.ui.ds.product.milestone-group :refer [milestone-group*]] [app.main.ui.ds.product.panel-title :refer [panel-title*]] [app.main.ui.ds.product.preview-card :refer [preview-card*]] + [app.main.ui.ds.product.progress-bar :refer [progress-bar*]] + [app.main.ui.ds.product.review-label :refer [review-label*]] + [app.main.ui.ds.product.review-marker :refer [review-marker*]] [app.main.ui.ds.product.tag :refer [tag*]] + [app.main.ui.ds.product.task-row :refer [task-row*]] + [app.main.ui.ds.product.task-status :refer [task-status*]] [app.main.ui.ds.storybook :as sb] [app.main.ui.ds.tooltip.tooltip :refer [tooltip*]] [app.main.ui.ds.utilities.date :refer [date*]] @@ -97,6 +106,15 @@ :FilterChip filter-chip* :PreviewCard preview-card* :Tag tag* + :CommentCard comment-card* + :LayerChip layer-chip* + :LinkButton link-button* + :ProgressBar progress-bar* + :ReviewLabel review-label* + :ReviewMarker review-marker* + :Textarea textarea* + :TaskRow task-row* + :TaskStatus task-status* :Milestone milestone* :MilestoneGroup milestone-group* :Date date* diff --git a/frontend/src/app/main/ui/ds/buttons/link_button.cljs b/frontend/src/app/main/ui/ds/buttons/link_button.cljs new file mode 100644 index 0000000000..a641a2fad7 --- /dev/null +++ b/frontend/src/app/main/ui/ds/buttons/link_button.cljs @@ -0,0 +1,35 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. +;; +;; Copyright (c) KALEIDOS SUBSIDIARY SL + +(ns app.main.ui.ds.buttons.link-button + (:require-macros + [app.main.style :as stl]) + (:require + [app.common.data :as d] + [app.main.ui.ds.foundations.assets.icon :refer [icon*] :as i] + [rumext.v2 :as mf])) + +(def ^:private schema:link-button + [:map + [:class {:optional true} [:maybe :string]] + [:icon {:optional true} [:maybe [:and :string [:fn #(contains? i/icon-list %)]]]] + [:tone {:optional true} [:maybe [:enum "accent" "info" "neutral"]]]]) + +(mf/defc link-button* + "An action that reads as a link inside a line of text: no box, underlined + on hover. `icon` goes before the text." + {::mf/schema schema:link-button} + [{:keys [class icon tone children] :rest props}] + (let [tone (d/nilv tone "accent") + props (mf/spread-props props + {:class [class (stl/css-case :link-button true + :tone-info (= tone "info") + :tone-neutral (= tone "neutral"))] + :type "button"})] + [:> :button props + (when icon + [:> icon* {:icon-id icon :size "s"}]) + children])) diff --git a/frontend/src/app/main/ui/ds/buttons/link_button.mdx b/frontend/src/app/main/ui/ds/buttons/link_button.mdx new file mode 100644 index 0000000000..83f30df077 --- /dev/null +++ b/frontend/src/app/main/ui/ds/buttons/link_button.mdx @@ -0,0 +1,30 @@ +{ /* This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + + Copyright (c) KALEIDOS SUBSIDIARY SL */ } + +import { Canvas, Meta } from '@storybook/addon-docs/blocks'; +import * as LinkButton from "./link_button.stories"; + + + +# LinkButton + +An action that reads as a link inside a line of text. + + + +## Variants + +`tone` is `accent` (default), `info` or `neutral`. + +## Technical notes + +It renders a `button`, so use it for actions; a link that navigates is an +`a`. `icon` goes before the text. + +```clj +[:> link-button* {:icon i/add :on-click on-add} + (tr "workspace.tasks.new-task")] +``` diff --git a/frontend/src/app/main/ui/ds/buttons/link_button.scss b/frontend/src/app/main/ui/ds/buttons/link_button.scss new file mode 100644 index 0000000000..02ad53690c --- /dev/null +++ b/frontend/src/app/main/ui/ds/buttons/link_button.scss @@ -0,0 +1,34 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// +// Copyright (c) KALEIDOS SUBSIDIARY SL + +@use "ds/typography.scss" as *; + +.link-button { + --link-button-fg-color: var(--color-accent-primary); + + @include use-typography("body-small"); + + display: inline-flex; + align-items: center; + gap: var(--sp-xs); + padding: 0; + border: none; + background: none; + color: var(--link-button-fg-color); + cursor: pointer; + + &:hover { + text-decoration: underline; + } + + &.tone-info { + --link-button-fg-color: var(--color-accent-info); + } + + &.tone-neutral { + --link-button-fg-color: var(--color-foreground-secondary); + } +} diff --git a/frontend/src/app/main/ui/ds/buttons/link_button.stories.jsx b/frontend/src/app/main/ui/ds/buttons/link_button.stories.jsx new file mode 100644 index 0000000000..918edf6fa1 --- /dev/null +++ b/frontend/src/app/main/ui/ds/buttons/link_button.stories.jsx @@ -0,0 +1,38 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// +// Copyright (c) KALEIDOS SUBSIDIARY SL + +import * as React from "react"; +import Components from "@target/components"; + +const { LinkButton } = Components; + +export default { + title: "Buttons/LinkButton", + component: LinkButton, + argTypes: { + tone: { + options: ["accent", "info", "neutral"], + control: { type: "select" }, + }, + }, + args: { + tone: "accent", + children: "See more", + }, + render: ({ ...args }) => , +}; + +export const Default = {}; + +export const AllTones = { + render: () => ( +
+ Accent + Info + Neutral +
+ ), +}; diff --git a/frontend/src/app/main/ui/ds/controls/select.cljs b/frontend/src/app/main/ui/ds/controls/select.cljs index 3d7a65b9a3..23869811a2 100644 --- a/frontend/src/app/main/ui/ds/controls/select.cljs +++ b/frontend/src/app/main/ui/ds/controls/select.cljs @@ -312,7 +312,9 @@ :empty-to-end empty-to-end :ref set-option-ref :wrapper-ref dropdown-wrapper-ref}]) - container) + ;; a modal makes everything outside it inert: its dropdown stays inside + (or (some-> (mf/ref-val select-ref) (.closest "[role='dialog']")) + container)) [:> options-dropdown* {:on-click on-option-click :id listbox-id :options options diff --git a/frontend/src/app/main/ui/ds/controls/textarea.cljs b/frontend/src/app/main/ui/ds/controls/textarea.cljs new file mode 100644 index 0000000000..8955b677fb --- /dev/null +++ b/frontend/src/app/main/ui/ds/controls/textarea.cljs @@ -0,0 +1,23 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. +;; +;; Copyright (c) KALEIDOS SUBSIDIARY SL + +(ns app.main.ui.ds.controls.textarea + (:require-macros + [app.main.style :as stl]) + (:require + [rumext.v2 :as mf])) + +(def ^:private schema:textarea + [:map + [:class {:optional true} [:maybe :string]]]) + +(mf/defc textarea* + "A text area of several lines. It takes the props of a `textarea`; name + it with `aria-label` or a `label`." + {::mf/schema schema:textarea} + [{:keys [class] :rest props}] + (let [props (mf/spread-props props {:class [class (stl/css :textarea)]})] + [:> :textarea props])) diff --git a/frontend/src/app/main/ui/ds/controls/textarea.mdx b/frontend/src/app/main/ui/ds/controls/textarea.mdx new file mode 100644 index 0000000000..68bc72a625 --- /dev/null +++ b/frontend/src/app/main/ui/ds/controls/textarea.mdx @@ -0,0 +1,29 @@ +{ /* This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + + Copyright (c) KALEIDOS SUBSIDIARY SL */ } + +import { Canvas, Meta } from '@storybook/addon-docs/blocks'; +import * as Textarea from "./textarea.stories"; + + + +# Textarea + +A text area of several lines. + + + +## Technical notes + +It takes the props of a `textarea` (`value`, `rows`, `max-length`, +`placeholder`, `on-change`...). Name it with `aria-label` or a `label`. +Set `--textarea-resize` through `class` to change how it resizes. + +```clj +[:> textarea* {:value value + :rows 3 + :aria-label (tr "workspace.tasks.title") + :on-change on-change}] +``` diff --git a/frontend/src/app/main/ui/ds/controls/textarea.scss b/frontend/src/app/main/ui/ds/controls/textarea.scss new file mode 100644 index 0000000000..8602dd0937 --- /dev/null +++ b/frontend/src/app/main/ui/ds/controls/textarea.scss @@ -0,0 +1,30 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// +// Copyright (c) KALEIDOS SUBSIDIARY SL + +@use "ds/_borders.scss" as *; +@use "ds/typography.scss" as *; + +.textarea { + --textarea-border-color: var(--color-background-quaternary); + + @include use-typography("body-small"); + + inline-size: 100%; + padding: var(--sp-s); + border: $b-1 solid var(--textarea-border-color); + border-radius: $br-8; + background-color: var(--color-background-tertiary); + color: var(--color-foreground-primary); + + // a caller may fix its height + resize: var(--textarea-resize, vertical); + + &:focus { + --textarea-border-color: var(--color-accent-primary); + + outline: none; + } +} diff --git a/frontend/src/app/main/ui/ds/controls/textarea.stories.jsx b/frontend/src/app/main/ui/ds/controls/textarea.stories.jsx new file mode 100644 index 0000000000..faf29d2a1b --- /dev/null +++ b/frontend/src/app/main/ui/ds/controls/textarea.stories.jsx @@ -0,0 +1,27 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +// +// Copyright (c) KALEIDOS SUBSIDIARY SL + +import * as React from "react"; +import Components from "@target/components"; + +const { Textarea } = Components; + +export default { + title: "Controls/Textarea", + component: Textarea, + args: { + rows: 3, + placeholder: "What needs to be done?", + "aria-label": "Title", + }, + render: ({ ...args }) => ( +
+