✨ Add review mode, review comments and tasks to design reviews (#12939)

* ✨ Add review mode, review comments and tasks to design reviews

A design review now opens a read-only review mode. The left panel shows
the pages and layers with the View only badge, the toolbar offers the
review tools (move, comment, comment an area, create a task, show the
changes) and the right panel holds the inspect of the selection, the
comments of the review and its tasks. A bar at the bottom names the
review, shows the progress of its tasks and opens its details.

Comments can point at a spot, a layer or an area, and a comment written
in a review says so with its own mark, wherever the file is open. The
layers panel counts the open comments of each layer.

Tasks are new: work on a file, assigned to someone and tied to a layer
or to a spot of the canvas. A comment can become a task and stays
attached to it. A task moves through open, done, verified, reopened and
won't do; anybody may move it, and each move is an event that records
who made it. Deleting a layer with open tasks moves them to its board
and offers to undo the deletion or to mark them done; a task can then
be linked to another layer or get its layer back. Assignees are told by
email. Merging a branch moves its tasks and their threads into main:
the open ones keep going, the closed ones stay as its history, and the
merge dialog lists them and can tell their assignees.

The details of a review show its overview, its tasks and its activity:
what the saves of the branch did to each layer since the review opened,
by person and day, with the values before and after. The changes can be
shown on the canvas one after another.

The backend adds the review fields of a comment thread, the task and
task event tables, the activity of a review (recorded by each save of a
branch under review) and the commands of the tasks.

* ♻️ Bring the design review styles and components up to the DS

Move what the review UI repeated into the design system: layer-chip*,
progress-bar*, comment-card*, link-button* and textarea*, each with its
story and docs. The screens keep the look they had: the same review states
compare equal, pixel by pixel, before and after.

The stylesheets follow the rules of the UI guide: local variables for the
colors that change by state, the right tokens, no unused imports and fewer
element and nested selectors. What has no DS token or typography says so in
a TODO. The aliases left in comments.scss resolve to their tokens.

The components get complete schemas and a single owner for the copyright.
Translations take literal keys and templates instead of dynamic keys and
glued strings, and comments.cljs no longer depends on the review tasks: the
workspace passes it what a thread shows about its task.

Fix three bugs of the review:

- The inspect took the width of a narrower panel and its height from the
  window, so it looked squeezed and cut its last rows. It now fills the
  panel that holds it.
- Enter on the menu of a task opened the task. The row now reacts only to
  keys on itself, and the menu keeps Enter from the workspace shortcuts.
- The resolved and lost marks ignored the pointer: hover now wins over the
  state of a mark.

* ✨ Turn each review message into a task and restore the filter dropdown

Each message of a thread can now become a task, so one thread can hold
several. The new file_task.comment_id column records the message, the
migration fills it with the first message of the thread for existing tasks,
and the backend rejects a message from another thread or one that already
has a task.

Comments and tasks of a review behave like normal ones. The canvas marks
show a short preview on hover and there is one mark per task. A blue label
marks what belongs to a review, in the thread and in the sidebar, and a
selected card takes a blue border there and the primary color elsewhere.
The new review-label* component holds the label.

The sidebar and the review panel go back to a filter dropdown in place of
the chips. Comments offer the views all, yours and mentions, with an option
to hide the resolved ones. Tasks offer all, yours, open and to verify, with
an option to hide the closed ones. Resolved comments now show by default.

"New task" outside a review now arms the task tool: it shows the task cursor
and the next click opens the task form, not a comment. Then the comment tool
returns, and Esc leaves the tool.

The details modal shows changed properties in the format of the compare
dialogs, and showing a task on the canvas syncs the WASM viewport. The sidebar
cards put the layer chip on the line of the replies, and task states lose the
dot and take a color each.

Fix these bugs:

- The hover card of the activity tab crashed on a change with no token.
- The assignee and reviewer dropdowns came out cut. The select now portals
  into the closest dialog, because the modal makes the rest of the page inert.
- The review label cut the header of the thread. It now sits below it.

* ✨ Group overlapping review marks and let tasks change assignee

Comments and tasks of a review that fall on the same spot now show as one
mark with a counter in a white bubble. A click fans them out, as the comment
bubbles do, and the user picks one. They group on the same layer and, by
proximity, at a low zoom. The card of the mark lists up to five items.

Hovering a mark outlines its layer, or its board when the layer is gone. The
WASM viewport draws no outlines under the comments tool, so it now draws the
highlighted ones there. Opening a comment from a mark closes the open task.

A task can change assignee from the selector in its state and from "Assign
to" in its menu, which holds the team in the same popover. The change shows
right away and goes to the history of the task. A closed task keeps its
assignee.

Deleting a task or a comment now asks first, with the usual confirmation. A
task deleted from the details of a review brings the dialog back on its tab.

The state of a task takes two rows, in its panel and in a thread: state and
layer, then assignee and the review it comes from, which a review omits. The
text of tasks and comments sits in a box. The history no longer says that the
task was created.

* ✨ Keep the branch bar and the palettes at one level on a branch

The open branch bar covered the horizontal scroll of the canvas. It now sits
as far from the bottom as the review bar. Folded, it stays flush.

On a branch the palettes no longer lift over the branch bar: both sit at the
same level and work as a toggle. Opening one folds the other, also through
the palette shortcuts, and both can stay folded. The new `:bottom-bar` state
says which one is open. It exists only while the branch bar does, so a file
that is not a branch keeps the palettes on their layout flags and at their
usual place, and what happens on a branch does not reach them.

The branch bar comes open on a branch and centers on the canvas, not on the
window, so that it clears the folded palettes at usual widths. The room it
published for the palettes goes away with the lifting.

* ✨ Give every task a thread and tidy the design review screens

Every task now lives in a message of a comment thread, so anyone can go on
commenting on it. A task made from scratch gets a thread whose first message
is its title, on its layer and in its review, created in the same
transaction. A comment turned into a task keeps its thread, as before. The
panel of a task with no thread is gone: a task always opens as its thread.
Migration 0814 gives a thread to the tasks that had none. Deleting a thread
deletes its tasks, after a confirmation that says so.

The anchor of a task was a plain map, not a point, so a thread on a layer
refused replies. It is now a point.

The details of a review filter the tasks by state with the chips of the
activity, in the colour of each state, and show how many are closed on the
right. The "New task" button leaves the dialog.

Descriptions look the same everywhere: the box of the branch info dialog,
an "Edit" button and a dashed box when empty. Read, they grow up to 400px
and scroll inside; edited, the textarea starts at 400px. The text of a
review in the sidebar does the same once unfolded.

In the review bar, the author gets a "Publish latest changes" button when
the branch moved past the review, with a hint that approvals must be
renewed. The others keep a badge, now "Unpublished changes", with a hint.
The bar refreshes once the publish lands.

Smaller changes: the resolve checkbox lines up with the task button and has
a tooltip, messages sit in a filled box, task events take an outline, and
the change navigator sits right above the review bar.

* 💄 Sort the test runner requires that cljfmt rejects

The Frontend Tests lint step fails on runner.cljs: the requires for
workspace-tasks-test, review-details-test and review-markers-test sat
out of alphabetical order. This is the output of cljfmt fix.

AI-assisted-by: claude-opus-5-5
Signed-off-by: Álvaro Tejero Cantero <alvorithm@teje.ro>

* 🐛 Test the design review mode in the pull request spec

The review bar replaced the branch banner, so four tests still drove
the branch bar: a visible Compare button, the rectangle tool and the
Review button. They now drive the design review instead.

* Opening a file with a pr-id enters the review: the bar names the
  review, the header trades the file name for the review title, and
  comparing, merging and cancelling sit in the bar's options menu.
* The compare dialog opens from that menu.
* The review is read-only rather than an editable file: the review
  toolbar offers its five tools, the drawing tools are gone, the
  sidebar says View only, and the right panel is the review's own
  Inspect, Comments and Tasks tabs.
* The verdict comes from the bar's Submit review button and the
  dialog it opens, scoped by role so the bar action and the dialog
  action do not collide.

The tests also reach the review bar by its region label instead of
walking up three parents from the Reviewing the design review text,
which broke as soon as the bar's markup changed.

AI-assisted-by: claude-opus-5-5
Signed-off-by: Álvaro Tejero Cantero <alvorithm@teje.ro>

* 🐛 Count only the test thread's acquisitions in the climit test

acquires-the-command-own-limits-before-the-root-limits failed on CI
with an extra "root/global" ahead of the expected order. The test
records metrics through with-redefs, which is global, so a call of
another thread of the test JVM, such as an RPC an earlier test left
running, can take a root limiter inside the window and land in the
same atom.

Record the thread with each metrics call and keep, in
acquired-in-order, only the acquisitions of the calling thread. Both
tests that read it acquire their limiters on the test thread. The
same class of flake was fixed on develop for the waiting-count test
(12d73d0f63); this one is still open there.

AI-assisted-by: claude-opus-5-5
Signed-off-by: Álvaro Tejero Cantero <alvorithm@teje.ro>

* 📚 Describe the task moves the server allows in the table comment

The comment on file_task said a task is reopened only from done and
that editors move tasks. files_task.clj::transitions also reopens a
verified or won't-do task, and set-task-status lets anybody who can
read the file move one. Say the same in the schema.

AI-assisted-by: claude-opus-5-5
Signed-off-by: Álvaro Tejero Cantero <alvorithm@teje.ro>

---------

Signed-off-by: Álvaro Tejero Cantero <alvorithm@teje.ro>
Co-authored-by: Álvaro Tejero Cantero <alvorithm@teje.ro>
This commit is contained in:
Juan de la Cruz 2026-11-17 22:30:22 +01:00 committed by GitHub
parent 4cb0e452ff
commit ea61730f61
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
147 changed files with 12387 additions and 839 deletions

View File

@ -0,0 +1,244 @@
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml"
xmlns:o="urn:schemas-microsoft-com:office:office">
<head>
<title>
</title>
<!--[if !mso]><!-- -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!--<![endif]-->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">
#outlook a {
padding: 0;
}
body {
margin: 0;
padding: 0;
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
}
table,
td {
border-collapse: collapse;
mso-table-lspace: 0pt;
mso-table-rspace: 0pt;
}
img {
border: 0;
height: auto;
line-height: 100%;
outline: none;
text-decoration: none;
-ms-interpolation-mode: bicubic;
}
p {
display: block;
margin: 13px 0;
}
</style>
<!--[if mso]>
<xml>
<o:OfficeDocumentSettings>
<o:AllowPNG/>
<o:PixelsPerInch>96</o:PixelsPerInch>
</o:OfficeDocumentSettings>
</xml>
<![endif]-->
<!--[if lte mso 11]>
<style type="text/css">
.mj-outlook-group-fix { width:100% !important; }
</style>
<![endif]-->
<!--[if !mso]><!-->
<link href="https://fonts.googleapis.com/css?family=Source%20Sans%20Pro" rel="stylesheet" type="text/css">
<style type="text/css">
@import url(https://fonts.googleapis.com/css?family=Source%20Sans%20Pro);
</style>
<!--<![endif]-->
<style type="text/css">
@media only screen and (min-width:480px) {
.mj-column-per-100 {
width: 100% !important;
max-width: 100%;
}
.mj-column-px-425 {
width: 425px !important;
max-width: 425px;
}
}
</style>
<style type="text/css">
@media only screen and (max-width:480px) {
table.mj-full-width-mobile {
width: 100% !important;
}
td.mj-full-width-mobile {
width: auto !important;
}
}
</style>
</head>
<body style="background-color:#E5E5E5;">
<div style="background-color:#E5E5E5;">
<!--[if mso | IE]>
<table
align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600"
>
<tr>
<td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;">
<![endif]-->
<div style="margin:0px auto;max-width:600px;">
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td style="direction:ltr;font-size:0px;padding:0;text-align:center;">
<!--[if mso | IE]>
<table role="presentation" border="0" cellpadding="0" cellspacing="0">
<tr>
<td
class="" style="vertical-align:top;width:600px;"
>
<![endif]-->
<div class="mj-column-per-100 mj-outlook-group-fix"
style="font-size:0px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">
<table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;"
width="100%">
<tr>
<td align="left" style="font-size:0px;padding:16px;word-break:break-word;">
<table border="0" cellpadding="0" cellspacing="0" role="presentation"
style="border-collapse:collapse;border-spacing:0px;">
<tbody>
<tr>
<td style="width:97px;">
<img height="32" src="{{ public-uri }}/images/email/logo-penpot.svg"
style="border:0;display:block;outline:none;text-decoration:none;height:32px;width:100%;font-size:13px;"
width="97" />
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<![endif]-->
</td>
</tr>
</tbody>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<table
align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600"
>
<tr>
<td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;">
<![endif]-->
<div style="background:#FFFFFF;background-color:#FFFFFF;margin:0px auto;max-width:600px;">
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation"
style="background:#FFFFFF;background-color:#FFFFFF;width:100%;">
<tbody>
<tr>
<td style="direction:ltr;font-size:0px;padding:20px 0;text-align:center;">
<!--[if mso | IE]>
<table role="presentation" border="0" cellpadding="0" cellspacing="0">
<tr>
<td
class="" style="vertical-align:top;width:600px;"
>
<![endif]-->
<div class="mj-column-per-100 mj-outlook-group-fix"
style="font-size:0px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">
<table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;"
width="100%">
<tr>
<td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;">
<div
style="font-family:Source Sans Pro, sans-serif;font-size:24px;font-weight:600;line-height:150%;text-align:left;color:#000000;">
Hello {{name|abbreviate:25}}!</div>
</td>
</tr>
<tr>
<td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;">
<div
style="font-family:Source Sans Pro, sans-serif;font-size:16px;line-height:150%;text-align:left;color:#000000;">
<span style="font-weight:bold;">{{ source-user }}</span> assigned you a task:</div>
</td>
</tr>
<tr>
<td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;">
<div style="font-family:Source Sans Pro, sans-serif;font-size:16px;font-style:italic;line-height:150%;text-align:left;color:#212426;
border-top: 1px solid #bfbfbf; border-bottom: 1px solid #bfbfbf; padding: 32px 0px;">
{{ task-title }}
</div>
</td>
</tr>
<tr>
<td align="center" vertical-align="middle"
style="font-size:0px;padding:10px 25px;word-break:break-word;">
<table border="0" cellpadding="0" cellspacing="0" role="presentation"
style="border-collapse:separate;line-height:100%;">
<tr>
<td align="center" bgcolor="#6911d4" role="presentation"
style="border:none;border-radius:8px;cursor:auto;mso-padding-alt:10px 25px;background:#6911d4;"
valign="middle">
<a href="{{ task-url }}"
style="display:inline-block;background:#6911d4;color:#FFFFFF;font-family:Source Sans Pro, sans-serif;font-size:16px;font-weight:normal;line-height:120%;margin:0;text-decoration:none;text-transform:none;padding:10px 25px;mso-padding-alt:0px;border-radius:8px;"
target="_blank"> OPEN THE TASK </a>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;">
<div
style="font-family:Source Sans Pro, sans-serif;font-size:16px;line-height:150%;text-align:left;color:#000000;">
The Penpot team.</div>
</td>
</tr>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<![endif]-->
</td>
</tr>
</tbody>
</table>
</div>
{% include "app/email/includes/footer.html" %}
</div>
</body>
</html>

View File

@ -0,0 +1 @@
You have a new task

View File

@ -0,0 +1,9 @@
Hello {{name|abbreviate:25}}!
{{ source-user }} assigned you a task:
{{ task-title }}
{{ task-url }}
The Penpot team.

View File

@ -0,0 +1,244 @@
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml"
xmlns:o="urn:schemas-microsoft-com:office:office">
<head>
<title>
</title>
<!--[if !mso]><!-- -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!--<![endif]-->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">
#outlook a {
padding: 0;
}
body {
margin: 0;
padding: 0;
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
}
table,
td {
border-collapse: collapse;
mso-table-lspace: 0pt;
mso-table-rspace: 0pt;
}
img {
border: 0;
height: auto;
line-height: 100%;
outline: none;
text-decoration: none;
-ms-interpolation-mode: bicubic;
}
p {
display: block;
margin: 13px 0;
}
</style>
<!--[if mso]>
<xml>
<o:OfficeDocumentSettings>
<o:AllowPNG/>
<o:PixelsPerInch>96</o:PixelsPerInch>
</o:OfficeDocumentSettings>
</xml>
<![endif]-->
<!--[if lte mso 11]>
<style type="text/css">
.mj-outlook-group-fix { width:100% !important; }
</style>
<![endif]-->
<!--[if !mso]><!-->
<link href="https://fonts.googleapis.com/css?family=Source%20Sans%20Pro" rel="stylesheet" type="text/css">
<style type="text/css">
@import url(https://fonts.googleapis.com/css?family=Source%20Sans%20Pro);
</style>
<!--<![endif]-->
<style type="text/css">
@media only screen and (min-width:480px) {
.mj-column-per-100 {
width: 100% !important;
max-width: 100%;
}
.mj-column-px-425 {
width: 425px !important;
max-width: 425px;
}
}
</style>
<style type="text/css">
@media only screen and (max-width:480px) {
table.mj-full-width-mobile {
width: 100% !important;
}
td.mj-full-width-mobile {
width: auto !important;
}
}
</style>
</head>
<body style="background-color:#E5E5E5;">
<div style="background-color:#E5E5E5;">
<!--[if mso | IE]>
<table
align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600"
>
<tr>
<td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;">
<![endif]-->
<div style="margin:0px auto;max-width:600px;">
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td style="direction:ltr;font-size:0px;padding:0;text-align:center;">
<!--[if mso | IE]>
<table role="presentation" border="0" cellpadding="0" cellspacing="0">
<tr>
<td
class="" style="vertical-align:top;width:600px;"
>
<![endif]-->
<div class="mj-column-per-100 mj-outlook-group-fix"
style="font-size:0px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">
<table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;"
width="100%">
<tr>
<td align="left" style="font-size:0px;padding:16px;word-break:break-word;">
<table border="0" cellpadding="0" cellspacing="0" role="presentation"
style="border-collapse:collapse;border-spacing:0px;">
<tbody>
<tr>
<td style="width:97px;">
<img height="32" src="{{ public-uri }}/images/email/logo-penpot.svg"
style="border:0;display:block;outline:none;text-decoration:none;height:32px;width:100%;font-size:13px;"
width="97" />
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<![endif]-->
</td>
</tr>
</tbody>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<table
align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600"
>
<tr>
<td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;">
<![endif]-->
<div style="background:#FFFFFF;background-color:#FFFFFF;margin:0px auto;max-width:600px;">
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation"
style="background:#FFFFFF;background-color:#FFFFFF;width:100%;">
<tbody>
<tr>
<td style="direction:ltr;font-size:0px;padding:20px 0;text-align:center;">
<!--[if mso | IE]>
<table role="presentation" border="0" cellpadding="0" cellspacing="0">
<tr>
<td
class="" style="vertical-align:top;width:600px;"
>
<![endif]-->
<div class="mj-column-per-100 mj-outlook-group-fix"
style="font-size:0px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">
<table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;"
width="100%">
<tr>
<td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;">
<div
style="font-family:Source Sans Pro, sans-serif;font-size:24px;font-weight:600;line-height:150%;text-align:left;color:#000000;">
Hello {{name|abbreviate:25}}!</div>
</td>
</tr>
<tr>
<td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;">
<div
style="font-family:Source Sans Pro, sans-serif;font-size:16px;line-height:150%;text-align:left;color:#000000;">
<span style="font-weight:bold;">{{ source-user }}</span> merged the branch "{{ branch-name }}" into "{{ file-name }}". Your open tasks moved to main as they were:</div>
</td>
</tr>
<tr>
<td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;">
<div style="font-family:Source Sans Pro, sans-serif;font-size:16px;font-style:italic;white-space:pre-line;line-height:150%;text-align:left;color:#212426;
border-top: 1px solid #bfbfbf; border-bottom: 1px solid #bfbfbf; padding: 32px 0px;">
{{ task-titles }}
</div>
</td>
</tr>
<tr>
<td align="center" vertical-align="middle"
style="font-size:0px;padding:10px 25px;word-break:break-word;">
<table border="0" cellpadding="0" cellspacing="0" role="presentation"
style="border-collapse:separate;line-height:100%;">
<tr>
<td align="center" bgcolor="#6911d4" role="presentation"
style="border:none;border-radius:8px;cursor:auto;mso-padding-alt:10px 25px;background:#6911d4;"
valign="middle">
<a href="{{ file-url }}"
style="display:inline-block;background:#6911d4;color:#FFFFFF;font-family:Source Sans Pro, sans-serif;font-size:16px;font-weight:normal;line-height:120%;margin:0;text-decoration:none;text-transform:none;padding:10px 25px;mso-padding-alt:0px;border-radius:8px;"
target="_blank"> OPEN THE FILE </a>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;">
<div
style="font-family:Source Sans Pro, sans-serif;font-size:16px;line-height:150%;text-align:left;color:#000000;">
The Penpot team.</div>
</td>
</tr>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<![endif]-->
</td>
</tr>
</tbody>
</table>
</div>
{% include "app/email/includes/footer.html" %}
</div>
</body>
</html>

View File

@ -0,0 +1 @@
Your tasks moved to main

View File

@ -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.

View File

@ -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,

View File

@ -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]

View File

@ -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;

View File

@ -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);

View File

@ -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;

View File

@ -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;

View File

@ -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;

View File

@ -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;

View File

@ -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

View File

@ -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))

View File

@ -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

View File

@ -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

View File

@ -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))))

View File

@ -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))

View File

@ -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

View File

@ -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

View File

@ -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}))))))))

View File

@ -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))))

View File

@ -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)))))

View File

@ -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

View File

@ -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();
});

View File

@ -0,0 +1,12 @@
<svg width="24px" height="24px" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
<path d="m6.9 12.519-2.5349 2.0222-0.17039-2.8021c-0.94178-0.55996-2.933-2.2948-3.3621-4.7515-0.42907-2.4551 2.6642-4.7755 4.2636-5.6282 3.7036-0.49567 10.862-0.12159 9.8685 5.3362-0.99444 5.4578-5.7908 6.1564-8.0655 5.8234z" fill="#fff"/>
<path d="m7.8642 0.38698c-2.26 0.027882-4.5687 0.88679-6.1014 2.586-1.0146 1.1052-1.6148 2.6201-1.4816 4.1296 0.10533 1.7488 1.1292 3.3396 2.4939 4.3929 0.25093 0.19827 0.51271 0.3826 0.77991 0.55841 0.029431 0.98902-0.026333 1.9858 0.072802 2.9694 0.16342 0.39731 0.73731 0.49567 1.0432 0.20369 0.81244-0.66993 1.6334-1.3306 2.4466-2.0013 0.76055 0.07745 1.5319 0.03486 2.2878-0.06815 2.1283-0.3462 4.1807-1.4994 5.3749-3.3257 0.81089-1.2214 1.1772-2.7618 0.85581-4.2055-0.31212-1.4847-1.2764-2.7711-2.4962-3.6447-1.5164-1.1036-3.4101-1.6303-5.2758-1.5947zm0.17426 1.3089c1.8696 0.00697 3.8027 0.65677 5.1217 2.0307 0.80392 0.82251 1.3282 1.9533 1.2686 3.1072-0.02478 1.3089-0.72647 2.5364-1.6961 3.3892-1.3848 1.2314-3.2792 1.8216-5.1101 1.7209-0.31599 0.01084-0.63973-0.08829-0.94642-0.04957-0.59868 0.48715-1.1966 0.97431-1.7937 1.4622-0.01549-0.6893-0.012392-1.3794-0.020137-2.0694-1.3677-0.68929-2.6093-1.8046-3.0871-3.2939-0.41203-1.2547-0.17503-2.7068 0.64515-3.7563 1.2911-1.7372 3.51-2.5519 5.6181-2.5403z" color="#000000"/>
<g fill="#000000">
<rect x="4.3" y="4.3" width="1.3" height="1.3" rx="0.3"/>
<rect x="6.6" y="4.45" width="4.6" height="1" rx="0.5"/>
<rect x="4.3" y="6.6" width="1.3" height="1.3" rx="0.3"/>
<rect x="6.6" y="6.75" width="4.6" height="1" rx="0.5"/>
<rect x="4.3" y="8.9" width="1.3" height="1.3" rx="0.3"/>
<rect x="6.6" y="9.05" width="4.6" height="1" rx="0.5"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.7 KiB

View File

@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" stroke-linecap="round" stroke-linejoin="round">
<path d="M4 1.333V10.667c0 .736.597 1.333 1.333 1.333h9.334M1.333 4H10.667c.736 0 1.333.597 1.333 1.333v9.334"/>
</svg>

After

Width:  |  Height:  |  Size: 232 B

View File

@ -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)

View File

@ -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

View File

@ -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

View File

@ -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)

View File

@ -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!

View File

@ -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)

View File

@ -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"))

View File

@ -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))))

View File

@ -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)))))))

View File

@ -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)))}

View File

@ -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))))

View File

@ -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))

View File

@ -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}]])

View File

@ -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}

View File

@ -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);
}

View File

@ -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)

View File

@ -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))

View File

@ -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*

View File

@ -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]))

View File

@ -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";
<Meta title="Buttons/LinkButton" />
# LinkButton
An action that reads as a link inside a line of text.
<Canvas of={LinkButton.AllTones} />
## 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")]
```

View File

@ -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);
}
}

View File

@ -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 }) => <LinkButton {...args} />,
};
export const Default = {};
export const AllTones = {
render: () => (
<div style={{ display: "flex", gap: "16px" }}>
<LinkButton>Accent</LinkButton>
<LinkButton tone="info">Info</LinkButton>
<LinkButton tone="neutral">Neutral</LinkButton>
</div>
),
};

View File

@ -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

View File

@ -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]))

View File

@ -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";
<Meta title="Controls/Textarea" />
# Textarea
A text area of several lines.
<Canvas of={Textarea.Default} />
## 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}]
```

View File

@ -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;
}
}

View File

@ -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 }) => (
<div style={{ inlineSize: "286px" }}>
<Textarea {...args} />
</div>
),
};
export const Default = {};

View File

@ -103,6 +103,7 @@
(def ^:icon-id collapse "collapse")
(def ^:icon-id column "column")
(def ^:icon-id column-reverse "column-reverse")
(def ^:icon-id comment-area "comment-area")
(def ^:icon-id comments "comments")
(def ^:icon-id component "component")
(def ^:icon-id component-copy "component-copy")

View File

@ -7,6 +7,7 @@
@use "ds/typography.scss" as t;
@use "ds/_borders.scss" as *;
@use "ds/_sizes.scss" as *;
@use "ds/_utils.scss" as *;
@mixin text-ellipsis {
display: block;
@ -25,6 +26,17 @@
-webkit-box-orient: vertical;
}
// The checkerboard of a transparent background, the same in both themes, so
// white, black and grey shapes all stand out from it.
@mixin transparency-checkerboard {
background-color: var(--color-static-white);
background-image: repeating-conic-gradient(
color-mix(in srgb, var(--color-canvas) 70%, var(--color-static-white)) 0% 25%,
transparent 0% 50%
);
background-size: px2rem(20) px2rem(20);
}
/// Custom Scrollbar Mixin
/// @param {Color} $thumb-color - Base thumb color
/// @param {Color} $thumb-hover-color - Thumb color on hover

View File

@ -25,6 +25,8 @@
[:tone {:optional true} [:maybe (into [:enum] tag/tones)]]
[:is-selected {:optional true} [:maybe :boolean]]
[:is-muted {:optional true} [:maybe :boolean]]
[:start {:optional true} [:maybe :any]]
[:end {:optional true} [:maybe :any]]
[:on-click {:optional true} [:maybe fn?]]])
(mf/defc change-row*

View File

@ -24,11 +24,9 @@
}
&:focus-visible {
outline: none;
}
--row-card-outline: #{$b-1} solid var(--color-accent-primary);
&:focus-visible .card {
outline: $b-1 solid var(--color-accent-primary);
outline: none;
}
&.is-muted {
@ -69,6 +67,7 @@
}
.card {
outline: var(--row-card-outline, none);
display: flex;
flex: 1;
align-items: center;

View File

@ -0,0 +1,72 @@
;; 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.product.comment-card
(:require-macros
[app.main.style :as stl])
(:require
[app.main.ui.ds.foundations.typography :as t]
[app.main.ui.ds.foundations.typography.text :refer [text*]]
[app.main.ui.ds.product.review-label :refer [review-label*]]
[app.util.dom :as dom]
[app.util.keyboard :as kbd]
[rumext.v2 :as mf]))
(def ^:private schema:comment-card
[:map
[:class {:optional true} [:maybe :string]]
[:location :string]
[:author :string]
[:time :string]
[:replies :string]
[:avatar {:optional true} [:maybe :any]]
[:anchor {:optional true} [:maybe :any]]
[:review {:optional true} [:maybe :string]]
[:is-review {:optional true} [:maybe :boolean]]
[:is-open {:optional true} [:maybe :boolean]]
[:is-resolved {:optional true} [:maybe :boolean]]
[:on-click {:optional true} [:maybe fn?]]])
(mf/defc comment-card*
"One comment of a list: where it is, who wrote it and when (`avatar`, an
avatar), its text (`children`), and its replies beside what it points at
(`anchor`, a chip). The whole card opens it. `review` names the design review
it belongs to, and `is-review` outlines it open in the review colour."
{::mf/schema schema:comment-card}
[{:keys [class location author time replies avatar anchor review is-review is-open is-resolved
on-click children]
:rest props}]
(let [on-key-down (mf/use-fn
(mf/deps on-click)
(fn [event]
;; the text may hold links: the keys on them are theirs
(when (and on-click
(identical? (dom/get-target event) (dom/get-current-target event))
(or (kbd/enter? event) (kbd/space? event)))
(dom/prevent-default event)
(on-click event))))
props (mf/spread-props props
{:class [class (stl/css-case :comment-card true
:is-open is-open
:is-review is-review
:is-resolved is-resolved)]
:role "button"
:tab-index 0
:on-click on-click
:on-key-down on-key-down})]
[:> :div props
[:> text* {:as "span" :typography t/body-small :class (stl/css :location)} location]
(when review
[:> review-label* {:label review}])
[:div {:class (stl/css :author)}
avatar
[:div {:class (stl/css :identity)}
[:> text* {:as "span" :typography t/body-small :class (stl/css :name)} author]
[:> text* {:as "span" :typography t/body-small :class (stl/css :muted)} time]]]
[:div {:class (stl/css :content)} children]
[:div {:class (stl/css :footer)}
[:> text* {:as "span" :typography t/body-small :class (stl/css :replies)} replies]
anchor]]))

View File

@ -0,0 +1,45 @@
{ /* 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 CommentCard from "./comment_card.stories";
<Meta title="Product/Review/CommentCard" />
# CommentCard
One comment of a list: where it is, who wrote it and when, its text and
its replies.
<Canvas of={CommentCard.Default} />
## Variants
`is-open` outlines the comment open on the canvas, in the review colour
with `is-review`; `is-resolved` fades a settled one. `review` shows the name
of the design review it belongs to.
<Canvas of={CommentCard.Open} />
<Canvas of={CommentCard.InAReview} />
<Canvas of={CommentCard.Resolved} />
## Technical notes
The card is a `role="button"` that reacts to Enter and Space. Two slots
take elements: `avatar` and `anchor` (a chip with what the comment points
at). The text of the comment goes in `children`. The caller translates
`location`, `time` and `replies`.
```clj
[:> comment-card* {:location "#1 - Board"
:author (:fullname owner)
:time (ct/timeago (:modified-at thread))
:replies (tr "workspace.review.comments.no-replies")
:avatar (mf/html [:> avatar* {:profile owner :variant "M"}])
:anchor (mf/html [:> layer-chip* {:label "Card form"}])
:on-click on-open}
(:content thread)]
```

View File

@ -0,0 +1,89 @@
// 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 *;
.comment-card {
--comment-card-bg-color: var(--color-background-tertiary);
--comment-card-border-color: transparent;
display: flex;
flex-direction: column;
align-items: flex-start;
gap: var(--sp-s);
inline-size: 100%;
padding: var(--sp-m);
border: $b-1 solid var(--comment-card-border-color);
border-radius: $br-8;
background-color: var(--comment-card-bg-color);
color: var(--color-foreground-primary);
text-align: start;
cursor: pointer;
&:hover {
--comment-card-bg-color: var(--color-background-quaternary);
}
&:focus-visible {
outline: $b-1 solid var(--color-accent-primary);
}
&.is-open {
--comment-card-border-color: var(--color-accent-primary);
}
&.is-open.is-review {
--comment-card-border-color: var(--color-accent-info);
}
&.is-resolved {
opacity: 0.7;
}
}
.location {
color: var(--color-foreground-secondary);
}
.author {
display: flex;
align-items: center;
gap: var(--sp-s);
}
.identity {
display: flex;
flex-direction: column;
}
.name {
color: var(--color-foreground-primary);
}
.muted {
color: var(--color-foreground-secondary);
}
.footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--sp-s);
inline-size: 100%;
}
.replies {
flex-shrink: 0;
color: var(--color-foreground-secondary);
}
.content {
@include use-typography("body-small");
color: var(--color-foreground-primary);
overflow-wrap: anywhere;
}

View File

@ -0,0 +1,55 @@
// 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 { CommentCard } = Components;
export default {
title: "Product/Review/CommentCard",
component: CommentCard,
argTypes: {
isOpen: { control: { type: "boolean" } },
isResolved: { control: { type: "boolean" } },
},
args: {
location: "#1 - Board",
author: "Ana Pérez",
time: "1 hour ago",
replies: "No replies",
children: "The summary should sit closer to the form.",
isOpen: false,
isResolved: false,
},
render: ({ ...args }) => (
<div style={{ inlineSize: "286px" }}>
<CommentCard {...args} />
</div>
),
};
export const Default = {};
export const Open = {
args: {
isOpen: true,
},
};
export const InAReview = {
args: {
review: "Checkout redesign",
isReview: true,
isOpen: true,
},
};
export const Resolved = {
args: {
isResolved: true,
},
};

View File

@ -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
(ns app.main.ui.ds.product.layer-chip
(:require-macros
[app.main.style :as stl])
(:require
[app.main.ui.ds.foundations.assets.icon :refer [icon*] :as i]
[rumext.v2 :as mf]))
(def ^:private schema:layer-chip
[:map
[:class {:optional true} [:maybe :string]]
[:label :string]
[:icon {:optional true} [:maybe [:and :string [:fn #(contains? i/icon-list %)]]]]
[:is-lost {:optional true} [:maybe :boolean]]
[:is-struck {:optional true} [:maybe :boolean]]])
(mf/defc layer-chip*
"A chip naming a layer, or what a comment points at. A lost layer reads
in the warning tone, struck through when `is-struck`."
{::mf/schema schema:layer-chip}
[{:keys [class label icon is-lost is-struck] :rest props}]
(let [props (mf/spread-props props
{:class [class (stl/css-case :layer-chip true
:is-lost is-lost)]})]
[:> :span props
[:> icon* {:icon-id (if ^boolean is-lost i/triangle-alert (or icon i/board)) :size "s"}]
[:span {:class (stl/css-case :label true
:is-struck is-struck)}
label]]))

View File

@ -0,0 +1,31 @@
{ /* 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 LayerChip from "./layer_chip.stories";
<Meta title="Product/Review/LayerChip" />
# LayerChip
A chip naming a layer, or what a comment points at.
<Canvas of={LayerChip.AllChips} />
## Variants
`is-lost` marks a layer that was deleted: the chip turns orange and shows
a warning. `is-struck` also strikes its name through.
## Technical notes
`icon` replaces the board icon, except on a lost layer.
```clj
[:> layer-chip* {:label "Card form"
:icon i/pin
:is-lost (dwtk/lost? task)}]
```

View File

@ -0,0 +1,40 @@
// 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 *;
.layer-chip {
--layer-chip-bg-color: var(--color-background-quaternary);
--layer-chip-fg-color: var(--color-foreground-secondary);
@include use-typography("body-small");
display: inline-flex;
align-items: center;
gap: var(--sp-xs);
min-inline-size: 0;
max-inline-size: 100%;
padding: var(--sp-xxs) var(--sp-s);
border-radius: $br-4;
background-color: var(--layer-chip-bg-color);
color: var(--layer-chip-fg-color);
&.is-lost {
--layer-chip-bg-color: var(--color-background-warning);
--layer-chip-fg-color: var(--color-accent-warning);
}
}
.label {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.is-struck {
text-decoration: line-through;
}

View File

@ -0,0 +1,37 @@
// 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 { LayerChip } = Components;
export default {
title: "Product/Review/LayerChip",
component: LayerChip,
argTypes: {
isLost: { control: { type: "boolean" } },
isStruck: { control: { type: "boolean" } },
},
args: {
label: "Card form",
isLost: false,
isStruck: false,
},
render: ({ ...args }) => <LayerChip {...args} />,
};
export const Default = {};
export const AllChips = {
render: () => (
<div style={{ display: "flex", gap: "8px" }}>
<LayerChip label="Card form" />
<LayerChip label="Promo banner" isLost />
<LayerChip label="Promo banner" isLost isStruck />
</div>
),
};

View File

@ -5,7 +5,6 @@
// Copyright (c) KALEIDOS SUBSIDIARY SL
@use "ds/_borders.scss" as *;
@use "ds/_sizes.scss" as *;
@use "ds/_utils.scss" as *;
@use "ds/mixins.scss" as *;
@ -53,10 +52,7 @@
}
.stage {
// the checkerboard of a transparent background, the same in both
// themes (the DS swatch draws its transparency the same way), so
// white, black and grey shapes all stand out from it
--stage-check-color: color-mix(in srgb, var(--color-canvas) 70%, var(--color-static-white));
@include transparency-checkerboard;
display: flex;
align-items: center;
@ -67,9 +63,6 @@
padding: var(--sp-s);
overflow: hidden;
border-radius: $br-6;
background-color: var(--color-static-white);
background-image: repeating-conic-gradient(var(--stage-check-color) 0% 25%, transparent 0% 50%);
background-size: px2rem(20) px2rem(20);
&.is-large {
block-size: var(--preview-card-stage-large-block-size, #{px2rem(320)});

View File

@ -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
(ns app.main.ui.ds.product.progress-bar
(:require-macros
[app.main.style :as stl])
(:require
[app.common.data.macros :as dm]
[rumext.v2 :as mf]))
(def ^:private schema:progress-bar
[:map
[:class {:optional true} [:maybe :string]]
[:value :int]
[:total :int]])
(mf/defc progress-bar*
"A thin bar filled by how much of `total` is done (`value`). The caller
sizes it through `class`."
{::mf/schema schema:progress-bar}
[{:keys [class value total] :rest props}]
(let [percent (if (pos? total) (* 100 (/ value total)) 0)
props (mf/spread-props props
{:class [class (stl/css :progress-bar)]
:role "progressbar"
:aria-valuemin 0
:aria-valuemax total
:aria-valuenow value})]
[:> :span props
[:span {:class (stl/css :fill)
:style #js {:width (dm/str percent "%")}}]]))

View File

@ -0,0 +1,28 @@
{ /* 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 ProgressBar from "./progress_bar.stories";
<Meta title="Product/Review/ProgressBar" />
# ProgressBar
A thin bar filled by how much of a total is done.
<Canvas of={ProgressBar.Default} />
## Technical notes
It takes the width of its container: size it with `class`. Set
`--progress-bar-fill-radius` there to round the end of the fill. Add
`aria-hidden` when text next to it already says the same.
```clj
[:> progress-bar* {:value closed
:total total
:class (stl/css :tasks-progress)}]
```

View File

@ -0,0 +1,25 @@
// 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/_utils.scss" as *;
.progress-bar {
display: block;
block-size: px2rem(4);
border-radius: $br-4;
background-color: var(--color-background-quaternary);
overflow: hidden;
}
.fill {
display: block;
block-size: 100%;
// a caller may round the end of the fill
border-radius: var(--progress-bar-fill-radius, 0);
background-color: var(--color-accent-info);
}

View File

@ -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 * as React from "react";
import Components from "@target/components";
const { ProgressBar } = Components;
export default {
title: "Product/Review/ProgressBar",
component: ProgressBar,
argTypes: {
value: { control: { type: "number" } },
total: { control: { type: "number" } },
},
args: {
value: 2,
total: 7,
},
render: ({ ...args }) => (
<div style={{ inlineSize: "286px" }}>
<ProgressBar {...args} />
</div>
),
};
export const Default = {};

View File

@ -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
(ns app.main.ui.ds.product.review-label
(:require-macros
[app.main.style :as stl])
(:require
[app.main.ui.ds.foundations.assets.icon :refer [icon*] :as i]
[rumext.v2 :as mf]))
(def ^:private schema:review-label
[:map
[:class {:optional true} [:maybe :string]]
[:label :string]])
(mf/defc review-label*
"Says that a comment or a task belongs to a design review, with the name
of the review."
{::mf/schema schema:review-label}
[{:keys [class label] :rest props}]
(let [props (mf/spread-props props
{:class [class (stl/css :review-label)]
:title label})]
[:> :span props
[:> icon* {:icon-id i/git-pull-request-arrow :size "s"}]
[:span {:class (stl/css :text)} label]]))

View File

@ -0,0 +1,26 @@
{ /* 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 ReviewLabel from "./review_label.stories";
<Meta title="Product/Review/ReviewLabel" />
# ReviewLabel
Says that a comment or a task belongs to a design review, with the name of
the review.
<Canvas of={ReviewLabel.Default} />
## Technical notes
A long name is cut with an ellipsis, and the whole name shows as its
`title`.
```clj
[:> review-label* {:label (:review-title task)}]
```

View File

@ -0,0 +1,28 @@
// 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/mixins.scss" as *;
@use "ds/typography.scss" as *;
.review-label {
@include use-typography("body-small");
display: inline-flex;
flex-shrink: 0;
align-self: flex-start;
align-items: center;
gap: var(--sp-xxs);
max-inline-size: 100%;
padding: 0 var(--sp-xs);
border-radius: $br-4;
background-color: var(--color-background-info);
color: var(--color-accent-info);
}
.text {
@include text-ellipsis;
}

View File

@ -0,0 +1,25 @@
// 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 { ReviewLabel } = Components;
export default {
title: "Product/Review/ReviewLabel",
component: ReviewLabel,
args: {
label: "Checkout redesign",
},
render: ({ ...args }) => (
<div style={{ display: "flex", inlineSize: "286px" }}>
<ReviewLabel {...args} />
</div>
),
};
export const Default = {};

View File

@ -0,0 +1,59 @@
;; 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.product.review-marker
(: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:review-marker
[:map
[:class {:optional true} [:maybe :string]]
[:type {:optional true} [:maybe [:enum "comment" "task"]]]
[:state {:optional true} [:maybe [:enum "default" "active" "resolved" "lost" "ghost"]]]
[:label {:optional true} [:maybe :string]]
[:counter {:optional true} [:maybe :int]]
[:aria-label :string]])
(mf/defc review-marker*
"The mark a design review leaves on the canvas. A comment is a round
mark with its number; a task, a square one with the task icon. Active
is the one open now, resolved a comment already settled (it shows a
tick instead of its number), lost a mark whose layer was deleted and
ghost what stays where a group of marks fanned out from. `counter` is
the number of items a mark holds; a comment mark that holds several has
no number, so it shows the comments icon. It renders a button: the caller names
it (`aria-label`) and handles the click."
{::mf/schema schema:review-marker}
[{:keys [class type state label counter] :rest props}]
(let [type (d/nilv type "comment")
state (d/nilv state "default")
props (mf/spread-props props
{:class [class (stl/css-case :review-marker true
:is-task (= type "task")
:is-active (= state "active")
:is-resolved (= state "resolved")
:is-lost (= state "lost")
:is-ghost (= state "ghost"))]
:type "button"})]
[:> :button props
(cond
(= type "task")
[:> icon* {:icon-id i/view-as-list :size "s"}]
(= state "resolved")
[:> icon* {:icon-id i/tick :size "s"}]
(nil? label)
[:> icon* {:icon-id i/comments :size "s"}]
:else
label)
(when (some? counter)
[:span {:class (stl/css :counter)} counter])]))

View File

@ -0,0 +1,40 @@
{ /* 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 ReviewMarker from "./review_marker.stories";
<Meta title="Product/Review/ReviewMarker" />
# ReviewMarker
The mark a design review leaves on the canvas: a round mark with the
number of a comment, or a square one with the task icon.
<Canvas of={ReviewMarker.AllMarkers} />
## Variants
- `type`: `comment` (default) or `task`.
- `state`: `default`, `active` (the one open now), `resolved` (a settled
comment: a tick replaces its number) and `lost` (its layer was deleted:
a dashed orange outline) and `ghost` (what stays where a group of marks
fanned out from).
- `counter`: the number of items a mark holds, in a white bubble on its
top right corner. A comment mark with several comments has no `label`,
so it shows the comments icon.
## Technical notes
It renders a `button`. The caller names it with `aria-label` and handles
`on-click`; `label` is the number of a comment.
```clj
[:> review-marker* {:label (str (:seqn thread))
:state (if open? "active" "default")
:aria-label (tr "workspace.review.marker.comment" (:seqn thread))
:on-click on-open}]
```

View File

@ -0,0 +1,92 @@
// 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/_sizes.scss" as *;
@use "ds/_utils.scss" as *;
@use "ds/typography.scss" as *;
.review-marker {
--marker-fg-color: var(--color-foreground-primary);
--marker-bg-color: var(--color-background-info);
--marker-border-color: var(--color-accent-info);
--marker-border-style: solid;
@include use-typography("body-small");
position: relative;
display: inline-flex;
align-items: center;
justify-content: center;
inline-size: $sz-32;
block-size: $sz-32;
padding: 0;
border: $b-2 var(--marker-border-style) var(--marker-border-color);
border-radius: $br-circle;
background-color: var(--marker-bg-color);
color: var(--marker-fg-color);
// TODO: No exact DS typography match found.
// Closest match: body-small (weight 700 vs 400).
font-weight: 700;
cursor: pointer;
&:focus-visible {
outline: $b-1 solid var(--color-accent-primary);
outline-offset: $b-2;
}
&.is-task {
border-radius: $br-6;
}
&.is-active {
--marker-fg-color: var(--color-background-primary);
--marker-bg-color: var(--color-accent-info);
}
&.is-resolved {
--marker-fg-color: var(--color-foreground-secondary);
--marker-bg-color: var(--color-background-primary);
--marker-border-color: var(--color-foreground-secondary);
}
&.is-lost {
--marker-fg-color: var(--color-accent-warning);
--marker-bg-color: var(--color-background-warning);
--marker-border-color: var(--color-accent-warning);
--marker-border-style: dashed;
}
&.is-ghost {
--marker-bg-color: var(--color-background-primary);
--marker-border-style: dashed;
}
// after the states, which set the same color with the same specificity
&:hover {
--marker-border-color: var(--color-foreground-primary);
}
}
.counter {
@include use-typography("body-small");
position: absolute;
inset-block-start: px2rem(-8);
inset-inline-end: px2rem(-8);
display: inline-flex;
align-items: center;
justify-content: center;
min-inline-size: $sz-16;
block-size: $sz-16;
padding-inline: var(--sp-xxs);
border: $b-1 solid var(--marker-border-color);
border-radius: $sz-16;
background-color: var(--color-static-white);
color: var(--color-static-black);
font-weight: 700;
}

View File

@ -0,0 +1,61 @@
// 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 { ReviewMarker } = Components;
export default {
title: "Product/Review/ReviewMarker",
component: ReviewMarker,
argTypes: {
type: {
options: ["comment", "task"],
control: { type: "select" },
},
state: {
options: ["default", "active", "resolved", "lost", "ghost"],
control: { type: "select" },
},
label: {
control: { type: "text" },
},
counter: {
control: { type: "number" },
},
},
args: {
type: "comment",
state: "default",
label: "1",
"aria-label": "Comment 1",
},
render: ({ ...args }) => <ReviewMarker {...args} />,
};
export const Default = {};
export const AllMarkers = {
render: () => (
<div style={{ display: "flex", gap: "8px" }}>
<ReviewMarker label="1" aria-label="Comment 1" />
<ReviewMarker label="2" state="active" aria-label="Comment 2" />
<ReviewMarker state="resolved" aria-label="Comment 3" />
<ReviewMarker type="task" aria-label="Task" />
<ReviewMarker type="task" state="active" aria-label="Task" />
<ReviewMarker type="task" state="lost" aria-label="Task" />
<ReviewMarker type="task" counter={3} aria-label="3 tasks" />
<ReviewMarker counter={2} aria-label="2 comments" />
<ReviewMarker
type="task"
state="ghost"
counter={3}
aria-label="3 tasks"
/>
</div>
),
};

View File

@ -27,6 +27,8 @@
border-radius: $br-4;
background-color: var(--tag-bg-color);
color: var(--tag-fg-color);
// TODO: 10px is not a size of the DS typographies.
font-size: px2rem(10);
white-space: nowrap;

View File

@ -0,0 +1,78 @@
;; 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.product.task-row
(:require-macros
[app.main.style :as stl])
(:require
[app.common.data :as d]
[app.main.ui.ds.foundations.typography :as t]
[app.main.ui.ds.foundations.typography.text :refer [text*]]
[app.main.ui.ds.product.layer-chip :refer [layer-chip*]]
[app.main.ui.ds.product.review-label :refer [review-label*]]
[app.main.ui.ds.product.task-status :as ts :refer [task-status*]]
[app.util.dom :as dom]
[app.util.keyboard :as kbd]
[rumext.v2 :as mf]))
(def ^:private schema:task-row
[:map
[:class {:optional true} [:maybe :string]]
[:title :string]
[:status (into [:enum] ts/statuses)]
[:status-label :string]
[:layer {:optional true} [:maybe :string]]
[:is-layer-lost {:optional true} [:maybe :boolean]]
[:is-selected {:optional true} [:maybe :boolean]]
[:review {:optional true} [:maybe :string]]
[:is-review {:optional true} [:maybe :boolean]]
[:assignee {:optional true} [:maybe :any]]
[:actions {:optional true} [:maybe :any]]
[:on-click {:optional true} [:maybe fn?]]])
(mf/defc task-row*
"One task of a list: its title over its state and the layer it points
at, with the assignee (`assignee`, an avatar) and the actions of the
task (`actions`, a menu) at the end. A task whose layer was deleted
shows the layer it lost in the warning tone. `review` names the design
review it belongs to, and `is-review` outlines it selected in the review
colour."
{::mf/schema schema:task-row}
[{:keys [class title status status-label layer is-layer-lost is-selected review is-review
assignee actions on-click] :rest props}]
(let [is-selected (d/nilv is-selected false)
is-layer-lost (d/nilv is-layer-lost false)
on-key-down (mf/use-fn
(mf/deps on-click)
(fn [event]
;; the keys on the actions of the row are theirs
(when (and on-click
(identical? (dom/get-target event) (dom/get-current-target event))
(or (kbd/enter? event) (kbd/space? event)))
(dom/prevent-default event)
(on-click event))))
props (mf/spread-props props
{:class [class (stl/css-case :task-row true
:is-selected is-selected
:is-review is-review)]
:role "button"
:tab-index 0
:aria-pressed is-selected
:on-click on-click
:on-key-down on-key-down})]
[:> :div props
[:div {:class (stl/css :header)}
[:> text* {:as "span" :typography t/body-small :class (stl/css :title)} title]
(when actions
[:div {:class (stl/css :actions)} actions])]
(when review
[:> review-label* {:label review}])
[:div {:class (stl/css :footer)}
[:> task-status* {:status status :label status-label}]
(when layer
[:> layer-chip* {:label layer :is-lost is-layer-lost}])
(when assignee
[:div {:class (stl/css :assignee)} assignee])]]))

View File

@ -0,0 +1,46 @@
{ /* 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 TaskRow from "./task_row.stories";
<Meta title="Product/Review/TaskRow" />
# TaskRow
One task of a list: its title over its state and the layer it points at.
<Canvas of={TaskRow.Default} />
## Variants
`is-selected` outlines the task open on the canvas, in the review colour
with `is-review`. `review` shows the name of the design review it belongs to.
<Canvas of={TaskRow.Selected} />
<Canvas of={TaskRow.InAReview} />
`is-layer-lost` marks a task whose layer was deleted: the chip of the
layer turns orange and shows a warning.
<Canvas of={TaskRow.LostLayer} />
## Technical notes
The row is a `role="button"` that reacts to Enter and Space while the focus
is on the row itself. Two slots
take elements: `assignee` (an avatar, at the end of the second line)
and `actions` (a menu trigger, at the end of the title). A click inside
a slot must stop its propagation when it should not open the task.
```clj
[:> task-row* {:title (:title task)
:status (:status task)
:status-label (tr "workspace.tasks.status.open")
:layer "Card form"
:assignee (mf/html [:> avatar* {:profile assignee :variant "S"}])
:on-click on-open}]
```

View File

@ -0,0 +1,68 @@
// 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 *;
.task-row {
--task-row-bg-color: var(--color-background-tertiary);
--task-row-border-color: transparent;
display: flex;
flex-direction: column;
gap: var(--sp-s);
padding: var(--sp-m);
border: $b-1 solid var(--task-row-border-color);
border-radius: $br-8;
background-color: var(--task-row-bg-color);
color: var(--color-foreground-primary);
cursor: pointer;
&:hover {
--task-row-bg-color: var(--color-background-quaternary);
}
&:focus-visible {
outline: $b-1 solid var(--color-accent-primary);
}
&.is-selected {
--task-row-border-color: var(--color-accent-primary);
}
&.is-selected.is-review {
--task-row-border-color: var(--color-accent-info);
}
}
.header {
display: flex;
align-items: flex-start;
gap: var(--sp-s);
}
.title {
flex: 1;
min-inline-size: 0;
color: var(--color-foreground-primary);
}
.actions {
flex-shrink: 0;
margin-block: calc(var(--sp-xs) * -1);
}
.footer {
display: flex;
align-items: center;
gap: var(--sp-s);
min-inline-size: 0;
}
.assignee {
display: flex;
flex-shrink: 0;
margin-inline-start: auto;
}

View File

@ -0,0 +1,66 @@
// 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 { TaskRow } = Components;
export default {
title: "Product/Review/TaskRow",
component: TaskRow,
argTypes: {
status: {
options: ["open", "done", "reopened", "verified", "wont-do"],
control: { type: "select" },
},
isSelected: {
control: { type: "boolean" },
},
isLayerLost: {
control: { type: "boolean" },
},
},
args: {
title: "Add 24 px between the card fields and the summary",
status: "open",
statusLabel: "Open",
layer: "Card form",
isSelected: false,
isLayerLost: false,
},
render: ({ ...args }) => (
<div style={{ inlineSize: "286px" }}>
<TaskRow {...args} />
</div>
),
};
export const Default = {};
export const Selected = {
args: {
isSelected: true,
},
};
export const InAReview = {
args: {
isSelected: true,
isReview: true,
review: "Checkout redesign",
},
};
export const LostLayer = {
args: {
title: "Replace the promo copy (waiting for marketing)",
status: "reopened",
statusLabel: "Reopened",
layer: "Promo banner",
isLayerLost: true,
},
};

View File

@ -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
(ns app.main.ui.ds.product.task-status
(:require-macros
[app.main.style :as stl])
(:require
[rumext.v2 :as mf]))
(def statuses
#{"open" "done" "reopened" "verified" "wont-do"})
(def ^:private schema:task-status
[:map
[:class {:optional true} [:maybe :string]]
[:status (into [:enum] statuses)]
[:label :string]])
(mf/defc task-status*
"The state of a task, a word in the colour of the state: open is blue,
done green, reopened orange, verified purple and won't do red."
{::mf/schema schema:task-status}
[{:keys [class status label] :rest props}]
(let [props (mf/spread-props props
{:class [class (stl/css-case :task-status true
:is-open (= status "open")
:is-done (= status "done")
:is-reopened (= status "reopened")
:is-verified (= status "verified")
:is-wont-do (= status "wont-do"))]})]
[:> :span props label]))

View File

@ -0,0 +1,32 @@
{ /* 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 TaskStatus from "./task_status.stories";
<Meta title="Product/Review/TaskStatus" />
# TaskStatus
The state of a task: a word in the colour of the state.
<Canvas of={TaskStatus.AllStatuses} />
## Technical notes
`status` is one of `open`, `done`, `reopened`, `verified` and `wont-do`;
`label` is the translated name the caller shows.
```clj
[:> task-status* {:status (:status task)
:label (tr "workspace.tasks.status.open")}]
```
## Usage guidelines (design)
Open is blue: the task needs work. Done is green: it waits for someone to
verify it. Reopened is orange: it needs work again. Verified is purple and
closes the task. Won't do is red and drops it.

View File

@ -0,0 +1,51 @@
// 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 *;
.task-status {
--task-status-fg-color: var(--color-foreground-secondary);
--task-status-bg-color: var(--color-background-quaternary);
@include use-typography("body-small");
display: inline-flex;
flex-shrink: 0;
align-items: center;
padding: var(--sp-xxs) var(--sp-s);
border-radius: $br-4;
background-color: var(--task-status-bg-color);
color: var(--task-status-fg-color);
white-space: nowrap;
&.is-open {
--task-status-fg-color: var(--color-accent-info);
--task-status-bg-color: var(--color-background-info);
}
&.is-done {
--task-status-fg-color: var(--color-accent-success);
--task-status-bg-color: var(--color-background-success);
}
&.is-reopened {
--task-status-fg-color: var(--color-accent-warning);
--task-status-bg-color: var(--color-background-warning);
}
&.is-verified {
--task-status-fg-color: var(--color-accent-secondary);
// TODO: no DS background token pairs with the secondary accent
--task-status-bg-color: color-mix(in srgb, var(--color-accent-secondary) 18%, transparent);
}
&.is-wont-do {
--task-status-fg-color: var(--color-accent-error);
--task-status-bg-color: var(--color-background-error);
}
}

View File

@ -0,0 +1,43 @@
// 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 { TaskStatus } = Components;
export default {
title: "Product/Review/TaskStatus",
component: TaskStatus,
argTypes: {
status: {
options: ["open", "done", "reopened", "verified", "wont-do"],
control: { type: "select" },
},
label: {
control: { type: "text" },
},
},
args: {
status: "open",
label: "Open",
},
render: ({ ...args }) => <TaskStatus {...args} />,
};
export const Default = {};
export const AllStatuses = {
render: () => (
<div style={{ display: "flex", gap: "8px" }}>
<TaskStatus status="open" label="Open" />
<TaskStatus status="done" label="Done" />
<TaskStatus status="reopened" label="Reopened" />
<TaskStatus status="verified" label="Verified" />
<TaskStatus status="wont-do" label="Won't do" />
</div>
),
};

View File

@ -15,7 +15,7 @@
.element-options {
display: flex;
flex-direction: column;
block-size: calc(100vh - #{$sz-160}); // TODO: Fix this hardcoded value
block-size: var(--inspect-tab-block-size, calc(100vh - #{$sz-160})); // TODO: Fix this hardcoded value
overflow: hidden;
padding-block-end: var(--sp-l);
overflow-y: auto;

View File

@ -12,7 +12,11 @@
.settings-bar-right {
min-inline-size: px2rem(252);
inline-size: 100%;
block-size: 100vh;
// a panel that holds the inspect below its own header sets these four
// (`--inspect-block-size`, `--inspect-content-display`,
// `--inspect-tab-block-size` and `--options-available-height`)
block-size: var(--inspect-block-size, 100vh);
position: relative;
inset-inline-start: unset;
inset-inline-end: unset;
@ -127,6 +131,8 @@
}
.inspect-content {
display: var(--inspect-content-display, block);
flex-direction: column;
overflow: hidden;
}

View File

@ -11,7 +11,7 @@
}
.styles-tab-workspace {
block-size: calc(100vh - px2rem(180)); // TODO: Fix this hardcoded value
block-size: var(--inspect-tab-block-size, calc(100vh - px2rem(180))); // TODO: Fix this hardcoded value
}
.exports-wrapper {

View File

@ -13,7 +13,9 @@
[app.main.data.persistence :as dps]
[app.main.data.plugins :as dpl]
[app.main.data.workspace :as dw]
[app.main.data.workspace.drawing :as dwd]
[app.main.data.workspace.pull-requests :as dwpr]
[app.main.data.workspace.tasks :as dwtk]
[app.main.features :as features]
[app.main.fonts :as fonts]
[app.main.refs :as refs]
@ -33,6 +35,7 @@
[app.main.ui.workspace.nudge]
[app.main.ui.workspace.palette :refer [palette*]]
[app.main.ui.workspace.plugins]
[app.main.ui.workspace.review.details]
[app.main.ui.workspace.sidebar :refer [sidebar*]]
[app.main.ui.workspace.sidebar.branches :refer [branch-context-banner*]]
[app.main.ui.workspace.sidebar.history :refer [history-toolbox*]]
@ -76,6 +79,7 @@
colorpalette? (:colorpalette layout)
textpalette? (:textpalette layout)
hide-ui? (:hide-ui layout)
bottom-bar (mf/deref refs/bottom-bar)
on-resize
(mf/use-fn
@ -127,8 +131,12 @@
:selected selected
:layout layout
:palete-size
(when (and (or colorpalette? textpalette?) (not hide-ui?))
@palete-size)}]]]
(when (and (or colorpalette? textpalette?)
(not hide-ui?)
(contains? #{nil :palette} bottom-bar))
;; on a branch the palettes sit higher, at the level of its bar
(cond-> @palete-size
(some? bottom-bar) (+ 8)))}]]]
(when-not hide-ui?
[:> sidebar* {:layout layout
@ -202,7 +210,7 @@
(mf/defc workspace*
{::mf/wrap [mf/memo]}
[{:keys [team-id project-id file-id page-id pr-id layout-name]}]
[{:keys [team-id project-id file-id page-id pr-id task-id layout-name]}]
(let [layout (mf/deref refs/workspace-layout)
wglobal (mf/deref refs/workspace-global)
@ -264,6 +272,12 @@
(when (and file-loaded? page-id pr-id)
(st/emit! (dwpr/initialize-pull-request-preview pr-id))))
;; a link to a task (the email that assigns it) opens the task
(mf/with-effect [file-id task-id file-loaded?]
(when (and file-loaded? task-id)
(st/emit! (dwd/select-for-drawing :comments)
(dwtk/open-task-link task-id))))
(mf/with-effect [file-id page-id]
(reset! first-frame-rendered? false))

View File

@ -12,14 +12,20 @@
[app.main.data.workspace :as dw]
[app.main.data.workspace.comments :as dwcm]
[app.main.data.workspace.drawing.common :as dwdc]
[app.main.data.workspace.review :as dwrv]
[app.main.data.workspace.tasks :as dwtk]
[app.main.refs :as refs]
[app.main.store :as st]
[app.main.ui.comments :as cmt]
[app.main.ui.components.dropdown :refer [dropdown]]
[app.main.ui.context :as ctx]
[app.main.ui.ds.buttons.icon-button :refer [icon-button*]]
[app.main.ui.ds.foundations.assets.icon :refer [icon*] :as i]
[app.main.ui.ds.layout.tab-switcher :refer [tab-switcher*]]
[app.main.ui.ds.product.empty-state :refer [empty-state*]]
[app.main.ui.ds.product.panel-title :refer [panel-title*]]
[app.main.ui.workspace.review.panel :refer [comments-tab* tasks-tab*]]
[app.main.ui.workspace.review.tasks :as rvt]
[app.util.dom :as dom]
[app.util.i18n :as i18n :refer [tr]]
[rumext.v2 :as mf]))
@ -79,6 +85,8 @@
[:span {:class (stl/css :icon)}
[:> icon* {:icon-id i/tick :size "s" :class (stl/css :tick-icon)}]]]]))
(declare comments-tasks-tabs* comments-list*)
(mf/defc comments-sidebar*
[{:keys [profiles threads page-id from-viewer]}]
(let [threads-map (mf/deref refs/threads)
@ -126,46 +134,103 @@
(st/emit! (with-meta (dcmt/open-thread thread) {::ev/origin "viewer"}))
(st/emit! (dwcm/navigate-to-comment thread)))))]
[:div {:class (stl/css-case :comments-section true
:from-viewer from-viewer)}
(if (and (not from-viewer) (dwtk/enabled?))
[:> comments-tasks-tabs* {:threads (vals threads-map)
:on-close close-section}]
[:> panel-title* {:class (stl/css :comments-title)
:text (tr "labels.comments")
:on-close close-section}]
[:div {:class (stl/css-case :comments-section true
:from-viewer from-viewer)}
[:button {:class (stl/css :mode-dropdown-wrapper)
:type "button"
:aria-haspopup "menu"
:aria-expanded options?
:on-click toggle-mode-selector}
[:> panel-title* {:class (stl/css :comments-title)
:text (tr "labels.comments")
:on-close close-section}]
[:> comments-list* {:local local
:options? options?
:state* state*
:from-viewer from-viewer
:toggle-mode-selector toggle-mode-selector
:tgroups tgroups
:on-thread-click on-thread-click
:profiles profiles}]])))
[:span {:class (stl/css :mode-label)}
(case (:mode local)
(nil :all) (tr "labels.show-all-comments")
:yours (tr "labels.show-your-comments")
:mentions (tr "labels.show-mentions"))]
[:div {:class (stl/css :arrow-icon)}
[:> icon* {:icon-id i/arrow-down :size "s" :class (stl/css :arrow-svg)}]]]
(mf/defc comments-tasks-tabs*
"The comments panel of a file with tasks: a tab for its comments and one
for its tasks, beside the button that closes the panel."
{::mf/private true}
[{:keys [threads on-close]}]
(let [local (mf/deref refs/review-local)
tasks* (mf/deref refs/tasks)
tab (get local :panel-tab :comments)
tasks (mf/with-memo [tasks*]
(vec (rvt/visible-tasks tasks*)))
tabs (mf/with-memo [threads tasks]
[{:id "comments"
:label (tr "workspace.review.tab.comments" (count threads))}
{:id "tasks"
:label (tr "workspace.review.tab.tasks" (count tasks))}])
on-tab (mf/use-fn #(st/emit! (dwrv/set-panel-tab (keyword %))))
button (mf/with-memo [on-close]
(mf/html
[:> icon-button* {:variant "ghost"
:aria-label (tr "labels.close")
:on-click on-close
:icon i/close}]))]
[:& dropdown {:show options?
:on-close #(reset! state* false)}
[:& sidebar-options {:local local :from-viewer from-viewer}]]
(mf/with-effect []
(st/emit! (dwtk/fetch-tasks)))
[:div {:class (stl/css :comments-section-content)}
[:div {:class (stl/css :comments-panel)}
[:> tab-switcher* {:tabs tabs
:selected (name tab)
:on-change on-tab
:scrollable-panel true
:action-button-position "end"
:action-button button
:class (stl/css :comments-tabs)}
[:div {:class (stl/css :comments-tab-content)}
(if (= tab :tasks)
[:> tasks-tab* {:tasks tasks :grouped true :show-review true}]
[:> comments-tab* {:threads threads :show-page true :show-review true}])]]]))
(if (seq tgroups)
[:div {:class (stl/css :thread-groups)}
(mf/defc comments-list*
"The comment threads of the file, grouped by page, with the selector of
which ones to show."
{::mf/private true}
[{:keys [local options? state* from-viewer toggle-mode-selector tgroups on-thread-click profiles]}]
[:*
[:button {:class (stl/css :mode-dropdown-wrapper)
:type "button"
:aria-haspopup "menu"
:aria-expanded options?
:on-click toggle-mode-selector}
[:span {:class (stl/css :mode-label)}
(case (:mode local)
(nil :all) (tr "labels.show-all-comments")
:yours (tr "labels.show-your-comments")
:mentions (tr "labels.show-mentions"))]
[:div {:class (stl/css :arrow-icon)}
[:> icon* {:icon-id i/arrow-down :size "s" :class (stl/css :arrow-svg)}]]]
[:& dropdown {:show options?
:on-close #(reset! state* false)}
[:& sidebar-options {:local local :from-viewer from-viewer}]]
[:div {:class (stl/css :comments-section-content)}
(if (seq tgroups)
[:div {:class (stl/css :thread-groups)}
[:> cmt/comment-sidebar-thread-group*
{:group (first tgroups)
:on-thread-click on-thread-click
:profiles profiles}]
(for [tgroup (rest tgroups)]
[:> cmt/comment-sidebar-thread-group*
{:group (first tgroups)
{:group tgroup
:on-thread-click on-thread-click
:profiles profiles}]
(for [tgroup (rest tgroups)]
[:> cmt/comment-sidebar-thread-group*
{:group tgroup
:on-thread-click on-thread-click
:profiles profiles
:key (:page-id tgroup)}])]
:profiles profiles
:key (:page-id tgroup)}])]
[:div {:class (stl/css :thread-group-placeholder)}
[:> empty-state* {:icon i/comments
:text (tr "labels.no-comments-available")}]])]]))
[:div {:class (stl/css :thread-group-placeholder)}
[:> empty-state* {:icon i/comments
:text (tr "labels.no-comments-available")}]])]])

View File

@ -24,6 +24,28 @@
padding: 0 var(--sp-s);
}
// with tasks the panel has a tab for its comments and one for its tasks,
// beside the button that closes it, like the history panel
.comments-panel {
display: flex;
flex-direction: column;
block-size: 100%;
min-block-size: 0;
background-color: var(--color-background-primary);
}
.comments-tabs {
--tabs-nav-padding-inline-start: var(--sp-m);
--tabs-nav-padding-inline-end: var(--sp-m);
block-size: 100%;
min-block-size: 0;
}
.comments-tab-content {
padding-inline: var(--sp-m);
}
.comments-title {
margin: var(--sp-s) var(--sp-s) 0 var(--sp-s);
}

View File

@ -54,7 +54,13 @@
[{:keys [layout on-change-size]}]
(let [color-palette? (:colorpalette layout)
text-palette? (:textpalette layout)
hide-palettes? (:hide-palettes layout)
bottom-bar (mf/deref refs/bottom-bar)
on-branch? (some? bottom-bar)
;; on a branch it shares its level with the bar of the branch, and is
;; open only when that one is not (see `layout/open-bottom-bar`)
hide-palettes? (if on-branch?
(not= :palette bottom-bar)
(:hide-palettes layout))
custom-shortcuts (mf/deref refs/custom-shortcuts)
get-tt #(sc/get-effective-tooltip % custom-shortcuts)
@ -121,11 +127,14 @@
toggle-palettes
(mf/use-fn
(mf/deps on-branch?)
(fn [_]
(r/set-resize-type! :top)
(dom/add-class! (dom/get-element-by-class "color-palette") "fade-out-down")
(st/emit! (-> (dw/toggle-layout-flag :hide-palettes)
(vary-meta assoc ::ev/origin "workspace-left-toolbar")))))
(if on-branch?
(st/emit! (dw/toggle-bottom-bar :palette))
(st/emit! (-> (dw/toggle-layout-flag :hide-palettes)
(vary-meta assoc ::ev/origin "workspace-left-toolbar"))))))
on-select-color-palette
(mf/use-fn
@ -169,7 +178,8 @@
width (obj/get dom "clientWidth")]
(swap! state* assoc :width width)))
[:section {:class (stl/css :palette-wrapper)
[:section {:class (stl/css-case :palette-wrapper true
:on-branch on-branch?)
:id "palette-wrapper"
:style (calculate-palette-style rulers?)
:aria-label (tr "workspace.toolbar.palette-bar")
@ -177,7 +187,7 @@
(when-not ^boolean read-only?
[:div {:ref parent-ref
:class (dm/str size-classname " " (stl/css-case :palettes true
:wide any-palette?
:wide (and any-palette? (not hide-palettes?))
:hidden-bts hide-palettes?))
:style #js {"--height" (dm/str size "px")}}
@ -204,7 +214,7 @@
:on-click on-select-text-palette}]]]
(if any-palette?
(if (and any-palette? (not hide-palettes?))
[:*
[:> icon-button* {:variant "ghost"
:class (stl/css :palette-actions)

View File

@ -12,12 +12,7 @@
position: absolute;
inline-size: 100vw;
inset-inline-start: 0;
// The branch banner hangs from this same bottom edge and publishes the room
// it takes from it (`branches.cljs::publish-banner-clearance!`), so the bar
// sits above the banner instead of over its controls. With no banner the
// property is unset and the bar keeps its plain bottom anchor.
inset-block-end: var(--branch-banner-clearance, 0);
inset-block-end: 0;
padding-block-end: var(--sp-xs);
/** Aligns AI Chat button **/
@ -25,6 +20,11 @@
align-items: center;
justify-content: space-between;
gap: var(--sp-s);
// the level of the bar of the branch, clear of the scroll of the canvas
&.on-branch {
padding-block-end: var(--sp-m);
}
}
// `right` and `width` stay physical: they are the transitioned properties.

View File

@ -0,0 +1,103 @@
;; 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.workspace.review.common
"Pieces shared by the review mode and the tasks: who someone is, what a
task points at, and what a change did."
(:require
[app.common.files.helpers :as cfh]
[app.common.math :as mth]
[app.main.ui.ds.foundations.assets.icon :as i]
[app.util.dom :as dom]
[app.util.i18n :refer [tr]]))
(defn profile-name
"The name of the person `profile-id`, or a dash when nobody knows it."
[profiles profile-id]
(or (get-in profiles [profile-id :fullname])
(tr "workspace.review.unknown-name")))
(defn status-tone
"The tone a task in `status` is drawn in, the colour of its state."
[status]
(case status
"done" "success"
"reopened" "warning"
"verified" "purple"
"wont-do" "error"
"info"))
(defn status-label
[status]
(case status
"done" (tr "workspace.tasks.status.done")
"reopened" (tr "workspace.tasks.status.reopened")
"verified" (tr "workspace.tasks.status.verified")
"wont-do" (tr "workspace.tasks.status.wont-do")
(tr "workspace.tasks.status.open")))
(defn board-name
"The name of the board `frame-id`: what the header of a thread or a
task says it is on."
[objects frame-id]
(let [frame (get objects frame-id)]
(if (or (nil? frame) (cfh/root? frame))
(tr "workspace.tasks.canvas")
(:name frame))))
(defn layer-name
"The name of the layer a task points at: the lost one when it was
deleted, its board when it points at none."
[objects {:keys [shape-id frame-id lost-shape-name]}]
(let [shape (get objects shape-id)]
(or lost-shape-name
(when (and (some? shape) (not (cfh/root? shape)))
(:name shape))
(board-name objects frame-id))))
(defn thread-anchor-label
"What a comment thread points at, as its chip says it: the layer, the
size of the area, or the board of the spot."
[objects {:keys [anchor-type shape-id area frame-id]}]
(case anchor-type
:layer (or (some-> (get objects shape-id) :name)
(tr "workspace.review.anchor.deleted-layer"))
:area (tr "workspace.review.anchor.area"
(mth/round (:width area))
(mth/round (:height area)))
(board-name objects frame-id)))
(defn thread-anchor-icon
[{:keys [anchor-type]}]
(case anchor-type
:layer i/board
:area i/comment-area
i/pin))
(defn change-kind-label
"What a change did to its layer."
[kind]
(case kind
:added (tr "workspace.review.change.added")
:deleted (tr "workspace.review.change.deleted")
(tr "workspace.review.change.modified")))
(defn change-kind-label-lower
"What a change did to its layer, in the middle of a sentence."
[kind]
(case kind
:added (tr "workspace.review.change.added-lower")
:deleted (tr "workspace.review.change.deleted-lower")
(tr "workspace.review.change.modified-lower")))
(defn event->canvas
"The canvas point under a pointer `event` on a layer that covers the
viewport."
[event vbox zoom]
(let [rect (dom/get-bounding-rect (dom/get-current-target event))
pt (dom/get-client-position event)]
{:x (+ (:x vbox) (/ (- (:x pt) (:left rect)) zoom))
:y (+ (:y vbox) (/ (- (:y pt) (:top rect)) zoom))}))

View File

@ -0,0 +1,684 @@
;; 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.workspace.review.details
"The details of a design review: an overview (who opened it, where it
stands, its description and reviewers), its activity (what the saves
of the branch did since it opened) and its tasks."
(:require-macros [app.main.style :as stl])
(:require
[app.common.data :as d]
[app.common.data.macros :as dm]
[app.common.time :as ct]
[app.common.uuid :as uuid]
[app.main.data.modal :as modal]
[app.main.data.workspace.pull-requests :as dwpr]
[app.main.data.workspace.review :as dwrv]
[app.main.data.workspace.tasks :as dwtk]
[app.main.refs :as refs]
[app.main.store :as st]
[app.main.ui.ds.buttons.button :refer [button*]]
[app.main.ui.ds.buttons.link-button :refer [link-button*]]
[app.main.ui.ds.controls.select :refer [select*]]
[app.main.ui.ds.controls.textarea :refer [textarea*]]
[app.main.ui.ds.foundations.assets.icon :refer [icon*] :as i]
[app.main.ui.ds.foundations.typography :as t]
[app.main.ui.ds.foundations.typography.heading :refer [heading*]]
[app.main.ui.ds.foundations.typography.text :refer [text*]]
[app.main.ui.ds.layout.modal :refer [modal* modal-content* modal-footer*]]
[app.main.ui.ds.layout.tab-switcher :refer [tab-switcher*]]
[app.main.ui.ds.notifications.context-notification :refer [context-notification*]]
[app.main.ui.ds.product.avatar :refer [avatar*]]
[app.main.ui.ds.product.change-row :refer [change-row*]]
[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.progress-bar :refer [progress-bar*]]
[app.main.ui.ds.product.tag :refer [tag*]]
[app.main.ui.ds.product.task-status :refer [task-status*]]
[app.main.ui.hooks :as hooks]
[app.main.ui.workspace.review.common :as rvc]
[app.main.ui.workspace.review.tasks :as rvt]
[app.main.ui.workspace.sidebar.branch-review.common :as brc]
[app.main.ui.workspace.sidebar.branch-review.layout :as brl]
[app.main.ui.workspace.sidebar.branch-review.previews :as brp]
[app.main.ui.workspace.sidebar.pull-requests :as prui :refer [pr-state-badge* dialog-header*]]
[app.util.dom :as dom]
[app.util.i18n :as i18n :refer [tr]]
[cuerdas.core :as str]
[rumext.v2 :as mf]))
(defn- review-tasks
[tasks pr-id]
(vec (dwtk/sort-tasks (dwtk/review-tasks (vals tasks) pr-id))))
;; --- Overview
(mf/defc stat-card*
{::mf/private true}
[{:keys [label children]}]
[:div {:class (stl/css :stat-card)}
[:> text* {:as "span" :typography t/body-small :class (stl/css :muted)} label]
[:div {:class (stl/css :stat-value)} children]])
(mf/defc description-block*
"The description of the review; its author and the admins edit it."
{::mf/private true}
[{:keys [pr can-edit]}]
(let [editing* (mf/use-state false)
editing? (deref editing*)
value* (mf/use-state (or (:description pr) ""))
value (deref value*)
on-edit (mf/use-fn #(reset! editing* true))
on-change (mf/use-fn #(reset! value* (dom/get-target-val %)))
on-cancel (mf/use-fn (mf/deps pr)
(fn [_]
(reset! value* (or (:description pr) ""))
(reset! editing* false)))
on-save (mf/use-fn
(mf/deps pr value)
(fn [_]
(reset! editing* false)
(st/emit! (dwpr/update-pull-request (:id pr) {:description (str/trim value)}))))]
[:section {:class (stl/css :section)}
[:div {:class (stl/css :section-head)}
[:> heading* {:level 3 :typography t/body-small :class (stl/css :section-title)}
(tr "workspace.pull-requests.info.description")]
(when (and can-edit (not editing?))
[:> button* {:variant "ghost" :on-click on-edit}
(tr "labels.edit")])]
;; the same look as the description of a branch (its info dialog)
(cond
editing?
[:div {:class (stl/css :edit-block)}
[:> textarea* {:class (stl/css :description-input)
:value value
:rows 3
:max-length 4000
:auto-focus true
:aria-label (tr "workspace.pull-requests.info.description")
:on-change on-change}]
[:div {:class (stl/css :edit-actions)}
[:> button* {:variant "secondary" :on-click on-cancel} (tr "labels.cancel")]
[:> button* {:variant "primary" :on-click on-save} (tr "labels.save")]]]
(str/blank? (:description pr))
[:> text* {:as "p" :typography t/body-medium :class (stl/css :description-empty)}
(tr "workspace.review.details.no-description")]
:else
[:> text* {:as "p" :typography t/body-medium :class (stl/css :description)}
(:description pr)])]))
(defn- verdict-label
[{:keys [state stale]}]
(cond
stale (tr "workspace.pull-requests.review-state.stale")
(= "approved" state) (tr "workspace.pull-requests.review-state.approved")
(= "changes-requested" state) (tr "workspace.pull-requests.review-state.changes-requested")
:else (tr "workspace.pull-requests.review-state.pending")))
(defn- verdict-tone
[{:keys [state stale]}]
(cond
stale "neutral"
(= "approved" state) "success"
(= "changes-requested" state) "warning"
:else "neutral"))
(mf/defc reviewers-block*
"The reviewers of the review and their verdicts; its author and the
admins add reviewers."
{::mf/private true}
[{:keys [pr can-edit]}]
(let [profiles (mf/deref refs/profiles)
team (mf/deref refs/team)
adding* (mf/use-state false)
adding? (deref adding*)
current (into #{} (map :profile-id) (:reviews pr))
options (mf/with-memo [team current pr]
(->> (:members team)
(remove #(contains? current (:id %)))
(remove #(= (:created-by pr) (:id %)))
(sort-by :fullname)
(mapv (fn [{:keys [id fullname]}] {:id (str id) :label fullname}))))
on-add (mf/use-fn #(reset! adding* true))
on-select (mf/use-fn
(mf/deps pr current)
(fn [id]
(reset! adding* false)
(st/emit! (dwpr/update-pull-request
(:id pr)
{:reviewers (conj (vec current) (uuid/parse id))}))))]
[:section {:class (stl/css :section)}
[:div {:class (stl/css :section-head)}
[:> heading* {:level 3 :typography t/body-small :class (stl/css :section-title)}
(tr "workspace.pull-requests.info.reviewers")]
(when (and can-edit (seq options) (not adding?))
[:> link-button* {:icon i/add :on-click on-add}
(tr "workspace.review.details.add-reviewer")])]
(when adding?
[:> select* {:options (into [{:id "" :label (tr "workspace.review.details.pick-reviewer")}] options)
:default-selected ""
:on-change on-select
:has-portal true
:wrapper-class (stl/css :reviewer-picker)}])
(if (empty? (:reviews pr))
[:> text* {:as "p" :typography t/body-small :class (stl/css :muted)}
(tr "workspace.review.details.no-reviewers")]
[:ul {:class (stl/css :reviewers)}
(for [review (:reviews pr)]
(let [reviewer (get profiles (:profile-id review))]
[:li {:key (dm/str (:profile-id review)) :class (stl/css :reviewer)}
[:div {:class (stl/css :reviewer-head)}
(when reviewer [:> avatar* {:profile reviewer :variant "S"}])
[:> text* {:as "span" :typography t/body-small :class (stl/css :strong)}
(rvc/profile-name profiles (:profile-id review))]
[:> text* {:as "span" :typography t/body-small :class (stl/css :muted)}
(ct/format-inst (:updated-at review) :localized-date-time)]
[:> tag* {:variant "pill"
:tone (verdict-tone review)
:class (stl/css :push-end)}
(verdict-label review)]]
(when-not (str/blank? (:comment review))
[:> text* {:as "p" :typography t/body-small :class (stl/css :reviewer-comment)}
(tr "workspace.review.details.quoted-comment" (:comment review))])]))])]))
(mf/defc overview-tab*
{::mf/private true}
[{:keys [pr tasks activity]}]
(let [profiles (mf/deref refs/profiles)
profile (mf/deref refs/profile)
team (mf/deref refs/team)
author (get profiles (:created-by pr))
can-edit (or (= (:created-by pr) (:id profile))
(boolean (get-in team [:permissions :is-admin])))
[approvals total] (prui/current-approvals pr)
missing (- total approvals)
open (count (remove dwtk/closed? tasks))
closed (count (filter dwtk/closed? tasks))
counts (:counts pr)
last-row (first (:rows activity))]
[:div {:class (stl/css :tab-body)}
[:div {:class (stl/css :facts)}
[:div {:class (stl/css :fact)}
[:> text* {:as "span" :typography t/body-small :class (stl/css :muted)}
(tr "workspace.pull-requests.info.author")]
[:div {:class (stl/css :fact-value)}
(when author [:> avatar* {:profile author :variant "S"}])
[:> text* {:as "span" :typography t/body-small} (rvc/profile-name profiles (:created-by pr))]]]
[:div {:class (stl/css :fact)}
[:> text* {:as "span" :typography t/body-small :class (stl/css :muted)}
(tr "workspace.review.details.opened")]
[:> text* {:as "span" :typography t/body-small :class (stl/css :fact-value)}
(ct/format-inst (:created-at pr) :localized-date-time)]]
[:div {:class (stl/css :fact)}
[:> text* {:as "span" :typography t/body-small :class (stl/css :muted)}
(tr "workspace.review.details.last-change")]
[:> text* {:as "span" :typography t/body-small :class (stl/css :fact-value)}
(if (some? last-row)
(tr "workspace.review.details.last-change-by"
(ct/timeago (:created-at last-row))
(rvc/profile-name profiles (:profile-id last-row)))
(ct/timeago (:review-updated-at pr)))]]]
(when (and (pos? missing) (= "open" (:status pr)))
[:> context-notification* {:level :warning :appearance :ghost}
(dm/str (tr "workspace.review.details.needs-approvals" (i18n/c missing))
(when (pos? open)
(dm/str " " (tr "workspace.review.details.open-tasks-dont-block" (i18n/c open)))))])
[:div {:class (stl/css :stats)}
[:> stat-card* {:label (tr "workspace.pull-requests.info.approvals")}
[:span (tr "workspace.review.details.x-of-y" approvals total)]
[:span {:class (stl/css :avatars)}
(for [review (:reviews pr)]
(when-let [reviewer (get profiles (:profile-id review))]
[:> avatar* {:key (dm/str (:profile-id review)) :profile reviewer :variant "S"}]))]]
[:> stat-card* {:label (tr "workspace.review.details.comments")}
[:span (tr "workspace.review.details.comments-open" (:comments-open counts 0))]
[:span {:class (stl/css :muted)}
(tr "workspace.review.details.comments-resolved" (:comments-resolved counts 0))]]
[:> stat-card* {:label (tr "workspace.review.tab.tasks-plain")}
[:span (tr "workspace.review.details.x-of-y" closed (count tasks))]
[:> progress-bar* {:value closed :total (count tasks) :class (stl/css :mini-bar)}]]
[:> stat-card* {:label (tr "workspace.review.details.branch")}
(cond
(pos? (or (:conflicts pr) 0))
[:span {:class (stl/css :warning)} (tr "workspace.pull-requests.badge.conflicts" (dm/str (:conflicts pr)))]
(pos? (or (:behind pr) 0))
[:span {:class (stl/css :warning)} (tr "workspace.review.details.behind" (i18n/c (:behind pr)))]
:else
[:span {:class (stl/css :ok)}
[:span {:class (stl/css :dot)}]
(tr "workspace.review.details.up-to-date")])]]
[:> description-block* {:pr pr :can-edit can-edit}]
[:> reviewers-block* {:pr pr :can-edit can-edit}]]))
;; --- Activity
(defn- day-label
"Today, yesterday, or the date of `inst`: the heading of the changes
made that day."
[inst]
(let [day (fn [ms] (.toDateString (js/Date. ms)))
now (js/Date.now)
this-day (day (inst-ms inst))]
(cond
(= this-day (day now)) (tr "workspace.review.activity.today")
(= this-day (day (- now 86400000))) (tr "workspace.review.activity.yesterday")
:else (ct/format-inst inst :localized-date))))
(defn- kind-tone
[kind]
(case kind :added "success" :deleted "error" "info"))
(defn- display-attr
"A property of a change as the hover card shows it: its label and its
values before and after, the token behind a value when there is one."
[attr [before after] [tokens-before tokens-after]]
(let [token-key (case attr :fills :fill :strokes :stroke-color nil)]
[(brc/attr-label attr)
(or (get tokens-before token-key) before)
(or (get tokens-after token-key) after)]))
(def ^:private card-width
"The width of the card of a change, as its style sets it."
320)
(defn- card-style
"Put the card beside the row box `rect` (viewport coordinates), on its
right when it fits there and on its left otherwise, inside the window."
[{:keys [left right top]}]
(let [gap 8
win-w (.-innerWidth js/window)
win-h (.-innerHeight js/window)
x (if (< (+ right gap card-width) win-w)
(+ right gap)
(max gap (- left gap card-width)))
y (min top (- win-h 360))]
#js {:left (dm/str x "px")
:top (dm/str (max gap y) "px")}))
(mf/defc change-card*
"What a change did, beside its row. It goes in a portal so the scroll of
the dialog never cuts it."
{::mf/private true}
[{:keys [entry tasks rect]}]
(let [profiles (mf/deref refs/profiles)
data (mf/deref refs/workspace-data)
objects (dm/get-in data [:pages-index (:page-id entry) :objects])
shape (get objects (:id entry))
attrs (:attrs entry)
tokens (:applied-tokens attrs)
linked (filterv #(= (:id entry) (:shape-id %)) tasks)]
[:div {:class (stl/css :change-card) :role "tooltip" :style (card-style rect)}
[:div {:class (stl/css :change-card-head)}
[:> text* {:as "span" :typography t/body-small :class (stl/css :strong)} (:name entry)]
[:> tag* {:tone (kind-tone (:kind entry))} (rvc/change-kind-label (:kind entry))]]
[:div {:class (stl/css :change-card-preview)}
(if (and (some? shape) (not= :deleted (:kind entry)))
[:> brp/shape-preview* {:shape shape :objects objects}]
[:div {:class (stl/css :deleted-preview)}])]
(when (seq attrs)
[:dl {:class (stl/css :attrs)}
(for [[attr diff] (dissoc attrs :applied-tokens :parent-id)]
(let [[label before after] (display-attr attr diff tokens)]
[:* {:key (name attr)}
[:dt {:class (stl/css :muted)} label]
[:dd {:class (stl/css :attr-value)}
[:> brl/value-chip* {:value before :is-old true}]
[:> icon* {:icon-id i/arrow-long-right :size "s" :class (stl/css :attr-arrow)}]
[:> brl/value-chip* {:value after}]]]))])
(when (seq linked)
[:div {:class (stl/css :linked)}
[:> text* {:as "span" :typography t/body-small :class (stl/css :section-title)}
(tr "workspace.review.activity.linked-tasks" (i18n/c (count linked)))]
(for [task linked]
[:div {:key (dm/str (:id task)) :class (stl/css :linked-task)}
[:> text* {:as "span" :typography t/body-small} (:title task)]
[:> task-status* {:status (:status task) :label (rvc/status-label (:status task))}]
(when (dwtk/lost? task)
[:> text* {:as "span" :typography t/body-small :class (stl/css :warning)}
(tr "workspace.review.activity.now-points-to"
(rvc/board-name objects (:frame-id task)))])])])
[:> text* {:as "span" :typography t/body-small :class (stl/css :muted)}
(tr "workspace.review.text-and-detail"
(rvc/profile-name profiles (:profile-id entry))
(ct/format-inst (:changed-at entry) :localized-time))]
[:> text* {:as "span" :typography t/body-small :class (stl/css :muted)}
(if (seq linked)
(tr "workspace.review.activity.open-task-to-relink")
(tr "workspace.review.activity.click-to-show"))]]))
(def ^:private rows-shown
"The changes a group lists before it folds the rest."
4)
(mf/defc change-item*
"One change of a group: a click shows it on the canvas, and hovering it
shows what it did."
{::mf/private true}
[{:keys [entry tasks portal]}]
(let [id (:id entry)
tone (kind-tone (:kind entry))
rect* (mf/use-state nil)
rect (deref rect*)
on-enter (mf/use-fn #(reset! rect* (dom/get-bounding-rect (dom/get-current-target %))))
on-leave (mf/use-fn #(reset! rect* nil))
on-show (mf/use-fn (mf/deps id) #(st/emit! (dwrv/show-change-of id)))]
[:li {:class (stl/css :change-item)
:on-pointer-enter on-enter
:on-pointer-leave on-leave}
[:> change-row* {:title (or (:name entry) (tr "workspace.review.unknown-name"))
:subtitle (:frame-name entry)
:tone tone
:is-muted (= :deleted (:kind entry))
:end (mf/html [:> tag* {:tone tone}
(rvc/change-kind-label (:kind entry))])
:on-click on-show}]
(when (some? rect)
(mf/portal
(mf/html [:> change-card* {:entry entry :tasks tasks :rect rect}])
portal))]))
(mf/defc change-group*
{::mf/private true}
[{:keys [session tasks is-open]}]
(let [profiles (mf/deref refs/profiles)
open* (mf/use-state is-open)
open? (deref open*)
all* (mf/use-state false)
all? (deref all*)
portal (hooks/use-portal-container :tooltip)
entries (:entries session)
shown (if all? entries (take rows-shown entries))
person (get profiles (:profile-id session))
on-toggle (mf/use-fn #(swap! open* not))
on-all (mf/use-fn #(reset! all* true))]
[:div {:class (stl/css :change-group)}
[:button {:class (stl/css :change-group-head)
:type "button"
:aria-expanded open?
:on-click on-toggle}
[:> icon* {:icon-id (if open? i/arrow-down i/arrow-right) :size "s"}]
(when person [:> avatar* {:profile person :variant "S"}])
[:> text* {:as "span" :typography t/body-small :class (stl/css :strong)}
(rvc/profile-name profiles (:profile-id session))]
[:> text* {:as "span" :typography t/body-small :class (stl/css :muted)}
(tr "workspace.review.activity.changed" (i18n/c (count entries)))]
[:> text* {:as "span" :typography t/body-small :class (stl/css :muted :push-end)}
(ct/format-inst (:end session) :localized-time)]]
(when open?
[:ul {:class (stl/css :change-rows)}
(for [entry shown]
[:> change-item* {:key (dm/str (:id entry))
:entry entry
:tasks tasks
:portal portal}])
(when (and (not all?) (> (count entries) rows-shown))
[:li
[:> link-button* {:on-click on-all}
(tr "workspace.review.activity.more" (i18n/c (- (count entries) rows-shown)))]])])]))
(mf/defc day-group*
"The changes of one day: only the group of its last session opens."
{::mf/private true}
[{:keys [sessions tasks]}]
(let [sessions (mf/with-memo [sessions]
(into [] d/xf:add-index sessions))]
[:section {:class (stl/css :section)}
[:> heading* {:level 3 :typography t/body-small :class (stl/css :section-title)}
(day-label (:end (first sessions)))]
(for [session sessions]
[:> change-group* {:key (dm/str (inst-ms (:start session)) (:profile-id session))
:session session
:tasks tasks
:is-open (zero? (::d/index session))}])]))
(mf/defc activity-tab*
{::mf/private true}
[{:keys [pr activity tasks]}]
(let [profiles (mf/deref refs/profiles)
local (mf/deref refs/review-local)
kind (get local :change-filter :all)
entries (:entries activity)
people (count (into #{} (map :profile-id) (:rows activity)))
counts (frequencies (map :kind entries))
sessions (mf/with-memo [activity kind]
(->> (:sessions activity)
(keep (fn [s]
(let [es (cond->> (:entries s)
(not= :all kind) (filterv #(= kind (:kind %))))]
(when (seq es) (assoc s :entries es)))))))
by-day (mf/with-memo [sessions]
(partition-by #(day-label (:end %)) sessions))
on-filter
(mf/use-fn
(fn [event]
(let [kind (-> (dom/get-current-target event) (dom/get-data "filter") keyword)]
(st/emit! (dwrv/set-change-filter kind)))))
on-show (mf/use-fn #(st/emit! (dwrv/show-change 0)))]
(case (:status activity)
:loaded
[:div {:class (stl/css :tab-body)}
[:> text* {:as "p" :typography t/body-small :class (stl/css :muted)}
(tr "workspace.review.activity.summary" (count entries) people)]
[:div {:class (stl/css :activity-bar)}
[:div {:class (stl/css :filters)}
(for [[id label n] [[:all (tr "workspace.review.activity.all") (count entries)]
[:added (tr "workspace.review.change.added") (:added counts 0)]
[:modified (tr "workspace.review.change.modified") (:modified counts 0)]
[:deleted (tr "workspace.review.change.deleted") (:deleted counts 0)]]]
[:> filter-chip* {:key (name id)
:label (tr "workspace.review.label-count" label n)
:tone (case id :added "success" :deleted "error" :modified "info" "neutral")
:is-selected (= kind id)
:data-filter (name id)
:on-click on-filter}])]
[:> button* {:variant "ghost" :icon i/shown :on-click on-show
:disabled (empty? entries)}
(tr "workspace.review.activity.show-on-canvas")]]
(if (empty? sessions)
[:> empty-state* {:icon i/history
:text (tr "workspace.review.activity.empty")}]
(for [day by-day]
[:> day-group* {:key (day-label (:end (first day)))
:sessions day
:tasks tasks}]))
[:div {:class (stl/css :opened-line)}
[:> icon* {:icon-id i/git-pull-request-arrow :size "s"}]
[:> text* {:as "span" :typography t/body-small :class (stl/css :muted)}
(tr "workspace.review.activity.opened"
(rvc/profile-name profiles (:created-by pr))
(ct/format-inst (:created-at pr) :localized-date-time))]]]
:error
[:> empty-state* {:icon i/triangle-alert
:text (tr "workspace.review.activity.error")}]
[:div {:class (stl/css :tab-body)}
[:> text* {:as "p" :typography t/body-small :class (stl/css :muted)}
(tr "labels.loading")]])))
;; --- Tasks
(mf/defc tasks-tab*
"The tasks of the review: filters by state, as the activity has by kind
of change, how many are closed and the list. With every state shown,
the closed tasks fold under the open ones."
{::mf/private true}
[{:keys [tasks]}]
(let [local (mf/deref refs/review-local)
status (get local :task-status-filter :all)
closed-open* (mf/use-state false)
closed-open? (deref closed-open*)
counts (frequencies (map :status tasks))
open-tasks (remove dwtk/closed? tasks)
closed-tasks (filter dwtk/closed? tasks)
shown (mf/with-memo [tasks status]
(filterv #(= status (:status %)) tasks))
on-filter
(mf/use-fn
(fn [event]
(let [value (-> (dom/get-current-target event) (dom/get-data "filter"))]
(st/emit! (dwrv/set-task-status-filter
(if (= "all" value) :all value))))))
on-toggle (mf/use-fn #(swap! closed-open* not))]
[:div {:class (stl/css :tab-body)}
[:div {:class (stl/css :tasks-head)}
[:div {:class (stl/css :filters)}
[:> filter-chip* {:label (tr "workspace.review.label-count"
(tr "workspace.review.activity.all")
(count tasks))
:is-selected (= :all status)
:data-filter "all"
:on-click on-filter}]
(for [id dwrv/task-statuses]
[:> filter-chip* {:key id
:label (tr "workspace.review.label-count"
(rvc/status-label id)
(get counts id 0))
:tone (rvc/status-tone id)
:is-selected (= status id)
:data-filter id
:on-click on-filter}])]
[:> text* {:as "span" :typography t/body-small :class (stl/css :strong)}
(tr "workspace.tasks.closed-of" (count closed-tasks) (count tasks))]]
[:> progress-bar* {:value (count closed-tasks) :total (count tasks) :class (stl/css :wide-bar)}]
(cond
(empty? tasks)
[:> empty-state* {:icon i/view-as-list :text (tr "workspace.tasks.empty")}]
(not= :all status)
(if (empty? shown)
[:> empty-state* {:icon i/view-as-list :text (tr "workspace.tasks.empty")}]
[:> rvt/task-list* {:tasks shown}])
:else
[:*
[:> rvt/task-list* {:tasks (vec open-tasks)}]
(when (seq closed-tasks)
[:section {:class (stl/css :section)}
[:> link-button* {:icon (if closed-open? i/arrow-down i/arrow-right)
:tone "neutral"
:class (stl/css :closed-toggle)
:aria-expanded closed-open?
:on-click on-toggle}
(tr "workspace.review.details.closed" (count closed-tasks))]
(when closed-open?
[:> rvt/task-list* {:tasks (vec closed-tasks)}])])])]))
;; --- Dialog
(mf/defc review-details-dialog*
{::mf/register modal/components
::mf/register-as :review-details}
[{:keys [pr tab]}]
(let [preview (mf/deref refs/pull-request-preview)
;; the review open now is fresher than the row the dialog got
pr (if (= (:id pr) (:pr-id preview)) (or (:info preview) pr) pr)
profile (mf/deref refs/profile)
team (mf/deref refs/team)
tasks* (mf/deref refs/tasks)
activity (mf/deref refs/review-activity)
tasks (mf/with-memo [tasks* pr] (review-tasks tasks* (:id pr)))
tab* (mf/use-state (or tab "overview"))
tab (deref tab*)
profiles (mf/deref refs/profiles)
author (get profiles (:created-by pr))
reviewer? (some #(= (:profile-id %) (:id profile)) (:reviews pr))
can-close? (and (or (= (:created-by pr) (:id profile))
(boolean (get-in team [:permissions :is-admin])))
(= "open" (:status pr)))
entries (:entries activity)
tabs (mf/with-memo [entries tasks]
[{:id "overview" :label (tr "workspace.review.details.overview")}
{:id "activity" :label (tr "workspace.review.details.activity" (count entries))}
{:id "tasks" :label (tr "workspace.review.tab.tasks" (count tasks))}])
;; kept in the props too: a confirmation takes the place of the dialog
;; and brings it back with its props
on-tab (mf/use-fn
(fn [id]
(reset! tab* id)
(st/emit! (modal/update-props :review-details {:tab id}))))
on-close (mf/use-fn #(st/emit! (modal/hide)))
on-open-change (mf/use-fn (fn [open?] (when-not open? (st/emit! (modal/hide)))))
on-compare (mf/use-fn (mf/deps pr) #(prui/open-compare! pr))
on-review (mf/use-fn (mf/deps pr) #(modal/show! :pull-request-review {:pr pr}))
on-close-review (mf/use-fn (mf/deps pr) #(prui/confirm-close! pr))]
(mf/with-effect [pr]
(st/emit! (dwrv/fetch-activity (:id pr))
(dwtk/fetch-tasks)))
[:> modal* {:is-open true
:on-open-change on-open-change
:size "large"}
[:> dialog-header*
{:icon i/git-pull-request-arrow
:title (:title pr)
:subtitle
(mf/html
[:div {:class (stl/css :subtitle)}
[:> pr-state-badge* {:pr pr}]
[:> text* {:as "span" :typography t/body-small :class (stl/css :muted)}
(tr "workspace.review.text-and-detail"
(tr "workspace.review.route" (:branch-name pr) (tr "workspace.branches.main"))
(tr "workspace.review.details.opened-by"
(ct/format-inst (:created-at pr) :localized-date)
(or (:fullname author) (tr "workspace.review.unknown-name"))))]])}]
[:> modal-content* {:class (stl/css :content)}
[:> tab-switcher* {:tabs tabs
:selected tab
:on-change on-tab
:scrollable-panel true
:class (stl/css :tabs)}
(case tab
"activity" [:> activity-tab* {:pr pr :activity activity :tasks tasks}]
"tasks" [:> tasks-tab* {:tasks tasks}]
[:> overview-tab* {:pr pr :tasks tasks :activity activity}])]]
[:> modal-footer* {:class (stl/css :footer)}
(when can-close?
[:> button* {:variant "ghost"
:class (stl/css :push-start)
:on-click on-close-review}
(tr "workspace.review.details.close-review")])
[:> button* {:variant "secondary" :icon i/git-compare-arrows :on-click on-compare}
(tr "workspace.branches.compare")]
(if reviewer?
[:> button* {:variant "primary" :on-click on-review}
(tr "workspace.review.submit")]
[:> button* {:variant "primary" :on-click on-close}
(tr "labels.close")])]]))

Some files were not shown because too many files have changed in this diff Show More