From 488d38e8e2eacd4ce04e76fc0e342e61c41cfa0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 28 Oct 2026 10:01:24 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20task=20modal:=20fields,=20d?= =?UTF-8?q?eadline,=20assignees,=20watch,=20subtasks,=20dependencies,=20co?= =?UTF-8?q?mments,=20activity,=20delete?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/iz-core/src/store/activity.rs | 49 + crates/iz-core/src/store/comments.rs | 15 +- crates/iz-core/src/store/tasks.rs | 72 ++ crates/iz-web/assets/board.js | 15 +- crates/iz-web/src/i18n/board.rs | 4 + crates/iz-web/src/i18n/mod.rs | 1 + crates/iz-web/src/i18n/task.rs | 425 ++++++++ crates/iz-web/src/pages/board.rs | 32 +- crates/iz-web/src/pages/mod.rs | 1 + crates/iz-web/src/pages/task.rs | 1345 ++++++++++++++++++++++++++ crates/iz-web/src/pages/tasks.rs | 8 +- crates/iz-web/src/views/board.rs | 6 +- crates/iz-web/src/views/mod.rs | 1 + crates/iz-web/src/views/task.rs | 627 ++++++++++++ style/_task.scss | 144 +++ style/main.scss | 1 + 16 files changed, 2729 insertions(+), 17 deletions(-) create mode 100644 crates/iz-web/src/i18n/task.rs create mode 100644 crates/iz-web/src/pages/task.rs create mode 100644 crates/iz-web/src/views/task.rs create mode 100644 style/_task.scss diff --git a/crates/iz-core/src/store/activity.rs b/crates/iz-core/src/store/activity.rs index 66fc1a2..a722304 100644 --- a/crates/iz-core/src/store/activity.rs +++ b/crates/iz-core/src/store/activity.rs @@ -120,6 +120,55 @@ impl Store { .await } + /// One keyset page of a task's activity, newest first, for the task modal. `cursor` is the + /// `next_cursor` of the previous page. `limit` must be between [`PAGE_MIN`] and [`PAGE_MAX`]. + pub async fn list_task_page( + &self, + board_id: &str, + task_id: &str, + cursor: Option<&str>, + limit: usize, + ) -> Result { + if !(PAGE_MIN..=PAGE_MAX).contains(&limit) { + return Err(Error::Invalid(format!( + "page size must be {PAGE_MIN} to {PAGE_MAX}" + ))); + } + let (before_at, before_id) = match cursor { + None => (None, None), + Some(text) => { + let (at, id) = text + .split_once('~') + .ok_or_else(|| Error::Invalid("malformed activity cursor".into()))?; + (Some(at.to_owned()), Some(id.to_owned())) + } + }; + let conn = self.read_conn().await; + let items = fetch_all( + &conn, + &format!( + "SELECT {ACTIVITY_COLS} FROM activity a JOIN tasks t ON t.id = a.task_id \ + WHERE a.task_id = ?1 AND t.board_id = ?2 \ + AND (?3 IS NULL OR a.at < ?3 OR (a.at = ?3 AND a.id < ?4)) \ + ORDER BY a.at DESC, a.id DESC LIMIT ?5" + ), + ( + task_id.to_owned(), + board_id.to_owned(), + before_at, + before_id, + i64::try_from(limit).unwrap_or(i64::MAX), + ), + map_activity, + ) + .await?; + let next_cursor = match items.last() { + Some(last) if items.len() == limit => Some(format!("{}~{}", last.at, last.id)), + _ => None, + }; + Ok(ActivityPage { items, next_cursor }) + } + /// One page of recent activity, newest first. `cursor` is the `next_cursor` of the previous page. /// `limit` must be between [`PAGE_MIN`] and [`PAGE_MAX`]. pub async fn list_recent( diff --git a/crates/iz-core/src/store/comments.rs b/crates/iz-core/src/store/comments.rs index 78b3a67..071fd15 100644 --- a/crates/iz-core/src/store/comments.rs +++ b/crates/iz-core/src/store/comments.rs @@ -64,13 +64,14 @@ fn member_sub(actor: &Actor) -> Result<&str> { } } -/// Reads a live comment of `board_id` with its task id and author. Missing or foreign: `NotFound`. +/// Reads a live comment of a live task of `board_id` with its task id and author. A comment whose task +/// was deleted, or a comment of another board, is `NotFound`. async fn live_comment(conn: &Connection, board_id: &str, comment_id: &str) -> Result { fetch_opt( conn, "SELECT c.id, c.task_id, c.author, c.body, c.created_at, c.edited_at, c.deleted_at FROM comments c \ JOIN tasks t ON t.id = c.task_id \ - WHERE c.id = ?1 AND t.board_id = ?2 AND c.deleted_at IS NULL", + WHERE c.id = ?1 AND t.board_id = ?2 AND c.deleted_at IS NULL AND t.deleted_at IS NULL", (comment_id.to_owned(), board_id.to_owned()), map_comment, ) @@ -196,16 +197,17 @@ impl Store { finish(tx, outcome).await } - /// Soft-deletes a comment. Its author (while a member) or any admin may do it (`authz`). + /// Soft-deletes a comment. Its author (while a member) or any admin may do it (`authz`). Returns the id + /// of the task the comment belonged to, so the caller can tell that task's viewers. pub async fn delete_comment( &self, board_id: &str, comment_id: &str, actor: &Actor, - ) -> Result<()> { + ) -> Result { let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; - let outcome: Result<()> = async { + let outcome: Result = async { let current = live_comment(&tx, board_id, comment_id).await?; authorize( actor, @@ -230,7 +232,8 @@ impl Store { detail: serde_json::json!({ "comment": comment_id }), }, ) - .await + .await?; + Ok(current.task_id) } .await; finish(tx, outcome).await diff --git a/crates/iz-core/src/store/tasks.rs b/crates/iz-core/src/store/tasks.rs index 318a598..46c38bc 100644 --- a/crates/iz-core/src/store/tasks.rs +++ b/crates/iz-core/src/store/tasks.rs @@ -1109,6 +1109,78 @@ impl Store { finish(tx, outcome).await } + /// Starts (`on`) or stops watching a live task for one member. Watching is the member's own choice, so + /// `sub` is always the actor. Only a real change writes a `watch_changed` activity row. + pub async fn set_watch( + &self, + board_id: &str, + task_id: &str, + sub: &str, + on: bool, + ) -> Result<()> { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + live_task(&tx, board_id, task_id).await?; + let changed = if on { + tx.execute( + "INSERT INTO task_watchers (task_id, sub, created_at) VALUES (?1, ?2, ?3) \ + ON CONFLICT(task_id, sub) DO NOTHING", + (task_id.to_owned(), sub.to_owned(), now_stamp()), + ) + .await + .map_err(db_err)? + } else { + tx.execute( + "DELETE FROM task_watchers WHERE task_id = ?1 AND sub = ?2", + (task_id.to_owned(), sub.to_owned()), + ) + .await + .map_err(db_err)? + }; + if changed > 0 { + log( + &tx, + task_id, + sub, + "watch_changed", + None, + serde_json::json!({ "on": on }), + ) + .await?; + } + Ok(()) + } + .await; + finish(tx, outcome).await + } + + /// Whether `sub` watches the task. + pub async fn is_watching(&self, task_id: &str, sub: &str) -> Result { + let conn = self.read_conn().await; + let found = fetch_opt( + &conn, + "SELECT 1 FROM task_watchers WHERE task_id = ?1 AND sub = ?2", + (task_id.to_owned(), sub.to_owned()), + |row| col_int(row, 0), + ) + .await?; + Ok(found.is_some()) + } + + /// Every live task of the board, top-level and subtasks, by key. The task modal picks dependency + /// partners and parents from this list; the store checks each choice again when it is written. + pub async fn task_options(&self, board_id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!("SELECT {TASK_COLS} FROM tasks WHERE board_id = ?1 AND deleted_at IS NULL ORDER BY key"), + (board_id.to_owned(),), + map_task, + ) + .await + } + /// A cheap summary of everything the board page shows: counts and the newest change of the board's /// tasks, assignments, links, comments, columns and projects. The live stream sends `changed` only /// when this text changes, so it must change whenever any of those rows does. diff --git a/crates/iz-web/assets/board.js b/crates/iz-web/assets/board.js index 9c4675d..7c82ce0 100644 --- a/crates/iz-web/assets/board.js +++ b/crates/iz-web/assets/board.js @@ -10,7 +10,7 @@ * anything else puts it back and shows a toast with the server's translated message. * - A drag that ends outside any column puts the card back where it was. * - * What it never does: decide anything about the move itself. The server checks the column, the + * It also closes the task modal on Escape (see below). What it never does: decide anything about the move itself. The server checks the column, the * subtasks, the role and the token; this script only shows the result. Dropping onto the card's own * column is nothing to send, so it puts the card back. * @@ -20,6 +20,19 @@ (function () { "use strict"; + /** + * Escape closes the task modal. The modal's `data-close-href` is the board with its filters, so closing + * is the same navigation as the close link. The page is read on every key press, because a soft + * navigation (nav.js) can replace the modal without this script running again. + */ + document.addEventListener("keydown", (event) => { + if (event.key !== "Escape") return; + const dialog = document.querySelector("dialog[data-close-href]"); + if (dialog && dialog.open) { + window.location.assign(dialog.dataset.closeHref); + } + }); + const board = document.querySelector("[data-board-write]"); if (!board || !window.fetch || !window.URLSearchParams) { return; diff --git a/crates/iz-web/src/i18n/board.rs b/crates/iz-web/src/i18n/board.rs index 3a7c6bd..db3e9ea 100644 --- a/crates/iz-web/src/i18n/board.rs +++ b/crates/iz-web/src/i18n/board.rs @@ -251,6 +251,10 @@ pub fn notice(lang: Lang, name: &str) -> Option<&'static str> { match name { "created" => Some(t(lang, K::NoticeCreated)), "deleted" => Some(t(lang, K::NoticeDeleted)), + "saved" => Some(crate::i18n::task::t( + lang, + crate::i18n::task::K::NoticeSaved, + )), _ => None, } } diff --git a/crates/iz-web/src/i18n/mod.rs b/crates/iz-web/src/i18n/mod.rs index 29ae9f5..bfcb045 100644 --- a/crates/iz-web/src/i18n/mod.rs +++ b/crates/iz-web/src/i18n/mod.rs @@ -9,6 +9,7 @@ pub mod board; pub mod shell; +pub mod task; use topcoat::context::Cx; use topcoat::router::request::headers; diff --git a/crates/iz-web/src/i18n/task.rs b/crates/iz-web/src/i18n/task.rs new file mode 100644 index 0000000..15f7daa --- /dev/null +++ b/crates/iz-web/src/i18n/task.rs @@ -0,0 +1,425 @@ +//! Strings of the task modal: its fields, its sections, the activity sentences and the message of every +//! refused write. Each key has an English and a Turkish text in [`t`]; the match is exhaustive, so a +//! missing translation does not compile. + +use super::Lang; + +/// One variant per phrase of the task modal. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum K { + /// The link that closes the modal. + Close, + /// The label of the title field. + Title, + /// The label of the description field. + Description, + /// The hint under the description: plain text, and which links are clickable. + DescriptionHint, + /// The label of the project field. + Project, + /// The label of the deadline day field. + Deadline, + /// The label of the meeting time field. + Meeting, + /// The hint under the meeting time: the viewer's zone. + MeetingHint, + /// The button that saves the fields. + Save, + /// The heading of the assignees section. + Assignees, + /// The label of the person picker. + AssignPick, + /// The button that assigns the picked person. + Assign, + /// The button that removes one assignee. + Remove, + /// The text when nobody is assigned. + NobodyAssigned, + /// The button that starts watching the task. + Watch, + /// The button that stops watching the task. + Unwatch, + /// The text while the viewer watches the task. + Watching, + /// The text while the viewer does not watch the task. + NotWatching, + /// The heading of the subtasks section. + Subtasks, + /// The text when the task has no subtasks. + NoSubtasks, + /// The label of the subtask title field. + SubtaskTitle, + /// The button that creates a subtask. + AddSubtask, + /// The heading of the parent section. + Parent, + /// The first entry of the parent picker: a top-level task. + NoParent, + /// The button that sets the parent. + SetParent, + /// The heading of the dependencies section. + Dependencies, + /// The label for tasks this one waits for. + BlockedBy, + /// The label for tasks waiting for this one. + Blocks, + /// The text when there are no dependencies. + NoLinks, + /// The label of the task picker for a dependency. + LinkWith, + /// The label of the direction picker for a dependency. + LinkDirection, + /// The direction "waits for". + DirBlockedBy, + /// The direction "is waited for by". + DirBlocks, + /// The button that adds a dependency. + AddLink, + /// The button that removes a dependency. + RemoveLink, + /// The heading of the comments section. + Comments, + /// The text when there are no comments. + NoComments, + /// The label of the comment field. + CommentBody, + /// The button that posts a comment. + PostComment, + /// The summary of a comment's editor. + EditComment, + /// The button that saves an edited comment. + SaveComment, + /// The button that deletes a comment. + DeleteComment, + /// The mark after a comment that was edited. + Edited, + /// The heading of the activity section. + Activity, + /// The text when there is no activity. + NoActivity, + /// The link to the next, older page of activity. + Older, + /// The link that opens the delete confirmation. + DeleteTask, + /// The question of the delete confirmation. + DeleteQuestion, + /// The consequence line of the delete confirmation. + DeleteConsequence, + /// The button that confirms the delete. + DeleteYes, + /// The notice after a change in the modal. + NoticeSaved, + /// Activity: the task was created. + ActCreated, + /// Activity: the task was edited. + ActEdited, + /// Activity: the task was moved. + ActMoved, + /// Activity: the task was deleted. + ActDeleted, + /// Activity: someone was assigned. + ActAssigned, + /// Activity: someone was unassigned. + ActUnassigned, + /// Activity: the project changed. + ActTagChanged, + /// Activity: the parent changed. + ActParentChanged, + /// Activity: a dependency was added. + ActLinkAdded, + /// Activity: a dependency was removed. + ActLinkRemoved, + /// Activity: the task was unblocked. + ActUnblocked, + /// Activity: the deadline was set. + ActDeadlineSet, + /// Activity: the deadline was cleared. + ActDeadlineCleared, + /// Activity: the meeting time was set. + ActClockSet, + /// Activity: the meeting time was cleared. + ActClockCleared, + /// Activity: watching changed. + ActWatchChanged, + /// Activity: a comment was added. + ActCommentAdded, + /// Activity: a comment was edited. + ActCommentEdited, + /// Activity: a comment was deleted. + ActCommentDeleted, + /// Activity: a file was added. + ActFileAdded, + /// Activity: a file was deleted. + ActFileDeleted, + /// Activity: a reminder was sent. + ActReminded, + /// Activity: an account changed. + ActAccountChanged, + /// Activity of a kind this build does not name. + ActOther, + /// Refused: the description is longer than the limit. + DescriptionTooLong, + /// Refused: the project does not exist on this board. + ErrProject, + /// Refused: the deadline is not a day. + ErrDeadline, + /// Refused: the meeting time is not a clock time. + ErrTime, + /// Refused: the meeting time needs a day, or does not exist in the viewer's zone. + ErrMeeting, + /// Refused: the person cannot be assigned. + ErrAssignee, + /// Refused: a task cannot depend on itself. + ErrSelf, + /// Refused: the dependency would close a cycle. + ErrCycle, + /// Refused: the parent is not a top-level task of this board, or the task is not a top-level task. + ErrParent, + /// Refused: the task has subtasks and so cannot become one. + ErrParentHasChildren, + /// Refused: the comment is empty or longer than the limit. + ErrComment, + /// Refused: the subtask title is empty or longer than the limit. + ErrSubtaskTitle, + /// Refused: the picked task is not on this board. + ErrOtherTask, + /// Refused: the picked direction is not one of the two. + ErrDirection, +} + +/// The text of `key` in `lang`. +pub fn t(lang: Lang, key: K) -> &'static str { + match (key, lang) { + (K::Close, Lang::En) => "Close", + (K::Close, Lang::Tr) => "Kapat", + (K::Title, Lang::En) => "Title", + (K::Title, Lang::Tr) => "Başlık", + (K::Description, Lang::En) => "Description", + (K::Description, Lang::Tr) => "Açıklama", + (K::DescriptionHint, Lang::En) => { + "Plain text. Addresses that start with http:// or https:// become links." + } + (K::DescriptionHint, Lang::Tr) => { + "Düz metin. http:// veya https:// ile başlayan adresler bağlantı olur." + } + (K::Project, Lang::En) => "Project", + (K::Project, Lang::Tr) => "Proje", + (K::Deadline, Lang::En) => "Deadline", + (K::Deadline, Lang::Tr) => "Son tarih", + (K::Meeting, Lang::En) => "Meeting time", + (K::Meeting, Lang::Tr) => "Toplantı saati", + (K::MeetingHint, Lang::En) => "Optional. In your time zone. Needs a deadline day.", + (K::MeetingHint, Lang::Tr) => { + "İsteğe bağlı. Sizin saat diliminizde. Bir son tarih gerekir." + } + (K::Save, Lang::En) => "Save", + (K::Save, Lang::Tr) => "Kaydet", + (K::Assignees, Lang::En) => "Assignees", + (K::Assignees, Lang::Tr) => "Atananlar", + (K::AssignPick, Lang::En) => "Person", + (K::AssignPick, Lang::Tr) => "Kişi", + (K::Assign, Lang::En) => "Assign", + (K::Assign, Lang::Tr) => "Ata", + (K::Remove, Lang::En) => "Remove", + (K::Remove, Lang::Tr) => "Çıkar", + (K::NobodyAssigned, Lang::En) => "Nobody is assigned.", + (K::NobodyAssigned, Lang::Tr) => "Kimse atanmadı.", + (K::Watch, Lang::En) => "Watch", + (K::Watch, Lang::Tr) => "İzle", + (K::Unwatch, Lang::En) => "Stop watching", + (K::Unwatch, Lang::Tr) => "İzlemeyi bırak", + (K::Watching, Lang::En) => "You are watching this task.", + (K::Watching, Lang::Tr) => "Bu görevi izliyorsunuz.", + (K::NotWatching, Lang::En) => "You are not watching this task.", + (K::NotWatching, Lang::Tr) => "Bu görevi izlemiyorsunuz.", + (K::Subtasks, Lang::En) => "Subtasks", + (K::Subtasks, Lang::Tr) => "Alt görevler", + (K::NoSubtasks, Lang::En) => "No subtasks.", + (K::NoSubtasks, Lang::Tr) => "Alt görev yok.", + (K::SubtaskTitle, Lang::En) => "New subtask", + (K::SubtaskTitle, Lang::Tr) => "Yeni alt görev", + (K::AddSubtask, Lang::En) => "Add subtask", + (K::AddSubtask, Lang::Tr) => "Alt görev ekle", + (K::Parent, Lang::En) => "Parent task", + (K::Parent, Lang::Tr) => "Üst görev", + (K::NoParent, Lang::En) => "None (top-level task)", + (K::NoParent, Lang::Tr) => "Yok (ana görev)", + (K::SetParent, Lang::En) => "Set parent", + (K::SetParent, Lang::Tr) => "Üst görevi ayarla", + (K::Dependencies, Lang::En) => "Dependencies", + (K::Dependencies, Lang::Tr) => "Bağımlılıklar", + (K::BlockedBy, Lang::En) => "Waits for", + (K::BlockedBy, Lang::Tr) => "Bekliyor", + (K::Blocks, Lang::En) => "Blocks", + (K::Blocks, Lang::Tr) => "Engelliyor", + (K::NoLinks, Lang::En) => "No dependencies.", + (K::NoLinks, Lang::Tr) => "Bağımlılık yok.", + (K::LinkWith, Lang::En) => "Task", + (K::LinkWith, Lang::Tr) => "Görev", + (K::LinkDirection, Lang::En) => "Direction", + (K::LinkDirection, Lang::Tr) => "Yön", + (K::DirBlockedBy, Lang::En) => "This task waits for the chosen task", + (K::DirBlockedBy, Lang::Tr) => "Bu görev seçilen görevi bekler", + (K::DirBlocks, Lang::En) => "This task blocks the chosen task", + (K::DirBlocks, Lang::Tr) => "Bu görev seçilen görevi engeller", + (K::AddLink, Lang::En) => "Add dependency", + (K::AddLink, Lang::Tr) => "Bağımlılık ekle", + (K::RemoveLink, Lang::En) => "Remove", + (K::RemoveLink, Lang::Tr) => "Kaldır", + (K::Comments, Lang::En) => "Comments", + (K::Comments, Lang::Tr) => "Yorumlar", + (K::NoComments, Lang::En) => "No comments yet.", + (K::NoComments, Lang::Tr) => "Henüz yorum yok.", + (K::CommentBody, Lang::En) => "Comment", + (K::CommentBody, Lang::Tr) => "Yorum", + (K::PostComment, Lang::En) => "Post comment", + (K::PostComment, Lang::Tr) => "Yorumu gönder", + (K::EditComment, Lang::En) => "Edit", + (K::EditComment, Lang::Tr) => "Düzenle", + (K::SaveComment, Lang::En) => "Save comment", + (K::SaveComment, Lang::Tr) => "Yorumu kaydet", + (K::DeleteComment, Lang::En) => "Delete comment", + (K::DeleteComment, Lang::Tr) => "Yorumu sil", + (K::Edited, Lang::En) => "edited", + (K::Edited, Lang::Tr) => "düzenlendi", + (K::Activity, Lang::En) => "Activity", + (K::Activity, Lang::Tr) => "Etkinlik", + (K::NoActivity, Lang::En) => "No activity yet.", + (K::NoActivity, Lang::Tr) => "Henüz etkinlik yok.", + (K::Older, Lang::En) => "Older activity", + (K::Older, Lang::Tr) => "Daha eski etkinlik", + (K::DeleteTask, Lang::En) => "Delete task", + (K::DeleteTask, Lang::Tr) => "Görevi sil", + (K::DeleteQuestion, Lang::En) => "Delete this task?", + (K::DeleteQuestion, Lang::Tr) => "Bu görev silinsin mi?", + (K::DeleteConsequence, Lang::En) => { + "Its subtasks and comments go with it. This cannot be undone." + } + (K::DeleteConsequence, Lang::Tr) => { + "Alt görevleri ve yorumları da silinir. Bu geri alınamaz." + } + (K::DeleteYes, Lang::En) => "Delete the task", + (K::DeleteYes, Lang::Tr) => "Görevi sil", + (K::NoticeSaved, Lang::En) => "Saved.", + (K::NoticeSaved, Lang::Tr) => "Kaydedildi.", + (K::ActCreated, Lang::En) => "created the task", + (K::ActCreated, Lang::Tr) => "görevi oluşturdu", + (K::ActEdited, Lang::En) => "edited the task", + (K::ActEdited, Lang::Tr) => "görevi düzenledi", + (K::ActMoved, Lang::En) => "moved the task", + (K::ActMoved, Lang::Tr) => "görevi taşıdı", + (K::ActDeleted, Lang::En) => "deleted the task", + (K::ActDeleted, Lang::Tr) => "görevi sildi", + (K::ActAssigned, Lang::En) => "assigned someone", + (K::ActAssigned, Lang::Tr) => "birini atadı", + (K::ActUnassigned, Lang::En) => "removed an assignee", + (K::ActUnassigned, Lang::Tr) => "bir atananı çıkardı", + (K::ActTagChanged, Lang::En) => "changed the project", + (K::ActTagChanged, Lang::Tr) => "projeyi değiştirdi", + (K::ActParentChanged, Lang::En) => "changed the parent task", + (K::ActParentChanged, Lang::Tr) => "üst görevi değiştirdi", + (K::ActLinkAdded, Lang::En) => "added a dependency", + (K::ActLinkAdded, Lang::Tr) => "bağımlılık ekledi", + (K::ActLinkRemoved, Lang::En) => "removed a dependency", + (K::ActLinkRemoved, Lang::Tr) => "bağımlılığı kaldırdı", + (K::ActUnblocked, Lang::En) => "was unblocked", + (K::ActUnblocked, Lang::Tr) => "engeli kalktı", + (K::ActDeadlineSet, Lang::En) => "set the deadline", + (K::ActDeadlineSet, Lang::Tr) => "son tarihi ayarladı", + (K::ActDeadlineCleared, Lang::En) => "cleared the deadline", + (K::ActDeadlineCleared, Lang::Tr) => "son tarihi kaldırdı", + (K::ActClockSet, Lang::En) => "set the meeting time", + (K::ActClockSet, Lang::Tr) => "toplantı saatini ayarladı", + (K::ActClockCleared, Lang::En) => "cleared the meeting time", + (K::ActClockCleared, Lang::Tr) => "toplantı saatini kaldırdı", + (K::ActWatchChanged, Lang::En) => "changed watching", + (K::ActWatchChanged, Lang::Tr) => "izleme durumunu değiştirdi", + (K::ActCommentAdded, Lang::En) => "commented", + (K::ActCommentAdded, Lang::Tr) => "yorum yaptı", + (K::ActCommentEdited, Lang::En) => "edited a comment", + (K::ActCommentEdited, Lang::Tr) => "bir yorumu düzenledi", + (K::ActCommentDeleted, Lang::En) => "deleted a comment", + (K::ActCommentDeleted, Lang::Tr) => "bir yorumu sildi", + (K::ActFileAdded, Lang::En) => "added a file", + (K::ActFileAdded, Lang::Tr) => "dosya ekledi", + (K::ActFileDeleted, Lang::En) => "deleted a file", + (K::ActFileDeleted, Lang::Tr) => "bir dosyayı sildi", + (K::ActReminded, Lang::En) => "was reminded", + (K::ActReminded, Lang::Tr) => "hatırlatıldı", + (K::ActAccountChanged, Lang::En) => "changed an account", + (K::ActAccountChanged, Lang::Tr) => "bir hesabı değiştirdi", + (K::ActOther, Lang::En) => "changed the task", + (K::ActOther, Lang::Tr) => "görevi değiştirdi", + (K::DescriptionTooLong, Lang::En) => "The description is longer than 20 000 characters.", + (K::DescriptionTooLong, Lang::Tr) => "Açıklama 20 000 karakterden uzun.", + (K::ErrProject, Lang::En) => "That project does not exist on this board.", + (K::ErrProject, Lang::Tr) => "Bu pano üzerinde böyle bir proje yok.", + (K::ErrDeadline, Lang::En) => "Use a deadline day such as 2026-10-28, or leave it empty.", + (K::ErrDeadline, Lang::Tr) => "2026-10-28 gibi bir gün yazın ya da boş bırakın.", + (K::ErrTime, Lang::En) => "Use a meeting time such as 09:30, or leave it empty.", + (K::ErrTime, Lang::Tr) => "09:30 gibi bir saat yazın ya da boş bırakın.", + (K::ErrMeeting, Lang::En) => { + "A meeting time needs a deadline day, and the time must exist in your time zone." + } + (K::ErrMeeting, Lang::Tr) => { + "Toplantı saati için bir son tarih gerekir ve saat sizin saat diliminizde olmalı." + } + (K::ErrAssignee, Lang::En) => "That person cannot be assigned.", + (K::ErrAssignee, Lang::Tr) => "Bu kişi atanamaz.", + (K::ErrSelf, Lang::En) => "A task cannot depend on itself.", + (K::ErrSelf, Lang::Tr) => "Bir görev kendisine bağımlı olamaz.", + (K::ErrCycle, Lang::En) => { + "This dependency would make a cycle of tasks waiting for each other." + } + (K::ErrCycle, Lang::Tr) => { + "Bu bağımlılık birbirini bekleyen görevlerden bir döngü oluşturur." + } + (K::ErrParent, Lang::En) => { + "A subtask must sit directly under a top-level task, and the parent must not be a subtask." + } + (K::ErrParent, Lang::Tr) => { + "Bir alt görev doğrudan bir ana göreve bağlanır ve üst görev de bir alt görev olamaz." + } + (K::ErrParentHasChildren, Lang::En) => "A task with subtasks cannot become a subtask.", + (K::ErrParentHasChildren, Lang::Tr) => "Alt görevi olan bir görev, alt görev yapılamaz.", + (K::ErrComment, Lang::En) => "Write a comment of 1 to 10 000 characters.", + (K::ErrComment, Lang::Tr) => "1 ile 10 000 karakter arasında bir yorum yazın.", + (K::ErrSubtaskTitle, Lang::En) => "Enter a subtask title of up to 200 characters.", + (K::ErrSubtaskTitle, Lang::Tr) => "En fazla 200 karakterlik bir alt görev başlığı girin.", + (K::ErrOtherTask, Lang::En) => "Pick a task from the list.", + (K::ErrOtherTask, Lang::Tr) => "Listeden bir görev seçin.", + (K::ErrDirection, Lang::En) => "Pick one of the two directions.", + (K::ErrDirection, Lang::Tr) => "İki yönden birini seçin.", + } +} + +/// The sentence of one activity row: the kind, in the viewer's language. +pub fn activity_kind(lang: Lang, kind: &str) -> &'static str { + let key = match kind { + "task_created" => K::ActCreated, + "task_edited" => K::ActEdited, + "task_moved" => K::ActMoved, + "task_deleted" => K::ActDeleted, + "assigned" => K::ActAssigned, + "unassigned" => K::ActUnassigned, + "tag_changed" => K::ActTagChanged, + "parent_changed" => K::ActParentChanged, + "link_added" => K::ActLinkAdded, + "link_removed" => K::ActLinkRemoved, + "unblocked" => K::ActUnblocked, + "deadline_set" => K::ActDeadlineSet, + "deadline_cleared" => K::ActDeadlineCleared, + "clock_set" => K::ActClockSet, + "clock_cleared" => K::ActClockCleared, + "watch_changed" => K::ActWatchChanged, + "comment_added" => K::ActCommentAdded, + "comment_edited" => K::ActCommentEdited, + "comment_deleted" => K::ActCommentDeleted, + "file_added" => K::ActFileAdded, + "file_deleted" => K::ActFileDeleted, + "reminded" => K::ActReminded, + "account_changed" => K::ActAccountChanged, + _ => K::ActOther, + }; + t(lang, key) +} diff --git a/crates/iz-web/src/pages/board.rs b/crates/iz-web/src/pages/board.rs index 1295617..ae5104a 100644 --- a/crates/iz-web/src/pages/board.rs +++ b/crates/iz-web/src/pages/board.rs @@ -20,7 +20,7 @@ use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::error::not_found; use topcoat::router::response::Response; -use topcoat::router::route; +use topcoat::router::{StatusCode, route}; use topcoat::view::view; use crate::assets::BOARD_JS_HREF; @@ -105,6 +105,8 @@ pub struct BoardPage { pub alert: Option, /// The notice of the last write, shown above the board. pub notice: Option<&'static str>, + /// The task modal, when `?task=` opened one (`pages/task.rs`). + pub modal: Option, } /// The board of this installation. The board is created at boot, so its absence is a missing page. @@ -249,6 +251,7 @@ pub async fn load( new_form: None, alert: None, notice: None, + modal: None, }) } @@ -297,13 +300,32 @@ async fn board_page(cx: &Cx) -> Result { let lang = lang(cx, me.member.locale_override.as_deref()); let query = uri_query(cx); let mut page = load(&state.store, &me, lang, query.as_deref()).await?; - let new_wanted = query_param(cx, "new").is_some_and(|v| v == "1"); - if new_wanted && page.can_write { - page.new_form = Some(blank_form(&page)); + let mut status = None; + match query_param(cx, "task").filter(|key| !key.is_empty()) { + Some(key) => { + let draft = crate::pages::task::Draft { + confirm: query_param(cx, "confirm").is_some_and(|v| v == "delete"), + before: query_param(cx, "before"), + ..Default::default() + }; + let found = + crate::pages::task::open(state, &me, &mut page, &key, query.as_deref(), draft) + .await?; + if !found { + page.alert = Some(K::TaskNotFound); + status = Some(StatusCode::NOT_FOUND); + } + } + None => { + let new_wanted = query_param(cx, "new").is_some_and(|v| v == "1"); + if new_wanted && page.can_write { + page.new_form = Some(blank_form(&page)); + } + } } page.notice = query_param(cx, "notice").and_then(|name| crate::i18n::board::notice(lang, &name)); - render(cx, &page, None).await + render(cx, &page, status).await } /// The new-task form with the first column and the default project chosen. diff --git a/crates/iz-web/src/pages/mod.rs b/crates/iz-web/src/pages/mod.rs index f26a18b..558d758 100644 --- a/crates/iz-web/src/pages/mod.rs +++ b/crates/iz-web/src/pages/mod.rs @@ -5,4 +5,5 @@ pub mod board; pub mod not_found; pub mod photo; pub mod sign_in; +pub mod task; pub mod tasks; diff --git a/crates/iz-web/src/pages/task.rs b/crates/iz-web/src/pages/task.rs new file mode 100644 index 0000000..4196d2f --- /dev/null +++ b/crates/iz-web/src/pages/task.rs @@ -0,0 +1,1345 @@ +//! The task modal (`docs/architecture.md` section 4, `docs/reference/old-inventory.md` 2.3): the card that +//! `GET /?task=` opens over the board, and every write the modal makes. +//! +//! Reads: the modal loads one task of this board by its key. A key that is unknown, deleted or on another +//! board answers the board with a "not found" notice and `404`. A viewer sees the same content with no +//! write control. +//! +//! Writes: every write is a form that carries the CSRF token and a `next` path (the modal's own URL). The +//! gate is the same as the board's (`pages/tasks.rs`): a member with the write level, the token, then the +//! change. A refused change re-renders the board with the modal open, the message above the fields, and +//! the typed values kept, at `422`. An accepted change redirects (Post/Redirect/Get) to the modal of its +//! task, with a notice. Each write bumps the board topic and the task topic (`live.rs`). +//! +//! Comments are checked by their own id: the store loads the comment, checks that its task is live and on +//! this board, and only then asks `authz` whether this member may edit or delete it. A comment of a deleted +//! task is not found. + +use std::collections::{HashMap, HashSet}; +use std::result::Result as StdResult; + +use iz_core::authz::{Action, authorize}; +use iz_core::clock::{MeetingInput, resolve_meeting, timestamp_of}; +use iz_core::limits::{COMMENT_MAX, DESCRIPTION_MAX, TITLE_MAX}; +use iz_core::store::board::Tag; +use iz_core::store::members::Member; +use iz_core::store::tasks::{NewTask, Task, TaskDetail, TaskEdit}; +use iz_core::zones::{parse_zone, utc_to_local}; +use jiff::civil::Date; +use jiff::tz::TimeZone; +use serde::Deserialize; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::Form; +use topcoat::router::error::{forbidden, not_found, see_other}; +use topcoat::router::response::Response; +use topcoat::router::{StatusCode, path_param_segment, route}; + +use crate::auth::{CurrentMember, percent_encode, safe_next}; +use crate::i18n::board::{K as BK, t as bt}; +use crate::i18n::task::{K, activity_kind, t}; +use crate::i18n::{Lang, lang}; +use crate::live::Topic; +use crate::pages::board::{BoardPage, board_url, load, pairs, query_of, render, the_board}; +use crate::pages::tasks::{answer_stop, writer}; +use crate::state::AppState; + +/// Rows of activity per page in the modal. Reason: the feed is a summary; older rows are one click away. +const ACTIVITY_PAGE: usize = 20; + +/// The filters that the modal keeps in its own links, so the board behind it is the same one. +const FILTER_KEYS: [&str; 4] = ["tag", "assignee", "sort", "q"]; + +/// The fields of the edit form as typed, or as stored. A refused edit shows the typed values again. +#[derive(Clone, Debug, Default)] +pub struct EditValues { + /// The title. + pub title: String, + /// The description, as plain text. + pub description: String, + /// The project id. + pub tag: String, + /// The deadline day, `YYYY-MM-DD`, or empty. + pub deadline: String, + /// The meeting time in the viewer's zone, `HH:MM`, or empty. + pub time: String, +} + +/// One comment as the modal shows it, with the rights of the viewer over it. +pub struct CommentRow { + /// The comment id. + pub id: String, + /// The author's name. + pub author: String, + /// The body as stored (plain text). + pub body: String, + /// When it was written, in the viewer's zone, `YYYY-MM-DD HH:MM`. + pub when: String, + /// Whether it was edited after it was written. + pub edited: bool, + /// Whether the viewer may edit it (its author, while a member). + pub can_edit: bool, + /// Whether the viewer may delete it (its author, or an admin). + pub can_delete: bool, +} + +/// One row of the activity feed. +pub struct ActivityRow { + /// The sentence for the kind of event, in the viewer's language. + pub sentence: &'static str, + /// Who did it, by name (`-` for the system). + pub actor: String, + /// When, in the viewer's zone, `YYYY-MM-DD HH:MM`. + pub when: String, +} + +/// The task modal, as the board page shows it. +pub struct TaskModal { + /// The task with its tag, assignees, subtasks and links. + pub detail: TaskDetail, + /// Whether the viewer may change the task. + pub can_write: bool, + /// This modal's own URL: the board filters and `task=`. Forms return here. + pub base: String, + /// The board with the same filters and no task: where the modal closes. + pub close: String, + /// The edit form's values: the stored ones, or the typed ones after a refusal. + pub edit: EditValues, + /// Enabled members who may be assigned and are not yet assigned here. + pub assignable: Vec, + /// Every other live task of the board, for the dependency and parent pickers. + pub options: Vec, + /// Whether the viewer watches the task. + pub watching: bool, + /// The live comments, oldest first. + pub comments: Vec, + /// The newest page of the activity feed. + pub activity: Vec, + /// The URL of the next, older page of activity, when there is one. + pub older: Option, + /// Whether the delete confirmation is open. + pub confirm_delete: bool, + /// The message of a refused write, shown above the fields. + pub error: Option<&'static str>, + /// The comment text typed in the composer, kept after a refusal. + pub comment_draft: String, +} + +/// What a re-rendered modal starts from: the message of a refusal, the typed values, and the view options. +#[derive(Default)] +pub struct Draft { + /// The refusal to show. + pub error: Option<&'static str>, + /// The typed edit values, when the edit was refused. + pub edit: Option, + /// The typed comment, when the comment was refused. + pub comment: Option, + /// Whether the delete confirmation is open (`?confirm=delete`). + pub confirm: bool, + /// The cursor of the activity page to show (`?before=`). + pub before: Option, +} + +/// The form of every modal write. Each field is optional on the wire; a missing one is empty. +#[derive(Deserialize, Default)] +pub struct ModalForm { + #[serde(default)] + csrf: String, + /// The modal URL the form was on. + #[serde(default)] + next: String, + #[serde(default)] + title: String, + #[serde(default)] + description: String, + /// The project id. + #[serde(default)] + tag: String, + #[serde(default)] + deadline: String, + /// The meeting time, `HH:MM`. + #[serde(default)] + time: String, + /// A comment body. + #[serde(default)] + body: String, + /// A member's id, for assign and unassign. + #[serde(default)] + sub: String, + /// `1` to watch, `0` to stop. + #[serde(default)] + on: String, + /// The parent task's id, or empty for none. + #[serde(default)] + parent: String, + /// The other task of a dependency. + #[serde(default)] + other: String, + /// `blocked_by` (this task waits for `other`) or `blocks` (`other` waits for this task). + #[serde(default)] + direction: String, +} + +/// The modal's URL for `key`: the board filters of `query` and `task=`, plus `extra`. Filters that are +/// not in [`FILTER_KEYS`] are dropped, so a stale `confirm` or `before` never comes back. +pub fn modal_url(query: Option<&str>, key: &str, extra: &[(&str, &str)]) -> String { + let mut parts: Vec = pairs(query.unwrap_or("")) + .into_iter() + .filter(|(name, _)| FILTER_KEYS.contains(&name.as_str())) + .map(|(name, value)| format!("{name}={}", percent_encode(&value))) + .collect(); + parts.push(format!("task={}", percent_encode(key))); + parts.extend( + extra + .iter() + .map(|(name, value)| format!("{name}={}", percent_encode(value))), + ); + format!("/?{}", parts.join("&")) +} + +/// The link to another task's modal from `close` (the board URL with the filters). +pub fn task_link(close: &str, key: &str) -> String { + let separator = if close.contains('?') { '&' } else { '?' }; + format!("{close}{separator}task={}", percent_encode(key)) +} + +/// The `task` value of a `next` path, when it names one. +fn task_of(next: &str) -> Option { + pairs(query_of(safe_next(Some(next))).unwrap_or("")) + .into_iter() + .find(|(name, _)| name == "task") + .map(|(_, value)| value) + .filter(|value| !value.is_empty()) +} + +/// Maps a store error to the framework's answer: a missing or hidden thing is `404`, a refused right is +/// `403`, and anything else is a logged `500`. +pub fn core_err(error: iz_core::Error) -> topcoat::Error { + match error { + iz_core::Error::NotFound => not_found().into(), + iz_core::Error::Forbidden(_) => forbidden().into(), + other => other.into(), + } +} + +/// The zone of the signed-in member; UTC when the stored name does not parse. +fn zone_of(me: &CurrentMember) -> TimeZone { + parse_zone(&me.member.zoneinfo).unwrap_or(TimeZone::UTC) +} + +/// A stored UTC stamp in `zone` as `YYYY-MM-DD HH:MM`. Empty when the stamp does not parse. +fn local_text(stamp: &str, zone: &TimeZone) -> String { + match timestamp_of(stamp) { + Ok(at) => { + let local = utc_to_local(zone, at); + format!( + "{:04}-{:02}-{:02} {:02}:{:02}", + local.year(), + local.month(), + local.day(), + local.hour(), + local.minute() + ) + } + Err(_) => String::new(), + } +} + +/// A stored UTC stamp in `zone` as `HH:MM`, for the time field. +fn clock_text(stamp: &str, zone: &TimeZone) -> String { + match timestamp_of(stamp) { + Ok(at) => { + let local = utc_to_local(zone, at); + format!("{:02}:{:02}", local.hour(), local.minute()) + } + Err(_) => String::new(), + } +} + +/// Reads `HH:MM` (one or two digits per part). `None` for anything else, or an hour or minute out of range. +fn parse_clock(text: &str) -> Option<(u8, u8)> { + let (hour, minute) = text.trim().split_once(':')?; + if hour.is_empty() || hour.len() > 2 || minute.len() != 2 { + return None; + } + let hour: u8 = hour.parse().ok()?; + let minute: u8 = minute.parse().ok()?; + (hour < 24 && minute < 60).then_some((hour, minute)) +} + +/// Checks the edit form and turns it into the store's input. The first problem found is the message. The +/// deadline and the meeting time are resolved in the viewer's zone (`clock.rs`). +fn edit_input( + form: &ModalForm, + tags: &[Tag], + zone: &TimeZone, + language: Lang, +) -> StdResult { + let title = form.title.trim(); + if title.is_empty() || title.chars().count() > TITLE_MAX { + return Err(bt(language, BK::TitleInvalid)); + } + if form.description.chars().count() > DESCRIPTION_MAX { + return Err(t(language, K::DescriptionTooLong)); + } + if !tags.iter().any(|tag| tag.id == form.tag) { + return Err(t(language, K::ErrProject)); + } + let day = match form.deadline.trim() { + "" => None, + text => Some( + text.parse::() + .map_err(|_| t(language, K::ErrDeadline))?, + ), + }; + let clock = match form.time.trim() { + "" => None, + text => Some(parse_clock(text).ok_or(t(language, K::ErrTime))?), + }; + let (hour, minute) = match clock { + Some((hour, minute)) => (Some(hour), Some(minute)), + None => (None, None), + }; + let (deadline, meeting_at) = resolve_meeting(MeetingInput { day, hour, minute }, zone) + .map_err(|_| t(language, K::ErrMeeting))?; + Ok(TaskEdit { + title: title.to_owned(), + description: form.description.clone(), + tag_id: form.tag.clone(), + deadline, + meeting_at, + }) +} + +/// The direction of a dependency as the stored pair: `(blocked, blocking)`. `None` for an unknown word. +fn link_pair<'a>(task: &'a str, other: &'a str, direction: &str) -> Option<(&'a str, &'a str)> { + match direction { + "blocked_by" => Some((task, other)), + "blocks" => Some((other, task)), + _ => None, + } +} + +/// Loads the modal of `key` into `page`. Returns `false` when the task does not exist on this board (or is +/// deleted); the page is then left as it was. +pub async fn open( + state: &AppState, + me: &CurrentMember, + page: &mut BoardPage, + key: &str, + query: Option<&str>, + draft: Draft, +) -> Result { + let store = &state.store; + let board = the_board(store).await?; + let detail = match store.task_detail(&board.id, key).await { + Ok(detail) => detail, + Err(iz_core::Error::NotFound) => return Ok(false), + Err(error) => return Err(core_err(error)), + }; + let task_id = detail.task.id.clone(); + let zone = page.zone.clone(); + let names: HashMap = store + .list_members() + .await + .map_err(core_err)? + .into_iter() + .map(|member| (member.sub, member.name)) + .collect(); + let name_of = |sub: &str| names.get(sub).cloned().unwrap_or_else(|| "-".to_owned()); + let comments = store + .list_comments(&board.id, &task_id) + .await + .map_err(core_err)?; + let before = draft.before.filter(|cursor| cursor.contains('~')); + let feed = store + .list_task_page(&board.id, &task_id, before.as_deref(), ACTIVITY_PAGE) + .await + .map_err(core_err)?; + let watching = store + .is_watching(&task_id, &me.member.sub) + .await + .map_err(core_err)?; + let options: Vec = store + .task_options(&board.id) + .await + .map_err(core_err)? + .into_iter() + .filter(|other| other.id != task_id) + .collect(); + let assigned: HashSet<&str> = detail.assignees.iter().map(|a| a.sub.as_str()).collect(); + let assignable: Vec = page + .members + .iter() + .filter(|member| !assigned.contains(member.sub.as_str())) + .cloned() + .collect(); + let can_write = page.can_write; + let comment_rows: Vec = comments + .into_iter() + .map(|comment| { + let author = comment.author.clone(); + CommentRow { + can_edit: can_write + && authorize( + &me.actor(), + &Action::EditComment { + author: author.clone(), + }, + ) + .is_ok(), + can_delete: can_write + && authorize( + &me.actor(), + &Action::DeleteComment { + author: author.clone(), + }, + ) + .is_ok(), + author: name_of(&author), + when: local_text(&comment.created_at, &zone), + edited: comment.edited_at.is_some(), + id: comment.id, + body: comment.body, + } + }) + .collect(); + let activity: Vec = feed + .items + .iter() + .map(|item| ActivityRow { + sentence: activity_kind(page.lang, &item.kind), + actor: item + .actor + .as_deref() + .map_or_else(|| "-".to_owned(), name_of), + when: local_text(&item.at, &zone), + }) + .collect(); + let base = modal_url(query, key, &[]); + let older = feed + .next_cursor + .map(|cursor| format!("{base}&before={}", percent_encode(&cursor))); + let stored = EditValues { + title: detail.task.title.clone(), + description: detail.task.description.clone(), + tag: detail.task.tag_id.clone(), + deadline: detail + .task + .deadline + .map(|day| day.to_string()) + .unwrap_or_default(), + time: detail + .task + .meeting_at + .as_deref() + .map(|stamp| clock_text(stamp, &zone)) + .unwrap_or_default(), + }; + let modal = TaskModal { + can_write, + close: board_url(&page.filters, &[]), + base, + edit: draft.edit.unwrap_or(stored), + assignable, + options, + watching, + comments: comment_rows, + activity, + older, + confirm_delete: draft.confirm && can_write, + error: draft.error, + comment_draft: draft.comment.unwrap_or_default(), + detail, + }; + page.modal = Some(modal); + Ok(true) +} + +/// A write that passed the gate and found its task on this board. +struct Begun { + me: CurrentMember, + lang: Lang, + board_id: String, + detail: TaskDetail, +} + +/// The gate of a write: the member with the write level and the CSRF token, then the board. A refusal of +/// the gate is answered as the board's writes answer theirs; the inner `Err` carries that answer. +async fn gate( + cx: &Cx, + csrf: &str, + next: &str, +) -> Result> { + let state = app_context::(cx); + let me = match writer(cx, csrf).await { + Ok(me) => me, + Err(stop) => { + return Ok(Err( + answer_stop(cx, stop, false, next, lang(cx, None)).await? + )); + } + }; + let language = lang(cx, me.member.locale_override.as_deref()); + let board = the_board(&state.store).await?; + Ok(Ok((me, language, board.id))) +} + +/// The gate of a write that names its task in the path. +async fn gate_task(cx: &Cx, form: &ModalForm, task_id: &str) -> Result> { + let state = app_context::(cx); + let (me, language, board_id) = match gate(cx, &form.csrf, &form.next).await? { + Ok(found) => found, + Err(response) => return Ok(Err(response)), + }; + let detail = state + .store + .task_detail(&board_id, task_id) + .await + .map_err(core_err)?; + Ok(Ok(Begun { + me, + lang: language, + board_id, + detail, + })) +} + +/// Re-renders the board with the modal of `key` open, the refusal above its fields, and `422`. When the +/// task is gone the board answers `404` with its "not found" notice. +async fn refuse( + cx: &Cx, + me: &CurrentMember, + language: Lang, + next: &str, + key: &str, + draft: Draft, +) -> Result { + let state = app_context::(cx); + let query = query_of(safe_next(Some(next))); + let mut page = load(&state.store, me, language, query).await?; + let found = open(state, me, &mut page, key, query, draft).await?; + let status = if found { + StatusCode::UNPROCESSABLE_ENTITY + } else { + page.alert = Some(BK::TaskNotFound); + StatusCode::NOT_FOUND + }; + render(cx, &page, Some(status)).await +} + +/// A `Draft` that only shows a refusal. +fn refusal(message: &'static str) -> Draft { + Draft { + error: Some(message), + ..Draft::default() + } +} + +/// Tells every open view of the board and of the task that something changed. +fn bump(state: &AppState, board_id: &str, task_id: &str) { + state.live.bump(&Topic::Board(board_id.to_owned())); + state.live.bump(&Topic::Task(task_id.to_owned())); +} + +/// Answers a write that went through: the modal of `key` with the saved notice, or the board when there is +/// no task to return to. +fn back(next: &str, key: Option<&str>) -> Result { + let target = match key { + Some(key) => modal_url(query_of(safe_next(Some(next))), key, &[("notice", "saved")]), + None => "/".to_owned(), + }; + Err(see_other(target).into()) +} + +/// `POST /tasks/{id}/edit`: the title, description, project, deadline and meeting time. +#[route(POST "/tasks/{id}/edit")] +async fn edit_task(cx: &Cx, form: Option>) -> Result { + let state = app_context::(cx); + let form = form.map(|Form(form)| form).unwrap_or_default(); + let task_id = path_param_segment(cx, "id").to_owned(); + let begun = match gate_task(cx, &form, &task_id).await? { + Ok(begun) => begun, + Err(response) => return Ok(response), + }; + let key = begun.detail.task.key.clone(); + let zone = zone_of(&begun.me); + let tags = state.store.tags(&begun.board_id).await.map_err(core_err)?; + let typed = EditValues { + title: form.title.clone(), + description: form.description.clone(), + tag: form.tag.clone(), + deadline: form.deadline.clone(), + time: form.time.clone(), + }; + let edit = match edit_input(&form, &tags, &zone, begun.lang) { + Ok(edit) => edit, + Err(message) => { + let draft = Draft { + edit: Some(typed), + ..refusal(message) + }; + return refuse(cx, &begun.me, begun.lang, &form.next, &key, draft).await; + } + }; + match state + .store + .edit_task(&begun.board_id, &task_id, edit, &begun.me.member.sub) + .await + { + Ok(_) => { + bump(state, &begun.board_id, &task_id); + back(&form.next, Some(key.as_str())) + } + Err(iz_core::Error::Invalid(_)) => { + let draft = Draft { + edit: Some(typed), + ..refusal(bt(begun.lang, BK::InvalidForm)) + }; + refuse(cx, &begun.me, begun.lang, &form.next, &key, draft).await + } + Err(error) => Err(core_err(error)), + } +} + +/// `POST /tasks/{id}/assign`: adds one member. The store refuses anyone who is not an enabled admin or +/// member. +#[route(POST "/tasks/{id}/assign")] +async fn assign(cx: &Cx, form: Option>) -> Result { + let state = app_context::(cx); + let form = form.map(|Form(form)| form).unwrap_or_default(); + let task_id = path_param_segment(cx, "id").to_owned(); + let begun = match gate_task(cx, &form, &task_id).await? { + Ok(begun) => begun, + Err(response) => return Ok(response), + }; + let key = begun.detail.task.key.clone(); + let sub = form.sub.trim().to_owned(); + if sub.is_empty() { + return refuse( + cx, + &begun.me, + begun.lang, + &form.next, + &key, + refusal(t(begun.lang, K::ErrAssignee)), + ) + .await; + } + match state + .store + .assign(&begun.board_id, &task_id, &[sub], &begun.me.member.sub) + .await + { + Ok(()) => { + bump(state, &begun.board_id, &task_id); + back(&form.next, Some(key.as_str())) + } + Err(iz_core::Error::Invalid(_)) => { + refuse( + cx, + &begun.me, + begun.lang, + &form.next, + &key, + refusal(t(begun.lang, K::ErrAssignee)), + ) + .await + } + Err(error) => Err(core_err(error)), + } +} + +/// `POST /tasks/{id}/unassign`: removes one member. Removing someone who is not assigned changes nothing. +#[route(POST "/tasks/{id}/unassign")] +async fn unassign(cx: &Cx, form: Option>) -> Result { + let state = app_context::(cx); + let form = form.map(|Form(form)| form).unwrap_or_default(); + let task_id = path_param_segment(cx, "id").to_owned(); + let begun = match gate_task(cx, &form, &task_id).await? { + Ok(begun) => begun, + Err(response) => return Ok(response), + }; + let key = begun.detail.task.key.clone(); + state + .store + .unassign( + &begun.board_id, + &task_id, + &[form.sub.trim().to_owned()], + &begun.me.member.sub, + ) + .await + .map_err(core_err)?; + bump(state, &begun.board_id, &task_id); + back(&form.next, Some(key.as_str())) +} + +/// `POST /tasks/{id}/watch`: starts (`on=1`) or stops (`on=0`) watching the task, for the viewer. +#[route(POST "/tasks/{id}/watch")] +async fn watch(cx: &Cx, form: Option>) -> Result { + let state = app_context::(cx); + let form = form.map(|Form(form)| form).unwrap_or_default(); + let task_id = path_param_segment(cx, "id").to_owned(); + let begun = match gate_task(cx, &form, &task_id).await? { + Ok(begun) => begun, + Err(response) => return Ok(response), + }; + let key = begun.detail.task.key.clone(); + let on = match form.on.trim() { + "1" => true, + "0" => false, + _ => { + return refuse( + cx, + &begun.me, + begun.lang, + &form.next, + &key, + refusal(bt(begun.lang, BK::InvalidForm)), + ) + .await; + } + }; + state + .store + .set_watch(&begun.board_id, &task_id, &begun.me.member.sub, on) + .await + .map_err(core_err)?; + bump(state, &begun.board_id, &task_id); + back(&form.next, Some(key.as_str())) +} + +/// `POST /tasks/{id}/subtasks`: creates a subtask under this task, in its column and project. +#[route(POST "/tasks/{id}/subtasks")] +async fn add_subtask(cx: &Cx, form: Option>) -> Result { + let state = app_context::(cx); + let form = form.map(|Form(form)| form).unwrap_or_default(); + let task_id = path_param_segment(cx, "id").to_owned(); + let begun = match gate_task(cx, &form, &task_id).await? { + Ok(begun) => begun, + Err(response) => return Ok(response), + }; + let key = begun.detail.task.key.clone(); + let title = form.title.trim().to_owned(); + if title.is_empty() || title.chars().count() > TITLE_MAX { + let message = t(begun.lang, K::ErrSubtaskTitle); + return refuse( + cx, + &begun.me, + begun.lang, + &form.next, + &key, + refusal(message), + ) + .await; + } + if begun.detail.task.parent_id.is_some() { + let message = t(begun.lang, K::ErrParent); + return refuse( + cx, + &begun.me, + begun.lang, + &form.next, + &key, + refusal(message), + ) + .await; + } + let input = NewTask { + title, + description: String::new(), + column_id: begun.detail.task.column_id.clone(), + tag_id: begun.detail.task.tag_id.clone(), + deadline: None, + meeting_at: None, + assignees: Vec::new(), + parent_id: Some(task_id.clone()), + link: None, + }; + match state + .store + .create_task(&begun.board_id, input, &begun.me.member.sub) + .await + { + Ok(_) => { + bump(state, &begun.board_id, &task_id); + back(&form.next, Some(key.as_str())) + } + Err(iz_core::Error::Invalid(_)) => { + let message = t(begun.lang, K::ErrParent); + refuse( + cx, + &begun.me, + begun.lang, + &form.next, + &key, + refusal(message), + ) + .await + } + Err(error) => Err(core_err(error)), + } +} + +/// `POST /tasks/{id}/parent`: makes this task a subtask of `parent`, or a top-level task when `parent` is +/// empty. One level only; the store refuses the rest. +#[route(POST "/tasks/{id}/parent")] +async fn set_parent(cx: &Cx, form: Option>) -> Result { + let state = app_context::(cx); + let form = form.map(|Form(form)| form).unwrap_or_default(); + let task_id = path_param_segment(cx, "id").to_owned(); + let begun = match gate_task(cx, &form, &task_id).await? { + Ok(begun) => begun, + Err(response) => return Ok(response), + }; + let key = begun.detail.task.key.clone(); + let parent = form.parent.trim(); + let parent = (!parent.is_empty()).then_some(parent); + match state + .store + .set_parent(&begun.board_id, &task_id, parent, &begun.me.member.sub) + .await + { + Ok(()) => { + bump(state, &begun.board_id, &task_id); + back(&form.next, Some(key.as_str())) + } + Err(iz_core::Error::Conflict(_)) => { + let message = t(begun.lang, K::ErrParentHasChildren); + refuse( + cx, + &begun.me, + begun.lang, + &form.next, + &key, + refusal(message), + ) + .await + } + Err(iz_core::Error::Invalid(_)) => { + let message = t(begun.lang, K::ErrParent); + refuse( + cx, + &begun.me, + begun.lang, + &form.next, + &key, + refusal(message), + ) + .await + } + Err(error) => Err(core_err(error)), + } +} + +/// `POST /tasks/{id}/links`: adds a dependency with `other`. A cycle is refused with its own message. +#[route(POST "/tasks/{id}/links")] +async fn add_link(cx: &Cx, form: Option>) -> Result { + let state = app_context::(cx); + let form = form.map(|Form(form)| form).unwrap_or_default(); + let task_id = path_param_segment(cx, "id").to_owned(); + let begun = match gate_task(cx, &form, &task_id).await? { + Ok(begun) => begun, + Err(response) => return Ok(response), + }; + let key = begun.detail.task.key.clone(); + let other = form.other.trim().to_owned(); + if other.is_empty() { + let message = t(begun.lang, K::ErrOtherTask); + return refuse( + cx, + &begun.me, + begun.lang, + &form.next, + &key, + refusal(message), + ) + .await; + } + let Some((blocked, blocking)) = link_pair(&task_id, &other, form.direction.trim()) else { + let message = t(begun.lang, K::ErrDirection); + return refuse( + cx, + &begun.me, + begun.lang, + &form.next, + &key, + refusal(message), + ) + .await; + }; + match state + .store + .add_dependency(&begun.board_id, blocked, blocking, &begun.me.member.sub) + .await + { + Ok(()) => { + bump(state, &begun.board_id, &task_id); + state.live.bump(&Topic::Task(other.clone())); + back(&form.next, Some(key.as_str())) + } + Err(iz_core::Error::Conflict(_)) => { + let message = t(begun.lang, K::ErrCycle); + refuse( + cx, + &begun.me, + begun.lang, + &form.next, + &key, + refusal(message), + ) + .await + } + Err(iz_core::Error::Invalid(_)) => { + let message = t(begun.lang, K::ErrSelf); + refuse( + cx, + &begun.me, + begun.lang, + &form.next, + &key, + refusal(message), + ) + .await + } + Err(iz_core::Error::NotFound) => { + let message = t(begun.lang, K::ErrOtherTask); + refuse( + cx, + &begun.me, + begun.lang, + &form.next, + &key, + refusal(message), + ) + .await + } + Err(error) => Err(core_err(error)), + } +} + +/// `POST /tasks/{id}/links/remove`: clears a dependency (a soft clear: the history stays). +#[route(POST "/tasks/{id}/links/remove")] +async fn remove_link(cx: &Cx, form: Option>) -> Result { + let state = app_context::(cx); + let form = form.map(|Form(form)| form).unwrap_or_default(); + let task_id = path_param_segment(cx, "id").to_owned(); + let begun = match gate_task(cx, &form, &task_id).await? { + Ok(begun) => begun, + Err(response) => return Ok(response), + }; + let key = begun.detail.task.key.clone(); + let other = form.other.trim().to_owned(); + let Some((blocked, blocking)) = link_pair(&task_id, &other, form.direction.trim()) else { + let message = t(begun.lang, K::ErrDirection); + return refuse( + cx, + &begun.me, + begun.lang, + &form.next, + &key, + refusal(message), + ) + .await; + }; + match state + .store + .clear_dependency(&begun.board_id, blocked, blocking, &begun.me.member.sub) + .await + { + Ok(()) | Err(iz_core::Error::NotFound) => { + bump(state, &begun.board_id, &task_id); + state.live.bump(&Topic::Task(other.clone())); + back(&form.next, Some(key.as_str())) + } + Err(error) => Err(core_err(error)), + } +} + +/// `POST /tasks/{id}/comments`: posts a comment on the task. +#[route(POST "/tasks/{id}/comments")] +async fn add_comment(cx: &Cx, form: Option>) -> Result { + let state = app_context::(cx); + let form = form.map(|Form(form)| form).unwrap_or_default(); + let task_id = path_param_segment(cx, "id").to_owned(); + let begun = match gate_task(cx, &form, &task_id).await? { + Ok(begun) => begun, + Err(response) => return Ok(response), + }; + let key = begun.detail.task.key.clone(); + let body = form.body.trim().to_owned(); + if body.is_empty() || body.chars().count() > COMMENT_MAX { + let draft = Draft { + comment: Some(form.body.clone()), + ..refusal(t(begun.lang, K::ErrComment)) + }; + return refuse(cx, &begun.me, begun.lang, &form.next, &key, draft).await; + } + match state + .store + .add_comment(&begun.board_id, &task_id, &begun.me.member.sub, &body) + .await + { + Ok(_) => { + bump(state, &begun.board_id, &task_id); + back(&form.next, Some(key.as_str())) + } + Err(error) => Err(core_err(error)), + } +} + +/// `POST /comments/{id}/edit`: edits a comment. Only its author may, and only while a member. The comment +/// is checked by its own id (live, on this board, its task live), then by `authz`. +#[route(POST "/comments/{id}/edit")] +async fn edit_comment(cx: &Cx, form: Option>) -> Result { + let state = app_context::(cx); + let form = form.map(|Form(form)| form).unwrap_or_default(); + let comment_id = path_param_segment(cx, "id").to_owned(); + let (me, language, board_id) = match gate(cx, &form.csrf, &form.next).await? { + Ok(found) => found, + Err(response) => return Ok(response), + }; + let key = task_of(&form.next); + let body = form.body.trim().to_owned(); + if body.is_empty() || body.chars().count() > COMMENT_MAX { + let Some(key) = key else { + return Err(not_found().into()); + }; + let draft = Draft { + comment: Some(form.body.clone()), + ..refusal(t(language, K::ErrComment)) + }; + return refuse(cx, &me, language, &form.next, &key, draft).await; + } + match state + .store + .edit_comment(&board_id, &comment_id, &me.actor(), &body) + .await + { + Ok(comment) => { + bump(state, &board_id, &comment.task_id); + back(&form.next, key.as_deref()) + } + Err(error) => Err(core_err(error)), + } +} + +/// `POST /comments/{id}/delete`: deletes a comment. Its author (while a member) or an admin may. +#[route(POST "/comments/{id}/delete")] +async fn delete_comment(cx: &Cx, form: Option>) -> Result { + let state = app_context::(cx); + let form = form.map(|Form(form)| form).unwrap_or_default(); + let comment_id = path_param_segment(cx, "id").to_owned(); + let (me, _language, board_id) = match gate(cx, &form.csrf, &form.next).await? { + Ok(found) => found, + Err(response) => return Ok(response), + }; + let key = task_of(&form.next); + match state + .store + .delete_comment(&board_id, &comment_id, &me.actor()) + .await + { + Ok(task_id) => { + bump(state, &board_id, &task_id); + back(&form.next, key.as_deref()) + } + Err(error) => Err(core_err(error)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn modal_url_keeps_filters_and_drops_the_rest() { + assert_eq!( + modal_url(Some("tag=a b&confirm=delete&sort=title&q=x"), "IZ-4", &[]), + "/?tag=a%20b&sort=title&q=x&task=IZ-4" + ); + assert_eq!( + modal_url(None, "IZ-4", &[("before", "2026~01")]), + "/?task=IZ-4&before=2026~01" + ); + } + + #[test] + fn clock_text_is_hours_and_minutes() { + assert_eq!(parse_clock("09:30"), Some((9, 30))); + assert_eq!(parse_clock("9:30"), Some((9, 30))); + assert_eq!(parse_clock("24:00"), None); + assert_eq!(parse_clock("09:60"), None); + assert_eq!(parse_clock("0930"), None); + } + + #[test] + fn a_dependency_names_its_blocked_and_blocking_side() { + assert_eq!(link_pair("a", "b", "blocked_by"), Some(("a", "b"))); + assert_eq!(link_pair("a", "b", "blocks"), Some(("b", "a"))); + assert_eq!(link_pair("a", "b", "other"), None); + } + + #[test] + fn a_return_path_names_its_task_only_when_local() { + assert_eq!(task_of("/?task=IZ-4&tag=x").as_deref(), Some("IZ-4")); + assert_eq!(task_of("//evil.example/?task=IZ-4"), None); + } +} + +#[cfg(test)] +mod render_tests { + use http::header::{CONTENT_TYPE, COOKIE}; + use iz_core::authz::Role; + use iz_core::store::tasks::{NewTask, TaskEdit}; + use topcoat::router::{Body, to_bytes}; + + use super::*; + use crate::boot::{router, test_state}; + use crate::pages::board::{cookie_of, one_card, sign_in_as}; + use crate::state::AppState; + + const AUTHOR: &str = "01ADAAAAAAAAAAAAAAAAAAAAAA"; + const OTHER: &str = "01BOAAAAAAAAAAAAAAAAAAAAAA"; + const VIEWER: &str = "01VIAAAAAAAAAAAAAAAAAAAAAA"; + + /// Sends one request and returns its status and body as text. + async fn send(state: &AppState, request: http::Request) -> (u16, String) { + let response = router(state.clone()).handle(request).await; + let status = response.status().as_u16(); + let bytes = to_bytes(response.into_body(), 1024 * 1024) + .await + .expect("body"); + (status, String::from_utf8_lossy(&bytes).into_owned()) + } + + /// A form POST with the session's cookie. + fn post(path: &str, token: &str, body: String) -> http::Request { + http::Request::post(path) + .header(CONTENT_TYPE, "application/x-www-form-urlencoded") + .header(COOKIE, cookie_of(token)) + .body(Body::from(body)) + .expect("request") + } + + /// A GET with the session's cookie. + fn get(path: &str, token: &str) -> http::Request { + http::Request::get(path) + .header(COOKIE, cookie_of(token)) + .body(Body::empty()) + .expect("request") + } + + /// The key of a task, read through the store. + async fn key_of(state: &AppState, task_id: &str) -> String { + let board = state.store.board().await.expect("board").expect("some"); + state + .store + .task_detail(&board.id, task_id) + .await + .expect("detail") + .task + .key + } + + /// The modal URL of a task, as a form carries it. + fn next_of(key: &str) -> String { + percent_encode(&modal_url(None, key, &[])) + } + + /// A viewer's comment is refused with `403`, and nothing is stored. + #[tokio::test] + async fn a_viewer_cannot_comment() { + let (_dir, state) = test_state().await; + sign_in_as(&state, AUTHOR, Role::Member).await; + let (task_id, _) = one_card(&state, "Milk", AUTHOR).await; + let (token, csrf) = sign_in_as(&state, VIEWER, Role::Viewer).await; + let key = key_of(&state, &task_id).await; + let body = format!("csrf={csrf}&next={}&body=hello", next_of(&key)); + let (status, _) = send( + &state, + post(&format!("/tasks/{task_id}/comments"), &token, body), + ) + .await; + assert_eq!(status, 403); + let board = state.store.board().await.expect("board").expect("some"); + let comments = state + .store + .list_comments(&board.id, &task_id) + .await + .expect("comments"); + assert!(comments.is_empty()); + } + + /// Another member cannot edit someone else's comment: `403`, and the body stays as it was. + #[tokio::test] + async fn another_member_cannot_edit_a_comment() { + let (_dir, state) = test_state().await; + sign_in_as(&state, AUTHOR, Role::Member).await; + sign_in_as(&state, OTHER, Role::Member).await; + let (task_id, _) = one_card(&state, "Milk", AUTHOR).await; + let board = state.store.board().await.expect("board").expect("some"); + let comment = state + .store + .add_comment(&board.id, &task_id, AUTHOR, "mine") + .await + .expect("comment"); + let (token, csrf) = sign_in_as(&state, OTHER, Role::Member).await; + let key = key_of(&state, &task_id).await; + let body = format!("csrf={csrf}&next={}&body=changed", next_of(&key)); + let (status, _) = send( + &state, + post(&format!("/comments/{}/edit", comment.id), &token, body), + ) + .await; + assert_eq!(status, 403); + let comments = state + .store + .list_comments(&board.id, &task_id) + .await + .expect("comments"); + assert_eq!(comments[0].body, "mine"); + } + + /// A comment of a deleted task is not found, for edit and for delete. + #[tokio::test] + async fn a_comment_of_a_deleted_task_is_not_found() { + let (_dir, state) = test_state().await; + sign_in_as(&state, AUTHOR, Role::Member).await; + let (task_id, _) = one_card(&state, "Milk", AUTHOR).await; + let board = state.store.board().await.expect("board").expect("some"); + let comment = state + .store + .add_comment(&board.id, &task_id, AUTHOR, "old") + .await + .expect("comment"); + state + .store + .delete_task(&board.id, &task_id, AUTHOR) + .await + .expect("delete"); + let (token, csrf) = sign_in_as(&state, AUTHOR, Role::Member).await; + let body = format!("csrf={csrf}&next=%2F&body=again"); + let (status, _) = send( + &state, + post(&format!("/comments/{}/edit", comment.id), &token, body), + ) + .await; + assert_eq!(status, 404); + let body = format!("csrf={csrf}&next=%2F"); + let (status, _) = send( + &state, + post(&format!("/comments/{}/delete", comment.id), &token, body), + ) + .await; + assert_eq!(status, 404); + } + + /// A description with markup and a `javascript:` address reaches the page as text. Only the https + /// address becomes a link. + #[tokio::test] + async fn a_description_is_plain_text_with_safe_links() { + let (_dir, state) = test_state().await; + let (token, _) = sign_in_as(&state, AUTHOR, Role::Member).await; + let (task_id, _) = one_card(&state, "Milk", AUTHOR).await; + let board = state.store.board().await.expect("board").expect("some"); + let tags = state.store.tags(&board.id).await.expect("tags"); + let description = "\njavascript:alert(1) \ + https://ok.example/a?b=1. bold"; + state + .store + .edit_task( + &board.id, + &task_id, + TaskEdit { + title: "Milk".into(), + description: description.into(), + tag_id: tags[0].id.clone(), + deadline: None, + meeting_at: None, + }, + AUTHOR, + ) + .await + .expect("edit"); + let key = key_of(&state, &task_id).await; + let (status, html) = send(&state, get(&format!("/?task={key}"), &token)).await; + assert_eq!(status, 200); + assert!( + html.contains("<img src=x onerror=alert(1)>"), + "not escaped" + ); + assert!(!html.contains("bold"), "markup reached the page"); + assert!(!html.contains("href=\"javascript"), "javascript link"); + assert!( + html.contains("href=\"https://ok.example/a?b=1\""), + "https address not linked" + ); + } + + /// A dependency that closes a cycle is refused with `422` and its translated message. + #[tokio::test] + async fn a_dependency_cycle_is_refused_with_a_message() { + let (_dir, state) = test_state().await; + let (token, csrf) = sign_in_as(&state, AUTHOR, Role::Member).await; + let (first, column) = one_card(&state, "First", AUTHOR).await; + let board = state.store.board().await.expect("board").expect("some"); + let tags = state.store.tags(&board.id).await.expect("tags"); + let second = state + .store + .create_task( + &board.id, + NewTask { + title: "Second".into(), + description: String::new(), + column_id: column, + tag_id: tags[0].id.clone(), + deadline: None, + meeting_at: None, + assignees: Vec::new(), + parent_id: None, + link: None, + }, + AUTHOR, + ) + .await + .expect("second task") + .id; + state + .store + .add_dependency(&board.id, &first, &second, AUTHOR) + .await + .expect("first link"); + let key = key_of(&state, &second).await; + let body = format!( + "csrf={csrf}&next={}&other={first}&direction=blocked_by", + next_of(&key) + ); + let (status, html) = send( + &state, + post(&format!("/tasks/{second}/links"), &token, body), + ) + .await; + assert_eq!(status, 422); + assert!( + html.contains(t(Lang::En, K::ErrCycle)), + "cycle message missing: {html}" + ); + } + + /// An unknown task key answers the board with its notice and `404`. + #[tokio::test] + async fn an_unknown_task_key_is_not_found() { + let (_dir, state) = test_state().await; + let (token, _) = sign_in_as(&state, AUTHOR, Role::Member).await; + state.store.ensure_board("IZ").await.expect("board"); + let (status, html) = send(&state, get("/?task=IZ-999", &token)).await; + assert_eq!(status, 404); + assert!(html.contains(crate::i18n::board::t( + Lang::En, + crate::i18n::board::K::TaskNotFound + ))); + } +} diff --git a/crates/iz-web/src/pages/tasks.rs b/crates/iz-web/src/pages/tasks.rs index 4278967..3e81699 100644 --- a/crates/iz-web/src/pages/tasks.rs +++ b/crates/iz-web/src/pages/tasks.rs @@ -40,7 +40,7 @@ use crate::pages::board::{NewForm, load, query_of, render, the_board}; use crate::state::AppState; /// A refused write: the status, the code a client reads, and the message a person reads. -struct Refused { +pub(crate) struct Refused { status: StatusCode, code: &'static str, message: K, @@ -56,7 +56,7 @@ fn refused(status: u16, code: &'static str, message: K) -> Refused { } /// Why the gate of a write stopped it before any change. -enum Stop { +pub(crate) enum Stop { /// No session: the browser goes to sign-in, a `fetch` gets `401`. Anonymous, /// The member may not write, or the token is wrong (`403`), or the member has no access (`404`). @@ -156,7 +156,7 @@ fn parse_position(text: &str) -> StdResult, ()> { /// The gate of every write: the member with the write level, and the CSRF token. The level is checked /// first, so a viewer gets `403` whatever token they send. -async fn writer(cx: &Cx, csrf: &str) -> StdResult { +pub(crate) async fn writer(cx: &Cx, csrf: &str) -> StdResult { match require_csrf(cx, Need::Member, csrf).await { Ok(me) => Ok(me), Err(error) if error.downcast_ref::().is_some() => { @@ -172,7 +172,7 @@ async fn writer(cx: &Cx, csrf: &str) -> StdResult { /// Answers a gate stop: sign-in for the anonymous, the refusal for the rest. Gate refusals are always /// `403` or `404`, so they never need the board page. -async fn answer_stop( +pub(crate) async fn answer_stop( cx: &Cx, stop: Stop, json: bool, diff --git a/crates/iz-web/src/views/board.rs b/crates/iz-web/src/views/board.rs index e862a70..3c38a0b 100644 --- a/crates/iz-web/src/views/board.rs +++ b/crates/iz-web/src/views/board.rs @@ -15,6 +15,7 @@ use topcoat::view::{View, component, view}; use crate::i18n::Lang; use crate::i18n::board::{K, column_title, subtasks, t}; use crate::pages::board::{BoardPage, Filters, NewForm, board_url}; +use crate::views::task::task_modal; use crate::views::{alert, notice}; /// Number of palette tones a project chip can take. @@ -36,7 +37,7 @@ pub fn tone(tags: &[Tag], tag_id: &str) -> usize { } /// The value of an attribute that is present only when `on`. -fn flag(on: bool) -> Option<&'static str> { +pub(crate) fn flag(on: bool) -> Option<&'static str> { on.then_some("") } @@ -100,6 +101,9 @@ pub async fn board_content(page: &BoardPage) -> Result { } + if let Some(modal) = page.modal.as_ref() { + task_modal(page: page, modal: modal) + } }) } diff --git a/crates/iz-web/src/views/mod.rs b/crates/iz-web/src/views/mod.rs index ab89779..7a56bac 100644 --- a/crates/iz-web/src/views/mod.rs +++ b/crates/iz-web/src/views/mod.rs @@ -9,6 +9,7 @@ use topcoat::router::response::{IntoResponse, Response}; use topcoat::view::{Child, View, ViewExt, component, view}; pub mod board; +pub mod task; use crate::assets::{MAIN_CSS_HREF, NAV_JS_HREF, PAGES_JS_HREF}; use crate::i18n::Lang; diff --git a/crates/iz-web/src/views/task.rs b/crates/iz-web/src/views/task.rs new file mode 100644 index 0000000..293ed09 --- /dev/null +++ b/crates/iz-web/src/views/task.rs @@ -0,0 +1,627 @@ +//! The task modal's markup: the `` over the board, its sections, and the plain-text renderer for +//! descriptions and comments. +//! +//! Text from users is never markup. [`segments`] splits a text into lines, text runs and links; only +//! addresses that start with `http://` or `https://` become links, with `rel="noopener noreferrer +//! nofollow"`. Everything else is escaped by `view!`, so `` and `javascript:` addresses +//! reach the page as plain characters. +//! +//! Forms carry the CSRF token and the modal's own URL as `next`. A viewer gets the same sections with no +//! form, so the read-only view and the write view differ only in controls. + +use topcoat::Result; +use topcoat::view::{View, component, view}; + +use crate::i18n::task::{K, t}; +use crate::pages::board::BoardPage; +use crate::pages::task::{TaskModal, task_link}; +use crate::views::alert; +use crate::views::board::flag; + +/// One piece of a plain-text body: a run of text, a link, or a line break. +pub struct Segment { + /// The text of the run, or the address of the link. Empty for a line break. + pub text: String, + /// Whether this piece is an address that becomes a link. + pub link: bool, + /// Whether this piece is a line break. + pub brk: bool, +} + +/// The text run `text` as a segment. +fn run(text: &str) -> Segment { + Segment { + text: text.to_owned(), + link: false, + brk: false, + } +} + +/// The first `http://` or `https://` address in `text` that is longer than its scheme, as its byte range. +/// Trailing sentence punctuation and brackets are not part of the address; whitespace and `<>"'` end it. +fn next_link(text: &str) -> Option<(usize, usize)> { + let lower = text.to_ascii_lowercase(); + let mut from = 0; + loop { + let (offset, scheme) = ["http://", "https://"] + .iter() + .filter_map(|scheme| lower[from..].find(scheme).map(|at| (at, *scheme))) + .min_by_key(|(at, _)| *at)?; + let start = from + offset; + let tail = &text[start..]; + let length = tail + .find(|c: char| c.is_whitespace() || matches!(c, '<' | '>' | '"' | '\'' | '`')) + .unwrap_or(tail.len()); + let mut end = start + length; + while end > start + && text[..end] + .chars() + .last() + .is_some_and(|c| matches!(c, '.' | ',' | ';' | ':' | '!' | '?' | ')' | ']' | '}')) + { + end -= 1; + } + if end - start > scheme.len() { + return Some((start, end)); + } + from = start + scheme.len(); + } +} + +/// Splits a plain-text body into segments: each line, its runs of text and its links, with a line break +/// between lines. A carriage return before a line feed is dropped. +pub fn segments(text: &str) -> Vec { + let mut out = Vec::new(); + for (index, line) in text.split('\n').enumerate() { + if index > 0 { + out.push(Segment { + text: String::new(), + link: false, + brk: true, + }); + } + let mut rest = line.strip_suffix('\r').unwrap_or(line); + while let Some((start, end)) = next_link(rest) { + if start > 0 { + out.push(run(&rest[..start])); + } + out.push(Segment { + text: rest[start..end].to_owned(), + link: true, + brk: false, + }); + rest = &rest[end..]; + } + if !rest.is_empty() { + out.push(run(rest)); + } + } + out +} + +/// A plain-text body as markup: escaped text, line breaks, and links for http and https addresses only. +#[component] +pub async fn rich_text(text: &str) -> Result { + let pieces = segments(text); + Ok(view! { +
+ for piece in pieces.iter() { + if piece.brk { +
+ } + if piece.link { + (piece.text.as_str()) + } + if !piece.link && !piece.brk { + (piece.text.as_str()) + } + } +
+ }) +} + +/// The modal: the `` over the board. Escape and the close link return to the board with its +/// filters (`board.js` reads `data-close-href`). Without JavaScript the dialog is shown in place. +#[component] +pub async fn task_modal(page: &BoardPage, modal: &TaskModal) -> Result { + let lang = page.lang; + let task = &modal.detail.task; + let key = task.key.as_str(); + let close = modal.close.as_str(); + Ok(view! { + +
+

(key)

+ (t(lang, K::Close)) +
+ if let Some(message) = modal.error { + alert(message: message) + } +

(task.title.as_str())

+ task_details(page: page, modal: modal) + task_people(page: page, modal: modal) + task_structure(page: page, modal: modal) + task_links(page: page, modal: modal) + task_comments(page: page, modal: modal) + task_activity(page: page, modal: modal) + task_delete(page: page, modal: modal) +
+ }) +} + +/// The fields as read, and for a member the edit form folded under them. The form opens by itself after a +/// refusal, so the typed values stay in view. +#[component] +pub async fn task_details(page: &BoardPage, modal: &TaskModal) -> Result { + let lang = page.lang; + let task = &modal.detail.task; + let deadline = task.deadline.map(|day| day.to_string()).unwrap_or_default(); + let deadline = if deadline.is_empty() { + "-".to_owned() + } else { + deadline + }; + let time = if modal.edit.time.is_empty() { + "-".to_owned() + } else { + modal.edit.time.clone() + }; + let project = modal.detail.tag.name.as_str(); + let id = task.id.as_str(); + let edit_action = format!("/tasks/{id}/edit"); + let csrf = page.viewer.csrf.as_str(); + let next = modal.base.as_str(); + let edit = &modal.edit; + Ok(view! { +
+
+
(t(lang, K::Project))
+
(project)
+
(t(lang, K::Deadline))
+
(deadline.as_str())
+
(t(lang, K::Meeting))
+
(time.as_str())
+
+ rich_text(text: task.description.as_str()) + if modal.can_write { +
+ (t(lang, K::EditComment)) +
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +

(t(lang, K::MeetingHint))

+
+
+ + +

(t(lang, K::DescriptionHint))

+
+
+ +
+
+ } +
+ }) +} + +/// The assignees, with a remove control each, the picker for a new one, and the watch switch. +#[component] +pub async fn task_people(page: &BoardPage, modal: &TaskModal) -> Result { + let lang = page.lang; + let id = modal.detail.task.id.as_str(); + let csrf = page.viewer.csrf.as_str(); + let next = modal.base.as_str(); + let assign_action = format!("/tasks/{id}/assign"); + let unassign_action = format!("/tasks/{id}/unassign"); + let watch_action = format!("/tasks/{id}/watch"); + let watch_on = if modal.watching { "0" } else { "1" }; + let watch_label = if modal.watching { + t(lang, K::Unwatch) + } else { + t(lang, K::Watch) + }; + let watch_text = if modal.watching { + t(lang, K::Watching) + } else { + t(lang, K::NotWatching) + }; + let assignees: Vec<(String, String)> = modal + .detail + .assignees + .iter() + .map(|a| (a.sub.clone(), a.name.clone())) + .collect(); + let picks: Vec<(String, String)> = modal + .assignable + .iter() + .map(|member| (member.sub.clone(), member.name.clone())) + .collect(); + Ok(view! { +
+

(t(lang, K::Assignees))

+ if assignees.is_empty() { +

(t(lang, K::NobodyAssigned))

+ } +
    + for (sub, name) in assignees.iter() { +
  • + (name.as_str()) + if modal.can_write { +
    + + + + +
    + } +
  • + } +
+ if modal.can_write && !picks.is_empty() { +
+ + +
+ + +
+ +
+ } +

(watch_text)

+ if modal.can_write { +
+ + + + +
+ } +
+ }) +} + +/// The subtasks, the form that adds one, and the parent picker. +#[component] +pub async fn task_structure(page: &BoardPage, modal: &TaskModal) -> Result { + let lang = page.lang; + let task = &modal.detail.task; + let id = task.id.as_str(); + let csrf = page.viewer.csrf.as_str(); + let next = modal.base.as_str(); + let subtask_action = format!("/tasks/{id}/subtasks"); + let parent_action = format!("/tasks/{id}/parent"); + let subtasks: Vec<(String, String)> = modal + .detail + .subtasks + .iter() + .map(|sub| { + ( + task_link(&modal.close, &sub.key), + format!("{} {}", sub.key, sub.title), + ) + }) + .collect(); + let parent_id = task.parent_id.clone().unwrap_or_default(); + let parents: Vec<(String, String, bool)> = modal + .options + .iter() + .filter(|other| other.parent_id.is_none()) + .map(|other| { + ( + other.id.clone(), + format!("{} {}", other.key, other.title), + other.id == parent_id, + ) + }) + .collect(); + let title_max = iz_core::limits::TITLE_MAX.to_string(); + Ok(view! { +
+

(t(lang, K::Subtasks))

+ if subtasks.is_empty() { +

(t(lang, K::NoSubtasks))

+ } + + if modal.can_write && task.parent_id.is_none() { +
+ + +
+ + +
+ +
+ } + if modal.can_write { +
+ + +
+ + +
+ +
+ } +
+ }) +} + +/// The dependencies in both directions, each with a remove control, and the form that adds one. +#[component] +pub async fn task_links(page: &BoardPage, modal: &TaskModal) -> Result { + let lang = page.lang; + let id = modal.detail.task.id.as_str(); + let csrf = page.viewer.csrf.as_str(); + let next = modal.base.as_str(); + let remove_action = format!("/tasks/{id}/links/remove"); + let add_action = format!("/tasks/{id}/links"); + let waits: Vec<(String, String, String)> = modal + .detail + .blocked_by + .iter() + .map(|other| { + ( + other.id.clone(), + task_link(&modal.close, &other.key), + format!("{} {}", other.key, other.title), + ) + }) + .collect(); + let blocks: Vec<(String, String, String)> = modal + .detail + .blocks + .iter() + .map(|other| { + ( + other.id.clone(), + task_link(&modal.close, &other.key), + format!("{} {}", other.key, other.title), + ) + }) + .collect(); + let options: Vec<(String, String)> = modal + .options + .iter() + .map(|other| (other.id.clone(), format!("{} {}", other.key, other.title))) + .collect(); + let nothing = waits.is_empty() && blocks.is_empty(); + Ok(view! { +
+

(t(lang, K::Dependencies))

+ if nothing { +

(t(lang, K::NoLinks))

+ } + if !waits.is_empty() { +

(t(lang, K::BlockedBy))

+
    + for (other_id, link, label) in waits.iter() { +
  • + (label.as_str()) + if modal.can_write { +
    + + + + + +
    + } +
  • + } +
+ } + if !blocks.is_empty() { +

(t(lang, K::Blocks))

+
    + for (other_id, link, label) in blocks.iter() { +
  • + (label.as_str()) + if modal.can_write { +
    + + + + + +
    + } +
  • + } +
+ } + if modal.can_write && !options.is_empty() { +
+ + +
+ + +
+
+ + +
+ +
+ } +
+ }) +} + +/// The comments, oldest first, with edit and delete for the ones the viewer may change, and the composer. +#[component] +pub async fn task_comments(page: &BoardPage, modal: &TaskModal) -> Result { + let lang = page.lang; + let id = modal.detail.task.id.as_str(); + let csrf = page.viewer.csrf.as_str(); + let next = modal.base.as_str(); + let comment_action = format!("/tasks/{id}/comments"); + let actions: Vec<(String, String)> = modal + .comments + .iter() + .map(|c| { + ( + format!("/comments/{}/edit", c.id), + format!("/comments/{}/delete", c.id), + ) + }) + .collect(); + let limit = iz_core::limits::COMMENT_MAX.to_string(); + Ok(view! { +
+

(t(lang, K::Comments))

+ if modal.comments.is_empty() { +

(t(lang, K::NoComments))

+ } +
    + for (c, (edit_action, delete_action)) in modal.comments.iter().zip(actions.iter()) { +
  1. +

    + (c.author.as_str()) + " " + + if c.edited { + " " + (t(lang, K::Edited)) + } +

    + rich_text(text: c.body.as_str()) + if c.can_edit { +
    + (t(lang, K::EditComment)) +
    + + + + +
    +
    + } + if c.can_delete { +
    + + + +
    + } +
  2. + } +
+ if modal.can_write { +
+ + +
+ + +
+ +
+ } +
+ }) +} + +/// The activity feed, newest first, with the link to the next older page. +#[component] +pub async fn task_activity(page: &BoardPage, modal: &TaskModal) -> Result { + let lang = page.lang; + Ok(view! { +
+

(t(lang, K::Activity))

+ if modal.activity.is_empty() { +

(t(lang, K::NoActivity))

+ } +
    + for row in modal.activity.iter() { +
  • + + " " + (row.actor.as_str()) + " " + (row.sentence) +
  • + } +
+ if let Some(older) = modal.older.as_ref() { +

(t(lang, K::Older))

+ } +
+ }) +} + +/// Deleting the task. The first step is a link to `?confirm=delete`; the confirmation form posts the +/// delete and returns to the board, without the task. +#[component] +pub async fn task_delete(page: &BoardPage, modal: &TaskModal) -> Result { + let lang = page.lang; + let id = modal.detail.task.id.as_str(); + let csrf = page.viewer.csrf.as_str(); + let delete_action = format!("/tasks/{id}/delete"); + let confirm_url = format!("{}&confirm=delete", modal.base); + let close = modal.close.as_str(); + Ok(view! { + if modal.can_write { +
+ if modal.confirm_delete { +
+

(t(lang, K::DeleteQuestion))

+

(t(lang, K::DeleteConsequence))

+
+ + + + (t(lang, K::Close)) +
+
+ } else { + (t(lang, K::DeleteTask)) + } +
+ } + }) +} diff --git a/style/_task.scss b/style/_task.scss new file mode 100644 index 0000000..d28a16e --- /dev/null +++ b/style/_task.scss @@ -0,0 +1,144 @@ +//! The task modal: a panel over the board that holds the task's fields, people, structure, dependencies, +//! comments and activity. Without JavaScript the dialog is shown in place, so the panel rules also apply +//! to a plain ``. + +.task-dialog { + position: fixed; + inset: 0 0 0 auto; + z-index: 20; + width: min(44rem, 100vw); + max-width: 100vw; + height: 100dvh; + max-height: 100dvh; + margin: 0; + padding: 1.25rem 1.5rem 3rem; + overflow-y: auto; + border: 0; + border-left: 1px solid var(--border); + background: var(--surface); + color: var(--text); + box-shadow: -8px 0 24px rgb(0 0 0 / 0.12); +} + +.task-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.75rem; +} + +.task-key { + margin: 0; + font-family: ui-monospace, monospace; + color: var(--muted); +} + +.task-title { + margin: 0.5rem 0 0.75rem; + overflow-wrap: anywhere; +} + +.task-section { + padding-block: 1rem; + border-top: 1px solid var(--border); + + h3 { + margin: 0 0 0.5rem; + font-size: 1rem; + } + + h4 { + margin: 0.75rem 0 0.25rem; + font-size: 0.9rem; + color: var(--muted); + } +} + +.task-facts { + display: grid; + grid-template-columns: max-content 1fr; + gap: 0.25rem 1rem; + margin: 0 0 0.75rem; + + dt { + color: var(--muted); + } + + dd { + margin: 0; + } +} + +.task-list, +.comment-list, +.activity-list { + margin: 0; + padding: 0; + list-style: none; +} + +.task-row { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 0.5rem; + padding-block: 0.25rem; + overflow-wrap: anywhere; +} + +.task-inline { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + gap: 0.5rem; + margin-block: 0.5rem; +} + +.task-form { + margin-block: 0.5rem; +} + +.task-edit { + margin-top: 0.75rem; + + summary { + cursor: pointer; + color: var(--accent); + } +} + +.rich-text { + overflow-wrap: anywhere; + white-space: normal; + line-height: 1.5; + + a { + color: var(--accent); + } +} + +.comment { + padding-block: 0.5rem; + border-top: 1px solid var(--border); +} + +.comment-meta { + margin: 0 0 0.25rem; + font-size: 0.85rem; + color: var(--muted); +} + +.comment-edit { + margin-top: 0.25rem; +} + +.activity-list li { + padding-block: 0.2rem; + font-size: 0.9rem; + overflow-wrap: anywhere; +} + +.task-confirm { + border-color: var(--danger); +} diff --git a/style/main.scss b/style/main.scss index 00a9ad7..50f448d 100644 --- a/style/main.scss +++ b/style/main.scss @@ -7,3 +7,4 @@ @use "layout"; @use "components"; @use "board"; +@use "task";