From 62a58515f825daea2c937306fd5d6627f23f464c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 20 Oct 2026 13:02:20 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix:=20autocomplete=20reopen=20a?= =?UTF-8?q?fter=20choose,=20drop=20dead=20i18n=20keys,=20clippy=20arg-coun?= =?UTF-8?q?t=20allow?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Includes: ✨ feat: attachments, @ and # autocomplete, task lists, review requests, math in markdown --- .../migrations/0055_attachments.sql | 15 + .../migrations/0056_review_requests.sql | 11 + crates/forge-core/src/issues.rs | 3 + crates/forge-core/src/store/attachments.rs | 127 +++++ crates/forge-core/src/store/issues.rs | 7 + crates/forge-core/src/store/migrate.rs | 5 + crates/forge-core/src/store/mod.rs | 3 + .../forge-core/src/store/review_requests.rs | 179 +++++++ crates/forge-core/src/store/reviews.rs | 7 + crates/forge-core/src/store/suggest.rs | 156 ++++++ crates/forge-core/src/store/user_delete.rs | 8 + crates/forge-web/assets/nav.js | 310 ++++++++++++ crates/forge-web/src/blobs.rs | 5 + crates/forge-web/src/i18n/authoring.rs | 75 +++ crates/forge-web/src/i18n/mod.rs | 5 + crates/forge-web/src/mail/templates.rs | 2 + crates/forge-web/src/notify.rs | 43 +- crates/forge-web/src/pages/authoring.rs | 406 +++++++++++++++ crates/forge-web/src/pages/authoring_tests.rs | 477 ++++++++++++++++++ crates/forge-web/src/pages/issue_parts.rs | 27 +- crates/forge-web/src/pages/issues_list.rs | 75 ++- crates/forge-web/src/pages/mod.rs | 4 + crates/forge-web/src/pages/notifications.rs | 1 + crates/forge-web/src/pages/pull_view.rs | 3 + crates/forge-web/src/pages/pulls_list.rs | 30 +- crates/forge-web/src/pages/review_requests.rs | 270 ++++++++++ crates/forge-web/src/render/markdown.rs | 79 ++- style/_authoring.scss | 122 +++++ style/main.scss | 4 + 29 files changed, 2434 insertions(+), 25 deletions(-) create mode 100644 crates/forge-core/migrations/0055_attachments.sql create mode 100644 crates/forge-core/migrations/0056_review_requests.sql create mode 100644 crates/forge-core/src/store/attachments.rs create mode 100644 crates/forge-core/src/store/review_requests.rs create mode 100644 crates/forge-core/src/store/suggest.rs create mode 100644 crates/forge-web/src/i18n/authoring.rs create mode 100644 crates/forge-web/src/pages/authoring.rs create mode 100644 crates/forge-web/src/pages/authoring_tests.rs create mode 100644 crates/forge-web/src/pages/review_requests.rs create mode 100644 style/_authoring.scss diff --git a/crates/forge-core/migrations/0055_attachments.sql b/crates/forge-core/migrations/0055_attachments.sql new file mode 100644 index 0000000..f516ed0 --- /dev/null +++ b/crates/forge-core/migrations/0055_attachments.sql @@ -0,0 +1,15 @@ +-- Files attached to issues, pull requests, comments and discussions through the markdown +-- editors. The bytes live in blob storage under `attachments/`; this row is the metadata +-- and the repo link that access checks use. Applied by store/migrate.rs. + +CREATE TABLE attachments ( + id TEXT PRIMARY KEY, + repo_id TEXT NOT NULL REFERENCES repos(id) ON DELETE CASCADE, + uploader_id TEXT NOT NULL REFERENCES users(id), + name TEXT NOT NULL, + content_type TEXT NOT NULL, + size INTEGER NOT NULL, + sha256 TEXT NOT NULL, + created_at TEXT NOT NULL +); +CREATE INDEX attachments_repo ON attachments(repo_id); diff --git a/crates/forge-core/migrations/0056_review_requests.sql b/crates/forge-core/migrations/0056_review_requests.sql new file mode 100644 index 0000000..c6f094b --- /dev/null +++ b/crates/forge-core/migrations/0056_review_requests.sql @@ -0,0 +1,11 @@ +-- Reviewers requested on a pull request. A row is removed when the reviewer submits a review or +-- the request is withdrawn. Applied by store/migrate.rs. + +CREATE TABLE review_requests ( + issue_id TEXT NOT NULL REFERENCES issues(id) ON DELETE CASCADE, + reviewer_id TEXT NOT NULL REFERENCES users(id), + requested_by TEXT NOT NULL REFERENCES users(id), + created_at TEXT NOT NULL, + PRIMARY KEY (issue_id, reviewer_id) +); +CREATE INDEX review_requests_reviewer ON review_requests(reviewer_id); diff --git a/crates/forge-core/src/issues.rs b/crates/forge-core/src/issues.rs index cf237a5..0eba672 100644 --- a/crates/forge-core/src/issues.rs +++ b/crates/forge-core/src/issues.rs @@ -150,6 +150,8 @@ pub struct IssueFilter { pub author: Option, /// Assignee username. pub assignee: Option, + /// Username with a pending review request (pull requests only). + pub review_requested: Option, /// Substring of the title, case-insensitive. pub query: Option, /// Pull requests only: `Some(true)` lists drafts, `Some(false)` lists ready pull requests. @@ -168,6 +170,7 @@ impl Default for IssueFilter { milestone: None, author: None, assignee: None, + review_requested: None, query: None, draft: None, sort: IssueSort::Newest, diff --git a/crates/forge-core/src/store/attachments.rs b/crates/forge-core/src/store/attachments.rs new file mode 100644 index 0000000..13a5e60 --- /dev/null +++ b/crates/forge-core/src/store/attachments.rs @@ -0,0 +1,127 @@ +//! Metadata of files attached through the markdown editors. The bytes are in blob storage under +//! `attachments/`; a row ties the file to the repo it was uploaded in, which is what the +//! download access check follows (a file is as visible as its repo). + +use serde::Serialize; + +use super::{Store, col_int, col_text, db_err, fetch_opt}; +use crate::error::Result; +use crate::time::now_stamp; + +/// One stored attachment. +#[derive(Debug, Clone, Serialize)] +pub struct Attachment { + pub id: String, + pub repo_id: String, + pub uploader_id: String, + pub name: String, + pub content_type: String, + pub size: u64, + pub sha256: String, + pub created_at: String, +} + +impl Store { + /// Records an attachment whose blob is already stored under `id`. + #[allow(clippy::too_many_arguments)] + pub async fn add_attachment( + &self, + id: &str, + repo_id: &str, + uploader_id: &str, + name: &str, + content_type: &str, + size: u64, + sha256: &str, + ) -> Result { + let created_at = now_stamp(); + let conn = self.inner.conn.lock().await; + conn.execute( + "INSERT INTO attachments (id, repo_id, uploader_id, name, content_type, size, sha256, created_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", + ( + id.to_string(), + repo_id.to_string(), + uploader_id.to_string(), + name.to_string(), + content_type.to_string(), + i64::try_from(size).unwrap_or(i64::MAX), + sha256.to_string(), + created_at.clone(), + ), + ) + .await + .map_err(db_err)?; + Ok(Attachment { + id: id.to_string(), + repo_id: repo_id.to_string(), + uploader_id: uploader_id.to_string(), + name: name.to_string(), + content_type: content_type.to_string(), + size, + sha256: sha256.to_string(), + created_at, + }) + } + + /// The attachment `id`, if any. The caller checks the viewer can read `repo_id`. + pub async fn attachment(&self, id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + "SELECT id, repo_id, uploader_id, name, content_type, size, sha256, created_at \ + FROM attachments WHERE id = ?1", + (id.to_string(),), + |row| { + Ok(Attachment { + id: col_text(row, 0)?, + repo_id: col_text(row, 1)?, + uploader_id: col_text(row, 2)?, + name: col_text(row, 3)?, + content_type: col_text(row, 4)?, + size: u64::try_from(col_int(row, 5)?).unwrap_or(0), + sha256: col_text(row, 6)?, + created_at: col_text(row, 7)?, + }) + }, + ) + .await + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::Visibility; + + #[tokio::test] + async fn attachment_round_trips() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); + let tahinli = store + .create_user("tahinli", None, "hash", false) + .await + .unwrap(); + let a = store + .create_repo(&tahinli.id, "a", "", Visibility::Public, "main") + .await + .unwrap(); + store + .add_attachment( + "att1", + &a.id, + &tahinli.id, + "shot.png", + "image/png", + 12, + "abc", + ) + .await + .unwrap(); + let found = store.attachment("att1").await.unwrap().unwrap(); + assert_eq!(found.repo_id, a.id); + assert_eq!(found.name, "shot.png"); + assert_eq!(found.size, 12); + assert!(store.attachment("nope").await.unwrap().is_none()); + } +} diff --git a/crates/forge-core/src/store/issues.rs b/crates/forge-core/src/store/issues.rs index 5881890..e2ebaf8 100644 --- a/crates/forge-core/src/store/issues.rs +++ b/crates/forge-core/src/store/issues.rs @@ -393,6 +393,13 @@ impl Store { ); params.push(Value::Text(normalize_name(assignee))); } + if let Some(reviewer) = non_empty(f.review_requested.as_deref()) { + clauses.push( + "EXISTS (SELECT 1 FROM review_requests rr JOIN users ur ON ur.id = rr.reviewer_id \ + WHERE rr.issue_id = i.id AND ur.username_folded = ?)", + ); + params.push(Value::Text(normalize_name(reviewer))); + } if let Some(query) = non_empty(f.query.as_deref()) { // Escape the LIKE wildcards and the escape character itself. clauses.push("i.title LIKE ? ESCAPE '\\'"); diff --git a/crates/forge-core/src/store/migrate.rs b/crates/forge-core/src/store/migrate.rs index 8ce50bc..6b10137 100644 --- a/crates/forge-core/src/store/migrate.rs +++ b/crates/forge-core/src/store/migrate.rs @@ -82,6 +82,11 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ ), (50, include_str!("../../migrations/0050_imports.sql")), (51, include_str!("../../migrations/0051_data_exports.sql")), + (55, include_str!("../../migrations/0055_attachments.sql")), + ( + 56, + include_str!("../../migrations/0056_review_requests.sql"), + ), ]; /// The highest migration version this binary knows about. diff --git a/crates/forge-core/src/store/mod.rs b/crates/forge-core/src/store/mod.rs index 550de8c..7cc9915 100644 --- a/crates/forge-core/src/store/mod.rs +++ b/crates/forge-core/src/store/mod.rs @@ -2,6 +2,7 @@ pub mod account_tokens; pub mod advisories; +pub mod attachments; pub mod audit; pub mod backup_runs; pub mod ci; @@ -29,11 +30,13 @@ pub mod reactions; pub mod releases; pub mod replication; pub mod repo_listing; +pub mod review_requests; pub mod reviews; pub mod server_settings; pub mod signatures; pub mod snapshot; pub mod snippets; +pub mod suggest; pub mod transfers; pub mod ui_prefs; pub mod user_delete; diff --git a/crates/forge-core/src/store/review_requests.rs b/crates/forge-core/src/store/review_requests.rs new file mode 100644 index 0000000..7d5f284 --- /dev/null +++ b/crates/forge-core/src/store/review_requests.rs @@ -0,0 +1,179 @@ +//! Review requests on pull requests: who was asked to review, by whom. A request is cleared when +//! the reviewer submits a review (`submit_review` does it in the same transaction) or when it is +//! withdrawn. Deleting a pull request removes its requests through the foreign key. + +use std::collections::HashMap; + +use super::{Store, col_text, db_err, fetch_all, fetch_opt}; +use crate::error::Result; +use crate::time::now_stamp; + +/// A pending request as the global "Review requests" view lists it. +#[derive(Debug, Clone)] +pub struct ReviewRequestItem { + pub repo_owner: String, + pub repo_name: String, + pub number: i64, + pub title: String, + pub requested_by: String, + pub created_at: String, +} + +impl Store { + /// Asks `reviewer_id` to review. Returns `false` when a request is already pending. + pub async fn request_review( + &self, + issue_id: &str, + reviewer_id: &str, + requested_by: &str, + ) -> Result { + let conn = self.inner.conn.lock().await; + let exists = fetch_opt( + &conn, + "SELECT 1 FROM review_requests WHERE issue_id = ?1 AND reviewer_id = ?2", + (issue_id.to_string(), reviewer_id.to_string()), + |row| col_text(row, 0).or(Ok(String::new())), + ) + .await?; + if exists.is_some() { + return Ok(false); + } + conn.execute( + "INSERT INTO review_requests (issue_id, reviewer_id, requested_by, created_at) \ + VALUES (?1, ?2, ?3, ?4)", + ( + issue_id.to_string(), + reviewer_id.to_string(), + requested_by.to_string(), + now_stamp(), + ), + ) + .await + .map_err(db_err)?; + Ok(true) + } + + /// Withdraws a pending request. Returns whether there was one. + pub async fn withdraw_review_request(&self, issue_id: &str, reviewer_id: &str) -> Result { + let conn = self.inner.conn.lock().await; + let n = conn + .execute( + "DELETE FROM review_requests WHERE issue_id = ?1 AND reviewer_id = ?2", + (issue_id.to_string(), reviewer_id.to_string()), + ) + .await + .map_err(db_err)?; + Ok(n > 0) + } + + /// Usernames with a pending request on the pull request, oldest request first. + pub async fn requested_reviewers(&self, issue_id: &str) -> Result> { + let mut map = self + .requested_reviewers_for(std::slice::from_ref(&issue_id.to_string())) + .await?; + Ok(map.remove(issue_id).unwrap_or_default()) + } + + /// Pending reviewer usernames for each of `ids`, in one query. Pulls without requests have + /// no entry. + pub async fn requested_reviewers_for( + &self, + ids: &[String], + ) -> Result>> { + let mut out: HashMap> = HashMap::new(); + if ids.is_empty() { + return Ok(out); + } + let conn = self.read_conn().await; + for chunk in ids.chunks(500) { + let marks = vec!["?"; chunk.len()].join(","); + let rows = fetch_all( + &conn, + &format!( + "SELECT rr.issue_id, u.username FROM review_requests rr \ + JOIN users u ON u.id = rr.reviewer_id \ + WHERE rr.issue_id IN ({marks}) ORDER BY rr.created_at, u.username_folded" + ), + chunk.to_vec(), + |row| Ok((col_text(row, 0)?, col_text(row, 1)?)), + ) + .await?; + for (issue, name) in rows { + out.entry(issue).or_default().push(name); + } + } + Ok(out) + } + + /// Open pull requests where the user has a pending request, newest request first. + pub async fn review_requests_for_user(&self, user_id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + "SELECT o.username, r.name, i.number, i.title, b.username, rr.created_at \ + FROM review_requests rr \ + JOIN issues i ON i.id = rr.issue_id AND i.state = 'open' AND i.kind = 'pull' \ + JOIN repos r ON r.id = i.repo_id \ + JOIN users o ON o.id = r.owner_id \ + JOIN users b ON b.id = rr.requested_by \ + WHERE rr.reviewer_id = ?1 ORDER BY rr.created_at DESC LIMIT 200", + (user_id.to_string(),), + |row| { + Ok(ReviewRequestItem { + repo_owner: col_text(row, 0)?, + repo_name: col_text(row, 1)?, + number: super::col_int(row, 2)?, + title: col_text(row, 3)?, + requested_by: col_text(row, 4)?, + created_at: col_text(row, 5)?, + }) + }, + ) + .await + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::Visibility; + + #[tokio::test] + async fn request_withdraw_and_list() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); + let tahinli = store + .create_user("tahinli", None, "hash", false) + .await + .unwrap(); + let bob = store.create_user("bob", None, "hash", false).await.unwrap(); + let repo = store + .create_repo(&tahinli.id, "proj", "", Visibility::Public, "main") + .await + .unwrap(); + let pr = store + .create_issue(&repo.id, &tahinli.id, "pr", "") + .await + .unwrap(); + assert!( + store + .request_review(&pr.id, &bob.id, &tahinli.id) + .await + .unwrap() + ); + assert!( + !store + .request_review(&pr.id, &bob.id, &tahinli.id) + .await + .unwrap() + ); + assert_eq!(store.requested_reviewers(&pr.id).await.unwrap(), ["bob"]); + assert!( + store + .withdraw_review_request(&pr.id, &bob.id) + .await + .unwrap() + ); + assert!(store.requested_reviewers(&pr.id).await.unwrap().is_empty()); + } +} diff --git a/crates/forge-core/src/store/reviews.rs b/crates/forge-core/src/store/reviews.rs index 6a89d5f..7887bd6 100644 --- a/crates/forge-core/src/store/reviews.rs +++ b/crates/forge-core/src/store/reviews.rs @@ -487,6 +487,13 @@ impl Store { insert_review(&tx, issue_id, author_id, state, body, head_oid, &now).await? } }; + // A submitted review answers the author's own review request. + tx.execute( + "DELETE FROM review_requests WHERE issue_id = ?1 AND reviewer_id = ?2", + (issue_id.to_string(), author_id.to_string()), + ) + .await + .map_err(db_err)?; review_by_id(&tx, &id).await?.ok_or_else(missing_row) } .await; diff --git a/crates/forge-core/src/store/suggest.rs b/crates/forge-core/src/store/suggest.rs new file mode 100644 index 0000000..eebd968 --- /dev/null +++ b/crates/forge-core/src/store/suggest.rs @@ -0,0 +1,156 @@ +//! Lookups behind the `@` and `#` autocomplete of the markdown editors. + +use turso::Value; + +use super::issues::like_pattern; +use super::{Store, col_int, col_text, fetch_all}; +use crate::error::Result; +use crate::names::normalize_name; + +/// One `#` suggestion: an issue or pull request. +#[derive(Debug, Clone)] +pub struct IssueSuggestion { + pub number: i64, + pub title: String, + pub is_pull: bool, + pub open: bool, +} + +impl Store { + /// Usernames starting with `prefix` (case-insensitive) that are people in the repo, nearest + /// first: the owner and collaborators, then anyone who opened an issue or commented, then + /// every other person account. At most `limit` names, no duplicates. + pub async fn suggest_usernames( + &self, + repo_id: &str, + prefix: &str, + limit: usize, + ) -> Result> { + let pattern = { + let mut p = like_pattern(&normalize_name(prefix)); + p.remove(0); + p + }; + // `like_pattern` wraps in `%..%`; for a prefix match drop the leading one (done above). + let cap = Value::Integer(i64::try_from(limit).unwrap_or(8)); + let queries = [ + // Owner and collaborators. + "SELECT u.username FROM users u WHERE u.username_folded LIKE ?2 ESCAPE '\\' AND u.kind = 'user' AND \ + (u.id = (SELECT owner_id FROM repos WHERE id = ?1) OR \ + u.id IN (SELECT user_id FROM collaborators WHERE repo_id = ?1)) \ + ORDER BY u.username_folded LIMIT ?3", + // Participants. + "SELECT u.username FROM users u WHERE u.username_folded LIKE ?2 ESCAPE '\\' AND u.kind = 'user' AND \ + (u.id IN (SELECT author_id FROM issues WHERE repo_id = ?1) OR \ + u.id IN (SELECT c.author_id FROM comments c JOIN issues i ON i.id = c.issue_id WHERE i.repo_id = ?1)) \ + ORDER BY u.username_folded LIMIT ?3", + // Everyone else. + "SELECT u.username FROM users u WHERE u.username_folded LIKE ?2 ESCAPE '\\' AND u.kind = 'user' \ + AND u.username_folded <> 'ghost' ORDER BY u.username_folded LIMIT ?3", + ]; + let conn = self.read_conn().await; + let mut out: Vec = Vec::new(); + for sql in queries { + let names = fetch_all( + &conn, + sql, + vec![ + Value::Text(repo_id.to_string()), + Value::Text(pattern.clone()), + cap.clone(), + ], + |row| col_text(row, 0), + ) + .await?; + for name in names { + if out.len() < limit && !out.contains(&name) { + out.push(name); + } + } + } + Ok(out) + } + + /// Issues and pull requests of the repo whose number starts with `q` (when it is digits) or + /// whose title contains it. Newest first, at most `limit`. + pub async fn suggest_issues( + &self, + repo_id: &str, + q: &str, + limit: u32, + ) -> Result> { + let q = q.trim(); + let (clause, param) = if !q.is_empty() && q.bytes().all(|b| b.is_ascii_digit()) { + ("CAST(i.number AS TEXT) LIKE ? ESCAPE '\\'", format!("{q}%")) + } else { + ("i.title LIKE ? ESCAPE '\\'", like_pattern(q)) + }; + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!( + "SELECT i.number, i.title, i.kind, i.state FROM issues i \ + WHERE i.repo_id = ? AND {clause} ORDER BY i.number DESC LIMIT ?" + ), + vec![ + Value::Text(repo_id.to_string()), + Value::Text(param), + Value::Integer(i64::from(limit.clamp(1, 20))), + ], + |row| { + Ok(IssueSuggestion { + number: col_int(row, 0)?, + title: col_text(row, 1)?, + is_pull: col_text(row, 2)? == "pull", + open: col_text(row, 3)? == "open", + }) + }, + ) + .await + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::Visibility; + + #[tokio::test] + async fn users_and_issues_are_suggested() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); + let tahinli = store + .create_user("tahinli", None, "hash", false) + .await + .unwrap(); + let tanya = store + .create_user("tanya", None, "hash", false) + .await + .unwrap(); + let _tam = store.create_user("tam", None, "hash", false).await.unwrap(); + let repo = store + .create_repo(&tahinli.id, "proj", "", Visibility::Public, "main") + .await + .unwrap(); + let issue = store + .create_issue(&repo.id, &tanya.id, "Fix the parser", "") + .await + .unwrap(); + store + .create_issue(&repo.id, &tahinli.id, "Docs", "") + .await + .unwrap(); + // Owner first, then participant, then the rest. + let names = store.suggest_usernames(&repo.id, "ta", 8).await.unwrap(); + assert_eq!(names, ["tahinli", "tanya", "tam"]); + assert_eq!( + store.suggest_usernames(&repo.id, "tan", 8).await.unwrap(), + ["tanya"] + ); + let by_title = store.suggest_issues(&repo.id, "parser", 8).await.unwrap(); + assert_eq!(by_title.len(), 1); + assert_eq!(by_title[0].number, issue.number); + let by_number = store.suggest_issues(&repo.id, "2", 8).await.unwrap(); + assert_eq!(by_number[0].title, "Docs"); + } +} diff --git a/crates/forge-core/src/store/user_delete.rs b/crates/forge-core/src/store/user_delete.rs index 9b22413..f625e6d 100644 --- a/crates/forge-core/src/store/user_delete.rs +++ b/crates/forge-core/src/store/user_delete.rs @@ -49,6 +49,13 @@ const NOT_DRAFT_EDIT: &str = " AND NOT (target_kind = 'review_comment' AND targe /// appended to the `WHERE column = ?1` clause. const REASSIGNED: &[(&str, &str, &str, &str)] = &[ ("issues", "issues", "author_id", ""), + ("attachments", "attachments", "uploader_id", ""), + ( + "review requests sent", + "review_requests", + "requested_by", + "", + ), ("comments", "comments", "author_id", ""), ("edits", "edit_history", "editor_id", NOT_DRAFT_EDIT), ("timeline events", "issue_events", "actor_id", ""), @@ -128,6 +135,7 @@ const REMOVED: &[(&str, &str, &str)] = &[ "user_id", ), ("reactions", "reactions", "user_id"), + ("review requests", "review_requests", "reviewer_id"), ]; /// What a deletion did, or would do: row counts per kind, in the order the lists above give. diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index 0b1318e..271f37d 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -1376,4 +1376,314 @@ // been updated (observer callbacks run after the swap function returns). new MutationObserver(function () { applyLines(true); }).observe(document.body, { childList: true }); applyLines(true); + +// Authoring helpers for markdown textareas: attach (button, paste, drop), `@` and `#` autocomplete, +// and clickable task lists. Everything is delegated or re-applied from a MutationObserver on the +// body, so it survives soft navigation swaps. Nothing polls. +(function () { + 'use strict'; + if (window.__forgeAuthoring) { return; } + window.__forgeAuthoring = true; + + var TR = (document.documentElement.getAttribute('lang') || '').indexOf('tr') === 0; + var T = TR + ? { attach: 'Ekle', title: 'Görsel veya dosya ekle (yapıştırabilir veya bırakabilirsiniz)', up: 'Yükleniyor', fail: 'Yükleme başarısız', taskFail: 'Görev kaydedilemedi' } + : { attach: 'Attach', title: 'Attach an image or file (you can also paste or drop it)', up: 'Uploading', fail: 'Upload failed', taskFail: 'Could not save the task' }; + + // Repo pages whose textareas take markdown. `/owner/repo/section/...` + var REPO_PATH = /^\/([^\/]+)\/([^\/]+)\/(issues|pulls|discussions|wiki|compare|releases)(\/|$)/; + var NAMES = { body: 1, content: 1, message: 1 }; + + function repoBase() { + var m = REPO_PATH.exec(location.pathname); + return m ? '/' + m[1] + '/' + m[2] : null; + } + + function eligible(el) { + return el && el.tagName === 'TEXTAREA' && NAMES[el.name] && !el.readOnly && !!repoBase() && !!csrfOf(el); + } + + function csrfOf(el) { + var f = el.form; + var c = f ? f.querySelector('input[name=csrf]') : null; + return c ? c.value : ''; + } + + // ---- toolbar and upload ---- + + function enhance() { + document.querySelectorAll('textarea').forEach(function (ta) { + if (ta.__md || !eligible(ta)) { return; } + ta.__md = true; + var bar = document.createElement('div'); + bar.className = 'md-tools'; + var btn = document.createElement('button'); + btn.type = 'button'; + btn.className = 'link-button md-attach'; + btn.textContent = T.attach; + btn.title = T.title; + var status = document.createElement('span'); + status.className = 'md-status muted small'; + status.setAttribute('role', 'status'); + var file = document.createElement('input'); + file.type = 'file'; + file.hidden = true; + file.multiple = true; + file.setAttribute('aria-hidden', 'true'); + file.tabIndex = -1; + var list = document.createElement('ul'); + list.className = 'md-suggest'; + list.setAttribute('role', 'listbox'); + list.hidden = true; + bar.appendChild(btn); + bar.appendChild(status); + bar.appendChild(file); + bar.appendChild(list); + ta.insertAdjacentElement('afterend', bar); + ta.__bar = bar; + btn.addEventListener('click', function () { file.click(); }); + file.addEventListener('change', function () { + Array.prototype.forEach.call(file.files, function (f) { upload(ta, f); }); + file.value = ''; + }); + }); + enableTasks(); + } + + function say(ta, text, bad) { + var s = ta.__bar && ta.__bar.querySelector('.md-status'); + if (!s) { return; } + s.textContent = text; + s.classList.toggle('md-status-bad', !!bad); + } + + function insertAtCaret(ta, text) { + var start = ta.selectionStart == null ? ta.value.length : ta.selectionStart; + var end = ta.selectionEnd == null ? start : ta.selectionEnd; + var before = ta.value.slice(0, start); + var lead = before && !/\n$/.test(before) ? '\n' : ''; + var ins = lead + text + '\n'; + ta.value = before + ins + ta.value.slice(end); + var pos = start + ins.length; + ta.setSelectionRange(pos, pos); + ta.dispatchEvent(new Event('input', { bubbles: true })); + ta.focus(); + } + + function upload(ta, file) { + var base = repoBase(); + if (!base) { return; } + var fd = new FormData(); + fd.append('csrf', csrfOf(ta)); + var name = file.name || 'image.png'; + fd.append('file', file, name); + say(ta, T.up + ' ' + name + '...'); + fetch(base + '/attachments', { method: 'POST', body: fd, headers: { accept: 'application/json' } }) + .then(function (r) { + return r.json().catch(function () { return {}; }).then(function (j) { return { ok: r.ok, j: j }; }); + }) + .then(function (res) { + if (!res.ok || !res.j.markdown) { throw new Error(res.j.error || T.fail); } + insertAtCaret(ta, res.j.markdown); + say(ta, ''); + }) + .catch(function (err) { say(ta, T.fail + ': ' + (err && err.message ? err.message : ''), true); }); + } + + document.addEventListener('paste', function (e) { + var ta = e.target; + if (!ta || !ta.__md || !e.clipboardData) { return; } + var files = Array.prototype.filter.call(e.clipboardData.files || [], function (f) { return f.size > 0; }); + if (!files.length) { return; } + e.preventDefault(); + files.forEach(function (f) { upload(ta, f); }); + }); + + document.addEventListener('dragover', function (e) { + var ta = e.target; + if (ta && ta.__md && e.dataTransfer && Array.prototype.indexOf.call(e.dataTransfer.types || [], 'Files') >= 0) { + e.preventDefault(); + ta.classList.add('md-drop'); + } + }); + document.addEventListener('dragleave', function (e) { + if (e.target && e.target.classList) { e.target.classList.remove('md-drop'); } + }); + document.addEventListener('drop', function (e) { + var ta = e.target; + if (!ta || !ta.__md || !e.dataTransfer || !e.dataTransfer.files.length) { return; } + e.preventDefault(); + ta.classList.remove('md-drop'); + Array.prototype.forEach.call(e.dataTransfer.files, function (f) { upload(ta, f); }); + }); + + // ---- autocomplete ---- + + var active = null; // { el, kind, items, index, from, to } + var reqId = 0; + + function closeSuggest() { + if (active && active.list) { active.list.hidden = true; active.list.replaceChildren(); } + active = null; + } + + // The trigger just before the caret: `@name` or `#12` at a word start. + function trigger(ta) { + var pos = ta.selectionStart; + if (pos == null) { return null; } + var before = ta.value.slice(0, pos); + var m = /(^|[\s(])([@#])([\w.\-]*)$/.exec(before); + if (!m) { return null; } + var q = m[3]; + return { kind: m[2] === '@' ? 'user' : 'issue', q: q, from: pos - q.length - 1, to: pos }; + } + + function render(state) { + var list = state.list; + list.replaceChildren(); + state.items.forEach(function (it, i) { + var li = document.createElement('li'); + li.setAttribute('role', 'option'); + li.className = i === state.index ? 'md-suggest-item active' : 'md-suggest-item'; + li.setAttribute('aria-selected', i === state.index ? 'true' : 'false'); + var strong = document.createElement('strong'); + var rest = document.createElement('span'); + rest.className = 'muted small'; + if (state.kind === 'user') { + strong.textContent = '@' + it.login; + rest.textContent = it.name || ''; + } else { + strong.textContent = '#' + it.number; + rest.textContent = it.title + (it.pull ? ' (PR)' : ''); + } + li.appendChild(strong); + li.appendChild(document.createTextNode(' ')); + li.appendChild(rest); + li.addEventListener('mousedown', function (ev) { ev.preventDefault(); choose(state, i); }); + list.appendChild(li); + }); + list.hidden = state.items.length === 0; + } + + function choose(state, i) { + var it = state.items[i]; + if (!it) { return; } + var el = state.el; + var text = state.kind === 'user' ? '@' + it.login + ' ' : '#' + it.number + ' '; + if (state.whole) { + el.value = it.login; + } else { + el.value = el.value.slice(0, state.from) + text + el.value.slice(state.to); + var pos = state.from + text.length; + el.setSelectionRange(pos, pos); + } + closeSuggest(); + el.__skip = true; // the input event below is ours: it must not reopen the list + el.dispatchEvent(new Event('input', { bubbles: true })); + el.focus(); + } + + function ask(el, kind, q, from, to, whole, list) { + var base = repoBase(); + if (!base) { return; } + var id = ++reqId; + fetch(base + '/suggest?kind=' + kind + '&q=' + encodeURIComponent(q), { headers: { accept: 'application/json' } }) + .then(function (r) { return r.ok ? r.json() : []; }) + .then(function (items) { + if (id !== reqId || document.activeElement !== el) { return; } + active = { el: el, kind: kind, items: items, index: 0, from: from, to: to, whole: whole, list: list }; + render(active); + }) + .catch(function () { closeSuggest(); }); + } + + document.addEventListener('input', function (e) { + var el = e.target; + if (!el) { return; } + if (el.__skip) { el.__skip = false; return; } + if (el.tagName === 'INPUT' && el.getAttribute('data-suggest') === 'user') { + if (!repoBase()) { return; } + if (!el.__list) { + var l = document.createElement('ul'); + l.className = 'md-suggest md-suggest-input'; + l.setAttribute('role', 'listbox'); + l.hidden = true; + el.insertAdjacentElement('afterend', l); + el.__list = l; + } + if (!el.value.trim()) { closeSuggest(); return; } + ask(el, 'user', el.value.trim().replace(/^@/, ''), 0, el.value.length, true, el.__list); + return; + } + if (!el.__md) { return; } + var t = trigger(el); + if (!t) { closeSuggest(); return; } + ask(el, t.kind, t.q, t.from, t.to, false, el.__bar.querySelector('.md-suggest')); + }); + + document.addEventListener('keydown', function (e) { + if (!active || e.target !== active.el || !active.items.length) { return; } + if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { + e.preventDefault(); + var n = active.items.length; + active.index = (active.index + (e.key === 'ArrowDown' ? 1 : n - 1)) % n; + render(active); + } else if (e.key === 'Enter' || e.key === 'Tab') { + e.preventDefault(); + choose(active, active.index); + } else if (e.key === 'Escape') { + e.preventDefault(); + closeSuggest(); + } + }); + + document.addEventListener('focusout', function (e) { + if (active && e.target === active.el) { closeSuggest(); } + }); + + // ---- task lists ---- + + function enableTasks() { + document.querySelectorAll('.markdown-body[data-task-action] li > input[type=checkbox]:first-child').forEach(function (cb) { + cb.disabled = false; + cb.classList.add('task-toggle'); + }); + } + + document.addEventListener('change', function (e) { + var cb = e.target; + if (!cb || !cb.classList || !cb.classList.contains('task-toggle')) { return; } + var box = cb.closest('.markdown-body[data-task-action]'); + if (!box) { return; } + var all = box.querySelectorAll('li > input[type=checkbox]:first-child'); + var index = Array.prototype.indexOf.call(all, cb); + var want = cb.checked; + var body = new URLSearchParams(); + body.set('csrf', box.getAttribute('data-csrf') || ''); + body.set('kind', box.getAttribute('data-task-kind') || ''); + body.set('id', box.getAttribute('data-task-id') || ''); + body.set('index', String(index)); + body.set('checked', want ? '1' : '0'); + cb.disabled = true; + fetch(box.getAttribute('data-task-action'), { + method: 'POST', + headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' }, + body: body.toString() + }).then(function (r) { + if (!r.ok) { throw new Error('task'); } + }).catch(function () { + cb.checked = !want; + cb.title = T.taskFail; + }).then(function () { cb.disabled = false; }); + }); + + // ---- keep it applied ---- + + var scheduled = false; + new MutationObserver(function () { + if (scheduled) { return; } + scheduled = true; + Promise.resolve().then(function () { scheduled = false; enhance(); }); + }).observe(document.body, { childList: true, subtree: true }); + enhance(); })(); diff --git a/crates/forge-web/src/blobs.rs b/crates/forge-web/src/blobs.rs index 505a9d6..ac90aaa 100644 --- a/crates/forge-web/src/blobs.rs +++ b/crates/forge-web/src/blobs.rs @@ -33,6 +33,11 @@ pub fn asset_key(asset_id: &str) -> String { format!("assets/{asset_id}") } +/// The object key of a markdown attachment. +pub fn attachment_key(attachment_id: &str) -> String { + format!("attachments/{attachment_id}") +} + fn storage_err(e: E) -> Error where E: std::error::Error + Send + Sync + 'static, diff --git a/crates/forge-web/src/i18n/authoring.rs b/crates/forge-web/src/i18n/authoring.rs new file mode 100644 index 0000000..89cfeed --- /dev/null +++ b/crates/forge-web/src/i18n/authoring.rs @@ -0,0 +1,75 @@ +//! Strings for the authoring helpers: attachments, autocomplete, task lists and review requests. + +use super::Lang; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum K { + Reviewers, + NoReviewers, + RequestReview, + ReviewerName, + WithdrawRequest, + ReviewRequests, + NoReviewRequests, + ReviewerUnknown, + ReviewerNoAccess, + ReviewerIsAuthor, + ReviewerAlready, + ReviewRequestsTab, +} + +pub fn t(lang: Lang, key: K) -> &'static str { + use K::*; + use Lang::*; + match (key, lang) { + (Reviewers, En) => "Reviewers", + (Reviewers, Tr) => "İnceleyenler", + (NoReviewers, En) => "No review requested", + (NoReviewers, Tr) => "İnceleme istenmedi", + (RequestReview, En) => "Request review", + (RequestReview, Tr) => "İnceleme iste", + (ReviewerName, En) => "Username", + (ReviewerName, Tr) => "Kullanıcı adı", + (WithdrawRequest, En) => "Withdraw request", + (WithdrawRequest, Tr) => "İsteği geri çek", + (ReviewRequests, En) => "Review requests", + (ReviewRequests, Tr) => "İnceleme istekleri", + (NoReviewRequests, En) => "Nobody is waiting for your review.", + (NoReviewRequests, Tr) => "İncelemenizi bekleyen yok.", + (ReviewerUnknown, En) => "No such user.", + (ReviewerUnknown, Tr) => "Böyle bir kullanıcı yok.", + (ReviewerNoAccess, En) => "That user cannot read this repository.", + (ReviewerNoAccess, Tr) => "Bu kullanıcı bu depoyu okuyamaz.", + (ReviewerIsAuthor, En) => "The author cannot review their own pull request.", + (ReviewerIsAuthor, Tr) => "Yazar kendi değişiklik isteğini inceleyemez.", + (ReviewerAlready, En) => "A review is already requested from that user.", + (ReviewerAlready, Tr) => "Bu kullanıcıdan zaten inceleme istendi.", + (ReviewRequestsTab, En) => "Review requests", + (ReviewRequestsTab, Tr) => "İnceleme istekleri", + } +} + +/// "2 of 5 tasks". +pub fn tasks_progress(lang: Lang, done: usize, total: usize) -> String { + match lang { + Lang::En => format!("{done} of {total} tasks"), + Lang::Tr => format!("{done}/{total} görev"), + } +} + +/// Title text of a request on a list row: "Review requested from tahinli, bob". +pub fn requested_from(lang: Lang, names: &[String]) -> String { + let joined = names.join(", "); + match lang { + Lang::En => format!("Review requested from {joined}"), + Lang::Tr => format!("İnceleme istenen: {joined}"), + } +} + +/// "requested by tahinli". +pub fn requested_by(lang: Lang, name: &str) -> String { + match lang { + Lang::En => format!("requested by {name}"), + Lang::Tr => format!("{name} istedi"), + } +} diff --git a/crates/forge-web/src/i18n/mod.rs b/crates/forge-web/src/i18n/mod.rs index 3080964..725bd0d 100644 --- a/crates/forge-web/src/i18n/mod.rs +++ b/crates/forge-web/src/i18n/mod.rs @@ -20,6 +20,7 @@ use forge_core::User; pub mod accents; pub mod admin; pub mod browse; +pub mod authoring; pub mod code; pub mod community; pub mod integrations; @@ -308,6 +309,7 @@ pub enum Key { MailVerbMerged, MailVerbReviewed, MailVerbAssigned, + MailVerbReviewRequested, MailVerbPushed, MailVerbMentioned, MailSomeone, @@ -514,6 +516,7 @@ pub const ALL: &[Key] = &[ Key::MailVerbMerged, Key::MailVerbReviewed, Key::MailVerbAssigned, + Key::MailVerbReviewRequested, Key::MailVerbPushed, Key::MailVerbMentioned, Key::MailSomeone, @@ -997,6 +1000,8 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (MailVerbReopened, En) => "reopened this", (MailVerbMerged, En) => "merged this", (MailVerbReviewed, En) => "reviewed this", + (MailVerbReviewRequested, En) => "requested your review on this", + (MailVerbReviewRequested, Tr) => "bunun için incelemenizi istedi", (MailVerbAssigned, En) => "assigned you to this", (MailVerbPushed, En) => "pushed new commits", (MailVerbMentioned, En) => "mentioned you", diff --git a/crates/forge-web/src/mail/templates.rs b/crates/forge-web/src/mail/templates.rs index b06cc58..f95fa56 100644 --- a/crates/forge-web/src/mail/templates.rs +++ b/crates/forge-web/src/mail/templates.rs @@ -16,6 +16,7 @@ pub enum Verb { Merged, Reviewed, AssignedYou, + ReviewRequested, Pushed, MentionedYou, } @@ -83,6 +84,7 @@ fn verb_key(verb: Verb) -> Key { Verb::Merged => Key::MailVerbMerged, Verb::Reviewed => Key::MailVerbReviewed, Verb::AssignedYou => Key::MailVerbAssigned, + Verb::ReviewRequested => Key::MailVerbReviewRequested, Verb::Pushed => Key::MailVerbPushed, Verb::MentionedYou => Key::MailVerbMentioned, } diff --git a/crates/forge-web/src/notify.rs b/crates/forge-web/src/notify.rs index 2809e48..a90fd66 100644 --- a/crates/forge-web/src/notify.rs +++ b/crates/forge-web/src/notify.rs @@ -34,6 +34,10 @@ pub enum Activity { Assigned { assignee_id: String, }, + /// The user with `reviewer_id` was asked to review. + ReviewRequested { + reviewer_id: String, + }, /// The pull request head moved. Pushed, /// The body or a comment was edited. Only newly mentioned users hear about it. @@ -51,6 +55,7 @@ impl Activity { Activity::Merged => "merged", Activity::Review => "review", Activity::Assigned { .. } => "assigned", + Activity::ReviewRequested { .. } => "review_requested", Activity::Pushed => "pushed", Activity::Edited => "edited", } @@ -144,6 +149,20 @@ pub async fn dispatch_assigned( } } +/// Tells `reviewer_id` that `actor_id` asked for their review of the pull request. Never fails. +pub async fn dispatch_review_requested( + state: &AppState, + repo: &Repo, + issue: &Issue, + actor_id: &str, + reviewer_id: &str, +) { + let activity = Activity::ReviewRequested { + reviewer_id: reviewer_id.to_owned(), + }; + dispatch(state, repo, issue, actor_id, activity, None).await; +} + /// Tells the admins of `repo` that a lockfile scan opened `opened` security alerts on it. The /// admins are the owner (for an organization, its owners) and the collaborators with the Admin /// role. Writes inbox rows only. Never fails: problems are logged. @@ -287,7 +306,10 @@ async fn run( let mut candidates: BTreeMap = BTreeMap::new(); let mut mentioned: BTreeSet = BTreeSet::new(); - if *activity != Activity::Edited { + if !matches!( + activity, + Activity::Edited | Activity::ReviewRequested { .. } + ) { for (user_id, stored) in store.subscribers(issue_id).await? { let reason = if activity.changes_state() { strongest(stored, Reason::StateChange) @@ -312,6 +334,17 @@ async fn run( } } + // A review request reaches the reviewer only, not the thread's other subscribers. + if let Activity::ReviewRequested { reviewer_id } = activity + && !is_ignored(state, reviewer_id, issue_id).await? + { + add( + &mut candidates, + reviewer_id.clone(), + Reason::ReviewRequested, + ); + } + // Mentions reach the user whatever their watch level or subscription. for name in mentions { if let Some(user) = store.user_by_username(name).await? { @@ -358,6 +391,13 @@ async fn run( .auto_subscribe(assignee_id, issue_id, Reason::Assign) .await?; } + if let Activity::ReviewRequested { reviewer_id } = activity + && readable_user(state, repo, reviewer_id).await?.is_some() + { + store + .auto_subscribe(reviewer_id, issue_id, Reason::ReviewRequested) + .await?; + } for user_id in &mentioned { if readable_user(state, repo, user_id).await?.is_some() { store @@ -469,6 +509,7 @@ fn verb_for(activity: &Activity) -> Verb { Activity::Merged => Verb::Merged, Activity::Review => Verb::Reviewed, Activity::Assigned { .. } => Verb::AssignedYou, + Activity::ReviewRequested { .. } => Verb::ReviewRequested, Activity::Pushed => Verb::Pushed, Activity::Edited => Verb::MentionedYou, } diff --git a/crates/forge-web/src/pages/authoring.rs b/crates/forge-web/src/pages/authoring.rs new file mode 100644 index 0000000..1cd83f8 --- /dev/null +++ b/crates/forge-web/src/pages/authoring.rs @@ -0,0 +1,406 @@ +//! Helpers behind the markdown editors: attachment upload and download, the `@` and `#` +//! suggestion endpoint, and task-list checkbox toggles. +//! +//! * `POST /{owner}/{repo}/attachments` takes a multipart body (`csrf` first, then `file`) and +//! answers JSON with the markdown to insert. Bytes go to blob storage under `attachments/`. +//! * `GET /attachments/{id}/{name}` serves the file if the viewer can read the repo it was +//! uploaded to. Images show inline; every other type downloads. `nosniff` and a locked-down CSP +//! are always set. +//! * `GET /{owner}/{repo}/suggest?kind=user|issue&q=..` returns up to eight matches as JSON. +//! * `POST /{owner}/{repo}/issues|pulls/{n}/tasks` flips one `- [ ]` item in a body or comment. + +use futures_util::TryStreamExt; +use http::header::{CONTENT_DISPOSITION, CONTENT_LENGTH, CONTENT_TYPE}; +use http_body::Frame; +use http_body_util::StreamBody; +use serde::Deserialize; +use serde_json::json; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::Form; +use topcoat::router::error::{bad_request, forbidden, not_found}; +use topcoat::router::request::{headers, uri}; +use topcoat::router::response::Response; +use topcoat::router::{Body, HeaderName, HeaderValue, StatusCode, path_param, route}; + +use forge_core::authz::{Action, authorize}; + +use crate::api; +use crate::auth::{current_user, require_csrf}; +use crate::blobs::attachment_key; +use crate::pages::issue_parts::{ItemKind, comment_for, item_for, may_change, parse_number}; +use crate::pages::repo_ctx::load_repo; +use crate::render::markdown::{set_task, task_progress}; +use crate::state::AppState; + +path_param!(owner); +path_param!(repo); +path_param!(number); +path_param!(id); +path_param!(name); + +/// Largest accepted attachment, in bytes. +pub const MAX_ATTACHMENT_BYTES: u64 = 10 * 1024 * 1024; +/// Allowance for the multipart framing around the file. +const MULTIPART_OVERHEAD: u64 = 64 * 1024; +/// Longest stored file name, in characters. +const MAX_NAME_CHARS: usize = 100; + +/// The content type served for a file extension, and whether it may be shown inline. `None` for +/// types that are not accepted. The type comes from the extension, never from the client. +fn type_for(name: &str) -> Option<(&'static str, bool)> { + let ext = name.rsplit_once('.')?.1.to_ascii_lowercase(); + Some(match ext.as_str() { + "png" => ("image/png", true), + "jpg" | "jpeg" => ("image/jpeg", true), + "gif" => ("image/gif", true), + "webp" => ("image/webp", true), + "pdf" => ("application/pdf", false), + "txt" | "log" | "md" | "patch" | "diff" => ("text/plain; charset=utf-8", false), + "csv" => ("text/csv; charset=utf-8", false), + "json" => ("application/json", false), + "zip" => ("application/zip", false), + "gz" | "tgz" => ("application/gzip", false), + _ => return None, + }) +} + +/// A file name safe in a URL path and a header: ASCII letters, digits and `. _ - +`, everything +/// else becomes `_`, cut to `MAX_NAME_CHARS`, never starting with a dot. +pub fn clean_name(raw: &str) -> String { + let base = raw.rsplit(['/', '\\']).next().unwrap_or(raw); + let mut out: String = base + .chars() + .take(MAX_NAME_CHARS) + .map(|c| { + if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-' | '+') { + c + } else { + '_' + } + }) + .collect(); + while out.starts_with('.') { + out.remove(0); + } + out +} + +/// Decodes `%XX` escapes and `+` in a query value; invalid escapes are kept as typed. +fn percent_decode(input: &str) -> String { + let bytes = input.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + match bytes[i] { + b'+' => out.push(b' '), + b'%' if i + 2 < bytes.len() => { + let hex = std::str::from_utf8(&bytes[i + 1..i + 3]) + .ok() + .and_then(|h| u8::from_str_radix(h, 16).ok()); + match hex { + Some(b) => { + out.push(b); + i += 2; + } + None => out.push(b'%'), + } + } + b => out.push(b), + } + i += 1; + } + String::from_utf8_lossy(&out).into_owned() +} + +fn fail(status: StatusCode, message: &str) -> Response { + api::error(status, message) +} + +/// Stores an uploaded file for a repo. The viewer needs a session and read access (anyone who can +/// comment can attach), and the repo must not be archived. +#[route(POST "/{owner}/{repo}/attachments")] +async fn upload(cx: &Cx, body: Body) -> Result { + let ctx = load_repo(cx, path_param::(cx), path_param::(cx)).await?; + let state = app_context::(cx); + if ctx.repo.archived { + return Err(forbidden().into()); + } + let declared = headers(cx) + .get(CONTENT_LENGTH) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.parse::().ok()); + if declared.is_some_and(|len| len > MAX_ATTACHMENT_BYTES + MULTIPART_OVERHEAD) { + return Ok(fail(StatusCode::PAYLOAD_TOO_LARGE, "file too large")); + } + let content_type = headers(cx) + .get(CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .unwrap_or("") + .to_owned(); + let Ok(boundary) = multer::parse_boundary(&content_type) else { + return Ok(fail(StatusCode::BAD_REQUEST, "not a multipart upload")); + }; + let mut multipart = multer::Multipart::new(body.into_data_stream(), boundary); + let mut uploader = None; + loop { + let mut field = match multipart.next_field().await { + Ok(Some(field)) => field, + Ok(None) => return Ok(fail(StatusCode::BAD_REQUEST, "no file")), + Err(_) => return Ok(fail(StatusCode::BAD_REQUEST, "bad upload")), + }; + match field.name() { + Some("csrf") => { + let token = field.text().await.unwrap_or_default(); + let (user, _) = require_csrf(cx, &token).await?; + uploader = Some(user); + } + Some("file") => { + let Some(user) = uploader.as_ref() else { + return Err(forbidden().into()); + }; + let name = clean_name(field.file_name().unwrap_or("")); + let name = if name.is_empty() { + "file".to_owned() + } else { + name + }; + let Some((mime, inline)) = type_for(&name) else { + return Ok(fail( + StatusCode::UNSUPPORTED_MEDIA_TYPE, + "file type not allowed", + )); + }; + let id = ulid::Ulid::generate().to_string().to_ascii_lowercase(); + let key = attachment_key(&id); + let mut writer = state.blobs.begin(&key, MAX_ATTACHMENT_BYTES).await?; + loop { + match field.chunk().await { + Ok(Some(chunk)) => { + if let Err(e) = writer.push(&chunk).await { + writer.abort().await; + return Ok(match e { + forge_core::Error::Invalid(_) => { + fail(StatusCode::PAYLOAD_TOO_LARGE, "file too large") + } + other => return Err(other.into()), + }); + } + } + Ok(None) => break, + Err(_) => { + writer.abort().await; + return Ok(fail(StatusCode::BAD_REQUEST, "bad upload")); + } + } + } + let (size, sha256) = writer.finish().await?; + if size == 0 { + let _ = state.blobs.delete(&key).await; + return Ok(fail(StatusCode::BAD_REQUEST, "empty file")); + } + if let Err(e) = state + .store + .add_attachment(&id, &ctx.repo.id, &user.id, &name, mime, size, &sha256) + .await + { + let _ = state.blobs.delete(&key).await; + return Err(e.into()); + } + let url = format!("/attachments/{id}/{name}"); + let markdown = if inline { + format!("![{name}]({url})") + } else { + format!("[{name}]({url})") + }; + return Ok(api::json( + StatusCode::CREATED, + &json!({ "url": url, "name": name, "image": inline, "markdown": markdown }), + )); + } + _ => { + let _ = field.bytes().await; + } + } + } +} + +/// Serves an attachment to anyone who can read its repo; everyone else gets 404. +#[route(GET "/attachments/{id}/{name}")] +async fn download(cx: &Cx) -> Result { + let state = app_context::(cx); + let Some(att) = state.store.attachment(path_param::(cx)).await? else { + return Err(not_found().into()); + }; + if att.name != path_param::(cx) { + return Err(not_found().into()); + } + let Some(repo) = state.store.repo_by_id(&att.repo_id).await? else { + return Err(not_found().into()); + }; + let viewer = current_user(cx).await?; + let (role, org_role) = match &viewer { + Some((user, _)) => ( + state.store.collaborator_role(&repo.id, &user.id).await?, + state + .store + .org_repo_role(&repo.owner_id, &user.id, &repo.id) + .await?, + ), + None => (None, None), + }; + let actor = viewer.as_ref().map(|(user, _)| user); + if authorize(actor, &repo, role, org_role, Action::Read).is_err() { + return Err(not_found().into()); + } + let Some(read) = state.blobs.read(&attachment_key(&att.id)).await? else { + return Err(not_found().into()); + }; + let inline = type_for(&att.name).is_some_and(|(_, inline)| inline); + let mut res = Response::new(Body::new(StreamBody::new(read.stream.map_ok(Frame::data)))); + *res.status_mut() = StatusCode::OK; + let h = res.headers_mut(); + if let Ok(value) = HeaderValue::from_str(&att.content_type) { + h.insert(CONTENT_TYPE, value); + } + h.insert(CONTENT_LENGTH, HeaderValue::from(read.size)); + let disposition = if inline { "inline" } else { "attachment" }; + if let Ok(value) = HeaderValue::from_str(&format!("{disposition}; filename=\"{}\"", att.name)) { + h.insert(CONTENT_DISPOSITION, value); + } + h.insert( + HeaderName::from_static("x-content-type-options"), + HeaderValue::from_static("nosniff"), + ); + h.insert( + HeaderName::from_static("content-security-policy"), + HeaderValue::from_static("default-src 'none'; style-src 'unsafe-inline'; sandbox"), + ); + h.insert( + HeaderName::from_static("cache-control"), + HeaderValue::from_static("private, max-age=3600"), + ); + Ok(res) +} + +/// Up to eight suggestions for the editors. `kind=user` lists people (people in the repo first), +/// `kind=issue` lists issues and pull requests by number or title. +#[route(GET "/{owner}/{repo}/suggest")] +async fn suggest(cx: &Cx) -> Result { + let ctx = load_repo(cx, path_param::(cx), path_param::(cx)).await?; + let state = app_context::(cx); + if ctx.viewer.is_none() { + return Err(forbidden().into()); + } + let mut kind = ""; + let mut q = String::new(); + for pair in uri(cx).query().unwrap_or_default().split('&') { + if let Some(v) = pair.strip_prefix("kind=") { + kind = if v == "issue" { "issue" } else { "user" }; + } else if let Some(v) = pair.strip_prefix("q=") { + q = percent_decode(v); + } + } + let q: String = q.chars().take(60).collect(); + let items = if kind == "issue" { + state + .store + .suggest_issues(&ctx.repo.id, &q, 8) + .await? + .into_iter() + .map(|i| { + json!({ + "number": i.number, + "title": i.title, + "pull": i.is_pull, + "open": i.open, + }) + }) + .collect::>() + } else { + let mut names = state.store.suggest_usernames(&ctx.repo.id, &q, 8).await?; + names.retain(|n| !n.is_empty()); + let mut out = Vec::new(); + for name in names { + let display = state + .store + .user_by_username(&name) + .await? + .and_then(|u| u.display_name) + .unwrap_or_default(); + out.push(json!({ "login": name, "name": display })); + } + out + }; + Ok(api::json(StatusCode::OK, &json!(items))) +} + +#[derive(Deserialize)] +struct TaskForm { + #[serde(default)] + csrf: String, + /// `issue` for the item body, `comment` for a comment. + #[serde(default)] + kind: String, + #[serde(default)] + id: String, + #[serde(default)] + index: String, + /// `1` to check, anything else to uncheck. + #[serde(default)] + checked: String, +} + +#[route(POST "/{owner}/{repo}/issues/{number}/tasks")] +async fn issue_tasks(cx: &Cx, Form(form): Form) -> Result { + toggle(cx, ItemKind::Issue, form).await +} + +#[route(POST "/{owner}/{repo}/pulls/{number}/tasks")] +async fn pull_tasks(cx: &Cx, Form(form): Form) -> Result { + toggle(cx, ItemKind::Pull, form).await +} + +async fn toggle(cx: &Cx, kind: ItemKind, form: TaskForm) -> Result { + let number = parse_number(path_param::(cx))?; + let ctx = load_repo(cx, path_param::(cx), path_param::(cx)).await?; + let (user, _) = require_csrf(cx, &form.csrf).await?; + let state = app_context::(cx); + let item = item_for(state, &ctx, kind, number).await?; + let Ok(index) = form.index.parse::() else { + return Err(bad_request("bad task index").into()); + }; + let checked = form.checked == "1"; + let (author_id, old_body) = match form.kind.as_str() { + "issue" if form.id == item.id => (item.author_id.clone(), item.body.clone()), + "comment" => { + let comment = comment_for(state, &item, &form.id).await?; + (comment.author_id, comment.body) + } + _ => return Err(bad_request("unknown task target").into()), + }; + if !may_change(&ctx, &author_id) { + return Err(forbidden().into()); + } + let Some(new_body) = set_task(&old_body, index, checked) else { + return Ok(fail(StatusCode::CONFLICT, "task not found")); + }; + if new_body != old_body { + if form.kind == "issue" { + state + .store + .edit_issue(&item.id, &user.id, &item.title, &new_body) + .await?; + } else { + state + .store + .edit_comment(&form.id, &user.id, &new_body) + .await?; + } + } + let (done, total) = task_progress(&new_body); + Ok(api::json( + StatusCode::OK, + &json!({ "done": done, "total": total }), + )) +} diff --git a/crates/forge-web/src/pages/authoring_tests.rs b/crates/forge-web/src/pages/authoring_tests.rs new file mode 100644 index 0000000..bc2623e --- /dev/null +++ b/crates/forge-web/src/pages/authoring_tests.rs @@ -0,0 +1,477 @@ +//! Router-level tests for attachments, suggestions, task toggles and review requests. + +use forge_core::Visibility; +use topcoat::router::request::Request; +use topcoat::router::{Body, to_bytes}; + +use crate::auth::SESSION_COOKIE; +use crate::pages::authoring::clean_name; +use crate::pages::issues_list::test_util::{CSRF, OWNER, REPO, TOKEN, fixture, send}; + +const OID_A: &str = "1111111111111111111111111111111111111111"; +const OID_B: &str = "2222222222222222222222222222222222222222"; + +fn base() -> String { + format!("/{OWNER}/{REPO}") +} + +fn multipart(csrf: &str, file_name: &str, bytes: &[u8]) -> (String, Vec) { + let boundary = "----forgetest"; + let mut body = Vec::new(); + body.extend_from_slice( + format!("--{boundary}\r\nContent-Disposition: form-data; name=\"csrf\"\r\n\r\n{csrf}\r\n") + .as_bytes(), + ); + body.extend_from_slice( + format!( + "--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{file_name}\"\r\nContent-Type: application/octet-stream\r\n\r\n" + ) + .as_bytes(), + ); + body.extend_from_slice(bytes); + body.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes()); + (format!("multipart/form-data; boundary={boundary}"), body) +} + +async fn upload( + router: &topcoat::router::Router, + path: &str, + csrf: &str, + name: &str, + bytes: &[u8], +) -> (u16, String) { + let (content_type, body) = multipart(csrf, name, bytes); + let req = Request::builder() + .method("POST") + .uri(path) + .header("cookie", format!("__Host-{SESSION_COOKIE}={TOKEN}")) + .header("content-type", content_type) + .body(Body::from(body)) + .unwrap(); + let res = router.handle(req).await; + let status = res.status().as_u16(); + let text = + String::from_utf8_lossy(&to_bytes(res.into_body(), usize::MAX).await.unwrap()).into_owned(); + (status, text) +} + +#[test] +fn file_names_are_made_safe() { + assert_eq!(clean_name("shot.png"), "shot.png"); + assert_eq!(clean_name("../../etc/pass wd.png"), "pass_wd.png"); + assert_eq!(clean_name(".hidden.png"), "hidden.png"); + assert_eq!(clean_name("C:\\dir\\a b.PNG"), "a_b.PNG"); + assert!(clean_name(&"a".repeat(300)).len() <= 100); +} + +#[tokio::test] +async fn attachment_round_trip_and_visibility() { + let fx = fixture(Visibility::Private).await; + let png = b"\x89PNG\r\n\x1a\nfake"; + let (status, text) = upload( + &fx.router, + &format!("{}/attachments", base()), + CSRF, + "shot.png", + png, + ) + .await; + assert_eq!(status, 201, "{text}"); + let json: serde_json::Value = serde_json::from_str(&text).unwrap(); + let url = json["url"].as_str().unwrap().to_owned(); + assert!(url.starts_with("/attachments/") && url.ends_with("/shot.png")); + assert_eq!(json["markdown"], format!("![shot.png]({url})")); + + let ok = send(&fx.router, "GET", &url, true, None, &[]).await; + assert_eq!(ok.status, 200); + assert_eq!(ok.header("content-type").as_deref(), Some("image/png")); + assert_eq!( + ok.header("x-content-type-options").as_deref(), + Some("nosniff") + ); + assert!( + ok.header("content-disposition") + .unwrap() + .starts_with("inline") + ); + // A private repo's file is invisible to anonymous viewers. + let anon = send(&fx.router, "GET", &url, false, None, &[]).await; + assert_eq!(anon.status, 404); + // The name in the URL must match. + let wrong = url.replace("shot.png", "other.png"); + assert_eq!( + send(&fx.router, "GET", &wrong, true, None, &[]) + .await + .status, + 404 + ); +} + +#[tokio::test] +async fn attachment_rejects_bad_csrf_and_types() { + let fx = fixture(Visibility::Public).await; + let path = format!("{}/attachments", base()); + assert_eq!( + upload(&fx.router, &path, "wrong", "a.png", b"x").await.0, + 403 + ); + assert_eq!( + upload(&fx.router, &path, CSRF, "a.html", b"").await.0, + 415 + ); + assert_eq!( + upload(&fx.router, &path, CSRF, "a.svg", b"").await.0, + 415 + ); + let (status, text) = upload(&fx.router, &path, CSRF, "notes.txt", b"hello").await; + assert_eq!(status, 201); + let json: serde_json::Value = serde_json::from_str(&text).unwrap(); + let url = json["url"].as_str().unwrap(); + // Non-images download rather than render. + let got = send(&fx.router, "GET", url, true, None, &[]).await; + assert!( + got.header("content-disposition") + .unwrap() + .starts_with("attachment") + ); + assert_eq!(got.body, "hello"); +} + +#[tokio::test] +async fn suggest_lists_users_and_issues() { + let fx = fixture(Visibility::Public).await; + fx.store + .create_issue(&fx.repo.id, &fx.owner.id, "Parser crash", "") + .await + .unwrap(); + fx.store + .create_user("tanya", None, "hash", false) + .await + .unwrap(); + let users = send( + &fx.router, + "GET", + &format!("{}/suggest?kind=user&q=ta", base()), + true, + None, + &[], + ) + .await; + let list: serde_json::Value = serde_json::from_str(&users.body).unwrap(); + assert_eq!(list[0]["login"], "tahinli"); + assert_eq!(list[1]["login"], "tanya"); + let issues = send( + &fx.router, + "GET", + &format!("{}/suggest?kind=issue&q=pars", base()), + true, + None, + &[], + ) + .await; + let list: serde_json::Value = serde_json::from_str(&issues.body).unwrap(); + assert_eq!(list[0]["number"], 1); + // Anonymous viewers get nothing. + let anon = send( + &fx.router, + "GET", + &format!("{}/suggest?kind=user&q=ta", base()), + false, + None, + &[], + ) + .await; + assert_eq!(anon.status, 403); +} + +#[tokio::test] +async fn ticking_a_task_saves_it_with_history() { + let fx = fixture(Visibility::Public).await; + let issue = fx + .store + .create_issue(&fx.repo.id, &fx.owner.id, "Plan", "- [ ] one\n- [ ] two\n") + .await + .unwrap(); + let form = format!("csrf={CSRF}&kind=issue&id={}&index=1&checked=1", issue.id); + let uri = format!("{}/issues/{}/tasks", base(), issue.number); + let ok = send(&fx.router, "POST", &uri, true, Some(&form), &[]).await; + assert_eq!(ok.status, 200, "{}", ok.body); + assert!( + ok.body.contains("\"done\":1") && ok.body.contains("\"total\":2"), + "{}", + ok.body + ); + let now = fx + .store + .issue_by_number(&fx.repo.id, issue.number) + .await + .unwrap() + .unwrap(); + assert_eq!(now.body, "- [ ] one\n- [x] two\n"); + let history = fx.store.edit_history("issue", &issue.id).await.unwrap(); + assert_eq!(history.len(), 1); + assert_eq!(history[0].old_body, "- [ ] one\n- [ ] two\n"); + + let bad = form.replace(CSRF, "wrong"); + assert_eq!( + send(&fx.router, "POST", &uri, true, Some(&bad), &[]) + .await + .status, + 403 + ); + let missing = form.replace("index=1", "index=9"); + assert_eq!( + send(&fx.router, "POST", &uri, true, Some(&missing), &[]) + .await + .status, + 409 + ); + assert_eq!( + send(&fx.router, "POST", &uri, false, Some(&form), &[]) + .await + .status, + 303 + ); + + let comment = fx + .store + .add_comment(&issue.id, &fx.owner.id, "- [x] done\n- [ ] todo") + .await + .unwrap(); + let form = format!( + "csrf={CSRF}&kind=comment&id={}&index=0&checked=0", + comment.id + ); + assert_eq!( + send(&fx.router, "POST", &uri, true, Some(&form), &[]) + .await + .status, + 200 + ); + let c = fx + .store + .comment_by_id(&issue.id, &comment.id) + .await + .unwrap() + .unwrap(); + assert_eq!(c.body, "- [ ] done\n- [ ] todo"); +} + +#[tokio::test] +async fn requesting_a_review_notifies_and_a_review_clears_it() { + let fx = fixture(Visibility::Public).await; + let bob = fx + .store + .create_user("bob", None, "hash", false) + .await + .unwrap(); + let pr = fx + .store + .create_pull( + &fx.repo.id, + &fx.owner.id, + "Add thing", + "- [x] a\n- [ ] b", + "main", + &fx.repo.id, + "feature", + OID_A, + OID_B, + ) + .await + .unwrap(); + let uri = format!("{}/pulls/{}/reviewers", base(), pr.issue.number); + let form = |who: &str, action: &str| format!("csrf={CSRF}&username={who}&action={action}"); + + // The author cannot be asked, an unknown name is refused, a real one is requested once. + let own = send( + &fx.router, + "POST", + &uri, + true, + Some(&form("tahinli", "request")), + &[], + ) + .await; + assert!( + own.header("location") + .unwrap() + .contains("reviewer_error=author") + ); + let nobody = send( + &fx.router, + "POST", + &uri, + true, + Some(&form("nobody", "request")), + &[], + ) + .await; + assert!( + nobody + .header("location") + .unwrap() + .contains("reviewer_error=unknown") + ); + let ok = send( + &fx.router, + "POST", + &uri, + true, + Some(&form("bob", "request")), + &[], + ) + .await; + assert_eq!(ok.status, 303); + assert!(!ok.header("location").unwrap().contains("reviewer_error")); + let again = send( + &fx.router, + "POST", + &uri, + true, + Some(&form("bob", "request")), + &[], + ) + .await; + assert!( + again + .header("location") + .unwrap() + .contains("reviewer_error=already") + ); + assert_eq!( + fx.store.requested_reviewers(&pr.issue.id).await.unwrap(), + ["bob"] + ); + + // bob's inbox has a review_requested row. + let inbox = fx + .store + .list_notifications(&bob.id, false, None, 10) + .await + .unwrap(); + assert_eq!(inbox.len(), 1); + assert_eq!( + inbox[0].reason, + forge_core::notifications::Reason::ReviewRequested + ); + + // The list shows the request and the task progress, and the filter narrows to it. + let list = send( + &fx.router, + "GET", + &format!("{}/pulls", base()), + true, + None, + &[], + ) + .await + .body; + assert!(list.contains("Review requested from bob"), "{list}"); + assert!(list.contains("1 of 2 tasks"), "{list}"); + let filtered = send( + &fx.router, + "GET", + &format!("{}/pulls?review_requested=bob", base()), + true, + None, + &[], + ) + .await + .body; + assert!(filtered.contains("Add thing")); + let none = send( + &fx.router, + "GET", + &format!("{}/pulls?q=review-requested:tahinli", base()), + true, + None, + &[], + ) + .await + .body; + assert!(!none.contains("Add thing"), "{none}"); + + // bob submits a review: his request is gone. + fx.store + .submit_review( + &pr.issue.id, + &bob.id, + forge_core::ReviewState::Commented, + "looks fine", + OID_A, + ) + .await + .unwrap(); + assert!( + fx.store + .requested_reviewers(&pr.issue.id) + .await + .unwrap() + .is_empty() + ); + + // Withdrawing works too. + send( + &fx.router, + "POST", + &uri, + true, + Some(&form("bob", "request")), + &[], + ) + .await; + send( + &fx.router, + "POST", + &uri, + true, + Some(&form("bob", "withdraw")), + &[], + ) + .await; + assert!( + fx.store + .requested_reviewers(&pr.issue.id) + .await + .unwrap() + .is_empty() + ); +} + +#[tokio::test] +async fn global_review_requests_page_lists_waiting_pulls() { + let fx = fixture(Visibility::Public).await; + let bob = fx + .store + .create_user("bob", None, "hash", false) + .await + .unwrap(); + let pr = fx + .store + .create_pull( + &fx.repo.id, + &bob.id, + "Bob's change", + "", + "main", + &fx.repo.id, + "feature", + OID_A, + OID_B, + ) + .await + .unwrap(); + fx.store + .request_review(&pr.issue.id, &fx.owner.id, &bob.id) + .await + .unwrap(); + let page = send(&fx.router, "GET", "/review-requests", true, None, &[]).await; + assert_eq!(page.status, 200); + assert!( + page.body.contains("Bob's change") || page.body.contains("Bob's change"), + "{}", + page.body + ); + assert!(page.body.contains("requested by bob")); +} diff --git a/crates/forge-web/src/pages/issue_parts.rs b/crates/forge-web/src/pages/issue_parts.rs index ce6303b..85ea084 100644 --- a/crates/forge-web/src/pages/issue_parts.rs +++ b/crates/forge-web/src/pages/issue_parts.rs @@ -231,10 +231,20 @@ pub(crate) struct CommentView { edit_href: Option, delete_href: Option, csrf: String, + /// Set when the viewer may edit the text: ticking a task checkbox posts here. + tasks: Option, /// The reaction row under the text; `None` when there is nothing to show. reactions: Option, } +/// Where a task checkbox toggle is posted, and which text it changes. +pub(crate) struct TaskTarget { + action: String, + /// `issue` for the item body, `comment` for a comment. + kind: &'static str, + id: String, +} + /// One reaction button: a POST toggle when `enabled`, a plain count otherwise. pub(crate) struct ReactionButton { pub(crate) action: String, @@ -398,6 +408,7 @@ pub(crate) async fn comment_item(lang: Lang, item: CommentView) -> Result Result -
(Unescaped::new_unchecked(html))
+ if let Some(task) = tasks { +
(Unescaped::new_unchecked(html))
+ } else { +
(Unescaped::new_unchecked(html))
+ } if let Some(bar) = reactions { reaction_row(lang: lang, bar: bar) } @@ -702,6 +717,11 @@ pub(crate) async fn load_discussion( .then(|| repo_href(&owner, &name, segment, &format!("{number}/edit"))), delete_href: None, csrf: csrf.clone(), + tasks: may_change(ctx, &item.author_id).then(|| TaskTarget { + action: repo_href(&owner, &name, segment, &format!("{number}/tasks")), + kind: "issue", + id: item.id.clone(), + }), reactions: reaction_bar_for( lang, body_reaction_map.get(&item.id), @@ -738,6 +758,11 @@ pub(crate) async fn load_discussion( delete_href: mine .then(|| repo_href(&owner, &name, segment, &format!("{comment_path}/delete"))), csrf: csrf.clone(), + tasks: mine.then(|| TaskTarget { + action: repo_href(&owner, &name, segment, &format!("{number}/tasks")), + kind: "comment", + id: comment.id.clone(), + }), reactions: reaction_bar_for( lang, comment_reaction_map.get(&comment.id), diff --git a/crates/forge-web/src/pages/issues_list.rs b/crates/forge-web/src/pages/issues_list.rs index adc0854..0061c1a 100644 --- a/crates/forge-web/src/pages/issues_list.rs +++ b/crates/forge-web/src/pages/issues_list.rs @@ -47,6 +47,7 @@ pub(crate) struct ListQuery { milestone: Option, author: Option, assignee: Option, + review_requested: Option, q: Option, draft: Option, sort: Option, @@ -61,6 +62,8 @@ pub(crate) struct Selection { pub(crate) milestone: String, pub(crate) author: String, pub(crate) assignee: String, + /// Username with a pending review request, or `@me` (pull requests only). + pub(crate) review_requested: String, pub(crate) query: String, /// Pull requests only: `true` (drafts), `false` (ready) or empty (both). A `draft:true` or /// `draft:false` word in the search text sets it too. @@ -92,23 +95,21 @@ impl Selection { Some("false") => "false", _ => "", }; - // `draft:true` / `draft:false` words in the search text become the draft filter. - let raw_query = clean(query.q.as_deref()); - let words: Vec<&str> = raw_query - .split_whitespace() - .filter(|word| match *word { - "draft:true" => { - draft = "true"; - false - } - "draft:false" => { - draft = "false"; - false - } - _ => true, - }) - .collect(); - let query_text = words.join(" "); + // `draft:true` / `draft:false` words and `review-requested:user` in the search text become + // filters, not title text. + let mut review_requested = clean(query.review_requested.as_deref()); + let mut words: Vec<&str> = Vec::new(); + for word in query.q.as_deref().unwrap_or_default().split_whitespace() { + match word { + "draft:true" => draft = "true", + "draft:false" => draft = "false", + _ => match word.strip_prefix("review-requested:") { + Some(who) if !who.is_empty() => review_requested = clean(Some(who)), + _ => words.push(word), + }, + } + } + let q_text = words.join(" "); Self { draft, state: match query.state.as_deref() { @@ -120,7 +121,8 @@ impl Selection { milestone: clean(query.milestone.as_deref()), author: clean(query.author.as_deref()), assignee: clean(query.assignee.as_deref()), - query: query_text, + review_requested, + query: clean(Some(&q_text)), sort: match query.sort.as_deref() { Some("oldest") => "oldest", Some("updated") => "updated", @@ -146,6 +148,8 @@ impl Selection { milestone: non_empty(&self.milestone), author: non_empty(&self.author), assignee: non_empty(&self.assignee), + review_requested: non_empty(self.review_requested.trim_start_matches('@')) + .filter(|w| self.review_requested != "@me" && !w.is_empty()), query: non_empty(&self.query), draft: match self.draft { "true" => Some(true), @@ -168,10 +172,29 @@ impl Selection { && self.milestone.is_empty() && self.author.is_empty() && self.assignee.is_empty() + && self.review_requested.is_empty() && self.query.is_empty() && self.draft.is_empty()) } + /// The search box text: the title query plus the `review-requested:` token when one is set. + pub(crate) fn search_text(&self) -> String { + if self.review_requested.is_empty() { + self.query.clone() + } else { + format!("{} review-requested:{}", self.query, self.review_requested) + .trim() + .to_owned() + } + } + + /// Resolves `@me` to the viewer's username. Anonymous viewers lose the filter. + pub(crate) fn resolve_me(&mut self, viewer: Option<&str>) { + if self.review_requested == "@me" { + self.review_requested = viewer.map(str::to_owned).unwrap_or_default(); + } + } + /// The list URL with this selection, but a different state and page. pub(crate) fn href(&self, base: &str, state: &str, page: u32) -> String { let page_text = if page > 1 { @@ -188,6 +211,7 @@ impl Selection { ("milestone", self.milestone.as_str()), ("author", self.author.as_str()), ("assignee", self.assignee.as_str()), + ("review_requested", self.review_requested.as_str()), ("q", self.query.as_str()), ("draft", self.draft), ("sort", sort), @@ -255,6 +279,8 @@ struct RowView { assignees: Vec, has_comments: bool, comments_text: String, + /// "2 of 5 tasks" when the body has task items. + tasks_text: Option, } /// What every row of one list page shares: the language, the repo, the state filter, the @@ -330,9 +356,16 @@ fn row_view(row: RowCtx<'_>, item: &IssueListItem) -> RowView { .collect(), has_comments: comments > 0, comments_text: g::comment_count(lang, comments), + tasks_text: tasks_text(lang, &issue.body), } } +/// The "N of M tasks" label for a body, or `None` without task items. +pub(crate) fn tasks_text(lang: Lang, body: &str) -> Option { + let (done, total) = crate::render::markdown::task_progress(body); + (total > 0).then(|| crate::i18n::authoring::tasks_progress(lang, done, total)) +} + /// One pinned issue card, with the strings the template shows already built. struct PinnedCard { state_class: &'static str, @@ -379,6 +412,7 @@ async fn issues_list_page(cx: &Cx) -> Result { let ctx = load_repo(cx, owner, name).await?; let state = app_context::(cx); let sel = Selection::parse(query); + let search_value = sel.search_text(); let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(u, _)| u)); let (items, total) = state.store.list_issues(&ctx.repo.id, &sel.filter()).await?; @@ -478,7 +512,7 @@ async fn issues_list_page(cx: &Cx) -> Result { - + - + + + + + } + + } + + if write { +
+ + +
+
+ } + + }) +} + +/// The open pull requests waiting for the viewer's review, newest request first. +#[page("/review-requests")] +async fn review_requests(cx: &Cx) -> Result { + let viewer = require_user(cx).await?; + let state = app_context::(cx); + let user = &viewer.0; + let lang = i18n::lang(cx, Some(user)); + let items = state.store.review_requests_for_user(&user.id).await?; + let now = now_unix(); + let mut rows = Vec::new(); + for item in items { + // A repo the viewer can no longer read is not listed. + let Some(repo) = state + .store + .repo_by_owner_and_name(&item.repo_owner, &item.repo_name) + .await? + else { + continue; + }; + let role = state.store.collaborator_role(&repo.id, &user.id).await?; + let org_role = state + .store + .org_repo_role(&repo.owner_id, &user.id, &repo.id) + .await?; + if authorize(Some(user), &repo, role, org_role, Action::Read).is_err() { + continue; + } + let unix = crate::pages::issue_parts::stamp_unix(&item.created_at); + rows.push(( + format!("{}/{}", item.repo_owner, item.repo_name), + repo_href( + &item.repo_owner, + &item.repo_name, + "pulls", + &item.number.to_string(), + ), + format!("#{} {}", item.number, item.title), + ga::requested_by(lang, &item.requested_by), + relative_time(lang, unix, now), + )); + } + let heading = ga::t(lang, AK::ReviewRequests); + let empty = rows.is_empty(); + Ok(view! { + shell(title: heading, viewer: Some(&viewer), +
+

(heading)

+
+ if empty { +

(ga::t(lang, AK::NoReviewRequests))

+ } + if !empty { +
+
    + for row in rows.iter() { +
  • + (row.0.as_str()) + (row.2.as_str()) + (row.3.as_str()) + (row.4.as_str()) +
  • + } +
+
+ } + ) + }) +} diff --git a/crates/forge-web/src/render/markdown.rs b/crates/forge-web/src/render/markdown.rs index 5fd5444..41b7268 100644 --- a/crates/forge-web/src/render/markdown.rs +++ b/crates/forge-web/src/render/markdown.rs @@ -77,6 +77,7 @@ fn markdown_options() -> Options<'static> { options.extension.autolink = true; options.extension.footnotes = true; options.extension.alerts = true; + options.extension.math_dollars = true; options.extension.header_id_prefix = Some(ID_PREFIX.to_string()); // Raw HTML is passed through to ammonia, which removes anything not allowlisted. options.render.r#unsafe = true; @@ -127,7 +128,12 @@ impl Resolver { /// Returns the rewritten URL, or `None` to keep the original. fn rewrite(&self, url: &str, image: bool) -> Option { - if url.is_empty() || url.starts_with("//") || has_scheme(url) { + // Attachment URLs are site-absolute and independent of the rendered file's location. + if url.is_empty() + || url.starts_with("//") + || has_scheme(url) + || url.starts_with("/attachments/") + { return None; } if let Some(fragment) = url.strip_prefix('#') { @@ -630,6 +636,56 @@ pub fn mentioned_usernames(text: &str) -> Vec { found } +/// The task items of `src` in document order, as `(byte offset of the mark, checked)`. The mark is +/// the character between the brackets. Tasks inside code blocks are not task items, so they are +/// not listed. +fn task_marks(src: &str) -> Vec<(usize, bool)> { + let options = markdown_options(); + let arena = Arena::new(); + let root = parse_document(&arena, src, &options); + let mut line_starts = vec![0usize]; + for (i, b) in src.bytes().enumerate() { + if b == b'\n' { + line_starts.push(i + 1); + } + } + let mut out = Vec::new(); + for node in root.descendants() { + if let NodeValue::TaskItem(item) = &node.data.borrow().value { + let pos = item.symbol_sourcepos.start; + let Some(line) = line_starts.get(pos.line.wrapping_sub(1)) else { + continue; + }; + let at = line + pos.column.saturating_sub(1); + if at < src.len() && src.is_char_boundary(at) { + out.push((at, item.symbol.is_some())); + } + } + } + out +} + +/// `(done, total)` task items in markdown `src`. +pub fn task_progress(src: &str) -> (usize, usize) { + let marks = task_marks(src); + (marks.iter().filter(|(_, done)| *done).count(), marks.len()) +} + +/// Sets the `index`th task item (document order) to `checked`. `None` when there is no such task. +pub fn set_task(src: &str, index: usize, checked: bool) -> Option { + let (at, _) = *task_marks(src).get(index)?; + let mark = src[at..].chars().next()?; + let before = src[..at].chars().next_back()?; + if before != '[' || !(mark == ' ' || mark == 'x' || mark == 'X') { + return None; + } + let mut out = String::with_capacity(src.len()); + out.push_str(&src[..at]); + out.push(if checked { 'x' } else { ' ' }); + out.push_str(&src[at + mark.len_utf8()..]); + Some(out) +} + /// Adds the lowercased names of the `@mention`s in one text run to `found`, skipping duplicates. fn collect_mentions(text: &str, found: &mut Vec) { for range in mention_spans(text) { @@ -737,6 +793,7 @@ fn sanitizer() -> Builder<'static> { ("th", &["align"]), ("input", &["type", "checked", "disabled"]), ("details", &["open"]), + ("span", &["data-math-style"]), ] .into_iter() .map(|(tag, names)| (tag, names.iter().copied().collect())) @@ -780,6 +837,26 @@ mod tests { } } + #[test] + fn tasks_are_counted_and_toggled() { + let src = "- [ ] one\n- [x] two\n - [ ] nested\n\n```\n- [ ] code\n```\n"; + assert_eq!(task_progress(src), (1, 3)); + let on = set_task(src, 0, true).unwrap(); + assert!(on.starts_with("- [x] one\n"), "{on}"); + let off = set_task(&on, 1, false).unwrap(); + assert!(off.contains("- [ ] two"), "{off}"); + assert_eq!(set_task(src, 2, true).unwrap().matches("[x]").count(), 2); + assert!(set_task(src, 3, true).is_none()); + assert!(set_task("no tasks", 0, true).is_none()); + } + + #[test] + fn math_and_attachment_urls_survive() { + let html = render_markdown("$x^2$ and ![a](/attachments/abc/a.png)", Some(&ctx())); + assert!(html.contains("data-math-style=\"inline\""), "{html}"); + assert!(html.contains("src=\"/attachments/abc/a.png\""), "{html}"); + } + #[test] fn issue_refs_and_mentions_are_linked() { let html = render_markdown("fixes #12, see @tahinli.\n\n- #3", Some(&issue_ctx())); diff --git a/style/_authoring.scss b/style/_authoring.scss new file mode 100644 index 0000000..85f323e --- /dev/null +++ b/style/_authoring.scss @@ -0,0 +1,122 @@ +// Authoring helpers: attach toolbar, autocomplete list, task lists, alerts, reviewers, math. + +.md-tools { + position: relative; + display: flex; + align-items: center; + gap: 0.6rem; + min-height: 1.6rem; + margin-top: 0.25rem; +} + +.md-status { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.md-status-bad { + color: var(--caution); +} + +textarea.md-drop { + outline: 2px dashed var(--accent); + outline-offset: -2px; +} + +.md-suggest { + position: absolute; + top: 100%; + left: 0; + z-index: 30; + min-width: min(22rem, 100%); + max-width: 100%; + margin: 2px 0 0; + padding: 4px; + list-style: none; + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-md); + box-shadow: var(--shadow); + + &[hidden] { + display: none; + } +} + +.md-suggest-input { + top: auto; + left: 0; + right: 0; +} + +.md-suggest-item { + display: flex; + align-items: baseline; + gap: 0.4rem; + padding: 0.3rem 0.5rem; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + border-radius: var(--radius-sm); + cursor: pointer; + + &.active, + &:hover { + background: var(--accent-soft, var(--hover, var(--border))); + } +} + +.markdown-body { + li:has(> input[type="checkbox"]:first-child) { + list-style: none; + } + + li > input[type="checkbox"]:first-child { + width: auto; + margin: 0 0.4em 0 -1.4em; + vertical-align: middle; + } + + .task-toggle { + cursor: pointer; + } + + .markdown-alert { + background: color-mix(in srgb, var(--alert-accent, var(--border)) 9%, var(--surface)); + } + + [data-math-style] { + font-family: var(--mono, ui-monospace, monospace); + font-style: italic; + } + + [data-math-style="display"] { + display: block; + margin: 0.5em 0; + text-align: center; + } +} + +.task-progress, +.review-pending { + &::before { + content: "\00b7"; + margin-right: 0.4em; + } +} + +.reviewer-list li { + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.5rem; + padding: 0.1rem 0; +} + +.review-request-list li { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 0.2rem 0.75rem; +} diff --git a/style/main.scss b/style/main.scss index f2cd847..4993460 100644 --- a/style/main.scss +++ b/style/main.scss @@ -82,6 +82,7 @@ --del-text: #7D2B25; --del-mark: #B0413A; --row-target: #FFF4C2; + --note: #2B6CB0; --tip: #1D7A62; --important: #6A4BB0; --warning: #9A6200; @@ -119,6 +120,7 @@ --del-text: #F2B8B0; --del-mark: #F09A90; --row-target: #3A3510; + --note: #8AB4F0; --tip: #7CCBAE; --important: #C4A7FF; --warning: #E6B765; @@ -147,6 +149,7 @@ --del-text: #F2B8B0; --del-mark: #F09A90; --row-target: #3A3510; + --note: #8AB4F0; --tip: #7CCBAE; --important: #C4A7FF; --warning: #E6B765; @@ -5574,6 +5577,7 @@ button.ci-job-last { @import "wiki"; @import "browse"; @import "import"; +@import "authoring"; // Code inside cards, notices and settings panels must stay inside the card. Long tokens and // commands wrap instead of running past the right edge. The rendered README card (.readme) and