forge
Explore
Log in

Don't you dare go Hollow

Autocomplete reopen after choose, drop dead i18n keys, clippy arg-count allow

Browse files at this commit

62a58515f825daea2c937306fd5d6627f23f464cAhmet Kaan GümüşParent: fd072f9
  • fix
    • autocomplete reopen after choose, drop dead i18n keys, clippy arg-count allow
Show full message
🐛 fix: autocomplete reopen after choose, drop dead i18n keys, clippy arg-count allow

Includes: ✨ feat: attachments, @ and # autocomplete, task lists, review requests, math in markdown
crates/forge-core/migrations/0055_attachments.sqladded+15 -0
@@ -0,0 +1,15 @@
1+-- Files attached to issues, pull requests, comments and discussions through the markdown
2+-- editors. The bytes live in blob storage under `attachments/<id>`; this row is the metadata
3+-- and the repo link that access checks use. Applied by store/migrate.rs.
4+
5+CREATE TABLE attachments (
6+ id TEXT PRIMARY KEY,
7+ repo_id TEXT NOT NULL REFERENCES repos(id) ON DELETE CASCADE,
8+ uploader_id TEXT NOT NULL REFERENCES users(id),
9+ name TEXT NOT NULL,
10+ content_type TEXT NOT NULL,
11+ size INTEGER NOT NULL,
12+ sha256 TEXT NOT NULL,
13+ created_at TEXT NOT NULL
14+);
15+CREATE INDEX attachments_repo ON attachments(repo_id);
crates/forge-core/migrations/0056_review_requests.sqladded+11 -0
@@ -0,0 +1,11 @@
1+-- Reviewers requested on a pull request. A row is removed when the reviewer submits a review or
2+-- the request is withdrawn. Applied by store/migrate.rs.
3+
4+CREATE TABLE review_requests (
5+ issue_id TEXT NOT NULL REFERENCES issues(id) ON DELETE CASCADE,
6+ reviewer_id TEXT NOT NULL REFERENCES users(id),
7+ requested_by TEXT NOT NULL REFERENCES users(id),
8+ created_at TEXT NOT NULL,
9+ PRIMARY KEY (issue_id, reviewer_id)
10+);
11+CREATE INDEX review_requests_reviewer ON review_requests(reviewer_id);
crates/forge-core/src/issues.rsmodified+3 -0
@@ -150,6 +150,8 @@ pub struct IssueFilter {
150 pub author: Option<String>,150 pub author: Option<String>,
151 /// Assignee username.151 /// Assignee username.
152 pub assignee: Option<String>,152 pub assignee: Option<String>,
153+ /// Username with a pending review request (pull requests only).
154+ pub review_requested: Option<String>,
153 /// Substring of the title, case-insensitive.155 /// Substring of the title, case-insensitive.
154 pub query: Option<String>,156 pub query: Option<String>,
155 /// Pull requests only: `Some(true)` lists drafts, `Some(false)` lists ready pull requests.157 /// Pull requests only: `Some(true)` lists drafts, `Some(false)` lists ready pull requests.
@@ -168,6 +170,7 @@ impl Default for IssueFilter {
168 milestone: None,170 milestone: None,
169 author: None,171 author: None,
170 assignee: None,172 assignee: None,
173+ review_requested: None,
171 query: None,174 query: None,
172 draft: None,175 draft: None,
173 sort: IssueSort::Newest,176 sort: IssueSort::Newest,
crates/forge-core/src/store/attachments.rsadded+127 -0
@@ -0,0 +1,127 @@
1+//! Metadata of files attached through the markdown editors. The bytes are in blob storage under
2+//! `attachments/<id>`; a row ties the file to the repo it was uploaded in, which is what the
3+//! download access check follows (a file is as visible as its repo).
4+
5+use serde::Serialize;
6+
7+use super::{Store, col_int, col_text, db_err, fetch_opt};
8+use crate::error::Result;
9+use crate::time::now_stamp;
10+
11+/// One stored attachment.
12+#[derive(Debug, Clone, Serialize)]
13+pub struct Attachment {
14+ pub id: String,
15+ pub repo_id: String,
16+ pub uploader_id: String,
17+ pub name: String,
18+ pub content_type: String,
19+ pub size: u64,
20+ pub sha256: String,
21+ pub created_at: String,
22+}
23+
24+impl Store {
25+ /// Records an attachment whose blob is already stored under `id`.
26+ #[allow(clippy::too_many_arguments)]
27+ pub async fn add_attachment(
28+ &self,
29+ id: &str,
30+ repo_id: &str,
31+ uploader_id: &str,
32+ name: &str,
33+ content_type: &str,
34+ size: u64,
35+ sha256: &str,
36+ ) -> Result<Attachment> {
37+ let created_at = now_stamp();
38+ let conn = self.inner.conn.lock().await;
39+ conn.execute(
40+ "INSERT INTO attachments (id, repo_id, uploader_id, name, content_type, size, sha256, created_at) \
41+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
42+ (
43+ id.to_string(),
44+ repo_id.to_string(),
45+ uploader_id.to_string(),
46+ name.to_string(),
47+ content_type.to_string(),
48+ i64::try_from(size).unwrap_or(i64::MAX),
49+ sha256.to_string(),
50+ created_at.clone(),
51+ ),
52+ )
53+ .await
54+ .map_err(db_err)?;
55+ Ok(Attachment {
56+ id: id.to_string(),
57+ repo_id: repo_id.to_string(),
58+ uploader_id: uploader_id.to_string(),
59+ name: name.to_string(),
60+ content_type: content_type.to_string(),
61+ size,
62+ sha256: sha256.to_string(),
63+ created_at,
64+ })
65+ }
66+
67+ /// The attachment `id`, if any. The caller checks the viewer can read `repo_id`.
68+ pub async fn attachment(&self, id: &str) -> Result<Option<Attachment>> {
69+ let conn = self.read_conn().await;
70+ fetch_opt(
71+ &conn,
72+ "SELECT id, repo_id, uploader_id, name, content_type, size, sha256, created_at \
73+ FROM attachments WHERE id = ?1",
74+ (id.to_string(),),
75+ |row| {
76+ Ok(Attachment {
77+ id: col_text(row, 0)?,
78+ repo_id: col_text(row, 1)?,
79+ uploader_id: col_text(row, 2)?,
80+ name: col_text(row, 3)?,
81+ content_type: col_text(row, 4)?,
82+ size: u64::try_from(col_int(row, 5)?).unwrap_or(0),
83+ sha256: col_text(row, 6)?,
84+ created_at: col_text(row, 7)?,
85+ })
86+ },
87+ )
88+ .await
89+ }
90+}
91+
92+#[cfg(test)]
93+mod tests {
94+ use super::*;
95+ use crate::model::Visibility;
96+
97+ #[tokio::test]
98+ async fn attachment_round_trips() {
99+ let dir = tempfile::tempdir().unwrap();
100+ let store = Store::open(&dir.path().join("forge.db")).await.unwrap();
101+ let tahinli = store
102+ .create_user("tahinli", None, "hash", false)
103+ .await
104+ .unwrap();
105+ let a = store
106+ .create_repo(&tahinli.id, "a", "", Visibility::Public, "main")
107+ .await
108+ .unwrap();
109+ store
110+ .add_attachment(
111+ "att1",
112+ &a.id,
113+ &tahinli.id,
114+ "shot.png",
115+ "image/png",
116+ 12,
117+ "abc",
118+ )
119+ .await
120+ .unwrap();
121+ let found = store.attachment("att1").await.unwrap().unwrap();
122+ assert_eq!(found.repo_id, a.id);
123+ assert_eq!(found.name, "shot.png");
124+ assert_eq!(found.size, 12);
125+ assert!(store.attachment("nope").await.unwrap().is_none());
126+ }
127+}
crates/forge-core/src/store/issues.rsmodified+7 -0
@@ -393,6 +393,13 @@ impl Store {
393 );393 );
394 params.push(Value::Text(normalize_name(assignee)));394 params.push(Value::Text(normalize_name(assignee)));
395 }395 }
396+ if let Some(reviewer) = non_empty(f.review_requested.as_deref()) {
397+ clauses.push(
398+ "EXISTS (SELECT 1 FROM review_requests rr JOIN users ur ON ur.id = rr.reviewer_id \
399+ WHERE rr.issue_id = i.id AND ur.username_folded = ?)",
400+ );
401+ params.push(Value::Text(normalize_name(reviewer)));
402+ }
396 if let Some(query) = non_empty(f.query.as_deref()) {403 if let Some(query) = non_empty(f.query.as_deref()) {
397 // Escape the LIKE wildcards and the escape character itself.404 // Escape the LIKE wildcards and the escape character itself.
398 clauses.push("i.title LIKE ? ESCAPE '\\'");405 clauses.push("i.title LIKE ? ESCAPE '\\'");
crates/forge-core/src/store/migrate.rsmodified+5 -0
@@ -82,6 +82,11 @@ pub const MIGRATIONS: &[(u32, &str)] = &[
82 ),82 ),
83 (50, include_str!("../../migrations/0050_imports.sql")),83 (50, include_str!("../../migrations/0050_imports.sql")),
84 (51, include_str!("../../migrations/0051_data_exports.sql")),84 (51, include_str!("../../migrations/0051_data_exports.sql")),
85+ (55, include_str!("../../migrations/0055_attachments.sql")),
86+ (
87+ 56,
88+ include_str!("../../migrations/0056_review_requests.sql"),
89+ ),
85 ];90 ];
86 91
87 /// The highest migration version this binary knows about.92 /// The highest migration version this binary knows about.
crates/forge-core/src/store/mod.rsmodified+3 -0
@@ -2,6 +2,7 @@
2 2
3 pub mod account_tokens;3 pub mod account_tokens;
4 pub mod advisories;4 pub mod advisories;
5+pub mod attachments;
5 pub mod audit;6 pub mod audit;
6 pub mod backup_runs;7 pub mod backup_runs;
7 pub mod ci;8 pub mod ci;
@@ -29,11 +30,13 @@ pub mod reactions;
29 pub mod releases;30 pub mod releases;
30 pub mod replication;31 pub mod replication;
31 pub mod repo_listing;32 pub mod repo_listing;
33+pub mod review_requests;
32 pub mod reviews;34 pub mod reviews;
33 pub mod server_settings;35 pub mod server_settings;
34 pub mod signatures;36 pub mod signatures;
35 pub mod snapshot;37 pub mod snapshot;
36 pub mod snippets;38 pub mod snippets;
39+pub mod suggest;
37 pub mod transfers;40 pub mod transfers;
38 pub mod ui_prefs;41 pub mod ui_prefs;
39 pub mod user_delete;42 pub mod user_delete;
crates/forge-core/src/store/review_requests.rsadded+179 -0
@@ -0,0 +1,179 @@
1+//! Review requests on pull requests: who was asked to review, by whom. A request is cleared when
2+//! the reviewer submits a review (`submit_review` does it in the same transaction) or when it is
3+//! withdrawn. Deleting a pull request removes its requests through the foreign key.
4+
5+use std::collections::HashMap;
6+
7+use super::{Store, col_text, db_err, fetch_all, fetch_opt};
8+use crate::error::Result;
9+use crate::time::now_stamp;
10+
11+/// A pending request as the global "Review requests" view lists it.
12+#[derive(Debug, Clone)]
13+pub struct ReviewRequestItem {
14+ pub repo_owner: String,
15+ pub repo_name: String,
16+ pub number: i64,
17+ pub title: String,
18+ pub requested_by: String,
19+ pub created_at: String,
20+}
21+
22+impl Store {
23+ /// Asks `reviewer_id` to review. Returns `false` when a request is already pending.
24+ pub async fn request_review(
25+ &self,
26+ issue_id: &str,
27+ reviewer_id: &str,
28+ requested_by: &str,
29+ ) -> Result<bool> {
30+ let conn = self.inner.conn.lock().await;
31+ let exists = fetch_opt(
32+ &conn,
33+ "SELECT 1 FROM review_requests WHERE issue_id = ?1 AND reviewer_id = ?2",
34+ (issue_id.to_string(), reviewer_id.to_string()),
35+ |row| col_text(row, 0).or(Ok(String::new())),
36+ )
37+ .await?;
38+ if exists.is_some() {
39+ return Ok(false);
40+ }
41+ conn.execute(
42+ "INSERT INTO review_requests (issue_id, reviewer_id, requested_by, created_at) \
43+ VALUES (?1, ?2, ?3, ?4)",
44+ (
45+ issue_id.to_string(),
46+ reviewer_id.to_string(),
47+ requested_by.to_string(),
48+ now_stamp(),
49+ ),
50+ )
51+ .await
52+ .map_err(db_err)?;
53+ Ok(true)
54+ }
55+
56+ /// Withdraws a pending request. Returns whether there was one.
57+ pub async fn withdraw_review_request(&self, issue_id: &str, reviewer_id: &str) -> Result<bool> {
58+ let conn = self.inner.conn.lock().await;
59+ let n = conn
60+ .execute(
61+ "DELETE FROM review_requests WHERE issue_id = ?1 AND reviewer_id = ?2",
62+ (issue_id.to_string(), reviewer_id.to_string()),
63+ )
64+ .await
65+ .map_err(db_err)?;
66+ Ok(n > 0)
67+ }
68+
69+ /// Usernames with a pending request on the pull request, oldest request first.
70+ pub async fn requested_reviewers(&self, issue_id: &str) -> Result<Vec<String>> {
71+ let mut map = self
72+ .requested_reviewers_for(std::slice::from_ref(&issue_id.to_string()))
73+ .await?;
74+ Ok(map.remove(issue_id).unwrap_or_default())
75+ }
76+
77+ /// Pending reviewer usernames for each of `ids`, in one query. Pulls without requests have
78+ /// no entry.
79+ pub async fn requested_reviewers_for(
80+ &self,
81+ ids: &[String],
82+ ) -> Result<HashMap<String, Vec<String>>> {
83+ let mut out: HashMap<String, Vec<String>> = HashMap::new();
84+ if ids.is_empty() {
85+ return Ok(out);
86+ }
87+ let conn = self.read_conn().await;
88+ for chunk in ids.chunks(500) {
89+ let marks = vec!["?"; chunk.len()].join(",");
90+ let rows = fetch_all(
91+ &conn,
92+ &format!(
93+ "SELECT rr.issue_id, u.username FROM review_requests rr \
94+ JOIN users u ON u.id = rr.reviewer_id \
95+ WHERE rr.issue_id IN ({marks}) ORDER BY rr.created_at, u.username_folded"
96+ ),
97+ chunk.to_vec(),
98+ |row| Ok((col_text(row, 0)?, col_text(row, 1)?)),
99+ )
100+ .await?;
101+ for (issue, name) in rows {
102+ out.entry(issue).or_default().push(name);
103+ }
104+ }
105+ Ok(out)
106+ }
107+
108+ /// Open pull requests where the user has a pending request, newest request first.
109+ pub async fn review_requests_for_user(&self, user_id: &str) -> Result<Vec<ReviewRequestItem>> {
110+ let conn = self.read_conn().await;
111+ fetch_all(
112+ &conn,
113+ "SELECT o.username, r.name, i.number, i.title, b.username, rr.created_at \
114+ FROM review_requests rr \
115+ JOIN issues i ON i.id = rr.issue_id AND i.state = 'open' AND i.kind = 'pull' \
116+ JOIN repos r ON r.id = i.repo_id \
117+ JOIN users o ON o.id = r.owner_id \
118+ JOIN users b ON b.id = rr.requested_by \
119+ WHERE rr.reviewer_id = ?1 ORDER BY rr.created_at DESC LIMIT 200",
120+ (user_id.to_string(),),
121+ |row| {
122+ Ok(ReviewRequestItem {
123+ repo_owner: col_text(row, 0)?,
124+ repo_name: col_text(row, 1)?,
125+ number: super::col_int(row, 2)?,
126+ title: col_text(row, 3)?,
127+ requested_by: col_text(row, 4)?,
128+ created_at: col_text(row, 5)?,
129+ })
130+ },
131+ )
132+ .await
133+ }
134+}
135+
136+#[cfg(test)]
137+mod tests {
138+ use super::*;
139+ use crate::model::Visibility;
140+
141+ #[tokio::test]
142+ async fn request_withdraw_and_list() {
143+ let dir = tempfile::tempdir().unwrap();
144+ let store = Store::open(&dir.path().join("forge.db")).await.unwrap();
145+ let tahinli = store
146+ .create_user("tahinli", None, "hash", false)
147+ .await
148+ .unwrap();
149+ let bob = store.create_user("bob", None, "hash", false).await.unwrap();
150+ let repo = store
151+ .create_repo(&tahinli.id, "proj", "", Visibility::Public, "main")
152+ .await
153+ .unwrap();
154+ let pr = store
155+ .create_issue(&repo.id, &tahinli.id, "pr", "")
156+ .await
157+ .unwrap();
158+ assert!(
159+ store
160+ .request_review(&pr.id, &bob.id, &tahinli.id)
161+ .await
162+ .unwrap()
163+ );
164+ assert!(
165+ !store
166+ .request_review(&pr.id, &bob.id, &tahinli.id)
167+ .await
168+ .unwrap()
169+ );
170+ assert_eq!(store.requested_reviewers(&pr.id).await.unwrap(), ["bob"]);
171+ assert!(
172+ store
173+ .withdraw_review_request(&pr.id, &bob.id)
174+ .await
175+ .unwrap()
176+ );
177+ assert!(store.requested_reviewers(&pr.id).await.unwrap().is_empty());
178+ }
179+}
crates/forge-core/src/store/reviews.rsmodified+7 -0
@@ -487,6 +487,13 @@ impl Store {
487 insert_review(&tx, issue_id, author_id, state, body, head_oid, &now).await?487 insert_review(&tx, issue_id, author_id, state, body, head_oid, &now).await?
488 }488 }
489 };489 };
490+ // A submitted review answers the author's own review request.
491+ tx.execute(
492+ "DELETE FROM review_requests WHERE issue_id = ?1 AND reviewer_id = ?2",
493+ (issue_id.to_string(), author_id.to_string()),
494+ )
495+ .await
496+ .map_err(db_err)?;
490 review_by_id(&tx, &id).await?.ok_or_else(missing_row)497 review_by_id(&tx, &id).await?.ok_or_else(missing_row)
491 }498 }
492 .await;499 .await;
crates/forge-core/src/store/suggest.rsadded+156 -0
@@ -0,0 +1,156 @@
1+//! Lookups behind the `@` and `#` autocomplete of the markdown editors.
2+
3+use turso::Value;
4+
5+use super::issues::like_pattern;
6+use super::{Store, col_int, col_text, fetch_all};
7+use crate::error::Result;
8+use crate::names::normalize_name;
9+
10+/// One `#` suggestion: an issue or pull request.
11+#[derive(Debug, Clone)]
12+pub struct IssueSuggestion {
13+ pub number: i64,
14+ pub title: String,
15+ pub is_pull: bool,
16+ pub open: bool,
17+}
18+
19+impl Store {
20+ /// Usernames starting with `prefix` (case-insensitive) that are people in the repo, nearest
21+ /// first: the owner and collaborators, then anyone who opened an issue or commented, then
22+ /// every other person account. At most `limit` names, no duplicates.
23+ pub async fn suggest_usernames(
24+ &self,
25+ repo_id: &str,
26+ prefix: &str,
27+ limit: usize,
28+ ) -> Result<Vec<String>> {
29+ let pattern = {
30+ let mut p = like_pattern(&normalize_name(prefix));
31+ p.remove(0);
32+ p
33+ };
34+ // `like_pattern` wraps in `%..%`; for a prefix match drop the leading one (done above).
35+ let cap = Value::Integer(i64::try_from(limit).unwrap_or(8));
36+ let queries = [
37+ // Owner and collaborators.
38+ "SELECT u.username FROM users u WHERE u.username_folded LIKE ?2 ESCAPE '\\' AND u.kind = 'user' AND \
39+ (u.id = (SELECT owner_id FROM repos WHERE id = ?1) OR \
40+ u.id IN (SELECT user_id FROM collaborators WHERE repo_id = ?1)) \
41+ ORDER BY u.username_folded LIMIT ?3",
42+ // Participants.
43+ "SELECT u.username FROM users u WHERE u.username_folded LIKE ?2 ESCAPE '\\' AND u.kind = 'user' AND \
44+ (u.id IN (SELECT author_id FROM issues WHERE repo_id = ?1) OR \
45+ u.id IN (SELECT c.author_id FROM comments c JOIN issues i ON i.id = c.issue_id WHERE i.repo_id = ?1)) \
46+ ORDER BY u.username_folded LIMIT ?3",
47+ // Everyone else.
48+ "SELECT u.username FROM users u WHERE u.username_folded LIKE ?2 ESCAPE '\\' AND u.kind = 'user' \
49+ AND u.username_folded <> 'ghost' ORDER BY u.username_folded LIMIT ?3",
50+ ];
51+ let conn = self.read_conn().await;
52+ let mut out: Vec<String> = Vec::new();
53+ for sql in queries {
54+ let names = fetch_all(
55+ &conn,
56+ sql,
57+ vec![
58+ Value::Text(repo_id.to_string()),
59+ Value::Text(pattern.clone()),
60+ cap.clone(),
61+ ],
62+ |row| col_text(row, 0),
63+ )
64+ .await?;
65+ for name in names {
66+ if out.len() < limit && !out.contains(&name) {
67+ out.push(name);
68+ }
69+ }
70+ }
71+ Ok(out)
72+ }
73+
74+ /// Issues and pull requests of the repo whose number starts with `q` (when it is digits) or
75+ /// whose title contains it. Newest first, at most `limit`.
76+ pub async fn suggest_issues(
77+ &self,
78+ repo_id: &str,
79+ q: &str,
80+ limit: u32,
81+ ) -> Result<Vec<IssueSuggestion>> {
82+ let q = q.trim();
83+ let (clause, param) = if !q.is_empty() && q.bytes().all(|b| b.is_ascii_digit()) {
84+ ("CAST(i.number AS TEXT) LIKE ? ESCAPE '\\'", format!("{q}%"))
85+ } else {
86+ ("i.title LIKE ? ESCAPE '\\'", like_pattern(q))
87+ };
88+ let conn = self.read_conn().await;
89+ fetch_all(
90+ &conn,
91+ &format!(
92+ "SELECT i.number, i.title, i.kind, i.state FROM issues i \
93+ WHERE i.repo_id = ? AND {clause} ORDER BY i.number DESC LIMIT ?"
94+ ),
95+ vec![
96+ Value::Text(repo_id.to_string()),
97+ Value::Text(param),
98+ Value::Integer(i64::from(limit.clamp(1, 20))),
99+ ],
100+ |row| {
101+ Ok(IssueSuggestion {
102+ number: col_int(row, 0)?,
103+ title: col_text(row, 1)?,
104+ is_pull: col_text(row, 2)? == "pull",
105+ open: col_text(row, 3)? == "open",
106+ })
107+ },
108+ )
109+ .await
110+ }
111+}
112+
113+#[cfg(test)]
114+mod tests {
115+ use super::*;
116+ use crate::model::Visibility;
117+
118+ #[tokio::test]
119+ async fn users_and_issues_are_suggested() {
120+ let dir = tempfile::tempdir().unwrap();
121+ let store = Store::open(&dir.path().join("forge.db")).await.unwrap();
122+ let tahinli = store
123+ .create_user("tahinli", None, "hash", false)
124+ .await
125+ .unwrap();
126+ let tanya = store
127+ .create_user("tanya", None, "hash", false)
128+ .await
129+ .unwrap();
130+ let _tam = store.create_user("tam", None, "hash", false).await.unwrap();
131+ let repo = store
132+ .create_repo(&tahinli.id, "proj", "", Visibility::Public, "main")
133+ .await
134+ .unwrap();
135+ let issue = store
136+ .create_issue(&repo.id, &tanya.id, "Fix the parser", "")
137+ .await
138+ .unwrap();
139+ store
140+ .create_issue(&repo.id, &tahinli.id, "Docs", "")
141+ .await
142+ .unwrap();
143+ // Owner first, then participant, then the rest.
144+ let names = store.suggest_usernames(&repo.id, "ta", 8).await.unwrap();
145+ assert_eq!(names, ["tahinli", "tanya", "tam"]);
146+ assert_eq!(
147+ store.suggest_usernames(&repo.id, "tan", 8).await.unwrap(),
148+ ["tanya"]
149+ );
150+ let by_title = store.suggest_issues(&repo.id, "parser", 8).await.unwrap();
151+ assert_eq!(by_title.len(), 1);
152+ assert_eq!(by_title[0].number, issue.number);
153+ let by_number = store.suggest_issues(&repo.id, "2", 8).await.unwrap();
154+ assert_eq!(by_number[0].title, "Docs");
155+ }
156+}
crates/forge-core/src/store/user_delete.rsmodified+8 -0
@@ -49,6 +49,13 @@ const NOT_DRAFT_EDIT: &str = " AND NOT (target_kind = 'review_comment' AND targe
49 /// appended to the `WHERE column = ?1` clause.49 /// appended to the `WHERE column = ?1` clause.
50 const REASSIGNED: &[(&str, &str, &str, &str)] = &[50 const REASSIGNED: &[(&str, &str, &str, &str)] = &[
51 ("issues", "issues", "author_id", ""),51 ("issues", "issues", "author_id", ""),
52+ ("attachments", "attachments", "uploader_id", ""),
53+ (
54+ "review requests sent",
55+ "review_requests",
56+ "requested_by",
57+ "",
58+ ),
52 ("comments", "comments", "author_id", ""),59 ("comments", "comments", "author_id", ""),
53 ("edits", "edit_history", "editor_id", NOT_DRAFT_EDIT),60 ("edits", "edit_history", "editor_id", NOT_DRAFT_EDIT),
54 ("timeline events", "issue_events", "actor_id", ""),61 ("timeline events", "issue_events", "actor_id", ""),
@@ -128,6 +135,7 @@ const REMOVED: &[(&str, &str, &str)] = &[
128 "user_id",135 "user_id",
129 ),136 ),
130 ("reactions", "reactions", "user_id"),137 ("reactions", "reactions", "user_id"),
138+ ("review requests", "review_requests", "reviewer_id"),
131 ];139 ];
132 140
133 /// What a deletion did, or would do: row counts per kind, in the order the lists above give.141 /// What a deletion did, or would do: row counts per kind, in the order the lists above give.
crates/forge-web/assets/nav.jsmodified+310 -0
@@ -1376,4 +1376,314 @@
1376 // been updated (observer callbacks run after the swap function returns).1376 // been updated (observer callbacks run after the swap function returns).
1377 new MutationObserver(function () { applyLines(true); }).observe(document.body, { childList: true });1377 new MutationObserver(function () { applyLines(true); }).observe(document.body, { childList: true });
1378 applyLines(true);1378 applyLines(true);
1379+
1380+// Authoring helpers for markdown textareas: attach (button, paste, drop), `@` and `#` autocomplete,
1381+// and clickable task lists. Everything is delegated or re-applied from a MutationObserver on the
1382+// body, so it survives soft navigation swaps. Nothing polls.
1383+(function () {
1384+ 'use strict';
1385+ if (window.__forgeAuthoring) { return; }
1386+ window.__forgeAuthoring = true;
1387+
1388+ var TR = (document.documentElement.getAttribute('lang') || '').indexOf('tr') === 0;
1389+ var T = TR
1390+ ? { 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' }
1391+ : { 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' };
1392+
1393+ // Repo pages whose textareas take markdown. `/owner/repo/section/...`
1394+ var REPO_PATH = /^\/([^\/]+)\/([^\/]+)\/(issues|pulls|discussions|wiki|compare|releases)(\/|$)/;
1395+ var NAMES = { body: 1, content: 1, message: 1 };
1396+
1397+ function repoBase() {
1398+ var m = REPO_PATH.exec(location.pathname);
1399+ return m ? '/' + m[1] + '/' + m[2] : null;
1400+ }
1401+
1402+ function eligible(el) {
1403+ return el && el.tagName === 'TEXTAREA' && NAMES[el.name] && !el.readOnly && !!repoBase() && !!csrfOf(el);
1404+ }
1405+
1406+ function csrfOf(el) {
1407+ var f = el.form;
1408+ var c = f ? f.querySelector('input[name=csrf]') : null;
1409+ return c ? c.value : '';
1410+ }
1411+
1412+ // ---- toolbar and upload ----
1413+
1414+ function enhance() {
1415+ document.querySelectorAll('textarea').forEach(function (ta) {
1416+ if (ta.__md || !eligible(ta)) { return; }
1417+ ta.__md = true;
1418+ var bar = document.createElement('div');
1419+ bar.className = 'md-tools';
1420+ var btn = document.createElement('button');
1421+ btn.type = 'button';
1422+ btn.className = 'link-button md-attach';
1423+ btn.textContent = T.attach;
1424+ btn.title = T.title;
1425+ var status = document.createElement('span');
1426+ status.className = 'md-status muted small';
1427+ status.setAttribute('role', 'status');
1428+ var file = document.createElement('input');
1429+ file.type = 'file';
1430+ file.hidden = true;
1431+ file.multiple = true;
1432+ file.setAttribute('aria-hidden', 'true');
1433+ file.tabIndex = -1;
1434+ var list = document.createElement('ul');
1435+ list.className = 'md-suggest';
1436+ list.setAttribute('role', 'listbox');
1437+ list.hidden = true;
1438+ bar.appendChild(btn);
1439+ bar.appendChild(status);
1440+ bar.appendChild(file);
1441+ bar.appendChild(list);
1442+ ta.insertAdjacentElement('afterend', bar);
1443+ ta.__bar = bar;
1444+ btn.addEventListener('click', function () { file.click(); });
1445+ file.addEventListener('change', function () {
1446+ Array.prototype.forEach.call(file.files, function (f) { upload(ta, f); });
1447+ file.value = '';
1448+ });
1449+ });
1450+ enableTasks();
1451+ }
1452+
1453+ function say(ta, text, bad) {
1454+ var s = ta.__bar && ta.__bar.querySelector('.md-status');
1455+ if (!s) { return; }
1456+ s.textContent = text;
1457+ s.classList.toggle('md-status-bad', !!bad);
1458+ }
1459+
1460+ function insertAtCaret(ta, text) {
1461+ var start = ta.selectionStart == null ? ta.value.length : ta.selectionStart;
1462+ var end = ta.selectionEnd == null ? start : ta.selectionEnd;
1463+ var before = ta.value.slice(0, start);
1464+ var lead = before && !/\n$/.test(before) ? '\n' : '';
1465+ var ins = lead + text + '\n';
1466+ ta.value = before + ins + ta.value.slice(end);
1467+ var pos = start + ins.length;
1468+ ta.setSelectionRange(pos, pos);
1469+ ta.dispatchEvent(new Event('input', { bubbles: true }));
1470+ ta.focus();
1471+ }
1472+
1473+ function upload(ta, file) {
1474+ var base = repoBase();
1475+ if (!base) { return; }
1476+ var fd = new FormData();
1477+ fd.append('csrf', csrfOf(ta));
1478+ var name = file.name || 'image.png';
1479+ fd.append('file', file, name);
1480+ say(ta, T.up + ' ' + name + '...');
1481+ fetch(base + '/attachments', { method: 'POST', body: fd, headers: { accept: 'application/json' } })
1482+ .then(function (r) {
1483+ return r.json().catch(function () { return {}; }).then(function (j) { return { ok: r.ok, j: j }; });
1484+ })
1485+ .then(function (res) {
1486+ if (!res.ok || !res.j.markdown) { throw new Error(res.j.error || T.fail); }
1487+ insertAtCaret(ta, res.j.markdown);
1488+ say(ta, '');
1489+ })
1490+ .catch(function (err) { say(ta, T.fail + ': ' + (err && err.message ? err.message : ''), true); });
1491+ }
1492+
1493+ document.addEventListener('paste', function (e) {
1494+ var ta = e.target;
1495+ if (!ta || !ta.__md || !e.clipboardData) { return; }
1496+ var files = Array.prototype.filter.call(e.clipboardData.files || [], function (f) { return f.size > 0; });
1497+ if (!files.length) { return; }
1498+ e.preventDefault();
1499+ files.forEach(function (f) { upload(ta, f); });
1500+ });
1501+
1502+ document.addEventListener('dragover', function (e) {
1503+ var ta = e.target;
1504+ if (ta && ta.__md && e.dataTransfer && Array.prototype.indexOf.call(e.dataTransfer.types || [], 'Files') >= 0) {
1505+ e.preventDefault();
1506+ ta.classList.add('md-drop');
1507+ }
1508+ });
1509+ document.addEventListener('dragleave', function (e) {
1510+ if (e.target && e.target.classList) { e.target.classList.remove('md-drop'); }
1511+ });
1512+ document.addEventListener('drop', function (e) {
1513+ var ta = e.target;
1514+ if (!ta || !ta.__md || !e.dataTransfer || !e.dataTransfer.files.length) { return; }
1515+ e.preventDefault();
1516+ ta.classList.remove('md-drop');
1517+ Array.prototype.forEach.call(e.dataTransfer.files, function (f) { upload(ta, f); });
1518+ });
1519+
1520+ // ---- autocomplete ----
1521+
1522+ var active = null; // { el, kind, items, index, from, to }
1523+ var reqId = 0;
1524+
1525+ function closeSuggest() {
1526+ if (active && active.list) { active.list.hidden = true; active.list.replaceChildren(); }
1527+ active = null;
1528+ }
1529+
1530+ // The trigger just before the caret: `@name` or `#12` at a word start.
1531+ function trigger(ta) {
1532+ var pos = ta.selectionStart;
1533+ if (pos == null) { return null; }
1534+ var before = ta.value.slice(0, pos);
1535+ var m = /(^|[\s(])([@#])([\w.\-]*)$/.exec(before);
1536+ if (!m) { return null; }
1537+ var q = m[3];
1538+ return { kind: m[2] === '@' ? 'user' : 'issue', q: q, from: pos - q.length - 1, to: pos };
1539+ }
1540+
1541+ function render(state) {
1542+ var list = state.list;
1543+ list.replaceChildren();
1544+ state.items.forEach(function (it, i) {
1545+ var li = document.createElement('li');
1546+ li.setAttribute('role', 'option');
1547+ li.className = i === state.index ? 'md-suggest-item active' : 'md-suggest-item';
1548+ li.setAttribute('aria-selected', i === state.index ? 'true' : 'false');
1549+ var strong = document.createElement('strong');
1550+ var rest = document.createElement('span');
1551+ rest.className = 'muted small';
1552+ if (state.kind === 'user') {
1553+ strong.textContent = '@' + it.login;
1554+ rest.textContent = it.name || '';
1555+ } else {
1556+ strong.textContent = '#' + it.number;
1557+ rest.textContent = it.title + (it.pull ? ' (PR)' : '');
1558+ }
1559+ li.appendChild(strong);
1560+ li.appendChild(document.createTextNode(' '));
1561+ li.appendChild(rest);
1562+ li.addEventListener('mousedown', function (ev) { ev.preventDefault(); choose(state, i); });
1563+ list.appendChild(li);
1564+ });
1565+ list.hidden = state.items.length === 0;
1566+ }
1567+
1568+ function choose(state, i) {
1569+ var it = state.items[i];
1570+ if (!it) { return; }
1571+ var el = state.el;
1572+ var text = state.kind === 'user' ? '@' + it.login + ' ' : '#' + it.number + ' ';
1573+ if (state.whole) {
1574+ el.value = it.login;
1575+ } else {
1576+ el.value = el.value.slice(0, state.from) + text + el.value.slice(state.to);
1577+ var pos = state.from + text.length;
1578+ el.setSelectionRange(pos, pos);
1579+ }
1580+ closeSuggest();
1581+ el.__skip = true; // the input event below is ours: it must not reopen the list
1582+ el.dispatchEvent(new Event('input', { bubbles: true }));
1583+ el.focus();
1584+ }
1585+
1586+ function ask(el, kind, q, from, to, whole, list) {
1587+ var base = repoBase();
1588+ if (!base) { return; }
1589+ var id = ++reqId;
1590+ fetch(base + '/suggest?kind=' + kind + '&q=' + encodeURIComponent(q), { headers: { accept: 'application/json' } })
1591+ .then(function (r) { return r.ok ? r.json() : []; })
1592+ .then(function (items) {
1593+ if (id !== reqId || document.activeElement !== el) { return; }
1594+ active = { el: el, kind: kind, items: items, index: 0, from: from, to: to, whole: whole, list: list };
1595+ render(active);
1596+ })
1597+ .catch(function () { closeSuggest(); });
1598+ }
1599+
1600+ document.addEventListener('input', function (e) {
1601+ var el = e.target;
1602+ if (!el) { return; }
1603+ if (el.__skip) { el.__skip = false; return; }
1604+ if (el.tagName === 'INPUT' && el.getAttribute('data-suggest') === 'user') {
1605+ if (!repoBase()) { return; }
1606+ if (!el.__list) {
1607+ var l = document.createElement('ul');
1608+ l.className = 'md-suggest md-suggest-input';
1609+ l.setAttribute('role', 'listbox');
1610+ l.hidden = true;
1611+ el.insertAdjacentElement('afterend', l);
1612+ el.__list = l;
1613+ }
1614+ if (!el.value.trim()) { closeSuggest(); return; }
1615+ ask(el, 'user', el.value.trim().replace(/^@/, ''), 0, el.value.length, true, el.__list);
1616+ return;
1617+ }
1618+ if (!el.__md) { return; }
1619+ var t = trigger(el);
1620+ if (!t) { closeSuggest(); return; }
1621+ ask(el, t.kind, t.q, t.from, t.to, false, el.__bar.querySelector('.md-suggest'));
1622+ });
1623+
1624+ document.addEventListener('keydown', function (e) {
1625+ if (!active || e.target !== active.el || !active.items.length) { return; }
1626+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
1627+ e.preventDefault();
1628+ var n = active.items.length;
1629+ active.index = (active.index + (e.key === 'ArrowDown' ? 1 : n - 1)) % n;
1630+ render(active);
1631+ } else if (e.key === 'Enter' || e.key === 'Tab') {
1632+ e.preventDefault();
1633+ choose(active, active.index);
1634+ } else if (e.key === 'Escape') {
1635+ e.preventDefault();
1636+ closeSuggest();
1637+ }
1638+ });
1639+
1640+ document.addEventListener('focusout', function (e) {
1641+ if (active && e.target === active.el) { closeSuggest(); }
1642+ });
1643+
1644+ // ---- task lists ----
1645+
1646+ function enableTasks() {
1647+ document.querySelectorAll('.markdown-body[data-task-action] li > input[type=checkbox]:first-child').forEach(function (cb) {
1648+ cb.disabled = false;
1649+ cb.classList.add('task-toggle');
1650+ });
1651+ }
1652+
1653+ document.addEventListener('change', function (e) {
1654+ var cb = e.target;
1655+ if (!cb || !cb.classList || !cb.classList.contains('task-toggle')) { return; }
1656+ var box = cb.closest('.markdown-body[data-task-action]');
1657+ if (!box) { return; }
1658+ var all = box.querySelectorAll('li > input[type=checkbox]:first-child');
1659+ var index = Array.prototype.indexOf.call(all, cb);
1660+ var want = cb.checked;
1661+ var body = new URLSearchParams();
1662+ body.set('csrf', box.getAttribute('data-csrf') || '');
1663+ body.set('kind', box.getAttribute('data-task-kind') || '');
1664+ body.set('id', box.getAttribute('data-task-id') || '');
1665+ body.set('index', String(index));
1666+ body.set('checked', want ? '1' : '0');
1667+ cb.disabled = true;
1668+ fetch(box.getAttribute('data-task-action'), {
1669+ method: 'POST',
1670+ headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
1671+ body: body.toString()
1672+ }).then(function (r) {
1673+ if (!r.ok) { throw new Error('task'); }
1674+ }).catch(function () {
1675+ cb.checked = !want;
1676+ cb.title = T.taskFail;
1677+ }).then(function () { cb.disabled = false; });
1678+ });
1679+
1680+ // ---- keep it applied ----
1681+
1682+ var scheduled = false;
1683+ new MutationObserver(function () {
1684+ if (scheduled) { return; }
1685+ scheduled = true;
1686+ Promise.resolve().then(function () { scheduled = false; enhance(); });
1687+ }).observe(document.body, { childList: true, subtree: true });
1688+ enhance();
1379 })();1689 })();
crates/forge-web/src/blobs.rsmodified+5 -0
@@ -33,6 +33,11 @@ pub fn asset_key(asset_id: &str) -> String {
33 format!("assets/{asset_id}")33 format!("assets/{asset_id}")
34 }34 }
35 35
36+/// The object key of a markdown attachment.
37+pub fn attachment_key(attachment_id: &str) -> String {
38+ format!("attachments/{attachment_id}")
39+}
40+
36 fn storage_err<E>(e: E) -> Error41 fn storage_err<E>(e: E) -> Error
37 where42 where
38 E: std::error::Error + Send + Sync + 'static,43 E: std::error::Error + Send + Sync + 'static,
crates/forge-web/src/i18n/authoring.rsadded+75 -0
@@ -0,0 +1,75 @@
1+//! Strings for the authoring helpers: attachments, autocomplete, task lists and review requests.
2+
3+use super::Lang;
4+
5+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6+pub enum K {
7+ Reviewers,
8+ NoReviewers,
9+ RequestReview,
10+ ReviewerName,
11+ WithdrawRequest,
12+ ReviewRequests,
13+ NoReviewRequests,
14+ ReviewerUnknown,
15+ ReviewerNoAccess,
16+ ReviewerIsAuthor,
17+ ReviewerAlready,
18+ ReviewRequestsTab,
19+}
20+
21+pub fn t(lang: Lang, key: K) -> &'static str {
22+ use K::*;
23+ use Lang::*;
24+ match (key, lang) {
25+ (Reviewers, En) => "Reviewers",
26+ (Reviewers, Tr) => "İnceleyenler",
27+ (NoReviewers, En) => "No review requested",
28+ (NoReviewers, Tr) => "İnceleme istenmedi",
29+ (RequestReview, En) => "Request review",
30+ (RequestReview, Tr) => "İnceleme iste",
31+ (ReviewerName, En) => "Username",
32+ (ReviewerName, Tr) => "Kullanıcı adı",
33+ (WithdrawRequest, En) => "Withdraw request",
34+ (WithdrawRequest, Tr) => "İsteği geri çek",
35+ (ReviewRequests, En) => "Review requests",
36+ (ReviewRequests, Tr) => "İnceleme istekleri",
37+ (NoReviewRequests, En) => "Nobody is waiting for your review.",
38+ (NoReviewRequests, Tr) => "İncelemenizi bekleyen yok.",
39+ (ReviewerUnknown, En) => "No such user.",
40+ (ReviewerUnknown, Tr) => "Böyle bir kullanıcı yok.",
41+ (ReviewerNoAccess, En) => "That user cannot read this repository.",
42+ (ReviewerNoAccess, Tr) => "Bu kullanıcı bu depoyu okuyamaz.",
43+ (ReviewerIsAuthor, En) => "The author cannot review their own pull request.",
44+ (ReviewerIsAuthor, Tr) => "Yazar kendi değişiklik isteğini inceleyemez.",
45+ (ReviewerAlready, En) => "A review is already requested from that user.",
46+ (ReviewerAlready, Tr) => "Bu kullanıcıdan zaten inceleme istendi.",
47+ (ReviewRequestsTab, En) => "Review requests",
48+ (ReviewRequestsTab, Tr) => "İnceleme istekleri",
49+ }
50+}
51+
52+/// "2 of 5 tasks".
53+pub fn tasks_progress(lang: Lang, done: usize, total: usize) -> String {
54+ match lang {
55+ Lang::En => format!("{done} of {total} tasks"),
56+ Lang::Tr => format!("{done}/{total} görev"),
57+ }
58+}
59+
60+/// Title text of a request on a list row: "Review requested from tahinli, bob".
61+pub fn requested_from(lang: Lang, names: &[String]) -> String {
62+ let joined = names.join(", ");
63+ match lang {
64+ Lang::En => format!("Review requested from {joined}"),
65+ Lang::Tr => format!("İnceleme istenen: {joined}"),
66+ }
67+}
68+
69+/// "requested by tahinli".
70+pub fn requested_by(lang: Lang, name: &str) -> String {
71+ match lang {
72+ Lang::En => format!("requested by {name}"),
73+ Lang::Tr => format!("{name} istedi"),
74+ }
75+}
crates/forge-web/src/i18n/mod.rsmodified+5 -0
@@ -20,6 +20,7 @@ use forge_core::User;
20 pub mod accents;20 pub mod accents;
21 pub mod admin;21 pub mod admin;
22 pub mod browse;22 pub mod browse;
23+pub mod authoring;
23 pub mod code;24 pub mod code;
24 pub mod community;25 pub mod community;
25 pub mod integrations;26 pub mod integrations;
@@ -308,6 +309,7 @@ pub enum Key {
308 MailVerbMerged,309 MailVerbMerged,
309 MailVerbReviewed,310 MailVerbReviewed,
310 MailVerbAssigned,311 MailVerbAssigned,
312+ MailVerbReviewRequested,
311 MailVerbPushed,313 MailVerbPushed,
312 MailVerbMentioned,314 MailVerbMentioned,
313 MailSomeone,315 MailSomeone,
@@ -514,6 +516,7 @@ pub const ALL: &[Key] = &[
514 Key::MailVerbMerged,516 Key::MailVerbMerged,
515 Key::MailVerbReviewed,517 Key::MailVerbReviewed,
516 Key::MailVerbAssigned,518 Key::MailVerbAssigned,
519+ Key::MailVerbReviewRequested,
517 Key::MailVerbPushed,520 Key::MailVerbPushed,
518 Key::MailVerbMentioned,521 Key::MailVerbMentioned,
519 Key::MailSomeone,522 Key::MailSomeone,
@@ -997,6 +1000,8 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
997 (MailVerbReopened, En) => "reopened this",1000 (MailVerbReopened, En) => "reopened this",
998 (MailVerbMerged, En) => "merged this",1001 (MailVerbMerged, En) => "merged this",
999 (MailVerbReviewed, En) => "reviewed this",1002 (MailVerbReviewed, En) => "reviewed this",
1003+ (MailVerbReviewRequested, En) => "requested your review on this",
1004+ (MailVerbReviewRequested, Tr) => "bunun için incelemenizi istedi",
1000 (MailVerbAssigned, En) => "assigned you to this",1005 (MailVerbAssigned, En) => "assigned you to this",
1001 (MailVerbPushed, En) => "pushed new commits",1006 (MailVerbPushed, En) => "pushed new commits",
1002 (MailVerbMentioned, En) => "mentioned you",1007 (MailVerbMentioned, En) => "mentioned you",
crates/forge-web/src/mail/templates.rsmodified+2 -0
@@ -16,6 +16,7 @@ pub enum Verb {
16 Merged,16 Merged,
17 Reviewed,17 Reviewed,
18 AssignedYou,18 AssignedYou,
19+ ReviewRequested,
19 Pushed,20 Pushed,
20 MentionedYou,21 MentionedYou,
21 }22 }
@@ -83,6 +84,7 @@ fn verb_key(verb: Verb) -> Key {
83 Verb::Merged => Key::MailVerbMerged,84 Verb::Merged => Key::MailVerbMerged,
84 Verb::Reviewed => Key::MailVerbReviewed,85 Verb::Reviewed => Key::MailVerbReviewed,
85 Verb::AssignedYou => Key::MailVerbAssigned,86 Verb::AssignedYou => Key::MailVerbAssigned,
87+ Verb::ReviewRequested => Key::MailVerbReviewRequested,
86 Verb::Pushed => Key::MailVerbPushed,88 Verb::Pushed => Key::MailVerbPushed,
87 Verb::MentionedYou => Key::MailVerbMentioned,89 Verb::MentionedYou => Key::MailVerbMentioned,
88 }90 }
crates/forge-web/src/notify.rsmodified+42 -1
@@ -34,6 +34,10 @@ pub enum Activity {
34 Assigned {34 Assigned {
35 assignee_id: String,35 assignee_id: String,
36 },36 },
37+ /// The user with `reviewer_id` was asked to review.
38+ ReviewRequested {
39+ reviewer_id: String,
40+ },
37 /// The pull request head moved.41 /// The pull request head moved.
38 Pushed,42 Pushed,
39 /// The body or a comment was edited. Only newly mentioned users hear about it.43 /// The body or a comment was edited. Only newly mentioned users hear about it.
@@ -51,6 +55,7 @@ impl Activity {
51 Activity::Merged => "merged",55 Activity::Merged => "merged",
52 Activity::Review => "review",56 Activity::Review => "review",
53 Activity::Assigned { .. } => "assigned",57 Activity::Assigned { .. } => "assigned",
58+ Activity::ReviewRequested { .. } => "review_requested",
54 Activity::Pushed => "pushed",59 Activity::Pushed => "pushed",
55 Activity::Edited => "edited",60 Activity::Edited => "edited",
56 }61 }
@@ -144,6 +149,20 @@ pub async fn dispatch_assigned(
144 }149 }
145 }150 }
146 151
152+/// Tells `reviewer_id` that `actor_id` asked for their review of the pull request. Never fails.
153+pub async fn dispatch_review_requested(
154+ state: &AppState,
155+ repo: &Repo,
156+ issue: &Issue,
157+ actor_id: &str,
158+ reviewer_id: &str,
159+) {
160+ let activity = Activity::ReviewRequested {
161+ reviewer_id: reviewer_id.to_owned(),
162+ };
163+ dispatch(state, repo, issue, actor_id, activity, None).await;
164+}
165+
147 /// Tells the admins of `repo` that a lockfile scan opened `opened` security alerts on it. The166 /// Tells the admins of `repo` that a lockfile scan opened `opened` security alerts on it. The
148 /// admins are the owner (for an organization, its owners) and the collaborators with the Admin167 /// admins are the owner (for an organization, its owners) and the collaborators with the Admin
149 /// role. Writes inbox rows only. Never fails: problems are logged.168 /// role. Writes inbox rows only. Never fails: problems are logged.
@@ -287,7 +306,10 @@ async fn run(
287 let mut candidates: BTreeMap<String, Reason> = BTreeMap::new();306 let mut candidates: BTreeMap<String, Reason> = BTreeMap::new();
288 let mut mentioned: BTreeSet<String> = BTreeSet::new();307 let mut mentioned: BTreeSet<String> = BTreeSet::new();
289 308
290- if *activity != Activity::Edited {309+ if !matches!(
310+ activity,
311+ Activity::Edited | Activity::ReviewRequested { .. }
312+ ) {
291 for (user_id, stored) in store.subscribers(issue_id).await? {313 for (user_id, stored) in store.subscribers(issue_id).await? {
292 let reason = if activity.changes_state() {314 let reason = if activity.changes_state() {
293 strongest(stored, Reason::StateChange)315 strongest(stored, Reason::StateChange)
@@ -312,6 +334,17 @@ async fn run(
312 }334 }
313 }335 }
314 336
337+ // A review request reaches the reviewer only, not the thread's other subscribers.
338+ if let Activity::ReviewRequested { reviewer_id } = activity
339+ && !is_ignored(state, reviewer_id, issue_id).await?
340+ {
341+ add(
342+ &mut candidates,
343+ reviewer_id.clone(),
344+ Reason::ReviewRequested,
345+ );
346+ }
347+
315 // Mentions reach the user whatever their watch level or subscription.348 // Mentions reach the user whatever their watch level or subscription.
316 for name in mentions {349 for name in mentions {
317 if let Some(user) = store.user_by_username(name).await? {350 if let Some(user) = store.user_by_username(name).await? {
@@ -358,6 +391,13 @@ async fn run(
358 .auto_subscribe(assignee_id, issue_id, Reason::Assign)391 .auto_subscribe(assignee_id, issue_id, Reason::Assign)
359 .await?;392 .await?;
360 }393 }
394+ if let Activity::ReviewRequested { reviewer_id } = activity
395+ && readable_user(state, repo, reviewer_id).await?.is_some()
396+ {
397+ store
398+ .auto_subscribe(reviewer_id, issue_id, Reason::ReviewRequested)
399+ .await?;
400+ }
361 for user_id in &mentioned {401 for user_id in &mentioned {
362 if readable_user(state, repo, user_id).await?.is_some() {402 if readable_user(state, repo, user_id).await?.is_some() {
363 store403 store
@@ -469,6 +509,7 @@ fn verb_for(activity: &Activity) -> Verb {
469 Activity::Merged => Verb::Merged,509 Activity::Merged => Verb::Merged,
470 Activity::Review => Verb::Reviewed,510 Activity::Review => Verb::Reviewed,
471 Activity::Assigned { .. } => Verb::AssignedYou,511 Activity::Assigned { .. } => Verb::AssignedYou,
512+ Activity::ReviewRequested { .. } => Verb::ReviewRequested,
472 Activity::Pushed => Verb::Pushed,513 Activity::Pushed => Verb::Pushed,
473 Activity::Edited => Verb::MentionedYou,514 Activity::Edited => Verb::MentionedYou,
474 }515 }
crates/forge-web/src/pages/authoring.rsadded+406 -0
@@ -0,0 +1,406 @@
1+//! Helpers behind the markdown editors: attachment upload and download, the `@` and `#`
2+//! suggestion endpoint, and task-list checkbox toggles.
3+//!
4+//! * `POST /{owner}/{repo}/attachments` takes a multipart body (`csrf` first, then `file`) and
5+//! answers JSON with the markdown to insert. Bytes go to blob storage under `attachments/<id>`.
6+//! * `GET /attachments/{id}/{name}` serves the file if the viewer can read the repo it was
7+//! uploaded to. Images show inline; every other type downloads. `nosniff` and a locked-down CSP
8+//! are always set.
9+//! * `GET /{owner}/{repo}/suggest?kind=user|issue&q=..` returns up to eight matches as JSON.
10+//! * `POST /{owner}/{repo}/issues|pulls/{n}/tasks` flips one `- [ ]` item in a body or comment.
11+
12+use futures_util::TryStreamExt;
13+use http::header::{CONTENT_DISPOSITION, CONTENT_LENGTH, CONTENT_TYPE};
14+use http_body::Frame;
15+use http_body_util::StreamBody;
16+use serde::Deserialize;
17+use serde_json::json;
18+use topcoat::Result;
19+use topcoat::context::{Cx, app_context};
20+use topcoat::router::content::Form;
21+use topcoat::router::error::{bad_request, forbidden, not_found};
22+use topcoat::router::request::{headers, uri};
23+use topcoat::router::response::Response;
24+use topcoat::router::{Body, HeaderName, HeaderValue, StatusCode, path_param, route};
25+
26+use forge_core::authz::{Action, authorize};
27+
28+use crate::api;
29+use crate::auth::{current_user, require_csrf};
30+use crate::blobs::attachment_key;
31+use crate::pages::issue_parts::{ItemKind, comment_for, item_for, may_change, parse_number};
32+use crate::pages::repo_ctx::load_repo;
33+use crate::render::markdown::{set_task, task_progress};
34+use crate::state::AppState;
35+
36+path_param!(owner);
37+path_param!(repo);
38+path_param!(number);
39+path_param!(id);
40+path_param!(name);
41+
42+/// Largest accepted attachment, in bytes.
43+pub const MAX_ATTACHMENT_BYTES: u64 = 10 * 1024 * 1024;
44+/// Allowance for the multipart framing around the file.
45+const MULTIPART_OVERHEAD: u64 = 64 * 1024;
46+/// Longest stored file name, in characters.
47+const MAX_NAME_CHARS: usize = 100;
48+
49+/// The content type served for a file extension, and whether it may be shown inline. `None` for
50+/// types that are not accepted. The type comes from the extension, never from the client.
51+fn type_for(name: &str) -> Option<(&'static str, bool)> {
52+ let ext = name.rsplit_once('.')?.1.to_ascii_lowercase();
53+ Some(match ext.as_str() {
54+ "png" => ("image/png", true),
55+ "jpg" | "jpeg" => ("image/jpeg", true),
56+ "gif" => ("image/gif", true),
57+ "webp" => ("image/webp", true),
58+ "pdf" => ("application/pdf", false),
59+ "txt" | "log" | "md" | "patch" | "diff" => ("text/plain; charset=utf-8", false),
60+ "csv" => ("text/csv; charset=utf-8", false),
61+ "json" => ("application/json", false),
62+ "zip" => ("application/zip", false),
63+ "gz" | "tgz" => ("application/gzip", false),
64+ _ => return None,
65+ })
66+}
67+
68+/// A file name safe in a URL path and a header: ASCII letters, digits and `. _ - +`, everything
69+/// else becomes `_`, cut to `MAX_NAME_CHARS`, never starting with a dot.
70+pub fn clean_name(raw: &str) -> String {
71+ let base = raw.rsplit(['/', '\\']).next().unwrap_or(raw);
72+ let mut out: String = base
73+ .chars()
74+ .take(MAX_NAME_CHARS)
75+ .map(|c| {
76+ if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-' | '+') {
77+ c
78+ } else {
79+ '_'
80+ }
81+ })
82+ .collect();
83+ while out.starts_with('.') {
84+ out.remove(0);
85+ }
86+ out
87+}
88+
89+/// Decodes `%XX` escapes and `+` in a query value; invalid escapes are kept as typed.
90+fn percent_decode(input: &str) -> String {
91+ let bytes = input.as_bytes();
92+ let mut out = Vec::with_capacity(bytes.len());
93+ let mut i = 0;
94+ while i < bytes.len() {
95+ match bytes[i] {
96+ b'+' => out.push(b' '),
97+ b'%' if i + 2 < bytes.len() => {
98+ let hex = std::str::from_utf8(&bytes[i + 1..i + 3])
99+ .ok()
100+ .and_then(|h| u8::from_str_radix(h, 16).ok());
101+ match hex {
102+ Some(b) => {
103+ out.push(b);
104+ i += 2;
105+ }
106+ None => out.push(b'%'),
107+ }
108+ }
109+ b => out.push(b),
110+ }
111+ i += 1;
112+ }
113+ String::from_utf8_lossy(&out).into_owned()
114+}
115+
116+fn fail(status: StatusCode, message: &str) -> Response {
117+ api::error(status, message)
118+}
119+
120+/// Stores an uploaded file for a repo. The viewer needs a session and read access (anyone who can
121+/// comment can attach), and the repo must not be archived.
122+#[route(POST "/{owner}/{repo}/attachments")]
123+async fn upload(cx: &Cx, body: Body) -> Result<Response> {
124+ let ctx = load_repo(cx, path_param::<Owner>(cx), path_param::<Repo>(cx)).await?;
125+ let state = app_context::<AppState>(cx);
126+ if ctx.repo.archived {
127+ return Err(forbidden().into());
128+ }
129+ let declared = headers(cx)
130+ .get(CONTENT_LENGTH)
131+ .and_then(|v| v.to_str().ok())
132+ .and_then(|v| v.parse::<u64>().ok());
133+ if declared.is_some_and(|len| len > MAX_ATTACHMENT_BYTES + MULTIPART_OVERHEAD) {
134+ return Ok(fail(StatusCode::PAYLOAD_TOO_LARGE, "file too large"));
135+ }
136+ let content_type = headers(cx)
137+ .get(CONTENT_TYPE)
138+ .and_then(|v| v.to_str().ok())
139+ .unwrap_or("")
140+ .to_owned();
141+ let Ok(boundary) = multer::parse_boundary(&content_type) else {
142+ return Ok(fail(StatusCode::BAD_REQUEST, "not a multipart upload"));
143+ };
144+ let mut multipart = multer::Multipart::new(body.into_data_stream(), boundary);
145+ let mut uploader = None;
146+ loop {
147+ let mut field = match multipart.next_field().await {
148+ Ok(Some(field)) => field,
149+ Ok(None) => return Ok(fail(StatusCode::BAD_REQUEST, "no file")),
150+ Err(_) => return Ok(fail(StatusCode::BAD_REQUEST, "bad upload")),
151+ };
152+ match field.name() {
153+ Some("csrf") => {
154+ let token = field.text().await.unwrap_or_default();
155+ let (user, _) = require_csrf(cx, &token).await?;
156+ uploader = Some(user);
157+ }
158+ Some("file") => {
159+ let Some(user) = uploader.as_ref() else {
160+ return Err(forbidden().into());
161+ };
162+ let name = clean_name(field.file_name().unwrap_or(""));
163+ let name = if name.is_empty() {
164+ "file".to_owned()
165+ } else {
166+ name
167+ };
168+ let Some((mime, inline)) = type_for(&name) else {
169+ return Ok(fail(
170+ StatusCode::UNSUPPORTED_MEDIA_TYPE,
171+ "file type not allowed",
172+ ));
173+ };
174+ let id = ulid::Ulid::generate().to_string().to_ascii_lowercase();
175+ let key = attachment_key(&id);
176+ let mut writer = state.blobs.begin(&key, MAX_ATTACHMENT_BYTES).await?;
177+ loop {
178+ match field.chunk().await {
179+ Ok(Some(chunk)) => {
180+ if let Err(e) = writer.push(&chunk).await {
181+ writer.abort().await;
182+ return Ok(match e {
183+ forge_core::Error::Invalid(_) => {
184+ fail(StatusCode::PAYLOAD_TOO_LARGE, "file too large")
185+ }
186+ other => return Err(other.into()),
187+ });
188+ }
189+ }
190+ Ok(None) => break,
191+ Err(_) => {
192+ writer.abort().await;
193+ return Ok(fail(StatusCode::BAD_REQUEST, "bad upload"));
194+ }
195+ }
196+ }
197+ let (size, sha256) = writer.finish().await?;
198+ if size == 0 {
199+ let _ = state.blobs.delete(&key).await;
200+ return Ok(fail(StatusCode::BAD_REQUEST, "empty file"));
201+ }
202+ if let Err(e) = state
203+ .store
204+ .add_attachment(&id, &ctx.repo.id, &user.id, &name, mime, size, &sha256)
205+ .await
206+ {
207+ let _ = state.blobs.delete(&key).await;
208+ return Err(e.into());
209+ }
210+ let url = format!("/attachments/{id}/{name}");
211+ let markdown = if inline {
212+ format!("![{name}]({url})")
213+ } else {
214+ format!("[{name}]({url})")
215+ };
216+ return Ok(api::json(
217+ StatusCode::CREATED,
218+ &json!({ "url": url, "name": name, "image": inline, "markdown": markdown }),
219+ ));
220+ }
221+ _ => {
222+ let _ = field.bytes().await;
223+ }
224+ }
225+ }
226+}
227+
228+/// Serves an attachment to anyone who can read its repo; everyone else gets 404.
229+#[route(GET "/attachments/{id}/{name}")]
230+async fn download(cx: &Cx) -> Result<Response> {
231+ let state = app_context::<AppState>(cx);
232+ let Some(att) = state.store.attachment(path_param::<Id>(cx)).await? else {
233+ return Err(not_found().into());
234+ };
235+ if att.name != path_param::<Name>(cx) {
236+ return Err(not_found().into());
237+ }
238+ let Some(repo) = state.store.repo_by_id(&att.repo_id).await? else {
239+ return Err(not_found().into());
240+ };
241+ let viewer = current_user(cx).await?;
242+ let (role, org_role) = match &viewer {
243+ Some((user, _)) => (
244+ state.store.collaborator_role(&repo.id, &user.id).await?,
245+ state
246+ .store
247+ .org_repo_role(&repo.owner_id, &user.id, &repo.id)
248+ .await?,
249+ ),
250+ None => (None, None),
251+ };
252+ let actor = viewer.as_ref().map(|(user, _)| user);
253+ if authorize(actor, &repo, role, org_role, Action::Read).is_err() {
254+ return Err(not_found().into());
255+ }
256+ let Some(read) = state.blobs.read(&attachment_key(&att.id)).await? else {
257+ return Err(not_found().into());
258+ };
259+ let inline = type_for(&att.name).is_some_and(|(_, inline)| inline);
260+ let mut res = Response::new(Body::new(StreamBody::new(read.stream.map_ok(Frame::data))));
261+ *res.status_mut() = StatusCode::OK;
262+ let h = res.headers_mut();
263+ if let Ok(value) = HeaderValue::from_str(&att.content_type) {
264+ h.insert(CONTENT_TYPE, value);
265+ }
266+ h.insert(CONTENT_LENGTH, HeaderValue::from(read.size));
267+ let disposition = if inline { "inline" } else { "attachment" };
268+ if let Ok(value) = HeaderValue::from_str(&format!("{disposition}; filename=\"{}\"", att.name)) {
269+ h.insert(CONTENT_DISPOSITION, value);
270+ }
271+ h.insert(
272+ HeaderName::from_static("x-content-type-options"),
273+ HeaderValue::from_static("nosniff"),
274+ );
275+ h.insert(
276+ HeaderName::from_static("content-security-policy"),
277+ HeaderValue::from_static("default-src 'none'; style-src 'unsafe-inline'; sandbox"),
278+ );
279+ h.insert(
280+ HeaderName::from_static("cache-control"),
281+ HeaderValue::from_static("private, max-age=3600"),
282+ );
283+ Ok(res)
284+}
285+
286+/// Up to eight suggestions for the editors. `kind=user` lists people (people in the repo first),
287+/// `kind=issue` lists issues and pull requests by number or title.
288+#[route(GET "/{owner}/{repo}/suggest")]
289+async fn suggest(cx: &Cx) -> Result<Response> {
290+ let ctx = load_repo(cx, path_param::<Owner>(cx), path_param::<Repo>(cx)).await?;
291+ let state = app_context::<AppState>(cx);
292+ if ctx.viewer.is_none() {
293+ return Err(forbidden().into());
294+ }
295+ let mut kind = "";
296+ let mut q = String::new();
297+ for pair in uri(cx).query().unwrap_or_default().split('&') {
298+ if let Some(v) = pair.strip_prefix("kind=") {
299+ kind = if v == "issue" { "issue" } else { "user" };
300+ } else if let Some(v) = pair.strip_prefix("q=") {
301+ q = percent_decode(v);
302+ }
303+ }
304+ let q: String = q.chars().take(60).collect();
305+ let items = if kind == "issue" {
306+ state
307+ .store
308+ .suggest_issues(&ctx.repo.id, &q, 8)
309+ .await?
310+ .into_iter()
311+ .map(|i| {
312+ json!({
313+ "number": i.number,
314+ "title": i.title,
315+ "pull": i.is_pull,
316+ "open": i.open,
317+ })
318+ })
319+ .collect::<Vec<_>>()
320+ } else {
321+ let mut names = state.store.suggest_usernames(&ctx.repo.id, &q, 8).await?;
322+ names.retain(|n| !n.is_empty());
323+ let mut out = Vec::new();
324+ for name in names {
325+ let display = state
326+ .store
327+ .user_by_username(&name)
328+ .await?
329+ .and_then(|u| u.display_name)
330+ .unwrap_or_default();
331+ out.push(json!({ "login": name, "name": display }));
332+ }
333+ out
334+ };
335+ Ok(api::json(StatusCode::OK, &json!(items)))
336+}
337+
338+#[derive(Deserialize)]
339+struct TaskForm {
340+ #[serde(default)]
341+ csrf: String,
342+ /// `issue` for the item body, `comment` for a comment.
343+ #[serde(default)]
344+ kind: String,
345+ #[serde(default)]
346+ id: String,
347+ #[serde(default)]
348+ index: String,
349+ /// `1` to check, anything else to uncheck.
350+ #[serde(default)]
351+ checked: String,
352+}
353+
354+#[route(POST "/{owner}/{repo}/issues/{number}/tasks")]
355+async fn issue_tasks(cx: &Cx, Form(form): Form<TaskForm>) -> Result<Response> {
356+ toggle(cx, ItemKind::Issue, form).await
357+}
358+
359+#[route(POST "/{owner}/{repo}/pulls/{number}/tasks")]
360+async fn pull_tasks(cx: &Cx, Form(form): Form<TaskForm>) -> Result<Response> {
361+ toggle(cx, ItemKind::Pull, form).await
362+}
363+
364+async fn toggle(cx: &Cx, kind: ItemKind, form: TaskForm) -> Result<Response> {
365+ let number = parse_number(path_param::<Number>(cx))?;
366+ let ctx = load_repo(cx, path_param::<Owner>(cx), path_param::<Repo>(cx)).await?;
367+ let (user, _) = require_csrf(cx, &form.csrf).await?;
368+ let state = app_context::<AppState>(cx);
369+ let item = item_for(state, &ctx, kind, number).await?;
370+ let Ok(index) = form.index.parse::<usize>() else {
371+ return Err(bad_request("bad task index").into());
372+ };
373+ let checked = form.checked == "1";
374+ let (author_id, old_body) = match form.kind.as_str() {
375+ "issue" if form.id == item.id => (item.author_id.clone(), item.body.clone()),
376+ "comment" => {
377+ let comment = comment_for(state, &item, &form.id).await?;
378+ (comment.author_id, comment.body)
379+ }
380+ _ => return Err(bad_request("unknown task target").into()),
381+ };
382+ if !may_change(&ctx, &author_id) {
383+ return Err(forbidden().into());
384+ }
385+ let Some(new_body) = set_task(&old_body, index, checked) else {
386+ return Ok(fail(StatusCode::CONFLICT, "task not found"));
387+ };
388+ if new_body != old_body {
389+ if form.kind == "issue" {
390+ state
391+ .store
392+ .edit_issue(&item.id, &user.id, &item.title, &new_body)
393+ .await?;
394+ } else {
395+ state
396+ .store
397+ .edit_comment(&form.id, &user.id, &new_body)
398+ .await?;
399+ }
400+ }
401+ let (done, total) = task_progress(&new_body);
402+ Ok(api::json(
403+ StatusCode::OK,
404+ &json!({ "done": done, "total": total }),
405+ ))
406+}
crates/forge-web/src/pages/authoring_tests.rsadded+477 -0
@@ -0,0 +1,477 @@
1+//! Router-level tests for attachments, suggestions, task toggles and review requests.
2+
3+use forge_core::Visibility;
4+use topcoat::router::request::Request;
5+use topcoat::router::{Body, to_bytes};
6+
7+use crate::auth::SESSION_COOKIE;
8+use crate::pages::authoring::clean_name;
9+use crate::pages::issues_list::test_util::{CSRF, OWNER, REPO, TOKEN, fixture, send};
10+
11+const OID_A: &str = "1111111111111111111111111111111111111111";
12+const OID_B: &str = "2222222222222222222222222222222222222222";
13+
14+fn base() -> String {
15+ format!("/{OWNER}/{REPO}")
16+}
17+
18+fn multipart(csrf: &str, file_name: &str, bytes: &[u8]) -> (String, Vec<u8>) {
19+ let boundary = "----forgetest";
20+ let mut body = Vec::new();
21+ body.extend_from_slice(
22+ format!("--{boundary}\r\nContent-Disposition: form-data; name=\"csrf\"\r\n\r\n{csrf}\r\n")
23+ .as_bytes(),
24+ );
25+ body.extend_from_slice(
26+ format!(
27+ "--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{file_name}\"\r\nContent-Type: application/octet-stream\r\n\r\n"
28+ )
29+ .as_bytes(),
30+ );
31+ body.extend_from_slice(bytes);
32+ body.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes());
33+ (format!("multipart/form-data; boundary={boundary}"), body)
34+}
35+
36+async fn upload(
37+ router: &topcoat::router::Router,
38+ path: &str,
39+ csrf: &str,
40+ name: &str,
41+ bytes: &[u8],
42+) -> (u16, String) {
43+ let (content_type, body) = multipart(csrf, name, bytes);
44+ let req = Request::builder()
45+ .method("POST")
46+ .uri(path)
47+ .header("cookie", format!("__Host-{SESSION_COOKIE}={TOKEN}"))
48+ .header("content-type", content_type)
49+ .body(Body::from(body))
50+ .unwrap();
51+ let res = router.handle(req).await;
52+ let status = res.status().as_u16();
53+ let text =
54+ String::from_utf8_lossy(&to_bytes(res.into_body(), usize::MAX).await.unwrap()).into_owned();
55+ (status, text)
56+}
57+
58+#[test]
59+fn file_names_are_made_safe() {
60+ assert_eq!(clean_name("shot.png"), "shot.png");
61+ assert_eq!(clean_name("../../etc/pass wd.png"), "pass_wd.png");
62+ assert_eq!(clean_name(".hidden.png"), "hidden.png");
63+ assert_eq!(clean_name("C:\\dir\\a b.PNG"), "a_b.PNG");
64+ assert!(clean_name(&"a".repeat(300)).len() <= 100);
65+}
66+
67+#[tokio::test]
68+async fn attachment_round_trip_and_visibility() {
69+ let fx = fixture(Visibility::Private).await;
70+ let png = b"\x89PNG\r\n\x1a\nfake";
71+ let (status, text) = upload(
72+ &fx.router,
73+ &format!("{}/attachments", base()),
74+ CSRF,
75+ "shot.png",
76+ png,
77+ )
78+ .await;
79+ assert_eq!(status, 201, "{text}");
80+ let json: serde_json::Value = serde_json::from_str(&text).unwrap();
81+ let url = json["url"].as_str().unwrap().to_owned();
82+ assert!(url.starts_with("/attachments/") && url.ends_with("/shot.png"));
83+ assert_eq!(json["markdown"], format!("![shot.png]({url})"));
84+
85+ let ok = send(&fx.router, "GET", &url, true, None, &[]).await;
86+ assert_eq!(ok.status, 200);
87+ assert_eq!(ok.header("content-type").as_deref(), Some("image/png"));
88+ assert_eq!(
89+ ok.header("x-content-type-options").as_deref(),
90+ Some("nosniff")
91+ );
92+ assert!(
93+ ok.header("content-disposition")
94+ .unwrap()
95+ .starts_with("inline")
96+ );
97+ // A private repo's file is invisible to anonymous viewers.
98+ let anon = send(&fx.router, "GET", &url, false, None, &[]).await;
99+ assert_eq!(anon.status, 404);
100+ // The name in the URL must match.
101+ let wrong = url.replace("shot.png", "other.png");
102+ assert_eq!(
103+ send(&fx.router, "GET", &wrong, true, None, &[])
104+ .await
105+ .status,
106+ 404
107+ );
108+}
109+
110+#[tokio::test]
111+async fn attachment_rejects_bad_csrf_and_types() {
112+ let fx = fixture(Visibility::Public).await;
113+ let path = format!("{}/attachments", base());
114+ assert_eq!(
115+ upload(&fx.router, &path, "wrong", "a.png", b"x").await.0,
116+ 403
117+ );
118+ assert_eq!(
119+ upload(&fx.router, &path, CSRF, "a.html", b"<b>").await.0,
120+ 415
121+ );
122+ assert_eq!(
123+ upload(&fx.router, &path, CSRF, "a.svg", b"<svg/>").await.0,
124+ 415
125+ );
126+ let (status, text) = upload(&fx.router, &path, CSRF, "notes.txt", b"hello").await;
127+ assert_eq!(status, 201);
128+ let json: serde_json::Value = serde_json::from_str(&text).unwrap();
129+ let url = json["url"].as_str().unwrap();
130+ // Non-images download rather than render.
131+ let got = send(&fx.router, "GET", url, true, None, &[]).await;
132+ assert!(
133+ got.header("content-disposition")
134+ .unwrap()
135+ .starts_with("attachment")
136+ );
137+ assert_eq!(got.body, "hello");
138+}
139+
140+#[tokio::test]
141+async fn suggest_lists_users_and_issues() {
142+ let fx = fixture(Visibility::Public).await;
143+ fx.store
144+ .create_issue(&fx.repo.id, &fx.owner.id, "Parser crash", "")
145+ .await
146+ .unwrap();
147+ fx.store
148+ .create_user("tanya", None, "hash", false)
149+ .await
150+ .unwrap();
151+ let users = send(
152+ &fx.router,
153+ "GET",
154+ &format!("{}/suggest?kind=user&q=ta", base()),
155+ true,
156+ None,
157+ &[],
158+ )
159+ .await;
160+ let list: serde_json::Value = serde_json::from_str(&users.body).unwrap();
161+ assert_eq!(list[0]["login"], "tahinli");
162+ assert_eq!(list[1]["login"], "tanya");
163+ let issues = send(
164+ &fx.router,
165+ "GET",
166+ &format!("{}/suggest?kind=issue&q=pars", base()),
167+ true,
168+ None,
169+ &[],
170+ )
171+ .await;
172+ let list: serde_json::Value = serde_json::from_str(&issues.body).unwrap();
173+ assert_eq!(list[0]["number"], 1);
174+ // Anonymous viewers get nothing.
175+ let anon = send(
176+ &fx.router,
177+ "GET",
178+ &format!("{}/suggest?kind=user&q=ta", base()),
179+ false,
180+ None,
181+ &[],
182+ )
183+ .await;
184+ assert_eq!(anon.status, 403);
185+}
186+
187+#[tokio::test]
188+async fn ticking_a_task_saves_it_with_history() {
189+ let fx = fixture(Visibility::Public).await;
190+ let issue = fx
191+ .store
192+ .create_issue(&fx.repo.id, &fx.owner.id, "Plan", "- [ ] one\n- [ ] two\n")
193+ .await
194+ .unwrap();
195+ let form = format!("csrf={CSRF}&kind=issue&id={}&index=1&checked=1", issue.id);
196+ let uri = format!("{}/issues/{}/tasks", base(), issue.number);
197+ let ok = send(&fx.router, "POST", &uri, true, Some(&form), &[]).await;
198+ assert_eq!(ok.status, 200, "{}", ok.body);
199+ assert!(
200+ ok.body.contains("\"done\":1") && ok.body.contains("\"total\":2"),
201+ "{}",
202+ ok.body
203+ );
204+ let now = fx
205+ .store
206+ .issue_by_number(&fx.repo.id, issue.number)
207+ .await
208+ .unwrap()
209+ .unwrap();
210+ assert_eq!(now.body, "- [ ] one\n- [x] two\n");
211+ let history = fx.store.edit_history("issue", &issue.id).await.unwrap();
212+ assert_eq!(history.len(), 1);
213+ assert_eq!(history[0].old_body, "- [ ] one\n- [ ] two\n");
214+
215+ let bad = form.replace(CSRF, "wrong");
216+ assert_eq!(
217+ send(&fx.router, "POST", &uri, true, Some(&bad), &[])
218+ .await
219+ .status,
220+ 403
221+ );
222+ let missing = form.replace("index=1", "index=9");
223+ assert_eq!(
224+ send(&fx.router, "POST", &uri, true, Some(&missing), &[])
225+ .await
226+ .status,
227+ 409
228+ );
229+ assert_eq!(
230+ send(&fx.router, "POST", &uri, false, Some(&form), &[])
231+ .await
232+ .status,
233+ 303
234+ );
235+
236+ let comment = fx
237+ .store
238+ .add_comment(&issue.id, &fx.owner.id, "- [x] done\n- [ ] todo")
239+ .await
240+ .unwrap();
241+ let form = format!(
242+ "csrf={CSRF}&kind=comment&id={}&index=0&checked=0",
243+ comment.id
244+ );
245+ assert_eq!(
246+ send(&fx.router, "POST", &uri, true, Some(&form), &[])
247+ .await
248+ .status,
249+ 200
250+ );
251+ let c = fx
252+ .store
253+ .comment_by_id(&issue.id, &comment.id)
254+ .await
255+ .unwrap()
256+ .unwrap();
257+ assert_eq!(c.body, "- [ ] done\n- [ ] todo");
258+}
259+
260+#[tokio::test]
261+async fn requesting_a_review_notifies_and_a_review_clears_it() {
262+ let fx = fixture(Visibility::Public).await;
263+ let bob = fx
264+ .store
265+ .create_user("bob", None, "hash", false)
266+ .await
267+ .unwrap();
268+ let pr = fx
269+ .store
270+ .create_pull(
271+ &fx.repo.id,
272+ &fx.owner.id,
273+ "Add thing",
274+ "- [x] a\n- [ ] b",
275+ "main",
276+ &fx.repo.id,
277+ "feature",
278+ OID_A,
279+ OID_B,
280+ )
281+ .await
282+ .unwrap();
283+ let uri = format!("{}/pulls/{}/reviewers", base(), pr.issue.number);
284+ let form = |who: &str, action: &str| format!("csrf={CSRF}&username={who}&action={action}");
285+
286+ // The author cannot be asked, an unknown name is refused, a real one is requested once.
287+ let own = send(
288+ &fx.router,
289+ "POST",
290+ &uri,
291+ true,
292+ Some(&form("tahinli", "request")),
293+ &[],
294+ )
295+ .await;
296+ assert!(
297+ own.header("location")
298+ .unwrap()
299+ .contains("reviewer_error=author")
300+ );
301+ let nobody = send(
302+ &fx.router,
303+ "POST",
304+ &uri,
305+ true,
306+ Some(&form("nobody", "request")),
307+ &[],
308+ )
309+ .await;
310+ assert!(
311+ nobody
312+ .header("location")
313+ .unwrap()
314+ .contains("reviewer_error=unknown")
315+ );
316+ let ok = send(
317+ &fx.router,
318+ "POST",
319+ &uri,
320+ true,
321+ Some(&form("bob", "request")),
322+ &[],
323+ )
324+ .await;
325+ assert_eq!(ok.status, 303);
326+ assert!(!ok.header("location").unwrap().contains("reviewer_error"));
327+ let again = send(
328+ &fx.router,
329+ "POST",
330+ &uri,
331+ true,
332+ Some(&form("bob", "request")),
333+ &[],
334+ )
335+ .await;
336+ assert!(
337+ again
338+ .header("location")
339+ .unwrap()
340+ .contains("reviewer_error=already")
341+ );
342+ assert_eq!(
343+ fx.store.requested_reviewers(&pr.issue.id).await.unwrap(),
344+ ["bob"]
345+ );
346+
347+ // bob's inbox has a review_requested row.
348+ let inbox = fx
349+ .store
350+ .list_notifications(&bob.id, false, None, 10)
351+ .await
352+ .unwrap();
353+ assert_eq!(inbox.len(), 1);
354+ assert_eq!(
355+ inbox[0].reason,
356+ forge_core::notifications::Reason::ReviewRequested
357+ );
358+
359+ // The list shows the request and the task progress, and the filter narrows to it.
360+ let list = send(
361+ &fx.router,
362+ "GET",
363+ &format!("{}/pulls", base()),
364+ true,
365+ None,
366+ &[],
367+ )
368+ .await
369+ .body;
370+ assert!(list.contains("Review requested from bob"), "{list}");
371+ assert!(list.contains("1 of 2 tasks"), "{list}");
372+ let filtered = send(
373+ &fx.router,
374+ "GET",
375+ &format!("{}/pulls?review_requested=bob", base()),
376+ true,
377+ None,
378+ &[],
379+ )
380+ .await
381+ .body;
382+ assert!(filtered.contains("Add thing"));
383+ let none = send(
384+ &fx.router,
385+ "GET",
386+ &format!("{}/pulls?q=review-requested:tahinli", base()),
387+ true,
388+ None,
389+ &[],
390+ )
391+ .await
392+ .body;
393+ assert!(!none.contains("Add thing"), "{none}");
394+
395+ // bob submits a review: his request is gone.
396+ fx.store
397+ .submit_review(
398+ &pr.issue.id,
399+ &bob.id,
400+ forge_core::ReviewState::Commented,
401+ "looks fine",
402+ OID_A,
403+ )
404+ .await
405+ .unwrap();
406+ assert!(
407+ fx.store
408+ .requested_reviewers(&pr.issue.id)
409+ .await
410+ .unwrap()
411+ .is_empty()
412+ );
413+
414+ // Withdrawing works too.
415+ send(
416+ &fx.router,
417+ "POST",
418+ &uri,
419+ true,
420+ Some(&form("bob", "request")),
421+ &[],
422+ )
423+ .await;
424+ send(
425+ &fx.router,
426+ "POST",
427+ &uri,
428+ true,
429+ Some(&form("bob", "withdraw")),
430+ &[],
431+ )
432+ .await;
433+ assert!(
434+ fx.store
435+ .requested_reviewers(&pr.issue.id)
436+ .await
437+ .unwrap()
438+ .is_empty()
439+ );
440+}
441+
442+#[tokio::test]
443+async fn global_review_requests_page_lists_waiting_pulls() {
444+ let fx = fixture(Visibility::Public).await;
445+ let bob = fx
446+ .store
447+ .create_user("bob", None, "hash", false)
448+ .await
449+ .unwrap();
450+ let pr = fx
451+ .store
452+ .create_pull(
453+ &fx.repo.id,
454+ &bob.id,
455+ "Bob's change",
456+ "",
457+ "main",
458+ &fx.repo.id,
459+ "feature",
460+ OID_A,
461+ OID_B,
462+ )
463+ .await
464+ .unwrap();
465+ fx.store
466+ .request_review(&pr.issue.id, &fx.owner.id, &bob.id)
467+ .await
468+ .unwrap();
469+ let page = send(&fx.router, "GET", "/review-requests", true, None, &[]).await;
470+ assert_eq!(page.status, 200);
471+ assert!(
472+ page.body.contains("Bob&#39;s change") || page.body.contains("Bob's change"),
473+ "{}",
474+ page.body
475+ );
476+ assert!(page.body.contains("requested by bob"));
477+}
crates/forge-web/src/pages/issue_parts.rsmodified+26 -1
@@ -231,10 +231,20 @@ pub(crate) struct CommentView {
231 edit_href: Option<String>,231 edit_href: Option<String>,
232 delete_href: Option<String>,232 delete_href: Option<String>,
233 csrf: String,233 csrf: String,
234+ /// Set when the viewer may edit the text: ticking a task checkbox posts here.
235+ tasks: Option<TaskTarget>,
234 /// The reaction row under the text; `None` when there is nothing to show.236 /// The reaction row under the text; `None` when there is nothing to show.
235 reactions: Option<ReactionBar>,237 reactions: Option<ReactionBar>,
236 }238 }
237 239
240+/// Where a task checkbox toggle is posted, and which text it changes.
241+pub(crate) struct TaskTarget {
242+ action: String,
243+ /// `issue` for the item body, `comment` for a comment.
244+ kind: &'static str,
245+ id: String,
246+}
247+
238 /// One reaction button: a POST toggle when `enabled`, a plain count otherwise.248 /// One reaction button: a POST toggle when `enabled`, a plain count otherwise.
239 pub(crate) struct ReactionButton {249 pub(crate) struct ReactionButton {
240 pub(crate) action: String,250 pub(crate) action: String,
@@ -398,6 +408,7 @@ pub(crate) async fn comment_item(lang: Lang, item: CommentView) -> Result<impl V
398 edit_href,408 edit_href,
399 delete_href,409 delete_href,
400 csrf,410 csrf,
411+ tasks,
401 reactions,412 reactions,
402 } = item;413 } = item;
403 let profile = user_href(&login);414 let profile = user_href(&login);
@@ -422,7 +433,11 @@ pub(crate) async fn comment_item(lang: Lang, item: CommentView) -> Result<impl V
422 }433 }
423 </span>434 </span>
424 </header>435 </header>
425- <div class="issue-item-body markdown-body">(Unescaped::new_unchecked(html))</div>436+ if let Some(task) = tasks {
437+ <div class="issue-item-body markdown-body" data-task-action=(task.action.as_str()) data-task-kind=(task.kind) data-task-id=(task.id.as_str()) data-csrf=(csrf.as_str())>(Unescaped::new_unchecked(html))</div>
438+ } else {
439+ <div class="issue-item-body markdown-body">(Unescaped::new_unchecked(html))</div>
440+ }
426 if let Some(bar) = reactions {441 if let Some(bar) = reactions {
427 reaction_row(lang: lang, bar: bar)442 reaction_row(lang: lang, bar: bar)
428 }443 }
@@ -702,6 +717,11 @@ pub(crate) async fn load_discussion(
702 .then(|| repo_href(&owner, &name, segment, &format!("{number}/edit"))),717 .then(|| repo_href(&owner, &name, segment, &format!("{number}/edit"))),
703 delete_href: None,718 delete_href: None,
704 csrf: csrf.clone(),719 csrf: csrf.clone(),
720+ tasks: may_change(ctx, &item.author_id).then(|| TaskTarget {
721+ action: repo_href(&owner, &name, segment, &format!("{number}/tasks")),
722+ kind: "issue",
723+ id: item.id.clone(),
724+ }),
705 reactions: reaction_bar_for(725 reactions: reaction_bar_for(
706 lang,726 lang,
707 body_reaction_map.get(&item.id),727 body_reaction_map.get(&item.id),
@@ -738,6 +758,11 @@ pub(crate) async fn load_discussion(
738 delete_href: mine758 delete_href: mine
739 .then(|| repo_href(&owner, &name, segment, &format!("{comment_path}/delete"))),759 .then(|| repo_href(&owner, &name, segment, &format!("{comment_path}/delete"))),
740 csrf: csrf.clone(),760 csrf: csrf.clone(),
761+ tasks: mine.then(|| TaskTarget {
762+ action: repo_href(&owner, &name, segment, &format!("{number}/tasks")),
763+ kind: "comment",
764+ id: comment.id.clone(),
765+ }),
741 reactions: reaction_bar_for(766 reactions: reaction_bar_for(
742 lang,767 lang,
743 comment_reaction_map.get(&comment.id),768 comment_reaction_map.get(&comment.id),
crates/forge-web/src/pages/issues_list.rsmodified+56 -19
@@ -47,6 +47,7 @@ pub(crate) struct ListQuery {
47 milestone: Option<String>,47 milestone: Option<String>,
48 author: Option<String>,48 author: Option<String>,
49 assignee: Option<String>,49 assignee: Option<String>,
50+ review_requested: Option<String>,
50 q: Option<String>,51 q: Option<String>,
51 draft: Option<String>,52 draft: Option<String>,
52 sort: Option<String>,53 sort: Option<String>,
@@ -61,6 +62,8 @@ pub(crate) struct Selection {
61 pub(crate) milestone: String,62 pub(crate) milestone: String,
62 pub(crate) author: String,63 pub(crate) author: String,
63 pub(crate) assignee: String,64 pub(crate) assignee: String,
65+ /// Username with a pending review request, or `@me` (pull requests only).
66+ pub(crate) review_requested: String,
64 pub(crate) query: String,67 pub(crate) query: String,
65 /// Pull requests only: `true` (drafts), `false` (ready) or empty (both). A `draft:true` or68 /// Pull requests only: `true` (drafts), `false` (ready) or empty (both). A `draft:true` or
66 /// `draft:false` word in the search text sets it too.69 /// `draft:false` word in the search text sets it too.
@@ -92,23 +95,21 @@ impl Selection {
92 Some("false") => "false",95 Some("false") => "false",
93 _ => "",96 _ => "",
94 };97 };
95- // `draft:true` / `draft:false` words in the search text become the draft filter.98+ // `draft:true` / `draft:false` words and `review-requested:user` in the search text become
96- let raw_query = clean(query.q.as_deref());99+ // filters, not title text.
97- let words: Vec<&str> = raw_query100+ let mut review_requested = clean(query.review_requested.as_deref());
98- .split_whitespace()101+ let mut words: Vec<&str> = Vec::new();
99- .filter(|word| match *word {102+ for word in query.q.as_deref().unwrap_or_default().split_whitespace() {
100- "draft:true" => {103+ match word {
101- draft = "true";104+ "draft:true" => draft = "true",
102- false105+ "draft:false" => draft = "false",
103- }106+ _ => match word.strip_prefix("review-requested:") {
104- "draft:false" => {107+ Some(who) if !who.is_empty() => review_requested = clean(Some(who)),
105- draft = "false";108+ _ => words.push(word),
106- false109+ },
107- }110+ }
108- _ => true,111+ }
109- })112+ let q_text = words.join(" ");
110- .collect();
111- let query_text = words.join(" ");
112 Self {113 Self {
113 draft,114 draft,
114 state: match query.state.as_deref() {115 state: match query.state.as_deref() {
@@ -120,7 +121,8 @@ impl Selection {
120 milestone: clean(query.milestone.as_deref()),121 milestone: clean(query.milestone.as_deref()),
121 author: clean(query.author.as_deref()),122 author: clean(query.author.as_deref()),
122 assignee: clean(query.assignee.as_deref()),123 assignee: clean(query.assignee.as_deref()),
123- query: query_text,124+ review_requested,
125+ query: clean(Some(&q_text)),
124 sort: match query.sort.as_deref() {126 sort: match query.sort.as_deref() {
125 Some("oldest") => "oldest",127 Some("oldest") => "oldest",
126 Some("updated") => "updated",128 Some("updated") => "updated",
@@ -146,6 +148,8 @@ impl Selection {
146 milestone: non_empty(&self.milestone),148 milestone: non_empty(&self.milestone),
147 author: non_empty(&self.author),149 author: non_empty(&self.author),
148 assignee: non_empty(&self.assignee),150 assignee: non_empty(&self.assignee),
151+ review_requested: non_empty(self.review_requested.trim_start_matches('@'))
152+ .filter(|w| self.review_requested != "@me" && !w.is_empty()),
149 query: non_empty(&self.query),153 query: non_empty(&self.query),
150 draft: match self.draft {154 draft: match self.draft {
151 "true" => Some(true),155 "true" => Some(true),
@@ -168,10 +172,29 @@ impl Selection {
168 && self.milestone.is_empty()172 && self.milestone.is_empty()
169 && self.author.is_empty()173 && self.author.is_empty()
170 && self.assignee.is_empty()174 && self.assignee.is_empty()
175+ && self.review_requested.is_empty()
171 && self.query.is_empty()176 && self.query.is_empty()
172 && self.draft.is_empty())177 && self.draft.is_empty())
173 }178 }
174 179
180+ /// The search box text: the title query plus the `review-requested:` token when one is set.
181+ pub(crate) fn search_text(&self) -> String {
182+ if self.review_requested.is_empty() {
183+ self.query.clone()
184+ } else {
185+ format!("{} review-requested:{}", self.query, self.review_requested)
186+ .trim()
187+ .to_owned()
188+ }
189+ }
190+
191+ /// Resolves `@me` to the viewer's username. Anonymous viewers lose the filter.
192+ pub(crate) fn resolve_me(&mut self, viewer: Option<&str>) {
193+ if self.review_requested == "@me" {
194+ self.review_requested = viewer.map(str::to_owned).unwrap_or_default();
195+ }
196+ }
197+
175 /// The list URL with this selection, but a different state and page.198 /// The list URL with this selection, but a different state and page.
176 pub(crate) fn href(&self, base: &str, state: &str, page: u32) -> String {199 pub(crate) fn href(&self, base: &str, state: &str, page: u32) -> String {
177 let page_text = if page > 1 {200 let page_text = if page > 1 {
@@ -188,6 +211,7 @@ impl Selection {
188 ("milestone", self.milestone.as_str()),211 ("milestone", self.milestone.as_str()),
189 ("author", self.author.as_str()),212 ("author", self.author.as_str()),
190 ("assignee", self.assignee.as_str()),213 ("assignee", self.assignee.as_str()),
214+ ("review_requested", self.review_requested.as_str()),
191 ("q", self.query.as_str()),215 ("q", self.query.as_str()),
192 ("draft", self.draft),216 ("draft", self.draft),
193 ("sort", sort),217 ("sort", sort),
@@ -255,6 +279,8 @@ struct RowView {
255 assignees: Vec<AssigneeView>,279 assignees: Vec<AssigneeView>,
256 has_comments: bool,280 has_comments: bool,
257 comments_text: String,281 comments_text: String,
282+ /// "2 of 5 tasks" when the body has task items.
283+ tasks_text: Option<String>,
258 }284 }
259 285
260 /// What every row of one list page shares: the language, the repo, the state filter, the286 /// 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 {
330 .collect(),356 .collect(),
331 has_comments: comments > 0,357 has_comments: comments > 0,
332 comments_text: g::comment_count(lang, comments),358 comments_text: g::comment_count(lang, comments),
359+ tasks_text: tasks_text(lang, &issue.body),
333 }360 }
334 }361 }
335 362
363+/// The "N of M tasks" label for a body, or `None` without task items.
364+pub(crate) fn tasks_text(lang: Lang, body: &str) -> Option<String> {
365+ let (done, total) = crate::render::markdown::task_progress(body);
366+ (total > 0).then(|| crate::i18n::authoring::tasks_progress(lang, done, total))
367+}
368+
336 /// One pinned issue card, with the strings the template shows already built.369 /// One pinned issue card, with the strings the template shows already built.
337 struct PinnedCard {370 struct PinnedCard {
338 state_class: &'static str,371 state_class: &'static str,
@@ -379,6 +412,7 @@ async fn issues_list_page(cx: &Cx) -> Result<impl View> {
379 let ctx = load_repo(cx, owner, name).await?;412 let ctx = load_repo(cx, owner, name).await?;
380 let state = app_context::<AppState>(cx);413 let state = app_context::<AppState>(cx);
381 let sel = Selection::parse(query);414 let sel = Selection::parse(query);
415+ let search_value = sel.search_text();
382 let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(u, _)| u));416 let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(u, _)| u));
383 417
384 let (items, total) = state.store.list_issues(&ctx.repo.id, &sel.filter()).await?;418 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<impl View> {
478 <input type="hidden" name="milestone" value=(sel.milestone.as_str())>512 <input type="hidden" name="milestone" value=(sel.milestone.as_str())>
479 <input type="hidden" name="author" value=(sel.author.as_str())>513 <input type="hidden" name="author" value=(sel.author.as_str())>
480 <input type="hidden" name="assignee" value=(sel.assignee.as_str())>514 <input type="hidden" name="assignee" value=(sel.assignee.as_str())>
481- <input type="search" name="q" value=(sel.query.as_str()) placeholder=(g::t(lang, K::SearchTitles)) aria-label=(g::t(lang, K::SearchTitles)) maxlength="256">515+ <input type="search" name="q" value=(search_value.as_str()) placeholder=(g::t(lang, K::SearchTitles)) aria-label=(g::t(lang, K::SearchTitles)) maxlength="256">
482 <select name="sort" aria-label=(g::t(lang, K::Sort))>516 <select name="sort" aria-label=(g::t(lang, K::Sort))>
483 for option in sort_options.iter() {517 for option in sort_options.iter() {
484 <option value=(option.value) selected=(option.selected)>(option.label)</option>518 <option value=(option.value) selected=(option.selected)>(option.label)</option>
@@ -536,6 +570,9 @@ async fn issues_list_page(cx: &Cx) -> Result<impl View> {
536 if let Some(milestone) = row.milestone.clone() {570 if let Some(milestone) = row.milestone.clone() {
537 <a href=(milestone.href.as_str())>(milestone.title.as_str())</a>571 <a href=(milestone.href.as_str())>(milestone.title.as_str())</a>
538 }572 }
573+ if let Some(tasks) = row.tasks_text.clone() {
574+ <span class="task-progress">(tasks.as_str())</span>
575+ }
539 </div>576 </div>
540 </div>577 </div>
541 <div class="issue-aside">578 <div class="issue-aside">
crates/forge-web/src/pages/mod.rsmodified+4 -0
@@ -9,6 +9,9 @@ pub mod admin_users;
9 pub mod archive;9 pub mod archive;
10 pub mod assets;10 pub mod assets;
11 pub mod audit_log;11 pub mod audit_log;
12+pub mod authoring;
13+#[cfg(test)]
14+mod authoring_tests;
12 pub mod avatars;15 pub mod avatars;
13 pub mod blame;16 pub mod blame;
14 pub mod blob;17 pub mod blob;
@@ -87,6 +90,7 @@ pub mod repo_security;
87 pub mod repo_settings;90 pub mod repo_settings;
88 pub mod repo_transfer;91 pub mod repo_transfer;
89 pub mod repo_webhooks;92 pub mod repo_webhooks;
93+pub mod review_requests;
90 #[cfg(test)]94 #[cfg(test)]
91 mod security_tab_tests;95 mod security_tab_tests;
92 pub mod settings_appearance;96 pub mod settings_appearance;
crates/forge-web/src/pages/notifications.rsmodified+1 -0
@@ -789,6 +789,7 @@ async fn inbox_list(
789 <nav class="notif-tabs" aria-label=(g::t(lang, K::NotificationFilter))>789 <nav class="notif-tabs" aria-label=(g::t(lang, K::NotificationFilter))>
790 <a href="/notifications" class=(unread_class)>(unread_text.as_str())</a>790 <a href="/notifications" class=(unread_class)>(unread_text.as_str())</a>
791 <a href="/notifications?all=1" class=(all_class)>(g::t(lang, K::AllTab))</a>791 <a href="/notifications?all=1" class=(all_class)>(g::t(lang, K::AllTab))</a>
792+ <a href="/review-requests">(crate::i18n::authoring::t(lang, crate::i18n::authoring::K::ReviewRequestsTab))</a>
792 </nav>793 </nav>
793 if empty {794 if empty {
794 <p class="muted">795 <p class="muted">
crates/forge-web/src/pages/pull_view.rsmodified+3 -0
@@ -40,6 +40,7 @@ use crate::pages::pulls_merge::{
40 };40 };
41 use crate::pages::repo::repo_head;41 use crate::pages::repo::repo_head;
42 use crate::pages::repo_ctx::{RepoCtx, load_repo};42 use crate::pages::repo_ctx::{RepoCtx, load_repo};
43+use crate::pages::review_requests::{load_reviewers, reviewers_box};
43 use crate::state::AppState;44 use crate::state::AppState;
44 use crate::views::commit_status::{StatusLang, StatusSummary, checks_summary, commit_status};45 use crate::views::commit_status::{StatusLang, StatusSummary, checks_summary, commit_status};
45 use crate::views::diff::LIMITS;46 use crate::views::diff::LIMITS;
@@ -583,6 +584,7 @@ async fn pull_conversation(
583 .await?;584 .await?;
584 let sidebar = load_sidebar(state, &ctx.repo.id, &pr.issue).await?;585 let sidebar = load_sidebar(state, &ctx.repo.id, &pr.issue).await?;
585 let notify = notify_box_for(state, &ctx, lang, &pr.issue.id, &href).await?;586 let notify = notify_box_for(state, &ctx, lang, &pr.issue.id, &href).await?;
587+ let reviewers = load_reviewers(cx, state, &ctx, &pr.issue, &href).await?;
586 let csrf = csrf_of(&ctx);588 let csrf = csrf_of(&ctx);
587 let checks = head_checks(state, &ctx, &pr).await?;589 let checks = head_checks(state, &ctx, &pr).await?;
588 let archived = ctx.repo.archived;590 let archived = ctx.repo.archived;
@@ -828,6 +830,7 @@ async fn pull_conversation(
828 </div>830 </div>
829 <aside class="issue-sidebar">831 <aside class="issue-sidebar">
830 item_sidebar(lang: lang, write: write_meta, base: href.clone(), csrf: csrf.clone(), sidebar: sidebar, notify: notify)832 item_sidebar(lang: lang, write: write_meta, base: href.clone(), csrf: csrf.clone(), sidebar: sidebar, notify: notify)
833+ reviewers_box(lang: lang, reviewers: reviewers)
831 </aside>834 </aside>
832 </div>835 </div>
833 )836 )
crates/forge-web/src/pages/pulls_list.rsmodified+27 -3
@@ -48,6 +48,9 @@ struct PullRowView {
48 has_comments: bool,48 has_comments: bool,
49 comments_text: String,49 comments_text: String,
50 draft: bool,50 draft: bool,
51+ tasks_text: Option<String>,
52+ /// "Review requested from a, b" when reviewers are pending.
53+ reviewers_text: Option<String>,
51 }54 }
52 55
53 /// The row's icon and badge: green for open, purple for merged, red for closed without a merge.56 /// The row's icon and badge: green for open, purple for merged, red for closed without a merge.
@@ -92,7 +95,13 @@ struct RowEnv<'a> {
92 }95 }
93 96
94 /// One row, built from the page's shared values and the item's own `merged` flag.97 /// One row, built from the page's shared values and the item's own `merged` flag.
95-fn row_view(env: &RowEnv<'_>, item: &IssueListItem, merged: bool, draft: bool) -> PullRowView {98+fn row_view(
99+ env: &RowEnv<'_>,
100+ item: &IssueListItem,
101+ merged: bool,
102+ draft: bool,
103+ reviewers: &[String],
104+) -> PullRowView {
96 let RowEnv {105 let RowEnv {
97 lang,106 lang,
98 base,107 base,
@@ -146,6 +155,9 @@ fn row_view(env: &RowEnv<'_>, item: &IssueListItem, merged: bool, draft: bool) -
146 has_comments: comments > 0,155 has_comments: comments > 0,
147 comments_text: g::comments(lang, comments),156 comments_text: g::comments(lang, comments),
148 draft: draft && open,157 draft: draft && open,
158+ tasks_text: crate::pages::issues_list::tasks_text(lang, &issue.body),
159+ reviewers_text: (!reviewers.is_empty() && open)
160+ .then(|| crate::i18n::authoring::requested_from(lang, reviewers)),
149 }161 }
150 }162 }
151 163
@@ -156,7 +168,9 @@ async fn pulls_list_page(cx: &Cx) -> Result<impl View> {
156 let query = query_params::<ListQuery>(cx)?;168 let query = query_params::<ListQuery>(cx)?;
157 let ctx = load_repo(cx, owner, name).await?;169 let ctx = load_repo(cx, owner, name).await?;
158 let state = app_context::<AppState>(cx);170 let state = app_context::<AppState>(cx);
159- let sel = Selection::parse(query);171+ let mut sel = Selection::parse(query);
172+ sel.resolve_me(ctx.viewer.as_ref().map(|(user, _)| user.username.as_str()));
173+ let search_value = sel.search_text();
160 let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(user, _)| user));174 let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(user, _)| user));
161 175
162 let (items, total) = state.store.list_pulls(&ctx.repo.id, &sel.filter()).await?;176 let (items, total) = state.store.list_pulls(&ctx.repo.id, &sel.filter()).await?;
@@ -164,6 +178,8 @@ async fn pulls_list_page(cx: &Cx) -> Result<impl View> {
164 let numbers: Vec<i64> = items.iter().map(|item| item.issue.number).collect();178 let numbers: Vec<i64> = items.iter().map(|item| item.issue.number).collect();
165 let merged = state.store.merged_numbers(&ctx.repo.id, &numbers).await?;179 let merged = state.store.merged_numbers(&ctx.repo.id, &numbers).await?;
166 let drafts = state.store.draft_numbers(&ctx.repo.id, &numbers).await?;180 let drafts = state.store.draft_numbers(&ctx.repo.id, &numbers).await?;
181+ let ids: Vec<String> = items.iter().map(|item| item.issue.id.clone()).collect();
182+ let requested = state.store.requested_reviewers_for(&ids).await?;
167 let milestones: HashMap<String, String> = state183 let milestones: HashMap<String, String> = state
168 .store184 .store
169 .list_milestones(&ctx.repo.id, None)185 .list_milestones(&ctx.repo.id, None)
@@ -188,11 +204,13 @@ async fn pulls_list_page(cx: &Cx) -> Result<impl View> {
188 let rows: Vec<PullRowView> = items204 let rows: Vec<PullRowView> = items
189 .iter()205 .iter()
190 .map(|item| {206 .map(|item| {
207+ let names = requested.get(&item.issue.id).map_or(&[][..], Vec::as_slice);
191 row_view(208 row_view(
192 &env,209 &env,
193 item,210 item,
194 merged.contains(&item.issue.number),211 merged.contains(&item.issue.number),
195 drafts.contains(&item.issue.number),212 drafts.contains(&item.issue.number),
213+ names,
196 )214 )
197 })215 })
198 .collect();216 .collect();
@@ -261,7 +279,7 @@ async fn pulls_list_page(cx: &Cx) -> Result<impl View> {
261 <input type="hidden" name="milestone" value=(sel.milestone.as_str())>279 <input type="hidden" name="milestone" value=(sel.milestone.as_str())>
262 <input type="hidden" name="author" value=(sel.author.as_str())>280 <input type="hidden" name="author" value=(sel.author.as_str())>
263 <input type="hidden" name="assignee" value=(sel.assignee.as_str())>281 <input type="hidden" name="assignee" value=(sel.assignee.as_str())>
264- <input type="search" name="q" value=(sel.query.as_str()) placeholder=(g::t(lang, K::SearchTitles)) aria-label=(g::t(lang, K::SearchTitles)) maxlength="256">282+ <input type="search" name="q" value=(search_value.as_str()) placeholder=(g::t(lang, K::SearchTitles)) aria-label=(g::t(lang, K::SearchTitles)) maxlength="256">
265 <select name="draft" aria-label=(g::t(lang, K::DraftFilterLabel)) data-autosubmit=(true)>283 <select name="draft" aria-label=(g::t(lang, K::DraftFilterLabel)) data-autosubmit=(true)>
266 <option value="" selected=(draft_sel.is_empty())>(g::t(lang, K::DraftAny))</option>284 <option value="" selected=(draft_sel.is_empty())>(g::t(lang, K::DraftAny))</option>
267 <option value="true" selected=(draft_sel == "true")>(g::t(lang, K::DraftOnly))</option>285 <option value="true" selected=(draft_sel == "true")>(g::t(lang, K::DraftOnly))</option>
@@ -311,6 +329,12 @@ async fn pulls_list_page(cx: &Cx) -> Result<impl View> {
311 if let Some(milestone) = row.milestone.clone() {329 if let Some(milestone) = row.milestone.clone() {
312 <a href=(milestone.href.as_str())>(milestone.title.as_str())</a>330 <a href=(milestone.href.as_str())>(milestone.title.as_str())</a>
313 }331 }
332+ if let Some(tasks) = row.tasks_text.clone() {
333+ <span class="task-progress">(tasks.as_str())</span>
334+ }
335+ if let Some(text) = row.reviewers_text.clone() {
336+ <span class="review-pending">(text.as_str())</span>
337+ }
314 </div>338 </div>
315 </div>339 </div>
316 <div class="issue-aside">340 <div class="issue-aside">
crates/forge-web/src/pages/review_requests.rsadded+270 -0
@@ -0,0 +1,270 @@
1+//! Review requests on pull requests: `POST /{owner}/{repo}/pulls/{n}/reviewers` adds or withdraws a
2+//! request (the pull author or Triage), the Reviewers box in the pull sidebar, and the global
3+//! `/review-requests` page listing the open pull requests waiting for the viewer. A request
4+//! notifies the reviewer through the normal fan-out (`Reason::ReviewRequested`); a submitted review
5+//! clears the reviewer's own request in the store.
6+
7+use forge_core::authz::{Action, authorize};
8+use serde::Deserialize;
9+use topcoat::Result;
10+use topcoat::context::{Cx, app_context};
11+use topcoat::router::content::Form;
12+use topcoat::router::error::{SeeOther, forbidden, not_found, see_other};
13+use topcoat::router::request::uri;
14+use topcoat::router::{page, path_param, route};
15+use topcoat::view::{View, component, view};
16+
17+use crate::auth::require_user;
18+use crate::i18n::authoring::{self as ga, K as AK};
19+use crate::i18n::{self, Lang};
20+use crate::notify;
21+use crate::pages::issue_parts::{ItemKind, check_write, may_change, parse_number};
22+use crate::pages::repo_ctx::{RepoCtx, load_repo};
23+use crate::state::AppState;
24+use crate::views::{now_unix, relative_time, repo_href, shell};
25+
26+path_param!(owner);
27+path_param!(repo);
28+path_param!(number);
29+
30+#[derive(Deserialize)]
31+struct ReviewerForm {
32+ #[serde(default)]
33+ csrf: String,
34+ /// `request` or `withdraw`.
35+ #[serde(default)]
36+ action: String,
37+ #[serde(default)]
38+ username: String,
39+}
40+
41+/// Why a request was refused, as the `reviewer_error` query word the pull page shows.
42+fn refusal(code: &str, href: &str) -> SeeOther {
43+ see_other(format!("{href}?reviewer_error={code}#reviewers"))
44+}
45+
46+#[route(POST "/{owner}/{repo}/pulls/{number}/reviewers")]
47+async fn reviewers_save(cx: &Cx, Form(form): Form<ReviewerForm>) -> Result<SeeOther> {
48+ let number = parse_number(path_param::<Number>(cx))?;
49+ let ctx = load_repo(cx, path_param::<Owner>(cx), path_param::<Repo>(cx)).await?;
50+ let (user, session) = require_user(cx).await?;
51+ check_write(&ctx, &session, &form.csrf)?;
52+ let state = app_context::<AppState>(cx);
53+ let Some(pr) = state.store.pull_by_number(&ctx.repo.id, number).await? else {
54+ return Err(not_found().into());
55+ };
56+ let pull = pr.issue;
57+ if !may_change(&ctx, &pull.author_id) {
58+ return Err(forbidden().into());
59+ }
60+ let href = repo_href(
61+ &ctx.repo.owner_name,
62+ &ctx.repo.name,
63+ ItemKind::Pull.segment(),
64+ &number.to_string(),
65+ );
66+ let name = form.username.trim().trim_start_matches('@');
67+ let Some(target) = state.store.user_by_username(name).await? else {
68+ return Ok(refusal("unknown", &href));
69+ };
70+ if form.action == "withdraw" {
71+ state
72+ .store
73+ .withdraw_review_request(&pull.id, &target.id)
74+ .await?;
75+ return Ok(see_other(format!("{href}#reviewers")));
76+ }
77+ if pull.state != forge_core::IssueState::Open {
78+ return Err(forbidden().into());
79+ }
80+ if target.id == pull.author_id {
81+ return Ok(refusal("author", &href));
82+ }
83+ let role = state
84+ .store
85+ .collaborator_role(&ctx.repo.id, &target.id)
86+ .await?;
87+ let org_role = state
88+ .store
89+ .org_repo_role(&ctx.repo.owner_id, &target.id, &ctx.repo.id)
90+ .await?;
91+ if target.is_org() || authorize(Some(&target), &ctx.repo, role, org_role, Action::Read).is_err()
92+ {
93+ return Ok(refusal("access", &href));
94+ }
95+ if state
96+ .store
97+ .request_review(&pull.id, &target.id, &user.id)
98+ .await?
99+ {
100+ notify::dispatch_review_requested(state, &ctx.repo, &pull, &user.id, &target.id).await;
101+ } else {
102+ return Ok(refusal("already", &href));
103+ }
104+ Ok(see_other(format!("{href}#reviewers")))
105+}
106+
107+/// What the Reviewers box shows.
108+pub(crate) struct ReviewersView {
109+ pub(crate) action: String,
110+ pub(crate) csrf: String,
111+ pub(crate) names: Vec<String>,
112+ /// Whether the viewer may request and withdraw.
113+ pub(crate) write: bool,
114+ pub(crate) error: Option<&'static str>,
115+}
116+
117+/// Loads the box for the pull request page. The error word comes from `?reviewer_error=`.
118+pub(crate) async fn load_reviewers(
119+ cx: &Cx,
120+ state: &AppState,
121+ ctx: &RepoCtx,
122+ pull: &forge_core::Issue,
123+ href: &str,
124+) -> Result<ReviewersView> {
125+ let names = state.store.requested_reviewers(&pull.id).await?;
126+ let error = uri(cx)
127+ .query()
128+ .unwrap_or_default()
129+ .split('&')
130+ .find_map(|pair| pair.strip_prefix("reviewer_error="))
131+ .and_then(|code| match code {
132+ "unknown" => Some("unknown"),
133+ "access" => Some("access"),
134+ "author" => Some("author"),
135+ "already" => Some("already"),
136+ _ => None,
137+ });
138+ Ok(ReviewersView {
139+ action: format!("{href}/reviewers"),
140+ csrf: crate::pages::issue_parts::csrf_of(ctx),
141+ names,
142+ write: may_change(ctx, &pull.author_id) && pull.state == forge_core::IssueState::Open,
143+ error,
144+ })
145+}
146+
147+fn error_text(lang: Lang, code: &str) -> &'static str {
148+ ga::t(
149+ lang,
150+ match code {
151+ "unknown" => AK::ReviewerUnknown,
152+ "access" => AK::ReviewerNoAccess,
153+ "author" => AK::ReviewerIsAuthor,
154+ _ => AK::ReviewerAlready,
155+ },
156+ )
157+}
158+
159+#[component]
160+pub(crate) async fn reviewers_box(lang: Lang, reviewers: ReviewersView) -> Result<impl View> {
161+ let ReviewersView {
162+ action,
163+ csrf,
164+ names,
165+ write,
166+ error,
167+ } = reviewers;
168+ let message = error.map(|code| error_text(lang, code));
169+ Ok(view! {
170+ <section class="issue-side-section reviewers-box" id="reviewers">
171+ <h2>(ga::t(lang, AK::Reviewers))</h2>
172+ if let Some(message) = message {
173+ <p class="alert small" role="alert">(message)</p>
174+ }
175+ if names.is_empty() {
176+ <p class="muted small">(ga::t(lang, AK::NoReviewers))</p>
177+ }
178+ <ul class="issue-names reviewer-list">
179+ for name in names.iter() {
180+ <li>
181+ <a href=(format!("/{name}"))>(name.as_str())</a>
182+ if write {
183+ <form method="post" action=(action.as_str()) class="notif-inline-form">
184+ <input type="hidden" name="csrf" value=(csrf.as_str())>
185+ <input type="hidden" name="username" value=(name.as_str())>
186+ <button type="submit" name="action" value="withdraw" class="link-button" title=(ga::t(lang, AK::WithdrawRequest)) aria-label=(ga::t(lang, AK::WithdrawRequest))>"×"</button>
187+ </form>
188+ }
189+ </li>
190+ }
191+ </ul>
192+ if write {
193+ <form method="post" action=(action.as_str()) class="stack">
194+ <input type="hidden" name="csrf" value=(csrf.as_str())>
195+ <input type="text" name="username" required=(true) autocomplete="off" spellcheck="false" data-suggest="user" placeholder=(ga::t(lang, AK::ReviewerName)) aria-label=(ga::t(lang, AK::ReviewerName))>
196+ <div><button type="submit" name="action" value="request">(ga::t(lang, AK::RequestReview))</button></div>
197+ </form>
198+ }
199+ </section>
200+ })
201+}
202+
203+/// The open pull requests waiting for the viewer's review, newest request first.
204+#[page("/review-requests")]
205+async fn review_requests(cx: &Cx) -> Result<impl View> {
206+ let viewer = require_user(cx).await?;
207+ let state = app_context::<AppState>(cx);
208+ let user = &viewer.0;
209+ let lang = i18n::lang(cx, Some(user));
210+ let items = state.store.review_requests_for_user(&user.id).await?;
211+ let now = now_unix();
212+ let mut rows = Vec::new();
213+ for item in items {
214+ // A repo the viewer can no longer read is not listed.
215+ let Some(repo) = state
216+ .store
217+ .repo_by_owner_and_name(&item.repo_owner, &item.repo_name)
218+ .await?
219+ else {
220+ continue;
221+ };
222+ let role = state.store.collaborator_role(&repo.id, &user.id).await?;
223+ let org_role = state
224+ .store
225+ .org_repo_role(&repo.owner_id, &user.id, &repo.id)
226+ .await?;
227+ if authorize(Some(user), &repo, role, org_role, Action::Read).is_err() {
228+ continue;
229+ }
230+ let unix = crate::pages::issue_parts::stamp_unix(&item.created_at);
231+ rows.push((
232+ format!("{}/{}", item.repo_owner, item.repo_name),
233+ repo_href(
234+ &item.repo_owner,
235+ &item.repo_name,
236+ "pulls",
237+ &item.number.to_string(),
238+ ),
239+ format!("#{} {}", item.number, item.title),
240+ ga::requested_by(lang, &item.requested_by),
241+ relative_time(lang, unix, now),
242+ ));
243+ }
244+ let heading = ga::t(lang, AK::ReviewRequests);
245+ let empty = rows.is_empty();
246+ Ok(view! {
247+ shell(title: heading, viewer: Some(&viewer),
248+ <section class="page-head">
249+ <h1>(heading)</h1>
250+ </section>
251+ if empty {
252+ <p class="muted">(ga::t(lang, AK::NoReviewRequests))</p>
253+ }
254+ if !empty {
255+ <section class="card">
256+ <ul class="notif-list review-request-list">
257+ for row in rows.iter() {
258+ <li>
259+ <span class="muted small">(row.0.as_str())</span>
260+ <a class="notif-title" href=(row.1.as_str())>(row.2.as_str())</a>
261+ <span class="muted small">(row.3.as_str())</span>
262+ <span class="muted small">(row.4.as_str())</span>
263+ </li>
264+ }
265+ </ul>
266+ </section>
267+ }
268+ )
269+ })
270+}
crates/forge-web/src/render/markdown.rsmodified+78 -1
@@ -77,6 +77,7 @@ fn markdown_options() -> Options<'static> {
77 options.extension.autolink = true;77 options.extension.autolink = true;
78 options.extension.footnotes = true;78 options.extension.footnotes = true;
79 options.extension.alerts = true;79 options.extension.alerts = true;
80+ options.extension.math_dollars = true;
80 options.extension.header_id_prefix = Some(ID_PREFIX.to_string());81 options.extension.header_id_prefix = Some(ID_PREFIX.to_string());
81 // Raw HTML is passed through to ammonia, which removes anything not allowlisted.82 // Raw HTML is passed through to ammonia, which removes anything not allowlisted.
82 options.render.r#unsafe = true;83 options.render.r#unsafe = true;
@@ -127,7 +128,12 @@ impl Resolver {
127 128
128 /// Returns the rewritten URL, or `None` to keep the original.129 /// Returns the rewritten URL, or `None` to keep the original.
129 fn rewrite(&self, url: &str, image: bool) -> Option<String> {130 fn rewrite(&self, url: &str, image: bool) -> Option<String> {
130- if url.is_empty() || url.starts_with("//") || has_scheme(url) {131+ // Attachment URLs are site-absolute and independent of the rendered file's location.
132+ if url.is_empty()
133+ || url.starts_with("//")
134+ || has_scheme(url)
135+ || url.starts_with("/attachments/")
136+ {
131 return None;137 return None;
132 }138 }
133 if let Some(fragment) = url.strip_prefix('#') {139 if let Some(fragment) = url.strip_prefix('#') {
@@ -630,6 +636,56 @@ pub fn mentioned_usernames(text: &str) -> Vec<String> {
630 found636 found
631 }637 }
632 638
639+/// The task items of `src` in document order, as `(byte offset of the mark, checked)`. The mark is
640+/// the character between the brackets. Tasks inside code blocks are not task items, so they are
641+/// not listed.
642+fn task_marks(src: &str) -> Vec<(usize, bool)> {
643+ let options = markdown_options();
644+ let arena = Arena::new();
645+ let root = parse_document(&arena, src, &options);
646+ let mut line_starts = vec![0usize];
647+ for (i, b) in src.bytes().enumerate() {
648+ if b == b'\n' {
649+ line_starts.push(i + 1);
650+ }
651+ }
652+ let mut out = Vec::new();
653+ for node in root.descendants() {
654+ if let NodeValue::TaskItem(item) = &node.data.borrow().value {
655+ let pos = item.symbol_sourcepos.start;
656+ let Some(line) = line_starts.get(pos.line.wrapping_sub(1)) else {
657+ continue;
658+ };
659+ let at = line + pos.column.saturating_sub(1);
660+ if at < src.len() && src.is_char_boundary(at) {
661+ out.push((at, item.symbol.is_some()));
662+ }
663+ }
664+ }
665+ out
666+}
667+
668+/// `(done, total)` task items in markdown `src`.
669+pub fn task_progress(src: &str) -> (usize, usize) {
670+ let marks = task_marks(src);
671+ (marks.iter().filter(|(_, done)| *done).count(), marks.len())
672+}
673+
674+/// Sets the `index`th task item (document order) to `checked`. `None` when there is no such task.
675+pub fn set_task(src: &str, index: usize, checked: bool) -> Option<String> {
676+ let (at, _) = *task_marks(src).get(index)?;
677+ let mark = src[at..].chars().next()?;
678+ let before = src[..at].chars().next_back()?;
679+ if before != '[' || !(mark == ' ' || mark == 'x' || mark == 'X') {
680+ return None;
681+ }
682+ let mut out = String::with_capacity(src.len());
683+ out.push_str(&src[..at]);
684+ out.push(if checked { 'x' } else { ' ' });
685+ out.push_str(&src[at + mark.len_utf8()..]);
686+ Some(out)
687+}
688+
633 /// Adds the lowercased names of the `@mention`s in one text run to `found`, skipping duplicates.689 /// Adds the lowercased names of the `@mention`s in one text run to `found`, skipping duplicates.
634 fn collect_mentions(text: &str, found: &mut Vec<String>) {690 fn collect_mentions(text: &str, found: &mut Vec<String>) {
635 for range in mention_spans(text) {691 for range in mention_spans(text) {
@@ -737,6 +793,7 @@ fn sanitizer() -> Builder<'static> {
737 ("th", &["align"]),793 ("th", &["align"]),
738 ("input", &["type", "checked", "disabled"]),794 ("input", &["type", "checked", "disabled"]),
739 ("details", &["open"]),795 ("details", &["open"]),
796+ ("span", &["data-math-style"]),
740 ]797 ]
741 .into_iter()798 .into_iter()
742 .map(|(tag, names)| (tag, names.iter().copied().collect()))799 .map(|(tag, names)| (tag, names.iter().copied().collect()))
@@ -780,6 +837,26 @@ mod tests {
780 }837 }
781 }838 }
782 839
840+ #[test]
841+ fn tasks_are_counted_and_toggled() {
842+ let src = "- [ ] one\n- [x] two\n - [ ] nested\n\n```\n- [ ] code\n```\n";
843+ assert_eq!(task_progress(src), (1, 3));
844+ let on = set_task(src, 0, true).unwrap();
845+ assert!(on.starts_with("- [x] one\n"), "{on}");
846+ let off = set_task(&on, 1, false).unwrap();
847+ assert!(off.contains("- [ ] two"), "{off}");
848+ assert_eq!(set_task(src, 2, true).unwrap().matches("[x]").count(), 2);
849+ assert!(set_task(src, 3, true).is_none());
850+ assert!(set_task("no tasks", 0, true).is_none());
851+ }
852+
853+ #[test]
854+ fn math_and_attachment_urls_survive() {
855+ let html = render_markdown("$x^2$ and ![a](/attachments/abc/a.png)", Some(&ctx()));
856+ assert!(html.contains("data-math-style=\"inline\""), "{html}");
857+ assert!(html.contains("src=\"/attachments/abc/a.png\""), "{html}");
858+ }
859+
783 #[test]860 #[test]
784 fn issue_refs_and_mentions_are_linked() {861 fn issue_refs_and_mentions_are_linked() {
785 let html = render_markdown("fixes #12, see @tahinli.\n\n- #3", Some(&issue_ctx()));862 let html = render_markdown("fixes #12, see @tahinli.\n\n- #3", Some(&issue_ctx()));
style/_authoring.scssadded+122 -0
@@ -0,0 +1,122 @@
1+// Authoring helpers: attach toolbar, autocomplete list, task lists, alerts, reviewers, math.
2+
3+.md-tools {
4+ position: relative;
5+ display: flex;
6+ align-items: center;
7+ gap: 0.6rem;
8+ min-height: 1.6rem;
9+ margin-top: 0.25rem;
10+}
11+
12+.md-status {
13+ overflow: hidden;
14+ text-overflow: ellipsis;
15+ white-space: nowrap;
16+}
17+
18+.md-status-bad {
19+ color: var(--caution);
20+}
21+
22+textarea.md-drop {
23+ outline: 2px dashed var(--accent);
24+ outline-offset: -2px;
25+}
26+
27+.md-suggest {
28+ position: absolute;
29+ top: 100%;
30+ left: 0;
31+ z-index: 30;
32+ min-width: min(22rem, 100%);
33+ max-width: 100%;
34+ margin: 2px 0 0;
35+ padding: 4px;
36+ list-style: none;
37+ background: var(--surface);
38+ border: 1px solid var(--border);
39+ border-radius: var(--radius-md);
40+ box-shadow: var(--shadow);
41+
42+ &[hidden] {
43+ display: none;
44+ }
45+}
46+
47+.md-suggest-input {
48+ top: auto;
49+ left: 0;
50+ right: 0;
51+}
52+
53+.md-suggest-item {
54+ display: flex;
55+ align-items: baseline;
56+ gap: 0.4rem;
57+ padding: 0.3rem 0.5rem;
58+ overflow: hidden;
59+ white-space: nowrap;
60+ text-overflow: ellipsis;
61+ border-radius: var(--radius-sm);
62+ cursor: pointer;
63+
64+ &.active,
65+ &:hover {
66+ background: var(--accent-soft, var(--hover, var(--border)));
67+ }
68+}
69+
70+.markdown-body {
71+ li:has(> input[type="checkbox"]:first-child) {
72+ list-style: none;
73+ }
74+
75+ li > input[type="checkbox"]:first-child {
76+ width: auto;
77+ margin: 0 0.4em 0 -1.4em;
78+ vertical-align: middle;
79+ }
80+
81+ .task-toggle {
82+ cursor: pointer;
83+ }
84+
85+ .markdown-alert {
86+ background: color-mix(in srgb, var(--alert-accent, var(--border)) 9%, var(--surface));
87+ }
88+
89+ [data-math-style] {
90+ font-family: var(--mono, ui-monospace, monospace);
91+ font-style: italic;
92+ }
93+
94+ [data-math-style="display"] {
95+ display: block;
96+ margin: 0.5em 0;
97+ text-align: center;
98+ }
99+}
100+
101+.task-progress,
102+.review-pending {
103+ &::before {
104+ content: "\00b7";
105+ margin-right: 0.4em;
106+ }
107+}
108+
109+.reviewer-list li {
110+ display: flex;
111+ align-items: center;
112+ justify-content: space-between;
113+ gap: 0.5rem;
114+ padding: 0.1rem 0;
115+}
116+
117+.review-request-list li {
118+ display: flex;
119+ flex-wrap: wrap;
120+ align-items: baseline;
121+ gap: 0.2rem 0.75rem;
122+}
style/main.scssmodified+4 -0
@@ -82,6 +82,7 @@
82 --del-text: #7D2B25;82 --del-text: #7D2B25;
83 --del-mark: #B0413A;83 --del-mark: #B0413A;
84 --row-target: #FFF4C2;84 --row-target: #FFF4C2;
85+ --note: #2B6CB0;
85 --tip: #1D7A62;86 --tip: #1D7A62;
86 --important: #6A4BB0;87 --important: #6A4BB0;
87 --warning: #9A6200;88 --warning: #9A6200;
@@ -119,6 +120,7 @@
119 --del-text: #F2B8B0;120 --del-text: #F2B8B0;
120 --del-mark: #F09A90;121 --del-mark: #F09A90;
121 --row-target: #3A3510;122 --row-target: #3A3510;
123+ --note: #8AB4F0;
122 --tip: #7CCBAE;124 --tip: #7CCBAE;
123 --important: #C4A7FF;125 --important: #C4A7FF;
124 --warning: #E6B765;126 --warning: #E6B765;
@@ -147,6 +149,7 @@
147 --del-text: #F2B8B0;149 --del-text: #F2B8B0;
148 --del-mark: #F09A90;150 --del-mark: #F09A90;
149 --row-target: #3A3510;151 --row-target: #3A3510;
152+ --note: #8AB4F0;
150 --tip: #7CCBAE;153 --tip: #7CCBAE;
151 --important: #C4A7FF;154 --important: #C4A7FF;
152 --warning: #E6B765;155 --warning: #E6B765;
@@ -5574,6 +5577,7 @@ button.ci-job-last {
5574 @import "wiki";5577 @import "wiki";
5575 @import "browse";5578 @import "browse";
5576 @import "import";5579 @import "import";
5580+@import "authoring";
5577 5581
5578 // Code inside cards, notices and settings panels must stay inside the card. Long tokens and5582 // Code inside cards, notices and settings panels must stay inside the card. Long tokens and
5579 // commands wrap instead of running past the right edge. The rendered README card (.readme) and5583 // commands wrap instead of running past the right edge. The rendered README card (.readme) and