Waterfall CI pages, accent colours, visible mail queue, security and profile redesign
Browse files at this commitcda33ca56a3771020e8cce21c69b11bb7132c069Parent: fabd8b3- feat
- waterfall CI pages, accent colours, visible mail queue, security and profile redesign
43 changed files +5377 -1381
- crates/forge-core/migrations/0038_display_name.sql +4 -0
- crates/forge-core/migrations/0039_totp_device.sql +9 -0
- crates/forge-core/migrations/0040_mail_queue.sql +15 -0
- crates/forge-core/migrations/0041_accent.sql +4 -0
- crates/forge-core/src/authz.rs +2 -0
- crates/forge-core/src/mail.rs +195 -0
- crates/forge-core/src/model.rs +7 -0
- crates/forge-core/src/store/account_tokens.rs +3 -1
- crates/forge-core/src/store/mail.rs +362 -5
- crates/forge-core/src/store/migrate.rs +4 -0
- crates/forge-core/src/store/mod.rs +234 -11
- crates/forge-core/src/store/orgs.rs +2 -2
- crates/forge-core/src/store/ui_prefs.rs +75 -3
- crates/forge-core/src/store/user_delete.rs +9 -1
- crates/forge-core/src/time.rs +15 -0
- crates/forge-web/assets/nav.js +1 -1
- crates/forge-web/build.rs +80 -1
- crates/forge-web/src/accent.rs +155 -0
- crates/forge-web/src/accent_palette.rs +338 -0
- crates/forge-web/src/i18n/accents.rs +39 -0
- crates/forge-web/src/i18n/admin.rs +98 -18
- crates/forge-web/src/i18n/misc.rs +12 -0
- crates/forge-web/src/i18n/mod.rs +156 -6
- crates/forge-web/src/i18n/releases_ci.rs +28 -28
- crates/forge-web/src/mail/account.rs +7 -0
- crates/forge-web/src/mail/live.rs +41 -0
- crates/forge-web/src/mail/mod.rs +10 -3
- crates/forge-web/src/mail/smtp.rs +5 -0
- crates/forge-web/src/mail/worker.rs +49 -7
- crates/forge-web/src/main.rs +3 -0
- crates/forge-web/src/notify.rs +3 -1
- crates/forge-web/src/pages/admin_mail.rs +510 -82
- crates/forge-web/src/pages/ci_badge.rs +5 -5
- crates/forge-web/src/pages/ci_runs.rs +1163 -578
- crates/forge-web/src/pages/ci_tests.rs +76 -44
- crates/forge-web/src/pages/profile.rs +32 -4
- crates/forge-web/src/pages/settings_appearance.rs +72 -13
- crates/forge-web/src/pages/settings_profile.rs +114 -8
- crates/forge-web/src/pages/settings_security.rs +559 -149
- crates/forge-web/src/views/mod.rs +67 -1
- crates/forge-web/tests/ui_prefs_e2e.rs +112 -2
- docs/ci.md +2 -2
- style/main.scss +700 -405
crates/forge-core/migrations/0038_display_name.sqladded+4 -0
| @@ -0,0 +1,4 @@ | |||
| 1 | +-- Optional display name shown as the big heading on the profile page. NULL when the user has | ||
| 2 | +-- not set one; the username is shown instead. Free text, validated by store/mod.rs. | ||
| 3 | + | ||
| 4 | +ALTER TABLE users ADD COLUMN display_name TEXT NULL; | ||
crates/forge-core/migrations/0039_totp_device.sqladded+9 -0
| @@ -0,0 +1,9 @@ | |||
| 1 | +-- The authenticator device behind two-factor sign-in: when it was turned on, when a code last | ||
| 2 | +-- passed, and the name the user gave it (NULL means the default "Authenticator app"). Also | ||
| 3 | +-- when the password last changed, for the "Last changed" line on the security page. Stamps are | ||
| 4 | +-- RFC 3339 UTC, the same format as created_at elsewhere. Existing rows stay NULL. | ||
| 5 | + | ||
| 6 | +ALTER TABLE users ADD COLUMN totp_created_at TEXT NULL; | ||
| 7 | +ALTER TABLE users ADD COLUMN totp_last_used_at TEXT NULL; | ||
| 8 | +ALTER TABLE users ADD COLUMN totp_name TEXT NULL; | ||
| 9 | +ALTER TABLE users ADD COLUMN password_changed_at TEXT NULL; | ||
crates/forge-core/migrations/0040_mail_queue.sqladded+15 -0
| @@ -0,0 +1,15 @@ | |||
| 1 | +-- Mail queue visibility (M4). `kind` says what the message is for, `user_id` ties it to the | ||
| 2 | +-- account it was sent about (NULL for mail with no account, such as an invite), and | ||
| 3 | +-- `discarded_at` marks a failed message an admin gave up on by hand. Existing rows get their kind | ||
| 4 | +-- from the idempotency key prefix the old call sites used. | ||
| 5 | +ALTER TABLE mail_outbox ADD COLUMN kind TEXT NOT NULL DEFAULT 'other'; | ||
| 6 | +ALTER TABLE mail_outbox ADD COLUMN user_id TEXT; | ||
| 7 | +ALTER TABLE mail_outbox ADD COLUMN discarded_at TEXT; | ||
| 8 | +UPDATE mail_outbox SET kind = CASE | ||
| 9 | + WHEN idem_key LIKE 'reset:%' THEN 'password_reset' | ||
| 10 | + WHEN idem_key LIKE 'verify:%' THEN 'verification' | ||
| 11 | + WHEN idem_key LIKE 'invite:%' THEN 'invite' | ||
| 12 | + WHEN idem_key LIKE 'notif:%' THEN 'notification' | ||
| 13 | + WHEN idem_key LIKE 'test:%' THEN 'test' | ||
| 14 | + ELSE 'other' END; | ||
| 15 | +CREATE INDEX mail_outbox_user_kind ON mail_outbox (user_id, kind, created_at); | ||
crates/forge-core/migrations/0041_accent.sqladded+4 -0
| @@ -0,0 +1,4 @@ | |||
| 1 | +-- Accent colour per user: the id of a palette in forge-web's accent_palette.rs. The web layer | ||
| 2 | +-- decides which ids exist, so there is no CHECK list here. Applied by store/migrate.rs. | ||
| 3 | + | ||
| 4 | +ALTER TABLE users ADD COLUMN accent TEXT NOT NULL DEFAULT 'sage'; | ||
crates/forge-core/src/authz.rsmodified+2 -0
| @@ -123,10 +123,12 @@ mod tests { | |||
| 123 | is_admin, | 123 | is_admin, |
| 124 | created_at: String::new(), | 124 | created_at: String::new(), |
| 125 | about: String::new(), | 125 | about: String::new(), |
| 126 | + display_name: None, | ||
| 126 | timezone: "UTC".into(), | 127 | timezone: "UTC".into(), |
| 127 | avatar_hash: None, | 128 | avatar_hash: None, |
| 128 | theme: "auto".into(), | 129 | theme: "auto".into(), |
| 129 | language: "auto".into(), | 130 | language: "auto".into(), |
| 131 | + accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(), | ||
| 130 | kind: AccountKind::User, | 132 | kind: AccountKind::User, |
| 131 | email_notifications: true, | 133 | email_notifications: true, |
| 132 | } | 134 | } |
crates/forge-core/src/mail.rsmodified+195 -0
| @@ -116,6 +116,85 @@ impl fmt::Debug for MailPassword { | |||
| 116 | } | 116 | } |
| 117 | } | 117 | } |
| 118 | 118 | ||
| 119 | +/// What a message is for. The queue page shows it, and the account page reads the latest one. | ||
| 120 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 121 | +pub enum MailKind { | ||
| 122 | + Verification, | ||
| 123 | + PasswordReset, | ||
| 124 | + Invite, | ||
| 125 | + Notification, | ||
| 126 | + Test, | ||
| 127 | + Other, | ||
| 128 | +} | ||
| 129 | + | ||
| 130 | +impl MailKind { | ||
| 131 | + pub const ALL: [MailKind; 6] = [ | ||
| 132 | + MailKind::Verification, | ||
| 133 | + MailKind::PasswordReset, | ||
| 134 | + MailKind::Invite, | ||
| 135 | + MailKind::Notification, | ||
| 136 | + MailKind::Test, | ||
| 137 | + MailKind::Other, | ||
| 138 | + ]; | ||
| 139 | + | ||
| 140 | + pub fn as_str(self) -> &'static str { | ||
| 141 | + match self { | ||
| 142 | + MailKind::Verification => "verification", | ||
| 143 | + MailKind::PasswordReset => "password_reset", | ||
| 144 | + MailKind::Invite => "invite", | ||
| 145 | + MailKind::Notification => "notification", | ||
| 146 | + MailKind::Test => "test", | ||
| 147 | + MailKind::Other => "other", | ||
| 148 | + } | ||
| 149 | + } | ||
| 150 | + | ||
| 151 | + pub fn parse(s: &str) -> Option<MailKind> { | ||
| 152 | + MailKind::ALL.into_iter().find(|kind| kind.as_str() == s) | ||
| 153 | + } | ||
| 154 | +} | ||
| 155 | + | ||
| 156 | +/// Where a queued message stands at one moment. Derived from the outbox row, never stored. | ||
| 157 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 158 | +pub enum MailState { | ||
| 159 | + /// Waiting for its first try. | ||
| 160 | + Queued, | ||
| 161 | + /// A try failed; the next one is scheduled. | ||
| 162 | + Retrying, | ||
| 163 | + /// Leased by a worker pass and being sent now. | ||
| 164 | + Sending, | ||
| 165 | + Sent, | ||
| 166 | + /// The last try failed (or the error was permanent). Nothing more is scheduled. | ||
| 167 | + Failed, | ||
| 168 | + /// A failed message an admin gave up on by hand. | ||
| 169 | + Discarded, | ||
| 170 | +} | ||
| 171 | + | ||
| 172 | +impl MailState { | ||
| 173 | + pub const ALL: [MailState; 6] = [ | ||
| 174 | + MailState::Queued, | ||
| 175 | + MailState::Retrying, | ||
| 176 | + MailState::Sending, | ||
| 177 | + MailState::Sent, | ||
| 178 | + MailState::Failed, | ||
| 179 | + MailState::Discarded, | ||
| 180 | + ]; | ||
| 181 | + | ||
| 182 | + pub fn as_str(self) -> &'static str { | ||
| 183 | + match self { | ||
| 184 | + MailState::Queued => "queued", | ||
| 185 | + MailState::Retrying => "retrying", | ||
| 186 | + MailState::Sending => "sending", | ||
| 187 | + MailState::Sent => "sent", | ||
| 188 | + MailState::Failed => "failed", | ||
| 189 | + MailState::Discarded => "discarded", | ||
| 190 | + } | ||
| 191 | + } | ||
| 192 | + | ||
| 193 | + pub fn parse(s: &str) -> Option<MailState> { | ||
| 194 | + MailState::ALL.into_iter().find(|state| state.as_str() == s) | ||
| 195 | + } | ||
| 196 | +} | ||
| 197 | + | ||
| 119 | /// One message to send. Its Debug output omits the body, which can carry one-time links. | 198 | /// One message to send. Its Debug output omits the body, which can carry one-time links. |
| 120 | #[derive(Clone, PartialEq, Eq)] | 199 | #[derive(Clone, PartialEq, Eq)] |
| 121 | pub struct OutgoingMail { | 200 | pub struct OutgoingMail { |
| @@ -126,6 +205,9 @@ pub struct OutgoingMail { | |||
| 126 | pub message_id: Option<String>, | 205 | pub message_id: Option<String>, |
| 127 | /// `In-Reply-To` and `References` headers, in `<...>` form. | 206 | /// `In-Reply-To` and `References` headers, in `<...>` form. |
| 128 | pub in_reply_to: Option<String>, | 207 | pub in_reply_to: Option<String>, |
| 208 | + pub kind: MailKind, | ||
| 209 | + /// The account the message is about. `None` for mail with no account yet. | ||
| 210 | + pub user_id: Option<String>, | ||
| 129 | } | 211 | } |
| 130 | 212 | ||
| 131 | impl fmt::Debug for OutgoingMail { | 213 | impl fmt::Debug for OutgoingMail { |
| @@ -133,6 +215,7 @@ impl fmt::Debug for OutgoingMail { | |||
| 133 | f.debug_struct("OutgoingMail") | 215 | f.debug_struct("OutgoingMail") |
| 134 | .field("to", &self.to) | 216 | .field("to", &self.to) |
| 135 | .field("subject", &self.subject) | 217 | .field("subject", &self.subject) |
| 218 | + .field("kind", &self.kind) | ||
| 136 | .field("body", &"<redacted>") | 219 | .field("body", &"<redacted>") |
| 137 | .finish() | 220 | .finish() |
| 138 | } | 221 | } |
| @@ -148,11 +231,16 @@ pub struct OutboxEntry { | |||
| 148 | pub body: String, | 231 | pub body: String, |
| 149 | pub message_id: Option<String>, | 232 | pub message_id: Option<String>, |
| 150 | pub in_reply_to: Option<String>, | 233 | pub in_reply_to: Option<String>, |
| 234 | + pub kind: MailKind, | ||
| 235 | + pub user_id: Option<String>, | ||
| 151 | pub created_at: String, | 236 | pub created_at: String, |
| 152 | /// Tries made so far. | 237 | /// Tries made so far. |
| 153 | pub attempts: u32, | 238 | pub attempts: u32, |
| 154 | pub next_attempt_at: Option<String>, | 239 | pub next_attempt_at: Option<String>, |
| 240 | + /// Set while a worker pass holds the row. Past this stamp the lease is void. | ||
| 241 | + pub lease_until: Option<String>, | ||
| 155 | pub sent_at: Option<String>, | 242 | pub sent_at: Option<String>, |
| 243 | + pub discarded_at: Option<String>, | ||
| 156 | pub last_error: Option<String>, | 244 | pub last_error: Option<String>, |
| 157 | } | 245 | } |
| 158 | 246 | ||
| @@ -162,6 +250,7 @@ impl fmt::Debug for OutboxEntry { | |||
| 162 | .field("id", &self.id) | 250 | .field("id", &self.id) |
| 163 | .field("to_addr", &self.to_addr) | 251 | .field("to_addr", &self.to_addr) |
| 164 | .field("subject", &self.subject) | 252 | .field("subject", &self.subject) |
| 253 | + .field("kind", &self.kind) | ||
| 165 | .field("body", &"<redacted>") | 254 | .field("body", &"<redacted>") |
| 166 | .field("attempts", &self.attempts) | 255 | .field("attempts", &self.attempts) |
| 167 | .field("next_attempt_at", &self.next_attempt_at) | 256 | .field("next_attempt_at", &self.next_attempt_at) |
| @@ -171,6 +260,17 @@ impl fmt::Debug for OutboxEntry { | |||
| 171 | } | 260 | } |
| 172 | } | 261 | } |
| 173 | 262 | ||
| 263 | +/// The latest message of one kind for one account, as the account page shows it. | ||
| 264 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 265 | +pub struct MailStatus { | ||
| 266 | + pub state: MailState, | ||
| 267 | + pub created_at: String, | ||
| 268 | + /// Tries made so far, failed ones included. | ||
| 269 | + pub attempts: u32, | ||
| 270 | + pub sent_at: Option<String>, | ||
| 271 | + pub last_error: Option<String>, | ||
| 272 | +} | ||
| 273 | + | ||
| 174 | /// Where a message stands. | 274 | /// Where a message stands. |
| 175 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 275 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 176 | pub enum OutboxStatus { | 276 | pub enum OutboxStatus { |
| @@ -199,6 +299,23 @@ impl OutboxEntry { | |||
| 199 | OutboxStatus::GaveUp | 299 | OutboxStatus::GaveUp |
| 200 | } | 300 | } |
| 201 | } | 301 | } |
| 302 | + | ||
| 303 | + /// The state of the row at `now` (an RFC 3339-style stamp, compared as text). | ||
| 304 | + pub fn state_at(&self, now: &str) -> MailState { | ||
| 305 | + if self.sent_at.is_some() { | ||
| 306 | + MailState::Sent | ||
| 307 | + } else if self.discarded_at.is_some() { | ||
| 308 | + MailState::Discarded | ||
| 309 | + } else if self.lease_until.as_deref().is_some_and(|until| until > now) { | ||
| 310 | + MailState::Sending | ||
| 311 | + } else if self.next_attempt_at.is_none() { | ||
| 312 | + MailState::Failed | ||
| 313 | + } else if self.attempts == 0 { | ||
| 314 | + MailState::Queued | ||
| 315 | + } else { | ||
| 316 | + MailState::Retrying | ||
| 317 | + } | ||
| 318 | + } | ||
| 202 | } | 319 | } |
| 203 | 320 | ||
| 204 | /// Why a send failed. A transient failure is retried on the schedule; a permanent one gives up now. | 321 | /// Why a send failed. A transient failure is retried on the schedule; a permanent one gives up now. |
| @@ -299,6 +416,8 @@ mod tests { | |||
| 299 | body: "https://forge.test/reset/SECRET-TOKEN".into(), | 416 | body: "https://forge.test/reset/SECRET-TOKEN".into(), |
| 300 | message_id: None, | 417 | message_id: None, |
| 301 | in_reply_to: None, | 418 | in_reply_to: None, |
| 419 | + kind: MailKind::PasswordReset, | ||
| 420 | + user_id: None, | ||
| 302 | }; | 421 | }; |
| 303 | assert!(!format!("{mail:?}").contains("SECRET-TOKEN")); | 422 | assert!(!format!("{mail:?}").contains("SECRET-TOKEN")); |
| 304 | } | 423 | } |
| @@ -341,6 +460,78 @@ mod tests { | |||
| 341 | assert!(validate_settings(&bad_from).is_err()); | 460 | assert!(validate_settings(&bad_from).is_err()); |
| 342 | } | 461 | } |
| 343 | 462 | ||
| 463 | + fn row(attempts: u32) -> OutboxEntry { | ||
| 464 | + OutboxEntry { | ||
| 465 | + id: "1".into(), | ||
| 466 | + idem_key: "k".into(), | ||
| 467 | + to_addr: "a@example.com".into(), | ||
| 468 | + subject: "s".into(), | ||
| 469 | + body: "b".into(), | ||
| 470 | + message_id: None, | ||
| 471 | + in_reply_to: None, | ||
| 472 | + kind: MailKind::Notification, | ||
| 473 | + user_id: None, | ||
| 474 | + created_at: "2026-10-15T12:00:00Z".into(), | ||
| 475 | + attempts, | ||
| 476 | + next_attempt_at: Some("2026-10-15T12:00:00Z".into()), | ||
| 477 | + lease_until: None, | ||
| 478 | + sent_at: None, | ||
| 479 | + discarded_at: None, | ||
| 480 | + last_error: None, | ||
| 481 | + } | ||
| 482 | + } | ||
| 483 | + | ||
| 484 | + #[test] | ||
| 485 | + fn kinds_and_states_round_trip_their_names() { | ||
| 486 | + for kind in MailKind::ALL { | ||
| 487 | + assert_eq!(MailKind::parse(kind.as_str()), Some(kind)); | ||
| 488 | + } | ||
| 489 | + assert_eq!(MailKind::parse("spam"), None); | ||
| 490 | + for state in MailState::ALL { | ||
| 491 | + assert_eq!(MailState::parse(state.as_str()), Some(state)); | ||
| 492 | + } | ||
| 493 | + assert_eq!(MailState::parse("gave up"), None); | ||
| 494 | + } | ||
| 495 | + | ||
| 496 | + #[test] | ||
| 497 | + fn a_row_moves_from_queued_to_sending_to_retrying_to_failed() { | ||
| 498 | + let now = "2026-10-15T12:00:00Z"; | ||
| 499 | + let mut entry = row(0); | ||
| 500 | + assert_eq!(entry.state_at(now), MailState::Queued); | ||
| 501 | + | ||
| 502 | + entry.lease_until = Some("2026-10-15T12:05:00Z".into()); | ||
| 503 | + assert_eq!( | ||
| 504 | + entry.state_at(now), | ||
| 505 | + MailState::Sending, | ||
| 506 | + "leased and not yet expired" | ||
| 507 | + ); | ||
| 508 | + entry.lease_until = Some("2026-10-15T11:59:00Z".into()); | ||
| 509 | + assert_eq!( | ||
| 510 | + entry.state_at(now), | ||
| 511 | + MailState::Queued, | ||
| 512 | + "an expired lease is void" | ||
| 513 | + ); | ||
| 514 | + entry.lease_until = None; | ||
| 515 | + | ||
| 516 | + entry.attempts = 1; | ||
| 517 | + entry.last_error = Some("timeout".into()); | ||
| 518 | + assert_eq!(entry.state_at(now), MailState::Retrying); | ||
| 519 | + | ||
| 520 | + entry.next_attempt_at = None; | ||
| 521 | + assert_eq!(entry.state_at(now), MailState::Failed); | ||
| 522 | + } | ||
| 523 | + | ||
| 524 | + #[test] | ||
| 525 | + fn sent_wins_over_everything_and_discard_only_applies_to_unsent() { | ||
| 526 | + let now = "2026-10-15T12:00:00Z"; | ||
| 527 | + let mut entry = row(2); | ||
| 528 | + entry.next_attempt_at = None; | ||
| 529 | + entry.discarded_at = Some(now.into()); | ||
| 530 | + assert_eq!(entry.state_at(now), MailState::Discarded); | ||
| 531 | + entry.sent_at = Some(now.into()); | ||
| 532 | + assert_eq!(entry.state_at(now), MailState::Sent); | ||
| 533 | + } | ||
| 534 | + | ||
| 344 | #[test] | 535 | #[test] |
| 345 | fn status_follows_sent_at_and_next_attempt() { | 536 | fn status_follows_sent_at_and_next_attempt() { |
| 346 | let mut entry = OutboxEntry { | 537 | let mut entry = OutboxEntry { |
| @@ -351,10 +542,14 @@ mod tests { | |||
| 351 | body: "b".into(), | 542 | body: "b".into(), |
| 352 | message_id: None, | 543 | message_id: None, |
| 353 | in_reply_to: None, | 544 | in_reply_to: None, |
| 545 | + kind: MailKind::Other, | ||
| 546 | + user_id: None, | ||
| 354 | created_at: "t".into(), | 547 | created_at: "t".into(), |
| 355 | attempts: 0, | 548 | attempts: 0, |
| 356 | next_attempt_at: Some("t".into()), | 549 | next_attempt_at: Some("t".into()), |
| 550 | + lease_until: None, | ||
| 357 | sent_at: None, | 551 | sent_at: None, |
| 552 | + discarded_at: None, | ||
| 358 | last_error: None, | 553 | last_error: None, |
| 359 | }; | 554 | }; |
| 360 | assert_eq!(entry.status(), OutboxStatus::Queued); | 555 | assert_eq!(entry.status(), OutboxStatus::Queued); |
crates/forge-core/src/model.rsmodified+7 -0
| @@ -37,6 +37,8 @@ pub struct User { | |||
| 37 | pub created_at: String, | 37 | pub created_at: String, |
| 38 | /// Raw markdown, at most 2000 chars. | 38 | /// Raw markdown, at most 2000 chars. |
| 39 | pub about: String, | 39 | pub about: String, |
| 40 | + /// Optional heading shown on the profile instead of the username. `None` when unset. | ||
| 41 | + pub display_name: Option<String>, | ||
| 40 | /// IANA name, e.g. "Europe/Istanbul"; "UTC" by default. | 42 | /// IANA name, e.g. "Europe/Istanbul"; "UTC" by default. |
| 41 | pub timezone: String, | 43 | pub timezone: String, |
| 42 | /// Hash of the current avatar, or `None` when the user has none. Filled by the user queries. | 44 | /// Hash of the current avatar, or `None` when the user has none. Filled by the user queries. |
| @@ -45,6 +47,8 @@ pub struct User { | |||
| 45 | pub theme: String, | 47 | pub theme: String, |
| 46 | /// Language code, e.g. "en"; "auto" uses the instance default. | 48 | /// Language code, e.g. "en"; "auto" uses the instance default. |
| 47 | pub language: String, | 49 | pub language: String, |
| 50 | + /// Accent colour: the id of a palette in forge-web's `accent_palette.rs`. "sage" is the default. | ||
| 51 | + pub accent: String, | ||
| 48 | /// `User` for a person, `Org` for an organization. | 52 | /// `User` for a person, `Org` for an organization. |
| 49 | pub kind: AccountKind, | 53 | pub kind: AccountKind, |
| 50 | /// Whether notifications are also sent by email (needs a verified email and instance mail). | 54 | /// Whether notifications are also sent by email (needs a verified email and instance mail). |
| @@ -125,6 +129,7 @@ impl std::fmt::Debug for User { | |||
| 125 | .field("avatar_hash", &self.avatar_hash) | 129 | .field("avatar_hash", &self.avatar_hash) |
| 126 | .field("theme", &self.theme) | 130 | .field("theme", &self.theme) |
| 127 | .field("language", &self.language) | 131 | .field("language", &self.language) |
| 132 | + .field("accent", &self.accent) | ||
| 128 | .field("kind", &self.kind) | 133 | .field("kind", &self.kind) |
| 129 | .finish() | 134 | .finish() |
| 130 | } | 135 | } |
| @@ -208,10 +213,12 @@ mod tests { | |||
| 208 | is_admin: true, | 213 | is_admin: true, |
| 209 | created_at: "now".into(), | 214 | created_at: "now".into(), |
| 210 | about: String::new(), | 215 | about: String::new(), |
| 216 | + display_name: None, | ||
| 211 | timezone: "UTC".into(), | 217 | timezone: "UTC".into(), |
| 212 | avatar_hash: None, | 218 | avatar_hash: None, |
| 213 | theme: "auto".into(), | 219 | theme: "auto".into(), |
| 214 | language: "auto".into(), | 220 | language: "auto".into(), |
| 221 | + accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(), | ||
| 215 | kind: AccountKind::User, | 222 | kind: AccountKind::User, |
| 216 | email_notifications: true, | 223 | email_notifications: true, |
| 217 | }; | 224 | }; |
crates/forge-core/src/store/account_tokens.rsmodified+3 -1
| @@ -100,7 +100,7 @@ impl Store { | |||
| 100 | &conn, | 100 | &conn, |
| 101 | "SELECT id, username, email, password_hash, is_admin, created_at, about, timezone, \ | 101 | "SELECT id, username, email, password_hash, is_admin, created_at, about, timezone, \ |
| 102 | (SELECT hash FROM avatars WHERE avatars.user_id = users.id) AS avatar_hash, \ | 102 | (SELECT hash FROM avatars WHERE avatars.user_id = users.id) AS avatar_hash, \ |
| 103 | - theme, language, kind, email_notifications FROM users WHERE LOWER(email) = LOWER(?1) \ | 103 | + theme, language, kind, email_notifications, display_name, accent FROM users WHERE LOWER(email) = LOWER(?1) \ |
| 104 | AND email_verified_at IS NOT NULL AND kind = 'user' LIMIT 1", | 104 | AND email_verified_at IS NOT NULL AND kind = 'user' LIMIT 1", |
| 105 | (email.to_owned(),), | 105 | (email.to_owned(),), |
| 106 | map_user, | 106 | map_user, |
| @@ -298,10 +298,12 @@ impl Store { | |||
| 298 | is_admin: false, | 298 | is_admin: false, |
| 299 | created_at: now.clone(), | 299 | created_at: now.clone(), |
| 300 | about: String::new(), | 300 | about: String::new(), |
| 301 | + display_name: None, | ||
| 301 | timezone: "UTC".to_owned(), | 302 | timezone: "UTC".to_owned(), |
| 302 | avatar_hash: None, | 303 | avatar_hash: None, |
| 303 | theme: "light".into(), | 304 | theme: "light".into(), |
| 304 | language: "auto".into(), | 305 | language: "auto".into(), |
| 306 | + accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(), | ||
| 305 | kind: AccountKind::User, | 307 | kind: AccountKind::User, |
| 306 | email_notifications: true, | 308 | email_notifications: true, |
| 307 | }; | 309 | }; |
crates/forge-core/src/store/mail.rsmodified+362 -5
| @@ -10,15 +10,34 @@ use super::{ | |||
| 10 | }; | 10 | }; |
| 11 | use crate::error::{Error, Result}; | 11 | use crate::error::{Error, Result}; |
| 12 | use crate::mail::{ | 12 | use crate::mail::{ |
| 13 | - MailPassword, MailSettings, MailSettingsUpdate, OutboxEntry, OutgoingMail, Security, | 13 | + MailKind, MailPassword, MailSettings, MailSettingsUpdate, MailState, MailStatus, OutboxEntry, |
| 14 | - validate_settings, | 14 | + OutgoingMail, Security, validate_settings, |
| 15 | }; | 15 | }; |
| 16 | use crate::secret; | 16 | use crate::secret; |
| 17 | 17 | ||
| 18 | const SETTINGS_COLS: &str = "host, port, security, username, from_addr, from_name, enabled, \ | 18 | const SETTINGS_COLS: &str = "host, port, security, username, from_addr, from_name, enabled, \ |
| 19 | password_sealed IS NOT NULL, updated_at"; | 19 | password_sealed IS NOT NULL, updated_at"; |
| 20 | const OUTBOX_COLS: &str = "id, idem_key, to_addr, subject, body_text, created_at, attempts, \ | 20 | const OUTBOX_COLS: &str = "id, idem_key, to_addr, subject, body_text, created_at, attempts, \ |
| 21 | - next_attempt_at, sent_at, last_error, message_id, in_reply_to"; | 21 | + next_attempt_at, sent_at, last_error, message_id, in_reply_to, kind, \ |
| 22 | + user_id, lease_until, discarded_at"; | ||
| 23 | + | ||
| 24 | +/// The SQL condition that selects the rows in `state`. It takes `?1`, the current stamp. | ||
| 25 | +fn state_clause(state: MailState) -> &'static str { | ||
| 26 | + match state { | ||
| 27 | + MailState::Sent => "sent_at IS NOT NULL", | ||
| 28 | + MailState::Discarded => "sent_at IS NULL AND discarded_at IS NOT NULL", | ||
| 29 | + MailState::Sending => "sent_at IS NULL AND discarded_at IS NULL AND lease_until > ?1", | ||
| 30 | + MailState::Failed => "sent_at IS NULL AND discarded_at IS NULL AND next_attempt_at IS NULL", | ||
| 31 | + MailState::Queued => { | ||
| 32 | + "sent_at IS NULL AND discarded_at IS NULL AND next_attempt_at IS NOT NULL \ | ||
| 33 | + AND attempts = 0 AND (lease_until IS NULL OR lease_until <= ?1)" | ||
| 34 | + } | ||
| 35 | + MailState::Retrying => { | ||
| 36 | + "sent_at IS NULL AND discarded_at IS NULL AND next_attempt_at IS NOT NULL \ | ||
| 37 | + AND attempts > 0 AND (lease_until IS NULL OR lease_until <= ?1)" | ||
| 38 | + } | ||
| 39 | + } | ||
| 40 | +} | ||
| 22 | 41 | ||
| 23 | fn map_settings(row: &Row) -> Result<MailSettings> { | 42 | fn map_settings(row: &Row) -> Result<MailSettings> { |
| 24 | let port = col_int(row, 1)?; | 43 | let port = col_int(row, 1)?; |
| @@ -41,6 +60,7 @@ fn map_settings(row: &Row) -> Result<MailSettings> { | |||
| 41 | 60 | ||
| 42 | fn map_outbox(row: &Row) -> Result<OutboxEntry> { | 61 | fn map_outbox(row: &Row) -> Result<OutboxEntry> { |
| 43 | let attempts = col_int(row, 6)?; | 62 | let attempts = col_int(row, 6)?; |
| 63 | + let kind = col_text(row, 12)?; | ||
| 44 | Ok(OutboxEntry { | 64 | Ok(OutboxEntry { |
| 45 | id: col_text(row, 0)?, | 65 | id: col_text(row, 0)?, |
| 46 | idem_key: col_text(row, 1)?, | 66 | idem_key: col_text(row, 1)?, |
| @@ -55,6 +75,11 @@ fn map_outbox(row: &Row) -> Result<OutboxEntry> { | |||
| 55 | last_error: col_opt_text(row, 9)?, | 75 | last_error: col_opt_text(row, 9)?, |
| 56 | message_id: col_opt_text(row, 10)?, | 76 | message_id: col_opt_text(row, 10)?, |
| 57 | in_reply_to: col_opt_text(row, 11)?, | 77 | in_reply_to: col_opt_text(row, 11)?, |
| 78 | + kind: MailKind::parse(&kind) | ||
| 79 | + .ok_or_else(|| Error::Database(format!("unknown mail kind {kind}")))?, | ||
| 80 | + user_id: col_opt_text(row, 13)?, | ||
| 81 | + lease_until: col_opt_text(row, 14)?, | ||
| 82 | + discarded_at: col_opt_text(row, 15)?, | ||
| 58 | }) | 83 | }) |
| 59 | } | 84 | } |
| 60 | 85 | ||
| @@ -163,8 +188,8 @@ impl Store { | |||
| 163 | let inserted = conn | 188 | let inserted = conn |
| 164 | .execute( | 189 | .execute( |
| 165 | "INSERT INTO mail_outbox (id, idem_key, to_addr, subject, body_text, created_at, \ | 190 | "INSERT INTO mail_outbox (id, idem_key, to_addr, subject, body_text, created_at, \ |
| 166 | - attempts, next_attempt_at, message_id, in_reply_to) \ | 191 | + attempts, next_attempt_at, message_id, in_reply_to, kind, user_id) \ |
| 167 | - VALUES (?1, ?2, ?3, ?4, ?5, ?6, 0, ?6, ?7, ?8) \ | 192 | + VALUES (?1, ?2, ?3, ?4, ?5, ?6, 0, ?6, ?7, ?8, ?9, ?10) \ |
| 168 | ON CONFLICT (idem_key) DO NOTHING", | 193 | ON CONFLICT (idem_key) DO NOTHING", |
| 169 | ( | 194 | ( |
| 170 | new_id(), | 195 | new_id(), |
| @@ -175,6 +200,8 @@ impl Store { | |||
| 175 | now, | 200 | now, |
| 176 | mail.message_id.clone().map_or(Value::Null, Value::Text), | 201 | mail.message_id.clone().map_or(Value::Null, Value::Text), |
| 177 | mail.in_reply_to.clone().map_or(Value::Null, Value::Text), | 202 | mail.in_reply_to.clone().map_or(Value::Null, Value::Text), |
| 203 | + mail.kind.as_str().to_owned(), | ||
| 204 | + mail.user_id.clone().map_or(Value::Null, Value::Text), | ||
| 178 | ), | 205 | ), |
| 179 | ) | 206 | ) |
| 180 | .await | 207 | .await |
| @@ -265,6 +292,120 @@ impl Store { | |||
| 265 | .map(Option::flatten) | 292 | .map(Option::flatten) |
| 266 | } | 293 | } |
| 267 | 294 | ||
| 295 | + /// Outbox rows in `state` (or every row when `None`), newest first. `now` decides the | ||
| 296 | + /// states that depend on the clock (sending, and the queued and retrying split). | ||
| 297 | + pub async fn list_mail( | ||
| 298 | + &self, | ||
| 299 | + state: Option<MailState>, | ||
| 300 | + now: &str, | ||
| 301 | + limit: u32, | ||
| 302 | + ) -> Result<Vec<OutboxEntry>> { | ||
| 303 | + let conn = self.read_conn().await; | ||
| 304 | + let filter = state.map_or("1 = 1", state_clause); | ||
| 305 | + fetch_all( | ||
| 306 | + &conn, | ||
| 307 | + &format!( | ||
| 308 | + "SELECT {OUTBOX_COLS} FROM mail_outbox WHERE {filter} \ | ||
| 309 | + ORDER BY created_at DESC, id DESC LIMIT ?2" | ||
| 310 | + ), | ||
| 311 | + (now.to_owned(), i64::from(limit)), | ||
| 312 | + map_outbox, | ||
| 313 | + ) | ||
| 314 | + .await | ||
| 315 | + } | ||
| 316 | + | ||
| 317 | + /// How many outbox rows stand in each state at `now`, in `MailState::ALL` order. | ||
| 318 | + pub async fn mail_state_counts(&self, now: &str) -> Result<Vec<(MailState, u32)>> { | ||
| 319 | + let conn = self.read_conn().await; | ||
| 320 | + let mut counts = Vec::with_capacity(MailState::ALL.len()); | ||
| 321 | + for state in MailState::ALL { | ||
| 322 | + let clause = state_clause(state); | ||
| 323 | + let sql = format!("SELECT COUNT(*) FROM mail_outbox WHERE {clause}"); | ||
| 324 | + // A clause without `?1` must be bound with no parameters at all. | ||
| 325 | + let n = if clause.contains("?1") { | ||
| 326 | + fetch_opt(&conn, &sql, (now.to_owned(),), |row| col_int(row, 0)).await? | ||
| 327 | + } else { | ||
| 328 | + fetch_opt(&conn, &sql, (), |row| col_int(row, 0)).await? | ||
| 329 | + } | ||
| 330 | + .unwrap_or(0); | ||
| 331 | + counts.push((state, u32::try_from(n).unwrap_or(u32::MAX))); | ||
| 332 | + } | ||
| 333 | + Ok(counts) | ||
| 334 | + } | ||
| 335 | + | ||
| 336 | + /// Gives a failed message a fresh set of tries, due at `now`. Returns `false` when the row is | ||
| 337 | + /// not failed (it was sent, discarded, or is still scheduled). | ||
| 338 | + pub async fn retry_mail(&self, id: &str, now: &str) -> Result<bool> { | ||
| 339 | + let conn = self.inner.conn.lock().await; | ||
| 340 | + let changed = conn | ||
| 341 | + .execute( | ||
| 342 | + "UPDATE mail_outbox SET attempts = 0, next_attempt_at = ?2, lease_until = NULL \ | ||
| 343 | + WHERE id = ?1 AND sent_at IS NULL AND discarded_at IS NULL \ | ||
| 344 | + AND next_attempt_at IS NULL", | ||
| 345 | + (id.to_owned(), now.to_owned()), | ||
| 346 | + ) | ||
| 347 | + .await | ||
| 348 | + .map_err(db_err)?; | ||
| 349 | + Ok(changed > 0) | ||
| 350 | + } | ||
| 351 | + | ||
| 352 | + /// Gives up on a failed message for good, keeping its row and last error. Returns `false` | ||
| 353 | + /// when the row is not failed. | ||
| 354 | + pub async fn discard_mail(&self, id: &str, now: &str) -> Result<bool> { | ||
| 355 | + let conn = self.inner.conn.lock().await; | ||
| 356 | + let changed = conn | ||
| 357 | + .execute( | ||
| 358 | + "UPDATE mail_outbox SET discarded_at = ?2 WHERE id = ?1 AND sent_at IS NULL \ | ||
| 359 | + AND discarded_at IS NULL AND next_attempt_at IS NULL", | ||
| 360 | + (id.to_owned(), now.to_owned()), | ||
| 361 | + ) | ||
| 362 | + .await | ||
| 363 | + .map_err(db_err)?; | ||
| 364 | + Ok(changed > 0) | ||
| 365 | + } | ||
| 366 | + | ||
| 367 | + /// Clears the leases of unsent rows and returns how many were cleared. Run once at boot: a | ||
| 368 | + /// lease left by a process that stopped mid-pass would hold its row until the lease ran out, | ||
| 369 | + /// and the row is due again as soon as it is released. | ||
| 370 | + pub async fn release_mail_leases(&self) -> Result<u64> { | ||
| 371 | + let conn = self.inner.conn.lock().await; | ||
| 372 | + conn.execute( | ||
| 373 | + "UPDATE mail_outbox SET lease_until = NULL \ | ||
| 374 | + WHERE sent_at IS NULL AND lease_until IS NOT NULL", | ||
| 375 | + (), | ||
| 376 | + ) | ||
| 377 | + .await | ||
| 378 | + .map_err(db_err) | ||
| 379 | + } | ||
| 380 | + | ||
| 381 | + /// The newest message of `kind` sent about `user_id`, with its state now. `None` when no such | ||
| 382 | + /// message was queued. | ||
| 383 | + pub async fn latest_mail_for( | ||
| 384 | + &self, | ||
| 385 | + user_id: &str, | ||
| 386 | + kind: MailKind, | ||
| 387 | + ) -> Result<Option<MailStatus>> { | ||
| 388 | + let now = crate::time::now_stamp(); | ||
| 389 | + let conn = self.read_conn().await; | ||
| 390 | + let entry = fetch_opt( | ||
| 391 | + &conn, | ||
| 392 | + &format!( | ||
| 393 | + "SELECT {OUTBOX_COLS} FROM mail_outbox WHERE user_id = ?1 AND kind = ?2 \ | ||
| 394 | + ORDER BY created_at DESC, id DESC LIMIT 1" | ||
| 395 | + ), | ||
| 396 | + (user_id.to_owned(), kind.as_str().to_owned()), | ||
| 397 | + map_outbox, | ||
| 398 | + ) | ||
| 399 | + .await?; | ||
| 400 | + Ok(entry.map(|entry| MailStatus { | ||
| 401 | + state: entry.state_at(&now), | ||
| 402 | + created_at: entry.created_at, | ||
| 403 | + attempts: entry.attempts, | ||
| 404 | + sent_at: entry.sent_at, | ||
| 405 | + last_error: entry.last_error, | ||
| 406 | + })) | ||
| 407 | + } | ||
| 408 | + | ||
| 268 | /// The newest outbox rows, newest first. | 409 | /// The newest outbox rows, newest first. |
| 269 | pub async fn recent_mail(&self, limit: u32) -> Result<Vec<OutboxEntry>> { | 410 | pub async fn recent_mail(&self, limit: u32) -> Result<Vec<OutboxEntry>> { |
| 270 | let conn = self.read_conn().await; | 411 | let conn = self.read_conn().await; |
| @@ -306,6 +447,8 @@ mod tests { | |||
| 306 | body: "Body".into(), | 447 | body: "Body".into(), |
| 307 | message_id: None, | 448 | message_id: None, |
| 308 | in_reply_to: None, | 449 | in_reply_to: None, |
| 450 | + kind: MailKind::Other, | ||
| 451 | + user_id: None, | ||
| 309 | } | 452 | } |
| 310 | } | 453 | } |
| 311 | 454 | ||
| @@ -538,4 +681,218 @@ mod tests { | |||
| 538 | // Without a password, no key is needed. | 681 | // Without a password, no key is needed. |
| 539 | assert!(store.update_mail_settings(&settings(None)).await.is_ok()); | 682 | assert!(store.update_mail_settings(&settings(None)).await.is_ok()); |
| 540 | } | 683 | } |
| 684 | + | ||
| 685 | + #[tokio::test] | ||
| 686 | + async fn the_queue_filters_and_counts_by_state() { | ||
| 687 | + use crate::mail::MailState; | ||
| 688 | + let (_dir, store) = store_with_key().await; | ||
| 689 | + let now = now_stamp(); | ||
| 690 | + for (key, to) in [ | ||
| 691 | + ("sent", "s@example.com"), | ||
| 692 | + ("failed", "f@example.com"), | ||
| 693 | + ("retry", "r@example.com"), | ||
| 694 | + ("queued", "q@example.com"), | ||
| 695 | + ("dropped", "d@example.com"), | ||
| 696 | + ] { | ||
| 697 | + store.enqueue_mail(key, &mail(to)).await.expect("queued"); | ||
| 698 | + } | ||
| 699 | + let rows = store.recent_mail(10).await.expect("rows"); | ||
| 700 | + let id = |to: &str| { | ||
| 701 | + rows.iter() | ||
| 702 | + .find(|r| r.to_addr == to) | ||
| 703 | + .expect("row") | ||
| 704 | + .id | ||
| 705 | + .clone() | ||
| 706 | + }; | ||
| 707 | + store | ||
| 708 | + .mark_mail_sent(&id("s@example.com"), &now) | ||
| 709 | + .await | ||
| 710 | + .expect("sent"); | ||
| 711 | + store | ||
| 712 | + .mark_mail_failed(&id("f@example.com"), "550 no such user", None) | ||
| 713 | + .await | ||
| 714 | + .expect("failed"); | ||
| 715 | + store | ||
| 716 | + .mark_mail_failed( | ||
| 717 | + &id("r@example.com"), | ||
| 718 | + "timeout", | ||
| 719 | + Some(&stamp_after(Duration::from_secs(3600))), | ||
| 720 | + ) | ||
| 721 | + .await | ||
| 722 | + .expect("retrying"); | ||
| 723 | + store | ||
| 724 | + .mark_mail_failed(&id("d@example.com"), "550", None) | ||
| 725 | + .await | ||
| 726 | + .expect("failed"); | ||
| 727 | + assert!( | ||
| 728 | + store | ||
| 729 | + .discard_mail(&id("d@example.com"), &now) | ||
| 730 | + .await | ||
| 731 | + .expect("discard") | ||
| 732 | + ); | ||
| 733 | + assert!( | ||
| 734 | + !store | ||
| 735 | + .discard_mail(&id("q@example.com"), &now) | ||
| 736 | + .await | ||
| 737 | + .expect("discard"), | ||
| 738 | + "only failed mail can be discarded" | ||
| 739 | + ); | ||
| 740 | + | ||
| 741 | + let counts = store.mail_state_counts(&now).await.expect("counts"); | ||
| 742 | + let count = |state: MailState| counts.iter().find(|(s, _)| *s == state).expect("state").1; | ||
| 743 | + assert_eq!(count(MailState::Queued), 1); | ||
| 744 | + assert_eq!(count(MailState::Retrying), 1); | ||
| 745 | + assert_eq!(count(MailState::Sending), 0); | ||
| 746 | + assert_eq!(count(MailState::Sent), 1); | ||
| 747 | + assert_eq!(count(MailState::Failed), 1); | ||
| 748 | + assert_eq!(count(MailState::Discarded), 1); | ||
| 749 | + | ||
| 750 | + let failed = store | ||
| 751 | + .list_mail(Some(MailState::Failed), &now, 10) | ||
| 752 | + .await | ||
| 753 | + .expect("failed list"); | ||
| 754 | + assert_eq!(failed.len(), 1); | ||
| 755 | + assert_eq!(failed[0].to_addr, "f@example.com"); | ||
| 756 | + assert_eq!(failed[0].last_error.as_deref(), Some("550 no such user")); | ||
| 757 | + assert_eq!(store.list_mail(None, &now, 10).await.expect("all").len(), 5); | ||
| 758 | + } | ||
| 759 | + | ||
| 760 | + #[tokio::test] | ||
| 761 | + async fn a_failed_message_can_be_retried_once_and_then_it_is_queued() { | ||
| 762 | + use crate::mail::MailState; | ||
| 763 | + let (_dir, store) = store_with_key().await; | ||
| 764 | + let now = now_stamp(); | ||
| 765 | + store | ||
| 766 | + .enqueue_mail("k", &mail("a@example.com")) | ||
| 767 | + .await | ||
| 768 | + .expect("queued"); | ||
| 769 | + let id = store.recent_mail(1).await.expect("row").remove(0).id; | ||
| 770 | + store | ||
| 771 | + .mark_mail_failed(&id, "550", None) | ||
| 772 | + .await | ||
| 773 | + .expect("failed"); | ||
| 774 | + | ||
| 775 | + assert!(store.retry_mail(&id, &now).await.expect("retry")); | ||
| 776 | + assert!( | ||
| 777 | + !store.retry_mail(&id, &now).await.expect("again"), | ||
| 778 | + "a queued message is not failed, so it is not retried twice" | ||
| 779 | + ); | ||
| 780 | + let queued = store | ||
| 781 | + .list_mail(Some(MailState::Queued), &now, 10) | ||
| 782 | + .await | ||
| 783 | + .expect("queued list"); | ||
| 784 | + assert_eq!(queued.len(), 1, "a retry starts over with no tries spent"); | ||
| 785 | + assert_eq!(queued[0].attempts, 0); | ||
| 786 | + } | ||
| 787 | + | ||
| 788 | + #[tokio::test] | ||
| 789 | + async fn a_lease_left_by_a_dead_pass_is_released_at_boot() { | ||
| 790 | + use crate::mail::MailState; | ||
| 791 | + let (_dir, store) = store_with_key().await; | ||
| 792 | + store | ||
| 793 | + .enqueue_mail("k", &mail("a@example.com")) | ||
| 794 | + .await | ||
| 795 | + .expect("queued"); | ||
| 796 | + let now = now_stamp(); | ||
| 797 | + let held_until = stamp_after(Duration::from_secs(300)); | ||
| 798 | + assert_eq!( | ||
| 799 | + store | ||
| 800 | + .lease_mail(&now, &held_until, 10) | ||
| 801 | + .await | ||
| 802 | + .expect("lease") | ||
| 803 | + .len(), | ||
| 804 | + 1 | ||
| 805 | + ); | ||
| 806 | + assert!( | ||
| 807 | + store | ||
| 808 | + .lease_mail(&now, &held_until, 10) | ||
| 809 | + .await | ||
| 810 | + .expect("again") | ||
| 811 | + .is_empty(), | ||
| 812 | + "a leased row is not handed out twice" | ||
| 813 | + ); | ||
| 814 | + assert_eq!( | ||
| 815 | + store | ||
| 816 | + .list_mail(Some(MailState::Sending), &now, 10) | ||
| 817 | + .await | ||
| 818 | + .expect("sending") | ||
| 819 | + .len(), | ||
| 820 | + 1 | ||
| 821 | + ); | ||
| 822 | + | ||
| 823 | + assert_eq!(store.release_mail_leases().await.expect("release"), 1); | ||
| 824 | + assert_eq!( | ||
| 825 | + store | ||
| 826 | + .list_mail(Some(MailState::Queued), &now, 10) | ||
| 827 | + .await | ||
| 828 | + .expect("queued") | ||
| 829 | + .len(), | ||
| 830 | + 1, | ||
| 831 | + "a released row is queued again" | ||
| 832 | + ); | ||
| 833 | + assert_eq!( | ||
| 834 | + store | ||
| 835 | + .lease_mail(&now, &held_until, 10) | ||
| 836 | + .await | ||
| 837 | + .expect("lease") | ||
| 838 | + .len(), | ||
| 839 | + 1 | ||
| 840 | + ); | ||
| 841 | + } | ||
| 842 | + | ||
| 843 | + #[tokio::test] | ||
| 844 | + async fn the_latest_mail_of_a_kind_is_read_per_account() { | ||
| 845 | + use crate::mail::{MailKind, MailState}; | ||
| 846 | + let (_dir, store) = store_with_key().await; | ||
| 847 | + assert!( | ||
| 848 | + store | ||
| 849 | + .latest_mail_for("u1", MailKind::Verification) | ||
| 850 | + .await | ||
| 851 | + .expect("none yet") | ||
| 852 | + .is_none() | ||
| 853 | + ); | ||
| 854 | + let mut verify = mail("a@example.com"); | ||
| 855 | + verify.kind = MailKind::Verification; | ||
| 856 | + verify.user_id = Some("u1".into()); | ||
| 857 | + store | ||
| 858 | + .enqueue_mail("verify:1", &verify) | ||
| 859 | + .await | ||
| 860 | + .expect("queued"); | ||
| 861 | + let status = store | ||
| 862 | + .latest_mail_for("u1", MailKind::Verification) | ||
| 863 | + .await | ||
| 864 | + .expect("status") | ||
| 865 | + .expect("one"); | ||
| 866 | + assert_eq!(status.state, MailState::Queued); | ||
| 867 | + assert!(status.sent_at.is_none()); | ||
| 868 | + | ||
| 869 | + let id = store.recent_mail(1).await.expect("row").remove(0).id; | ||
| 870 | + store | ||
| 871 | + .mark_mail_failed(&id, "550 no", None) | ||
| 872 | + .await | ||
| 873 | + .expect("failed"); | ||
| 874 | + let status = store | ||
| 875 | + .latest_mail_for("u1", MailKind::Verification) | ||
| 876 | + .await | ||
| 877 | + .expect("status") | ||
| 878 | + .expect("one"); | ||
| 879 | + assert_eq!(status.state, MailState::Failed); | ||
| 880 | + assert_eq!(status.last_error.as_deref(), Some("550 no")); | ||
| 881 | + | ||
| 882 | + assert!( | ||
| 883 | + store | ||
| 884 | + .latest_mail_for("u1", MailKind::PasswordReset) | ||
| 885 | + .await | ||
| 886 | + .expect("other kind") | ||
| 887 | + .is_none(), | ||
| 888 | + "a kind with no mail is not the verification mail" | ||
| 889 | + ); | ||
| 890 | + assert!( | ||
| 891 | + store | ||
| 892 | + .latest_mail_for("u2", MailKind::Verification) | ||
| 893 | + .await | ||
| 894 | + .expect("other user") | ||
| 895 | + .is_none() | ||
| 896 | + ); | ||
| 897 | + } | ||
| 541 | } | 898 | } |
crates/forge-core/src/store/migrate.rsmodified+4 -0
| @@ -56,6 +56,10 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ | |||
| 56 | include_str!("../../migrations/0036_default_light_theme.sql"), | 56 | include_str!("../../migrations/0036_default_light_theme.sql"), |
| 57 | ), | 57 | ), |
| 58 | (37, include_str!("../../migrations/0037_profile_pins.sql")), | 58 | (37, include_str!("../../migrations/0037_profile_pins.sql")), |
| 59 | + (38, include_str!("../../migrations/0038_display_name.sql")), | ||
| 60 | + (39, include_str!("../../migrations/0039_totp_device.sql")), | ||
| 61 | + (40, include_str!("../../migrations/0040_mail_queue.sql")), | ||
| 62 | + (41, include_str!("../../migrations/0041_accent.sql")), | ||
| 59 | ]; | 63 | ]; |
| 60 | 64 | ||
| 61 | /// The highest migration version this binary knows about. | 65 | /// The highest migration version this binary knows about. |
crates/forge-core/src/store/mod.rsmodified+234 -11
| @@ -54,6 +54,28 @@ use crate::time::now_stamp; | |||
| 54 | const BUSY_TIMEOUT: Duration = Duration::from_millis(5000); | 54 | const BUSY_TIMEOUT: Duration = Duration::from_millis(5000); |
| 55 | /// Longest accepted `about` text, in characters. | 55 | /// Longest accepted `about` text, in characters. |
| 56 | pub const MAX_ABOUT_CHARS: usize = 2000; | 56 | pub const MAX_ABOUT_CHARS: usize = 2000; |
| 57 | +/// Longest accepted display name, in characters. | ||
| 58 | +pub const MAX_DISPLAY_NAME_CHARS: usize = 80; | ||
| 59 | + | ||
| 60 | +/// Checks a display name. Surrounding whitespace is trimmed; an empty result means "no name" and | ||
| 61 | +/// gives `None`. Control characters are rejected; any other Unicode text is allowed. | ||
| 62 | +pub fn validate_display_name(input: &str) -> Result<Option<String>> { | ||
| 63 | + let name = input.trim(); | ||
| 64 | + if name.is_empty() { | ||
| 65 | + return Ok(None); | ||
| 66 | + } | ||
| 67 | + if name.chars().count() > MAX_DISPLAY_NAME_CHARS { | ||
| 68 | + return Err(Error::Invalid(format!( | ||
| 69 | + "display name is longer than {MAX_DISPLAY_NAME_CHARS} characters" | ||
| 70 | + ))); | ||
| 71 | + } | ||
| 72 | + if name.chars().any(char::is_control) { | ||
| 73 | + return Err(Error::Invalid( | ||
| 74 | + "display name must not contain control characters".into(), | ||
| 75 | + )); | ||
| 76 | + } | ||
| 77 | + Ok(Some(name.to_string())) | ||
| 78 | +} | ||
| 57 | 79 | ||
| 58 | /// Async and `Clone`. | 80 | /// Async and `Clone`. |
| 59 | /// | 81 | /// |
| @@ -88,7 +110,7 @@ struct Inner { | |||
| 88 | 110 | ||
| 89 | const USER_COLS: &str = "id, username, email, password_hash, is_admin, created_at, about, timezone, \ | 111 | const USER_COLS: &str = "id, username, email, password_hash, is_admin, created_at, about, timezone, \ |
| 90 | (SELECT hash FROM avatars WHERE avatars.user_id = users.id) AS avatar_hash, \ | 112 | (SELECT hash FROM avatars WHERE avatars.user_id = users.id) AS avatar_hash, \ |
| 91 | - theme, language, kind, email_notifications"; | 113 | + theme, language, kind, email_notifications, display_name, accent"; |
| 92 | const SESSION_COLS: &str = "id, user_id, csrf_token, created_at, expires_at, last_seen, user_agent"; | 114 | const SESSION_COLS: &str = "id, user_id, csrf_token, created_at, expires_at, last_seen, user_agent"; |
| 93 | const SSH_KEY_COLS: &str = | 115 | const SSH_KEY_COLS: &str = |
| 94 | "id, user_id, title, algorithm, key_blob, fingerprint, created_at, last_used_at"; | 116 | "id, user_id, title, algorithm, key_blob, fingerprint, created_at, last_used_at"; |
| @@ -173,10 +195,12 @@ impl Store { | |||
| 173 | is_admin, | 195 | is_admin, |
| 174 | created_at: now_stamp(), | 196 | created_at: now_stamp(), |
| 175 | about: String::new(), | 197 | about: String::new(), |
| 198 | + display_name: None, | ||
| 176 | timezone: "UTC".to_string(), | 199 | timezone: "UTC".to_string(), |
| 177 | avatar_hash: None, | 200 | avatar_hash: None, |
| 178 | theme: "light".into(), | 201 | theme: "light".into(), |
| 179 | language: "auto".into(), | 202 | language: "auto".into(), |
| 203 | + accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(), | ||
| 180 | kind: AccountKind::User, | 204 | kind: AccountKind::User, |
| 181 | email_notifications: true, | 205 | email_notifications: true, |
| 182 | }; | 206 | }; |
| @@ -215,10 +239,12 @@ impl Store { | |||
| 215 | is_admin: true, | 239 | is_admin: true, |
| 216 | created_at: now_stamp(), | 240 | created_at: now_stamp(), |
| 217 | about: String::new(), | 241 | about: String::new(), |
| 242 | + display_name: None, | ||
| 218 | timezone: "UTC".to_string(), | 243 | timezone: "UTC".to_string(), |
| 219 | avatar_hash: None, | 244 | avatar_hash: None, |
| 220 | theme: "light".into(), | 245 | theme: "light".into(), |
| 221 | language: "auto".into(), | 246 | language: "auto".into(), |
| 247 | + accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(), | ||
| 222 | kind: AccountKind::User, | 248 | kind: AccountKind::User, |
| 223 | email_notifications: true, | 249 | email_notifications: true, |
| 224 | }; | 250 | }; |
| @@ -776,6 +802,27 @@ impl Store { | |||
| 776 | Ok(()) | 802 | Ok(()) |
| 777 | } | 803 | } |
| 778 | 804 | ||
| 805 | + /// Sets the display name. `name` goes through `validate_display_name`; an empty name clears | ||
| 806 | + /// it (stored as NULL). A rejected name writes nothing. | ||
| 807 | + pub async fn set_display_name(&self, user_id: &str, name: &str) -> Result<()> { | ||
| 808 | + let name = match validate_display_name(name)? { | ||
| 809 | + Some(name) => Value::Text(name), | ||
| 810 | + None => Value::Null, | ||
| 811 | + }; | ||
| 812 | + let conn = self.inner.conn.lock().await; | ||
| 813 | + let n = conn | ||
| 814 | + .execute( | ||
| 815 | + "UPDATE users SET display_name = ?2 WHERE id = ?1", | ||
| 816 | + vec![Value::Text(user_id.to_owned()), name], | ||
| 817 | + ) | ||
| 818 | + .await | ||
| 819 | + .map_err(db_err)?; | ||
| 820 | + if n == 0 { | ||
| 821 | + return Err(Error::NotFound); | ||
| 822 | + } | ||
| 823 | + Ok(()) | ||
| 824 | + } | ||
| 825 | + | ||
| 779 | /// Inserts or replaces the user's avatar. `png` is the re-encoded image, `hash` its digest. | 826 | /// Inserts or replaces the user's avatar. `png` is the re-encoded image, `hash` its digest. |
| 780 | pub async fn set_avatar(&self, user_id: &str, png: &[u8], hash: &str) -> Result<()> { | 827 | pub async fn set_avatar(&self, user_id: &str, png: &[u8], hash: &str) -> Result<()> { |
| 781 | let conn = self.inner.conn.lock().await; | 828 | let conn = self.inner.conn.lock().await; |
| @@ -990,6 +1037,8 @@ fn map_user(row: &Row) -> Result<User> { | |||
| 990 | language: col_text(row, 10)?, | 1037 | language: col_text(row, 10)?, |
| 991 | kind: account_kind(&col_text(row, 11)?)?, | 1038 | kind: account_kind(&col_text(row, 11)?)?, |
| 992 | email_notifications: col_bool(row, 12)?, | 1039 | email_notifications: col_bool(row, 12)?, |
| 1040 | + display_name: col_opt_text(row, 13)?, | ||
| 1041 | + accent: col_text(row, 14)?, | ||
| 993 | }) | 1042 | }) |
| 994 | } | 1043 | } |
| 995 | 1044 | ||
| @@ -1421,6 +1470,12 @@ pub struct TotpState { | |||
| 1421 | pub enabled: bool, | 1470 | pub enabled: bool, |
| 1422 | /// The last time step whose code was accepted (replay guard). | 1471 | /// The last time step whose code was accepted (replay guard). |
| 1423 | pub last_step: u64, | 1472 | pub last_step: u64, |
| 1473 | + /// The device name the user gave at enrollment. `None` means the default name. | ||
| 1474 | + pub name: Option<String>, | ||
| 1475 | + /// When two-factor was turned on. `None` before that, and for rows from before migration 39. | ||
| 1476 | + pub created_at: Option<String>, | ||
| 1477 | + /// When a TOTP code last passed. `None` until the first one. | ||
| 1478 | + pub last_used_at: Option<String>, | ||
| 1424 | } | 1479 | } |
| 1425 | 1480 | ||
| 1426 | /// Checks the basic shape of an email address: one `@`, a non-empty local part and domain, | 1481 | /// Checks the basic shape of an email address: one `@`, a non-empty local part and domain, |
| @@ -1463,8 +1518,8 @@ impl Store { | |||
| 1463 | let conn = self.inner.conn.lock().await; | 1518 | let conn = self.inner.conn.lock().await; |
| 1464 | let n = conn | 1519 | let n = conn |
| 1465 | .execute( | 1520 | .execute( |
| 1466 | - "UPDATE users SET password_hash = ?2 WHERE id = ?1", | 1521 | + "UPDATE users SET password_hash = ?2, password_changed_at = ?3 WHERE id = ?1", |
| 1467 | - (user_id.to_string(), password_hash.to_string()), | 1522 | + (user_id.to_string(), password_hash.to_string(), now_stamp()), |
| 1468 | ) | 1523 | ) |
| 1469 | .await | 1524 | .await |
| 1470 | .map_err(db_err)?; | 1525 | .map_err(db_err)?; |
| @@ -1494,7 +1549,8 @@ impl Store { | |||
| 1494 | let conn = self.read_conn().await; | 1549 | let conn = self.read_conn().await; |
| 1495 | fetch_opt( | 1550 | fetch_opt( |
| 1496 | &conn, | 1551 | &conn, |
| 1497 | - "SELECT totp_secret_sealed, totp_enabled, totp_last_step FROM users WHERE id = ?1 LIMIT 1", | 1552 | + "SELECT totp_secret_sealed, totp_enabled, totp_last_step, totp_name, totp_created_at, \ |
| 1553 | + totp_last_used_at FROM users WHERE id = ?1 LIMIT 1", | ||
| 1498 | (user_id.to_string(),), | 1554 | (user_id.to_string(),), |
| 1499 | |row| { | 1555 | |row| { |
| 1500 | let sealed_secret = match row.get_value(0).map_err(db_err)? { | 1556 | let sealed_secret = match row.get_value(0).map_err(db_err)? { |
| @@ -1509,6 +1565,9 @@ impl Store { | |||
| 1509 | sealed_secret, | 1565 | sealed_secret, |
| 1510 | enabled: col_bool(row, 1)?, | 1566 | enabled: col_bool(row, 1)?, |
| 1511 | last_step: u64::try_from(col_int(row, 2)?).unwrap_or(0), | 1567 | last_step: u64::try_from(col_int(row, 2)?).unwrap_or(0), |
| 1568 | + name: col_opt_text(row, 3)?, | ||
| 1569 | + created_at: col_opt_text(row, 4)?, | ||
| 1570 | + last_used_at: col_opt_text(row, 5)?, | ||
| 1512 | }) | 1571 | }) |
| 1513 | }, | 1572 | }, |
| 1514 | ) | 1573 | ) |
| @@ -1521,7 +1580,8 @@ impl Store { | |||
| 1521 | let conn = self.inner.conn.lock().await; | 1580 | let conn = self.inner.conn.lock().await; |
| 1522 | let n = conn | 1581 | let n = conn |
| 1523 | .execute( | 1582 | .execute( |
| 1524 | - "UPDATE users SET totp_secret_sealed = ?2, totp_enabled = 0, totp_last_step = 0 \ | 1583 | + "UPDATE users SET totp_secret_sealed = ?2, totp_enabled = 0, totp_last_step = 0, \ |
| 1584 | + totp_name = NULL, totp_created_at = NULL, totp_last_used_at = NULL \ | ||
| 1525 | WHERE id = ?1", | 1585 | WHERE id = ?1", |
| 1526 | (user_id.to_string(), sealed.as_bytes().to_vec()), | 1586 | (user_id.to_string(), sealed.as_bytes().to_vec()), |
| 1527 | ) | 1587 | ) |
| @@ -1546,12 +1606,14 @@ impl Store { | |||
| 1546 | let conn = self.inner.conn.lock().await; | 1606 | let conn = self.inner.conn.lock().await; |
| 1547 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; | 1607 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 1548 | let uid = user_id.to_string(); | 1608 | let uid = user_id.to_string(); |
| 1609 | + let now = now_stamp(); | ||
| 1549 | let outcome: Result<()> = async { | 1610 | let outcome: Result<()> = async { |
| 1550 | let n = tx | 1611 | let n = tx |
| 1551 | .execute( | 1612 | .execute( |
| 1552 | - "UPDATE users SET totp_enabled = 1, totp_last_step = ?2 \ | 1613 | + "UPDATE users SET totp_enabled = 1, totp_last_step = ?2, \ |
| 1614 | + totp_created_at = ?3, totp_last_used_at = ?3 \ | ||
| 1553 | WHERE id = ?1 AND totp_secret_sealed IS NOT NULL", | 1615 | WHERE id = ?1 AND totp_secret_sealed IS NOT NULL", |
| 1554 | - (uid.clone(), step), | 1616 | + (uid.clone(), step, now), |
| 1555 | ) | 1617 | ) |
| 1556 | .await | 1618 | .await |
| 1557 | .map_err(db_err)?; | 1619 | .map_err(db_err)?; |
| @@ -1583,7 +1645,8 @@ impl Store { | |||
| 1583 | let uid = user_id.to_string(); | 1645 | let uid = user_id.to_string(); |
| 1584 | let outcome: Result<()> = async { | 1646 | let outcome: Result<()> = async { |
| 1585 | tx.execute( | 1647 | tx.execute( |
| 1586 | - "UPDATE users SET totp_secret_sealed = NULL, totp_enabled = 0, totp_last_step = 0 \ | 1648 | + "UPDATE users SET totp_secret_sealed = NULL, totp_enabled = 0, totp_last_step = 0, \ |
| 1649 | + totp_name = NULL, totp_created_at = NULL, totp_last_used_at = NULL \ | ||
| 1587 | WHERE id = ?1", | 1650 | WHERE id = ?1", |
| 1588 | (uid.clone(),), | 1651 | (uid.clone(),), |
| 1589 | ) | 1652 | ) |
| @@ -1608,14 +1671,44 @@ impl Store { | |||
| 1608 | let conn = self.inner.conn.lock().await; | 1671 | let conn = self.inner.conn.lock().await; |
| 1609 | let n = conn | 1672 | let n = conn |
| 1610 | .execute( | 1673 | .execute( |
| 1611 | - "UPDATE users SET totp_last_step = ?2 WHERE id = ?1 AND totp_last_step < ?2", | 1674 | + "UPDATE users SET totp_last_step = ?2, totp_last_used_at = ?3 \ |
| 1612 | - (user_id.to_string(), step), | 1675 | + WHERE id = ?1 AND totp_last_step < ?2", |
| 1676 | + (user_id.to_string(), step, now_stamp()), | ||
| 1613 | ) | 1677 | ) |
| 1614 | .await | 1678 | .await |
| 1615 | .map_err(db_err)?; | 1679 | .map_err(db_err)?; |
| 1616 | Ok(n > 0) | 1680 | Ok(n > 0) |
| 1617 | } | 1681 | } |
| 1618 | 1682 | ||
| 1683 | + /// Sets the device name shown on the security page. `None` restores the default name. | ||
| 1684 | + pub async fn set_totp_name(&self, user_id: &str, name: Option<&str>) -> Result<()> { | ||
| 1685 | + let conn = self.inner.conn.lock().await; | ||
| 1686 | + let value = match name { | ||
| 1687 | + Some(name) => Value::Text(name.to_owned()), | ||
| 1688 | + None => Value::Null, | ||
| 1689 | + }; | ||
| 1690 | + conn.execute( | ||
| 1691 | + "UPDATE users SET totp_name = ?2 WHERE id = ?1", | ||
| 1692 | + (user_id.to_string(), value), | ||
| 1693 | + ) | ||
| 1694 | + .await | ||
| 1695 | + .map_err(db_err)?; | ||
| 1696 | + Ok(()) | ||
| 1697 | + } | ||
| 1698 | + | ||
| 1699 | + /// When the password last changed, or `None` when no change was recorded since migration 39. | ||
| 1700 | + pub async fn password_changed_at(&self, user_id: &str) -> Result<Option<String>> { | ||
| 1701 | + let conn = self.read_conn().await; | ||
| 1702 | + fetch_opt( | ||
| 1703 | + &conn, | ||
| 1704 | + "SELECT password_changed_at FROM users WHERE id = ?1 LIMIT 1", | ||
| 1705 | + (user_id.to_string(),), | ||
| 1706 | + |row| col_opt_text(row, 0), | ||
| 1707 | + ) | ||
| 1708 | + .await | ||
| 1709 | + .map(Option::flatten) | ||
| 1710 | + } | ||
| 1711 | + | ||
| 1619 | /// Marks an unused recovery code as used. Returns false when no unused code has this hash. | 1712 | /// Marks an unused recovery code as used. Returns false when no unused code has this hash. |
| 1620 | pub async fn consume_recovery_code(&self, user_id: &str, code_hash: &str) -> Result<bool> { | 1713 | pub async fn consume_recovery_code(&self, user_id: &str, code_hash: &str) -> Result<bool> { |
| 1621 | let conn = self.inner.conn.lock().await; | 1714 | let conn = self.inner.conn.lock().await; |
| @@ -1734,6 +1827,67 @@ mod tests { | |||
| 1734 | assert_eq!(still.timezone, "Europe/Istanbul"); | 1827 | assert_eq!(still.timezone, "Europe/Istanbul"); |
| 1735 | } | 1828 | } |
| 1736 | 1829 | ||
| 1830 | + #[test] | ||
| 1831 | + fn display_name_validation() { | ||
| 1832 | + assert_eq!(validate_display_name(" ").unwrap(), None); | ||
| 1833 | + assert_eq!(validate_display_name("").unwrap(), None); | ||
| 1834 | + assert_eq!( | ||
| 1835 | + validate_display_name(" Ahmet Kaan Gümüş ").unwrap(), | ||
| 1836 | + Some("Ahmet Kaan Gümüş".to_string()) | ||
| 1837 | + ); | ||
| 1838 | + // The limit counts characters: 80 two-byte letters fit, 81 do not. | ||
| 1839 | + assert!(validate_display_name(&"ğ".repeat(MAX_DISPLAY_NAME_CHARS)).is_ok()); | ||
| 1840 | + assert!(matches!( | ||
| 1841 | + validate_display_name(&"ğ".repeat(MAX_DISPLAY_NAME_CHARS + 1)), | ||
| 1842 | + Err(Error::Invalid(_)) | ||
| 1843 | + )); | ||
| 1844 | + assert!(matches!( | ||
| 1845 | + validate_display_name("two\nlines"), | ||
| 1846 | + Err(Error::Invalid(_)) | ||
| 1847 | + )); | ||
| 1848 | + assert!(matches!( | ||
| 1849 | + validate_display_name("tab\there"), | ||
| 1850 | + Err(Error::Invalid(_)) | ||
| 1851 | + )); | ||
| 1852 | + assert!(matches!( | ||
| 1853 | + validate_display_name("nul\0byte"), | ||
| 1854 | + Err(Error::Invalid(_)) | ||
| 1855 | + )); | ||
| 1856 | + } | ||
| 1857 | + | ||
| 1858 | + #[tokio::test] | ||
| 1859 | + async fn display_name_round_trips_and_validates() { | ||
| 1860 | + let dir = tempfile::tempdir().unwrap(); | ||
| 1861 | + let (store, user) = store_with_user(&dir).await; | ||
| 1862 | + assert_eq!(user.display_name, None); | ||
| 1863 | + | ||
| 1864 | + store | ||
| 1865 | + .set_display_name(&user.id, " Ahmet Kaan Gümüş ") | ||
| 1866 | + .await | ||
| 1867 | + .unwrap(); | ||
| 1868 | + let fetched = store.user_by_id(&user.id).await.unwrap().unwrap(); | ||
| 1869 | + assert_eq!(fetched.display_name.as_deref(), Some("Ahmet Kaan Gümüş")); | ||
| 1870 | + | ||
| 1871 | + // Blank input clears the name back to NULL. | ||
| 1872 | + store.set_display_name(&user.id, " ").await.unwrap(); | ||
| 1873 | + let cleared = store.user_by_id(&user.id).await.unwrap().unwrap(); | ||
| 1874 | + assert_eq!(cleared.display_name, None); | ||
| 1875 | + | ||
| 1876 | + // A rejected name leaves the stored value alone. | ||
| 1877 | + store.set_display_name(&user.id, "Kept").await.unwrap(); | ||
| 1878 | + let long = "x".repeat(MAX_DISPLAY_NAME_CHARS + 1); | ||
| 1879 | + assert!(matches!( | ||
| 1880 | + store.set_display_name(&user.id, &long).await, | ||
| 1881 | + Err(Error::Invalid(_)) | ||
| 1882 | + )); | ||
| 1883 | + assert!(matches!( | ||
| 1884 | + store.set_display_name("nobody", "ok").await, | ||
| 1885 | + Err(Error::NotFound) | ||
| 1886 | + )); | ||
| 1887 | + let still = store.user_by_id(&user.id).await.unwrap().unwrap(); | ||
| 1888 | + assert_eq!(still.display_name.as_deref(), Some("Kept")); | ||
| 1889 | + } | ||
| 1890 | + | ||
| 1737 | #[tokio::test] | 1891 | #[tokio::test] |
| 1738 | async fn avatar_upsert_hash_delete() { | 1892 | async fn avatar_upsert_hash_delete() { |
| 1739 | let dir = tempfile::tempdir().unwrap(); | 1893 | let dir = tempfile::tempdir().unwrap(); |
| @@ -2015,7 +2169,7 @@ impl Store { | |||
| 2015 | WHERE collaborators.repo_id = ?1 ORDER BY users.username_folded" | 2169 | WHERE collaborators.repo_id = ?1 ORDER BY users.username_folded" |
| 2016 | ), | 2170 | ), |
| 2017 | (repo_id.to_string(),), | 2171 | (repo_id.to_string(),), |
| 2018 | - |row| Ok((map_user(row)?, parse_role(&col_text(row, 13)?)?)), | 2172 | + |row| Ok((map_user(row)?, parse_role(&col_text(row, 15)?)?)), |
| 2019 | ) | 2173 | ) |
| 2020 | .await | 2174 | .await |
| 2021 | } | 2175 | } |
| @@ -2452,6 +2606,75 @@ mod security_tests { | |||
| 2452 | assert!(!store.totp_state(&user.id).await.unwrap().unwrap().enabled); | 2606 | assert!(!store.totp_state(&user.id).await.unwrap().unwrap().enabled); |
| 2453 | } | 2607 | } |
| 2454 | 2608 | ||
| 2609 | + #[tokio::test] | ||
| 2610 | + async fn totp_device_tracks_added_last_used_and_name() { | ||
| 2611 | + let (store, user, _dir) = store_with_user().await; | ||
| 2612 | + assert_eq!(store.password_changed_at(&user.id).await.unwrap(), None); | ||
| 2613 | + store.set_totp_secret(&user.id, "v1:sealed").await.unwrap(); | ||
| 2614 | + let pending = store.totp_state(&user.id).await.unwrap().unwrap(); | ||
| 2615 | + assert_eq!((pending.created_at, pending.last_used_at), (None, None)); | ||
| 2616 | + | ||
| 2617 | + store | ||
| 2618 | + .enable_totp(&user.id, 100, &[recovery_hash("aaaa-bbbb")]) | ||
| 2619 | + .await | ||
| 2620 | + .unwrap(); | ||
| 2621 | + let on = store.totp_state(&user.id).await.unwrap().unwrap(); | ||
| 2622 | + let added = on.created_at.clone().expect("created_at set on enable"); | ||
| 2623 | + assert_eq!(on.last_used_at.as_deref(), Some(added.as_str())); | ||
| 2624 | + assert_eq!(on.name, None); | ||
| 2625 | + | ||
| 2626 | + store | ||
| 2627 | + .set_totp_name(&user.id, Some("Work phone")) | ||
| 2628 | + .await | ||
| 2629 | + .unwrap(); | ||
| 2630 | + assert_eq!( | ||
| 2631 | + store | ||
| 2632 | + .totp_state(&user.id) | ||
| 2633 | + .await | ||
| 2634 | + .unwrap() | ||
| 2635 | + .unwrap() | ||
| 2636 | + .name | ||
| 2637 | + .as_deref(), | ||
| 2638 | + Some("Work phone") | ||
| 2639 | + ); | ||
| 2640 | + | ||
| 2641 | + // Stamps have nanosecond precision and sort as text, so a later use compares greater. | ||
| 2642 | + std::thread::sleep(std::time::Duration::from_millis(5)); | ||
| 2643 | + assert!(store.accept_totp_step(&user.id, 101).await.unwrap()); | ||
| 2644 | + let used = store.totp_state(&user.id).await.unwrap().unwrap(); | ||
| 2645 | + assert!(used.last_used_at.as_deref().unwrap() > added.as_str()); | ||
| 2646 | + assert_eq!(used.created_at.as_deref(), Some(added.as_str())); | ||
| 2647 | + | ||
| 2648 | + // A replayed step is refused and leaves the last use alone. | ||
| 2649 | + std::thread::sleep(std::time::Duration::from_millis(5)); | ||
| 2650 | + assert!(!store.accept_totp_step(&user.id, 101).await.unwrap()); | ||
| 2651 | + assert_eq!( | ||
| 2652 | + store | ||
| 2653 | + .totp_state(&user.id) | ||
| 2654 | + .await | ||
| 2655 | + .unwrap() | ||
| 2656 | + .unwrap() | ||
| 2657 | + .last_used_at, | ||
| 2658 | + used.last_used_at | ||
| 2659 | + ); | ||
| 2660 | + | ||
| 2661 | + store.set_totp_name(&user.id, None).await.unwrap(); | ||
| 2662 | + assert_eq!( | ||
| 2663 | + store.totp_state(&user.id).await.unwrap().unwrap().name, | ||
| 2664 | + None | ||
| 2665 | + ); | ||
| 2666 | + | ||
| 2667 | + store.disable_totp(&user.id).await.unwrap(); | ||
| 2668 | + let off = store.totp_state(&user.id).await.unwrap().unwrap(); | ||
| 2669 | + assert_eq!( | ||
| 2670 | + (off.name, off.created_at, off.last_used_at), | ||
| 2671 | + (None, None, None) | ||
| 2672 | + ); | ||
| 2673 | + | ||
| 2674 | + store.set_password_hash(&user.id, "new-hash").await.unwrap(); | ||
| 2675 | + assert!(store.password_changed_at(&user.id).await.unwrap().is_some()); | ||
| 2676 | + } | ||
| 2677 | + | ||
| 2455 | fn recovery_hash(code: &str) -> String { | 2678 | fn recovery_hash(code: &str) -> String { |
| 2456 | crate::totp::recovery_code_hash(code) | 2679 | crate::totp::recovery_code_hash(code) |
| 2457 | } | 2680 | } |
crates/forge-core/src/store/orgs.rsmodified+2 -2
| @@ -277,7 +277,7 @@ impl Store { | |||
| 277 | ORDER BY (org_role = 'owner') DESC, username_folded" | 277 | ORDER BY (org_role = 'owner') DESC, username_folded" |
| 278 | ), | 278 | ), |
| 279 | (org_id.to_string(),), | 279 | (org_id.to_string(),), |
| 280 | - |row| Ok((map_user(row)?, OrgMemberRole::parse(&col_text(row, 13)?)?)), | 280 | + |row| Ok((map_user(row)?, OrgMemberRole::parse(&col_text(row, 15)?)?)), |
| 281 | ) | 281 | ) |
| 282 | .await | 282 | .await |
| 283 | } | 283 | } |
| @@ -397,7 +397,7 @@ impl Store { | |||
| 397 | (SELECT org_id FROM org_members WHERE user_id = ?1) ORDER BY username_folded" | 397 | (SELECT org_id FROM org_members WHERE user_id = ?1) ORDER BY username_folded" |
| 398 | ), | 398 | ), |
| 399 | (user_id.to_string(),), | 399 | (user_id.to_string(),), |
| 400 | - |row| Ok((map_user(row)?, OrgMemberRole::parse(&col_text(row, 13)?)?)), | 400 | + |row| Ok((map_user(row)?, OrgMemberRole::parse(&col_text(row, 15)?)?)), |
| 401 | ) | 401 | ) |
| 402 | .await | 402 | .await |
| 403 | } | 403 | } |
crates/forge-core/src/store/ui_prefs.rsmodified+75 -3
| @@ -1,6 +1,7 @@ | |||
| 1 | -//! Per-user UI preferences: the colour theme and the language. Both are stored as text in | 1 | +//! Per-user UI preferences: the colour theme, the language and the accent colour. All are stored |
| 2 | -//! `users` (migration 0030). The web layer decides which values it offers; the store only | 2 | +//! as text in `users` (migrations 0030 and 0041). The web layer decides which values it offers; |
| 3 | -//! checks that a value is well formed, so a new language needs no store change. | 3 | +//! the store only checks that a value is well formed, so a new language or accent needs no store |
| 4 | +//! change. | ||
| 4 | 5 | ||
| 5 | use super::{Store, db_err}; | 6 | use super::{Store, db_err}; |
| 6 | use crate::error::{Error, Result}; | 7 | use crate::error::{Error, Result}; |
| @@ -11,9 +12,16 @@ pub const THEMES: &[&str] = &["auto", "light", "dark"]; | |||
| 11 | /// The value meaning "follow the default", for both theme and language. | 12 | /// The value meaning "follow the default", for both theme and language. |
| 12 | pub const AUTO: &str = "auto"; | 13 | pub const AUTO: &str = "auto"; |
| 13 | 14 | ||
| 15 | +/// The accent colour a new user gets. It must match the default palette in forge-web's | ||
| 16 | +/// `accent_palette.rs`, which a test there checks. | ||
| 17 | +pub const DEFAULT_ACCENT: &str = "sage"; | ||
| 18 | + | ||
| 14 | /// Longest accepted language code, in bytes. | 19 | /// Longest accepted language code, in bytes. |
| 15 | const MAX_LANGUAGE_LEN: usize = 16; | 20 | const MAX_LANGUAGE_LEN: usize = 16; |
| 16 | 21 | ||
| 22 | +/// Longest accepted accent id, in bytes. | ||
| 23 | +const MAX_ACCENT_LEN: usize = 24; | ||
| 24 | + | ||
| 17 | /// True for `auto` or a BCP 47 style tag such as `en`, `tr` or `pt-BR`. | 25 | /// True for `auto` or a BCP 47 style tag such as `en`, `tr` or `pt-BR`. |
| 18 | pub fn valid_language(code: &str) -> bool { | 26 | pub fn valid_language(code: &str) -> bool { |
| 19 | if code == AUTO { | 27 | if code == AUTO { |
| @@ -30,6 +38,15 @@ pub fn valid_language(code: &str) -> bool { | |||
| 30 | && parts.all(|p| (1..=8).contains(&p.len()) && p.bytes().all(|b| b.is_ascii_alphanumeric())) | 38 | && parts.all(|p| (1..=8).contains(&p.len()) && p.bytes().all(|b| b.is_ascii_alphanumeric())) |
| 31 | } | 39 | } |
| 32 | 40 | ||
| 41 | +/// True for a short lowercase slug such as `sage` or `rose-2`: 1 to 24 ASCII letters, digits or | ||
| 42 | +/// hyphens. Whether forge offers the id is the web layer's call. | ||
| 43 | +pub fn valid_accent(id: &str) -> bool { | ||
| 44 | + (1..=MAX_ACCENT_LEN).contains(&id.len()) | ||
| 45 | + && id | ||
| 46 | + .bytes() | ||
| 47 | + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') | ||
| 48 | +} | ||
| 49 | + | ||
| 33 | impl Store { | 50 | impl Store { |
| 34 | /// Sets the user's theme and language. Anything malformed is rejected and nothing is written. | 51 | /// Sets the user's theme and language. Anything malformed is rejected and nothing is written. |
| 35 | pub async fn set_ui_prefs(&self, user_id: &str, theme: &str, language: &str) -> Result<()> { | 52 | pub async fn set_ui_prefs(&self, user_id: &str, theme: &str, language: &str) -> Result<()> { |
| @@ -53,6 +70,25 @@ impl Store { | |||
| 53 | Ok(()) | 70 | Ok(()) |
| 54 | } | 71 | } |
| 55 | 72 | ||
| 73 | + /// Sets the user's accent colour id. A malformed id is rejected and nothing is written. | ||
| 74 | + pub async fn set_accent(&self, user_id: &str, accent: &str) -> Result<()> { | ||
| 75 | + if !valid_accent(accent) { | ||
| 76 | + return Err(Error::Invalid(format!("accent {accent:?}"))); | ||
| 77 | + } | ||
| 78 | + let conn = self.inner.conn.lock().await; | ||
| 79 | + let n = conn | ||
| 80 | + .execute( | ||
| 81 | + "UPDATE users SET accent = ?2 WHERE id = ?1", | ||
| 82 | + (user_id.to_string(), accent.to_string()), | ||
| 83 | + ) | ||
| 84 | + .await | ||
| 85 | + .map_err(db_err)?; | ||
| 86 | + if n == 0 { | ||
| 87 | + return Err(Error::NotFound); | ||
| 88 | + } | ||
| 89 | + Ok(()) | ||
| 90 | + } | ||
| 91 | + | ||
| 56 | /// Turns the email copy of notifications on or off for one user (migration 0035). | 92 | /// Turns the email copy of notifications on or off for one user (migration 0035). |
| 57 | pub async fn set_email_notifications(&self, user_id: &str, on: bool) -> Result<()> { | 93 | pub async fn set_email_notifications(&self, user_id: &str, on: bool) -> Result<()> { |
| 58 | let conn = self.inner.conn.lock().await; | 94 | let conn = self.inner.conn.lock().await; |
| @@ -87,6 +123,42 @@ mod tests { | |||
| 87 | assert!(!valid_language(&"a".repeat(MAX_LANGUAGE_LEN + 1))); | 123 | assert!(!valid_language(&"a".repeat(MAX_LANGUAGE_LEN + 1))); |
| 88 | } | 124 | } |
| 89 | 125 | ||
| 126 | + #[test] | ||
| 127 | + fn accent_ids() { | ||
| 128 | + let longest = "a".repeat(MAX_ACCENT_LEN); | ||
| 129 | + let too_long = "a".repeat(MAX_ACCENT_LEN + 1); | ||
| 130 | + for ok in ["sage", "rose-2", "a", longest.as_str()] { | ||
| 131 | + assert!(valid_accent(ok), "{ok}"); | ||
| 132 | + } | ||
| 133 | + for bad in ["", "Sage", "sage_2", "../x", "a b", too_long.as_str()] { | ||
| 134 | + assert!(!valid_accent(bad), "{bad}"); | ||
| 135 | + } | ||
| 136 | + } | ||
| 137 | + | ||
| 138 | + #[tokio::test] | ||
| 139 | + async fn accent_persists_and_bad_values_change_nothing() { | ||
| 140 | + let dir = tempfile::tempdir().unwrap(); | ||
| 141 | + let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); | ||
| 142 | + let user = store | ||
| 143 | + .create_user("tahinli", None, "hash", false) | ||
| 144 | + .await | ||
| 145 | + .unwrap(); | ||
| 146 | + assert_eq!(user.accent, DEFAULT_ACCENT); | ||
| 147 | + | ||
| 148 | + store.set_accent(&user.id, "ocean").await.unwrap(); | ||
| 149 | + assert_eq!( | ||
| 150 | + store.user_by_id(&user.id).await.unwrap().unwrap().accent, | ||
| 151 | + "ocean" | ||
| 152 | + ); | ||
| 153 | + | ||
| 154 | + assert!(store.set_accent(&user.id, "Ocean").await.is_err()); | ||
| 155 | + assert!(store.set_accent(&user.id, "../x").await.is_err()); | ||
| 156 | + assert_eq!( | ||
| 157 | + store.user_by_id(&user.id).await.unwrap().unwrap().accent, | ||
| 158 | + "ocean" | ||
| 159 | + ); | ||
| 160 | + } | ||
| 161 | + | ||
| 90 | #[tokio::test] | 162 | #[tokio::test] |
| 91 | async fn prefs_persist_and_bad_values_change_nothing() { | 163 | async fn prefs_persist_and_bad_values_change_nothing() { |
| 92 | let dir = tempfile::tempdir().unwrap(); | 164 | let dir = tempfile::tempdir().unwrap(); |
crates/forge-core/src/store/user_delete.rsmodified+9 -1
| @@ -161,10 +161,12 @@ impl Store { | |||
| 161 | is_admin: false, | 161 | is_admin: false, |
| 162 | created_at: now_stamp(), | 162 | created_at: now_stamp(), |
| 163 | about: String::new(), | 163 | about: String::new(), |
| 164 | + display_name: None, | ||
| 164 | timezone: "UTC".to_string(), | 165 | timezone: "UTC".to_string(), |
| 165 | avatar_hash: None, | 166 | avatar_hash: None, |
| 166 | theme: "light".into(), | 167 | theme: "light".into(), |
| 167 | language: "auto".into(), | 168 | language: "auto".into(), |
| 169 | + accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(), | ||
| 168 | kind: AccountKind::User, | 170 | kind: AccountKind::User, |
| 169 | email_notifications: true, | 171 | email_notifications: true, |
| 170 | }; | 172 | }; |
| @@ -525,7 +527,13 @@ mod tests { | |||
| 525 | .await | 527 | .await |
| 526 | .unwrap(); | 528 | .unwrap(); |
| 527 | fx.store | 529 | fx.store |
| 528 | - .add_ssh_key(&fx.tahinli.id, "laptop", "ssh-ed25519", b"blob-1", "SHA256:x") | 530 | + .add_ssh_key( |
| 531 | + &fx.tahinli.id, | ||
| 532 | + "laptop", | ||
| 533 | + "ssh-ed25519", | ||
| 534 | + b"blob-1", | ||
| 535 | + "SHA256:x", | ||
| 536 | + ) | ||
| 529 | .await | 537 | .await |
| 530 | .unwrap(); | 538 | .unwrap(); |
| 531 | fx.store | 539 | fx.store |
crates/forge-core/src/time.rsmodified+15 -0
| @@ -40,10 +40,25 @@ pub fn stamp_ago(ago: Duration) -> String { | |||
| 40 | format_stamp(OffsetDateTime::now_utc().saturating_sub(delta)) | 40 | format_stamp(OffsetDateTime::now_utc().saturating_sub(delta)) |
| 41 | } | 41 | } |
| 42 | 42 | ||
| 43 | +/// Unix seconds for a stamp written by [`now_stamp`]. `None` when the text is not a stamp. | ||
| 44 | +pub fn stamp_to_unix(stamp: &str) -> Option<i64> { | ||
| 45 | + OffsetDateTime::parse(stamp, &time::format_description::well_known::Rfc3339) | ||
| 46 | + .ok() | ||
| 47 | + .map(OffsetDateTime::unix_timestamp) | ||
| 48 | +} | ||
| 49 | + | ||
| 43 | #[cfg(test)] | 50 | #[cfg(test)] |
| 44 | mod tests { | 51 | mod tests { |
| 45 | use super::*; | 52 | use super::*; |
| 46 | 53 | ||
| 54 | + #[test] | ||
| 55 | + fn stamp_to_unix_reads_what_now_stamp_writes() { | ||
| 56 | + let stamp = "2026-10-18T10:00:00.000000000Z"; | ||
| 57 | + assert_eq!(stamp_to_unix(stamp), Some(1_792_317_600)); | ||
| 58 | + assert!(stamp_to_unix(&now_stamp()).is_some()); | ||
| 59 | + assert_eq!(stamp_to_unix("yesterday"), None); | ||
| 60 | + } | ||
| 61 | + | ||
| 47 | fn is_valid_stamp(s: &str) -> bool { | 62 | fn is_valid_stamp(s: &str) -> bool { |
| 48 | let b = s.as_bytes(); | 63 | let b = s.as_bytes(); |
| 49 | b.len() == 30 | 64 | b.len() == 30 |
crates/forge-web/assets/nav.jsmodified+1 -1
| @@ -127,7 +127,7 @@ | |||
| 127 | 127 | ||
| 128 | function adopt(doc, keepFields, dd) { | 128 | function adopt(doc, keepFields, dd) { |
| 129 | document.title = doc.title; | 129 | document.title = doc.title; |
| 130 | - ['lang', 'data-theme', 'data-ui'].forEach(function (name) { | 130 | + ['lang', 'data-theme', 'data-accent', 'data-ui'].forEach(function (name) { |
| 131 | if (doc.documentElement.hasAttribute(name)) { root.setAttribute(name, doc.documentElement.getAttribute(name)); } | 131 | if (doc.documentElement.hasAttribute(name)) { root.setAttribute(name, doc.documentElement.getAttribute(name)); } |
| 132 | else { root.removeAttribute(name); } | 132 | else { root.removeAttribute(name); } |
| 133 | }); | 133 | }); |
crates/forge-web/build.rsmodified+80 -1
| @@ -1,21 +1,98 @@ | |||
| 1 | //! Compiles style/main.scss into OUT_DIR and emits FORGE_BUILD_SHA for the binary. Each static | 1 | //! Compiles style/main.scss into OUT_DIR and emits FORGE_BUILD_SHA for the binary. Each static |
| 2 | //! asset also gets a content hash (FORGE_MAIN_CSS_V, FORGE_NAV_JS_V) that the page links use as | 2 | //! asset also gets a content hash (FORGE_MAIN_CSS_V, FORGE_NAV_JS_V) that the page links use as |
| 3 | //! their cache-busting query, so an unchanged file keeps its URL and a changed one gets a new one. | 3 | //! their cache-busting query, so an unchanged file keeps its URL and a changed one gets a new one. |
| 4 | +//! | ||
| 5 | +//! The accent colours come from `src/accent_palette.rs`, the same data the app reads. This script | ||
| 6 | +//! turns it into `_accents.scss` in OUT_DIR, which main.scss imports. | ||
| 4 | 7 | ||
| 5 | use std::{env, fs, path::PathBuf}; | 8 | use std::{env, fs, path::PathBuf}; |
| 6 | 9 | ||
| 7 | use hex::encode; | 10 | use hex::encode; |
| 8 | use sha2::{Digest, Sha256}; | 11 | use sha2::{Digest, Sha256}; |
| 9 | 12 | ||
| 13 | +#[path = "src/accent_palette.rs"] | ||
| 14 | +#[allow(dead_code)] | ||
| 15 | +mod accent_palette; | ||
| 16 | + | ||
| 17 | +use accent_palette::{DEFAULT, PALETTES, Palette, TOKEN_VARS, Tokens}; | ||
| 18 | + | ||
| 10 | /// First 12 hex characters of the SHA-256 of `bytes`. | 19 | /// First 12 hex characters of the SHA-256 of `bytes`. |
| 11 | fn content_version(bytes: &[u8]) -> String { | 20 | fn content_version(bytes: &[u8]) -> String { |
| 12 | encode(Sha256::digest(bytes))[..12].to_string() | 21 | encode(Sha256::digest(bytes))[..12].to_string() |
| 13 | } | 22 | } |
| 14 | 23 | ||
| 24 | +/// One `--token: value;` line per token, indented for a rule body. | ||
| 25 | +fn declarations(tokens: &Tokens) -> String { | ||
| 26 | + TOKEN_VARS | ||
| 27 | + .iter() | ||
| 28 | + .map(|token| format!(" {}: {};\n", token.name, (token.value)(tokens))) | ||
| 29 | + .collect() | ||
| 30 | +} | ||
| 31 | + | ||
| 32 | +/// Appends `selector { … }` with the palette's tokens for one theme. `indent` is 0 or 2. | ||
| 33 | +fn rule(css: &mut String, indent: &str, selector: &str, tokens: &Tokens) { | ||
| 34 | + css.push_str(&format!("{indent}{selector} {{\n")); | ||
| 35 | + for line in declarations(tokens).lines() { | ||
| 36 | + css.push_str(&format!("{indent}{line}\n")); | ||
| 37 | + } | ||
| 38 | + css.push_str(&format!("{indent}}}\n")); | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +/// The rules for one palette. The default palette sits on bare `:root`, as it always has. Every | ||
| 42 | +/// other palette is scoped to `[data-accent]`, which is more specific, so it wins over the | ||
| 43 | +/// default in all three theme states: light, dark by `data-theme`, and dark by the OS. | ||
| 44 | +fn palette_rules(css: &mut String, palette: &Palette) { | ||
| 45 | + let base = if palette.id == DEFAULT { | ||
| 46 | + ":root".to_string() | ||
| 47 | + } else { | ||
| 48 | + format!(":root[data-accent=\"{}\"]", palette.id) | ||
| 49 | + }; | ||
| 50 | + let os_dark = format!("{base}:not([data-theme=\"light\"])"); | ||
| 51 | + let forced_dark = format!("{base}[data-theme=\"dark\"]"); | ||
| 52 | + rule(css, "", &base, &palette.light); | ||
| 53 | + css.push_str("@media (prefers-color-scheme: dark) {\n"); | ||
| 54 | + rule(css, " ", &os_dark, &palette.dark); | ||
| 55 | + css.push_str("}\n"); | ||
| 56 | + rule(css, "", &forced_dark, &palette.dark); | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +/// The swatch chip for one palette in the settings picker: its accent, light or dark. | ||
| 60 | +fn swatch_rules(css: &mut String, palette: &Palette) { | ||
| 61 | + let swatch = format!(".accent-swatch[data-accent-swatch=\"{}\"]", palette.id); | ||
| 62 | + css.push_str(&format!( | ||
| 63 | + "{swatch} {{ background: {}; }}\n", | ||
| 64 | + palette.light.accent | ||
| 65 | + )); | ||
| 66 | + css.push_str(&format!( | ||
| 67 | + "@media (prefers-color-scheme: dark) {{\n :root:not([data-theme=\"light\"]) {swatch} {{ background: {}; }}\n}}\n", | ||
| 68 | + palette.dark.accent | ||
| 69 | + )); | ||
| 70 | + css.push_str(&format!( | ||
| 71 | + ":root[data-theme=\"dark\"] {swatch} {{ background: {}; }}\n", | ||
| 72 | + palette.dark.accent | ||
| 73 | + )); | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +/// The whole generated stylesheet: the palettes, then the swatch chips. | ||
| 77 | +fn accents_scss() -> String { | ||
| 78 | + let mut css = String::from( | ||
| 79 | + "/* Generated by crates/forge-web/build.rs from src/accent_palette.rs. Edit that file. */\n", | ||
| 80 | + ); | ||
| 81 | + assert_eq!(PALETTES[0].id, DEFAULT, "the default palette comes first"); | ||
| 82 | + for palette in PALETTES { | ||
| 83 | + palette_rules(&mut css, palette); | ||
| 84 | + } | ||
| 85 | + for palette in PALETTES { | ||
| 86 | + swatch_rules(&mut css, palette); | ||
| 87 | + } | ||
| 88 | + css | ||
| 89 | +} | ||
| 90 | + | ||
| 15 | fn main() { | 91 | fn main() { |
| 16 | println!("cargo:rerun-if-env-changed=FORGE_BUILD_SHA"); | 92 | println!("cargo:rerun-if-env-changed=FORGE_BUILD_SHA"); |
| 17 | println!("cargo:rerun-if-changed=../../style"); | 93 | println!("cargo:rerun-if-changed=../../style"); |
| 18 | println!("cargo:rerun-if-changed=assets/nav.js"); | 94 | println!("cargo:rerun-if-changed=assets/nav.js"); |
| 95 | + println!("cargo:rerun-if-changed=src/accent_palette.rs"); | ||
| 19 | 96 | ||
| 20 | let sha = env::var("FORGE_BUILD_SHA").unwrap_or_else(|_| "dev".to_string()); | 97 | let sha = env::var("FORGE_BUILD_SHA").unwrap_or_else(|_| "dev".to_string()); |
| 21 | println!("cargo:rustc-env=FORGE_BUILD_SHA={sha}"); | 98 | println!("cargo:rustc-env=FORGE_BUILD_SHA={sha}"); |
| @@ -23,9 +100,11 @@ fn main() { | |||
| 23 | let manifest = | 100 | let manifest = |
| 24 | PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set by cargo")); | 101 | PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set by cargo")); |
| 25 | let out = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR is set by cargo")); | 102 | let out = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR is set by cargo")); |
| 103 | + fs::write(out.join("_accents.scss"), accents_scss()) | ||
| 104 | + .expect("writing generated accent stylesheet to OUT_DIR"); | ||
| 26 | let css = grass::from_path( | 105 | let css = grass::from_path( |
| 27 | manifest.join("../../style/main.scss"), | 106 | manifest.join("../../style/main.scss"), |
| 28 | - &grass::Options::default(), | 107 | + &grass::Options::default().load_path(&out), |
| 29 | ) | 108 | ) |
| 30 | .unwrap_or_else(|e| panic!("compiling style/main.scss: {e}")); | 109 | .unwrap_or_else(|e| panic!("compiling style/main.scss: {e}")); |
| 31 | println!( | 110 | println!( |
crates/forge-web/src/accent.rsadded+155 -0
| @@ -0,0 +1,155 @@ | |||
| 1 | +//! Accent colour: which palette a viewer sees. The colours live in `accent_palette.rs`, which | ||
| 2 | +//! `build.rs` also turns into the stylesheet. This module only resolves stored ids and checks | ||
| 3 | +//! which ids forge offers. | ||
| 4 | + | ||
| 5 | +use crate::accent_palette::{DEFAULT, PALETTES, Palette}; | ||
| 6 | + | ||
| 7 | +/// The palette for a stored id. An unknown or removed id falls back to the default. | ||
| 8 | +pub fn resolve(stored: &str) -> &'static Palette { | ||
| 9 | + PALETTES | ||
| 10 | + .iter() | ||
| 11 | + .find(|p| p.id == stored) | ||
| 12 | + .unwrap_or_else(default_palette) | ||
| 13 | +} | ||
| 14 | + | ||
| 15 | +/// True when forge offers this id. | ||
| 16 | +pub fn is_offered(id: &str) -> bool { | ||
| 17 | + PALETTES.iter().any(|p| p.id == id) | ||
| 18 | +} | ||
| 19 | + | ||
| 20 | +/// Every offered id, in the order the picker lists them. | ||
| 21 | +pub fn ids() -> impl Iterator<Item = &'static str> { | ||
| 22 | + PALETTES.iter().map(|p| p.id) | ||
| 23 | +} | ||
| 24 | + | ||
| 25 | +fn default_palette() -> &'static Palette { | ||
| 26 | + PALETTES | ||
| 27 | + .iter() | ||
| 28 | + .find(|p| p.id == DEFAULT) | ||
| 29 | + .expect("the default accent is one of the palettes") | ||
| 30 | +} | ||
| 31 | + | ||
| 32 | +#[cfg(test)] | ||
| 33 | +mod tests { | ||
| 34 | + use std::collections::HashSet; | ||
| 35 | + | ||
| 36 | + use super::*; | ||
| 37 | + use crate::accent_palette::{TOKEN_VARS, Tokens}; | ||
| 38 | + | ||
| 39 | + /// The neutral backgrounds of style/main.scss, in each theme. | ||
| 40 | + const LIGHT_BG: &str = "#F6F8F5"; | ||
| 41 | + const LIGHT_SURFACE: &str = "#FFFFFF"; | ||
| 42 | + const DARK_BG: &str = "#121613"; | ||
| 43 | + const DARK_SURFACE: &str = "#191E1A"; | ||
| 44 | + | ||
| 45 | + /// WCAG relative luminance of a `#RRGGBB` colour. | ||
| 46 | + fn luminance(hex: &str) -> f64 { | ||
| 47 | + let channel = |i: usize| { | ||
| 48 | + let v = f64::from(u8::from_str_radix(&hex[i..i + 2], 16).expect("hex")) / 255.0; | ||
| 49 | + if v <= 0.03928 { | ||
| 50 | + v / 12.92 | ||
| 51 | + } else { | ||
| 52 | + ((v + 0.055) / 1.055).powf(2.4) | ||
| 53 | + } | ||
| 54 | + }; | ||
| 55 | + 0.2126 * channel(1) + 0.7152 * channel(3) + 0.0722 * channel(5) | ||
| 56 | + } | ||
| 57 | + | ||
| 58 | + /// WCAG contrast ratio between two colours. | ||
| 59 | + fn contrast(a: &str, b: &str) -> f64 { | ||
| 60 | + let (x, y) = (luminance(a), luminance(b)); | ||
| 61 | + (x.max(y) + 0.05) / (x.min(y) + 0.05) | ||
| 62 | + } | ||
| 63 | + | ||
| 64 | + fn is_hex_colour(value: &str) -> bool { | ||
| 65 | + value.len() == 7 | ||
| 66 | + && value.starts_with('#') | ||
| 67 | + && value[1..].bytes().all(|b| b.is_ascii_hexdigit()) | ||
| 68 | + } | ||
| 69 | + | ||
| 70 | + #[test] | ||
| 71 | + fn ids_are_slugs_unique_and_the_default_comes_first() { | ||
| 72 | + assert_eq!(PALETTES[0].id, DEFAULT); | ||
| 73 | + assert_eq!(DEFAULT, forge_core::store::ui_prefs::DEFAULT_ACCENT); | ||
| 74 | + let mut seen = HashSet::new(); | ||
| 75 | + for p in PALETTES { | ||
| 76 | + assert!( | ||
| 77 | + forge_core::store::ui_prefs::valid_accent(p.id), | ||
| 78 | + "{} is not a slug", | ||
| 79 | + p.id | ||
| 80 | + ); | ||
| 81 | + assert!(seen.insert(p.id), "{} is listed twice", p.id); | ||
| 82 | + } | ||
| 83 | + } | ||
| 84 | + | ||
| 85 | + #[test] | ||
| 86 | + fn every_token_is_a_hex_colour() { | ||
| 87 | + for p in PALETTES { | ||
| 88 | + for token in TOKEN_VARS { | ||
| 89 | + for t in [&p.light, &p.dark] { | ||
| 90 | + assert!(is_hex_colour((token.value)(t)), "{} {}", p.id, token.name); | ||
| 91 | + } | ||
| 92 | + } | ||
| 93 | + } | ||
| 94 | + } | ||
| 95 | + | ||
| 96 | + #[test] | ||
| 97 | + fn unknown_and_removed_ids_fall_back_to_the_default() { | ||
| 98 | + assert_eq!(resolve("ocean").id, "ocean"); | ||
| 99 | + assert_eq!(resolve("removed-palette").id, DEFAULT); | ||
| 100 | + assert_eq!(resolve("").id, DEFAULT); | ||
| 101 | + assert!(is_offered("plum")); | ||
| 102 | + assert!(!is_offered("removed-palette")); | ||
| 103 | + } | ||
| 104 | + | ||
| 105 | + #[test] | ||
| 106 | + fn every_palette_meets_the_contrast_targets() { | ||
| 107 | + for p in PALETTES { | ||
| 108 | + let themes = [ | ||
| 109 | + ("light", &p.light, LIGHT_BG, LIGHT_SURFACE), | ||
| 110 | + ("dark", &p.dark, DARK_BG, DARK_SURFACE), | ||
| 111 | + ]; | ||
| 112 | + for (theme, t, bg, surface) in themes { | ||
| 113 | + let check = |what: &str, ratio: f64, min: f64| { | ||
| 114 | + assert!(ratio >= min, "{} {theme} {what}: {ratio:.2} < {min}", p.id); | ||
| 115 | + }; | ||
| 116 | + check( | ||
| 117 | + "accent_text on accent", | ||
| 118 | + contrast(t.accent_text, t.accent), | ||
| 119 | + 4.5, | ||
| 120 | + ); | ||
| 121 | + check("accent_ink on bg", contrast(t.accent_ink, bg), 4.5); | ||
| 122 | + check( | ||
| 123 | + "accent_ink on surface", | ||
| 124 | + contrast(t.accent_ink, surface), | ||
| 125 | + 4.5, | ||
| 126 | + ); | ||
| 127 | + check( | ||
| 128 | + "accent_ink on accent_soft", | ||
| 129 | + contrast(t.accent_ink, t.accent_soft), | ||
| 130 | + 4.5, | ||
| 131 | + ); | ||
| 132 | + check( | ||
| 133 | + "public_text on public_bg", | ||
| 134 | + contrast(t.public_text, t.public_bg), | ||
| 135 | + 4.5, | ||
| 136 | + ); | ||
| 137 | + check("focus on bg", contrast(t.focus, bg), 3.0); | ||
| 138 | + } | ||
| 139 | + } | ||
| 140 | + } | ||
| 141 | + | ||
| 142 | + #[test] | ||
| 143 | + fn heatmap_steps_grow_in_lightness_towards_the_strong_end() { | ||
| 144 | + fn steps(t: &Tokens) -> [f64; 5] { | ||
| 145 | + [t.h0, t.h1, t.h2, t.h3, t.h4].map(luminance) | ||
| 146 | + } | ||
| 147 | + for p in PALETTES { | ||
| 148 | + // Light theme: each step is darker than the one before. Dark theme: each is lighter. | ||
| 149 | + let light = steps(&p.light); | ||
| 150 | + assert!(light.windows(2).all(|w| w[0] > w[1]), "{} light", p.id); | ||
| 151 | + let dark = steps(&p.dark); | ||
| 152 | + assert!(dark.windows(2).all(|w| w[0] < w[1]), "{} dark", p.id); | ||
| 153 | + } | ||
| 154 | + } | ||
| 155 | +} | ||
crates/forge-web/src/accent_palette.rsadded+338 -0
| @@ -0,0 +1,338 @@ | |||
| 1 | +//! Accent palettes: the one place where the accent colours are defined. Nothing else holds | ||
| 2 | +//! these values. `build.rs` reads this file to generate the accent stylesheet, and the app | ||
| 3 | +//! reads it to resolve a stored id and to list the settings picker. Keep it pure data: no `use`, | ||
| 4 | +//! no crate items, no external crates. | ||
| 5 | + | ||
| 6 | +/// The colour tokens one palette sets in one theme. The values are CSS colours; `TOKEN_VARS` | ||
| 7 | +/// names the custom property each field becomes. | ||
| 8 | +pub struct Tokens { | ||
| 9 | + pub accent: &'static str, | ||
| 10 | + pub accent_ink: &'static str, | ||
| 11 | + pub accent_soft: &'static str, | ||
| 12 | + pub accent_text: &'static str, | ||
| 13 | + pub focus: &'static str, | ||
| 14 | + pub public_bg: &'static str, | ||
| 15 | + pub public_text: &'static str, | ||
| 16 | + pub note: &'static str, | ||
| 17 | + pub hunk_bg: &'static str, | ||
| 18 | + pub hunk_text: &'static str, | ||
| 19 | + pub h0: &'static str, | ||
| 20 | + pub h1: &'static str, | ||
| 21 | + pub h2: &'static str, | ||
| 22 | + pub h3: &'static str, | ||
| 23 | + pub h4: &'static str, | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +/// One accent colour: its id (the stored value and the `data-accent` attribute), and the tokens | ||
| 27 | +/// used in light and dark themes. | ||
| 28 | +pub struct Palette { | ||
| 29 | + pub id: &'static str, | ||
| 30 | + pub light: Tokens, | ||
| 31 | + pub dark: Tokens, | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +/// The palette used when none is stored, and for anonymous visitors. It must be `PALETTES[0]`. | ||
| 35 | +pub const DEFAULT: &str = "sage"; | ||
| 36 | + | ||
| 37 | +/// One token: the custom property it becomes and the field of `Tokens` that holds its value. | ||
| 38 | +pub struct TokenVar { | ||
| 39 | + pub name: &'static str, | ||
| 40 | + pub value: fn(&Tokens) -> &'static str, | ||
| 41 | +} | ||
| 42 | + | ||
| 43 | +/// Every token a palette sets. | ||
| 44 | +pub const TOKEN_VARS: &[TokenVar] = &[ | ||
| 45 | + TokenVar { | ||
| 46 | + name: "--accent", | ||
| 47 | + value: |t| t.accent, | ||
| 48 | + }, | ||
| 49 | + TokenVar { | ||
| 50 | + name: "--accent-ink", | ||
| 51 | + value: |t| t.accent_ink, | ||
| 52 | + }, | ||
| 53 | + TokenVar { | ||
| 54 | + name: "--accent-soft", | ||
| 55 | + value: |t| t.accent_soft, | ||
| 56 | + }, | ||
| 57 | + TokenVar { | ||
| 58 | + name: "--accent-text", | ||
| 59 | + value: |t| t.accent_text, | ||
| 60 | + }, | ||
| 61 | + TokenVar { | ||
| 62 | + name: "--focus", | ||
| 63 | + value: |t| t.focus, | ||
| 64 | + }, | ||
| 65 | + TokenVar { | ||
| 66 | + name: "--public-bg", | ||
| 67 | + value: |t| t.public_bg, | ||
| 68 | + }, | ||
| 69 | + TokenVar { | ||
| 70 | + name: "--public-text", | ||
| 71 | + value: |t| t.public_text, | ||
| 72 | + }, | ||
| 73 | + TokenVar { | ||
| 74 | + name: "--note", | ||
| 75 | + value: |t| t.note, | ||
| 76 | + }, | ||
| 77 | + TokenVar { | ||
| 78 | + name: "--hunk-bg", | ||
| 79 | + value: |t| t.hunk_bg, | ||
| 80 | + }, | ||
| 81 | + TokenVar { | ||
| 82 | + name: "--hunk-text", | ||
| 83 | + value: |t| t.hunk_text, | ||
| 84 | + }, | ||
| 85 | + TokenVar { | ||
| 86 | + name: "--h0", | ||
| 87 | + value: |t| t.h0, | ||
| 88 | + }, | ||
| 89 | + TokenVar { | ||
| 90 | + name: "--h1", | ||
| 91 | + value: |t| t.h1, | ||
| 92 | + }, | ||
| 93 | + TokenVar { | ||
| 94 | + name: "--h2", | ||
| 95 | + value: |t| t.h2, | ||
| 96 | + }, | ||
| 97 | + TokenVar { | ||
| 98 | + name: "--h3", | ||
| 99 | + value: |t| t.h3, | ||
| 100 | + }, | ||
| 101 | + TokenVar { | ||
| 102 | + name: "--h4", | ||
| 103 | + value: |t| t.h4, | ||
| 104 | + }, | ||
| 105 | +]; | ||
| 106 | + | ||
| 107 | +/// Every accent colour on offer, in the order the picker lists them. Heatmap steps run from | ||
| 108 | +/// `h0` (nearly the background) to `h4` (strongest). | ||
| 109 | +pub const PALETTES: &[Palette] = &[ | ||
| 110 | + // Sage: the original forge colour. | ||
| 111 | + Palette { | ||
| 112 | + id: "sage", | ||
| 113 | + light: Tokens { | ||
| 114 | + accent: "#5E7D63", | ||
| 115 | + accent_ink: "#4A6750", | ||
| 116 | + accent_soft: "#E4ECE3", | ||
| 117 | + accent_text: "#FFFFFF", | ||
| 118 | + focus: "#4A6750", | ||
| 119 | + public_bg: "#E4ECE3", | ||
| 120 | + public_text: "#4A6750", | ||
| 121 | + note: "#4A6750", | ||
| 122 | + hunk_bg: "#EDF1EB", | ||
| 123 | + hunk_text: "#3F5F46", | ||
| 124 | + h0: "#E6ECE4", | ||
| 125 | + h1: "#C6D9C8", | ||
| 126 | + h2: "#9DBDA2", | ||
| 127 | + h3: "#6F9676", | ||
| 128 | + h4: "#3F5F46", | ||
| 129 | + }, | ||
| 130 | + dark: Tokens { | ||
| 131 | + accent: "#9DBEA2", | ||
| 132 | + accent_ink: "#B5D2B9", | ||
| 133 | + accent_soft: "#233026", | ||
| 134 | + accent_text: "#0F1510", | ||
| 135 | + focus: "#9DBEA2", | ||
| 136 | + public_bg: "#233026", | ||
| 137 | + public_text: "#B5D2B9", | ||
| 138 | + note: "#B5D2B9", | ||
| 139 | + hunk_bg: "#1E2620", | ||
| 140 | + hunk_text: "#9DBEA2", | ||
| 141 | + h0: "#1F2722", | ||
| 142 | + h1: "#2D3D31", | ||
| 143 | + h2: "#41604A", | ||
| 144 | + h3: "#628A6C", | ||
| 145 | + h4: "#9DBEA2", | ||
| 146 | + }, | ||
| 147 | + }, | ||
| 148 | + // Blue, clear and cool. | ||
| 149 | + Palette { | ||
| 150 | + id: "ocean", | ||
| 151 | + light: Tokens { | ||
| 152 | + accent: "#467799", | ||
| 153 | + accent_ink: "#336180", | ||
| 154 | + accent_soft: "#DEECF6", | ||
| 155 | + accent_text: "#FFFFFF", | ||
| 156 | + focus: "#336180", | ||
| 157 | + public_bg: "#DEECF6", | ||
| 158 | + public_text: "#336180", | ||
| 159 | + note: "#336180", | ||
| 160 | + hunk_bg: "#E9F1F7", | ||
| 161 | + hunk_text: "#2B5977", | ||
| 162 | + h0: "#DFECF5", | ||
| 163 | + h1: "#BED7EA", | ||
| 164 | + h2: "#99BEDA", | ||
| 165 | + h3: "#6692B1", | ||
| 166 | + h4: "#2C5D7E", | ||
| 167 | + }, | ||
| 168 | + dark: Tokens { | ||
| 169 | + accent: "#86B9DD", | ||
| 170 | + accent_ink: "#9FCBEA", | ||
| 171 | + accent_soft: "#1C2F3C", | ||
| 172 | + accent_text: "#061118", | ||
| 173 | + focus: "#86B9DD", | ||
| 174 | + public_bg: "#1C2F3C", | ||
| 175 | + public_text: "#9FCBEA", | ||
| 176 | + note: "#9FCBEA", | ||
| 177 | + hunk_bg: "#1A252E", | ||
| 178 | + hunk_text: "#86B9DD", | ||
| 179 | + h0: "#1B262F", | ||
| 180 | + h1: "#243B4C", | ||
| 181 | + h2: "#375C76", | ||
| 182 | + h3: "#5685A5", | ||
| 183 | + h4: "#88BBDF", | ||
| 184 | + }, | ||
| 185 | + }, | ||
| 186 | + // Violet with a soft, muted edge. | ||
| 187 | + Palette { | ||
| 188 | + id: "plum", | ||
| 189 | + light: Tokens { | ||
| 190 | + accent: "#7B699C", | ||
| 191 | + accent_ink: "#645482", | ||
| 192 | + accent_soft: "#EBE7F5", | ||
| 193 | + accent_text: "#FFFFFF", | ||
| 194 | + focus: "#645482", | ||
| 195 | + public_bg: "#EBE7F5", | ||
| 196 | + public_text: "#645482", | ||
| 197 | + note: "#645482", | ||
| 198 | + hunk_bg: "#F0EEF7", | ||
| 199 | + hunk_text: "#5C4B79", | ||
| 200 | + h0: "#ECE7F6", | ||
| 201 | + h1: "#D7CEEA", | ||
| 202 | + h2: "#BEB1DA", | ||
| 203 | + h3: "#9382B2", | ||
| 204 | + h4: "#5F4D7E", | ||
| 205 | + }, | ||
| 206 | + dark: Tokens { | ||
| 207 | + accent: "#BBA9E0", | ||
| 208 | + accent_ink: "#CBBCEB", | ||
| 209 | + accent_soft: "#2F283C", | ||
| 210 | + accent_text: "#110D18", | ||
| 211 | + focus: "#BBA9E0", | ||
| 212 | + public_bg: "#2F283C", | ||
| 213 | + public_text: "#CBBCEB", | ||
| 214 | + note: "#CBBCEB", | ||
| 215 | + hunk_bg: "#25212E", | ||
| 216 | + hunk_text: "#BBA9E0", | ||
| 217 | + h0: "#26222F", | ||
| 218 | + h1: "#3C334C", | ||
| 219 | + h2: "#5D4F76", | ||
| 220 | + h3: "#8674A6", | ||
| 221 | + h4: "#BBA9E0", | ||
| 222 | + }, | ||
| 223 | + }, | ||
| 224 | + // Dusty pink, warm and quiet. | ||
| 225 | + Palette { | ||
| 226 | + id: "rose", | ||
| 227 | + light: Tokens { | ||
| 228 | + accent: "#A25E6F", | ||
| 229 | + accent_ink: "#864958", | ||
| 230 | + accent_soft: "#F6E4E8", | ||
| 231 | + accent_text: "#FFFFFF", | ||
| 232 | + focus: "#864958", | ||
| 233 | + public_bg: "#F6E4E8", | ||
| 234 | + public_text: "#864958", | ||
| 235 | + note: "#864958", | ||
| 236 | + hunk_bg: "#F7ECEE", | ||
| 237 | + hunk_text: "#7D4050", | ||
| 238 | + h0: "#F8E4E8", | ||
| 239 | + h1: "#EEC7CF", | ||
| 240 | + h2: "#DFA7B3", | ||
| 241 | + h3: "#B67785", | ||
| 242 | + h4: "#814151", | ||
| 243 | + }, | ||
| 244 | + dark: Tokens { | ||
| 245 | + accent: "#E79DAD", | ||
| 246 | + accent_ink: "#F3B2C0", | ||
| 247 | + accent_soft: "#3E242A", | ||
| 248 | + accent_text: "#190A0E", | ||
| 249 | + focus: "#E79DAD", | ||
| 250 | + public_bg: "#3E242A", | ||
| 251 | + public_text: "#F3B2C0", | ||
| 252 | + note: "#F3B2C0", | ||
| 253 | + hunk_bg: "#2F1E22", | ||
| 254 | + hunk_text: "#E79DAD", | ||
| 255 | + h0: "#301F23", | ||
| 256 | + h1: "#4E2D35", | ||
| 257 | + h2: "#794652", | ||
| 258 | + h3: "#AA6978", | ||
| 259 | + h4: "#E69CAC", | ||
| 260 | + }, | ||
| 261 | + }, | ||
| 262 | + // Clay brown, warmer and earthier than the warning amber. | ||
| 263 | + Palette { | ||
| 264 | + id: "ochre", | ||
| 265 | + light: Tokens { | ||
| 266 | + accent: "#93684B", | ||
| 267 | + accent_ink: "#7A5338", | ||
| 268 | + accent_soft: "#F5E6DD", | ||
| 269 | + accent_text: "#FFFFFF", | ||
| 270 | + focus: "#7A5338", | ||
| 271 | + public_bg: "#F5E6DD", | ||
| 272 | + public_text: "#7A5338", | ||
| 273 | + note: "#7A5338", | ||
| 274 | + hunk_bg: "#F6EEE8", | ||
| 275 | + hunk_text: "#724B30", | ||
| 276 | + h0: "#F4E7DF", | ||
| 277 | + h1: "#E6CEBE", | ||
| 278 | + h2: "#D4B199", | ||
| 279 | + h3: "#AB8267", | ||
| 280 | + h4: "#764D30", | ||
| 281 | + }, | ||
| 282 | + dark: Tokens { | ||
| 283 | + accent: "#D8A98A", | ||
| 284 | + accent_ink: "#E4BCA1", | ||
| 285 | + accent_soft: "#39281D", | ||
| 286 | + accent_text: "#170D07", | ||
| 287 | + focus: "#D8A98A", | ||
| 288 | + public_bg: "#39281D", | ||
| 289 | + public_text: "#E4BCA1", | ||
| 290 | + note: "#E4BCA1", | ||
| 291 | + hunk_bg: "#2C211A", | ||
| 292 | + hunk_text: "#D8A98A", | ||
| 293 | + h0: "#2D221B", | ||
| 294 | + h1: "#483325", | ||
| 295 | + h2: "#704F39", | ||
| 296 | + h3: "#9E7458", | ||
| 297 | + h4: "#D8A989", | ||
| 298 | + }, | ||
| 299 | + }, | ||
| 300 | + // Blue-grey graphite, nearly neutral. | ||
| 301 | + Palette { | ||
| 302 | + id: "slate", | ||
| 303 | + light: Tokens { | ||
| 304 | + accent: "#657383", | ||
| 305 | + accent_ink: "#505E6C", | ||
| 306 | + accent_soft: "#E0EBF7", | ||
| 307 | + accent_text: "#FFFFFF", | ||
| 308 | + focus: "#505E6C", | ||
| 309 | + public_bg: "#E0EBF7", | ||
| 310 | + public_text: "#505E6C", | ||
| 311 | + note: "#505E6C", | ||
| 312 | + hunk_bg: "#EAF0F7", | ||
| 313 | + hunk_text: "#485563", | ||
| 314 | + h0: "#E6EAEF", | ||
| 315 | + h1: "#CCD4DD", | ||
| 316 | + h2: "#AFBAC7", | ||
| 317 | + h3: "#808E9C", | ||
| 318 | + h4: "#4C5A69", | ||
| 319 | + }, | ||
| 320 | + dark: Tokens { | ||
| 321 | + accent: "#A4B4C4", | ||
| 322 | + accent_ink: "#B8C6D5", | ||
| 323 | + accent_soft: "#272D33", | ||
| 324 | + accent_text: "#0C1013", | ||
| 325 | + focus: "#A4B4C4", | ||
| 326 | + public_bg: "#272D33", | ||
| 327 | + public_text: "#B8C6D5", | ||
| 328 | + note: "#B8C6D5", | ||
| 329 | + hunk_bg: "#212428", | ||
| 330 | + hunk_text: "#A4B4C4", | ||
| 331 | + h0: "#222529", | ||
| 332 | + h1: "#323941", | ||
| 333 | + h2: "#4E5965", | ||
| 334 | + h3: "#728090", | ||
| 335 | + h4: "#A6B6C7", | ||
| 336 | + }, | ||
| 337 | + }, | ||
| 338 | +]; | ||
crates/forge-web/src/i18n/accents.rsadded+39 -0
| @@ -0,0 +1,39 @@ | |||
| 1 | +//! Names of the accent colours on the appearance page, keyed by palette id. Adding a palette | ||
| 2 | +//! without a name here fails `every_palette_has_a_name`. | ||
| 3 | + | ||
| 4 | +use super::Lang; | ||
| 5 | + | ||
| 6 | +/// The display name of a palette. An id with no name returns an empty string, which the test | ||
| 7 | +/// rules out for every offered palette. | ||
| 8 | +pub fn accent_name(lang: Lang, id: &str) -> &'static str { | ||
| 9 | + match (id, lang) { | ||
| 10 | + ("sage", Lang::En) => "Sage", | ||
| 11 | + ("sage", Lang::Tr) => "Adaçayı", | ||
| 12 | + ("ocean", Lang::En) => "Ocean", | ||
| 13 | + ("ocean", Lang::Tr) => "Okyanus", | ||
| 14 | + ("plum", Lang::En) => "Plum", | ||
| 15 | + ("plum", Lang::Tr) => "Erik", | ||
| 16 | + ("rose", Lang::En) => "Rose", | ||
| 17 | + ("rose", Lang::Tr) => "Gül", | ||
| 18 | + ("ochre", Lang::En) => "Ochre", | ||
| 19 | + ("ochre", Lang::Tr) => "Toprak", | ||
| 20 | + ("slate", Lang::En) => "Slate", | ||
| 21 | + ("slate", Lang::Tr) => "Arduvaz", | ||
| 22 | + _ => "", | ||
| 23 | + } | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +#[cfg(test)] | ||
| 27 | +mod tests { | ||
| 28 | + use super::*; | ||
| 29 | + use crate::accent; | ||
| 30 | + | ||
| 31 | + #[test] | ||
| 32 | + fn every_palette_has_a_name() { | ||
| 33 | + for id in accent::ids() { | ||
| 34 | + for lang in [Lang::En, Lang::Tr] { | ||
| 35 | + assert!(!accent_name(lang, id).is_empty(), "{id} has no name"); | ||
| 36 | + } | ||
| 37 | + } | ||
| 38 | + } | ||
| 39 | +} | ||
crates/forge-web/src/i18n/admin.rsmodified+98 -18
| @@ -1,7 +1,7 @@ | |||
| 1 | //! Strings for the admin pages: users, replication, backups, mail, CI runners and the audit log. | 1 | //! Strings for the admin pages: users, replication, backups, mail, CI runners and the audit log. |
| 2 | //! See `docs` in `super` for the pattern. | 2 | //! See `docs` in `super` for the pattern. |
| 3 | 3 | ||
| 4 | -use forge_core::mail::OutboxStatus; | 4 | +use forge_core::mail::{MailKind, MailState}; |
| 5 | use forge_core::store::backup_runs::{RunKind, RunTrigger}; | 5 | use forge_core::store::backup_runs::{RunKind, RunTrigger}; |
| 6 | 6 | ||
| 7 | use super::Lang; | 7 | use super::Lang; |
| @@ -68,6 +68,19 @@ pub enum K { | |||
| 68 | Mail, | 68 | Mail, |
| 69 | MailHost, | 69 | MailHost, |
| 70 | MailIntro, | 70 | MailIntro, |
| 71 | + MailTabSettings, | ||
| 72 | + MailTabQueue, | ||
| 73 | + MailFilterAll, | ||
| 74 | + MailRetryNow, | ||
| 75 | + MailDiscard, | ||
| 76 | + MailRetried, | ||
| 77 | + MailNotFailed, | ||
| 78 | + MailDiscarded, | ||
| 79 | + MailSentAt, | ||
| 80 | + MailTransportNote, | ||
| 81 | + MailTransportInUse, | ||
| 82 | + MailQueueIntro, | ||
| 83 | + MailNothingMatches, | ||
| 71 | MailPort, | 84 | MailPort, |
| 72 | MailSettingsSaved, | 85 | MailSettingsSaved, |
| 73 | MovedToGhost, | 86 | MovedToGhost, |
| @@ -77,11 +90,9 @@ pub enum K { | |||
| 77 | NoRunnersYet, | 90 | NoRunnersYet, |
| 78 | NoRunnerWithId, | 91 | NoRunnerWithId, |
| 79 | NoRunsYet, | 92 | NoRunsYet, |
| 80 | - NothingQueued, | ||
| 81 | Older, | 93 | Older, |
| 82 | OwnLogIntro, | 94 | OwnLogIntro, |
| 83 | PasswordStoredHint, | 95 | PasswordStoredHint, |
| 84 | - RecentMessages, | ||
| 85 | RecentRuns, | 96 | RecentRuns, |
| 86 | ReconcileNow, | 97 | ReconcileNow, |
| 87 | ReconcileStarted, | 98 | ReconcileStarted, |
| @@ -293,6 +304,44 @@ pub fn t(lang: Lang, key: K) -> &'static str { | |||
| 293 | (LastSuccess, Tr) => "Son başarı", | 304 | (LastSuccess, Tr) => "Son başarı", |
| 294 | (Mail, En) => "Mail", | 305 | (Mail, En) => "Mail", |
| 295 | (Mail, Tr) => "E-posta", | 306 | (Mail, Tr) => "E-posta", |
| 307 | + (MailTabSettings, En) => "Settings", | ||
| 308 | + (MailTabSettings, Tr) => "Ayarlar", | ||
| 309 | + (MailTabQueue, En) => "Queue", | ||
| 310 | + (MailTabQueue, Tr) => "Kuyruk", | ||
| 311 | + (MailFilterAll, En) => "All", | ||
| 312 | + (MailFilterAll, Tr) => "Tümü", | ||
| 313 | + (MailRetryNow, En) => "Retry now", | ||
| 314 | + (MailRetryNow, Tr) => "Şimdi yeniden dene", | ||
| 315 | + (MailDiscard, En) => "Discard", | ||
| 316 | + (MailDiscard, Tr) => "Vazgeç", | ||
| 317 | + (MailRetried, En) => "The message is queued for another try.", | ||
| 318 | + (MailRetried, Tr) => "Mesaj yeniden denenmek üzere kuyruğa alındı.", | ||
| 319 | + (MailNotFailed, En) => { | ||
| 320 | + "Only a failed message can be retried or discarded, and this one is not failed." | ||
| 321 | + } | ||
| 322 | + (MailNotFailed, Tr) => { | ||
| 323 | + "Yalnızca başarısız bir mesaj yeniden denenebilir ya da vazgeçilebilir; bu mesaj başarısız değil." | ||
| 324 | + } | ||
| 325 | + (MailDiscarded, En) => "The message was discarded.", | ||
| 326 | + (MailDiscarded, Tr) => "Mesajdan vazgeçildi.", | ||
| 327 | + (MailSentAt, En) => "Sent", | ||
| 328 | + (MailSentAt, Tr) => "Gönderildi", | ||
| 329 | + (MailTransportNote, En) => { | ||
| 330 | + "The SMTP account is stored in the database and applies to the next send, with no restart. The transport comes from forge.toml, in the [mail] section." | ||
| 331 | + } | ||
| 332 | + (MailTransportNote, Tr) => { | ||
| 333 | + "SMTP hesabı veritabanında tutulur ve bir sonraki gönderimde, yeniden başlatmadan geçerli olur. Taşıma yöntemi forge.toml dosyasındaki [mail] bölümünden gelir." | ||
| 334 | + } | ||
| 335 | + (MailTransportInUse, En) => "Transport in use:", | ||
| 336 | + (MailTransportInUse, Tr) => "Kullanılan taşıma:", | ||
| 337 | + (MailQueueIntro, En) => { | ||
| 338 | + "Every message goes through this queue. A failed try is retried on a backoff; a message that keeps failing is marked failed, and you can retry or discard it here." | ||
| 339 | + } | ||
| 340 | + (MailQueueIntro, Tr) => { | ||
| 341 | + "Her ileti bu kuyruktan geçer. Başarısız gönderim, aralığı artan şekilde yeniden denenir; sürekli başarısız olan ileti başarısız işaretlenir ve burada yeniden denenebilir ya da vazgeçilebilir." | ||
| 342 | + } | ||
| 343 | + (MailNothingMatches, En) => "No message is in this state.", | ||
| 344 | + (MailNothingMatches, Tr) => "Bu durumda ileti yok.", | ||
| 296 | (MailHost, En) => "Host", | 345 | (MailHost, En) => "Host", |
| 297 | (MailHost, Tr) => "Sunucu", | 346 | (MailHost, Tr) => "Sunucu", |
| 298 | (MailIntro, En) => { | 347 | (MailIntro, En) => { |
| @@ -319,8 +368,6 @@ pub fn t(lang: Lang, key: K) -> &'static str { | |||
| 319 | (NoRunnerWithId, Tr) => "Bu kimlikte bir çalıştırıcı yok. Hiçbir şey değiştirilmedi.", | 368 | (NoRunnerWithId, Tr) => "Bu kimlikte bir çalıştırıcı yok. Hiçbir şey değiştirilmedi.", |
| 320 | (NoRunsYet, En) => "No runs yet.", | 369 | (NoRunsYet, En) => "No runs yet.", |
| 321 | (NoRunsYet, Tr) => "Henüz çalıştırma yok.", | 370 | (NoRunsYet, Tr) => "Henüz çalıştırma yok.", |
| 322 | - (NothingQueued, En) => "Nothing has been queued yet.", | ||
| 323 | - (NothingQueued, Tr) => "Henüz kuyruğa alınmış bir şey yok.", | ||
| 324 | (Older, En) => "Older", | 371 | (Older, En) => "Older", |
| 325 | (Older, Tr) => "Daha eski", | 372 | (Older, Tr) => "Daha eski", |
| 326 | (OwnLogIntro, En) => { | 373 | (OwnLogIntro, En) => { |
| @@ -333,8 +380,6 @@ pub fn t(lang: Lang, key: K) -> &'static str { | |||
| 333 | (PasswordStoredHint, Tr) => { | 380 | (PasswordStoredHint, Tr) => { |
| 334 | "Bir parola kayıtlı. Mevcut parolayı korumak için bu alanı boş bırakın." | 381 | "Bir parola kayıtlı. Mevcut parolayı korumak için bu alanı boş bırakın." |
| 335 | } | 382 | } |
| 336 | - (RecentMessages, En) => "Recent messages", | ||
| 337 | - (RecentMessages, Tr) => "Son iletiler", | ||
| 338 | (RecentRuns, En) => "Recent runs", | 383 | (RecentRuns, En) => "Recent runs", |
| 339 | (RecentRuns, Tr) => "Son çalıştırmalar", | 384 | (RecentRuns, Tr) => "Son çalıştırmalar", |
| 340 | (ReconcileNow, En) => "Reconcile now", | 385 | (ReconcileNow, En) => "Reconcile now", |
| @@ -617,15 +662,39 @@ pub fn running_line(lang: Lang, kind: RunKind) -> String { | |||
| 617 | } | 662 | } |
| 618 | } | 663 | } |
| 619 | 664 | ||
| 620 | -/// The outbox status of a message: "sent", "queued" or "gave up". | 665 | +/// The queue state of a message, as the queue page labels it. |
| 621 | -pub fn outbox_status(lang: Lang, status: OutboxStatus) -> &'static str { | 666 | +pub fn mail_state(lang: Lang, state: MailState) -> &'static str { |
| 622 | - match (status, lang) { | 667 | + match (state, lang) { |
| 623 | - (OutboxStatus::Sent, Lang::En) => "sent", | 668 | + (MailState::Queued, Lang::En) => "queued", |
| 624 | - (OutboxStatus::Sent, Lang::Tr) => "gönderildi", | 669 | + (MailState::Queued, Lang::Tr) => "kuyrukta", |
| 625 | - (OutboxStatus::Queued, Lang::En) => "queued", | 670 | + (MailState::Retrying, Lang::En) => "retrying", |
| 626 | - (OutboxStatus::Queued, Lang::Tr) => "kuyrukta", | 671 | + (MailState::Retrying, Lang::Tr) => "yeniden denenecek", |
| 627 | - (OutboxStatus::GaveUp, Lang::En) => "gave up", | 672 | + (MailState::Sending, Lang::En) => "sending", |
| 628 | - (OutboxStatus::GaveUp, Lang::Tr) => "vazgeçildi", | 673 | + (MailState::Sending, Lang::Tr) => "gönderiliyor", |
| 674 | + (MailState::Sent, Lang::En) => "sent", | ||
| 675 | + (MailState::Sent, Lang::Tr) => "gönderildi", | ||
| 676 | + (MailState::Failed, Lang::En) => "failed", | ||
| 677 | + (MailState::Failed, Lang::Tr) => "başarısız", | ||
| 678 | + (MailState::Discarded, Lang::En) => "discarded", | ||
| 679 | + (MailState::Discarded, Lang::Tr) => "vazgeçildi", | ||
| 680 | + } | ||
| 681 | +} | ||
| 682 | + | ||
| 683 | +/// The kind of a message, as the queue page labels it. | ||
| 684 | +pub fn mail_kind(lang: Lang, kind: MailKind) -> &'static str { | ||
| 685 | + match (kind, lang) { | ||
| 686 | + (MailKind::Verification, Lang::En) => "verification", | ||
| 687 | + (MailKind::Verification, Lang::Tr) => "doğrulama", | ||
| 688 | + (MailKind::PasswordReset, Lang::En) => "password reset", | ||
| 689 | + (MailKind::PasswordReset, Lang::Tr) => "şifre sıfırlama", | ||
| 690 | + (MailKind::Invite, Lang::En) => "invite", | ||
| 691 | + (MailKind::Invite, Lang::Tr) => "davet", | ||
| 692 | + (MailKind::Notification, Lang::En) => "notification", | ||
| 693 | + (MailKind::Notification, Lang::Tr) => "bildirim", | ||
| 694 | + (MailKind::Test, Lang::En) => "test", | ||
| 695 | + (MailKind::Test, Lang::Tr) => "test", | ||
| 696 | + (MailKind::Other, Lang::En) => "other", | ||
| 697 | + (MailKind::Other, Lang::Tr) => "diğer", | ||
| 629 | } | 698 | } |
| 630 | } | 699 | } |
| 631 | 700 | ||
| @@ -710,6 +779,19 @@ mod tests { | |||
| 710 | K::Mail, | 779 | K::Mail, |
| 711 | K::MailHost, | 780 | K::MailHost, |
| 712 | K::MailIntro, | 781 | K::MailIntro, |
| 782 | + K::MailTabSettings, | ||
| 783 | + K::MailTabQueue, | ||
| 784 | + K::MailFilterAll, | ||
| 785 | + K::MailRetryNow, | ||
| 786 | + K::MailDiscard, | ||
| 787 | + K::MailRetried, | ||
| 788 | + K::MailNotFailed, | ||
| 789 | + K::MailDiscarded, | ||
| 790 | + K::MailSentAt, | ||
| 791 | + K::MailTransportNote, | ||
| 792 | + K::MailTransportInUse, | ||
| 793 | + K::MailQueueIntro, | ||
| 794 | + K::MailNothingMatches, | ||
| 713 | K::MailPort, | 795 | K::MailPort, |
| 714 | K::MailSettingsSaved, | 796 | K::MailSettingsSaved, |
| 715 | K::MovedToGhost, | 797 | K::MovedToGhost, |
| @@ -719,11 +801,9 @@ mod tests { | |||
| 719 | K::NoRunnersYet, | 801 | K::NoRunnersYet, |
| 720 | K::NoRunnerWithId, | 802 | K::NoRunnerWithId, |
| 721 | K::NoRunsYet, | 803 | K::NoRunsYet, |
| 722 | - K::NothingQueued, | ||
| 723 | K::Older, | 804 | K::Older, |
| 724 | K::OwnLogIntro, | 805 | K::OwnLogIntro, |
| 725 | K::PasswordStoredHint, | 806 | K::PasswordStoredHint, |
| 726 | - K::RecentMessages, | ||
| 727 | K::RecentRuns, | 807 | K::RecentRuns, |
| 728 | K::ReconcileNow, | 808 | K::ReconcileNow, |
| 729 | K::ReconcileStarted, | 809 | K::ReconcileStarted, |
crates/forge-web/src/i18n/misc.rsmodified+12 -0
| @@ -27,6 +27,9 @@ pub enum K { | |||
| 27 | AppearanceSaved, | 27 | AppearanceSaved, |
| 28 | ChooseTheme, | 28 | ChooseTheme, |
| 29 | ChooseLanguage, | 29 | ChooseLanguage, |
| 30 | + AccentLabel, | ||
| 31 | + AccentHelp, | ||
| 32 | + ChooseAccent, | ||
| 30 | // Notifications: row kinds. | 33 | // Notifications: row kinds. |
| 31 | KindOpenIssue, | 34 | KindOpenIssue, |
| 32 | KindClosedIssue, | 35 | KindClosedIssue, |
| @@ -165,6 +168,9 @@ const ALL: &[K] = &[ | |||
| 165 | K::AppearanceSaved, | 168 | K::AppearanceSaved, |
| 166 | K::ChooseTheme, | 169 | K::ChooseTheme, |
| 167 | K::ChooseLanguage, | 170 | K::ChooseLanguage, |
| 171 | + K::AccentLabel, | ||
| 172 | + K::AccentHelp, | ||
| 173 | + K::ChooseAccent, | ||
| 168 | K::KindOpenIssue, | 174 | K::KindOpenIssue, |
| 169 | K::KindClosedIssue, | 175 | K::KindClosedIssue, |
| 170 | K::KindOpenPull, | 176 | K::KindOpenPull, |
| @@ -311,6 +317,12 @@ pub fn t(lang: Lang, key: K) -> &'static str { | |||
| 311 | (ChooseTheme, Tr) => "Listeden bir tema seçin.", | 317 | (ChooseTheme, Tr) => "Listeden bir tema seçin.", |
| 312 | (ChooseLanguage, En) => "Choose a language from the list.", | 318 | (ChooseLanguage, En) => "Choose a language from the list.", |
| 313 | (ChooseLanguage, Tr) => "Listeden bir dil seçin.", | 319 | (ChooseLanguage, Tr) => "Listeden bir dil seçin.", |
| 320 | + (AccentLabel, En) => "Accent colour", | ||
| 321 | + (AccentLabel, Tr) => "Vurgu rengi", | ||
| 322 | + (AccentHelp, En) => "Used for buttons, links and the activity heatmap.", | ||
| 323 | + (AccentHelp, Tr) => "Düğmeler, bağlantılar ve etkinlik ısı haritası için kullanılır.", | ||
| 324 | + (ChooseAccent, En) => "Choose an accent colour from the list.", | ||
| 325 | + (ChooseAccent, Tr) => "Listeden bir vurgu rengi seçin.", | ||
| 314 | (KindOpenIssue, En) => "Open issue", | 326 | (KindOpenIssue, En) => "Open issue", |
| 315 | (KindOpenIssue, Tr) => "Açık sorun", | 327 | (KindOpenIssue, Tr) => "Açık sorun", |
| 316 | (KindClosedIssue, En) => "Closed issue", | 328 | (KindClosedIssue, En) => "Closed issue", |
crates/forge-web/src/i18n/mod.rsmodified+156 -6
| @@ -17,6 +17,7 @@ use topcoat::router::request::headers; | |||
| 17 | 17 | ||
| 18 | use forge_core::User; | 18 | use forge_core::User; |
| 19 | 19 | ||
| 20 | +pub mod accents; | ||
| 20 | pub mod admin; | 21 | pub mod admin; |
| 21 | pub mod code; | 22 | pub mod code; |
| 22 | pub mod community; | 23 | pub mod community; |
| @@ -184,6 +185,9 @@ pub enum Key { | |||
| 184 | AboutHint, | 185 | AboutHint, |
| 185 | Timezone, | 186 | Timezone, |
| 186 | ErrChooseImage, | 187 | ErrChooseImage, |
| 188 | + DisplayName, | ||
| 189 | + DisplayNameHint, | ||
| 190 | + ErrDisplayNameControl, | ||
| 187 | 191 | ||
| 188 | // Account security. | 192 | // Account security. |
| 189 | OkPasswordChanged, | 193 | OkPasswordChanged, |
| @@ -320,6 +324,23 @@ pub enum Key { | |||
| 320 | EmailNotifyUnverified, | 324 | EmailNotifyUnverified, |
| 321 | EmailNotifyServerOff, | 325 | EmailNotifyServerOff, |
| 322 | EmailNotifySaved, | 326 | EmailNotifySaved, |
| 327 | + AuthenticatorApp, | ||
| 328 | + PillOn, | ||
| 329 | + PillOff, | ||
| 330 | + PillVerified, | ||
| 331 | + PillUnverified, | ||
| 332 | + EmailNotVerified, | ||
| 333 | + EmailNoAddress, | ||
| 334 | + EmailMailQueued, | ||
| 335 | + EmailMailFailed, | ||
| 336 | + ChangeAction, | ||
| 337 | + SetUpAction, | ||
| 338 | + SetupInProgress, | ||
| 339 | + DeviceName, | ||
| 340 | + DeviceNameHint, | ||
| 341 | + ErrDeviceName, | ||
| 342 | + CodesRunningLow, | ||
| 343 | + DangerZone, | ||
| 323 | } | 344 | } |
| 324 | 345 | ||
| 325 | /// Every key, for the exhaustiveness test. Keep it in step with the enum. | 346 | /// Every key, for the exhaustiveness test. Keep it in step with the enum. |
| @@ -385,6 +406,9 @@ pub const ALL: &[Key] = &[ | |||
| 385 | Key::AboutHint, | 406 | Key::AboutHint, |
| 386 | Key::Timezone, | 407 | Key::Timezone, |
| 387 | Key::ErrChooseImage, | 408 | Key::ErrChooseImage, |
| 409 | + Key::DisplayName, | ||
| 410 | + Key::DisplayNameHint, | ||
| 411 | + Key::ErrDisplayNameControl, | ||
| 388 | Key::OkPasswordChanged, | 412 | Key::OkPasswordChanged, |
| 389 | Key::OkEmailSaved, | 413 | Key::OkEmailSaved, |
| 390 | Key::OkTwoFactorOn, | 414 | Key::OkTwoFactorOn, |
| @@ -508,6 +532,23 @@ pub const ALL: &[Key] = &[ | |||
| 508 | Key::EmailNotifyUnverified, | 532 | Key::EmailNotifyUnverified, |
| 509 | Key::EmailNotifyServerOff, | 533 | Key::EmailNotifyServerOff, |
| 510 | Key::EmailNotifySaved, | 534 | Key::EmailNotifySaved, |
| 535 | + Key::AuthenticatorApp, | ||
| 536 | + Key::PillOn, | ||
| 537 | + Key::PillOff, | ||
| 538 | + Key::PillVerified, | ||
| 539 | + Key::PillUnverified, | ||
| 540 | + Key::EmailNotVerified, | ||
| 541 | + Key::EmailNoAddress, | ||
| 542 | + Key::EmailMailQueued, | ||
| 543 | + Key::EmailMailFailed, | ||
| 544 | + Key::ChangeAction, | ||
| 545 | + Key::SetUpAction, | ||
| 546 | + Key::SetupInProgress, | ||
| 547 | + Key::DeviceName, | ||
| 548 | + Key::DeviceNameHint, | ||
| 549 | + Key::ErrDeviceName, | ||
| 550 | + Key::CodesRunningLow, | ||
| 551 | + Key::DangerZone, | ||
| 511 | ]; | 552 | ]; |
| 512 | 553 | ||
| 513 | /// The phrase a key names, in a user's language. | 554 | /// The phrase a key names, in a user's language. |
| @@ -666,6 +707,14 @@ pub fn t(lang: Lang, key: Key) -> &'static str { | |||
| 666 | (Timezone, Tr) => "Saat dilimi", | 707 | (Timezone, Tr) => "Saat dilimi", |
| 667 | (ErrChooseImage, En) => "Choose an image to upload.", | 708 | (ErrChooseImage, En) => "Choose an image to upload.", |
| 668 | (ErrChooseImage, Tr) => "Yüklemek için bir görsel seçin.", | 709 | (ErrChooseImage, Tr) => "Yüklemek için bir görsel seçin.", |
| 710 | + (DisplayName, En) => "Name", | ||
| 711 | + (DisplayName, Tr) => "Ad", | ||
| 712 | + (DisplayNameHint, En) => "Optional. Shown on your profile.", | ||
| 713 | + (DisplayNameHint, Tr) => "İsteğe bağlı. Profilinizde gösterilir.", | ||
| 714 | + (ErrDisplayNameControl, En) => { | ||
| 715 | + "The name must not contain line breaks or control characters." | ||
| 716 | + } | ||
| 717 | + (ErrDisplayNameControl, Tr) => "Ad satır sonu ya da denetim karakteri içermemeli.", | ||
| 669 | 718 | ||
| 670 | (OkPasswordChanged, En) => "Password changed. Your other sessions were signed out.", | 719 | (OkPasswordChanged, En) => "Password changed. Your other sessions were signed out.", |
| 671 | (OkPasswordChanged, Tr) => "Parola değiştirildi. Diğer oturumlarınız kapatıldı.", | 720 | (OkPasswordChanged, Tr) => "Parola değiştirildi. Diğer oturumlarınız kapatıldı.", |
| @@ -1006,6 +1055,44 @@ pub fn t(lang: Lang, key: Key) -> &'static str { | |||
| 1006 | "Bu sunucuda e-posta kapalı, bu yüzden bildirim e-postası gönderilmiyor." | 1055 | "Bu sunucuda e-posta kapalı, bu yüzden bildirim e-postası gönderilmiyor." |
| 1007 | } | 1056 | } |
| 1008 | (EmailNotifySaved, Tr) => "Bildirim ayarları kaydedildi.", | 1057 | (EmailNotifySaved, Tr) => "Bildirim ayarları kaydedildi.", |
| 1058 | + (AuthenticatorApp, En) => "Authenticator app", | ||
| 1059 | + (AuthenticatorApp, Tr) => "Kimlik doğrulama uygulaması", | ||
| 1060 | + (PillOn, En) => "On", | ||
| 1061 | + (PillOn, Tr) => "Açık", | ||
| 1062 | + (PillOff, En) => "Off", | ||
| 1063 | + (PillOff, Tr) => "Kapalı", | ||
| 1064 | + (PillVerified, En) => "Verified", | ||
| 1065 | + (PillVerified, Tr) => "Doğrulandı", | ||
| 1066 | + (PillUnverified, En) => "Unverified", | ||
| 1067 | + (PillUnverified, Tr) => "Doğrulanmadı", | ||
| 1068 | + (EmailNotVerified, En) => "Not verified", | ||
| 1069 | + (EmailNotVerified, Tr) => "Doğrulanmadı", | ||
| 1070 | + (EmailNoAddress, En) => "No email address", | ||
| 1071 | + (EmailNoAddress, Tr) => "E-posta adresi yok", | ||
| 1072 | + (EmailMailQueued, En) => "verification mail queued", | ||
| 1073 | + (EmailMailQueued, Tr) => "doğrulama iletisi kuyrukta", | ||
| 1074 | + (EmailMailFailed, En) => "verification mail failed", | ||
| 1075 | + (EmailMailFailed, Tr) => "doğrulama iletisi başarısız", | ||
| 1076 | + (ChangeAction, En) => "Change", | ||
| 1077 | + (ChangeAction, Tr) => "Değiştir", | ||
| 1078 | + (SetUpAction, En) => "Set up", | ||
| 1079 | + (SetUpAction, Tr) => "Kur", | ||
| 1080 | + (SetupInProgress, En) => "Setup in progress", | ||
| 1081 | + (SetupInProgress, Tr) => "Kurulum sürüyor", | ||
| 1082 | + (DeviceName, En) => "Device name (optional)", | ||
| 1083 | + (DeviceName, Tr) => "Cihaz adı (isteğe bağlı)", | ||
| 1084 | + (DeviceNameHint, En) => "Shown in your list of devices. Leave empty for the default name.", | ||
| 1085 | + (DeviceNameHint, Tr) => { | ||
| 1086 | + "Cihaz listenizde görünür. Boş bırakırsanız varsayılan ad kullanılır." | ||
| 1087 | + } | ||
| 1088 | + (ErrDeviceName, En) => { | ||
| 1089 | + "Use at most 40 characters for the device name, without line breaks." | ||
| 1090 | + } | ||
| 1091 | + (ErrDeviceName, Tr) => "Cihaz adı en fazla 40 karakter olabilir ve satır sonu içeremez.", | ||
| 1092 | + (CodesRunningLow, En) => "Running low. Generate new codes soon.", | ||
| 1093 | + (CodesRunningLow, Tr) => "Azaldı. Yakında yeni kodlar oluşturun.", | ||
| 1094 | + (DangerZone, En) => "Danger zone", | ||
| 1095 | + (DangerZone, Tr) => "Tehlikeli bölge", | ||
| 1009 | } | 1096 | } |
| 1010 | } | 1097 | } |
| 1011 | 1098 | ||
| @@ -1146,13 +1233,68 @@ pub fn unsupported_key_type(lang: Lang, algorithm: &str) -> String { | |||
| 1146 | } | 1233 | } |
| 1147 | } | 1234 | } |
| 1148 | 1235 | ||
| 1149 | -/// "Two-factor authentication is on. Unused recovery codes: 7." | 1236 | +/// "Last changed 3 days ago", with the relative time already rendered. |
| 1150 | -pub fn two_factor_on_line(lang: Lang, unused: u64) -> String { | 1237 | +pub fn last_changed_line(lang: Lang, when: &str) -> String { |
| 1151 | match lang { | 1238 | match lang { |
| 1152 | - Lang::En => format!("Two-factor authentication is on. Unused recovery codes: {unused}."), | 1239 | + Lang::En => format!("Last changed {when}"), |
| 1153 | - Lang::Tr => format!( | 1240 | + Lang::Tr => format!("Son değişiklik: {when}"), |
| 1154 | - "İki faktörlü kimlik doğrulama açık. Kullanılmamış kurtarma kodu sayısı: {unused}." | 1241 | + } |
| 1155 | - ), | 1242 | +} |
| 1243 | + | ||
| 1244 | +/// The state of the latest verification mail on the Email row, such as "verification mail sent | ||
| 1245 | +/// 5 minutes ago". `sent_ago` is the relative time of the send, when known. | ||
| 1246 | +pub fn email_mail_line( | ||
| 1247 | + lang: Lang, | ||
| 1248 | + state: forge_core::mail::MailState, | ||
| 1249 | + attempts: u32, | ||
| 1250 | + sent_ago: Option<&str>, | ||
| 1251 | +) -> String { | ||
| 1252 | + use forge_core::mail::MailState; | ||
| 1253 | + match (state, lang) { | ||
| 1254 | + (MailState::Queued | MailState::Sending, _) => t(lang, Key::EmailMailQueued).to_owned(), | ||
| 1255 | + (MailState::Failed | MailState::Discarded, _) => t(lang, Key::EmailMailFailed).to_owned(), | ||
| 1256 | + (MailState::Retrying, Lang::En) => { | ||
| 1257 | + format!("verification mail retrying (attempt {})", attempts + 1) | ||
| 1258 | + } | ||
| 1259 | + (MailState::Retrying, Lang::Tr) => { | ||
| 1260 | + format!( | ||
| 1261 | + "doğrulama iletisi yeniden denenecek (deneme {})", | ||
| 1262 | + attempts + 1 | ||
| 1263 | + ) | ||
| 1264 | + } | ||
| 1265 | + (MailState::Sent, Lang::En) => match sent_ago { | ||
| 1266 | + Some(ago) => format!("verification mail sent {ago}"), | ||
| 1267 | + None => "verification mail sent".to_owned(), | ||
| 1268 | + }, | ||
| 1269 | + (MailState::Sent, Lang::Tr) => match sent_ago { | ||
| 1270 | + Some(ago) => format!("doğrulama iletisi {ago} gönderildi"), | ||
| 1271 | + None => "doğrulama iletisi gönderildi".to_owned(), | ||
| 1272 | + }, | ||
| 1273 | + } | ||
| 1274 | +} | ||
| 1275 | + | ||
| 1276 | +/// The device's "Added 2026-10-18 · Last used 5 minutes ago" line. A part without a stamp is | ||
| 1277 | +/// left out. | ||
| 1278 | +pub fn device_line(lang: Lang, added: Option<&str>, used: Option<&str>) -> String { | ||
| 1279 | + let (added_word, used_word) = match lang { | ||
| 1280 | + Lang::En => ("Added", "Last used"), | ||
| 1281 | + Lang::Tr => ("Eklendi", "Son kullanım"), | ||
| 1282 | + }; | ||
| 1283 | + let mut parts = Vec::new(); | ||
| 1284 | + if let Some(day) = added { | ||
| 1285 | + parts.push(format!("{added_word} {day}")); | ||
| 1286 | + } | ||
| 1287 | + if let Some(when) = used { | ||
| 1288 | + parts.push(format!("{used_word} {when}")); | ||
| 1289 | + } | ||
| 1290 | + parts.join(" · ") | ||
| 1291 | +} | ||
| 1292 | + | ||
| 1293 | +/// "7 of 10 recovery codes unused". | ||
| 1294 | +pub fn codes_left_line(lang: Lang, unused: u64, total: u64) -> String { | ||
| 1295 | + match lang { | ||
| 1296 | + Lang::En => format!("{unused} of {total} recovery codes unused"), | ||
| 1297 | + Lang::Tr => format!("{total} kurtarma kodundan {unused} tanesi kullanılmamış"), | ||
| 1156 | } | 1298 | } |
| 1157 | } | 1299 | } |
| 1158 | 1300 | ||
| @@ -1164,6 +1306,14 @@ pub fn about_too_long(lang: Lang, max: usize) -> String { | |||
| 1164 | } | 1306 | } |
| 1165 | } | 1307 | } |
| 1166 | 1308 | ||
| 1309 | +/// The message for a display name longer than `max` characters. | ||
| 1310 | +pub fn display_name_too_long(lang: Lang, max: usize) -> String { | ||
| 1311 | + match lang { | ||
| 1312 | + Lang::En => format!("The name must be at most {max} characters."), | ||
| 1313 | + Lang::Tr => format!("Ad en fazla {max} karakter olabilir."), | ||
| 1314 | + } | ||
| 1315 | +} | ||
| 1316 | + | ||
| 1167 | /// The message for a password shorter than `min` characters. | 1317 | /// The message for a password shorter than `min` characters. |
| 1168 | pub fn password_too_short(lang: Lang, min: usize) -> String { | 1318 | pub fn password_too_short(lang: Lang, min: usize) -> String { |
| 1169 | match lang { | 1319 | match lang { |
crates/forge-web/src/i18n/releases_ci.rsmodified+28 -28
| @@ -30,14 +30,7 @@ pub enum K { | |||
| 30 | Runs, | 30 | Runs, |
| 31 | NoRunsYet, | 31 | NoRunsYet, |
| 32 | NoRunsHint, | 32 | NoRunsHint, |
| 33 | - Jobs, | ||
| 34 | - JobGraph, | ||
| 35 | NoJobs, | 33 | NoJobs, |
| 36 | - ColState, | ||
| 37 | - ColJob, | ||
| 38 | - ColDuration, | ||
| 39 | - ColRunner, | ||
| 40 | - ColMessage, | ||
| 41 | Newer, | 34 | Newer, |
| 42 | Older, | 35 | Older, |
| 43 | DeletedUser, | 36 | DeletedUser, |
| @@ -50,6 +43,9 @@ pub enum K { | |||
| 50 | FullLog, | 43 | FullLog, |
| 51 | LogTruncated, | 44 | LogTruncated, |
| 52 | Artifacts, | 45 | Artifacts, |
| 46 | + Timeline, | ||
| 47 | + Waiting, | ||
| 48 | + LastLogLines, | ||
| 53 | 49 | ||
| 54 | // CI status badge, on the run list. | 50 | // CI status badge, on the run list. |
| 55 | BadgeHeading, | 51 | BadgeHeading, |
| @@ -173,22 +169,8 @@ pub fn t(lang: Lang, key: K) -> &'static str { | |||
| 173 | (NoRunsHint, Tr) => { | 169 | (NoRunsHint, Tr) => { |
| 174 | ".forge/ci.toml dosyası ekleyin, ardından bir commit gönderin ya da bir çalıştırma başlatın." | 170 | ".forge/ci.toml dosyası ekleyin, ardından bir commit gönderin ya da bir çalıştırma başlatın." |
| 175 | } | 171 | } |
| 176 | - (Jobs, En) => "Jobs", | ||
| 177 | - (Jobs, Tr) => "İşler", | ||
| 178 | - (JobGraph, En) => "Job graph", | ||
| 179 | - (JobGraph, Tr) => "İş grafiği", | ||
| 180 | (NoJobs, En) => "No jobs.", | 172 | (NoJobs, En) => "No jobs.", |
| 181 | (NoJobs, Tr) => "İş yok.", | 173 | (NoJobs, Tr) => "İş yok.", |
| 182 | - (ColState, En) => "State", | ||
| 183 | - (ColState, Tr) => "Durum", | ||
| 184 | - (ColJob, En) => "Job", | ||
| 185 | - (ColJob, Tr) => "İş", | ||
| 186 | - (ColDuration, En) => "Duration", | ||
| 187 | - (ColDuration, Tr) => "Süre", | ||
| 188 | - (ColRunner, En) => "Runner", | ||
| 189 | - (ColRunner, Tr) => "Çalıştırıcı", | ||
| 190 | - (ColMessage, En) => "Message", | ||
| 191 | - (ColMessage, Tr) => "Mesaj", | ||
| 192 | (Newer, En) => "Newer", | 174 | (Newer, En) => "Newer", |
| 193 | (Newer, Tr) => "Daha yeni", | 175 | (Newer, Tr) => "Daha yeni", |
| 194 | (Older, En) => "Older", | 176 | (Older, En) => "Older", |
| @@ -215,6 +197,12 @@ pub fn t(lang: Lang, key: K) -> &'static str { | |||
| 215 | } | 197 | } |
| 216 | (Artifacts, En) => "Artifacts", | 198 | (Artifacts, En) => "Artifacts", |
| 217 | (Artifacts, Tr) => "Yapıtlar", | 199 | (Artifacts, Tr) => "Yapıtlar", |
| 200 | + (Timeline, En) => "Timeline", | ||
| 201 | + (Timeline, Tr) => "Zaman çizelgesi", | ||
| 202 | + (Waiting, En) => "waiting", | ||
| 203 | + (Waiting, Tr) => "bekliyor", | ||
| 204 | + (LastLogLines, En) => "last log lines", | ||
| 205 | + (LastLogLines, Tr) => "son günlük satırları", | ||
| 218 | (BadgeHeading, En) => "Status badge", | 206 | (BadgeHeading, En) => "Status badge", |
| 219 | (BadgeHeading, Tr) => "Durum rozeti", | 207 | (BadgeHeading, Tr) => "Durum rozeti", |
| 220 | (BadgeHelp, En) => { | 208 | (BadgeHelp, En) => { |
| @@ -378,6 +366,22 @@ pub fn page_label(lang: Lang, page: u32) -> String { | |||
| 378 | } | 366 | } |
| 379 | } | 367 | } |
| 380 | 368 | ||
| 369 | +/// "scale: 0 — 80 min", the scale of the run list in minutes. | ||
| 370 | +pub fn scale_label(lang: Lang, span: &str) -> String { | ||
| 371 | + match lang { | ||
| 372 | + Lang::En => format!("scale: 0 \u{2014} {span}"), | ||
| 373 | + Lang::Tr => format!("ölçek: 0 \u{2014} {span}"), | ||
| 374 | + } | ||
| 375 | +} | ||
| 376 | + | ||
| 377 | +/// "needs test", for the names of the jobs a job needs. | ||
| 378 | +pub fn needs_label(lang: Lang, names: &str) -> String { | ||
| 379 | + match lang { | ||
| 380 | + Lang::En => format!("needs {names}"), | ||
| 381 | + Lang::Tr => format!("{names} gerekli"), | ||
| 382 | + } | ||
| 383 | +} | ||
| 384 | + | ||
| 381 | /// "1m 5s". | 385 | /// "1m 5s". |
| 382 | pub fn duration_minutes(lang: Lang, minutes: i64, secs: i64) -> String { | 386 | pub fn duration_minutes(lang: Lang, minutes: i64, secs: i64) -> String { |
| 383 | match lang { | 387 | match lang { |
| @@ -461,14 +465,7 @@ mod tests { | |||
| 461 | K::Runs, | 465 | K::Runs, |
| 462 | K::NoRunsYet, | 466 | K::NoRunsYet, |
| 463 | K::NoRunsHint, | 467 | K::NoRunsHint, |
| 464 | - K::Jobs, | ||
| 465 | - K::JobGraph, | ||
| 466 | K::NoJobs, | 468 | K::NoJobs, |
| 467 | - K::ColState, | ||
| 468 | - K::ColJob, | ||
| 469 | - K::ColDuration, | ||
| 470 | - K::ColRunner, | ||
| 471 | - K::ColMessage, | ||
| 472 | K::Newer, | 469 | K::Newer, |
| 473 | K::Older, | 470 | K::Older, |
| 474 | K::DeletedUser, | 471 | K::DeletedUser, |
| @@ -481,6 +478,9 @@ mod tests { | |||
| 481 | K::FullLog, | 478 | K::FullLog, |
| 482 | K::LogTruncated, | 479 | K::LogTruncated, |
| 483 | K::Artifacts, | 480 | K::Artifacts, |
| 481 | + K::Timeline, | ||
| 482 | + K::Waiting, | ||
| 483 | + K::LastLogLines, | ||
| 484 | K::BadgeHeading, | 484 | K::BadgeHeading, |
| 485 | K::BadgeHelp, | 485 | K::BadgeHelp, |
| 486 | K::BadgeSnippet, | 486 | K::BadgeSnippet, |
crates/forge-web/src/mail/account.rsmodified+7 -0
| @@ -3,6 +3,7 @@ | |||
| 3 | //! queues nothing twice. The token itself appears only in the link. | 3 | //! queues nothing twice. The token itself appears only in the link. |
| 4 | 4 | ||
| 5 | use forge_core::User; | 5 | use forge_core::User; |
| 6 | +use forge_core::mail::MailKind; | ||
| 6 | use forge_core::token::hash_token; | 7 | use forge_core::token::hash_token; |
| 7 | 8 | ||
| 8 | use super::{enqueue, templates}; | 9 | use super::{enqueue, templates}; |
| @@ -25,6 +26,8 @@ pub async fn send_reset(state: &AppState, user: &User) -> forge_core::Result<()> | |||
| 25 | enqueue( | 26 | enqueue( |
| 26 | state, | 27 | state, |
| 27 | &format!("reset:{}", hash_token(&token)), | 28 | &format!("reset:{}", hash_token(&token)), |
| 29 | + MailKind::PasswordReset, | ||
| 30 | + Some(&user.id), | ||
| 28 | address, | 31 | address, |
| 29 | &subject, | 32 | &subject, |
| 30 | &body, | 33 | &body, |
| @@ -41,6 +44,8 @@ pub async fn send_verify(state: &AppState, user: &User, address: &str) -> forge_ | |||
| 41 | enqueue( | 44 | enqueue( |
| 42 | state, | 45 | state, |
| 43 | &format!("verify:{}", hash_token(&token)), | 46 | &format!("verify:{}", hash_token(&token)), |
| 47 | + MailKind::Verification, | ||
| 48 | + Some(&user.id), | ||
| 44 | address, | 49 | address, |
| 45 | &subject, | 50 | &subject, |
| 46 | &body, | 51 | &body, |
| @@ -62,6 +67,8 @@ pub async fn send_invite( | |||
| 62 | enqueue( | 67 | enqueue( |
| 63 | state, | 68 | state, |
| 64 | &format!("invite:{}", hash_token(&token)), | 69 | &format!("invite:{}", hash_token(&token)), |
| 70 | + MailKind::Invite, | ||
| 71 | + None, | ||
| 65 | address, | 72 | address, |
| 66 | &subject, | 73 | &subject, |
| 67 | &body, | 74 | &body, |
crates/forge-web/src/mail/live.rsadded+41 -0
| @@ -0,0 +1,41 @@ | |||
| 1 | +//! The change signal of the mail queue. Each change to the outbox (a message queued, a try's | ||
| 2 | +//! outcome, a retry, a discard) bumps one counter, and every open queue page wakes on it through | ||
| 3 | +//! its event stream. The counter carries no data: a subscriber reads the queue again when it | ||
| 4 | +//! wakes. Nothing polls. The signal is process-wide, like the mail worker's waker. | ||
| 5 | + | ||
| 6 | +use std::sync::OnceLock; | ||
| 7 | + | ||
| 8 | +use tokio::sync::watch; | ||
| 9 | + | ||
| 10 | +static CHANGES: OnceLock<watch::Sender<u64>> = OnceLock::new(); | ||
| 11 | + | ||
| 12 | +fn sender() -> &'static watch::Sender<u64> { | ||
| 13 | + CHANGES.get_or_init(|| watch::channel(0).0) | ||
| 14 | +} | ||
| 15 | + | ||
| 16 | +/// Subscribes to queue changes. Only a bump after this call wakes the receiver. | ||
| 17 | +pub fn subscribe() -> watch::Receiver<u64> { | ||
| 18 | + sender().subscribe() | ||
| 19 | +} | ||
| 20 | + | ||
| 21 | +/// Counts one change of the queue. Nobody has to be listening. | ||
| 22 | +pub fn bump() { | ||
| 23 | + sender().send_modify(|generation| *generation = generation.wrapping_add(1)); | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +#[cfg(test)] | ||
| 27 | +mod tests { | ||
| 28 | + use std::time::Duration; | ||
| 29 | + | ||
| 30 | + use super::*; | ||
| 31 | + | ||
| 32 | + #[tokio::test] | ||
| 33 | + async fn a_bump_wakes_a_subscriber_that_was_subscribed_before_it() { | ||
| 34 | + let mut rx = subscribe(); | ||
| 35 | + bump(); | ||
| 36 | + tokio::time::timeout(Duration::from_secs(1), rx.changed()) | ||
| 37 | + .await | ||
| 38 | + .expect("woken in time") | ||
| 39 | + .expect("the signal is open"); | ||
| 40 | + } | ||
| 41 | +} | ||
crates/forge-web/src/mail/mod.rsmodified+10 -3
| @@ -3,6 +3,7 @@ | |||
| 3 | //! Nothing sends mail inside a request. | 3 | //! Nothing sends mail inside a request. |
| 4 | 4 | ||
| 5 | pub mod account; | 5 | pub mod account; |
| 6 | +pub mod live; | ||
| 6 | pub mod log; | 7 | pub mod log; |
| 7 | pub mod smtp; | 8 | pub mod smtp; |
| 8 | pub mod templates; | 9 | pub mod templates; |
| @@ -11,7 +12,7 @@ pub mod worker; | |||
| 11 | use std::future::Future; | 12 | use std::future::Future; |
| 12 | use std::pin::Pin; | 13 | use std::pin::Pin; |
| 13 | 14 | ||
| 14 | -use forge_core::mail::{MailError, OutgoingMail}; | 15 | +use forge_core::mail::{MailError, MailKind, OutgoingMail}; |
| 15 | 16 | ||
| 16 | use crate::state::AppState; | 17 | use crate::state::AppState; |
| 17 | 18 | ||
| @@ -27,11 +28,14 @@ pub trait Mailer: Send + Sync { | |||
| 27 | fn send<'a>(&'a self, mail: &'a OutgoingMail) -> SendFuture<'a>; | 28 | fn send<'a>(&'a self, mail: &'a OutgoingMail) -> SendFuture<'a>; |
| 28 | } | 29 | } |
| 29 | 30 | ||
| 30 | -/// Queues one message, keyed by `idem_key`. Returns `false` when that key was already queued, so | 31 | +/// Queues one message of `kind` about the account `user_id` (if any), keyed by `idem_key`. Returns |
| 31 | -/// the caller can retry without sending twice. The worker is woken to pick it up. | 32 | +/// `false` when that key was already queued, so the caller can retry without sending twice. The |
| 33 | +/// worker is woken to pick it up. | ||
| 32 | pub async fn enqueue( | 34 | pub async fn enqueue( |
| 33 | state: &AppState, | 35 | state: &AppState, |
| 34 | idem_key: &str, | 36 | idem_key: &str, |
| 37 | + kind: MailKind, | ||
| 38 | + user_id: Option<&str>, | ||
| 35 | to: &str, | 39 | to: &str, |
| 36 | subject: &str, | 40 | subject: &str, |
| 37 | body: &str, | 41 | body: &str, |
| @@ -42,6 +46,8 @@ pub async fn enqueue( | |||
| 42 | body: body.to_owned(), | 46 | body: body.to_owned(), |
| 43 | message_id: None, | 47 | message_id: None, |
| 44 | in_reply_to: None, | 48 | in_reply_to: None, |
| 49 | + kind, | ||
| 50 | + user_id: user_id.map(str::to_owned), | ||
| 45 | }; | 51 | }; |
| 46 | enqueue_message(state, idem_key, &mail).await | 52 | enqueue_message(state, idem_key, &mail).await |
| 47 | } | 53 | } |
| @@ -55,6 +61,7 @@ pub async fn enqueue_message( | |||
| 55 | let queued = state.store.enqueue_mail(idem_key, mail).await?; | 61 | let queued = state.store.enqueue_mail(idem_key, mail).await?; |
| 56 | if queued { | 62 | if queued { |
| 57 | state.mail_waker.notify_one(); | 63 | state.mail_waker.notify_one(); |
| 64 | + live::bump(); | ||
| 58 | } | 65 | } |
| 59 | Ok(queued) | 66 | Ok(queued) |
| 60 | } | 67 | } |
crates/forge-web/src/mail/smtp.rsmodified+5 -0
| @@ -106,6 +106,7 @@ fn build_transport( | |||
| 106 | 106 | ||
| 107 | #[cfg(test)] | 107 | #[cfg(test)] |
| 108 | mod tests { | 108 | mod tests { |
| 109 | + use forge_core::mail::MailKind; | ||
| 109 | use super::*; | 110 | use super::*; |
| 110 | 111 | ||
| 111 | fn settings() -> MailSettings { | 112 | fn settings() -> MailSettings { |
| @@ -135,6 +136,8 @@ mod tests { | |||
| 135 | body: "hello".into(), | 136 | body: "hello".into(), |
| 136 | message_id: Some("<e1.u2@forge.test>".into()), | 137 | message_id: Some("<e1.u2@forge.test>".into()), |
| 137 | in_reply_to: Some("<issue-i3@forge.test>".into()), | 138 | in_reply_to: Some("<issue-i3@forge.test>".into()), |
| 139 | + kind: MailKind::Notification, | ||
| 140 | + user_id: None, | ||
| 138 | }; | 141 | }; |
| 139 | let text = rendered(&mail); | 142 | let text = rendered(&mail); |
| 140 | assert!(text.contains("Message-ID: <e1.u2@forge.test>"), "{text}"); | 143 | assert!(text.contains("Message-ID: <e1.u2@forge.test>"), "{text}"); |
| @@ -153,6 +156,8 @@ mod tests { | |||
| 153 | body: "b".into(), | 156 | body: "b".into(), |
| 154 | message_id: None, | 157 | message_id: None, |
| 155 | in_reply_to: None, | 158 | in_reply_to: None, |
| 159 | + kind: MailKind::Other, | ||
| 160 | + user_id: None, | ||
| 156 | }; | 161 | }; |
| 157 | let text = rendered(&mail); | 162 | let text = rendered(&mail); |
| 158 | assert!(!text.contains("In-Reply-To"), "{text}"); | 163 | assert!(!text.contains("In-Reply-To"), "{text}"); |
crates/forge-web/src/mail/worker.rsmodified+49 -7
| @@ -11,6 +11,7 @@ use forge_core::time::{now_stamp, stamp_after}; | |||
| 11 | use time::OffsetDateTime; | 11 | use time::OffsetDateTime; |
| 12 | use time::format_description::well_known::Rfc3339; | 12 | use time::format_description::well_known::Rfc3339; |
| 13 | 13 | ||
| 14 | +use crate::mail::live; | ||
| 14 | use crate::state::AppState; | 15 | use crate::state::AppState; |
| 15 | 16 | ||
| 16 | /// The longest the worker sleeps. It guards against a missed wake, not polling. | 17 | /// The longest the worker sleeps. It guards against a missed wake, not polling. |
| @@ -27,7 +28,22 @@ pub fn spawn(state: AppState) { | |||
| 27 | tokio::spawn(run(state)); | 28 | tokio::spawn(run(state)); |
| 28 | } | 29 | } |
| 29 | 30 | ||
| 31 | +/// Makes the outbox safe to resume after a restart: a row leased by a pass that died is released, | ||
| 32 | +/// so it is sent on the first pass instead of after its lease runs out. A message whose send had | ||
| 33 | +/// started but not finished may be sent again; that is the price of a queue that never loses mail. | ||
| 34 | +pub async fn boot(state: &AppState) -> forge_core::Result<u64> { | ||
| 35 | + let released = state.store.release_mail_leases().await?; | ||
| 36 | + if released > 0 { | ||
| 37 | + tracing::info!(released, "mail: released leases left by an earlier run"); | ||
| 38 | + live::bump(); | ||
| 39 | + } | ||
| 40 | + Ok(released) | ||
| 41 | +} | ||
| 42 | + | ||
| 30 | async fn run(state: AppState) { | 43 | async fn run(state: AppState) { |
| 44 | + if let Err(e) = boot(&state).await { | ||
| 45 | + tracing::error!(error = %e, "mail: could not release leases at boot"); | ||
| 46 | + } | ||
| 31 | loop { | 47 | loop { |
| 32 | let nap = match tick(&state).await { | 48 | let nap = match tick(&state).await { |
| 33 | Ok(nap) => nap, | 49 | Ok(nap) => nap, |
| @@ -67,6 +83,8 @@ async fn deliver(state: &AppState, entry: &OutboxEntry) { | |||
| 67 | body: entry.body.clone(), | 83 | body: entry.body.clone(), |
| 68 | message_id: entry.message_id.clone(), | 84 | message_id: entry.message_id.clone(), |
| 69 | in_reply_to: entry.in_reply_to.clone(), | 85 | in_reply_to: entry.in_reply_to.clone(), |
| 86 | + kind: entry.kind, | ||
| 87 | + user_id: entry.user_id.clone(), | ||
| 70 | }; | 88 | }; |
| 71 | let recorded = match state.mailer.send(&mail).await { | 89 | let recorded = match state.mailer.send(&mail).await { |
| 72 | Ok(()) => state.store.mark_mail_sent(&entry.id, &now_stamp()).await, | 90 | Ok(()) => state.store.mark_mail_sent(&entry.id, &now_stamp()).await, |
| @@ -91,6 +109,7 @@ async fn deliver(state: &AppState, entry: &OutboxEntry) { | |||
| 91 | if let Err(e) = recorded { | 109 | if let Err(e) = recorded { |
| 92 | tracing::error!(id = %entry.id, error = %e, "mail: could not record the outcome"); | 110 | tracing::error!(id = %entry.id, error = %e, "mail: could not record the outcome"); |
| 93 | } | 111 | } |
| 112 | + live::bump(); | ||
| 94 | } | 113 | } |
| 95 | 114 | ||
| 96 | /// How long the worker sleeps: until `next_due` (an RFC 3339 stamp), clamped to | 115 | /// How long the worker sleeps: until `next_due` (an RFC 3339 stamp), clamped to |
| @@ -107,7 +126,7 @@ pub fn sleep_for(next_due: Option<&str>, now: OffsetDateTime) -> Duration { | |||
| 107 | mod tests { | 126 | mod tests { |
| 108 | use std::sync::Arc; | 127 | use std::sync::Arc; |
| 109 | 128 | ||
| 110 | - use forge_core::mail::{MailSettingsUpdate, OutboxStatus, Security}; | 129 | + use forge_core::mail::{MailKind, MailSettingsUpdate, OutboxStatus, Security}; |
| 111 | use forge_core::time::{now_stamp, stamp_after}; | 130 | use forge_core::time::{now_stamp, stamp_after}; |
| 112 | 131 | ||
| 113 | use super::*; | 132 | use super::*; |
| @@ -151,18 +170,41 @@ mod tests { | |||
| 151 | assert_eq!(sleep_for(Some("soon"), now), BACKSTOP); | 170 | assert_eq!(sleep_for(Some("soon"), now), BACKSTOP); |
| 152 | } | 171 | } |
| 153 | 172 | ||
| 173 | + #[tokio::test] | ||
| 174 | + async fn a_row_leased_before_a_restart_is_sent_by_the_first_pass_after_boot() { | ||
| 175 | + let dir = tempfile::tempdir().expect("tempdir"); | ||
| 176 | + let (state, fake) = enabled_state(dir.path()).await; | ||
| 177 | + enqueue(&state, "stuck", MailKind::Notification, None, "a@example.com", "Hi", "body") | ||
| 178 | + .await | ||
| 179 | + .expect("queued"); | ||
| 180 | + // A pass that took the row and died before it finished: the lease is still set. | ||
| 181 | + let held = state | ||
| 182 | + .store | ||
| 183 | + .lease_mail(&now_stamp(), &stamp_after(LEASE), BATCH) | ||
| 184 | + .await | ||
| 185 | + .expect("lease"); | ||
| 186 | + assert_eq!(held.len(), 1); | ||
| 187 | + assert!(fake.sent().is_empty()); | ||
| 188 | + | ||
| 189 | + assert_eq!(boot(&state).await.expect("boot"), 1); | ||
| 190 | + tick(&state).await.expect("pass"); | ||
| 191 | + assert_eq!(fake.sent().len(), 1, "the released row goes out without waiting"); | ||
| 192 | + let row = state.store.recent_mail(10).await.expect("rows").remove(0); | ||
| 193 | + assert_eq!(row.status(), OutboxStatus::Sent); | ||
| 194 | + } | ||
| 195 | + | ||
| 154 | #[tokio::test] | 196 | #[tokio::test] |
| 155 | async fn a_queued_message_is_sent_once() { | 197 | async fn a_queued_message_is_sent_once() { |
| 156 | let dir = tempfile::tempdir().expect("tempdir"); | 198 | let dir = tempfile::tempdir().expect("tempdir"); |
| 157 | let (state, fake) = enabled_state(dir.path()).await; | 199 | let (state, fake) = enabled_state(dir.path()).await; |
| 158 | assert!( | 200 | assert!( |
| 159 | - enqueue(&state, "reset:1", "a@example.com", "Hi", "body") | 201 | + enqueue(&state, "reset:1", MailKind::PasswordReset, None, "a@example.com", "Hi", "body") |
| 160 | .await | 202 | .await |
| 161 | .expect("queued") | 203 | .expect("queued") |
| 162 | ); | 204 | ); |
| 163 | // A second enqueue with the same key is a no-op. | 205 | // A second enqueue with the same key is a no-op. |
| 164 | assert!( | 206 | assert!( |
| 165 | - !enqueue(&state, "reset:1", "a@example.com", "Hi", "body") | 207 | + !enqueue(&state, "reset:1", MailKind::PasswordReset, None, "a@example.com", "Hi", "body") |
| 166 | .await | 208 | .await |
| 167 | .expect("again") | 209 | .expect("again") |
| 168 | ); | 210 | ); |
| @@ -195,7 +237,7 @@ mod tests { | |||
| 195 | }) | 237 | }) |
| 196 | .await | 238 | .await |
| 197 | .expect("off"); | 239 | .expect("off"); |
| 198 | - enqueue(&state, "k", "a@example.com", "Hi", "body") | 240 | + enqueue(&state, "k", MailKind::Other, None, "a@example.com", "Hi", "body") |
| 199 | .await | 241 | .await |
| 200 | .expect("queued"); | 242 | .expect("queued"); |
| 201 | assert_eq!(tick(&state).await.expect("pass"), BACKSTOP); | 243 | assert_eq!(tick(&state).await.expect("pass"), BACKSTOP); |
| @@ -209,10 +251,10 @@ mod tests { | |||
| 209 | async fn a_transient_failure_is_retried_later_and_a_permanent_one_gives_up() { | 251 | async fn a_transient_failure_is_retried_later_and_a_permanent_one_gives_up() { |
| 210 | let dir = tempfile::tempdir().expect("tempdir"); | 252 | let dir = tempfile::tempdir().expect("tempdir"); |
| 211 | let (state, fake) = enabled_state(dir.path()).await; | 253 | let (state, fake) = enabled_state(dir.path()).await; |
| 212 | - enqueue(&state, "retry", "a@example.com", "Hi", "body") | 254 | + enqueue(&state, "retry", MailKind::Other, None, "a@example.com", "Hi", "body") |
| 213 | .await | 255 | .await |
| 214 | .expect("queued"); | 256 | .expect("queued"); |
| 215 | - enqueue(&state, "bounce", "b@example.com", "Hi", "body") | 257 | + enqueue(&state, "bounce", MailKind::Other, None, "b@example.com", "Hi", "body") |
| 216 | .await | 258 | .await |
| 217 | .expect("queued"); | 259 | .expect("queued"); |
| 218 | fake.fail_next(MailError::Transient("timeout".into())); | 260 | fake.fail_next(MailError::Transient("timeout".into())); |
| @@ -241,7 +283,7 @@ mod tests { | |||
| 241 | async fn the_last_try_gives_up_and_an_earlier_one_reschedules() { | 283 | async fn the_last_try_gives_up_and_an_earlier_one_reschedules() { |
| 242 | let dir = tempfile::tempdir().expect("tempdir"); | 284 | let dir = tempfile::tempdir().expect("tempdir"); |
| 243 | let (state, fake) = enabled_state(dir.path()).await; | 285 | let (state, fake) = enabled_state(dir.path()).await; |
| 244 | - enqueue(&state, "stubborn", "a@example.com", "Hi", "body") | 286 | + enqueue(&state, "stubborn", MailKind::Other, None, "a@example.com", "Hi", "body") |
| 245 | .await | 287 | .await |
| 246 | .expect("queued"); | 288 | .expect("queued"); |
| 247 | let row = state.store.recent_mail(10).await.expect("rows").remove(0); | 289 | let row = state.store.recent_mail(10).await.expect("rows").remove(0); |
crates/forge-web/src/main.rsmodified+3 -0
| @@ -6,6 +6,9 @@ | |||
| 6 | 6 | ||
| 7 | #![recursion_limit = "256"] | 7 | #![recursion_limit = "256"] |
| 8 | 8 | ||
| 9 | +mod accent; | ||
| 10 | +#[allow(dead_code)] // build.rs uses the whole file; the app reads only part of it. | ||
| 11 | +mod accent_palette; | ||
| 9 | mod access; | 12 | mod access; |
| 10 | mod admin_cli; | 13 | mod admin_cli; |
| 11 | mod admin_client; | 14 | mod admin_client; |
crates/forge-web/src/notify.rsmodified+3 -1
| @@ -6,7 +6,7 @@ | |||
| 6 | 6 | ||
| 7 | use std::collections::{BTreeMap, BTreeSet}; | 7 | use std::collections::{BTreeMap, BTreeSet}; |
| 8 | 8 | ||
| 9 | -use forge_core::mail::OutgoingMail; | 9 | +use forge_core::mail::{MailKind, OutgoingMail}; |
| 10 | use forge_core::notifications::{Reason, SubState, WatchLevel}; | 10 | use forge_core::notifications::{Reason, SubState, WatchLevel}; |
| 11 | use forge_core::store::orgs::OrgMemberRole; | 11 | use forge_core::store::orgs::OrgMemberRole; |
| 12 | use forge_core::{Action, Issue, Repo, Result, User, authorize}; | 12 | use forge_core::{Action, Issue, Repo, Result, User, authorize}; |
| @@ -533,6 +533,8 @@ async fn queue_email( | |||
| 533 | body, | 533 | body, |
| 534 | message_id: Some(message_id), | 534 | message_id: Some(message_id), |
| 535 | in_reply_to, | 535 | in_reply_to, |
| 536 | + kind: MailKind::Notification, | ||
| 537 | + user_id: Some(user_id.to_owned()), | ||
| 536 | }; | 538 | }; |
| 537 | let idem_key = format!("notif:{}:{user_id}", plan.event_id); | 539 | let idem_key = format!("notif:{}:{user_id}", plan.event_id); |
| 538 | mail::enqueue_message(state, &idem_key, &outgoing).await?; | 540 | mail::enqueue_message(state, &idem_key, &outgoing).await?; |
crates/forge-web/src/pages/admin_mail.rsmodified+510 -82
| @@ -1,17 +1,24 @@ | |||
| 1 | //! Page: outgoing mail (`/admin/mail`). Instance admins only; anyone else gets 404. | 1 | //! Page: outgoing mail (`/admin/mail`). Instance admins only; anyone else gets 404. |
| 2 | //! | 2 | //! |
| 3 | -//! The form stores the SMTP server, sender and password (the password is write-only: a blank field | 3 | +//! Two tabs. Settings: the SMTP server, sender and password (the password is write-only: a blank |
| 4 | -//! keeps the stored one). "Send test mail" queues one message to the admin's own address. The | 4 | +//! field keeps the stored one) and "Send test mail" to the admin's own address. Queue: every |
| 5 | -//! list shows the newest 50 outbox rows with their status and last error, never the body. | 5 | +//! message in the outbox with its state, kind, tries and last error, filtered by state. A failed |
| 6 | +//! message can be retried or discarded there. The queue's wrapper carries `data-live`, so each | ||
| 7 | +//! queue change re-renders it through `/admin/mail/events` with no reload and no polling. | ||
| 6 | //! Saving the settings and queuing a test are audited. | 8 | //! Saving the settings and queuing a test are audited. |
| 7 | 9 | ||
| 8 | -use forge_core::mail::{MailSettings, MailSettingsUpdate, OutboxEntry, Security}; | 10 | +use forge_core::config::MailTransport; |
| 11 | +use forge_core::mail::{MailKind, MailSettings, MailSettingsUpdate, MailState, OutboxEntry, Security}; | ||
| 12 | +use forge_core::time::now_stamp; | ||
| 9 | use forge_core::tz::format_in_tz; | 13 | use forge_core::tz::format_in_tz; |
| 10 | use forge_core::{AuditAction, Error}; | 14 | use forge_core::{AuditAction, Error}; |
| 15 | +use futures_util::{Stream, stream}; | ||
| 11 | use serde::Deserialize; | 16 | use serde::Deserialize; |
| 17 | +use tokio::sync::watch; | ||
| 12 | use topcoat::Result; | 18 | use topcoat::Result; |
| 13 | use topcoat::context::{Cx, app_context}; | 19 | use topcoat::context::{Cx, app_context}; |
| 14 | use topcoat::router::content::Form; | 20 | use topcoat::router::content::Form; |
| 21 | +use topcoat::router::content::sse::Event; | ||
| 15 | use topcoat::router::error::{forbidden, see_other}; | 22 | use topcoat::router::error::{forbidden, see_other}; |
| 16 | use topcoat::router::response::Response; | 23 | use topcoat::router::response::Response; |
| 17 | use topcoat::router::{page, query_params, route}; | 24 | use topcoat::router::{page, query_params, route}; |
| @@ -21,28 +28,58 @@ use crate::audit::{self, Actor, Target}; | |||
| 21 | use crate::auth::check_csrf; | 28 | use crate::auth::check_csrf; |
| 22 | use crate::i18n::admin::{self as g, K}; | 29 | use crate::i18n::admin::{self as g, K}; |
| 23 | use crate::i18n::{self, Key, Lang}; | 30 | use crate::i18n::{self, Key, Lang}; |
| 24 | -use crate::mail::{enqueue, templates}; | 31 | +use crate::mail::{enqueue, live, templates}; |
| 25 | use crate::pages::admin_users::admin_only; | 32 | use crate::pages::admin_users::admin_only; |
| 33 | +use crate::pages::ci_runs::{changed_event, events_response}; | ||
| 26 | use crate::pages::issues_list::stamp_unix; | 34 | use crate::pages::issues_list::stamp_unix; |
| 27 | use crate::state::AppState; | 35 | use crate::state::AppState; |
| 28 | use crate::views::{enc, shell}; | 36 | use crate::views::{enc, shell}; |
| 29 | 37 | ||
| 30 | -/// Rows shown in the outbox list. | 38 | +/// Rows shown in the queue at most. |
| 31 | -const LIST_LIMIT: u32 = 50; | 39 | +const LIST_LIMIT: u32 = 100; |
| 32 | 40 | ||
| 33 | #[query_params(error = bad_request)] | 41 | #[query_params(error = bad_request)] |
| 34 | pub(crate) struct NoticeQuery { | 42 | pub(crate) struct NoticeQuery { |
| 35 | notice: Option<String>, | 43 | notice: Option<String>, |
| 44 | + tab: Option<String>, | ||
| 45 | + state: Option<String>, | ||
| 36 | } | 46 | } |
| 37 | 47 | ||
| 38 | -/// One outbox row, already formatted. There is no body field on purpose. | 48 | +/// The two tabs of the page. |
| 39 | -struct MailRow { | 49 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 50 | +enum Tab { | ||
| 51 | + Settings, | ||
| 52 | + Queue, | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +/// One queue row, already formatted. There is no body field on purpose. | ||
| 56 | +struct QueueRow { | ||
| 57 | + id: String, | ||
| 40 | to: String, | 58 | to: String, |
| 41 | subject: String, | 59 | subject: String, |
| 42 | - status: &'static str, | 60 | + kind: &'static str, |
| 61 | + state: &'static str, | ||
| 62 | + state_class: &'static str, | ||
| 43 | attempts: u32, | 63 | attempts: u32, |
| 44 | error: String, | 64 | error: String, |
| 45 | created: String, | 65 | created: String, |
| 66 | + sent: String, | ||
| 67 | + failed: bool, | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +/// One state filter: the link, its label and how many rows it covers. | ||
| 71 | +struct FilterChip { | ||
| 72 | + href: String, | ||
| 73 | + label: &'static str, | ||
| 74 | + count: u32, | ||
| 75 | + class: &'static str, | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +/// The queue tab: the filter chips, the rows and the state the filter is on, for the forms. | ||
| 79 | +struct QueueData { | ||
| 80 | + chips: Vec<FilterChip>, | ||
| 81 | + rows: Vec<QueueRow>, | ||
| 82 | + filter_param: String, | ||
| 46 | } | 83 | } |
| 47 | 84 | ||
| 48 | /// Everything the page shows. The password is never in here. | 85 | /// Everything the page shows. The password is never in here. |
| @@ -55,29 +92,105 @@ struct PageData { | |||
| 55 | from_name: String, | 92 | from_name: String, |
| 56 | enabled: bool, | 93 | enabled: bool, |
| 57 | has_password: bool, | 94 | has_password: bool, |
| 58 | - rows: Vec<MailRow>, | 95 | + transport: &'static str, |
| 96 | + tab: Tab, | ||
| 97 | + queue: Option<QueueData>, | ||
| 98 | +} | ||
| 99 | + | ||
| 100 | +/// The CSS class of a state pill. The pills reuse the CI state colours. | ||
| 101 | +fn state_class(state: MailState) -> &'static str { | ||
| 102 | + match state { | ||
| 103 | + MailState::Sent => "ci-state ci-success", | ||
| 104 | + MailState::Sending => "ci-state ci-running", | ||
| 105 | + MailState::Queued => "ci-state ci-queued", | ||
| 106 | + MailState::Retrying => "ci-state ci-blocked", | ||
| 107 | + MailState::Failed => "ci-state ci-failure", | ||
| 108 | + MailState::Discarded => "ci-state ci-skipped", | ||
| 109 | + } | ||
| 59 | } | 110 | } |
| 60 | 111 | ||
| 61 | -fn row_view(entry: &OutboxEntry, tz: &str, lang: Lang) -> MailRow { | 112 | +fn transport_name(transport: MailTransport) -> &'static str { |
| 62 | - MailRow { | 113 | + match transport { |
| 114 | + MailTransport::Smtp => "smtp", | ||
| 115 | + MailTransport::Log => "log", | ||
| 116 | + } | ||
| 117 | +} | ||
| 118 | + | ||
| 119 | +fn tab_class(on: bool) -> &'static str { | ||
| 120 | + if on { "subnav-link current" } else { "subnav-link" } | ||
| 121 | +} | ||
| 122 | + | ||
| 123 | +fn row_view(entry: &OutboxEntry, now: &str, tz: &str, lang: Lang) -> QueueRow { | ||
| 124 | + let state = entry.state_at(now); | ||
| 125 | + QueueRow { | ||
| 126 | + id: entry.id.clone(), | ||
| 63 | to: entry.to_addr.clone(), | 127 | to: entry.to_addr.clone(), |
| 64 | subject: entry.subject.clone(), | 128 | subject: entry.subject.clone(), |
| 65 | - status: g::outbox_status(lang, entry.status()), | 129 | + kind: g::mail_kind(lang, entry.kind), |
| 130 | + state: g::mail_state(lang, state), | ||
| 131 | + state_class: state_class(state), | ||
| 66 | attempts: entry.attempts, | 132 | attempts: entry.attempts, |
| 67 | error: entry.last_error.clone().unwrap_or_default(), | 133 | error: entry.last_error.clone().unwrap_or_default(), |
| 68 | created: format_in_tz(stamp_unix(&entry.created_at), tz), | 134 | created: format_in_tz(stamp_unix(&entry.created_at), tz), |
| 135 | + sent: entry | ||
| 136 | + .sent_at | ||
| 137 | + .as_deref() | ||
| 138 | + .map(|sent| format_in_tz(stamp_unix(sent), tz)) | ||
| 139 | + .unwrap_or_default(), | ||
| 140 | + failed: state == MailState::Failed, | ||
| 69 | } | 141 | } |
| 70 | } | 142 | } |
| 71 | 143 | ||
| 72 | -async fn page_data(state: &AppState, tz: &str, lang: Lang) -> forge_core::Result<PageData> { | 144 | +/// The queue tab's data. `filter` of `None` lists every state. |
| 73 | - let settings: MailSettings = state.store.mail_settings().await?; | 145 | +async fn queue_data( |
| 146 | + state: &AppState, | ||
| 147 | + tz: &str, | ||
| 148 | + lang: Lang, | ||
| 149 | + filter: Option<MailState>, | ||
| 150 | +) -> forge_core::Result<QueueData> { | ||
| 151 | + let now = now_stamp(); | ||
| 152 | + let counts = state.store.mail_state_counts(&now).await?; | ||
| 153 | + let total: u32 = counts.iter().map(|(_, n)| *n).sum(); | ||
| 154 | + let mut chips = vec![FilterChip { | ||
| 155 | + href: "/admin/mail?tab=queue".to_owned(), | ||
| 156 | + label: g::t(lang, K::MailFilterAll), | ||
| 157 | + count: total, | ||
| 158 | + class: tab_class(filter.is_none()), | ||
| 159 | + }]; | ||
| 160 | + for (kind, count) in counts { | ||
| 161 | + chips.push(FilterChip { | ||
| 162 | + href: format!("/admin/mail?tab=queue&state={}", kind.as_str()), | ||
| 163 | + label: g::mail_state(lang, kind), | ||
| 164 | + count, | ||
| 165 | + class: tab_class(filter == Some(kind)), | ||
| 166 | + }); | ||
| 167 | + } | ||
| 74 | let rows = state | 168 | let rows = state |
| 75 | .store | 169 | .store |
| 76 | - .recent_mail(LIST_LIMIT) | 170 | + .list_mail(filter, &now, LIST_LIMIT) |
| 77 | .await? | 171 | .await? |
| 78 | .iter() | 172 | .iter() |
| 79 | - .map(|entry| row_view(entry, tz, lang)) | 173 | + .map(|entry| row_view(entry, &now, tz, lang)) |
| 80 | .collect(); | 174 | .collect(); |
| 175 | + Ok(QueueData { | ||
| 176 | + chips, | ||
| 177 | + rows, | ||
| 178 | + filter_param: filter.map_or_else(String::new, |s| s.as_str().to_owned()), | ||
| 179 | + }) | ||
| 180 | +} | ||
| 181 | + | ||
| 182 | +async fn page_data( | ||
| 183 | + state: &AppState, | ||
| 184 | + tz: &str, | ||
| 185 | + lang: Lang, | ||
| 186 | + tab: Tab, | ||
| 187 | + filter: Option<MailState>, | ||
| 188 | +) -> forge_core::Result<PageData> { | ||
| 189 | + let settings: MailSettings = state.store.mail_settings().await?; | ||
| 190 | + let queue = match tab { | ||
| 191 | + Tab::Queue => Some(queue_data(state, tz, lang, filter).await?), | ||
| 192 | + Tab::Settings => None, | ||
| 193 | + }; | ||
| 81 | Ok(PageData { | 194 | Ok(PageData { |
| 82 | host: settings.host, | 195 | host: settings.host, |
| 83 | port: settings.port.to_string(), | 196 | port: settings.port.to_string(), |
| @@ -87,7 +200,9 @@ async fn page_data(state: &AppState, tz: &str, lang: Lang) -> forge_core::Result | |||
| 87 | from_name: settings.from_name, | 200 | from_name: settings.from_name, |
| 88 | enabled: settings.enabled, | 201 | enabled: settings.enabled, |
| 89 | has_password: settings.has_password, | 202 | has_password: settings.has_password, |
| 90 | - rows, | 203 | + transport: transport_name(state.config.mail.transport), |
| 204 | + tab, | ||
| 205 | + queue, | ||
| 91 | }) | 206 | }) |
| 92 | } | 207 | } |
| 93 | 208 | ||
| @@ -106,79 +221,120 @@ async fn mail_view( | |||
| 106 | } else { | 221 | } else { |
| 107 | g::t(lang, K::NoPasswordStored) | 222 | g::t(lang, K::NoPasswordStored) |
| 108 | }; | 223 | }; |
| 224 | + let settings_on = data.tab == Tab::Settings; | ||
| 225 | + let settings_class = tab_class(settings_on); | ||
| 226 | + let queue_class = tab_class(!settings_on); | ||
| 227 | + let filter_param = data.queue.as_ref().map(|q| q.filter_param.clone()).unwrap_or_default(); | ||
| 109 | Ok(view! { | 228 | Ok(view! { |
| 110 | <section class="page-head"> | 229 | <section class="page-head"> |
| 111 | <h1>(g::t(lang, K::Mail))</h1> | 230 | <h1>(g::t(lang, K::Mail))</h1> |
| 112 | <p class="muted">(g::t(lang, K::MailIntro))</p> | 231 | <p class="muted">(g::t(lang, K::MailIntro))</p> |
| 113 | </section> | 232 | </section> |
| 233 | + <nav class="subnav" aria-label=(g::t(lang, K::Mail))> | ||
| 234 | + <a class=(settings_class) href="/admin/mail">(g::t(lang, K::MailTabSettings))</a> | ||
| 235 | + <a class=(queue_class) href="/admin/mail?tab=queue">(g::t(lang, K::MailTabQueue))</a> | ||
| 236 | + </nav> | ||
| 114 | if let Some(message) = notice { | 237 | if let Some(message) = notice { |
| 115 | <section class="card notice" role="status"> | 238 | <section class="card notice" role="status"> |
| 116 | <p>(message.as_str())</p> | 239 | <p>(message.as_str())</p> |
| 117 | </section> | 240 | </section> |
| 118 | } | 241 | } |
| 119 | - <section class="card"> | 242 | + if settings_on { |
| 120 | - <h2>(g::t(lang, K::SmtpServer))</h2> | 243 | + <section class="card"> |
| 121 | - <form method="post" action="/admin/mail"> | 244 | + <h2>(g::t(lang, K::SmtpServer))</h2> |
| 122 | - <input type="hidden" name="csrf" value=(csrf.as_str())> | 245 | + <p class="muted small">(g::t(lang, K::MailTransportNote))</p> |
| 123 | - <label>(g::t(lang, K::MailHost)) <input type="text" name="host" value=(data.host.as_str()) maxlength="253" autocomplete="off"></label> | 246 | + <p class="small">(g::t(lang, K::MailTransportInUse)) " " <code>(data.transport)</code></p> |
| 124 | - <label>(g::t(lang, K::MailPort)) <input type="number" name="port" value=(data.port.as_str()) min="1" max="65535"></label> | 247 | + <form method="post" action="/admin/mail"> |
| 125 | - <label>(i18n::t(lang, Key::Security)) | 248 | + <input type="hidden" name="csrf" value=(csrf.as_str())> |
| 126 | - <select name="security"> | 249 | + <label>(g::t(lang, K::MailHost)) <input type="text" name="host" value=(data.host.as_str()) maxlength="253" autocomplete="off"></label> |
| 127 | - <option value="starttls" selected=(starttls)>"STARTTLS"</option> | 250 | + <label>(g::t(lang, K::MailPort)) <input type="number" name="port" value=(data.port.as_str()) min="1" max="65535"></label> |
| 128 | - <option value="tls" selected=(tls)>"TLS"</option> | 251 | + <label>(i18n::t(lang, Key::Security)) |
| 129 | - <option value="none" selected=(plain)>(g::t(lang, K::SecurityNone))</option> | 252 | + <select name="security"> |
| 130 | - </select> | 253 | + <option value="starttls" selected=(starttls)>"STARTTLS"</option> |
| 131 | - </label> | 254 | + <option value="tls" selected=(tls)>"TLS"</option> |
| 132 | - <label>(i18n::t(lang, Key::Username)) <input type="text" name="username" value=(data.username.as_str()) maxlength="256" autocomplete="off"></label> | 255 | + <option value="none" selected=(plain)>(g::t(lang, K::SecurityNone))</option> |
| 133 | - <label>(i18n::t(lang, Key::Password)) <input type="password" name="password" autocomplete="new-password" maxlength="1024"></label> | 256 | + </select> |
| 134 | - <p class="muted small">(password_hint)</p> | 257 | + </label> |
| 135 | - <label>(g::t(lang, K::FromAddress)) <input type="email" name="from_addr" value=(data.from_addr.as_str()) maxlength="254"></label> | 258 | + <label>(i18n::t(lang, Key::Username)) <input type="text" name="username" value=(data.username.as_str()) maxlength="256" autocomplete="off"></label> |
| 136 | - <label>(g::t(lang, K::FromName)) <input type="text" name="from_name" value=(data.from_name.as_str()) maxlength="100"></label> | 259 | + <label>(i18n::t(lang, Key::Password)) <input type="password" name="password" autocomplete="new-password" maxlength="1024"></label> |
| 137 | - <label><input type="checkbox" name="enabled" value="on" checked=(data.enabled)>(g::t(lang, K::SendMailCheckbox))</label> | 260 | + <p class="muted small">(password_hint)</p> |
| 138 | - <div class="actions"> | 261 | + <label>(g::t(lang, K::FromAddress)) <input type="email" name="from_addr" value=(data.from_addr.as_str()) maxlength="254"></label> |
| 139 | - <button type="submit" class="primary">(i18n::t(lang, Key::Save))</button> | 262 | + <label>(g::t(lang, K::FromName)) <input type="text" name="from_name" value=(data.from_name.as_str()) maxlength="100"></label> |
| 140 | - </div> | 263 | + <label><input type="checkbox" name="enabled" value="on" checked=(data.enabled)>(g::t(lang, K::SendMailCheckbox))</label> |
| 141 | - </form> | 264 | + <div class="actions"> |
| 142 | - <form method="post" action="/admin/mail/test"> | 265 | + <button type="submit" class="primary">(i18n::t(lang, Key::Save))</button> |
| 143 | - <input type="hidden" name="csrf" value=(csrf.as_str())> | 266 | + </div> |
| 144 | - <div class="actions"> | 267 | + </form> |
| 145 | - <button type="submit">(g::t(lang, K::SendTestMailToMe))</button> | 268 | + <form method="post" action="/admin/mail/test"> |
| 269 | + <input type="hidden" name="csrf" value=(csrf.as_str())> | ||
| 270 | + <div class="actions"> | ||
| 271 | + <button type="submit">(g::t(lang, K::SendTestMailToMe))</button> | ||
| 272 | + </div> | ||
| 273 | + </form> | ||
| 274 | + </section> | ||
| 275 | + } else if let Some(queue) = data.queue { | ||
| 276 | + <section class="card"> | ||
| 277 | + <p class="muted small">(g::t(lang, K::MailQueueIntro))</p> | ||
| 278 | + <div class="mail-filters"> | ||
| 279 | + for chip in queue.chips.into_iter() { | ||
| 280 | + <a class=(chip.class) href=(chip.href.as_str())>(chip.label) " " <span class="tab-count">(chip.count)</span></a> | ||
| 281 | + } | ||
| 146 | </div> | 282 | </div> |
| 147 | - </form> | 283 | + <div data-live="/admin/mail/events"> |
| 148 | - </section> | 284 | + if queue.rows.is_empty() { |
| 149 | - <section class="card"> | 285 | + <p class="muted">(g::t(lang, K::MailNothingMatches))</p> |
| 150 | - <h2>(g::t(lang, K::RecentMessages))</h2> | 286 | + } else { |
| 151 | - if data.rows.is_empty() { | 287 | + <div class="table-wrap"> |
| 152 | - <p class="muted">(g::t(lang, K::NothingQueued))</p> | 288 | + <table class="table mail-queue"> |
| 153 | - } else { | 289 | + <thead> |
| 154 | - <div class="table-wrap"> | 290 | + <tr> |
| 155 | - <table class="table"> | 291 | + <th>(g::t(lang, K::TableQueued))</th> |
| 156 | - <thead> | 292 | + <th>(g::t(lang, K::TableTo))</th> |
| 157 | - <tr> | 293 | + <th>(g::t(lang, K::TableKind))</th> |
| 158 | - <th>(g::t(lang, K::TableQueued))</th> | 294 | + <th>(g::t(lang, K::TableSubject))</th> |
| 159 | - <th>(g::t(lang, K::TableTo))</th> | 295 | + <th>(g::t(lang, K::TableState))</th> |
| 160 | - <th>(g::t(lang, K::TableSubject))</th> | 296 | + <th>(g::t(lang, K::TableTries))</th> |
| 161 | - <th>(g::t(lang, K::TableStatus))</th> | 297 | + <th>(g::t(lang, K::MailSentAt))</th> |
| 162 | - <th>(g::t(lang, K::TableTries))</th> | 298 | + <th>(g::t(lang, K::TableLastError))</th> |
| 163 | - <th>(g::t(lang, K::TableLastError))</th> | 299 | + <th></th> |
| 164 | - </tr> | 300 | + </tr> |
| 165 | - </thead> | 301 | + </thead> |
| 166 | - <tbody> | 302 | + <tbody> |
| 167 | - for row in data.rows.into_iter() { | 303 | + for row in queue.rows.into_iter() { |
| 168 | - <tr> | 304 | + <tr> |
| 169 | - <td class="small">(row.created.as_str())</td> | 305 | + <td class="small">(row.created.as_str())</td> |
| 170 | - <td>(row.to.as_str())</td> | 306 | + <td>(row.to.as_str())</td> |
| 171 | - <td>(row.subject.as_str())</td> | 307 | + <td>(row.kind)</td> |
| 172 | - <td>(row.status)</td> | 308 | + <td>(row.subject.as_str())</td> |
| 173 | - <td>(row.attempts)</td> | 309 | + <td><span class=(row.state_class)>(row.state)</span></td> |
| 174 | - <td class="small">(row.error.as_str())</td> | 310 | + <td>(row.attempts)</td> |
| 175 | - </tr> | 311 | + <td class="small">(row.sent.as_str())</td> |
| 176 | - } | 312 | + <td class="small">(row.error.as_str())</td> |
| 177 | - </tbody> | 313 | + <td class="mail-actions"> |
| 178 | - </table> | 314 | + if row.failed { |
| 315 | + <form method="post" action="/admin/mail/queue/retry"> | ||
| 316 | + <input type="hidden" name="csrf" value=(csrf.as_str())> | ||
| 317 | + <input type="hidden" name="id" value=(row.id.as_str())> | ||
| 318 | + <input type="hidden" name="state" value=(filter_param.as_str())> | ||
| 319 | + <button type="submit">(g::t(lang, K::MailRetryNow))</button> | ||
| 320 | + </form> | ||
| 321 | + <form method="post" action="/admin/mail/queue/discard"> | ||
| 322 | + <input type="hidden" name="csrf" value=(csrf.as_str())> | ||
| 323 | + <input type="hidden" name="id" value=(row.id.as_str())> | ||
| 324 | + <input type="hidden" name="state" value=(filter_param.as_str())> | ||
| 325 | + <button type="submit">(g::t(lang, K::MailDiscard))</button> | ||
| 326 | + </form> | ||
| 327 | + } | ||
| 328 | + </td> | ||
| 329 | + </tr> | ||
| 330 | + } | ||
| 331 | + </tbody> | ||
| 332 | + </table> | ||
| 333 | + </div> | ||
| 334 | + } | ||
| 179 | </div> | 335 | </div> |
| 180 | - } | 336 | + </section> |
| 181 | - </section> | 337 | + } |
| 182 | }) | 338 | }) |
| 183 | } | 339 | } |
| 184 | 340 | ||
| @@ -188,7 +344,13 @@ async fn mail_page(cx: &Cx) -> Result<impl View> { | |||
| 188 | let query = query_params::<NoticeQuery>(cx)?; | 344 | let query = query_params::<NoticeQuery>(cx)?; |
| 189 | let state = app_context::<AppState>(cx); | 345 | let state = app_context::<AppState>(cx); |
| 190 | let lang = i18n::lang(cx, Some(&viewer.0)); | 346 | let lang = i18n::lang(cx, Some(&viewer.0)); |
| 191 | - let data = page_data(state, viewer.0.timezone.as_str(), lang).await?; | 347 | + let tab = if query.tab.as_deref() == Some("queue") { |
| 348 | + Tab::Queue | ||
| 349 | + } else { | ||
| 350 | + Tab::Settings | ||
| 351 | + }; | ||
| 352 | + let filter = query.state.as_deref().and_then(MailState::parse); | ||
| 353 | + let data = page_data(state, viewer.0.timezone.as_str(), lang, tab, filter).await?; | ||
| 192 | let csrf = viewer.1.csrf_token.clone(); | 354 | let csrf = viewer.1.csrf_token.clone(); |
| 193 | let title = g::t(lang, K::Mail); | 355 | let title = g::t(lang, K::Mail); |
| 194 | Ok(view! { | 356 | Ok(view! { |
| @@ -196,6 +358,24 @@ async fn mail_page(cx: &Cx) -> Result<impl View> { | |||
| 196 | }) | 358 | }) |
| 197 | } | 359 | } |
| 198 | 360 | ||
| 361 | +/// The live `changed` stream of the queue. One event per queue change. Nothing is sent on connect: | ||
| 362 | +/// the page was just rendered. | ||
| 363 | +fn queue_changes(wake: watch::Receiver<u64>) -> impl Stream<Item = Result<Event>> + Send + 'static { | ||
| 364 | + stream::unfold(wake, |mut wake| async move { | ||
| 365 | + wake.changed().await.ok()?; | ||
| 366 | + Some((changed_event("queue".to_owned()), wake)) | ||
| 367 | + }) | ||
| 368 | +} | ||
| 369 | + | ||
| 370 | +/// The queue's change stream. Admins only. | ||
| 371 | +#[route(GET "/admin/mail/events")] | ||
| 372 | +async fn mail_events(cx: &Cx) -> Result<Response> { | ||
| 373 | + admin_only(cx).await?; | ||
| 374 | + // Subscribed before the response is sent, so a change after this point is sent. | ||
| 375 | + let wake = live::subscribe(); | ||
| 376 | + events_response(cx, queue_changes(wake)) | ||
| 377 | +} | ||
| 378 | + | ||
| 199 | #[derive(Deserialize, Default)] | 379 | #[derive(Deserialize, Default)] |
| 200 | struct SettingsForm { | 380 | struct SettingsForm { |
| 201 | #[serde(default)] | 381 | #[serde(default)] |
| @@ -283,6 +463,7 @@ async fn save_settings( | |||
| 283 | ) | 463 | ) |
| 284 | .await; | 464 | .await; |
| 285 | state.mail_waker.notify_one(); | 465 | state.mail_waker.notify_one(); |
| 466 | + live::bump(); | ||
| 286 | Ok(()) | 467 | Ok(()) |
| 287 | } | 468 | } |
| 288 | 469 | ||
| @@ -327,7 +508,16 @@ async fn queue_test( | |||
| 327 | }; | 508 | }; |
| 328 | let (subject, body) = templates::test_mail(); | 509 | let (subject, body) = templates::test_mail(); |
| 329 | let key = format!("test:{}", ulid::Ulid::generate()); | 510 | let key = format!("test:{}", ulid::Ulid::generate()); |
| 330 | - enqueue(state, &key, address, &subject, &body).await?; | 511 | + enqueue( |
| 512 | + state, | ||
| 513 | + &key, | ||
| 514 | + MailKind::Test, | ||
| 515 | + Some(&user.id), | ||
| 516 | + address, | ||
| 517 | + &subject, | ||
| 518 | + &body, | ||
| 519 | + ) | ||
| 520 | + .await?; | ||
| 331 | audit::record( | 521 | audit::record( |
| 332 | &state.store, | 522 | &state.store, |
| 333 | Some(cx), | 523 | Some(cx), |
| @@ -344,6 +534,70 @@ async fn queue_test( | |||
| 344 | Ok(()) | 534 | Ok(()) |
| 345 | } | 535 | } |
| 346 | 536 | ||
| 537 | +#[derive(Clone, Copy)] | ||
| 538 | +enum QueueAction { | ||
| 539 | + Retry, | ||
| 540 | + Discard, | ||
| 541 | +} | ||
| 542 | + | ||
| 543 | +#[derive(Deserialize, Default)] | ||
| 544 | +struct QueueForm { | ||
| 545 | + #[serde(default)] | ||
| 546 | + csrf: String, | ||
| 547 | + #[serde(default)] | ||
| 548 | + id: String, | ||
| 549 | + /// The filter the admin was on, so the redirect lands back on it. | ||
| 550 | + #[serde(default)] | ||
| 551 | + state: String, | ||
| 552 | +} | ||
| 553 | + | ||
| 554 | +#[route(POST "/admin/mail/queue/retry")] | ||
| 555 | +async fn queue_retry(cx: &Cx, Form(form): Form<QueueForm>) -> Result<Response> { | ||
| 556 | + queue_action(cx, form, QueueAction::Retry).await | ||
| 557 | +} | ||
| 558 | + | ||
| 559 | +#[route(POST "/admin/mail/queue/discard")] | ||
| 560 | +async fn queue_discard(cx: &Cx, Form(form): Form<QueueForm>) -> Result<Response> { | ||
| 561 | + queue_action(cx, form, QueueAction::Discard).await | ||
| 562 | +} | ||
| 563 | + | ||
| 564 | +/// Retries or discards one failed message. Anything else is refused with a notice and changes | ||
| 565 | +/// nothing. Either way the worker is woken and the queue's watchers are told. | ||
| 566 | +async fn queue_action(cx: &Cx, form: QueueForm, action: QueueAction) -> Result<Response> { | ||
| 567 | + let viewer = admin_only(cx).await?; | ||
| 568 | + if !check_csrf(&viewer.1, &form.csrf) { | ||
| 569 | + return Err(forbidden().into()); | ||
| 570 | + } | ||
| 571 | + let lang = i18n::lang(cx, Some(&viewer.0)); | ||
| 572 | + let state = app_context::<AppState>(cx); | ||
| 573 | + let now = now_stamp(); | ||
| 574 | + let (done, notice) = match action { | ||
| 575 | + QueueAction::Retry => { | ||
| 576 | + let done = state.store.retry_mail(&form.id, &now).await?; | ||
| 577 | + if done { | ||
| 578 | + state.mail_waker.notify_one(); | ||
| 579 | + } | ||
| 580 | + (done, K::MailRetried) | ||
| 581 | + } | ||
| 582 | + QueueAction::Discard => ( | ||
| 583 | + state.store.discard_mail(&form.id, &now).await?, | ||
| 584 | + K::MailDiscarded, | ||
| 585 | + ), | ||
| 586 | + }; | ||
| 587 | + let notice = if done { notice } else { K::MailNotFailed }; | ||
| 588 | + if done { | ||
| 589 | + live::bump(); | ||
| 590 | + } | ||
| 591 | + let filter = MailState::parse(&form.state).map_or_else(String::new, |s| { | ||
| 592 | + format!("&state={}", s.as_str()) | ||
| 593 | + }); | ||
| 594 | + let location = format!( | ||
| 595 | + "/admin/mail?tab=queue{filter}¬ice={}", | ||
| 596 | + enc(g::t(lang, notice)) | ||
| 597 | + ); | ||
| 598 | + Err(see_other(&location).into()) | ||
| 599 | +} | ||
| 600 | + | ||
| 347 | #[cfg(test)] | 601 | #[cfg(test)] |
| 348 | mod tests { | 602 | mod tests { |
| 349 | use super::*; | 603 | use super::*; |
| @@ -585,4 +839,178 @@ mod tests { | |||
| 585 | assert!(body.contains("Bağlantı noktası"), "Turkish port label"); | 839 | assert!(body.contains("Bağlantı noktası"), "Turkish port label"); |
| 586 | assert!(!body.contains("SMTP server"), "no English heading left"); | 840 | assert!(!body.contains("SMTP server"), "no English heading left"); |
| 587 | } | 841 | } |
| 842 | + | ||
| 843 | + fn outgoing(to: &str, subject: &str, body: &str, kind: MailKind) -> forge_core::mail::OutgoingMail { | ||
| 844 | + forge_core::mail::OutgoingMail { | ||
| 845 | + to: to.into(), | ||
| 846 | + subject: subject.into(), | ||
| 847 | + body: body.into(), | ||
| 848 | + message_id: None, | ||
| 849 | + in_reply_to: None, | ||
| 850 | + kind, | ||
| 851 | + user_id: None, | ||
| 852 | + } | ||
| 853 | + } | ||
| 854 | + | ||
| 855 | + #[tokio::test] | ||
| 856 | + async fn the_queue_tab_is_live_filters_by_state_and_never_renders_a_body() { | ||
| 857 | + let fx = fixture().await; | ||
| 858 | + let reset = outgoing( | ||
| 859 | + "a@example.com", | ||
| 860 | + "Reset your password", | ||
| 861 | + "https://forge.test/reset/SECRET-LINK", | ||
| 862 | + MailKind::PasswordReset, | ||
| 863 | + ); | ||
| 864 | + fx.state.store.enqueue_mail("reset:1", &reset).await.expect("queued"); | ||
| 865 | + let later = outgoing("b@example.com", "Queued one", "body", MailKind::Notification); | ||
| 866 | + fx.state.store.enqueue_mail("notif:2", &later).await.expect("queued"); | ||
| 867 | + let failed_id = fx | ||
| 868 | + .state | ||
| 869 | + .store | ||
| 870 | + .recent_mail(10) | ||
| 871 | + .await | ||
| 872 | + .expect("rows") | ||
| 873 | + .into_iter() | ||
| 874 | + .find(|r| r.to_addr == "a@example.com") | ||
| 875 | + .expect("reset row") | ||
| 876 | + .id; | ||
| 877 | + fx.state | ||
| 878 | + .store | ||
| 879 | + .mark_mail_failed(&failed_id, "550 no such user", None) | ||
| 880 | + .await | ||
| 881 | + .expect("failed"); | ||
| 882 | + | ||
| 883 | + let (status, body) = send(&fx.router, "GET", "/admin/mail?tab=queue", Some(ADMIN_TOKEN), None).await; | ||
| 884 | + assert_eq!(status, 200); | ||
| 885 | + assert!(body.contains("data-live=\"/admin/mail/events\""), "the queue is live"); | ||
| 886 | + assert!(body.contains("Reset your password") && body.contains("Queued one")); | ||
| 887 | + assert!(body.contains("550 no such user"), "the last error shows"); | ||
| 888 | + assert!(!body.contains("SECRET-LINK"), "a body is never rendered"); | ||
| 889 | + assert!(body.contains("Retry now") && body.contains("/admin/mail/queue/retry")); | ||
| 890 | + | ||
| 891 | + let (_, failed_only) = send(&fx.router, "GET", "/admin/mail?tab=queue&state=failed", Some(ADMIN_TOKEN), None).await; | ||
| 892 | + assert!(failed_only.contains("Reset your password")); | ||
| 893 | + assert!(!failed_only.contains("Queued one"), "the filter hides queued mail"); | ||
| 894 | + | ||
| 895 | + let (_, settings) = send(&fx.router, "GET", "/admin/mail", Some(ADMIN_TOKEN), None).await; | ||
| 896 | + assert!(!settings.contains("data-live="), "only the queue is live"); | ||
| 897 | + assert!(!settings.contains("Reset your password"), "the queue is on its own tab"); | ||
| 898 | + } | ||
| 899 | + | ||
| 900 | + #[tokio::test] | ||
| 901 | + async fn the_queue_events_and_its_actions_are_admin_only() { | ||
| 902 | + let fx = fixture().await; | ||
| 903 | + for (method, uri) in [ | ||
| 904 | + ("GET", "/admin/mail/events"), | ||
| 905 | + ("POST", "/admin/mail/queue/retry"), | ||
| 906 | + ("POST", "/admin/mail/queue/discard"), | ||
| 907 | + ] { | ||
| 908 | + let (anon, _) = send(&fx.router, method, uri, None, Some(format!("csrf={CSRF}&id=x"))).await; | ||
| 909 | + assert_eq!(anon, 404, "{method} {uri} for anonymous"); | ||
| 910 | + let (user, _) = send(&fx.router, method, uri, Some(USER_TOKEN), Some(format!("csrf={CSRF}&id=x"))).await; | ||
| 911 | + assert_eq!(user, 404, "{method} {uri} for a plain user"); | ||
| 912 | + } | ||
| 913 | + } | ||
| 914 | + | ||
| 915 | + #[tokio::test] | ||
| 916 | + async fn an_admin_gets_the_queue_event_stream() { | ||
| 917 | + let fx = fixture().await; | ||
| 918 | + let request = Request::builder() | ||
| 919 | + .method("GET") | ||
| 920 | + .uri("/admin/mail/events") | ||
| 921 | + .header("cookie", format!("__Host-{SESSION_COOKIE}={ADMIN_TOKEN}")) | ||
| 922 | + .body(Body::empty()) | ||
| 923 | + .expect("request"); | ||
| 924 | + let res = fx.router.handle(request).await; | ||
| 925 | + assert_eq!(res.status().as_u16(), 200); | ||
| 926 | + let kind = res | ||
| 927 | + .headers() | ||
| 928 | + .get("content-type") | ||
| 929 | + .and_then(|v| v.to_str().ok()) | ||
| 930 | + .unwrap_or_default() | ||
| 931 | + .to_owned(); | ||
| 932 | + assert!(kind.starts_with("text/event-stream"), "{kind}"); | ||
| 933 | + } | ||
| 934 | + | ||
| 935 | + #[tokio::test] | ||
| 936 | + async fn an_admin_retries_and_discards_failed_mail_and_nothing_else() { | ||
| 937 | + let fx = fixture().await; | ||
| 938 | + for key in ["k1", "k2"] { | ||
| 939 | + let mail = outgoing("a@example.com", "Hi", "b", MailKind::Notification); | ||
| 940 | + fx.state.store.enqueue_mail(key, &mail).await.expect("queued"); | ||
| 941 | + } | ||
| 942 | + let ids: Vec<String> = fx | ||
| 943 | + .state | ||
| 944 | + .store | ||
| 945 | + .recent_mail(10) | ||
| 946 | + .await | ||
| 947 | + .expect("rows") | ||
| 948 | + .into_iter() | ||
| 949 | + .map(|r| r.id) | ||
| 950 | + .collect(); | ||
| 951 | + for id in &ids { | ||
| 952 | + fx.state.store.mark_mail_failed(id, "550", None).await.expect("failed"); | ||
| 953 | + } | ||
| 954 | + | ||
| 955 | + let (status, _) = send( | ||
| 956 | + &fx.router, | ||
| 957 | + "POST", | ||
| 958 | + "/admin/mail/queue/retry", | ||
| 959 | + Some(ADMIN_TOKEN), | ||
| 960 | + Some(format!("csrf={CSRF}&id={}&state=failed", ids[0])), | ||
| 961 | + ) | ||
| 962 | + .await; | ||
| 963 | + assert_eq!(status, 303); | ||
| 964 | + let now = now_stamp(); | ||
| 965 | + let queued = fx | ||
| 966 | + .state | ||
| 967 | + .store | ||
| 968 | + .list_mail(Some(MailState::Queued), &now, 10) | ||
| 969 | + .await | ||
| 970 | + .expect("queued"); | ||
| 971 | + assert_eq!(queued.len(), 1); | ||
| 972 | + assert_eq!(queued[0].id, ids[0]); | ||
| 973 | + | ||
| 974 | + let (status, _) = send( | ||
| 975 | + &fx.router, | ||
| 976 | + "POST", | ||
| 977 | + "/admin/mail/queue/discard", | ||
| 978 | + Some(ADMIN_TOKEN), | ||
| 979 | + Some(format!("csrf={CSRF}&id={}", ids[1])), | ||
| 980 | + ) | ||
| 981 | + .await; | ||
| 982 | + assert_eq!(status, 303); | ||
| 983 | + let discarded = fx | ||
| 984 | + .state | ||
| 985 | + .store | ||
| 986 | + .list_mail(Some(MailState::Discarded), &now, 10) | ||
| 987 | + .await | ||
| 988 | + .expect("discarded"); | ||
| 989 | + assert_eq!(discarded.len(), 1); | ||
| 990 | + assert_eq!(discarded[0].id, ids[1]); | ||
| 991 | + | ||
| 992 | + // A queued message cannot be retried, and a bad token changes nothing. | ||
| 993 | + let (status, _) = send( | ||
| 994 | + &fx.router, | ||
| 995 | + "POST", | ||
| 996 | + "/admin/mail/queue/retry", | ||
| 997 | + Some(ADMIN_TOKEN), | ||
| 998 | + Some(format!("csrf={CSRF}&id={}", ids[0])), | ||
| 999 | + ) | ||
| 1000 | + .await; | ||
| 1001 | + assert_eq!(status, 303, "refused with a notice, not an error"); | ||
| 1002 | + assert_eq!( | ||
| 1003 | + fx.state.store.list_mail(Some(MailState::Queued), &now, 10).await.expect("queued").len(), | ||
| 1004 | + 1 | ||
| 1005 | + ); | ||
| 1006 | + let (status, _) = send( | ||
| 1007 | + &fx.router, | ||
| 1008 | + "POST", | ||
| 1009 | + "/admin/mail/queue/discard", | ||
| 1010 | + Some(ADMIN_TOKEN), | ||
| 1011 | + Some(format!("csrf=wrong&id={}", ids[0])), | ||
| 1012 | + ) | ||
| 1013 | + .await; | ||
| 1014 | + assert_eq!(status, 403); | ||
| 1015 | + } | ||
| 588 | } | 1016 | } |
crates/forge-web/src/pages/ci_badge.rsmodified+5 -5
| @@ -3,7 +3,7 @@ | |||
| 3 | //! SVG is a flat shields-style image, rendered here with no outside assets. | 3 | //! SVG is a flat shields-style image, rendered here with no outside assets. |
| 4 | //! | 4 | //! |
| 5 | //! The label, the left half, is `?label=` if given, else the job name when `&job=` is given, else | 5 | //! The label, the left half, is `?label=` if given, else the job name when `&job=` is given, else |
| 6 | -//! the `name` of the run's `.forge/ci.toml`, else "ci". | 6 | +//! the `name` of the run's `.forge/ci.toml`, else "build". |
| 7 | //! | 7 | //! |
| 8 | //! Access is the repo's read access: a private repo a viewer cannot read is a 404, like every other | 8 | //! Access is the repo's read access: a private repo a viewer cannot read is a 404, like every other |
| 9 | //! repo page. A repo with no run on the branch still answers 200 with "no status". | 9 | //! repo page. A repo with no run on the branch still answers 200 with "no status". |
| @@ -26,7 +26,7 @@ path_param!(repo); | |||
| 26 | /// Longest label shown, in characters. A longer job name is cut here. | 26 | /// Longest label shown, in characters. A longer job name is cut here. |
| 27 | const MAX_LABEL_CHARS: usize = 64; | 27 | const MAX_LABEL_CHARS: usize = 64; |
| 28 | /// The label when neither `?label=`, a job, nor a workflow name gives one. | 28 | /// The label when neither `?label=`, a job, nor a workflow name gives one. |
| 29 | -const DEFAULT_LABEL: &str = "ci"; | 29 | +const DEFAULT_LABEL: &str = "build"; |
| 30 | /// Height of the badge in pixels. | 30 | /// Height of the badge in pixels. |
| 31 | const HEIGHT: u32 = 20; | 31 | const HEIGHT: u32 = 20; |
| 32 | /// Padding on each side of a text, in pixels. | 32 | /// Padding on each side of a text, in pixels. |
| @@ -297,7 +297,7 @@ mod tests { | |||
| 297 | (BadgeStatus::NoStatus, "#9f9f9f", "no status"), | 297 | (BadgeStatus::NoStatus, "#9f9f9f", "no status"), |
| 298 | ]; | 298 | ]; |
| 299 | for (status, color, word) in cases { | 299 | for (status, color, word) in cases { |
| 300 | - let svg = render_badge("ci", status); | 300 | + let svg = render_badge("build", status); |
| 301 | assert!(svg.contains(&format!("fill=\"{color}\"")), "{word}"); | 301 | assert!(svg.contains(&format!("fill=\"{color}\"")), "{word}"); |
| 302 | assert!(svg.contains(&format!(">{word}</text>")), "{word}"); | 302 | assert!(svg.contains(&format!(">{word}</text>")), "{word}"); |
| 303 | assert!(svg.contains("fill=\"#555\"")); | 303 | assert!(svg.contains("fill=\"#555\"")); |
| @@ -324,10 +324,10 @@ mod tests { | |||
| 324 | #[test] | 324 | #[test] |
| 325 | fn width_grows_with_text() { | 325 | fn width_grows_with_text() { |
| 326 | assert!(text_box("no status") > text_box("ok")); | 326 | assert!(text_box("no status") > text_box("ok")); |
| 327 | - let svg = render_badge("ci", BadgeStatus::Passing); | 327 | + let svg = render_badge("build", BadgeStatus::Passing); |
| 328 | assert!(svg.contains(&format!( | 328 | assert!(svg.contains(&format!( |
| 329 | "width=\"{}\"", | 329 | "width=\"{}\"", |
| 330 | - text_box("ci") + text_box("passing") | 330 | + text_box("build") + text_box("passing") |
| 331 | ))); | 331 | ))); |
| 332 | } | 332 | } |
| 333 | } | 333 | } |
crates/forge-web/src/pages/ci_runs.rsmodified+1163 -578
| @@ -1,23 +1,26 @@ | |||
| 1 | -//! Pages: CI runs (`/{owner}/{repo}/ci` and `/{owner}/{repo}/ci/runs/{number}`). Anyone who can read | 1 | +//! Pages: CI runs (`/{owner}/{repo}/ci` and `/{owner}/{repo}/ci/runs/{number}`). Both render one split |
| 2 | -//! the repo sees its runs, their jobs and the config error of a run. Starting a manual run, cancelling, | 2 | +//! view: the repo's runs on the left, the selected run on the right with its to-scale timeline, its jobs |
| 3 | -//! re-running and approving need Write, and the buttons are shown only to writers. Anyone else gets a | 3 | +//! and the last lines of its log. Anyone who can read the repo sees its runs, their jobs and the config |
| 4 | -//! 404 for a private repo and a refusal for a change. Every change notifies the job waker and syncs | 4 | +//! error of a run. Starting a manual run, cancelling, re-running and approving need Write, and the |
| 5 | -//! the commit status of each job it changed. A run or job page that is not finished stays live: it | 5 | +//! buttons are shown only to writers. Anyone else gets a 404 for a private repo and a refusal for a |
| 6 | -//! opens a `changed` event stream (`.../events`) and re-renders itself on each event, with no reload | 6 | +//! change. Every change notifies the job waker and syncs the commit status of each job it changed. A run |
| 7 | -//! and no timer. The run list stays live on page 1 the same way, through `/{owner}/{repo}/ci/events`, | 7 | +//! or job page that is not finished stays live. The split view is live on page 1 of the list through |
| 8 | -//! which fires on every run created or changed in the repo. | 8 | +//! `/{owner}/{repo}/ci/events`, which fires on every run created or changed in the repo, and a run or job |
| 9 | +//! page opens its own `changed` stream (`.../events`) when it is not finished. | ||
| 9 | 10 | ||
| 10 | use std::collections::HashMap; | 11 | use std::collections::HashMap; |
| 11 | use std::future::Future; | 12 | use std::future::Future; |
| 13 | +use std::path::Path; | ||
| 12 | use std::time::Duration; | 14 | use std::time::Duration; |
| 13 | 15 | ||
| 14 | -use forge_core::ci::{CiJob, CiRun, RunState}; | 16 | +use forge_core::ci::{CiJob, CiRun, JobState, RunState}; |
| 15 | use forge_core::{Action, Denied, Store, User, authorize}; | 17 | use forge_core::{Action, Denied, Store, User, authorize}; |
| 16 | use forge_git::browse::{RefInfo, RefKind, read_commit}; | 18 | use forge_git::browse::{RefInfo, RefKind, read_commit}; |
| 17 | use futures_util::{Stream, stream}; | 19 | use futures_util::{Stream, stream}; |
| 18 | use serde::Deserialize; | 20 | use serde::Deserialize; |
| 19 | use time::OffsetDateTime; | 21 | use time::OffsetDateTime; |
| 20 | use time::format_description::well_known::Rfc3339; | 22 | use time::format_description::well_known::Rfc3339; |
| 23 | +use tokio::io::{AsyncReadExt, AsyncSeekExt, SeekFrom}; | ||
| 21 | use tokio::sync::watch; | 24 | use tokio::sync::watch; |
| 22 | use topcoat::Result; | 25 | use topcoat::Result; |
| 23 | use topcoat::context::{Cx, app_context}; | 26 | use topcoat::context::{Cx, app_context}; |
| @@ -30,6 +33,7 @@ use topcoat::router::{HeaderValue, page, path_param, route}; | |||
| 30 | use topcoat::view::{View, component, view}; | 33 | use topcoat::view::{View, component, view}; |
| 31 | 34 | ||
| 32 | use crate::auth::{current_user, require_csrf}; | 35 | use crate::auth::{current_user, require_csrf}; |
| 36 | +use crate::ci::log_path; | ||
| 33 | use crate::i18n::{ | 37 | use crate::i18n::{ |
| 34 | self, Lang, | 38 | self, Lang, |
| 35 | releases_ci::{self as g, K}, | 39 | releases_ci::{self as g, K}, |
| @@ -38,7 +42,7 @@ use crate::pages::refs::load_refs; | |||
| 38 | use crate::pages::repo::repo_head; | 42 | use crate::pages::repo::repo_head; |
| 39 | use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; | 43 | use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; |
| 40 | use crate::state::AppState; | 44 | use crate::state::AppState; |
| 41 | -use crate::views::{alert, enc, now_unix, relative_time, shell, short_oid}; | 45 | +use crate::views::{alert, enc, human_size, now_unix, relative_time, shell, short_oid}; |
| 42 | 46 | ||
| 43 | path_param!(owner); | 47 | path_param!(owner); |
| 44 | path_param!(repo); | 48 | path_param!(repo); |
| @@ -130,7 +134,7 @@ pub fn job_href(title: &str, job_id: &str) -> String { | |||
| 130 | fn badge_info(state: &AppState, title: &str, default_branch: &str) -> BadgeInfo { | 134 | fn badge_info(state: &AppState, title: &str, default_branch: &str) -> BadgeInfo { |
| 131 | let base = state.config.base_url.trim_end_matches('/'); | 135 | let base = state.config.base_url.trim_end_matches('/'); |
| 132 | let image = format!("/{}/badge.svg?branch={}", enc(title), enc(default_branch)); | 136 | let image = format!("/{}/badge.svg?branch={}", enc(title), enc(default_branch)); |
| 133 | - let snippet = format!("[]({base}{})", ci_href(&enc(title))); | 137 | + let snippet = format!("[]({base}{})", ci_href(&enc(title))); |
| 134 | BadgeInfo { image, snippet } | 138 | BadgeInfo { image, snippet } |
| 135 | } | 139 | } |
| 136 | 140 | ||
| @@ -279,21 +283,14 @@ async fn after_change(state: &AppState, run_id: &str, before: &[CiJob]) -> Resul | |||
| 279 | Ok(()) | 283 | Ok(()) |
| 280 | } | 284 | } |
| 281 | 285 | ||
| 282 | -/// One run in the list, with its values already shown as text. `state_key` is the raw state word | 286 | +/// One run in the list. `bar` is its duration bar on the page's shared scale. |
| 283 | -/// that picks the row's icon. | ||
| 284 | struct RunRow { | 287 | struct RunRow { |
| 285 | href: String, | 288 | href: String, |
| 286 | - number: i64, | 289 | + current: &'static str, |
| 287 | title: String, | 290 | title: String, |
| 288 | - state: String, | 291 | + bar: Vec<Rect>, |
| 289 | - state_key: String, | ||
| 290 | - trigger: String, | ||
| 291 | - branch: String, | ||
| 292 | - commit_href: String, | ||
| 293 | - commit: String, | ||
| 294 | - actor: String, | ||
| 295 | duration: String, | 292 | duration: String, |
| 296 | - when: String, | 293 | + meta: String, |
| 297 | } | 294 | } |
| 298 | 295 | ||
| 299 | /// The run-list form that starts a manual run. | 296 | /// The run-list form that starts a manual run. |
| @@ -309,58 +306,552 @@ struct BadgeInfo { | |||
| 309 | snippet: String, | 306 | snippet: String, |
| 310 | } | 307 | } |
| 311 | 308 | ||
| 312 | -/// A job row on the run page. | 309 | +/// The left column: the header menus, the scale, the rows and the pager. |
| 313 | -struct JobRow { | 310 | +struct ListView { |
| 314 | - href: String, | 311 | + manual: Option<ManualRun>, |
| 315 | - name: String, | 312 | + badge: BadgeInfo, |
| 316 | - state: String, | 313 | + total: u64, |
| 317 | - state_class: String, | 314 | + scale: String, |
| 318 | - duration: String, | 315 | + rows: Vec<RunRow>, |
| 319 | - runner: String, | 316 | + newer_href: Option<String>, |
| 320 | - message: String, | 317 | + older_href: Option<String>, |
| 318 | + page_label: String, | ||
| 321 | } | 319 | } |
| 322 | 320 | ||
| 323 | -/// Layout of the job graph in SVG units. The `.ci-graph-*` rules in main.scss use the same sizes. | 321 | +/// One job line under the timeline. Its link goes to the job page. |
| 324 | -const GRAPH_PAD: i64 = 16; | 322 | +struct JobLine { |
| 325 | -const GRAPH_CARD_W: i64 = 200; | ||
| 326 | -const GRAPH_CARD_H: i64 = 56; | ||
| 327 | -const GRAPH_COL_GAP: i64 = 48; | ||
| 328 | -const GRAPH_ROW_GAP: i64 = 16; | ||
| 329 | - | ||
| 330 | -/// One job card of the graph. `class` is the card's class with its status word. | ||
| 331 | -struct GraphCard { | ||
| 332 | - class: String, | ||
| 333 | href: String, | 323 | href: String, |
| 334 | name: String, | 324 | name: String, |
| 335 | - state: String, | 325 | + dot: String, |
| 326 | + /// The image and the artifacts with their sizes, joined with a middle dot. | ||
| 327 | + detail: String, | ||
| 328 | + runner: String, | ||
| 336 | duration: String, | 329 | duration: String, |
| 337 | } | 330 | } |
| 338 | 331 | ||
| 339 | -/// The job graph of a run: the cards by stage column, and the connector paths between them. | 332 | +/// The last lines of the log of the job the run page points at. |
| 340 | -struct JobGraph { | 333 | +struct LogBlock { |
| 341 | - width: String, | 334 | + caption: String, |
| 342 | - height: String, | 335 | + text: String, |
| 343 | - columns: Vec<Vec<GraphCard>>, | ||
| 344 | - paths: Vec<String>, | ||
| 345 | } | 336 | } |
| 346 | 337 | ||
| 347 | -/// The run page's header values. | 338 | +/// The right column: the selected run, its timeline, its jobs and the log tail. |
| 348 | -struct RunView { | 339 | +struct RunDetail { |
| 349 | number: i64, | 340 | number: i64, |
| 350 | title: String, | 341 | title: String, |
| 351 | - commit_href: String, | ||
| 352 | - duration: String, | ||
| 353 | state: String, | 342 | state: String, |
| 354 | state_class: String, | 343 | state_class: String, |
| 355 | trigger: String, | 344 | trigger: String, |
| 356 | - git_ref: String, | 345 | + branch: String, |
| 346 | + commit_href: String, | ||
| 357 | commit: String, | 347 | commit: String, |
| 358 | actor: String, | 348 | actor: String, |
| 359 | when: String, | 349 | when: String, |
| 350 | + duration: String, | ||
| 360 | config_error: Option<String>, | 351 | config_error: Option<String>, |
| 361 | action_base: String, | 352 | action_base: String, |
| 362 | can_approve: bool, | 353 | can_approve: bool, |
| 363 | can_cancel: bool, | 354 | can_cancel: bool, |
| 355 | + writer_csrf: Option<String>, | ||
| 356 | + gantt: Option<Gantt>, | ||
| 357 | + jobs: Vec<JobLine>, | ||
| 358 | + log: Option<LogBlock>, | ||
| 359 | +} | ||
| 360 | + | ||
| 361 | +/// A box in an SVG, with its class and its position and size in the SVG's units. | ||
| 362 | +struct Rect { | ||
| 363 | + class: String, | ||
| 364 | + x: String, | ||
| 365 | + y: String, | ||
| 366 | + w: String, | ||
| 367 | + h: String, | ||
| 368 | +} | ||
| 369 | + | ||
| 370 | +impl Rect { | ||
| 371 | + fn new(class: impl Into<String>, x: i64, y: i64, w: i64, h: i64) -> Rect { | ||
| 372 | + Rect { | ||
| 373 | + class: class.into(), | ||
| 374 | + x: x.to_string(), | ||
| 375 | + y: y.to_string(), | ||
| 376 | + w: w.to_string(), | ||
| 377 | + h: h.to_string(), | ||
| 378 | + } | ||
| 379 | + } | ||
| 380 | +} | ||
| 381 | + | ||
| 382 | +/// A text label of the timeline. | ||
| 383 | +struct Label { | ||
| 384 | + class: &'static str, | ||
| 385 | + x: String, | ||
| 386 | + y: String, | ||
| 387 | + anchor: &'static str, | ||
| 388 | + text: String, | ||
| 389 | +} | ||
| 390 | + | ||
| 391 | +/// The timeline of a run: its SVG viewBox, its boxes, its connectors and its labels, in draw order. | ||
| 392 | +struct Gantt { | ||
| 393 | + view_box: String, | ||
| 394 | + rects: Vec<Rect>, | ||
| 395 | + links: Vec<String>, | ||
| 396 | + labels: Vec<Label>, | ||
| 397 | +} | ||
| 398 | + | ||
| 399 | +/// What the lists and the timeline need of one job: its times in unix seconds and the words it shows. | ||
| 400 | +struct Timing { | ||
| 401 | + id: String, | ||
| 402 | + name: String, | ||
| 403 | + state: JobState, | ||
| 404 | + needs: Vec<String>, | ||
| 405 | + image: String, | ||
| 406 | + runner: String, | ||
| 407 | + duration: String, | ||
| 408 | + message: String, | ||
| 409 | + queued: Option<i64>, | ||
| 410 | + started: Option<i64>, | ||
| 411 | + finished: Option<i64>, | ||
| 412 | +} | ||
| 413 | + | ||
| 414 | +impl Timing { | ||
| 415 | + /// Where the job ends, in unix seconds: its finish, or `now` while it runs. None before it starts. | ||
| 416 | + fn end(&self, now: i64) -> Option<i64> { | ||
| 417 | + self.started?; | ||
| 418 | + Some(self.finished.unwrap_or(now)) | ||
| 419 | + } | ||
| 420 | +} | ||
| 421 | + | ||
| 422 | +/// The parts of a job spec the pages use. A spec that does not read gives neither. | ||
| 423 | +#[derive(Deserialize, Default)] | ||
| 424 | +#[serde(default)] | ||
| 425 | +struct SpecFacts { | ||
| 426 | + image: String, | ||
| 427 | + needs: Vec<String>, | ||
| 428 | +} | ||
| 429 | + | ||
| 430 | +/// The width of a list bar in its viewBox. The bar is drawn with `preserveAspectRatio="none"`, so any | ||
| 431 | +/// width on the page works. | ||
| 432 | +const LIST_BAR_W: i64 = 1000; | ||
| 433 | +/// Timeline layout in SVG units. The labels take the first 100 units and the track the next 530. The | ||
| 434 | +/// `.ci-gantt` rules in main.scss use the same sizes. | ||
| 435 | +const GANTT_W: i64 = 640; | ||
| 436 | +const TRACK_X: i64 = 100; | ||
| 437 | +const TRACK_W: i64 = 530; | ||
| 438 | +const AXIS_H: i64 = 24; | ||
| 439 | +const ROW_H: i64 = 40; | ||
| 440 | +const BAR_DY: i64 = 9; | ||
| 441 | +const BAR_H: i64 = 22; | ||
| 442 | +/// The narrowest a box is drawn, so a short lead-in or job still shows. | ||
| 443 | +const MIN_BOX_W: i64 = 3; | ||
| 444 | +/// The most intervals an axis has, so its ticks stay readable. | ||
| 445 | +const MAX_INTERVALS: i64 = 5; | ||
| 446 | +/// The steps an axis can take, in seconds: one minute up to two days. | ||
| 447 | +const AXIS_STEPS: [i64; 14] = [ | ||
| 448 | + 60, 120, 300, 600, 900, 1200, 1800, 3600, 7200, 14400, 21600, 43200, 86400, 172800, | ||
| 449 | +]; | ||
| 450 | +/// How far back from the end of a log the run page reads for its last lines. | ||
| 451 | +const LOG_TAIL_BYTES: u64 = 8 * 1024; | ||
| 452 | +/// Lines of a log the run page shows. | ||
| 453 | +const LOG_LINES: usize = 3; | ||
| 454 | + | ||
| 455 | +/// Where an offset of `offset` seconds falls on a span of `span` seconds drawn `width` units wide. | ||
| 456 | +/// The offset is clamped to the span, so nothing is drawn past its end. | ||
| 457 | +fn place(offset: i64, span: i64, width: i64) -> i64 { | ||
| 458 | + if span <= 0 { | ||
| 459 | + return 0; | ||
| 460 | + } | ||
| 461 | + (offset.clamp(0, span) * width + span / 2) / span | ||
| 462 | +} | ||
| 463 | + | ||
| 464 | +/// The shared scale of a list page: its longest run in seconds, and at least one second. | ||
| 465 | +fn bar_scale(spans: &[i64]) -> i64 { | ||
| 466 | + spans.iter().copied().max().unwrap_or(0).max(1) | ||
| 467 | +} | ||
| 468 | + | ||
| 469 | +/// The axis of a timeline for a run of `total` seconds: the step between ticks, and the length of the | ||
| 470 | +/// axis, a whole number of steps. The step is the smallest one that keeps the axis to `MAX_INTERVALS`. | ||
| 471 | +fn axis(total: i64) -> (i64, i64) { | ||
| 472 | + let total = total.max(1); | ||
| 473 | + let step = AXIS_STEPS | ||
| 474 | + .iter() | ||
| 475 | + .copied() | ||
| 476 | + .find(|step| (total + step - 1) / step <= MAX_INTERVALS) | ||
| 477 | + .unwrap_or(AXIS_STEPS[AXIS_STEPS.len() - 1]); | ||
| 478 | + (step, (total + step - 1) / step * step) | ||
| 479 | +} | ||
| 480 | + | ||
| 481 | +/// A tick label of the axis: "0", "20m", "1h" or "1h 20m". | ||
| 482 | +fn tick_label(secs: i64) -> String { | ||
| 483 | + match (secs / 3600, secs % 3600 / 60) { | ||
| 484 | + (0, 0) => "0".to_owned(), | ||
| 485 | + (0, minutes) => format!("{minutes}m"), | ||
| 486 | + (hours, 0) => format!("{hours}h"), | ||
| 487 | + (hours, minutes) => format!("{hours}h {minutes}m"), | ||
| 488 | + } | ||
| 489 | +} | ||
| 490 | + | ||
| 491 | +/// A span of `secs` for the scale line: seconds under a minute, then minutes and hours as on the axis. | ||
| 492 | +fn span_text(secs: i64) -> String { | ||
| 493 | + if secs < 60 { | ||
| 494 | + format!("{secs}s") | ||
| 495 | + } else if secs % 60 != 0 && secs < 3600 { | ||
| 496 | + format!("{}m {}s", secs / 60, secs % 60) | ||
| 497 | + } else { | ||
| 498 | + tick_label((secs + 59) / 60 * 60) | ||
| 499 | + } | ||
| 500 | +} | ||
| 501 | + | ||
| 502 | +/// The first text that fits a bar of `width` units. A character takes 7 units and the bar keeps 12 | ||
| 503 | +/// units of padding. | ||
| 504 | +fn bar_text(width: i64, candidates: &[String]) -> Option<String> { | ||
| 505 | + candidates | ||
| 506 | + .iter() | ||
| 507 | + .find(|text| text.chars().count() as i64 * 7 + 12 <= width) | ||
| 508 | + .cloned() | ||
| 509 | +} | ||
| 510 | + | ||
| 511 | +/// The image of a job without its registry path: `rust:1` for `docker.io/library/rust:1`. | ||
| 512 | +fn image_short(image: &str) -> &str { | ||
| 513 | + image.rsplit('/').next().unwrap_or(image) | ||
| 514 | +} | ||
| 515 | + | ||
| 516 | +/// The colour class of a job's box, by its state. | ||
| 517 | +fn tone(state: JobState) -> &'static str { | ||
| 518 | + match state { | ||
| 519 | + JobState::Success => "ci-ok", | ||
| 520 | + JobState::Failure | JobState::Error => "ci-bad", | ||
| 521 | + JobState::Running => "ci-run", | ||
| 522 | + _ => "ci-muted", | ||
| 523 | + } | ||
| 524 | +} | ||
| 525 | + | ||
| 526 | +/// When a run started, in unix seconds. A stamp that does not read counts as now. | ||
| 527 | +fn origin_of(run: &CiRun, now: i64) -> i64 { | ||
| 528 | + unix_of(&run.created_at).unwrap_or(now) | ||
| 529 | +} | ||
| 530 | + | ||
| 531 | +/// When a run ended: its finish, or now while it runs. None before either. | ||
| 532 | +fn run_end(run: &CiRun, now: i64) -> Option<i64> { | ||
| 533 | + match run.finished_at.as_deref().and_then(unix_of) { | ||
| 534 | + Some(end) => Some(end), | ||
| 535 | + None => (run.state == RunState::Running).then_some(now), | ||
| 536 | + } | ||
| 537 | +} | ||
| 538 | + | ||
| 539 | +/// A run's duration in seconds, from its start to its end. Zero for a run that has not ended. | ||
| 540 | +fn run_span(run: &CiRun, now: i64) -> i64 { | ||
| 541 | + run_end(run, now).map_or(0, |end| (end - origin_of(run, now)).max(0)) | ||
| 542 | +} | ||
| 543 | + | ||
| 544 | +/// The duration bar of a list row: a segment for each job that started, in its state's colour, on the | ||
| 545 | +/// scale the page shares. A running run also gets a hatched remainder up to the scale. | ||
| 546 | +fn row_bar(jobs: &[Timing], origin: i64, scale: i64, now: i64, running: bool) -> Vec<Rect> { | ||
| 547 | + let mut bar = Vec::new(); | ||
| 548 | + for job in jobs { | ||
| 549 | + let (Some(start), Some(end)) = (job.started, job.end(now)) else { | ||
| 550 | + continue; | ||
| 551 | + }; | ||
| 552 | + let x = place(start - origin, scale, LIST_BAR_W); | ||
| 553 | + let to = place(end - origin, scale, LIST_BAR_W); | ||
| 554 | + bar.push(Rect::new( | ||
| 555 | + format!("ci-seg {}", tone(job.state)), | ||
| 556 | + x, | ||
| 557 | + 0, | ||
| 558 | + (to - x).max(2), | ||
| 559 | + 6, | ||
| 560 | + )); | ||
| 561 | + } | ||
| 562 | + if running { | ||
| 563 | + let x = place(now - origin, scale, LIST_BAR_W); | ||
| 564 | + bar.push(Rect::new("ci-seg ci-rest", x, 0, LIST_BAR_W - x, 6)); | ||
| 565 | + } | ||
| 566 | + bar | ||
| 567 | +} | ||
| 568 | + | ||
| 569 | +/// The line under a job's name in the timeline: its queueing lead-in when it had one, else what it | ||
| 570 | +/// needs. | ||
| 571 | +fn row_sub(job: &Timing, lang: Lang) -> Option<String> { | ||
| 572 | + if let (Some(queued), Some(start)) = (job.queued, job.started) | ||
| 573 | + && queued < start | ||
| 574 | + { | ||
| 575 | + return Some(format!( | ||
| 576 | + "{} {}", | ||
| 577 | + state_text(lang, "queued"), | ||
| 578 | + g::duration_seconds(lang, start - queued) | ||
| 579 | + )); | ||
| 580 | + } | ||
| 581 | + (!job.needs.is_empty()).then(|| g::needs_label(lang, &job.needs.join(", "))) | ||
| 582 | +} | ||
| 583 | + | ||
| 584 | +/// The timeline of a run, to scale: an axis of round ticks from the run's start, one row per job with | ||
| 585 | +/// its box at its real start and end, a hatched lead-in from its queueing, and a dashed connector from | ||
| 586 | +/// each needed job's end to the start of the job that needs it. A blocked job is an outline from its | ||
| 587 | +/// needs' end, and a skipped or cancelled one is an outline across the track. | ||
| 588 | +fn gantt(jobs: &[Timing], origin: i64, run_end: Option<i64>, now: i64, lang: Lang) -> Gantt { | ||
| 589 | + let last = jobs | ||
| 590 | + .iter() | ||
| 591 | + .filter_map(|job| job.end(now)) | ||
| 592 | + .chain(run_end) | ||
| 593 | + .max() | ||
| 594 | + .unwrap_or(now); | ||
| 595 | + let (step, len) = axis((last - origin).max(1)); | ||
| 596 | + let x = |at: i64| TRACK_X + place(at - origin, len, TRACK_W); | ||
| 597 | + let row_mid = |i: usize| AXIS_H + i as i64 * ROW_H + ROW_H / 2; | ||
| 598 | + let track_end = TRACK_X + TRACK_W; | ||
| 599 | + let height = AXIS_H + jobs.len() as i64 * ROW_H; | ||
| 600 | + let mut g = Gantt { | ||
| 601 | + view_box: format!("0 0 {GANTT_W} {height}"), | ||
| 602 | + rects: Vec::new(), | ||
| 603 | + links: Vec::new(), | ||
| 604 | + labels: Vec::new(), | ||
| 605 | + }; | ||
| 606 | + for k in 0..=len / step { | ||
| 607 | + let at = k * step; | ||
| 608 | + let gx = TRACK_X + place(at, len, TRACK_W); | ||
| 609 | + g.rects | ||
| 610 | + .push(Rect::new("ci-grid", gx, AXIS_H, 1, height - AXIS_H)); | ||
| 611 | + let anchor = match at { | ||
| 612 | + 0 => "start", | ||
| 613 | + _ if at == len => "end", | ||
| 614 | + _ => "middle", | ||
| 615 | + }; | ||
| 616 | + g.labels.push(Label { | ||
| 617 | + class: "ci-tick", | ||
| 618 | + x: gx.to_string(), | ||
| 619 | + y: (AXIS_H - 8).to_string(), | ||
| 620 | + anchor, | ||
| 621 | + text: tick_label(at), | ||
| 622 | + }); | ||
| 623 | + } | ||
| 624 | + for (i, job) in jobs.iter().enumerate() { | ||
| 625 | + let top = AXIS_H + i as i64 * ROW_H; | ||
| 626 | + let bar_y = top + BAR_DY; | ||
| 627 | + let label_y = (bar_y + BAR_H / 2 + 4).to_string(); | ||
| 628 | + g.labels.push(Label { | ||
| 629 | + class: "ci-gname", | ||
| 630 | + x: "0".to_owned(), | ||
| 631 | + y: (row_mid(i) - 3).to_string(), | ||
| 632 | + anchor: "start", | ||
| 633 | + text: job.name.clone(), | ||
| 634 | + }); | ||
| 635 | + if let Some(sub) = row_sub(job, lang) { | ||
| 636 | + g.labels.push(Label { | ||
| 637 | + class: "ci-gsub", | ||
| 638 | + x: "0".to_owned(), | ||
| 639 | + y: (row_mid(i) + 11).to_string(), | ||
| 640 | + anchor: "start", | ||
| 641 | + text: sub, | ||
| 642 | + }); | ||
| 643 | + } | ||
| 644 | + match (job.started, job.end(now)) { | ||
| 645 | + (Some(start), Some(end)) => { | ||
| 646 | + let left = x(start); | ||
| 647 | + if let Some(queued) = job.queued.filter(|queued| *queued < start) { | ||
| 648 | + let from = x(queued); | ||
| 649 | + g.rects.push(Rect::new( | ||
| 650 | + "ci-glead", | ||
| 651 | + from, | ||
| 652 | + bar_y, | ||
| 653 | + (left - from).max(MIN_BOX_W), | ||
| 654 | + BAR_H, | ||
| 655 | + )); | ||
| 656 | + } | ||
| 657 | + let width = (x(end) - left).max(MIN_BOX_W); | ||
| 658 | + g.rects.push(Rect::new( | ||
| 659 | + format!("ci-gbar {}", tone(job.state)), | ||
| 660 | + left, | ||
| 661 | + bar_y, | ||
| 662 | + width, | ||
| 663 | + BAR_H, | ||
| 664 | + )); | ||
| 665 | + if job.state == JobState::Running { | ||
| 666 | + g.rects | ||
| 667 | + .push(Rect::new("ci-gedge", left + width - 3, bar_y, 3, BAR_H)); | ||
| 668 | + } | ||
| 669 | + let candidates = [ | ||
| 670 | + format!("{} \u{b7} {} \u{b7} {}", job.name, job.duration, job.runner), | ||
| 671 | + format!("{} \u{b7} {}", job.name, job.duration), | ||
| 672 | + job.duration.clone(), | ||
| 673 | + ]; | ||
| 674 | + if let Some(text) = bar_text(width, &candidates) { | ||
| 675 | + g.labels.push(Label { | ||
| 676 | + class: if tone(job.state) == "ci-muted" { | ||
| 677 | + "ci-goff" | ||
| 678 | + } else { | ||
| 679 | + "ci-gon" | ||
| 680 | + }, | ||
| 681 | + x: (left + 8).to_string(), | ||
| 682 | + y: label_y, | ||
| 683 | + anchor: "start", | ||
| 684 | + text, | ||
| 685 | + }); | ||
| 686 | + } | ||
| 687 | + } | ||
| 688 | + _ => match job.state { | ||
| 689 | + JobState::Queued => { | ||
| 690 | + if let Some(queued) = job.queued { | ||
| 691 | + let from = x(queued); | ||
| 692 | + let width = (x(now) - from).max(MIN_BOX_W); | ||
| 693 | + g.rects | ||
| 694 | + .push(Rect::new("ci-glead", from, bar_y, width, BAR_H)); | ||
| 695 | + } | ||
| 696 | + } | ||
| 697 | + JobState::Blocked => { | ||
| 698 | + let from = job | ||
| 699 | + .needs | ||
| 700 | + .iter() | ||
| 701 | + .filter_map(|need| { | ||
| 702 | + jobs.iter() | ||
| 703 | + .find(|other| other.name == *need) | ||
| 704 | + .and_then(|other| other.end(now)) | ||
| 705 | + }) | ||
| 706 | + .max() | ||
| 707 | + .unwrap_or(origin); | ||
| 708 | + let left = x(from); | ||
| 709 | + g.rects.push(Rect::new( | ||
| 710 | + "ci-gbar ci-wait", | ||
| 711 | + left, | ||
| 712 | + bar_y, | ||
| 713 | + track_end - left, | ||
| 714 | + BAR_H, | ||
| 715 | + )); | ||
| 716 | + g.labels.push(Label { | ||
| 717 | + class: "ci-goff", | ||
| 718 | + x: (left + 8).to_string(), | ||
| 719 | + y: label_y, | ||
| 720 | + anchor: "start", | ||
| 721 | + text: g::t(lang, K::Waiting).to_owned(), | ||
| 722 | + }); | ||
| 723 | + } | ||
| 724 | + JobState::Skipped | JobState::Cancelled => { | ||
| 725 | + g.rects.push(Rect::new( | ||
| 726 | + "ci-gbar ci-wait", | ||
| 727 | + TRACK_X, | ||
| 728 | + bar_y, | ||
| 729 | + TRACK_W, | ||
| 730 | + BAR_H, | ||
| 731 | + )); | ||
| 732 | + g.labels.push(Label { | ||
| 733 | + class: "ci-goff", | ||
| 734 | + x: (TRACK_X + 8).to_string(), | ||
| 735 | + y: label_y, | ||
| 736 | + anchor: "start", | ||
| 737 | + text: state_text(lang, job.state.as_str()), | ||
| 738 | + }); | ||
| 739 | + } | ||
| 740 | + _ => {} | ||
| 741 | + }, | ||
| 742 | + } | ||
| 743 | + } | ||
| 744 | + for (i, job) in jobs.iter().enumerate() { | ||
| 745 | + let Some(start) = job.started else { | ||
| 746 | + continue; | ||
| 747 | + }; | ||
| 748 | + for need in &job.needs { | ||
| 749 | + let Some(j) = jobs.iter().position(|other| other.name == *need) else { | ||
| 750 | + continue; | ||
| 751 | + }; | ||
| 752 | + let Some(end) = jobs[j].end(now) else { | ||
| 753 | + continue; | ||
| 754 | + }; | ||
| 755 | + g.links.push(format!( | ||
| 756 | + "M{} {} H{} V{}", | ||
| 757 | + x(end), | ||
| 758 | + row_mid(j), | ||
| 759 | + x(start), | ||
| 760 | + row_mid(i) | ||
| 761 | + )); | ||
| 762 | + } | ||
| 763 | + } | ||
| 764 | + g | ||
| 765 | +} | ||
| 766 | + | ||
| 767 | +/// The timings of a run's jobs, in job order, with runner names from `runners`. | ||
| 768 | +async fn timings_of( | ||
| 769 | + state: &AppState, | ||
| 770 | + run_id: &str, | ||
| 771 | + runners: &HashMap<String, String>, | ||
| 772 | + lang: Lang, | ||
| 773 | +) -> Result<Vec<Timing>> { | ||
| 774 | + let jobs = state.store.jobs_for_run(run_id).await?; | ||
| 775 | + Ok(jobs | ||
| 776 | + .iter() | ||
| 777 | + .map(|job| { | ||
| 778 | + let runner = job | ||
| 779 | + .runner_id | ||
| 780 | + .as_ref() | ||
| 781 | + .and_then(|id| runners.get(id)) | ||
| 782 | + .cloned() | ||
| 783 | + .unwrap_or_default(); | ||
| 784 | + timing_of(job, runner, lang) | ||
| 785 | + }) | ||
| 786 | + .collect()) | ||
| 787 | +} | ||
| 788 | + | ||
| 789 | +/// The timing of one job, with its image and needs read from its spec. | ||
| 790 | +fn timing_of(job: &CiJob, runner: String, lang: Lang) -> Timing { | ||
| 791 | + let spec: SpecFacts = serde_json::from_str(&job.spec_json).unwrap_or_default(); | ||
| 792 | + Timing { | ||
| 793 | + id: job.id.clone(), | ||
| 794 | + name: job.name.clone(), | ||
| 795 | + state: job.state, | ||
| 796 | + needs: spec.needs, | ||
| 797 | + image: image_short(&spec.image).to_owned(), | ||
| 798 | + runner, | ||
| 799 | + duration: duration_text(lang, job.started_at.as_deref(), job.finished_at.as_deref()), | ||
| 800 | + message: job.message.clone().unwrap_or_default(), | ||
| 801 | + queued: job.queued_at.as_deref().and_then(unix_of), | ||
| 802 | + started: job.started_at.as_deref().and_then(unix_of), | ||
| 803 | + finished: job.finished_at.as_deref().and_then(unix_of), | ||
| 804 | + } | ||
| 805 | +} | ||
| 806 | + | ||
| 807 | +/// "test OOM" for a failed run: the first failed job's message, or its name and state. | ||
| 808 | +fn row_meta(run: &CiRun, jobs: &[Timing], actor: &str, lang: Lang) -> String { | ||
| 809 | + let mut meta = format!( | ||
| 810 | + "#{} \u{b7} {}", | ||
| 811 | + run.number, | ||
| 812 | + short_oid(&run.commit_oid) | ||
| 813 | + ); | ||
| 814 | + if !actor.is_empty() { | ||
| 815 | + meta.push_str(&format!(" \u{b7} {actor}")); | ||
| 816 | + } | ||
| 817 | + meta.push_str(&format!(" \u{b7} {}", age_text(lang, &run.created_at))); | ||
| 818 | + if let Some(job) = jobs | ||
| 819 | + .iter() | ||
| 820 | + .find(|job| matches!(job.state, JobState::Failure | JobState::Error)) | ||
| 821 | + { | ||
| 822 | + let hint = if job.message.is_empty() { | ||
| 823 | + format!("{} {}", job.name, state_text(lang, job.state.as_str())) | ||
| 824 | + } else { | ||
| 825 | + job.message.clone() | ||
| 826 | + }; | ||
| 827 | + meta.push_str(&format!(" \u{b7} {hint}")); | ||
| 828 | + } | ||
| 829 | + meta | ||
| 830 | +} | ||
| 831 | + | ||
| 832 | +/// The last lines of a log, read from its tail only. A log that cannot be read has none. | ||
| 833 | +async fn log_last_lines(path: &Path) -> Vec<String> { | ||
| 834 | + let Ok(mut file) = tokio::fs::File::open(path).await else { | ||
| 835 | + return Vec::new(); | ||
| 836 | + }; | ||
| 837 | + let Ok(len) = file.metadata().await.map(|meta| meta.len()) else { | ||
| 838 | + return Vec::new(); | ||
| 839 | + }; | ||
| 840 | + let start = len.saturating_sub(LOG_TAIL_BYTES); | ||
| 841 | + let mut buf = Vec::new(); | ||
| 842 | + if file.seek(SeekFrom::Start(start)).await.is_err() | ||
| 843 | + || file.read_to_end(&mut buf).await.is_err() | ||
| 844 | + { | ||
| 845 | + return Vec::new(); | ||
| 846 | + } | ||
| 847 | + let text = String::from_utf8_lossy(&buf); | ||
| 848 | + let mut lines: Vec<&str> = text.lines().collect(); | ||
| 849 | + // The first line of a tail that starts mid-file may be cut short. | ||
| 850 | + if start > 0 && !lines.is_empty() { | ||
| 851 | + lines.remove(0); | ||
| 852 | + } | ||
| 853 | + let skip = lines.len().saturating_sub(LOG_LINES); | ||
| 854 | + lines[skip..].iter().map(|line| (*line).to_owned()).collect() | ||
| 364 | } | 855 | } |
| 365 | 856 | ||
| 366 | /// Maps each user id in `ids` to a display name. A user that no longer exists shows as "deleted user". | 857 | /// Maps each user id in `ids` to a display name. A user that no longer exists shows as "deleted user". |
| @@ -394,40 +885,307 @@ async fn action_button(action: String, csrf: String, label: &'static str) -> Res | |||
| 394 | }) | 885 | }) |
| 395 | } | 886 | } |
| 396 | 887 | ||
| 397 | -/// The state icon of a run row, labelled with its state word. Finished runs get a disc with a glyph. | 888 | +/// What the runs pages draw: the repo context and the values of the split view. Owned, so each page |
| 398 | -/// Running and queued runs have no glyph: their ring is drawn in CSS, and the running ring turns. | 889 | +/// function can render it with `view!`. |
| 399 | -#[component] | 890 | +struct SplitPage { |
| 400 | -async fn run_icon(state: String, label: String) -> Result<impl View> { | 891 | + ctx: RepoCtx, |
| 401 | - let class = format!("ci-run-icon ci-{state}"); | 892 | + head: RepoHead, |
| 402 | - Ok(view! { | 893 | + lang: Lang, |
| 403 | - <span class=(class.as_str()) role="img" aria-label=(label.as_str()) title=(label.as_str())> | 894 | + notice: Option<(&'static str, bool)>, |
| 404 | - if state == "success" { | 895 | + live: Option<String>, |
| 405 | - <svg viewBox="0 0 16 16" aria-hidden="true"><path d="M4.5 8.5l2.4 2.4 4.6-5"/></svg> | 896 | + page_title: String, |
| 406 | - } else if state == "failure" || state == "error" { | 897 | + list: ListView, |
| 407 | - <svg viewBox="0 0 16 16" aria-hidden="true"><path d="M5.5 5.5l5 5M10.5 5.5l-5 5"/></svg> | 898 | + detail: Option<RunDetail>, |
| 408 | - } else if state == "cancelled" || state == "blocked" || state == "skipped" { | 899 | +} |
| 409 | - <svg viewBox="0 0 16 16" aria-hidden="true"><path d="M5 11l6-6"/></svg> | 900 | + |
| 901 | +/// The split view of the runs: the list (left) and the selected run (right). Both routes render it. | ||
| 902 | +/// `number` is the run the URL names. Without one, the newest run of the list page is selected. | ||
| 903 | +/// The list is live on page 1 only, since a new run can appear there at any time. | ||
| 904 | +async fn runs_split(cx: &Cx, number: Option<&str>) -> Result<SplitPage> { | ||
| 905 | + let owner = path_param::<Owner>(cx); | ||
| 906 | + let name = path_param::<Repo>(cx); | ||
| 907 | + let ctx = load_repo(cx, owner, name).await?; | ||
| 908 | + let lang = i18n::lang(cx, viewer_user(&ctx)); | ||
| 909 | + let state = app_context::<AppState>(cx); | ||
| 910 | + let title = title_of(&ctx); | ||
| 911 | + let base = ci_href(&title); | ||
| 912 | + let page = page_from_query(cx); | ||
| 913 | + let (runs, total) = state.store.list_runs(&ctx.repo.id, page, PER_PAGE).await?; | ||
| 914 | + let selected = match number { | ||
| 915 | + Some(number) => Some(run_of(state, &ctx, number).await?), | ||
| 916 | + None => runs.first().cloned(), | ||
| 917 | + }; | ||
| 918 | + let now = now_unix(); | ||
| 919 | + let runners: HashMap<String, String> = state | ||
| 920 | + .store | ||
| 921 | + .list_runners() | ||
| 922 | + .await? | ||
| 923 | + .into_iter() | ||
| 924 | + .map(|runner| (runner.id, runner.name)) | ||
| 925 | + .collect(); | ||
| 926 | + let names = usernames( | ||
| 927 | + state, | ||
| 928 | + lang, | ||
| 929 | + runs.iter().chain(selected.iter()).map(|run| run.actor_id.as_str()), | ||
| 930 | + ) | ||
| 931 | + .await?; | ||
| 932 | + // Commit subjects are the run titles. A commit that cannot be read leaves the trigger as the title. | ||
| 933 | + let path = ctx.path.clone(); | ||
| 934 | + let oids: Vec<String> = runs | ||
| 935 | + .iter() | ||
| 936 | + .chain(selected.iter()) | ||
| 937 | + .map(|run| run.commit_oid.clone()) | ||
| 938 | + .collect(); | ||
| 939 | + let subjects: HashMap<String, String> = tokio::task::spawn_blocking(move || { | ||
| 940 | + oids.into_iter() | ||
| 941 | + .filter_map(|oid| { | ||
| 942 | + let subject = read_commit(&path, &oid) | ||
| 943 | + .ok() | ||
| 944 | + .flatten() | ||
| 945 | + .map(|commit| commit.summary) | ||
| 946 | + .filter(|summary| !summary.is_empty())?; | ||
| 947 | + Some((oid, subject)) | ||
| 948 | + }) | ||
| 949 | + .collect() | ||
| 950 | + }) | ||
| 951 | + .await?; | ||
| 952 | + let mut timings = Vec::with_capacity(runs.len()); | ||
| 953 | + for run in runs.iter() { | ||
| 954 | + timings.push(timings_of(state, &run.id, &runners, lang).await?); | ||
| 955 | + } | ||
| 956 | + let spans: Vec<i64> = runs.iter().map(|run| run_span(run, now)).collect(); | ||
| 957 | + let scale = bar_scale(&spans); | ||
| 958 | + let row_href = |number: i64| { | ||
| 959 | + if page > 1 { | ||
| 960 | + format!("{}?page={page}", run_href(&title, number)) | ||
| 961 | + } else { | ||
| 962 | + run_href(&title, number) | ||
| 963 | + } | ||
| 964 | + }; | ||
| 965 | + let rows: Vec<RunRow> = runs | ||
| 966 | + .iter() | ||
| 967 | + .zip(&timings) | ||
| 968 | + .map(|(run, jobs)| { | ||
| 969 | + let actor = names.get(&run.actor_id).cloned().unwrap_or_default(); | ||
| 970 | + RunRow { | ||
| 971 | + href: row_href(run.number), | ||
| 972 | + current: if selected.as_ref().is_some_and(|sel| sel.id == run.id) { | ||
| 973 | + "true" | ||
| 974 | + } else { | ||
| 975 | + "false" | ||
| 976 | + }, | ||
| 977 | + title: subjects | ||
| 978 | + .get(&run.commit_oid) | ||
| 979 | + .cloned() | ||
| 980 | + .unwrap_or_else(|| run.trigger.clone()), | ||
| 981 | + bar: row_bar( | ||
| 982 | + jobs, | ||
| 983 | + origin_of(run, now), | ||
| 984 | + scale, | ||
| 985 | + now, | ||
| 986 | + run.state == RunState::Running, | ||
| 987 | + ), | ||
| 988 | + // Only a run that has started or finished has a duration. A queued run has none yet. | ||
| 989 | + duration: if run_finished(&run.state) || run.state == RunState::Running { | ||
| 990 | + duration_text( | ||
| 991 | + lang, | ||
| 992 | + Some(run.created_at.as_str()), | ||
| 993 | + run.finished_at.as_deref(), | ||
| 994 | + ) | ||
| 995 | + } else { | ||
| 996 | + String::new() | ||
| 997 | + }, | ||
| 998 | + meta: row_meta(run, jobs, &actor, lang), | ||
| 410 | } | 999 | } |
| 411 | - </span> | 1000 | + }) |
| 1001 | + .collect(); | ||
| 1002 | + let writer = can_write(&ctx); | ||
| 1003 | + let csrf = if writer { | ||
| 1004 | + current_user(cx) | ||
| 1005 | + .await? | ||
| 1006 | + .map(|(_, session)| session.csrf_token.clone()) | ||
| 1007 | + } else { | ||
| 1008 | + None | ||
| 1009 | + }; | ||
| 1010 | + let manual = if writer { | ||
| 1011 | + let refs = load_refs(ctx.path.clone()).await?; | ||
| 1012 | + Some(ManualRun { | ||
| 1013 | + action: base.clone(), | ||
| 1014 | + csrf: csrf.clone().unwrap_or_default(), | ||
| 1015 | + branches: branch_choices(&refs, &ctx.repo.default_branch), | ||
| 1016 | + }) | ||
| 1017 | + } else { | ||
| 1018 | + None | ||
| 1019 | + }; | ||
| 1020 | + let detail = match selected.as_ref() { | ||
| 1021 | + Some(run) => { | ||
| 1022 | + let actor = names.get(&run.actor_id).cloned().unwrap_or_default(); | ||
| 1023 | + let subject = subjects | ||
| 1024 | + .get(&run.commit_oid) | ||
| 1025 | + .cloned() | ||
| 1026 | + .unwrap_or_else(|| run.trigger.clone()); | ||
| 1027 | + Some( | ||
| 1028 | + run_detail( | ||
| 1029 | + state, | ||
| 1030 | + &title, | ||
| 1031 | + run, | ||
| 1032 | + RunHeader { | ||
| 1033 | + title: subject, | ||
| 1034 | + actor, | ||
| 1035 | + writer_csrf: csrf.clone(), | ||
| 1036 | + }, | ||
| 1037 | + &runners, | ||
| 1038 | + lang, | ||
| 1039 | + now, | ||
| 1040 | + ) | ||
| 1041 | + .await?, | ||
| 1042 | + ) | ||
| 1043 | + } | ||
| 1044 | + None => None, | ||
| 1045 | + }; | ||
| 1046 | + let last_page = total.div_ceil(u64::from(PER_PAGE)).max(1); | ||
| 1047 | + let newer_href = (page > 1).then(|| format!("{base}?page={}", page - 1)); | ||
| 1048 | + let older_href = (u64::from(page) < last_page).then(|| format!("{base}?page={}", page + 1)); | ||
| 1049 | + let list = ListView { | ||
| 1050 | + manual, | ||
| 1051 | + badge: badge_info(state, &title, &ctx.repo.default_branch), | ||
| 1052 | + total, | ||
| 1053 | + scale: g::scale_label(lang, &span_text(scale)), | ||
| 1054 | + rows, | ||
| 1055 | + newer_href, | ||
| 1056 | + older_href, | ||
| 1057 | + page_label: g::page_label(lang, page), | ||
| 1058 | + }; | ||
| 1059 | + let live = (page == 1).then(|| format!("{base}/events")); | ||
| 1060 | + let notice = notice_from_query(cx, lang); | ||
| 1061 | + let head = ctx.head(state, "ci").await?; | ||
| 1062 | + let page_title = match detail.as_ref() { | ||
| 1063 | + Some(run) if number.is_some() => format!("{title} \u{b7} CI #{}", run.number), | ||
| 1064 | + _ => format!("{title} \u{b7} CI"), | ||
| 1065 | + }; | ||
| 1066 | + Ok(SplitPage { | ||
| 1067 | + ctx, | ||
| 1068 | + head, | ||
| 1069 | + lang, | ||
| 1070 | + notice, | ||
| 1071 | + live, | ||
| 1072 | + page_title, | ||
| 1073 | + list, | ||
| 1074 | + detail, | ||
| 412 | }) | 1075 | }) |
| 413 | } | 1076 | } |
| 414 | 1077 | ||
| 415 | -/// The run list body. The header holds the manual run and badge menus and the run count, outside | 1078 | +/// The header values of the selected run that come from outside its row: its title, its actor and the |
| 416 | -/// the live region's card. The live region wraps the count and the card, so a live swap refreshes both. | 1079 | +/// CSRF token of a writer. |
| 1080 | +struct RunHeader { | ||
| 1081 | + title: String, | ||
| 1082 | + actor: String, | ||
| 1083 | + writer_csrf: Option<String>, | ||
| 1084 | +} | ||
| 1085 | + | ||
| 1086 | +/// The selected run: its header values, its timeline, its jobs and the last lines of the job to look at. | ||
| 1087 | +/// That is the failed job, else the running one, else the last job. | ||
| 1088 | +async fn run_detail( | ||
| 1089 | + state: &AppState, | ||
| 1090 | + title: &str, | ||
| 1091 | + run: &CiRun, | ||
| 1092 | + header: RunHeader, | ||
| 1093 | + runners: &HashMap<String, String>, | ||
| 1094 | + lang: Lang, | ||
| 1095 | + now: i64, | ||
| 1096 | +) -> Result<RunDetail> { | ||
| 1097 | + let jobs = timings_of(state, &run.id, runners, lang).await?; | ||
| 1098 | + let gantt = (!jobs.is_empty()).then(|| { | ||
| 1099 | + gantt( | ||
| 1100 | + &jobs, | ||
| 1101 | + origin_of(run, now), | ||
| 1102 | + run_end(run, now), | ||
| 1103 | + now, | ||
| 1104 | + lang, | ||
| 1105 | + ) | ||
| 1106 | + }); | ||
| 1107 | + let mut lines = Vec::with_capacity(jobs.len()); | ||
| 1108 | + for job in jobs.iter() { | ||
| 1109 | + let mut parts = Vec::new(); | ||
| 1110 | + if !job.image.is_empty() { | ||
| 1111 | + parts.push(job.image.clone()); | ||
| 1112 | + } | ||
| 1113 | + for artifact in state.store.list_artifacts(&job.id).await? { | ||
| 1114 | + let size = human_size(lang, u64::try_from(artifact.size).unwrap_or(0)); | ||
| 1115 | + parts.push(format!("{} {size}", artifact.name)); | ||
| 1116 | + } | ||
| 1117 | + lines.push(JobLine { | ||
| 1118 | + href: job_href(title, &job.id), | ||
| 1119 | + name: job.name.clone(), | ||
| 1120 | + dot: format!("ci-dot ci-{}", job.state.as_str()), | ||
| 1121 | + detail: parts.join(" \u{b7} "), | ||
| 1122 | + runner: job.runner.clone(), | ||
| 1123 | + duration: job.duration.clone(), | ||
| 1124 | + }); | ||
| 1125 | + } | ||
| 1126 | + let focus = jobs | ||
| 1127 | + .iter() | ||
| 1128 | + .find(|job| matches!(job.state, JobState::Failure | JobState::Error)) | ||
| 1129 | + .or_else(|| jobs.iter().find(|job| job.state == JobState::Running)) | ||
| 1130 | + .or(jobs.last()); | ||
| 1131 | + let log = match focus { | ||
| 1132 | + Some(job) => { | ||
| 1133 | + let tail = log_last_lines(&log_path(&state.config.data_dir, &job.id)).await; | ||
| 1134 | + (!tail.is_empty()).then(|| LogBlock { | ||
| 1135 | + caption: format!("{} \u{b7} {}", job.name, g::t(lang, K::LastLogLines)), | ||
| 1136 | + text: tail.join("\n"), | ||
| 1137 | + }) | ||
| 1138 | + } | ||
| 1139 | + None => None, | ||
| 1140 | + }; | ||
| 1141 | + Ok(RunDetail { | ||
| 1142 | + number: run.number, | ||
| 1143 | + title: header.title, | ||
| 1144 | + state: state_text(lang, run.state.as_str()), | ||
| 1145 | + state_class: format!("ci-state ci-{}", run.state.as_str()), | ||
| 1146 | + trigger: run.trigger.clone(), | ||
| 1147 | + branch: short_ref(&run.git_ref).to_owned(), | ||
| 1148 | + commit_href: format!("/{title}/commit/{}", run.commit_oid), | ||
| 1149 | + commit: short_oid(&run.commit_oid).to_owned(), | ||
| 1150 | + actor: header.actor, | ||
| 1151 | + when: age_text(lang, &run.created_at), | ||
| 1152 | + duration: duration_text( | ||
| 1153 | + lang, | ||
| 1154 | + Some(run.created_at.as_str()), | ||
| 1155 | + run.finished_at.as_deref(), | ||
| 1156 | + ), | ||
| 1157 | + config_error: run.config_error.clone(), | ||
| 1158 | + action_base: run_href(title, run.number), | ||
| 1159 | + can_approve: header.writer_csrf.is_some() && run.state == RunState::WaitingApproval, | ||
| 1160 | + can_cancel: header.writer_csrf.is_some() && !run_finished(&run.state), | ||
| 1161 | + writer_csrf: header.writer_csrf, | ||
| 1162 | + gantt, | ||
| 1163 | + jobs: lines, | ||
| 1164 | + log, | ||
| 1165 | + }) | ||
| 1166 | +} | ||
| 1167 | + | ||
| 1168 | +/// The runs page body. The header (the Run workflow and badge menus, the count) is the list's, and the | ||
| 1169 | +/// split view sits in the live region. The selected run is marked in the list and drawn on the right. | ||
| 417 | #[component] | 1170 | #[component] |
| 418 | async fn runs_body( | 1171 | async fn runs_body( |
| 419 | head: RepoHead, | 1172 | head: RepoHead, |
| 420 | lang: Lang, | 1173 | lang: Lang, |
| 421 | notice: Option<(&'static str, bool)>, | 1174 | notice: Option<(&'static str, bool)>, |
| 422 | - manual: Option<ManualRun>, | ||
| 423 | - badge: BadgeInfo, | ||
| 424 | - rows: Vec<RunRow>, | ||
| 425 | - total: u64, | ||
| 426 | - newer_href: Option<String>, | ||
| 427 | - older_href: Option<String>, | ||
| 428 | - page_label: String, | ||
| 429 | live: Option<String>, | 1175 | live: Option<String>, |
| 1176 | + list: ListView, | ||
| 1177 | + detail: Option<RunDetail>, | ||
| 430 | ) -> Result<impl View> { | 1178 | ) -> Result<impl View> { |
| 1179 | + let ListView { | ||
| 1180 | + manual, | ||
| 1181 | + badge, | ||
| 1182 | + total, | ||
| 1183 | + scale, | ||
| 1184 | + rows, | ||
| 1185 | + newer_href, | ||
| 1186 | + older_href, | ||
| 1187 | + page_label, | ||
| 1188 | + } = list; | ||
| 431 | Ok(view! { | 1189 | Ok(view! { |
| 432 | repo_head(head: head) | 1190 | repo_head(head: head) |
| 433 | if let Some((text, is_error)) = notice { | 1191 | if let Some((text, is_error)) = notice { |
| @@ -437,174 +1195,209 @@ async fn runs_body( | |||
| 437 | <section class="card notice" role="status">(text)</section> | 1195 | <section class="card notice" role="status">(text)</section> |
| 438 | } | 1196 | } |
| 439 | } | 1197 | } |
| 440 | - <div class="ci-list-head"> | 1198 | + <div data-live=(live.as_deref()) class="ci-split"> |
| 441 | - <h2 class="ci-list-title">(g::t(lang, K::Runs))</h2> | 1199 | + <svg class="ci-defs" width="0" height="0" focusable="false" aria-hidden="true"> |
| 442 | - <div class="ci-tools"> | 1200 | + <defs> |
| 443 | - if let Some(form) = manual { | 1201 | + <pattern id="ci-hatch" width="6" height="6" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"> |
| 444 | - <details class="menu ci-tool"> | 1202 | + <rect class="ci-hatch-ink" width="3" height="6"/> |
| 445 | - <summary>(g::t(lang, K::RunWorkflow))</summary> | 1203 | + </pattern> |
| 446 | - <div class="menu-list ci-pop"> | 1204 | + </defs> |
| 447 | - <p class="muted small">(g::t(lang, K::RunWorkflowHelp))</p> | 1205 | + </svg> |
| 448 | - <form method="post" action=(form.action.as_str()) class="ci-manual-form"> | 1206 | + <section class="card ci-side"> |
| 449 | - <input type="hidden" name="csrf" value=(form.csrf.as_str())> | 1207 | + <div class="ci-side-head"> |
| 450 | - <label> | 1208 | + <h2 class="ci-side-title">(g::t(lang, K::Runs)) <span class="ci-count">(total)</span></h2> |
| 451 | - (g::t(lang, K::Branch)) " " | 1209 | + <div class="ci-tools"> |
| 452 | - <select name="branch"> | 1210 | + if let Some(form) = manual { |
| 453 | - for branch in form.branches.iter() { | 1211 | + <details class="menu ci-tool"> |
| 454 | - <option value=(branch.as_str())>(branch.as_str())</option> | 1212 | + <summary>(g::t(lang, K::RunWorkflow))</summary> |
| 455 | - } | 1213 | + <div class="menu-list ci-pop"> |
| 456 | - </select> | 1214 | + <p class="muted small">(g::t(lang, K::RunWorkflowHelp))</p> |
| 1215 | + <form method="post" action=(form.action.as_str()) class="ci-manual-form"> | ||
| 1216 | + <input type="hidden" name="csrf" value=(form.csrf.as_str())> | ||
| 1217 | + <label> | ||
| 1218 | + (g::t(lang, K::Branch)) " " | ||
| 1219 | + <select name="branch"> | ||
| 1220 | + for branch in form.branches.iter() { | ||
| 1221 | + <option value=(branch.as_str())>(branch.as_str())</option> | ||
| 1222 | + } | ||
| 1223 | + </select> | ||
| 1224 | + </label> | ||
| 1225 | + <button type="submit">(g::t(lang, K::RunWorkflow))</button> | ||
| 1226 | + </form> | ||
| 1227 | + </div> | ||
| 1228 | + </details> | ||
| 1229 | + } | ||
| 1230 | + <details class="menu ci-tool"> | ||
| 1231 | + <summary>(g::t(lang, K::BadgeHeading))</summary> | ||
| 1232 | + <div class="menu-list ci-pop"> | ||
| 1233 | + <p class="muted small">(g::t(lang, K::BadgeHelp))</p> | ||
| 1234 | + <p><img src=(badge.image.as_str()) alt="build"></p> | ||
| 1235 | + <label class="small"> | ||
| 1236 | + (g::t(lang, K::BadgeSnippet)) | ||
| 1237 | + <textarea readonly="readonly" rows="2" class="ci-badge-snippet">(badge.snippet.as_str())</textarea> | ||
| 457 | </label> | 1238 | </label> |
| 458 | - <button type="submit">(g::t(lang, K::RunWorkflow))</button> | 1239 | + </div> |
| 459 | - </form> | 1240 | + </details> |
| 460 | - </div> | 1241 | + </div> |
| 461 | - </details> | 1242 | + </div> |
| 1243 | + if rows.is_empty() { | ||
| 1244 | + <div class="ci-empty"> | ||
| 1245 | + <p>(g::t(lang, K::NoRunsYet))</p> | ||
| 1246 | + <p class="muted small">(g::t(lang, K::NoRunsHint))</p> | ||
| 1247 | + </div> | ||
| 1248 | + } else { | ||
| 1249 | + <p class="ci-scale">(scale.as_str())</p> | ||
| 1250 | + <ul class="ci-run-list"> | ||
| 1251 | + for row in rows.iter() { | ||
| 1252 | + <li> | ||
| 1253 | + <a class="ci-row" href=(row.href.as_str()) aria-current=(row.current)> | ||
| 1254 | + <span class="ci-row-title">(row.title.as_str())</span> | ||
| 1255 | + <span class="ci-row-line"> | ||
| 1256 | + <svg class="ci-bar" viewBox="0 0 1000 6" preserveAspectRatio="none" aria-hidden="true"> | ||
| 1257 | + for seg in row.bar.iter() { | ||
| 1258 | + <rect class=(seg.class.as_str()) x=(seg.x.as_str()) y=(seg.y.as_str()) width=(seg.w.as_str()) height=(seg.h.as_str())/> | ||
| 1259 | + } | ||
| 1260 | + </svg> | ||
| 1261 | + <span class="ci-row-dur">(row.duration.as_str())</span> | ||
| 1262 | + </span> | ||
| 1263 | + <span class="ci-row-meta">(row.meta.as_str())</span> | ||
| 1264 | + </a> | ||
| 1265 | + </li> | ||
| 1266 | + } | ||
| 1267 | + </ul> | ||
| 462 | } | 1268 | } |
| 463 | - <details class="menu ci-tool"> | 1269 | + <nav class="pager"> |
| 464 | - <summary>(g::t(lang, K::BadgeHeading))</summary> | 1270 | + if let Some(href) = newer_href { |
| 465 | - <div class="menu-list ci-pop"> | 1271 | + <a href=(href.as_str())>(g::t(lang, K::Newer))</a> |
| 466 | - <p class="muted small">(g::t(lang, K::BadgeHelp))</p> | 1272 | + } |
| 467 | - <p><img src=(badge.image.as_str()) alt="CI"></p> | 1273 | + <span class="muted small">(page_label.as_str())</span> |
| 468 | - <label class="small"> | 1274 | + if let Some(href) = older_href { |
| 469 | - (g::t(lang, K::BadgeSnippet)) | 1275 | + <a href=(href.as_str())>(g::t(lang, K::Older))</a> |
| 470 | - <textarea readonly="readonly" rows="2" class="ci-badge-snippet">(badge.snippet.as_str())</textarea> | 1276 | + } |
| 471 | - </label> | 1277 | + </nav> |
| 1278 | + </section> | ||
| 1279 | + <section class="card ci-main"> | ||
| 1280 | + if let Some(run) = detail { | ||
| 1281 | + <div class="ci-main-head" data-run=(run.number)> | ||
| 1282 | + <h2 class="ci-eyebrow">(g::t(lang, K::RunNumber)) (run.number)</h2> | ||
| 1283 | + if let Some(csrf) = run.writer_csrf.as_ref() { | ||
| 1284 | + <div class="ci-actions"> | ||
| 1285 | + if run.can_approve { | ||
| 1286 | + action_button(action: format!("{}/approve", run.action_base), csrf: csrf.clone(), label: g::t(lang, K::ApproveAndRun)) | ||
| 1287 | + } | ||
| 1288 | + if run.can_cancel { | ||
| 1289 | + action_button(action: format!("{}/cancel", run.action_base), csrf: csrf.clone(), label: g::t(lang, K::Cancel)) | ||
| 1290 | + } | ||
| 1291 | + action_button(action: format!("{}/rerun", run.action_base), csrf: csrf.clone(), label: g::t(lang, K::Rerun)) | ||
| 1292 | + </div> | ||
| 1293 | + } | ||
| 472 | </div> | 1294 | </div> |
| 473 | - </details> | 1295 | + <h3 class="ci-run-title">(run.title.as_str())</h3> |
| 474 | - </div> | 1296 | + <p class="ci-run-top"> |
| 475 | - <div data-live=(live.as_deref()) class="ci-live"> | 1297 | + <span class=(run.state_class.as_str())>(run.state.as_str())</span> |
| 476 | - <span class="ci-count">(total)</span> | 1298 | + <span class="muted small"> |
| 477 | - <section class="card ci-list-card"> | 1299 | + (run.trigger.as_str()) " \u{b7} " (run.branch.as_str()) " \u{b7} " <a href=(run.commit_href.as_str())><code>(run.commit.as_str())</code></a> |
| 478 | - if rows.is_empty() { | 1300 | + if !run.actor.is_empty() { |
| 479 | - <div class="ci-empty"> | 1301 | + " \u{b7} " (run.actor.as_str()) |
| 480 | - <p>(g::t(lang, K::NoRunsYet))</p> | 1302 | + } |
| 481 | - <p class="muted small">(g::t(lang, K::NoRunsHint))</p> | 1303 | + " \u{b7} " (run.when.as_str()) |
| 1304 | + if !run.duration.is_empty() { | ||
| 1305 | + " \u{b7} " (run.duration.as_str()) | ||
| 1306 | + } | ||
| 1307 | + </span> | ||
| 1308 | + </p> | ||
| 1309 | + if let Some(message) = run.config_error.as_ref() { | ||
| 1310 | + <pre class="ci-config-error">(message.as_str())</pre> | ||
| 1311 | + } | ||
| 1312 | + if let Some(g) = run.gantt.as_ref() { | ||
| 1313 | + <div class="ci-gantt-scroll"> | ||
| 1314 | + <svg class="ci-gantt" viewBox=(g.view_box.as_str()) role="img" aria-label=(g::t(lang, K::Timeline))> | ||
| 1315 | + for r in g.rects.iter() { | ||
| 1316 | + <rect class=(r.class.as_str()) x=(r.x.as_str()) y=(r.y.as_str()) width=(r.w.as_str()) height=(r.h.as_str())/> | ||
| 1317 | + } | ||
| 1318 | + for d in g.links.iter() { | ||
| 1319 | + <path class="ci-glink" d=(d.as_str())/> | ||
| 1320 | + } | ||
| 1321 | + for t in g.labels.iter() { | ||
| 1322 | + <text class=(t.class) x=(t.x.as_str()) y=(t.y.as_str()) text-anchor=(t.anchor)>(t.text.as_str())</text> | ||
| 1323 | + } | ||
| 1324 | + </svg> | ||
| 482 | </div> | 1325 | </div> |
| 1326 | + } | ||
| 1327 | + if run.jobs.is_empty() { | ||
| 1328 | + <p class="muted">(g::t(lang, K::NoJobs))</p> | ||
| 483 | } else { | 1329 | } else { |
| 484 | - <ul class="ci-run-list"> | 1330 | + <ul class="ci-job-list"> |
| 485 | - for row in rows.iter() { | 1331 | + for job in run.jobs.iter() { |
| 486 | - <li class="ci-run-row"> | 1332 | + <li> |
| 487 | - run_icon(state: row.state_key.clone(), label: row.state.clone()) | 1333 | + <a class="ci-job-line" href=(job.href.as_str())> |
| 488 | - <div class="ci-run-body"> | 1334 | + <span class=(job.dot.as_str())></span> |
| 489 | - <p class="ci-run-title"><a class="ci-run-link" href=(row.href.as_str())>(row.title.as_str())</a></p> | 1335 | + <span class="ci-job-main"> |
| 490 | - <p class="ci-run-sub muted small"> | 1336 | + <span class="ci-job-name">(job.name.as_str())</span> |
| 491 | - "#" (row.number) | 1337 | + if !job.detail.is_empty() { |
| 492 | - " \u{b7} " (row.trigger.as_str()) | 1338 | + <span class="muted"> " \u{b7} " (job.detail.as_str())</span> |
| 493 | - " \u{b7} " <code class="ci-branch">(row.branch.as_str())</code> | ||
| 494 | - " \u{b7} " <a class="ci-run-commit" href=(row.commit_href.as_str())><code>(row.commit.as_str())</code></a> | ||
| 495 | - if !row.actor.is_empty() { | ||
| 496 | - " \u{b7} " (row.actor.as_str()) | ||
| 497 | } | 1339 | } |
| 498 | - </p> | 1340 | + </span> |
| 499 | - </div> | 1341 | + <span class="ci-job-runner">(job.runner.as_str())</span> |
| 500 | - <div class="ci-run-side muted small"> | 1342 | + <span class="ci-job-dur">(job.duration.as_str())</span> |
| 501 | - if !row.duration.is_empty() { | 1343 | + <span class="ci-chev" aria-hidden="true"></span> |
| 502 | - <span class="ci-run-dur"><svg viewBox="0 0 16 16" aria-hidden="true" class="ci-clock"><circle cx="8" cy="8" r="6"/><path d="M8 4.5V8l2.5 1.5"/></svg>(row.duration.as_str())</span> | 1344 | + </a> |
| 503 | - } | ||
| 504 | - <span>(row.when.as_str())</span> | ||
| 505 | - </div> | ||
| 506 | </li> | 1345 | </li> |
| 507 | } | 1346 | } |
| 508 | </ul> | 1347 | </ul> |
| 509 | } | 1348 | } |
| 510 | - <nav class="pager"> | 1349 | + if let Some(log) = run.log.as_ref() { |
| 511 | - if let Some(href) = newer_href { | 1350 | + <p class="ci-cap">(log.caption.as_str())</p> |
| 512 | - <a href=(href.as_str())>(g::t(lang, K::Newer))</a> | 1351 | + <pre class="ci-logpre">(log.text.as_str())</pre> |
| 513 | - } | 1352 | + } |
| 514 | - <span class="muted small">(page_label.as_str())</span> | 1353 | + } else { |
| 515 | - if let Some(href) = older_href { | 1354 | + <div class="ci-empty"> |
| 516 | - <a href=(href.as_str())>(g::t(lang, K::Older))</a> | 1355 | + <p>(g::t(lang, K::NoRunsYet))</p> |
| 517 | - } | 1356 | + <p class="muted small">(g::t(lang, K::NoRunsHint))</p> |
| 518 | - </nav> | 1357 | + </div> |
| 519 | - </section> | 1358 | + } |
| 520 | - </div> | 1359 | + </section> |
| 521 | </div> | 1360 | </div> |
| 522 | }) | 1361 | }) |
| 523 | } | 1362 | } |
| 524 | 1363 | ||
| 525 | -/// Lists the repo's runs, newest first, 25 to a page. The manual run form is for writers only. | 1364 | +/// Lists the repo's runs with the newest (or the one the URL names) on the right, 25 to a page. The |
| 1365 | +/// manual run form is for writers only. | ||
| 526 | #[page("/{owner}/{repo}/ci")] | 1366 | #[page("/{owner}/{repo}/ci")] |
| 527 | async fn runs_list_page(cx: &Cx) -> Result<impl View> { | 1367 | async fn runs_list_page(cx: &Cx) -> Result<impl View> { |
| 528 | - let owner = path_param::<Owner>(cx); | 1368 | + let SplitPage { |
| 529 | - let name = path_param::<Repo>(cx); | 1369 | + ctx, |
| 530 | - let ctx = load_repo(cx, owner, name).await?; | 1370 | + head, |
| 531 | - let lang = i18n::lang(cx, viewer_user(&ctx)); | 1371 | + lang, |
| 532 | - let state = app_context::<AppState>(cx); | 1372 | + notice, |
| 533 | - let page = page_from_query(cx); | 1373 | + live, |
| 534 | - let (runs, total) = state.store.list_runs(&ctx.repo.id, page, PER_PAGE).await?; | 1374 | + page_title, |
| 535 | - let names = usernames(state, lang, runs.iter().map(|run| run.actor_id.as_str())).await?; | 1375 | + list, |
| 536 | - // Each row's title is its commit's first line, read for this page's runs only. A commit that | 1376 | + detail, |
| 537 | - // cannot be read leaves the row's trigger as its title. | 1377 | + } = runs_split(cx, None).await?; |
| 538 | - let path = ctx.path.clone(); | 1378 | + Ok(view! { |
| 539 | - let oids: Vec<String> = runs.iter().map(|run| run.commit_oid.clone()).collect(); | 1379 | + shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), |
| 540 | - let subjects = tokio::task::spawn_blocking(move || { | 1380 | + runs_body(head: head, lang: lang, notice: notice, live: live, list: list, detail: detail)) |
| 541 | - oids.iter() | ||
| 542 | - .map(|oid| { | ||
| 543 | - read_commit(&path, oid) | ||
| 544 | - .ok() | ||
| 545 | - .flatten() | ||
| 546 | - .map(|commit| commit.summary) | ||
| 547 | - .filter(|summary| !summary.is_empty()) | ||
| 548 | - }) | ||
| 549 | - .collect::<Vec<_>>() | ||
| 550 | }) | 1381 | }) |
| 551 | - .await?; | 1382 | +} |
| 552 | - let base = ci_href(&title_of(&ctx)); | 1383 | + |
| 553 | - let rows: Vec<RunRow> = runs | 1384 | +/// One run, selected on the right of the list. A run that is not on the list page is still shown. |
| 554 | - .iter() | 1385 | +#[page("/{owner}/{repo}/ci/runs/{run_number}")] |
| 555 | - .zip(subjects) | 1386 | +async fn run_page(cx: &Cx) -> Result<impl View> { |
| 556 | - .map(|(run, subject)| RunRow { | 1387 | + let number = path_param::<RunNumber>(cx).to_owned(); |
| 557 | - href: run_href(&title_of(&ctx), run.number), | 1388 | + let SplitPage { |
| 558 | - number: run.number, | 1389 | + ctx, |
| 559 | - title: subject.unwrap_or_else(|| run.trigger.clone()), | 1390 | + head, |
| 560 | - state: state_text(lang, run.state.as_str()), | 1391 | + lang, |
| 561 | - state_key: run.state.as_str().to_owned(), | 1392 | + notice, |
| 562 | - trigger: run.trigger.clone(), | 1393 | + live, |
| 563 | - branch: short_ref(&run.git_ref).to_owned(), | 1394 | + page_title, |
| 564 | - commit_href: format!("/{}/commit/{}", title_of(&ctx), run.commit_oid), | 1395 | + list, |
| 565 | - commit: short_oid(&run.commit_oid).to_owned(), | 1396 | + detail, |
| 566 | - actor: names.get(&run.actor_id).cloned().unwrap_or_default(), | 1397 | + } = runs_split(cx, Some(&number)).await?; |
| 567 | - // Only a run that has started or finished has a duration. A queued run has none yet. | ||
| 568 | - duration: if run_finished(&run.state) || run.state == RunState::Running { | ||
| 569 | - duration_text( | ||
| 570 | - lang, | ||
| 571 | - Some(run.created_at.as_str()), | ||
| 572 | - run.finished_at.as_deref(), | ||
| 573 | - ) | ||
| 574 | - } else { | ||
| 575 | - String::new() | ||
| 576 | - }, | ||
| 577 | - when: age_text(lang, &run.created_at), | ||
| 578 | - }) | ||
| 579 | - .collect(); | ||
| 580 | - let last_page = total.div_ceil(u64::from(PER_PAGE)).max(1); | ||
| 581 | - let newer_href = (page > 1).then(|| format!("{base}?page={}", page - 1)); | ||
| 582 | - let older_href = (u64::from(page) < last_page).then(|| format!("{base}?page={}", page + 1)); | ||
| 583 | - let page_label = g::page_label(lang, page); | ||
| 584 | - // Page 1 follows the repo's changes, since a new run can appear at any time. Other pages do not. | ||
| 585 | - let live = (page == 1).then(|| format!("{base}/events")); | ||
| 586 | - let manual = if can_write(&ctx) { | ||
| 587 | - let csrf = match current_user(cx).await? { | ||
| 588 | - Some((_, session)) => session.csrf_token.clone(), | ||
| 589 | - None => String::new(), | ||
| 590 | - }; | ||
| 591 | - let refs = load_refs(ctx.path.clone()).await?; | ||
| 592 | - Some(ManualRun { | ||
| 593 | - action: base.clone(), | ||
| 594 | - csrf, | ||
| 595 | - branches: branch_choices(&refs, &ctx.repo.default_branch), | ||
| 596 | - }) | ||
| 597 | - } else { | ||
| 598 | - None | ||
| 599 | - }; | ||
| 600 | - let notice = notice_from_query(cx, lang); | ||
| 601 | - let badge = badge_info(state, &title_of(&ctx), &ctx.repo.default_branch); | ||
| 602 | - let head = ctx.head(state, "ci").await?; | ||
| 603 | - let title = format!("{} \u{b7} CI", title_of(&ctx)); | ||
| 604 | Ok(view! { | 1398 | Ok(view! { |
| 605 | - shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), | 1399 | + shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), |
| 606 | - runs_body(head: head, lang: lang, notice: notice, manual: manual, badge: badge, rows: rows, | 1400 | + runs_body(head: head, lang: lang, notice: notice, live: live, list: list, detail: detail)) |
| 607 | - total: total, newer_href: newer_href, older_href: older_href, page_label: page_label, live: live)) | ||
| 608 | }) | 1401 | }) |
| 609 | } | 1402 | } |
| 610 | 1403 | ||
| @@ -650,195 +1443,6 @@ async fn manual_run_post(cx: &Cx, Form(form): Form<ManualForm>) -> Result<SeeOth | |||
| 650 | Ok(see_other(run_href(&title, run.number))) | 1443 | Ok(see_other(run_href(&title, run.number))) |
| 651 | } | 1444 | } |
| 652 | 1445 | ||
| 653 | -/// The header values of a run for its page. | ||
| 654 | -async fn run_view( | ||
| 655 | - state: &AppState, | ||
| 656 | - ctx: &RepoCtx, | ||
| 657 | - run: &CiRun, | ||
| 658 | - writer: bool, | ||
| 659 | - lang: Lang, | ||
| 660 | -) -> Result<RunView> { | ||
| 661 | - let names = usernames(state, lang, std::iter::once(run.actor_id.as_str())).await?; | ||
| 662 | - let repo_title = title_of(ctx); | ||
| 663 | - let action_base = run_href(&repo_title, run.number); | ||
| 664 | - // The commit's first line is the run title. A run whose commit cannot be read shows its trigger. | ||
| 665 | - let path = ctx.path.clone(); | ||
| 666 | - let oid = run.commit_oid.clone(); | ||
| 667 | - let subject = tokio::task::spawn_blocking(move || read_commit(&path, &oid)) | ||
| 668 | - .await?? | ||
| 669 | - .map(|commit| commit.summary) | ||
| 670 | - .filter(|summary| !summary.is_empty()); | ||
| 671 | - Ok(RunView { | ||
| 672 | - number: run.number, | ||
| 673 | - title: subject.unwrap_or_else(|| run.trigger.clone()), | ||
| 674 | - commit_href: format!("/{repo_title}/commit/{}", run.commit_oid), | ||
| 675 | - duration: duration_text( | ||
| 676 | - lang, | ||
| 677 | - Some(run.created_at.as_str()), | ||
| 678 | - run.finished_at.as_deref(), | ||
| 679 | - ), | ||
| 680 | - state: state_text(lang, run.state.as_str()), | ||
| 681 | - state_class: format!("ci-state ci-{}", run.state.as_str()), | ||
| 682 | - trigger: run.trigger.clone(), | ||
| 683 | - git_ref: run.git_ref.clone(), | ||
| 684 | - commit: run.commit_oid.clone(), | ||
| 685 | - actor: names.get(&run.actor_id).cloned().unwrap_or_default(), | ||
| 686 | - when: age_text(lang, &run.created_at), | ||
| 687 | - config_error: run.config_error.clone(), | ||
| 688 | - can_approve: writer && run.state == RunState::WaitingApproval, | ||
| 689 | - can_cancel: writer && !run_finished(&run.state), | ||
| 690 | - action_base, | ||
| 691 | - }) | ||
| 692 | -} | ||
| 693 | - | ||
| 694 | -/// The job rows of a run page. Runner names come from the runner list. | ||
| 695 | -fn job_rows( | ||
| 696 | - title: &str, | ||
| 697 | - jobs: &[CiJob], | ||
| 698 | - runners: &HashMap<String, String>, | ||
| 699 | - lang: Lang, | ||
| 700 | -) -> Vec<JobRow> { | ||
| 701 | - jobs.iter() | ||
| 702 | - .map(|job| JobRow { | ||
| 703 | - href: job_href(title, &job.id), | ||
| 704 | - name: job.name.clone(), | ||
| 705 | - state: state_text(lang, job.state.as_str()), | ||
| 706 | - state_class: format!("ci-state ci-{}", job.state.as_str()), | ||
| 707 | - duration: duration_text(lang, job.started_at.as_deref(), job.finished_at.as_deref()), | ||
| 708 | - runner: job | ||
| 709 | - .runner_id | ||
| 710 | - .as_ref() | ||
| 711 | - .and_then(|id| runners.get(id).cloned()) | ||
| 712 | - .unwrap_or_default(), | ||
| 713 | - message: job.message.clone().unwrap_or_default(), | ||
| 714 | - }) | ||
| 715 | - .collect() | ||
| 716 | -} | ||
| 717 | - | ||
| 718 | -/// The `needs` of a job spec. A spec that does not read gives no needs. | ||
| 719 | -fn needs_of(spec_json: &str) -> Vec<String> { | ||
| 720 | - #[derive(Deserialize)] | ||
| 721 | - struct Needs { | ||
| 722 | - #[serde(default)] | ||
| 723 | - needs: Vec<String>, | ||
| 724 | - } | ||
| 725 | - serde_json::from_str::<Needs>(spec_json) | ||
| 726 | - .map(|spec| spec.needs) | ||
| 727 | - .unwrap_or_default() | ||
| 728 | -} | ||
| 729 | - | ||
| 730 | -/// Stage depth of each job, in the order given: 0 with no needs, else 1 plus the largest depth of its | ||
| 731 | -/// needs. A need that names no job of the run is ignored. A cycle (config parsing refuses one) stops | ||
| 732 | -/// at the job that repeats, so the walk always ends. | ||
| 733 | -pub(crate) fn stage_depths(jobs: &[(&str, &[String])]) -> Vec<usize> { | ||
| 734 | - let index: HashMap<&str, usize> = jobs | ||
| 735 | - .iter() | ||
| 736 | - .enumerate() | ||
| 737 | - .map(|(i, (name, _))| (*name, i)) | ||
| 738 | - .collect(); | ||
| 739 | - let deps: Vec<Vec<usize>> = jobs | ||
| 740 | - .iter() | ||
| 741 | - .map(|(_, needs)| { | ||
| 742 | - needs | ||
| 743 | - .iter() | ||
| 744 | - .filter_map(|need| index.get(need.as_str()).copied()) | ||
| 745 | - .collect() | ||
| 746 | - }) | ||
| 747 | - .collect(); | ||
| 748 | - let mut memo = vec![None; jobs.len()]; | ||
| 749 | - let mut active = vec![false; jobs.len()]; | ||
| 750 | - (0..jobs.len()) | ||
| 751 | - .map(|i| depth_of(i, &deps, &mut memo, &mut active)) | ||
| 752 | - .collect() | ||
| 753 | -} | ||
| 754 | - | ||
| 755 | -/// The stage depth of job `i`, memoized in `memo`. `active` marks the jobs on the walk now. | ||
| 756 | -fn depth_of( | ||
| 757 | - i: usize, | ||
| 758 | - deps: &[Vec<usize>], | ||
| 759 | - memo: &mut [Option<usize>], | ||
| 760 | - active: &mut [bool], | ||
| 761 | -) -> usize { | ||
| 762 | - if let Some(depth) = memo[i] { | ||
| 763 | - return depth; | ||
| 764 | - } | ||
| 765 | - if active[i] { | ||
| 766 | - return 0; | ||
| 767 | - } | ||
| 768 | - active[i] = true; | ||
| 769 | - let depth = deps[i] | ||
| 770 | - .iter() | ||
| 771 | - .map(|&need| depth_of(need, deps, memo, active) + 1) | ||
| 772 | - .max() | ||
| 773 | - .unwrap_or(0); | ||
| 774 | - active[i] = false; | ||
| 775 | - memo[i] = Some(depth); | ||
| 776 | - depth | ||
| 777 | -} | ||
| 778 | - | ||
| 779 | -/// The job graph of a run. Each job sits in the column of its stage depth, below the jobs before it | ||
| 780 | -/// in that column. A connector runs from each needed job to the job that needs it. | ||
| 781 | -fn job_graph(title: &str, jobs: &[CiJob], lang: Lang) -> JobGraph { | ||
| 782 | - let needs: Vec<Vec<String>> = jobs.iter().map(|job| needs_of(&job.spec_json)).collect(); | ||
| 783 | - let named: Vec<(&str, &[String])> = jobs | ||
| 784 | - .iter() | ||
| 785 | - .zip(&needs) | ||
| 786 | - .map(|(job, n)| (job.name.as_str(), n.as_slice())) | ||
| 787 | - .collect(); | ||
| 788 | - let depths = stage_depths(&named); | ||
| 789 | - let stages = depths.iter().max().map_or(0, |deepest| deepest + 1); | ||
| 790 | - let mut columns: Vec<Vec<GraphCard>> = (0..stages).map(|_| Vec::new()).collect(); | ||
| 791 | - let mut slots = Vec::with_capacity(jobs.len()); | ||
| 792 | - for (job, &depth) in jobs.iter().zip(&depths) { | ||
| 793 | - slots.push((depth, columns[depth].len())); | ||
| 794 | - columns[depth].push(GraphCard { | ||
| 795 | - class: format!("ci-graph-card ci-{}", job.state.as_str()), | ||
| 796 | - href: job_href(title, &job.id), | ||
| 797 | - name: job.name.clone(), | ||
| 798 | - state: state_text(lang, job.state.as_str()), | ||
| 799 | - duration: duration_text(lang, job.started_at.as_deref(), job.finished_at.as_deref()), | ||
| 800 | - }); | ||
| 801 | - } | ||
| 802 | - let x = |stage: usize| GRAPH_PAD + stage as i64 * (GRAPH_CARD_W + GRAPH_COL_GAP); | ||
| 803 | - let y = |row: usize| GRAPH_PAD + row as i64 * (GRAPH_CARD_H + GRAPH_ROW_GAP); | ||
| 804 | - let stage_count = stages as i64; | ||
| 805 | - let tallest = columns.iter().map(Vec::len).max().unwrap_or(0) as i64; | ||
| 806 | - let width = | ||
| 807 | - 2 * GRAPH_PAD + stage_count * GRAPH_CARD_W + (stage_count - 1).max(0) * GRAPH_COL_GAP; | ||
| 808 | - let height = 2 * GRAPH_PAD + tallest * GRAPH_CARD_H + (tallest - 1).max(0) * GRAPH_ROW_GAP; | ||
| 809 | - let index: HashMap<&str, usize> = jobs | ||
| 810 | - .iter() | ||
| 811 | - .enumerate() | ||
| 812 | - .map(|(i, job)| (job.name.as_str(), i)) | ||
| 813 | - .collect(); | ||
| 814 | - let bend = GRAPH_COL_GAP / 2; | ||
| 815 | - let mut paths = Vec::new(); | ||
| 816 | - for (i, job_needs) in needs.iter().enumerate() { | ||
| 817 | - let (to_stage, to_row) = slots[i]; | ||
| 818 | - let x2 = x(to_stage); | ||
| 819 | - let y2 = y(to_row) + GRAPH_CARD_H / 2; | ||
| 820 | - for need in job_needs { | ||
| 821 | - let Some(&from) = index.get(need.as_str()) else { | ||
| 822 | - continue; | ||
| 823 | - }; | ||
| 824 | - let (from_stage, from_row) = slots[from]; | ||
| 825 | - let x1 = x(from_stage) + GRAPH_CARD_W; | ||
| 826 | - let y1 = y(from_row) + GRAPH_CARD_H / 2; | ||
| 827 | - paths.push(format!( | ||
| 828 | - "M{x1} {y1} C{} {y1} {} {y2} {x2} {y2}", | ||
| 829 | - x1 + bend, | ||
| 830 | - x2 - bend | ||
| 831 | - )); | ||
| 832 | - } | ||
| 833 | - } | ||
| 834 | - JobGraph { | ||
| 835 | - width: width.to_string(), | ||
| 836 | - height: height.to_string(), | ||
| 837 | - columns, | ||
| 838 | - paths, | ||
| 839 | - } | ||
| 840 | -} | ||
| 841 | - | ||
| 842 | /// How often an idle event stream sends a `: keepalive` comment, so a reverse proxy does not drop | 1446 | /// How often an idle event stream sends a `: keepalive` comment, so a reverse proxy does not drop |
| 843 | /// the connection. This is not a poll: events follow the change signals. | 1447 | /// the connection. This is not a poll: events follow the change signals. |
| 844 | const STREAM_KEEP_ALIVE: Duration = Duration::from_secs(30); | 1448 | const STREAM_KEEP_ALIVE: Duration = Duration::from_secs(30); |
| @@ -953,169 +1557,6 @@ pub(crate) fn events_response( | |||
| 953 | Ok(res) | 1557 | Ok(res) |
| 954 | } | 1558 | } |
| 955 | 1559 | ||
| 956 | -/// The run page body: the header, the buttons for writers, the config error, and the jobs. A run | ||
| 957 | -/// that is not finished carries `live`, the URL of its event stream. | ||
| 958 | -#[component] | ||
| 959 | -async fn run_body( | ||
| 960 | - head: RepoHead, | ||
| 961 | - lang: Lang, | ||
| 962 | - notice: Option<(&'static str, bool)>, | ||
| 963 | - run: RunView, | ||
| 964 | - jobs: Vec<JobRow>, | ||
| 965 | - graph: JobGraph, | ||
| 966 | - writer_csrf: Option<String>, | ||
| 967 | - live: Option<String>, | ||
| 968 | -) -> Result<impl View> { | ||
| 969 | - Ok(view! { | ||
| 970 | - repo_head(head: head) | ||
| 971 | - <div data-live=(live.as_deref())> | ||
| 972 | - if let Some((text, is_error)) = notice { | ||
| 973 | - if is_error { | ||
| 974 | - alert(message: text) | ||
| 975 | - } else { | ||
| 976 | - <section class="card notice" role="status">(text)</section> | ||
| 977 | - } | ||
| 978 | - } | ||
| 979 | - <section class="card ci-run-head"> | ||
| 980 | - <div class="ci-run-head-main"> | ||
| 981 | - <h2 class="ci-run-title"><span class=(run.state_class.as_str())>(run.state.as_str())</span>" "(run.title.as_str())</h2> | ||
| 982 | - <p class="muted small ci-run-meta"> | ||
| 983 | - "#" (run.number) | ||
| 984 | - " \u{b7} " (run.trigger.as_str()) | ||
| 985 | - " \u{b7} " <code>(run.git_ref.as_str())</code> | ||
| 986 | - " \u{b7} " <a href=(run.commit_href.as_str())><code>(short_oid(&run.commit).to_owned())</code></a> | ||
| 987 | - if !run.actor.is_empty() { | ||
| 988 | - " \u{b7} " (run.actor.as_str()) | ||
| 989 | - } | ||
| 990 | - " \u{b7} " (run.when.as_str()) | ||
| 991 | - if !run.duration.is_empty() { | ||
| 992 | - " \u{b7} " (run.duration.as_str()) | ||
| 993 | - } | ||
| 994 | - </p> | ||
| 995 | - if let Some(message) = run.config_error.as_ref() { | ||
| 996 | - <pre class="ci-config-error">(message.as_str())</pre> | ||
| 997 | - } | ||
| 998 | - </div> | ||
| 999 | - if let Some(csrf) = writer_csrf { | ||
| 1000 | - <div class="ci-actions"> | ||
| 1001 | - if run.can_approve { | ||
| 1002 | - action_button(action: format!("{}/approve", run.action_base), csrf: csrf.clone(), label: g::t(lang, K::ApproveAndRun)) | ||
| 1003 | - } | ||
| 1004 | - if run.can_cancel { | ||
| 1005 | - action_button(action: format!("{}/cancel", run.action_base), csrf: csrf.clone(), label: g::t(lang, K::Cancel)) | ||
| 1006 | - } | ||
| 1007 | - action_button(action: format!("{}/rerun", run.action_base), csrf: csrf, label: g::t(lang, K::Rerun)) | ||
| 1008 | - </div> | ||
| 1009 | - } | ||
| 1010 | - </section> | ||
| 1011 | - if !jobs.is_empty() { | ||
| 1012 | - <section class="card"> | ||
| 1013 | - <h2>(g::t(lang, K::JobGraph))</h2> | ||
| 1014 | - <div class="ci-graph" tabindex="0" role="region" aria-label=(g::t(lang, K::JobGraph))> | ||
| 1015 | - <div class="ci-graph-canvas"> | ||
| 1016 | - <svg class="ci-graph-lines" width=(graph.width.as_str()) height=(graph.height.as_str()) aria-hidden="true"> | ||
| 1017 | - for d in graph.paths.iter() { | ||
| 1018 | - <path d=(d.as_str())/> | ||
| 1019 | - } | ||
| 1020 | - </svg> | ||
| 1021 | - for stage in graph.columns.iter() { | ||
| 1022 | - <div class="ci-graph-col"> | ||
| 1023 | - for card in stage.iter() { | ||
| 1024 | - <a class=(card.class.as_str()) href=(card.href.as_str())> | ||
| 1025 | - <span class="ci-graph-name">(card.name.as_str())</span> | ||
| 1026 | - <span class="ci-graph-meta"> | ||
| 1027 | - <span class="ci-graph-icon" aria-hidden="true"></span> | ||
| 1028 | - (card.state.as_str()) | ||
| 1029 | - if !card.duration.is_empty() { | ||
| 1030 | - " \u{b7} " (card.duration.as_str()) | ||
| 1031 | - } | ||
| 1032 | - </span> | ||
| 1033 | - </a> | ||
| 1034 | - } | ||
| 1035 | - </div> | ||
| 1036 | - } | ||
| 1037 | - </div> | ||
| 1038 | - </div> | ||
| 1039 | - </section> | ||
| 1040 | - } | ||
| 1041 | - <section class="card"> | ||
| 1042 | - <h2>(g::t(lang, K::Jobs))</h2> | ||
| 1043 | - if jobs.is_empty() { | ||
| 1044 | - <p class="muted">(g::t(lang, K::NoJobs))</p> | ||
| 1045 | - } else { | ||
| 1046 | - <div class="table-wrap"> | ||
| 1047 | - <table class="table ci-jobs"> | ||
| 1048 | - <thead> | ||
| 1049 | - <tr> | ||
| 1050 | - <th>(g::t(lang, K::ColJob))</th> | ||
| 1051 | - <th>(g::t(lang, K::ColState))</th> | ||
| 1052 | - <th>(g::t(lang, K::ColDuration))</th> | ||
| 1053 | - <th>(g::t(lang, K::ColRunner))</th> | ||
| 1054 | - <th>(g::t(lang, K::ColMessage))</th> | ||
| 1055 | - </tr> | ||
| 1056 | - </thead> | ||
| 1057 | - <tbody> | ||
| 1058 | - for job in jobs.iter() { | ||
| 1059 | - <tr> | ||
| 1060 | - <td><a class="ci-job-link" href=(job.href.as_str())>(job.name.as_str())</a></td> | ||
| 1061 | - <td><span class=(job.state_class.as_str())>(job.state.as_str())</span></td> | ||
| 1062 | - <td>(job.duration.as_str())</td> | ||
| 1063 | - <td>(job.runner.as_str())</td> | ||
| 1064 | - <td>(job.message.as_str())</td> | ||
| 1065 | - </tr> | ||
| 1066 | - } | ||
| 1067 | - </tbody> | ||
| 1068 | - </table> | ||
| 1069 | - </div> | ||
| 1070 | - } | ||
| 1071 | - </section> | ||
| 1072 | - </div> | ||
| 1073 | - }) | ||
| 1074 | -} | ||
| 1075 | - | ||
| 1076 | -/// One run: its state, the buttons for writers, the config error and its jobs. | ||
| 1077 | -#[page("/{owner}/{repo}/ci/runs/{run_number}")] | ||
| 1078 | -async fn run_page(cx: &Cx) -> Result<impl View> { | ||
| 1079 | - let owner = path_param::<Owner>(cx); | ||
| 1080 | - let name = path_param::<Repo>(cx); | ||
| 1081 | - let number = path_param::<RunNumber>(cx).to_owned(); | ||
| 1082 | - let ctx = load_repo(cx, owner, name).await?; | ||
| 1083 | - let lang = i18n::lang(cx, viewer_user(&ctx)); | ||
| 1084 | - let state = app_context::<AppState>(cx); | ||
| 1085 | - let run = run_of(state, &ctx, &number).await?; | ||
| 1086 | - let writer = can_write(&ctx); | ||
| 1087 | - let writer_csrf = if writer { | ||
| 1088 | - match current_user(cx).await? { | ||
| 1089 | - Some((_, session)) => Some(session.csrf_token.clone()), | ||
| 1090 | - None => None, | ||
| 1091 | - } | ||
| 1092 | - } else { | ||
| 1093 | - None | ||
| 1094 | - }; | ||
| 1095 | - let jobs = state.store.jobs_for_run(&run.id).await?; | ||
| 1096 | - let runners: HashMap<String, String> = state | ||
| 1097 | - .store | ||
| 1098 | - .list_runners() | ||
| 1099 | - .await? | ||
| 1100 | - .into_iter() | ||
| 1101 | - .map(|runner| (runner.id, runner.name)) | ||
| 1102 | - .collect(); | ||
| 1103 | - let title = title_of(&ctx); | ||
| 1104 | - let rows = job_rows(&title, &jobs, &runners, lang); | ||
| 1105 | - let graph = job_graph(&title, &jobs, lang); | ||
| 1106 | - let live = | ||
| 1107 | - (!run_finished(&run.state)).then(|| format!("{}/events", run_href(&title, run.number))); | ||
| 1108 | - let notice = notice_from_query(cx, lang); | ||
| 1109 | - let header = run_view(state, &ctx, &run, writer, lang).await?; | ||
| 1110 | - let head = ctx.head(state, "ci").await?; | ||
| 1111 | - let page_title = format!("{title} \u{b7} CI #{}", run.number); | ||
| 1112 | - Ok(view! { | ||
| 1113 | - shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), | ||
| 1114 | - run_body(head: head, lang: lang, notice: notice, run: header, jobs: rows, | ||
| 1115 | - graph: graph, writer_csrf: writer_csrf, live: live)) | ||
| 1116 | - }) | ||
| 1117 | -} | ||
| 1118 | - | ||
| 1119 | /// The live `changed` stream of a run that is not finished. It is sent on every change to the run | 1560 | /// The live `changed` stream of a run that is not finished. It is sent on every change to the run |
| 1120 | /// or to one of its jobs, so the page can render its rows again. | 1561 | /// or to one of its jobs, so the page can render its rows again. |
| 1121 | #[route(GET "/{owner}/{repo}/ci/runs/{run_number}/events")] | 1562 | #[route(GET "/{owner}/{repo}/ci/runs/{run_number}/events")] |
| @@ -1204,6 +1645,29 @@ async fn run_rerun(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> { | |||
| 1204 | mod tests { | 1645 | mod tests { |
| 1205 | use super::*; | 1646 | use super::*; |
| 1206 | 1647 | ||
| 1648 | + /// A job timing with the given times, on runner `vps-1`. | ||
| 1649 | + fn timing( | ||
| 1650 | + name: &str, | ||
| 1651 | + state: JobState, | ||
| 1652 | + queued: Option<i64>, | ||
| 1653 | + started: Option<i64>, | ||
| 1654 | + finished: Option<i64>, | ||
| 1655 | + ) -> Timing { | ||
| 1656 | + Timing { | ||
| 1657 | + id: name.to_owned(), | ||
| 1658 | + name: name.to_owned(), | ||
| 1659 | + state, | ||
| 1660 | + needs: Vec::new(), | ||
| 1661 | + image: String::new(), | ||
| 1662 | + runner: "vps-1".to_owned(), | ||
| 1663 | + duration: String::new(), | ||
| 1664 | + message: String::new(), | ||
| 1665 | + queued, | ||
| 1666 | + started, | ||
| 1667 | + finished, | ||
| 1668 | + } | ||
| 1669 | + } | ||
| 1670 | + | ||
| 1207 | #[test] | 1671 | #[test] |
| 1208 | fn durations_read_well() { | 1672 | fn durations_read_well() { |
| 1209 | assert_eq!( | 1673 | assert_eq!( |
| @@ -1265,4 +1729,125 @@ mod tests { | |||
| 1265 | ]; | 1729 | ]; |
| 1266 | assert_eq!(branch_choices(&refs, "main"), vec!["main", "dev"]); | 1730 | assert_eq!(branch_choices(&refs, "main"), vec!["main", "dev"]); |
| 1267 | } | 1731 | } |
| 1732 | + | ||
| 1733 | + #[test] | ||
| 1734 | + fn refs_shorten_to_branch_and_tag_names() { | ||
| 1735 | + assert_eq!(short_ref("refs/heads/main"), "main"); | ||
| 1736 | + assert_eq!(short_ref("refs/tags/v1.2"), "v1.2"); | ||
| 1737 | + assert_eq!(short_ref("refs/pull/7/head"), "refs/pull/7/head"); | ||
| 1738 | + } | ||
| 1739 | + | ||
| 1740 | + #[test] | ||
| 1741 | + fn images_show_their_last_part() { | ||
| 1742 | + assert_eq!(image_short("docker.io/library/rust:1"), "rust:1"); | ||
| 1743 | + assert_eq!(image_short("alpine"), "alpine"); | ||
| 1744 | + } | ||
| 1745 | + | ||
| 1746 | + #[test] | ||
| 1747 | + fn bar_scale_is_the_longest_run_of_the_page() { | ||
| 1748 | + assert_eq!(bar_scale(&[30, 4692, 0]), 4692); | ||
| 1749 | + assert_eq!(bar_scale(&[]), 1); | ||
| 1750 | + assert_eq!(bar_scale(&[0, 0]), 1); | ||
| 1751 | + } | ||
| 1752 | + | ||
| 1753 | + #[test] | ||
| 1754 | + fn scale_line_reads_the_real_span() { | ||
| 1755 | + assert_eq!(span_text(5), "5s"); | ||
| 1756 | + assert_eq!(span_text(90), "1m 30s"); | ||
| 1757 | + assert_eq!(span_text(1200), "20m"); | ||
| 1758 | + assert_eq!(span_text(4692), "1h 19m"); | ||
| 1759 | + } | ||
| 1760 | + | ||
| 1761 | + #[test] | ||
| 1762 | + fn list_bars_share_the_page_scale() { | ||
| 1763 | + let jobs = [ | ||
| 1764 | + timing("test", JobState::Success, Some(0), Some(0), Some(2160)), | ||
| 1765 | + timing("build", JobState::Failure, Some(2160), Some(2160), Some(4692)), | ||
| 1766 | + ]; | ||
| 1767 | + let bar = row_bar(&jobs, 0, 4692, 4692, false); | ||
| 1768 | + let spans: Vec<(&str, &str)> = bar | ||
| 1769 | + .iter() | ||
| 1770 | + .map(|r| (r.x.as_str(), r.w.as_str())) | ||
| 1771 | + .collect(); | ||
| 1772 | + assert_eq!(spans, vec![("0", "460"), ("460", "540")]); | ||
| 1773 | + assert_eq!(bar[1].class, "ci-seg ci-bad"); | ||
| 1774 | + // A running run adds the hatched rest of the scale after its jobs. | ||
| 1775 | + let running = row_bar(&jobs[..1], 0, 4692, 2160, true); | ||
| 1776 | + assert_eq!( | ||
| 1777 | + running.last().map(|r| r.class.as_str()), | ||
| 1778 | + Some("ci-seg ci-rest") | ||
| 1779 | + ); | ||
| 1780 | + } | ||
| 1781 | + | ||
| 1782 | + #[test] | ||
| 1783 | + fn axis_ticks_are_round_and_few() { | ||
| 1784 | + assert_eq!(axis(4692), (1200, 4800)); | ||
| 1785 | + assert_eq!(axis(60), (60, 60)); | ||
| 1786 | + assert_eq!(tick_label(0), "0"); | ||
| 1787 | + assert_eq!(tick_label(1200), "20m"); | ||
| 1788 | + assert_eq!(tick_label(3600), "1h"); | ||
| 1789 | + assert_eq!(tick_label(4800), "1h 20m"); | ||
| 1790 | + } | ||
| 1791 | + | ||
| 1792 | + #[test] | ||
| 1793 | + fn places_follow_the_span() { | ||
| 1794 | + assert_eq!(place(0, 4800, 530), 0); | ||
| 1795 | + assert_eq!(place(2160, 4800, 530), 239); | ||
| 1796 | + assert_eq!(place(9999, 4800, 530), 530); | ||
| 1797 | + assert_eq!(place(5, 0, 530), 0); | ||
| 1798 | + } | ||
| 1799 | + | ||
| 1800 | + #[test] | ||
| 1801 | + fn timeline_boxes_sit_at_the_real_times() { | ||
| 1802 | + // The run starts at 0. Test runs to 2160 seconds, then build starts and runs to 4692. | ||
| 1803 | + let test = timing("test", JobState::Success, Some(0), Some(0), Some(2160)); | ||
| 1804 | + let mut build = timing("build", JobState::Success, Some(2160), Some(2160), Some(4692)); | ||
| 1805 | + build.needs = vec!["test".to_owned()]; | ||
| 1806 | + let g = gantt(&[test, build], 0, Some(4692), 4692, Lang::En); | ||
| 1807 | + assert_eq!(g.view_box, "0 0 640 104"); | ||
| 1808 | + let bars: Vec<&Rect> = g | ||
| 1809 | + .rects | ||
| 1810 | + .iter() | ||
| 1811 | + .filter(|r| r.class.starts_with("ci-gbar")) | ||
| 1812 | + .collect(); | ||
| 1813 | + assert_eq!((bars[0].x.as_str(), bars[0].w.as_str()), ("100", "239")); | ||
| 1814 | + assert_eq!((bars[1].x.as_str(), bars[1].w.as_str()), ("339", "279")); | ||
| 1815 | + // The connector leaves the end of test and turns down at the start of build. | ||
| 1816 | + assert_eq!(g.links, vec!["M339 44 H339 V84".to_owned()]); | ||
| 1817 | + } | ||
| 1818 | + | ||
| 1819 | + #[test] | ||
| 1820 | + fn a_queued_job_shows_its_lead_in_before_it_starts() { | ||
| 1821 | + let test = timing("test", JobState::Success, Some(0), Some(4), Some(10)); | ||
| 1822 | + let g = gantt(&[test], 0, Some(10), 10, Lang::En); | ||
| 1823 | + let lead = g | ||
| 1824 | + .rects | ||
| 1825 | + .iter() | ||
| 1826 | + .find(|r| r.class == "ci-glead") | ||
| 1827 | + .expect("a lead-in"); | ||
| 1828 | + // The axis is a minute long, so 4 seconds of queueing are 35 units from the track's start. | ||
| 1829 | + assert_eq!((lead.x.as_str(), lead.w.as_str()), ("100", "35")); | ||
| 1830 | + assert!(g.labels.iter().any(|l| l.text == "queued 4s")); | ||
| 1831 | + } | ||
| 1832 | + | ||
| 1833 | + #[test] | ||
| 1834 | + fn bar_text_takes_the_first_label_that_fits() { | ||
| 1835 | + let labels = [ | ||
| 1836 | + "build \u{b7} 42m 9s \u{b7} vps-1 \u{b7} dist".to_owned(), | ||
| 1837 | + "build \u{b7} 42m 9s".to_owned(), | ||
| 1838 | + "42m 9s".to_owned(), | ||
| 1839 | + ]; | ||
| 1840 | + assert_eq!(bar_text(400, &labels).as_deref(), Some(labels[0].as_str())); | ||
| 1841 | + assert_eq!(bar_text(120, &labels).as_deref(), Some("build \u{b7} 42m 9s")); | ||
| 1842 | + assert_eq!(bar_text(40, &labels), None); | ||
| 1843 | + } | ||
| 1844 | + | ||
| 1845 | + #[tokio::test] | ||
| 1846 | + async fn log_tails_keep_their_last_lines() { | ||
| 1847 | + let dir = tempfile::tempdir().expect("tempdir"); | ||
| 1848 | + let path = dir.path().join("log.txt"); | ||
| 1849 | + std::fs::write(&path, "one\ntwo\nthree\nfour\n").expect("write"); | ||
| 1850 | + assert_eq!(log_last_lines(&path).await, vec!["two", "three", "four"]); | ||
| 1851 | + assert!(log_last_lines(&dir.path().join("none")).await.is_empty()); | ||
| 1852 | + } | ||
| 1268 | } | 1853 | } |
crates/forge-web/src/pages/ci_tests.rsmodified+76 -44
| @@ -320,7 +320,8 @@ async fn pages_are_live_while_not_finished_and_never_meta_refresh() { | |||
| 320 | let url = format!("/tahinli/proj/ci/jobs/{}", job.id); | 320 | let url = format!("/tahinli/proj/ci/jobs/{}", job.id); |
| 321 | let run_url = format!("{RUN_BASE}/runs/{}", run.number); | 321 | let run_url = format!("{RUN_BASE}/runs/{}", run.number); |
| 322 | let job_marker = format!("data-live=\"{url}/events\""); | 322 | let job_marker = format!("data-live=\"{url}/events\""); |
| 323 | - let run_marker = format!("data-live=\"{run_url}/events\""); | 323 | + // The split view is live on page 1 through the repo stream, whatever the run's state. |
| 324 | + let run_marker = format!("data-live=\"{RUN_BASE}/events\""); | ||
| 324 | 325 | ||
| 325 | let queued = get(&fx.app, &url, Some(&cookie_for("tahinli-token"))).await; | 326 | let queued = get(&fx.app, &url, Some(&cookie_for("tahinli-token"))).await; |
| 326 | assert!(queued.text().contains(&job_marker), "job live while queued"); | 327 | assert!(queued.text().contains(&job_marker), "job live while queued"); |
| @@ -485,6 +486,74 @@ async fn run_list_is_live_on_page_one_only() { | |||
| 485 | ) | 486 | ) |
| 486 | .await; | 487 | .await; |
| 487 | assert!(!second.text().contains("data-live="), "page 2 is not live"); | 488 | assert!(!second.text().contains("data-live="), "page 2 is not live"); |
| 489 | + let run = get( | ||
| 490 | + &fx.app, | ||
| 491 | + &format!("{RUN_BASE}/runs/30?page=2"), | ||
| 492 | + Some(&cookie_for("tahinli-token")), | ||
| 493 | + ) | ||
| 494 | + .await; | ||
| 495 | + assert!(!run.text().contains("data-live="), "a run on page 2 is not live"); | ||
| 496 | +} | ||
| 497 | + | ||
| 498 | +/// The href of the list row marked as current, from the markup of the runs page. | ||
| 499 | +fn current_href(html: &str) -> Option<&str> { | ||
| 500 | + let mark = html.find("aria-current=\"true\"")?; | ||
| 501 | + let start = html[..mark].rfind("<a ")?; | ||
| 502 | + let link = &html[start..mark]; | ||
| 503 | + let at = link.find("href=\"")? + "href=\"".len(); | ||
| 504 | + link[at..].split('"').next() | ||
| 505 | +} | ||
| 506 | + | ||
| 507 | +/// `/ci` draws the newest run and `/ci/runs/n` draws run n. The drawn run is marked in the list. A run | ||
| 508 | +/// that is not on the list page is still drawn, and no row of the list is marked for it. | ||
| 509 | +#[tokio::test] | ||
| 510 | +async fn split_view_draws_the_newest_run_or_the_one_named() { | ||
| 511 | + let dir = tempfile::tempdir().expect("tempdir"); | ||
| 512 | + let fx = fixture(dir.path()).await; | ||
| 513 | + let first = run_with(&fx, &["build"], false).await; | ||
| 514 | + let second = run_with(&fx, &["build"], false).await; | ||
| 515 | + let tahinli = Some(cookie_for("tahinli-token")); | ||
| 516 | + let newest = get(&fx.app, RUN_BASE, tahinli.as_deref()).await.text(); | ||
| 517 | + assert!(newest.contains(&format!("data-run=\"{}\"", second.number))); | ||
| 518 | + assert_eq!( | ||
| 519 | + current_href(&newest), | ||
| 520 | + Some(format!("{RUN_BASE}/runs/{}", second.number).as_str()) | ||
| 521 | + ); | ||
| 522 | + let named = get( | ||
| 523 | + &fx.app, | ||
| 524 | + &format!("{RUN_BASE}/runs/{}", first.number), | ||
| 525 | + tahinli.as_deref(), | ||
| 526 | + ) | ||
| 527 | + .await | ||
| 528 | + .text(); | ||
| 529 | + assert!(named.contains(&format!("data-run=\"{}\"", first.number))); | ||
| 530 | + assert_eq!( | ||
| 531 | + current_href(&named), | ||
| 532 | + Some(format!("{RUN_BASE}/runs/{}", first.number).as_str()) | ||
| 533 | + ); | ||
| 534 | + assert_eq!(named.matches("aria-current=\"true\"").count(), 1); | ||
| 535 | + | ||
| 536 | + // Thirty runs make two pages. Run 1 is on page 2, so page 1 marks no row and draws run 1. | ||
| 537 | + for _ in 0..28 { | ||
| 538 | + run_with(&fx, &["build"], false).await; | ||
| 539 | + } | ||
| 540 | + let off_page = get( | ||
| 541 | + &fx.app, | ||
| 542 | + &format!("{RUN_BASE}/runs/{}", first.number), | ||
| 543 | + tahinli.as_deref(), | ||
| 544 | + ) | ||
| 545 | + .await | ||
| 546 | + .text(); | ||
| 547 | + assert!(off_page.contains(&format!("data-run=\"{}\"", first.number))); | ||
| 548 | + assert_eq!(off_page.matches("aria-current=\"true\"").count(), 0); | ||
| 549 | + assert!(off_page.contains(&format!("data-live=\"{RUN_BASE}/events\""))); | ||
| 550 | + let rows = get(&fx.app, &format!("{RUN_BASE}?page=2"), tahinli.as_deref()) | ||
| 551 | + .await | ||
| 552 | + .text(); | ||
| 553 | + assert!( | ||
| 554 | + rows.contains(&format!("href=\"{RUN_BASE}/runs/{}?page=2\"", first.number)), | ||
| 555 | + "rows keep the page" | ||
| 556 | + ); | ||
| 488 | } | 557 | } |
| 489 | 558 | ||
| 490 | #[tokio::test] | 559 | #[tokio::test] |
| @@ -1179,14 +1248,14 @@ async fn badge_label_is_trimmed_and_empty_means_absent() { | |||
| 1179 | .await | 1248 | .await |
| 1180 | .text(); | 1249 | .text(); |
| 1181 | assert!( | 1250 | assert!( |
| 1182 | - empty.contains(">ci</text>"), | 1251 | + empty.contains(">build</text>"), |
| 1183 | "empty label is absent: {empty}" | 1252 | "empty label is absent: {empty}" |
| 1184 | ); | 1253 | ); |
| 1185 | let blank = get(&fx.app, &format!("{path}?label=%20%20"), reader.as_deref()) | 1254 | let blank = get(&fx.app, &format!("{path}?label=%20%20"), reader.as_deref()) |
| 1186 | .await | 1255 | .await |
| 1187 | .text(); | 1256 | .text(); |
| 1188 | assert!( | 1257 | assert!( |
| 1189 | - blank.contains(">ci</text>"), | 1258 | + blank.contains(">build</text>"), |
| 1190 | "blank label is absent: {blank}" | 1259 | "blank label is absent: {blank}" |
| 1191 | ); | 1260 | ); |
| 1192 | } | 1261 | } |
| @@ -1210,7 +1279,7 @@ async fn badge_label_is_escaped() { | |||
| 1210 | } | 1279 | } |
| 1211 | 1280 | ||
| 1212 | #[tokio::test] | 1281 | #[tokio::test] |
| 1213 | -async fn badge_label_defaults_to_ci_without_a_usable_workflow_name() { | 1282 | +async fn badge_label_defaults_to_build_without_a_usable_workflow_name() { |
| 1214 | let dir = tempfile::tempdir().expect("tempdir"); | 1283 | let dir = tempfile::tempdir().expect("tempdir"); |
| 1215 | let fx = fixture(dir.path()).await; | 1284 | let fx = fixture(dir.path()).await; |
| 1216 | let bare = repo_path(&fx.data_dir, &fx.repo.id).expect("repo path"); | 1285 | let bare = repo_path(&fx.data_dir, &fx.repo.id).expect("repo path"); |
| @@ -1225,18 +1294,18 @@ async fn badge_label_defaults_to_ci_without_a_usable_workflow_name() { | |||
| 1225 | let svg = get(&fx.app, "/tahinli/proj/badge.svg", reader.as_deref()) | 1294 | let svg = get(&fx.app, "/tahinli/proj/badge.svg", reader.as_deref()) |
| 1226 | .await | 1295 | .await |
| 1227 | .text(); | 1296 | .text(); |
| 1228 | - assert!(svg.contains(">ci</text>"), "{svg}"); | 1297 | + assert!(svg.contains(">build</text>"), "{svg}"); |
| 1229 | } | 1298 | } |
| 1230 | 1299 | ||
| 1231 | #[tokio::test] | 1300 | #[tokio::test] |
| 1232 | -async fn badge_without_any_run_uses_the_label_or_ci() { | 1301 | +async fn badge_without_any_run_uses_the_label_or_build() { |
| 1233 | let dir = tempfile::tempdir().expect("tempdir"); | 1302 | let dir = tempfile::tempdir().expect("tempdir"); |
| 1234 | let fx = fixture(dir.path()).await; | 1303 | let fx = fixture(dir.path()).await; |
| 1235 | let reader = Some(cookie_for("dave-token")); | 1304 | let reader = Some(cookie_for("dave-token")); |
| 1236 | let plain = get(&fx.app, "/tahinli/proj/badge.svg", reader.as_deref()) | 1305 | let plain = get(&fx.app, "/tahinli/proj/badge.svg", reader.as_deref()) |
| 1237 | .await | 1306 | .await |
| 1238 | .text(); | 1307 | .text(); |
| 1239 | - assert!(plain.contains(">ci</text>"), "{plain}"); | 1308 | + assert!(plain.contains(">build</text>"), "{plain}"); |
| 1240 | assert!(plain.contains(">no status</text>")); | 1309 | assert!(plain.contains(">no status</text>")); |
| 1241 | let labelled = get( | 1310 | let labelled = get( |
| 1242 | &fx.app, | 1311 | &fx.app, |
| @@ -1248,40 +1317,3 @@ async fn badge_without_any_run_uses_the_label_or_ci() { | |||
| 1248 | assert!(labelled.contains(">Nightly</text>"), "{labelled}"); | 1317 | assert!(labelled.contains(">Nightly</text>"), "{labelled}"); |
| 1249 | assert!(labelled.contains(">no status</text>")); | 1318 | assert!(labelled.contains(">no status</text>")); |
| 1250 | } | 1319 | } |
| 1251 | - | ||
| 1252 | -/// Stage depths of a run's jobs, from `(name, needs)` pairs in job order. | ||
| 1253 | -fn depths_of(jobs: &[(&str, &[&str])]) -> Vec<usize> { | ||
| 1254 | - let owned: Vec<(&str, Vec<String>)> = jobs | ||
| 1255 | - .iter() | ||
| 1256 | - .map(|(name, needs)| (*name, needs.iter().map(|n| n.to_string()).collect())) | ||
| 1257 | - .collect(); | ||
| 1258 | - let named: Vec<(&str, &[String])> = owned | ||
| 1259 | - .iter() | ||
| 1260 | - .map(|(name, needs)| (*name, needs.as_slice())) | ||
| 1261 | - .collect(); | ||
| 1262 | - crate::pages::ci_runs::stage_depths(&named) | ||
| 1263 | -} | ||
| 1264 | - | ||
| 1265 | -#[test] | ||
| 1266 | -fn stage_depths_follow_the_longest_chain_of_needs() { | ||
| 1267 | - // A chain, a job with two needs one stage past the deeper one, and jobs with no needs. | ||
| 1268 | - let depths = depths_of(&[ | ||
| 1269 | - ("lint", &[]), | ||
| 1270 | - ("build", &[]), | ||
| 1271 | - ("test", &["build"]), | ||
| 1272 | - ("docs", &["lint"]), | ||
| 1273 | - ("deploy", &["test", "lint"]), | ||
| 1274 | - ]); | ||
| 1275 | - assert_eq!(depths, vec![0, 0, 1, 1, 2]); | ||
| 1276 | - // A job that needs a job which needs a job sits two stages down. | ||
| 1277 | - let chain = depths_of(&[("c", &["b"]), ("b", &["a"]), ("a", &[])]); | ||
| 1278 | - assert_eq!(chain, vec![2, 1, 0]); | ||
| 1279 | -} | ||
| 1280 | - | ||
| 1281 | -#[test] | ||
| 1282 | -fn stage_depths_ignore_unknown_needs_and_survive_cycles() { | ||
| 1283 | - assert_eq!(depths_of(&[("a", &["ghost"])]), vec![0]); | ||
| 1284 | - // Config parsing refuses cycles. The walk must still end. | ||
| 1285 | - let cycle = depths_of(&[("a", &["b"]), ("b", &["a"])]); | ||
| 1286 | - assert_eq!(cycle.len(), 2); | ||
| 1287 | -} | ||
crates/forge-web/src/pages/profile.rsmodified+32 -4
| @@ -357,6 +357,12 @@ async fn profile_card( | |||
| 357 | }; | 357 | }; |
| 358 | let has_cards = !cards.is_empty(); | 358 | let has_cards = !cards.is_empty(); |
| 359 | let edit_label = mi::t(lang, MK::EditProfile); | 359 | let edit_label = mi::t(lang, MK::EditProfile); |
| 360 | + // The display name is the heading when set; the username then moves under it. | ||
| 361 | + let has_name = user.display_name.is_some(); | ||
| 362 | + let heading = user | ||
| 363 | + .display_name | ||
| 364 | + .clone() | ||
| 365 | + .unwrap_or_else(|| user.username.clone()); | ||
| 360 | let filter_label = g::t(lang, K::FilterRepos); | 366 | let filter_label = g::t(lang, K::FilterRepos); |
| 361 | let Listing { | 367 | let Listing { |
| 362 | rows, | 368 | rows, |
| @@ -376,19 +382,22 @@ async fn profile_card( | |||
| 376 | <header class="profile-head"> | 382 | <header class="profile-head"> |
| 377 | <img class="profile-avatar" src=(src) alt="" width="256" height="256"> | 383 | <img class="profile-avatar" src=(src) alt="" width="256" height="256"> |
| 378 | <div class="profile-id"> | 384 | <div class="profile-id"> |
| 379 | - <h1>(user.username.as_str())</h1> | 385 | + <h1>(heading)</h1> |
| 386 | + if has_name { | ||
| 387 | + <p class="muted">(user.username.as_str())</p> | ||
| 388 | + } | ||
| 380 | if is_org { | 389 | if is_org { |
| 381 | <p class="muted small">(g::t(lang, K::Organization))</p> | 390 | <p class="muted small">(g::t(lang, K::Organization))</p> |
| 382 | } | 391 | } |
| 383 | <p class="muted">(g::t(lang, K::LocalTime)) (local_time.as_str())</p> | 392 | <p class="muted">(g::t(lang, K::LocalTime)) (local_time.as_str())</p> |
| 393 | + if edit_profile { | ||
| 394 | + <a class="button profile-edit" href="/settings/profile">(edit_label)</a> | ||
| 395 | + } | ||
| 384 | </div> | 396 | </div> |
| 385 | </header> | 397 | </header> |
| 386 | if has_about { | 398 | if has_about { |
| 387 | <section class="profile-about markdown-body">(Unescaped::new_unchecked(about_html))</section> | 399 | <section class="profile-about markdown-body">(Unescaped::new_unchecked(about_html))</section> |
| 388 | } | 400 | } |
| 389 | - if edit_profile { | ||
| 390 | - <a class="button profile-edit" href="/settings/profile">(edit_label)</a> | ||
| 391 | - } | ||
| 392 | <nav class="profile-tabs" aria-label=(user.username.as_str())> | 401 | <nav class="profile-tabs" aria-label=(user.username.as_str())> |
| 393 | <a class=(tab_class(overview_on)) href=(overview_href.as_str())>(g::t(lang, K::TabOverview))</a> | 402 | <a class=(tab_class(overview_on)) href=(overview_href.as_str())>(g::t(lang, K::TabOverview))</a> |
| 394 | <a class=(tab_class(repos_on)) href=(repositories_href.as_str())> | 403 | <a class=(tab_class(repos_on)) href=(repositories_href.as_str())> |
| @@ -811,6 +820,25 @@ mod tests { | |||
| 811 | assert!(!anon.contains("tahinli/secret-repo")); | 820 | assert!(!anon.contains("tahinli/secret-repo")); |
| 812 | } | 821 | } |
| 813 | 822 | ||
| 823 | + #[tokio::test] | ||
| 824 | + async fn display_name_is_the_heading_with_the_username_below() { | ||
| 825 | + let site = seeded().await; | ||
| 826 | + let tahinli = user_id(&site.store, "tahinli").await; | ||
| 827 | + site.store | ||
| 828 | + .set_display_name(&tahinli, "Ahmet Kaan Gümüş") | ||
| 829 | + .await | ||
| 830 | + .unwrap(); | ||
| 831 | + let (status, body) = get(&site.router, "/tahinli", None).await; | ||
| 832 | + assert_eq!(status, 200); | ||
| 833 | + assert!(body.contains("<h1>Ahmet Kaan Gümüş</h1>"), "{body}"); | ||
| 834 | + assert!(body.contains("<p class=\"muted\">tahinli</p>"), "{body}"); | ||
| 835 | + | ||
| 836 | + site.store.set_display_name(&tahinli, " ").await.unwrap(); | ||
| 837 | + let (_, body) = get(&site.router, "/tahinli", None).await; | ||
| 838 | + assert!(body.contains("<h1>tahinli</h1>"), "{body}"); | ||
| 839 | + assert!(!body.contains("<p class=\"muted\">tahinli</p>"), "{body}"); | ||
| 840 | + } | ||
| 841 | + | ||
| 814 | #[tokio::test] | 842 | #[tokio::test] |
| 815 | async fn only_the_owner_sees_the_edit_profile_button() { | 843 | async fn only_the_owner_sees_the_edit_profile_button() { |
| 816 | let site = seeded().await; | 844 | let site = seeded().await; |
crates/forge-web/src/pages/settings_appearance.rsmodified+72 -13
| @@ -1,11 +1,11 @@ | |||
| 1 | -//! Page: appearance (`/settings/appearance`). The colour theme and the language, both stored per | 1 | +//! Page: appearance (`/settings/appearance`). The colour theme, the accent colour and the language, |
| 2 | -//! user. Anonymous visitors set the theme from the footer instead (see `pages/theme_cookie.rs`). | 2 | +//! all stored per user. Anonymous visitors set the theme from the footer instead (see `pages/theme_cookie.rs`). |
| 3 | //! Every POST checks the CSRF token first. | 3 | //! Every POST checks the CSRF token first. |
| 4 | 4 | ||
| 5 | use forge_core::AuditAction; | 5 | use forge_core::AuditAction; |
| 6 | use forge_core::store::ui_prefs::THEMES; | 6 | use forge_core::store::ui_prefs::THEMES; |
| 7 | use forge_core::{Error as CoreError, Session, Store, User}; | 7 | use forge_core::{Error as CoreError, Session, Store, User}; |
| 8 | -use serde::Deserialize; | 8 | +use serde::{Deserialize, Deserializer}; |
| 9 | use topcoat::Result; | 9 | use topcoat::Result; |
| 10 | use topcoat::context::{Cx, app_context}; | 10 | use topcoat::context::{Cx, app_context}; |
| 11 | use topcoat::router::content::Form; | 11 | use topcoat::router::content::Form; |
| @@ -13,8 +13,10 @@ use topcoat::router::error::{SeeOther, see_other}; | |||
| 13 | use topcoat::router::{page, query_params, route}; | 13 | use topcoat::router::{page, query_params, route}; |
| 14 | use topcoat::view::{View, component, view}; | 14 | use topcoat::view::{View, component, view}; |
| 15 | 15 | ||
| 16 | +use crate::accent; | ||
| 16 | use crate::audit::{self, Actor, Target}; | 17 | use crate::audit::{self, Actor, Target}; |
| 17 | use crate::auth::{require_csrf, require_user}; | 18 | use crate::auth::{require_csrf, require_user}; |
| 19 | +use crate::i18n::accents::accent_name; | ||
| 18 | use crate::i18n::misc::{self as g, K}; | 20 | use crate::i18n::misc::{self as g, K}; |
| 19 | use crate::i18n::{self, Key, Lang}; | 21 | use crate::i18n::{self, Key, Lang}; |
| 20 | use crate::state::AppState; | 22 | use crate::state::AppState; |
| @@ -32,12 +34,24 @@ struct AppearanceQuery { | |||
| 32 | saved: Option<String>, | 34 | saved: Option<String>, |
| 33 | } | 35 | } |
| 34 | 36 | ||
| 37 | +/// Reads a field that is present as a string, even an empty one. The plain `Option<String>` | ||
| 38 | +/// reading would turn an empty value into `None`, which is the same as a missing field. | ||
| 39 | +fn present_string<'de, D: Deserializer<'de>>( | ||
| 40 | + de: D, | ||
| 41 | +) -> std::result::Result<Option<String>, D::Error> { | ||
| 42 | + String::deserialize(de).map(Some) | ||
| 43 | +} | ||
| 44 | + | ||
| 35 | #[derive(Deserialize)] | 45 | #[derive(Deserialize)] |
| 36 | struct AppearanceForm { | 46 | struct AppearanceForm { |
| 37 | #[serde(default)] | 47 | #[serde(default)] |
| 38 | csrf: String, | 48 | csrf: String, |
| 39 | #[serde(default)] | 49 | #[serde(default)] |
| 40 | theme: String, | 50 | theme: String, |
| 51 | + /// Optional so a form loaded before the accent picker existed still saves. When absent, | ||
| 52 | + /// the stored accent is kept. A present but empty value stays `Some("")` and is rejected. | ||
| 53 | + #[serde(default, deserialize_with = "present_string")] | ||
| 54 | + accent: Option<String>, | ||
| 41 | #[serde(default)] | 55 | #[serde(default)] |
| 42 | language: String, | 56 | language: String, |
| 43 | } | 57 | } |
| @@ -52,6 +66,7 @@ struct AppearancePage { | |||
| 52 | lang: Lang, | 66 | lang: Lang, |
| 53 | csrf: String, | 67 | csrf: String, |
| 54 | theme: Vec<Choice>, | 68 | theme: Vec<Choice>, |
| 69 | + accents: Vec<Choice>, | ||
| 55 | language: Vec<Choice>, | 70 | language: Vec<Choice>, |
| 56 | notice: Option<&'static str>, | 71 | notice: Option<&'static str>, |
| 57 | } | 72 | } |
| @@ -100,6 +115,7 @@ async fn appearance_body(page: AppearancePage) -> Result<impl View> { | |||
| 100 | lang, | 115 | lang, |
| 101 | csrf, | 116 | csrf, |
| 102 | theme, | 117 | theme, |
| 118 | + accents, | ||
| 103 | language, | 119 | language, |
| 104 | notice, | 120 | notice, |
| 105 | } = page; | 121 | } = page; |
| @@ -126,6 +142,19 @@ async fn appearance_body(page: AppearancePage) -> Result<impl View> { | |||
| 126 | </select> | 142 | </select> |
| 127 | <small class="muted">(g::t(lang, K::MatchSystemHelp))</small> | 143 | <small class="muted">(g::t(lang, K::MatchSystemHelp))</small> |
| 128 | </label> | 144 | </label> |
| 145 | + <fieldset class="accent-picker"> | ||
| 146 | + <legend>(g::t(lang, K::AccentLabel))</legend> | ||
| 147 | + <div class="accent-choices"> | ||
| 148 | + for choice in accents.into_iter() { | ||
| 149 | + <label class="accent-choice"> | ||
| 150 | + <input type="radio" name="accent" value=(choice.value) checked=(choice.selected)> | ||
| 151 | + <span class="accent-swatch" data-accent-swatch=(choice.value) aria-hidden="true"></span> | ||
| 152 | + <span>(choice.label)</span> | ||
| 153 | + </label> | ||
| 154 | + } | ||
| 155 | + </div> | ||
| 156 | + <small class="muted">(g::t(lang, K::AccentHelp))</small> | ||
| 157 | + </fieldset> | ||
| 129 | <label> | 158 | <label> |
| 130 | <span>(g::t(lang, K::LanguageLabel))</span> | 159 | <span>(g::t(lang, K::LanguageLabel))</span> |
| 131 | <select name="language"> | 160 | <select name="language"> |
| @@ -141,11 +170,19 @@ async fn appearance_body(page: AppearancePage) -> Result<impl View> { | |||
| 141 | }) | 170 | }) |
| 142 | } | 171 | } |
| 143 | 172 | ||
| 144 | -/// Rejects a theme or language that is not offered. Nothing is saved for either. | 173 | +/// Rejects a theme, accent or language that is not offered. Nothing is saved for any of them. |
| 145 | -fn check_choice(lang: Lang, theme: &str, language: &str) -> forge_core::Result<()> { | 174 | +fn check_choice( |
| 175 | + lang: Lang, | ||
| 176 | + theme: &str, | ||
| 177 | + accent_id: &str, | ||
| 178 | + language: &str, | ||
| 179 | +) -> forge_core::Result<()> { | ||
| 146 | if !THEMES.contains(&theme) { | 180 | if !THEMES.contains(&theme) { |
| 147 | return Err(CoreError::Invalid(g::t(lang, K::ChooseTheme).into())); | 181 | return Err(CoreError::Invalid(g::t(lang, K::ChooseTheme).into())); |
| 148 | } | 182 | } |
| 183 | + if !accent::is_offered(accent_id) { | ||
| 184 | + return Err(CoreError::Invalid(g::t(lang, K::ChooseAccent).into())); | ||
| 185 | + } | ||
| 149 | if !LANGUAGE_CODES.contains(&language) { | 186 | if !LANGUAGE_CODES.contains(&language) { |
| 150 | return Err(CoreError::Invalid(g::t(lang, K::ChooseLanguage).into())); | 187 | return Err(CoreError::Invalid(g::t(lang, K::ChooseLanguage).into())); |
| 151 | } | 188 | } |
| @@ -159,12 +196,14 @@ fn notice_for(lang: Lang, saved: Option<&str>) -> Option<&'static str> { | |||
| 159 | } | 196 | } |
| 160 | } | 197 | } |
| 161 | 198 | ||
| 162 | -/// Builds the page for a viewer. `theme` and `language` are the stored values. | 199 | +/// Builds the page for a viewer. The theme, accent and language are the stored values. |
| 163 | fn page_for(viewer: &(User, Session), lang: Lang, notice: Option<&'static str>) -> AppearancePage { | 200 | fn page_for(viewer: &(User, Session), lang: Lang, notice: Option<&'static str>) -> AppearancePage { |
| 201 | + let accent_codes: Vec<&'static str> = accent::ids().collect(); | ||
| 164 | AppearancePage { | 202 | AppearancePage { |
| 165 | lang, | 203 | lang, |
| 166 | csrf: viewer.1.csrf_token.clone(), | 204 | csrf: viewer.1.csrf_token.clone(), |
| 167 | theme: choices(THEME_CODES, &viewer.0.theme, |code| theme_label(lang, code)), | 205 | theme: choices(THEME_CODES, &viewer.0.theme, |code| theme_label(lang, code)), |
| 206 | + accents: choices(&accent_codes, &viewer.0.accent, |id| accent_name(lang, id)), | ||
| 168 | language: choices(LANGUAGE_CODES, &viewer.0.language, |code| { | 207 | language: choices(LANGUAGE_CODES, &viewer.0.language, |code| { |
| 169 | language_label(lang, code) | 208 | language_label(lang, code) |
| 170 | }), | 209 | }), |
| @@ -189,10 +228,14 @@ async fn appearance_save(cx: &Cx, Form(form): Form<AppearanceForm>) -> Result<Se | |||
| 189 | let lang = i18n::lang(cx, Some(&viewer.0)); | 228 | let lang = i18n::lang(cx, Some(&viewer.0)); |
| 190 | let store: &Store = &app_context::<AppState>(cx).store; | 229 | let store: &Store = &app_context::<AppState>(cx).store; |
| 191 | 230 | ||
| 192 | - check_choice(lang, &form.theme, &form.language)?; | 231 | + let accent = form.accent.as_deref().unwrap_or(&viewer.0.accent); |
| 232 | + check_choice(lang, &form.theme, accent, &form.language)?; | ||
| 193 | store | 233 | store |
| 194 | .set_ui_prefs(&viewer.0.id, &form.theme, &form.language) | 234 | .set_ui_prefs(&viewer.0.id, &form.theme, &form.language) |
| 195 | .await?; | 235 | .await?; |
| 236 | + if form.accent.is_some() { | ||
| 237 | + store.set_accent(&viewer.0.id, accent).await?; | ||
| 238 | + } | ||
| 196 | audit::record( | 239 | audit::record( |
| 197 | store, | 240 | store, |
| 198 | Some(cx), | 241 | Some(cx), |
| @@ -203,7 +246,7 @@ async fn appearance_save(cx: &Cx, Form(form): Form<AppearanceForm>) -> Result<Se | |||
| 203 | id: &viewer.0.id, | 246 | id: &viewer.0.id, |
| 204 | name: &viewer.0.username, | 247 | name: &viewer.0.username, |
| 205 | }, | 248 | }, |
| 206 | - serde_json::json!({ "theme": form.theme, "language": form.language }), | 249 | + serde_json::json!({ "theme": form.theme, "accent": accent, "language": form.language }), |
| 207 | ) | 250 | ) |
| 208 | .await; | 251 | .await; |
| 209 | Ok(see_other("/settings/appearance?saved=1")) | 252 | Ok(see_other("/settings/appearance?saved=1")) |
| @@ -215,11 +258,14 @@ mod tests { | |||
| 215 | 258 | ||
| 216 | #[test] | 259 | #[test] |
| 217 | fn only_offered_choices_pass() { | 260 | fn only_offered_choices_pass() { |
| 218 | - assert!(check_choice(Lang::En, "dark", "tr").is_ok()); | 261 | + assert!(check_choice(Lang::En, "dark", "ocean", "tr").is_ok()); |
| 219 | - assert!(check_choice(Lang::Tr, "auto", "auto").is_ok()); | 262 | + assert!(check_choice(Lang::Tr, "auto", "sage", "auto").is_ok()); |
| 220 | - assert!(check_choice(Lang::En, "neon", "en").is_err()); | 263 | + assert!(check_choice(Lang::En, "neon", "sage", "en").is_err()); |
| 221 | - assert!(check_choice(Lang::En, "light", "de").is_err()); | 264 | + assert!(check_choice(Lang::En, "light", "neon", "en").is_err()); |
| 222 | - assert!(check_choice(Lang::Tr, "light", "").is_err()); | 265 | + assert!(check_choice(Lang::En, "light", "Ocean", "en").is_err()); |
| 266 | + assert!(check_choice(Lang::En, "light", "", "en").is_err()); | ||
| 267 | + assert!(check_choice(Lang::En, "light", "sage", "de").is_err()); | ||
| 268 | + assert!(check_choice(Lang::Tr, "light", "sage", "").is_err()); | ||
| 223 | } | 269 | } |
| 224 | 270 | ||
| 225 | #[test] | 271 | #[test] |
| @@ -233,6 +279,19 @@ mod tests { | |||
| 233 | assert_eq!(selected, ["dark"]); | 279 | assert_eq!(selected, ["dark"]); |
| 234 | } | 280 | } |
| 235 | 281 | ||
| 282 | + #[test] | ||
| 283 | + fn the_stored_accent_is_selected() { | ||
| 284 | + let codes: Vec<&'static str> = accent::ids().collect(); | ||
| 285 | + let options = choices(&codes, "plum", |id| accent_name(Lang::En, id)); | ||
| 286 | + let selected: Vec<&str> = options | ||
| 287 | + .iter() | ||
| 288 | + .filter(|c| c.selected) | ||
| 289 | + .map(|c| c.value) | ||
| 290 | + .collect(); | ||
| 291 | + assert_eq!(selected, ["plum"]); | ||
| 292 | + assert_eq!(options[0].value, crate::accent_palette::DEFAULT); | ||
| 293 | + } | ||
| 294 | + | ||
| 236 | #[test] | 295 | #[test] |
| 237 | fn labels_follow_the_page_language() { | 296 | fn labels_follow_the_page_language() { |
| 238 | assert_eq!(theme_label(Lang::En, "dark"), "Dark"); | 297 | assert_eq!(theme_label(Lang::En, "dark"), "Dark"); |
crates/forge-web/src/pages/settings_profile.rsmodified+114 -8
| @@ -1,9 +1,10 @@ | |||
| 1 | -//! Page: public profile (`/settings/profile`). One form saves the username capitalization, the | 1 | +//! Page: public profile (`/settings/profile`). One form saves the display name, the username |
| 2 | -//! "about" text and the timezone. The avatar menu beside it posts to its own upload and removal | 2 | +//! capitalization, the "about" text and the timezone. The avatar menu beside it posts to its own upload and removal |
| 3 | //! routes. Every POST checks the CSRF token first. | 3 | //! routes. Every POST checks the CSRF token first. |
| 4 | 4 | ||
| 5 | use forge_core::AuditAction; | 5 | use forge_core::AuditAction; |
| 6 | use forge_core::names::capitalization_change; | 6 | use forge_core::names::capitalization_change; |
| 7 | +use forge_core::store::MAX_DISPLAY_NAME_CHARS; | ||
| 7 | use forge_core::tz::{all_timezones, validate_timezone}; | 8 | use forge_core::tz::{all_timezones, validate_timezone}; |
| 8 | use forge_core::{Session, Store, User, avatar::MAX_UPLOAD_BYTES, avatar::process_avatar}; | 9 | use forge_core::{Session, Store, User, avatar::MAX_UPLOAD_BYTES, avatar::process_avatar}; |
| 9 | use serde::Deserialize; | 10 | use serde::Deserialize; |
| @@ -17,7 +18,7 @@ use topcoat::view::{View, component, view}; | |||
| 17 | 18 | ||
| 18 | use crate::audit::{self, Actor, Target}; | 19 | use crate::audit::{self, Actor, Target}; |
| 19 | use crate::auth::{require_csrf, require_user}; | 20 | use crate::auth::{require_csrf, require_user}; |
| 20 | -use crate::i18n::{self, Key, Lang, about_too_long, t}; | 21 | +use crate::i18n::{self, Key, Lang, about_too_long, display_name_too_long, t}; |
| 21 | use crate::state::AppState; | 22 | use crate::state::AppState; |
| 22 | use crate::views::{alert, avatar_url, shell, user_facing_message}; | 23 | use crate::views::{alert, avatar_url, shell, user_facing_message}; |
| 23 | 24 | ||
| @@ -37,12 +38,14 @@ struct ProfileQuery { | |||
| 37 | saved: Option<String>, | 38 | saved: Option<String>, |
| 38 | } | 39 | } |
| 39 | 40 | ||
| 40 | -/// The one profile form: username, about and timezone. | 41 | +/// The one profile form: display name, username, about and timezone. |
| 41 | #[derive(Deserialize)] | 42 | #[derive(Deserialize)] |
| 42 | struct ProfileForm { | 43 | struct ProfileForm { |
| 43 | #[serde(default)] | 44 | #[serde(default)] |
| 44 | csrf: String, | 45 | csrf: String, |
| 45 | #[serde(default)] | 46 | #[serde(default)] |
| 47 | + display_name: String, | ||
| 48 | + #[serde(default)] | ||
| 46 | username: String, | 49 | username: String, |
| 47 | #[serde(default)] | 50 | #[serde(default)] |
| 48 | about: String, | 51 | about: String, |
| @@ -58,6 +61,7 @@ struct CsrfForm { | |||
| 58 | 61 | ||
| 59 | /// Values shown in the forms. On a failed POST these are what the user typed. | 62 | /// Values shown in the forms. On a failed POST these are what the user typed. |
| 60 | struct Draft { | 63 | struct Draft { |
| 64 | + display_name: String, | ||
| 61 | username: String, | 65 | username: String, |
| 62 | about: String, | 66 | about: String, |
| 63 | timezone: String, | 67 | timezone: String, |
| @@ -66,6 +70,7 @@ struct Draft { | |||
| 66 | impl Draft { | 70 | impl Draft { |
| 67 | fn from_user(user: &User) -> Self { | 71 | fn from_user(user: &User) -> Self { |
| 68 | Self { | 72 | Self { |
| 73 | + display_name: user.display_name.clone().unwrap_or_default(), | ||
| 69 | username: user.username.clone(), | 74 | username: user.username.clone(), |
| 70 | about: user.about.clone(), | 75 | about: user.about.clone(), |
| 71 | timezone: user.timezone.clone(), | 76 | timezone: user.timezone.clone(), |
| @@ -76,6 +81,7 @@ impl Draft { | |||
| 76 | /// Per-field error messages, shown under the field they belong to. | 81 | /// Per-field error messages, shown under the field they belong to. |
| 77 | #[derive(Default)] | 82 | #[derive(Default)] |
| 78 | struct Errors { | 83 | struct Errors { |
| 84 | + display_name: Option<String>, | ||
| 79 | username: Option<String>, | 85 | username: Option<String>, |
| 80 | about: Option<String>, | 86 | about: Option<String>, |
| 81 | timezone: Option<String>, | 87 | timezone: Option<String>, |
| @@ -86,7 +92,10 @@ impl Errors { | |||
| 86 | /// True when no profile field has an error. The avatar error does not count: it belongs to | 92 | /// True when no profile field has an error. The avatar error does not count: it belongs to |
| 87 | /// its own upload. | 93 | /// its own upload. |
| 88 | fn profile_is_clear(&self) -> bool { | 94 | fn profile_is_clear(&self) -> bool { |
| 89 | - self.username.is_none() && self.about.is_none() && self.timezone.is_none() | 95 | + self.display_name.is_none() |
| 96 | + && self.username.is_none() | ||
| 97 | + && self.about.is_none() | ||
| 98 | + && self.timezone.is_none() | ||
| 90 | } | 99 | } |
| 91 | } | 100 | } |
| 92 | 101 | ||
| @@ -131,6 +140,14 @@ async fn profile_body(page: ProfilePage) -> Result<impl View> { | |||
| 131 | <div class="profile-settings"> | 140 | <div class="profile-settings"> |
| 132 | <form method="post" action="/settings/profile" class="profile-form"> | 141 | <form method="post" action="/settings/profile" class="profile-form"> |
| 133 | <input type="hidden" name="csrf" value=(csrf.as_str())> | 142 | <input type="hidden" name="csrf" value=(csrf.as_str())> |
| 143 | + <div class="profile-field"> | ||
| 144 | + <label for="profile-display-name">(t(lang, Key::DisplayName))</label> | ||
| 145 | + <input id="profile-display-name" type="text" name="display_name" maxlength="80" autocomplete="name" value=(draft.display_name.as_str()) aria-describedby="profile-display-name-hint"> | ||
| 146 | + <small class="muted" id="profile-display-name-hint">(t(lang, Key::DisplayNameHint))</small> | ||
| 147 | + if let Some(message) = errors.display_name { | ||
| 148 | + alert(message: message.as_str()) | ||
| 149 | + } | ||
| 150 | + </div> | ||
| 134 | <div class="profile-field"> | 151 | <div class="profile-field"> |
| 135 | <label for="profile-username">(t(lang, Key::Username))</label> | 152 | <label for="profile-username">(t(lang, Key::Username))</label> |
| 136 | <input id="profile-username" type="text" name="username" maxlength="64" required=(true) autocomplete="username" value=(draft.username.as_str()) aria-describedby="profile-username-hint"> | 153 | <input id="profile-username" type="text" name="username" maxlength="64" required=(true) autocomplete="username" value=(draft.username.as_str()) aria-describedby="profile-username-hint"> |
| @@ -241,6 +258,24 @@ fn check_about(lang: Lang, about: &str) -> forge_core::Result<()> { | |||
| 241 | Ok(()) | 258 | Ok(()) |
| 242 | } | 259 | } |
| 243 | 260 | ||
| 261 | +/// Checks the display name after trimming: no control characters, at most | ||
| 262 | +/// `MAX_DISPLAY_NAME_CHARS` characters. The store checks it again before writing. | ||
| 263 | +fn check_display_name(lang: Lang, name: &str) -> forge_core::Result<()> { | ||
| 264 | + let name = name.trim(); | ||
| 265 | + if name.chars().any(char::is_control) { | ||
| 266 | + return Err(forge_core::Error::Invalid( | ||
| 267 | + t(lang, Key::ErrDisplayNameControl).into(), | ||
| 268 | + )); | ||
| 269 | + } | ||
| 270 | + if name.chars().count() > MAX_DISPLAY_NAME_CHARS { | ||
| 271 | + return Err(forge_core::Error::Invalid(display_name_too_long( | ||
| 272 | + lang, | ||
| 273 | + MAX_DISPLAY_NAME_CHARS, | ||
| 274 | + ))); | ||
| 275 | + } | ||
| 276 | + Ok(()) | ||
| 277 | +} | ||
| 278 | + | ||
| 244 | /// The message to show under a field whose check failed. An internal failure is not a form | 279 | /// The message to show under a field whose check failed. An internal failure is not a form |
| 245 | /// error, so it propagates as a server error. | 280 | /// error, so it propagates as a server error. |
| 246 | fn field_message(err: forge_core::Error) -> Result<String> { | 281 | fn field_message(err: forge_core::Error) -> Result<String> { |
| @@ -289,9 +324,9 @@ async fn profile_page(cx: &Cx) -> Result<impl View> { | |||
| 289 | }) | 324 | }) |
| 290 | } | 325 | } |
| 291 | 326 | ||
| 292 | -/// Saves the username, the "about" text and the timezone together. Nothing is written unless | 327 | +/// Saves the display name, the username, the "about" text and the timezone together. Nothing is |
| 293 | -/// every field passes, so one bad field keeps the old values for all of them. The username is | 328 | +/// written unless every field passes, so one bad field keeps the old values for all of them. The |
| 294 | -/// written only when its capitalization differs from the stored one. | 329 | +/// username is written only when its capitalization differs from the stored one. |
| 295 | #[page(POST "/settings/profile")] | 330 | #[page(POST "/settings/profile")] |
| 296 | async fn profile_save(cx: &Cx, Form(form): Form<ProfileForm>) -> Result<impl View> { | 331 | async fn profile_save(cx: &Cx, Form(form): Form<ProfileForm>) -> Result<impl View> { |
| 297 | let viewer = require_csrf(cx, &form.csrf).await?; | 332 | let viewer = require_csrf(cx, &form.csrf).await?; |
| @@ -300,6 +335,9 @@ async fn profile_save(cx: &Cx, Form(form): Form<ProfileForm>) -> Result<impl Vie | |||
| 300 | let about = form.about.replace("\r\n", "\n"); | 335 | let about = form.about.replace("\r\n", "\n"); |
| 301 | 336 | ||
| 302 | let mut errors = Errors::default(); | 337 | let mut errors = Errors::default(); |
| 338 | + if let Err(e) = check_display_name(lang, &form.display_name) { | ||
| 339 | + errors.display_name = Some(field_message(e)?); | ||
| 340 | + } | ||
| 303 | let display = match capitalization_change(&viewer.0.username, &form.username) { | 341 | let display = match capitalization_change(&viewer.0.username, &form.username) { |
| 304 | Ok(display) => Some(display), | 342 | Ok(display) => Some(display), |
| 305 | Err(e) => { | 343 | Err(e) => { |
| @@ -318,6 +356,7 @@ async fn profile_save(cx: &Cx, Form(form): Form<ProfileForm>) -> Result<impl Vie | |||
| 318 | Some(display) if errors.profile_is_clear() => display, | 356 | Some(display) if errors.profile_is_clear() => display, |
| 319 | _ => { | 357 | _ => { |
| 320 | let draft = Draft { | 358 | let draft = Draft { |
| 359 | + display_name: form.display_name, | ||
| 321 | username: form.username, | 360 | username: form.username, |
| 322 | about, | 361 | about, |
| 323 | timezone: form.timezone, | 362 | timezone: form.timezone, |
| @@ -332,6 +371,9 @@ async fn profile_save(cx: &Cx, Form(form): Form<ProfileForm>) -> Result<impl Vie | |||
| 332 | store | 371 | store |
| 333 | .set_profile(&viewer.0.id, &about, &form.timezone) | 372 | .set_profile(&viewer.0.id, &about, &form.timezone) |
| 334 | .await?; | 373 | .await?; |
| 374 | + store | ||
| 375 | + .set_display_name(&viewer.0.id, &form.display_name) | ||
| 376 | + .await?; | ||
| 335 | if display != viewer.0.username { | 377 | if display != viewer.0.username { |
| 336 | store.set_username_display(&viewer.0.id, &display).await?; | 378 | store.set_username_display(&viewer.0.id, &display).await?; |
| 337 | audit::record( | 379 | audit::record( |
| @@ -678,6 +720,70 @@ pub(crate) mod tests { | |||
| 678 | assert_eq!(stored.about, ""); | 720 | assert_eq!(stored.about, ""); |
| 679 | } | 721 | } |
| 680 | 722 | ||
| 723 | + #[tokio::test] | ||
| 724 | + async fn display_name_saves_shows_in_the_field_and_blank_clears_it() { | ||
| 725 | + let fx = fixture().await; | ||
| 726 | + let form = format!( | ||
| 727 | + "csrf={CSRF}&display_name=+Ahmet+Kaan+G%C3%BCm%C3%BC%C5%9F+&username=tahinli&about=&timezone=UTC" | ||
| 728 | + ); | ||
| 729 | + let (status, location, _) = | ||
| 730 | + send(&fx.router, "POST", "/settings/profile", true, Some(&form)).await; | ||
| 731 | + assert_eq!(status, 303); | ||
| 732 | + assert_eq!(location.as_deref(), Some("/settings/profile?saved=1")); | ||
| 733 | + let stored = fx.store.user_by_id(&fx.user.id).await.unwrap().unwrap(); | ||
| 734 | + assert_eq!(stored.display_name.as_deref(), Some("Ahmet Kaan Gümüş")); | ||
| 735 | + | ||
| 736 | + let (status, _, body) = send(&fx.router, "GET", "/settings/profile", true, None).await; | ||
| 737 | + assert_eq!(status, 200); | ||
| 738 | + assert!( | ||
| 739 | + body.contains(r#"name="display_name""#) && body.contains("Ahmet Kaan Gümüş"), | ||
| 740 | + "{body}" | ||
| 741 | + ); | ||
| 742 | + | ||
| 743 | + let blank = format!("csrf={CSRF}&display_name=+++&username=tahinli&about=&timezone=UTC"); | ||
| 744 | + let (status, _, _) = | ||
| 745 | + send(&fx.router, "POST", "/settings/profile", true, Some(&blank)).await; | ||
| 746 | + assert_eq!(status, 303); | ||
| 747 | + let stored = fx.store.user_by_id(&fx.user.id).await.unwrap().unwrap(); | ||
| 748 | + assert_eq!(stored.display_name, None); | ||
| 749 | + } | ||
| 750 | + | ||
| 751 | + #[tokio::test] | ||
| 752 | + async fn a_bad_display_name_is_rejected_and_nothing_is_saved() { | ||
| 753 | + let fx = fixture().await; | ||
| 754 | + let long = "x".repeat(81); | ||
| 755 | + let form = | ||
| 756 | + format!("csrf={CSRF}&display_name={long}&username=tahinli&about=kept&timezone=UTC"); | ||
| 757 | + let (status, location, body) = | ||
| 758 | + send(&fx.router, "POST", "/settings/profile", true, Some(&form)).await; | ||
| 759 | + assert_eq!(status, 200); | ||
| 760 | + assert!(location.is_none()); | ||
| 761 | + assert!( | ||
| 762 | + body.contains("The name must be at most 80 characters."), | ||
| 763 | + "{body}" | ||
| 764 | + ); | ||
| 765 | + // A bad name holds back the valid "about" text too. | ||
| 766 | + let stored = fx.store.user_by_id(&fx.user.id).await.unwrap().unwrap(); | ||
| 767 | + assert_eq!(stored.display_name, None); | ||
| 768 | + assert_eq!(stored.about, ""); | ||
| 769 | + | ||
| 770 | + let control = | ||
| 771 | + format!("csrf={CSRF}&display_name=two%0Alines&username=tahinli&about=&timezone=UTC"); | ||
| 772 | + let (status, _, body) = send( | ||
| 773 | + &fx.router, | ||
| 774 | + "POST", | ||
| 775 | + "/settings/profile", | ||
| 776 | + true, | ||
| 777 | + Some(&control), | ||
| 778 | + ) | ||
| 779 | + .await; | ||
| 780 | + assert_eq!(status, 200); | ||
| 781 | + assert!( | ||
| 782 | + body.contains("The name must not contain line breaks or control characters."), | ||
| 783 | + "{body}" | ||
| 784 | + ); | ||
| 785 | + } | ||
| 786 | + | ||
| 681 | #[tokio::test] | 787 | #[tokio::test] |
| 682 | async fn profile_post_without_csrf_is_rejected() { | 788 | async fn profile_post_without_csrf_is_rejected() { |
| 683 | let fx = fixture().await; | 789 | let fx = fixture().await; |
crates/forge-web/src/pages/settings_security.rsmodified+559 -149
| @@ -4,7 +4,9 @@ | |||
| 4 | 4 | ||
| 5 | use std::time::{Duration, Instant}; | 5 | use std::time::{Duration, Instant}; |
| 6 | 6 | ||
| 7 | +use forge_core::mail::MailKind; | ||
| 7 | use forge_core::names::normalize_name; | 8 | use forge_core::names::normalize_name; |
| 9 | +use forge_core::time::stamp_to_unix; | ||
| 8 | use forge_core::totp; | 10 | use forge_core::totp; |
| 9 | use forge_core::{AuditAction, Session, User, secret}; | 11 | use forge_core::{AuditAction, Session, User, secret}; |
| 10 | use http::header::{HeaderValue, RETRY_AFTER}; | 12 | use http::header::{HeaderValue, RETRY_AFTER}; |
| @@ -21,16 +23,20 @@ use crate::auth::{ | |||
| 21 | hash_password_async, logout, require_csrf, require_user, two_factor_enabled, unix_now, | 23 | hash_password_async, logout, require_csrf, require_user, two_factor_enabled, unix_now, |
| 22 | verify_password_async, verify_second_factor, | 24 | verify_password_async, verify_second_factor, |
| 23 | }; | 25 | }; |
| 24 | -use crate::i18n::{self, Key, Lang, password_too_long, password_too_short, t, two_factor_on_line}; | 26 | +use crate::i18n::{self, Key, Lang, password_too_long, password_too_short, t}; |
| 25 | use crate::state::AppState; | 27 | use crate::state::AppState; |
| 26 | use crate::throttle::{self, LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT}; | 28 | use crate::throttle::{self, LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT}; |
| 27 | -use crate::views::{alert, shell, user_facing_message}; | 29 | +use crate::views::{alert, relative_time, shell, user_facing_message}; |
| 28 | 30 | ||
| 29 | /// Shortest and longest new passwords, in characters. | 31 | /// Shortest and longest new passwords, in characters. |
| 30 | const MIN_PASSWORD_CHARS: usize = 10; | 32 | const MIN_PASSWORD_CHARS: usize = 10; |
| 31 | const MAX_PASSWORD_CHARS: usize = 1024; | 33 | const MAX_PASSWORD_CHARS: usize = 1024; |
| 32 | /// Recovery codes issued by each enrollment or regeneration. | 34 | /// Recovery codes issued by each enrollment or regeneration. |
| 33 | const RECOVERY_CODE_COUNT: usize = 10; | 35 | const RECOVERY_CODE_COUNT: usize = 10; |
| 36 | +/// At or below this many unused recovery codes the page warns and suggests regenerating. | ||
| 37 | +const LOW_RECOVERY_CODES: u64 = 3; | ||
| 38 | +/// Longest device name, in characters. The name is shown in one line of the page. | ||
| 39 | +const MAX_DEVICE_NAME_CHARS: usize = 40; | ||
| 34 | 40 | ||
| 35 | #[query_params(error = bad_request)] | 41 | #[query_params(error = bad_request)] |
| 36 | struct SecurityQuery { | 42 | struct SecurityQuery { |
| @@ -73,6 +79,17 @@ struct CodeForm { | |||
| 73 | code: String, | 79 | code: String, |
| 74 | } | 80 | } |
| 75 | 81 | ||
| 82 | +#[derive(Deserialize)] | ||
| 83 | +struct EnrollForm { | ||
| 84 | + #[serde(default)] | ||
| 85 | + csrf: String, | ||
| 86 | + #[serde(default)] | ||
| 87 | + code: String, | ||
| 88 | + /// Optional device name. Empty means the default name. | ||
| 89 | + #[serde(default)] | ||
| 90 | + name: String, | ||
| 91 | +} | ||
| 92 | + | ||
| 76 | #[derive(Deserialize)] | 93 | #[derive(Deserialize)] |
| 77 | struct DisableForm { | 94 | struct DisableForm { |
| 78 | #[serde(default)] | 95 | #[serde(default)] |
| @@ -104,12 +121,35 @@ struct Shown { | |||
| 104 | email_error: Option<String>, | 121 | email_error: Option<String>, |
| 105 | email_draft: Option<String>, | 122 | email_draft: Option<String>, |
| 106 | two_factor_error: Option<String>, | 123 | two_factor_error: Option<String>, |
| 124 | + /// The two-factor panel that `two_factor_error` belongs to. | ||
| 125 | + two_factor_panel: TwoFactorPanel, | ||
| 107 | /// Recovery codes, shown once in the response that created them. | 126 | /// Recovery codes, shown once in the response that created them. |
| 108 | codes: Option<Vec<String>>, | 127 | codes: Option<Vec<String>>, |
| 109 | /// Set when a check was refused by the throttle. The response then answers 429. | 128 | /// Set when a check was refused by the throttle. The response then answers 429. |
| 110 | throttled: Option<Duration>, | 129 | throttled: Option<Duration>, |
| 111 | } | 130 | } |
| 112 | 131 | ||
| 132 | +/// Which two-factor panel an error belongs to. That panel stays open with its message. | ||
| 133 | +#[derive(Clone, Copy, Default, PartialEq, Eq)] | ||
| 134 | +enum TwoFactorPanel { | ||
| 135 | + /// Enrollment: the setup form, while a secret waits for its first code. | ||
| 136 | + #[default] | ||
| 137 | + Setup, | ||
| 138 | + Regenerate, | ||
| 139 | + Disable, | ||
| 140 | +} | ||
| 141 | + | ||
| 142 | +/// The enabled authenticator device, with the recovery code count, as the page shows it. | ||
| 143 | +struct DeviceView { | ||
| 144 | + name: String, | ||
| 145 | + /// "Added 2026-10-18 · Last used 5 minutes ago". | ||
| 146 | + status: String, | ||
| 147 | + /// "7 of 10 recovery codes unused". | ||
| 148 | + codes_line: String, | ||
| 149 | + /// True when few recovery codes are left, so the line warns. | ||
| 150 | + codes_low: bool, | ||
| 151 | +} | ||
| 152 | + | ||
| 113 | /// What the page needs to draw itself. | 153 | /// What the page needs to draw itself. |
| 114 | struct SecurityPage { | 154 | struct SecurityPage { |
| 115 | lang: Lang, | 155 | lang: Lang, |
| @@ -117,19 +157,25 @@ struct SecurityPage { | |||
| 117 | email: String, | 157 | email: String, |
| 118 | /// Whether the stored address has been verified. | 158 | /// Whether the stored address has been verified. |
| 119 | email_verified: bool, | 159 | email_verified: bool, |
| 160 | + /// The address the account has stored. `email` may be an unsaved draft. | ||
| 161 | + stored_email: String, | ||
| 162 | + /// The Email row's state: "Verified", or "Not verified" with the verification mail's state. | ||
| 163 | + email_status: String, | ||
| 120 | notice: Option<&'static str>, | 164 | notice: Option<&'static str>, |
| 121 | password_error: Option<String>, | 165 | password_error: Option<String>, |
| 122 | email_error: Option<String>, | 166 | email_error: Option<String>, |
| 123 | two_factor_error: Option<String>, | 167 | two_factor_error: Option<String>, |
| 168 | + two_factor_panel: TwoFactorPanel, | ||
| 124 | codes: Option<Vec<String>>, | 169 | codes: Option<Vec<String>>, |
| 125 | /// Secret (base32) and `otpauth://` URI while enrollment is waiting for a code. | 170 | /// Secret (base32) and `otpauth://` URI while enrollment is waiting for a code. |
| 126 | pending: Option<(String, String)>, | 171 | pending: Option<(String, String)>, |
| 127 | - /// Unused recovery codes, when two-factor is on. | 172 | + /// "Last changed 3 days ago", when the change time is known. |
| 128 | - enabled_unused_codes: Option<u64>, | 173 | + password_changed: Option<String>, |
| 174 | + /// The enabled device. `None` when two-factor is off. | ||
| 175 | + two_factor: Option<DeviceView>, | ||
| 129 | delete_error: Option<String>, | 176 | delete_error: Option<String>, |
| 130 | /// Repositories still owned by the user. Deletion is refused while there are any. | 177 | /// Repositories still owned by the user. Deletion is refused while there are any. |
| 131 | owned_repos: Vec<String>, | 178 | owned_repos: Vec<String>, |
| 132 | - two_factor_on: bool, | ||
| 133 | } | 179 | } |
| 134 | 180 | ||
| 135 | #[component] | 181 | #[component] |
| @@ -139,17 +185,50 @@ async fn security_body(page: SecurityPage) -> Result<impl View> { | |||
| 139 | csrf, | 185 | csrf, |
| 140 | email, | 186 | email, |
| 141 | email_verified, | 187 | email_verified, |
| 188 | + stored_email, | ||
| 189 | + email_status, | ||
| 142 | notice, | 190 | notice, |
| 143 | password_error, | 191 | password_error, |
| 144 | email_error, | 192 | email_error, |
| 145 | two_factor_error, | 193 | two_factor_error, |
| 194 | + two_factor_panel, | ||
| 146 | codes, | 195 | codes, |
| 147 | pending, | 196 | pending, |
| 148 | - enabled_unused_codes, | 197 | + password_changed, |
| 198 | + two_factor, | ||
| 149 | delete_error, | 199 | delete_error, |
| 150 | owned_repos, | 200 | owned_repos, |
| 151 | - two_factor_on, | ||
| 152 | } = page; | 201 | } = page; |
| 202 | + let two_factor_on = two_factor.is_some(); | ||
| 203 | + let codes_class = match &two_factor { | ||
| 204 | + Some(device) if device.codes_low => "security-row-status warn", | ||
| 205 | + _ => "security-row-status", | ||
| 206 | + }; | ||
| 207 | + let password_open = password_error.is_some(); | ||
| 208 | + let email_open = email_error.is_some(); | ||
| 209 | + let email_set = !email.is_empty(); | ||
| 210 | + let show_resend = email_set && !email_verified; | ||
| 211 | + let two_factor_pill_class = if two_factor_on { | ||
| 212 | + "security-pill on" | ||
| 213 | + } else { | ||
| 214 | + "security-pill off" | ||
| 215 | + }; | ||
| 216 | + let two_factor_pill_text = if two_factor_on { | ||
| 217 | + t(lang, Key::PillOn) | ||
| 218 | + } else { | ||
| 219 | + t(lang, Key::PillOff) | ||
| 220 | + }; | ||
| 221 | + let regenerate_error = two_factor_error | ||
| 222 | + .clone() | ||
| 223 | + .filter(|_| two_factor_panel == TwoFactorPanel::Regenerate); | ||
| 224 | + let disable_error = two_factor_error | ||
| 225 | + .clone() | ||
| 226 | + .filter(|_| two_factor_panel == TwoFactorPanel::Disable); | ||
| 227 | + let setup_error = two_factor_error.filter(|_| two_factor_panel == TwoFactorPanel::Setup); | ||
| 228 | + let regenerate_open = regenerate_error.is_some(); | ||
| 229 | + let disable_open = disable_error.is_some(); | ||
| 230 | + let delete_open = delete_error.is_some(); | ||
| 231 | + let delete_blocked = !owned_repos.is_empty(); | ||
| 153 | Ok(view! { | 232 | Ok(view! { |
| 154 | <div class="settings-layout"> | 233 | <div class="settings-layout"> |
| 155 | <section class="page-head"> | 234 | <section class="page-head"> |
| @@ -172,142 +251,232 @@ async fn security_body(page: SecurityPage) -> Result<impl View> { | |||
| 172 | </ul> | 251 | </ul> |
| 173 | </section> | 252 | </section> |
| 174 | } | 253 | } |
| 175 | - <section class="card"> | 254 | + <section class="card security-card"> |
| 176 | - <h2>(t(lang, Key::Password))</h2> | 255 | + <div class="security-row"> |
| 177 | - if let Some(message) = password_error { | 256 | + <svg class="security-icon" viewBox="0 0 24 24" aria-hidden="true"><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></svg> |
| 178 | - alert(message: message.as_str()) | 257 | + <div class="security-row-main"> |
| 179 | - } | 258 | + <h2 class="security-row-title">(t(lang, Key::Password))</h2> |
| 180 | - <form data-hard="true" method="post" action="/settings/security/password" class="stack"> | 259 | + if let Some(line) = password_changed { |
| 181 | - <input type="hidden" name="csrf" value=(csrf.as_str())> | 260 | + <p class="security-row-status">(line.as_str())</p> |
| 182 | - <label> | 261 | + } |
| 183 | - <span>(t(lang, Key::CurrentPassword))</span> | 262 | + </div> |
| 184 | - <input type="password" name="current_password" autocomplete="current-password" required=(true)> | 263 | + <details class="security-action" open=(password_open)> |
| 185 | - </label> | 264 | + <summary>(t(lang, Key::ChangeAction))</summary> |
| 186 | - <label> | 265 | + <div class="security-panel"> |
| 187 | - <span>(t(lang, Key::NewPassword))</span> | 266 | + if let Some(message) = password_error { |
| 188 | - <input type="password" name="new_password" autocomplete="new-password" minlength="10" maxlength="1024" required=(true)> | 267 | + alert(message: message.as_str()) |
| 189 | - <small class="muted">(t(lang, Key::NewPasswordHint))</small> | 268 | + } |
| 190 | - </label> | 269 | + <form data-hard="true" method="post" action="/settings/security/password" class="stack"> |
| 191 | - <label> | 270 | + <input type="hidden" name="csrf" value=(csrf.as_str())> |
| 192 | - <span>(t(lang, Key::ConfirmNewPassword))</span> | 271 | + <label> |
| 193 | - <input type="password" name="confirm_password" autocomplete="new-password" required=(true)> | 272 | + <span>(t(lang, Key::CurrentPassword))</span> |
| 194 | - </label> | 273 | + <input type="password" name="current_password" autocomplete="current-password" required=(true)> |
| 195 | - <button type="submit" class="primary">(t(lang, Key::ChangePassword))</button> | 274 | + </label> |
| 196 | - </form> | 275 | + <label> |
| 197 | - </section> | 276 | + <span>(t(lang, Key::NewPassword))</span> |
| 198 | - <section class="card"> | 277 | + <input type="password" name="new_password" autocomplete="new-password" minlength="10" maxlength="1024" required=(true)> |
| 199 | - <h2>(t(lang, Key::Email))</h2> | 278 | + <small class="muted">(t(lang, Key::NewPasswordHint))</small> |
| 200 | - if let Some(message) = email_error { | 279 | + </label> |
| 201 | - alert(message: message.as_str()) | 280 | + <label> |
| 202 | - } | 281 | + <span>(t(lang, Key::ConfirmNewPassword))</span> |
| 203 | - <form method="post" action="/settings/security/email" class="stack"> | 282 | + <input type="password" name="confirm_password" autocomplete="new-password" required=(true)> |
| 204 | - <input type="hidden" name="csrf" value=(csrf.as_str())> | 283 | + </label> |
| 205 | - <label> | 284 | + <button type="submit" class="primary">(t(lang, Key::ChangePassword))</button> |
| 206 | - <span>(t(lang, Key::Email))</span> | 285 | + </form> |
| 207 | - <input type="email" name="email" autocomplete="email" maxlength="254" required=(true) value=(email.as_str())> | 286 | + </div> |
| 208 | - </label> | 287 | + </details> |
| 209 | - <label> | 288 | + </div> |
| 210 | - <span>(t(lang, Key::CurrentPassword))</span> | 289 | + <div class="security-row"> |
| 211 | - <input type="password" name="current_password" autocomplete="current-password" required=(true)> | 290 | + <svg class="security-icon" viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 7l9 6 9-6"/></svg> |
| 212 | - </label> | 291 | + <div class="security-row-main"> |
| 213 | - <button type="submit" class="primary">(t(lang, Key::SaveEmail))</button> | 292 | + <h2 class="security-row-title">(t(lang, Key::Email))</h2> |
| 214 | - </form> | 293 | + if stored_email.is_empty() { |
| 215 | - if !email.is_empty() { | 294 | + <p class="security-row-status">(t(lang, Key::EmailNoAddress))</p> |
| 216 | - if email_verified { | 295 | + } else { |
| 217 | - <p class="muted">(t(lang, Key::VerifyVerified))</p> | 296 | + <p class="security-row-status"><span class="security-email">(stored_email.as_str())</span> (" · ")(email_status.as_str())</p> |
| 218 | - } | 297 | + } |
| 219 | - if !email_verified { | 298 | + </div> |
| 220 | - <p class="muted">(t(lang, Key::VerifyUnverified))</p> | 299 | + if show_resend { |
| 221 | - <form method="post" action="/settings/security/email/resend" class="stack"> | 300 | + <form method="post" action="/settings/security/email/resend" class="security-inline-form"> |
| 222 | <input type="hidden" name="csrf" value=(csrf.as_str())> | 301 | <input type="hidden" name="csrf" value=(csrf.as_str())> |
| 223 | <button type="submit">(t(lang, Key::VerifyResend))</button> | 302 | <button type="submit">(t(lang, Key::VerifyResend))</button> |
| 224 | </form> | 303 | </form> |
| 225 | } | 304 | } |
| 226 | - } | 305 | + <details class="security-action" open=(email_open)> |
| 227 | - </section> | 306 | + <summary>(t(lang, Key::ChangeAction))</summary> |
| 228 | - <section class="card"> | 307 | + <div class="security-panel"> |
| 229 | - <h2>(t(lang, Key::TwoFactorAuth))</h2> | 308 | + if let Some(message) = email_error { |
| 230 | - if let Some(message) = two_factor_error { | 309 | + alert(message: message.as_str()) |
| 231 | - alert(message: message.as_str()) | 310 | + } |
| 232 | - } | 311 | + <form method="post" action="/settings/security/email" class="stack"> |
| 233 | - if let Some(unused) = enabled_unused_codes { | 312 | + <input type="hidden" name="csrf" value=(csrf.as_str())> |
| 234 | - <p>(two_factor_on_line(lang, unused))</p> | 313 | + <label> |
| 235 | - <h3>(t(lang, Key::RegenerateCodes))</h3> | 314 | + <span>(t(lang, Key::Email))</span> |
| 236 | - <p class="muted">(t(lang, Key::RegenerateCodesHint))</p> | 315 | + <input type="email" name="email" autocomplete="email" maxlength="254" required=(true) value=(email.as_str())> |
| 237 | - <form data-hard="true" method="post" action="/settings/security/2fa/recovery" class="stack"> | 316 | + </label> |
| 238 | - <input type="hidden" name="csrf" value=(csrf.as_str())> | 317 | + <label> |
| 239 | - <label> | 318 | + <span>(t(lang, Key::CurrentPassword))</span> |
| 240 | - <span>(t(lang, Key::Code))</span> | 319 | + <input type="password" name="current_password" autocomplete="current-password" required=(true)> |
| 241 | - <input type="text" name="code" autocomplete="one-time-code" required=(true)> | 320 | + </label> |
| 242 | - </label> | 321 | + <button type="submit" class="primary">(t(lang, Key::SaveEmail))</button> |
| 243 | - <button type="submit" class="primary">(t(lang, Key::RegenerateCodes))</button> | 322 | + </form> |
| 244 | - </form> | 323 | + </div> |
| 245 | - <h3>(t(lang, Key::TurnOffTwoFactor))</h3> | 324 | + </details> |
| 246 | - <form data-hard="true" method="post" action="/settings/security/2fa/disable" class="stack"> | 325 | + </div> |
| 247 | - <input type="hidden" name="csrf" value=(csrf.as_str())> | 326 | + <div class="security-block"> |
| 248 | - <label> | 327 | + <div class="security-row"> |
| 249 | - <span>(t(lang, Key::CurrentPassword))</span> | 328 | + <svg class="security-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l8 3v6c0 4.5-3.4 8.3-8 9-4.6-.7-8-4.5-8-9V6z"/><path d="M9 12l2 2 4-4"/></svg> |
| 250 | - <input type="password" name="current_password" autocomplete="current-password" required=(true)> | 329 | + <div class="security-row-main"> |
| 251 | - </label> | 330 | + <h2 class="security-row-title"> |
| 252 | - <label> | 331 | + <span>(t(lang, Key::TwoFactorAuth))</span> |
| 253 | - <span>(t(lang, Key::Code))</span> | 332 | + <span class=(two_factor_pill_class)>(two_factor_pill_text)</span> |
| 254 | - <input type="text" name="code" autocomplete="one-time-code" required=(true)> | 333 | + </h2> |
| 255 | - </label> | 334 | + if !two_factor_on && pending.is_none() { |
| 256 | - <button type="submit" class="danger">(t(lang, Key::TurnOffTwoFactorButton))</button> | 335 | + <p class="security-row-status">(t(lang, Key::TwoFactorOffIntro))</p> |
| 257 | - </form> | 336 | + } |
| 258 | - } else if let Some((secret, uri)) = pending { | 337 | + if pending.is_some() { |
| 259 | - <p>(t(lang, Key::TwoFactorPendingIntro))</p> | 338 | + <p class="security-row-status">(t(lang, Key::SetupInProgress))</p> |
| 260 | - <p>(t(lang, Key::SecretPrefix)) <code>(secret)</code></p> | 339 | + } |
| 261 | - <p>(t(lang, Key::LinkPrefix)) <code>(uri)</code></p> | 340 | + </div> |
| 262 | - <form data-hard="true" method="post" action="/settings/security/2fa/confirm" class="stack"> | ||
| 263 | - <input type="hidden" name="csrf" value=(csrf.as_str())> | ||
| 264 | - <label> | ||
| 265 | - <span>(t(lang, Key::CodeFromApp))</span> | ||
| 266 | - <input type="text" name="code" inputmode="numeric" autocomplete="one-time-code" maxlength="6" required=(true)> | ||
| 267 | - </label> | ||
| 268 | - <button type="submit" class="primary">(t(lang, Key::ConfirmAndTurnOn))</button> | ||
| 269 | - </form> | ||
| 270 | - } else { | ||
| 271 | - <p class="muted">(t(lang, Key::TwoFactorOffIntro))</p> | ||
| 272 | - <form data-hard="true" method="post" action="/settings/security/2fa/enable"> | ||
| 273 | - <input type="hidden" name="csrf" value=(csrf.as_str())> | ||
| 274 | - <button type="submit" class="primary">(t(lang, Key::Enable2fa))</button> | ||
| 275 | - </form> | ||
| 276 | - } | ||
| 277 | - </section> | ||
| 278 | - <section class="card"> | ||
| 279 | - <h2>(t(lang, Key::DeleteAccount))</h2> | ||
| 280 | - if let Some(message) = delete_error { | ||
| 281 | - alert(message: message.as_str()) | ||
| 282 | - } | ||
| 283 | - if owned_repos.is_empty() { | ||
| 284 | - <p class="muted">(t(lang, Key::DeleteAccountIntro))</p> | ||
| 285 | - <form data-hard="true" method="post" action="/settings/security/delete" class="stack"> | ||
| 286 | - <input type="hidden" name="csrf" value=(csrf.as_str())> | ||
| 287 | - <label> | ||
| 288 | - <span>(t(lang, Key::CurrentPassword))</span> | ||
| 289 | - <input type="password" name="current_password" autocomplete="current-password" required=(true)> | ||
| 290 | - </label> | ||
| 291 | if two_factor_on { | 341 | if two_factor_on { |
| 292 | - <label> | 342 | + <details class="security-action danger" open=(disable_open)> |
| 293 | - <span>(t(lang, Key::Code))</span> | 343 | + <summary>(t(lang, Key::TurnOffTwoFactorButton))</summary> |
| 294 | - <input type="text" name="code" autocomplete="one-time-code" required=(true)> | 344 | + <div class="security-panel"> |
| 295 | - </label> | 345 | + if let Some(message) = disable_error { |
| 346 | + alert(message: message.as_str()) | ||
| 347 | + } | ||
| 348 | + <form data-hard="true" method="post" action="/settings/security/2fa/disable" class="stack"> | ||
| 349 | + <input type="hidden" name="csrf" value=(csrf.as_str())> | ||
| 350 | + <label> | ||
| 351 | + <span>(t(lang, Key::CurrentPassword))</span> | ||
| 352 | + <input type="password" name="current_password" autocomplete="current-password" required=(true)> | ||
| 353 | + </label> | ||
| 354 | + <label> | ||
| 355 | + <span>(t(lang, Key::Code))</span> | ||
| 356 | + <input type="text" name="code" autocomplete="one-time-code" required=(true)> | ||
| 357 | + </label> | ||
| 358 | + <button type="submit" class="danger">(t(lang, Key::TurnOffTwoFactorButton))</button> | ||
| 359 | + </form> | ||
| 360 | + </div> | ||
| 361 | + </details> | ||
| 362 | + } else if pending.is_none() { | ||
| 363 | + <form data-hard="true" method="post" action="/settings/security/2fa/enable" class="security-inline-form"> | ||
| 364 | + <input type="hidden" name="csrf" value=(csrf.as_str())> | ||
| 365 | + <button type="submit" class="primary">(t(lang, Key::SetUpAction))</button> | ||
| 366 | + </form> | ||
| 296 | } | 367 | } |
| 297 | - <label> | 368 | + </div> |
| 298 | - <span>(t(lang, Key::TypeUsernameToConfirm))</span> | 369 | + if let Some(device) = two_factor { |
| 299 | - <input type="text" name="confirm_username" autocomplete="off" required=(true)> | 370 | + <ul class="security-devices"> |
| 300 | - </label> | 371 | + <li class="security-row security-device"> |
| 301 | - <button type="submit" class="danger">(t(lang, Key::DeleteAccount))</button> | 372 | + <svg class="security-icon" viewBox="0 0 24 24" aria-hidden="true"><rect x="7" y="3" width="10" height="18" rx="2"/><path d="M11 18h2"/></svg> |
| 302 | - </form> | 373 | + <div class="security-row-main"> |
| 303 | - } else { | 374 | + <p class="security-row-title">(device.name.as_str())</p> |
| 304 | - <p>(t(lang, Key::TransferOrDeleteRepos))</p> | 375 | + <p class="security-row-status">(device.status.as_str())</p> |
| 305 | - <ul class="item-list"> | 376 | + </div> |
| 306 | - for name in owned_repos.into_iter() { | 377 | + </li> |
| 307 | - <li>(name)</li> | 378 | + <li class="security-row security-device"> |
| 379 | + <svg class="security-icon" viewBox="0 0 24 24" aria-hidden="true"><circle cx="8" cy="15" r="4"/><path d="M11 12l9-9M17 6l3 3M14 9l3 3"/></svg> | ||
| 380 | + <div class="security-row-main"> | ||
| 381 | + <p class="security-row-title">(t(lang, Key::RecoveryCodes))</p> | ||
| 382 | + <p class=(codes_class)>(device.codes_line.as_str())</p> | ||
| 383 | + if device.codes_low { | ||
| 384 | + <p class="security-row-status warn">(t(lang, Key::CodesRunningLow))</p> | ||
| 385 | + } | ||
| 386 | + </div> | ||
| 387 | + <details class="security-action" open=(regenerate_open)> | ||
| 388 | + <summary>(t(lang, Key::RegenerateCodes))</summary> | ||
| 389 | + <div class="security-panel"> | ||
| 390 | + if let Some(message) = regenerate_error { | ||
| 391 | + alert(message: message.as_str()) | ||
| 392 | + } | ||
| 393 | + <form data-hard="true" method="post" action="/settings/security/2fa/recovery" class="stack"> | ||
| 394 | + <input type="hidden" name="csrf" value=(csrf.as_str())> | ||
| 395 | + <p class="muted">(t(lang, Key::RegenerateCodesHint))</p> | ||
| 396 | + <label> | ||
| 397 | + <span>(t(lang, Key::Code))</span> | ||
| 398 | + <input type="text" name="code" autocomplete="one-time-code" required=(true)> | ||
| 399 | + </label> | ||
| 400 | + <button type="submit" class="primary">(t(lang, Key::RegenerateCodes))</button> | ||
| 401 | + </form> | ||
| 402 | + </div> | ||
| 403 | + </details> | ||
| 404 | + </li> | ||
| 405 | + </ul> | ||
| 406 | + } | ||
| 407 | + if let Some((secret, uri)) = pending { | ||
| 408 | + <div class="security-panel security-setup"> | ||
| 409 | + <p>(t(lang, Key::TwoFactorPendingIntro))</p> | ||
| 410 | + <p>(t(lang, Key::SecretPrefix)) <code>(secret)</code></p> | ||
| 411 | + <p>(t(lang, Key::LinkPrefix)) <code>(uri)</code></p> | ||
| 412 | + if let Some(message) = setup_error { | ||
| 413 | + alert(message: message.as_str()) | ||
| 414 | + } | ||
| 415 | + <form data-hard="true" method="post" action="/settings/security/2fa/confirm" class="stack"> | ||
| 416 | + <input type="hidden" name="csrf" value=(csrf.as_str())> | ||
| 417 | + <label> | ||
| 418 | + <span>(t(lang, Key::CodeFromApp))</span> | ||
| 419 | + <input type="text" name="code" inputmode="numeric" autocomplete="one-time-code" maxlength="6" required=(true)> | ||
| 420 | + </label> | ||
| 421 | + <label> | ||
| 422 | + <span>(t(lang, Key::DeviceName))</span> | ||
| 423 | + <input type="text" name="name" autocomplete="off" maxlength="40" placeholder=(t(lang, Key::AuthenticatorApp))> | ||
| 424 | + <small class="muted">(t(lang, Key::DeviceNameHint))</small> | ||
| 425 | + </label> | ||
| 426 | + <button type="submit" class="primary">(t(lang, Key::ConfirmAndTurnOn))</button> | ||
| 427 | + </form> | ||
| 428 | + </div> | ||
| 429 | + } | ||
| 430 | + </div> | ||
| 431 | + </section> | ||
| 432 | + <section class="card security-card security-danger"> | ||
| 433 | + <p class="security-danger-label">(t(lang, Key::DangerZone))</p> | ||
| 434 | + <div class="security-row"> | ||
| 435 | + <svg class="security-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 4l9 16H3z"/><path d="M12 10v4M12 17v.5"/></svg> | ||
| 436 | + <div class="security-row-main"> | ||
| 437 | + <h2 class="security-row-title">(t(lang, Key::DeleteAccount))</h2> | ||
| 438 | + if delete_blocked { | ||
| 439 | + <p class="security-row-status">(t(lang, Key::TransferOrDeleteRepos))</p> | ||
| 440 | + } else { | ||
| 441 | + <p class="security-row-status">(t(lang, Key::DeleteAccountIntro))</p> | ||
| 308 | } | 442 | } |
| 309 | - </ul> | 443 | + </div> |
| 310 | - } | 444 | + if !delete_blocked { |
| 445 | + <details class="security-action danger" open=(delete_open)> | ||
| 446 | + <summary>(t(lang, Key::DeleteAccount))</summary> | ||
| 447 | + <div class="security-panel"> | ||
| 448 | + if let Some(message) = delete_error { | ||
| 449 | + alert(message: message.as_str()) | ||
| 450 | + } | ||
| 451 | + <form data-hard="true" method="post" action="/settings/security/delete" class="stack"> | ||
| 452 | + <input type="hidden" name="csrf" value=(csrf.as_str())> | ||
| 453 | + <label> | ||
| 454 | + <span>(t(lang, Key::CurrentPassword))</span> | ||
| 455 | + <input type="password" name="current_password" autocomplete="current-password" required=(true)> | ||
| 456 | + </label> | ||
| 457 | + if two_factor_on { | ||
| 458 | + <label> | ||
| 459 | + <span>(t(lang, Key::Code))</span> | ||
| 460 | + <input type="text" name="code" autocomplete="one-time-code" required=(true)> | ||
| 461 | + </label> | ||
| 462 | + } | ||
| 463 | + <label> | ||
| 464 | + <span>(t(lang, Key::TypeUsernameToConfirm))</span> | ||
| 465 | + <input type="text" name="confirm_username" autocomplete="off" required=(true)> | ||
| 466 | + </label> | ||
| 467 | + <button type="submit" class="danger">(t(lang, Key::DeleteAccount))</button> | ||
| 468 | + </form> | ||
| 469 | + </div> | ||
| 470 | + </details> | ||
| 471 | + } | ||
| 472 | + if delete_blocked { | ||
| 473 | + <ul class="item-list security-repos"> | ||
| 474 | + for name in owned_repos.into_iter() { | ||
| 475 | + <li>(name)</li> | ||
| 476 | + } | ||
| 477 | + </ul> | ||
| 478 | + } | ||
| 479 | + </div> | ||
| 311 | </section> | 480 | </section> |
| 312 | </div> | 481 | </div> |
| 313 | }) | 482 | }) |
| @@ -330,13 +499,32 @@ async fn build_page( | |||
| 330 | viewer: &(User, Session), | 499 | viewer: &(User, Session), |
| 331 | shown: Shown, | 500 | shown: Shown, |
| 332 | ) -> forge_core::Result<SecurityPage> { | 501 | ) -> forge_core::Result<SecurityPage> { |
| 502 | + // Relative times are rendered against one `now`, so every line on the page agrees. | ||
| 503 | + let now = i64::try_from(unix_now()).unwrap_or(i64::MAX); | ||
| 504 | + let ago = |stamp: Option<&str>| { | ||
| 505 | + stamp | ||
| 506 | + .and_then(stamp_to_unix) | ||
| 507 | + .map(|unix| relative_time(lang, unix, now)) | ||
| 508 | + }; | ||
| 333 | let totp_state = state.store.totp_state(&viewer.0.id).await?; | 509 | let totp_state = state.store.totp_state(&viewer.0.id).await?; |
| 334 | - let (pending, enabled_unused_codes) = match totp_state { | 510 | + let (pending, two_factor) = match totp_state { |
| 335 | - Some(t) if t.enabled => ( | 511 | + Some(totp) if totp.enabled => { |
| 336 | - None, | 512 | + let unused = state.store.unused_recovery_codes(&viewer.0.id).await?; |
| 337 | - Some(state.store.unused_recovery_codes(&viewer.0.id).await?), | 513 | + let device = DeviceView { |
| 338 | - ), | 514 | + name: totp |
| 339 | - Some(t) => match t.sealed_secret { | 515 | + .name |
| 516 | + .unwrap_or_else(|| t(lang, Key::AuthenticatorApp).to_owned()), | ||
| 517 | + status: i18n::device_line( | ||
| 518 | + lang, | ||
| 519 | + totp.created_at.as_deref().and_then(|stamp| stamp.get(..10)), | ||
| 520 | + ago(totp.last_used_at.as_deref()).as_deref(), | ||
| 521 | + ), | ||
| 522 | + codes_line: i18n::codes_left_line(lang, unused, RECOVERY_CODE_COUNT as u64), | ||
| 523 | + codes_low: unused <= LOW_RECOVERY_CODES, | ||
| 524 | + }; | ||
| 525 | + (None, Some(device)) | ||
| 526 | + } | ||
| 527 | + Some(totp) => match totp.sealed_secret { | ||
| 340 | Some(sealed) => { | 528 | Some(sealed) => { |
| 341 | let shared = secret::open(&state.key, &sealed)?; | 529 | let shared = secret::open(&state.key, &sealed)?; |
| 342 | let pending = ( | 530 | let pending = ( |
| @@ -349,6 +537,13 @@ async fn build_page( | |||
| 349 | }, | 537 | }, |
| 350 | None => (None, None), | 538 | None => (None, None), |
| 351 | }; | 539 | }; |
| 540 | + let password_changed = state | ||
| 541 | + .store | ||
| 542 | + .password_changed_at(&viewer.0.id) | ||
| 543 | + .await? | ||
| 544 | + .as_deref() | ||
| 545 | + .and_then(|stamp| ago(Some(stamp))) | ||
| 546 | + .map(|when| i18n::last_changed_line(lang, &when)); | ||
| 352 | let owned_repos = state | 547 | let owned_repos = state |
| 353 | .store | 548 | .store |
| 354 | .list_repos_by_owner(&viewer.0.id) | 549 | .list_repos_by_owner(&viewer.0.id) |
| @@ -356,14 +551,33 @@ async fn build_page( | |||
| 356 | .into_iter() | 551 | .into_iter() |
| 357 | .map(|repo| format!("{}/{}", repo.owner_name, repo.name)) | 552 | .map(|repo| format!("{}/{}", repo.owner_name, repo.name)) |
| 358 | .collect(); | 553 | .collect(); |
| 359 | - let two_factor_on = enabled_unused_codes.is_some(); | 554 | + let stored_email = viewer.0.email.clone().unwrap_or_default(); |
| 555 | + let email_verified = state.store.email_is_verified(&viewer.0.id).await?; | ||
| 556 | + let email_status = if stored_email.is_empty() { | ||
| 557 | + String::new() | ||
| 558 | + } else if email_verified { | ||
| 559 | + t(lang, Key::PillVerified).to_owned() | ||
| 560 | + } else { | ||
| 561 | + let mut status = t(lang, Key::EmailNotVerified).to_owned(); | ||
| 562 | + if let Some(mail) = state | ||
| 563 | + .store | ||
| 564 | + .latest_mail_for(&viewer.0.id, MailKind::Verification) | ||
| 565 | + .await? | ||
| 566 | + { | ||
| 567 | + let sent_ago = ago(mail.sent_at.as_deref()); | ||
| 568 | + let line = i18n::email_mail_line(lang, mail.state, mail.attempts, sent_ago.as_deref()); | ||
| 569 | + status = format!("{status} · {line}"); | ||
| 570 | + } | ||
| 571 | + status | ||
| 572 | + }; | ||
| 360 | Ok(SecurityPage { | 573 | Ok(SecurityPage { |
| 361 | lang, | 574 | lang, |
| 362 | csrf: viewer.1.csrf_token.clone(), | 575 | csrf: viewer.1.csrf_token.clone(), |
| 363 | delete_error: shown.delete_error, | 576 | delete_error: shown.delete_error, |
| 364 | owned_repos, | 577 | owned_repos, |
| 365 | - two_factor_on, | 578 | + email_verified, |
| 366 | - email_verified: state.store.email_is_verified(&viewer.0.id).await?, | 579 | + stored_email, |
| 580 | + email_status, | ||
| 367 | email: shown | 581 | email: shown |
| 368 | .email_draft | 582 | .email_draft |
| 369 | .unwrap_or_else(|| viewer.0.email.clone().unwrap_or_default()), | 583 | .unwrap_or_else(|| viewer.0.email.clone().unwrap_or_default()), |
| @@ -371,9 +585,11 @@ async fn build_page( | |||
| 371 | password_error: shown.password_error, | 585 | password_error: shown.password_error, |
| 372 | email_error: shown.email_error, | 586 | email_error: shown.email_error, |
| 373 | two_factor_error: shown.two_factor_error, | 587 | two_factor_error: shown.two_factor_error, |
| 588 | + two_factor_panel: shown.two_factor_panel, | ||
| 374 | codes: shown.codes, | 589 | codes: shown.codes, |
| 375 | pending, | 590 | pending, |
| 376 | - enabled_unused_codes, | 591 | + password_changed, |
| 592 | + two_factor, | ||
| 377 | }) | 593 | }) |
| 378 | } | 594 | } |
| 379 | 595 | ||
| @@ -569,7 +785,7 @@ async fn two_factor_enable(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOth | |||
| 569 | } | 785 | } |
| 570 | 786 | ||
| 571 | #[page(POST "/settings/security/2fa/confirm")] | 787 | #[page(POST "/settings/security/2fa/confirm")] |
| 572 | -async fn two_factor_confirm(cx: &Cx, Form(form): Form<CodeForm>) -> Result<impl View> { | 788 | +async fn two_factor_confirm(cx: &Cx, Form(form): Form<EnrollForm>) -> Result<impl View> { |
| 573 | let viewer = require_csrf(cx, &form.csrf).await?; | 789 | let viewer = require_csrf(cx, &form.csrf).await?; |
| 574 | let lang = i18n::lang(cx, Some(&viewer.0)); | 790 | let lang = i18n::lang(cx, Some(&viewer.0)); |
| 575 | let state = app_context::<AppState>(cx); | 791 | let state = app_context::<AppState>(cx); |
| @@ -587,6 +803,13 @@ async fn two_factor_confirm(cx: &Cx, Form(form): Form<CodeForm>) -> Result<impl | |||
| 587 | shown.throttled = Some(retry); | 803 | shown.throttled = Some(retry); |
| 588 | return respond(cx, viewer, shown).await; | 804 | return respond(cx, viewer, shown).await; |
| 589 | } | 805 | } |
| 806 | + // A bad name is refused before the code is checked, so the code is not spent on it. | ||
| 807 | + let name = form.name.trim(); | ||
| 808 | + if name.chars().count() > MAX_DEVICE_NAME_CHARS || name.chars().any(char::is_control) { | ||
| 809 | + shown.two_factor_error = Some(t(lang, Key::ErrDeviceName).into()); | ||
| 810 | + return respond(cx, viewer, shown).await; | ||
| 811 | + } | ||
| 812 | + let name = (!name.is_empty()).then(|| name.to_owned()); | ||
| 590 | let shared = secret::open(&state.key, &sealed)?; | 813 | let shared = secret::open(&state.key, &sealed)?; |
| 591 | let key = throttle::two_factor_key(&user_id); | 814 | let key = throttle::two_factor_key(&user_id); |
| 592 | match totp::verify( | 815 | match totp::verify( |
| @@ -599,6 +822,7 @@ async fn two_factor_confirm(cx: &Cx, Form(form): Form<CodeForm>) -> Result<impl | |||
| 599 | state.throttle.clear(&key); | 822 | state.throttle.clear(&key); |
| 600 | let (codes, hashes) = new_recovery_codes(); | 823 | let (codes, hashes) = new_recovery_codes(); |
| 601 | state.store.enable_totp(&user_id, step, &hashes).await?; | 824 | state.store.enable_totp(&user_id, step, &hashes).await?; |
| 825 | + state.store.set_totp_name(&user_id, name.as_deref()).await?; | ||
| 602 | audit::record( | 826 | audit::record( |
| 603 | &state.store, | 827 | &state.store, |
| 604 | Some(cx), | 828 | Some(cx), |
| @@ -629,7 +853,10 @@ async fn two_factor_disable(cx: &Cx, Form(form): Form<DisableForm>) -> Result<im | |||
| 629 | if !two_factor_enabled(&state.store, &user_id).await? { | 853 | if !two_factor_enabled(&state.store, &user_id).await? { |
| 630 | return Err(see_other("/settings/security").into()); | 854 | return Err(see_other("/settings/security").into()); |
| 631 | } | 855 | } |
| 632 | - let mut shown = Shown::default(); | 856 | + let mut shown = Shown { |
| 857 | + two_factor_panel: TwoFactorPanel::Disable, | ||
| 858 | + ..Shown::default() | ||
| 859 | + }; | ||
| 633 | if let Err(refused) = require_password(lang, state, &viewer.0, &form.current_password).await? { | 860 | if let Err(refused) = require_password(lang, state, &viewer.0, &form.current_password).await? { |
| 634 | shown.two_factor_error = Some(refused.message.into()); | 861 | shown.two_factor_error = Some(refused.message.into()); |
| 635 | shown.throttled = refused.retry; | 862 | shown.throttled = refused.retry; |
| @@ -729,7 +956,10 @@ async fn two_factor_recovery(cx: &Cx, Form(form): Form<CodeForm>) -> Result<impl | |||
| 729 | if !two_factor_enabled(&state.store, &user_id).await? { | 956 | if !two_factor_enabled(&state.store, &user_id).await? { |
| 730 | return Err(see_other("/settings/security").into()); | 957 | return Err(see_other("/settings/security").into()); |
| 731 | } | 958 | } |
| 732 | - let mut shown = Shown::default(); | 959 | + let mut shown = Shown { |
| 960 | + two_factor_panel: TwoFactorPanel::Regenerate, | ||
| 961 | + ..Shown::default() | ||
| 962 | + }; | ||
| 733 | if let Some(retry) = second_factor_blocked(state, &user_id) { | 963 | if let Some(retry) = second_factor_blocked(state, &user_id) { |
| 734 | shown.two_factor_error = Some(t(lang, Key::ErrThrottled).into()); | 964 | shown.two_factor_error = Some(t(lang, Key::ErrThrottled).into()); |
| 735 | shown.throttled = Some(retry); | 965 | shown.throttled = Some(retry); |
| @@ -1351,4 +1581,184 @@ mod tests { | |||
| 1351 | .await; | 1581 | .await; |
| 1352 | assert_eq!(reply.status, 403); | 1582 | assert_eq!(reply.status, 403); |
| 1353 | } | 1583 | } |
| 1584 | + | ||
| 1585 | + #[tokio::test] | ||
| 1586 | + async fn email_row_says_verified_once_the_address_is_verified() { | ||
| 1587 | + let fx = fixture().await; | ||
| 1588 | + fx.state | ||
| 1589 | + .store | ||
| 1590 | + .set_email(&fx.user.id, "tahinli@example.com") | ||
| 1591 | + .await | ||
| 1592 | + .unwrap(); | ||
| 1593 | + let token = fx | ||
| 1594 | + .state | ||
| 1595 | + .store | ||
| 1596 | + .create_verify_token(&fx.user.id, "tahinli@example.com") | ||
| 1597 | + .await | ||
| 1598 | + .unwrap(); | ||
| 1599 | + assert!( | ||
| 1600 | + fx.state | ||
| 1601 | + .store | ||
| 1602 | + .redeem_verify_token(&token) | ||
| 1603 | + .await | ||
| 1604 | + .unwrap() | ||
| 1605 | + .is_some() | ||
| 1606 | + ); | ||
| 1607 | + let page = send(&fx.router, "GET", "/settings/security", true, "").await; | ||
| 1608 | + assert_eq!(page.status, 200); | ||
| 1609 | + assert!( | ||
| 1610 | + page.body.contains("tahinli@example.com</span> · Verified"), | ||
| 1611 | + "{}", | ||
| 1612 | + page.body | ||
| 1613 | + ); | ||
| 1614 | + } | ||
| 1615 | + | ||
| 1616 | + #[tokio::test] | ||
| 1617 | + async fn email_row_shows_the_queued_verification_mail_while_unverified() { | ||
| 1618 | + let fx = fixture().await; | ||
| 1619 | + let before = send(&fx.router, "GET", "/settings/security", true, "").await; | ||
| 1620 | + assert!(before.body.contains("No email address"), "{}", before.body); | ||
| 1621 | + | ||
| 1622 | + fx.state | ||
| 1623 | + .store | ||
| 1624 | + .set_email(&fx.user.id, "tahinli@example.com") | ||
| 1625 | + .await | ||
| 1626 | + .unwrap(); | ||
| 1627 | + let mail = forge_core::mail::OutgoingMail { | ||
| 1628 | + to: "tahinli@example.com".into(), | ||
| 1629 | + subject: "Verify your address".into(), | ||
| 1630 | + body: "Open the link to verify.".into(), | ||
| 1631 | + message_id: None, | ||
| 1632 | + in_reply_to: None, | ||
| 1633 | + kind: forge_core::mail::MailKind::Verification, | ||
| 1634 | + user_id: Some(fx.user.id.clone()), | ||
| 1635 | + }; | ||
| 1636 | + fx.state | ||
| 1637 | + .store | ||
| 1638 | + .enqueue_mail("verify:security-test", &mail) | ||
| 1639 | + .await | ||
| 1640 | + .unwrap(); | ||
| 1641 | + let page = send(&fx.router, "GET", "/settings/security", true, "").await; | ||
| 1642 | + assert_eq!(page.status, 200); | ||
| 1643 | + assert!( | ||
| 1644 | + page.body | ||
| 1645 | + .contains("tahinli@example.com</span> · Not verified · verification mail queued"), | ||
| 1646 | + "{}", | ||
| 1647 | + page.body | ||
| 1648 | + ); | ||
| 1649 | + } | ||
| 1650 | + | ||
| 1651 | + #[tokio::test] | ||
| 1652 | + async fn the_page_shows_the_device_and_warns_when_codes_run_low() { | ||
| 1653 | + let fx = fixture().await; | ||
| 1654 | + enable_totp_directly(&fx).await; | ||
| 1655 | + let page = send(&fx.router, "GET", "/settings/security", true, "").await; | ||
| 1656 | + assert_eq!(page.status, 200); | ||
| 1657 | + assert!(page.body.contains("Authenticator app")); | ||
| 1658 | + assert!(page.body.contains("Added "), "{}", page.body); | ||
| 1659 | + assert!(page.body.contains("1 of 10 recovery codes unused")); | ||
| 1660 | + assert!(page.body.contains("Running low")); | ||
| 1661 | + assert!(page.body.contains("security-pill on")); | ||
| 1662 | + } | ||
| 1663 | + | ||
| 1664 | + #[tokio::test] | ||
| 1665 | + async fn confirm_saves_the_device_name_and_refuses_a_bad_one() { | ||
| 1666 | + let fx = fixture().await; | ||
| 1667 | + let enable = format!("csrf={CSRF}"); | ||
| 1668 | + send( | ||
| 1669 | + &fx.router, | ||
| 1670 | + "POST", | ||
| 1671 | + "/settings/security/2fa/enable", | ||
| 1672 | + true, | ||
| 1673 | + &enable, | ||
| 1674 | + ) | ||
| 1675 | + .await; | ||
| 1676 | + let sealed = fx | ||
| 1677 | + .state | ||
| 1678 | + .store | ||
| 1679 | + .totp_state(&fx.user.id) | ||
| 1680 | + .await | ||
| 1681 | + .unwrap() | ||
| 1682 | + .unwrap() | ||
| 1683 | + .sealed_secret | ||
| 1684 | + .expect("secret stored"); | ||
| 1685 | + let shared = secret::open(&KEY, &sealed).unwrap(); | ||
| 1686 | + | ||
| 1687 | + // An over-long name is refused, and the code is not spent on it. | ||
| 1688 | + let too_long = format!( | ||
| 1689 | + "csrf={CSRF}&code={}&name={}", | ||
| 1690 | + now_code(&shared), | ||
| 1691 | + "x".repeat(41) | ||
| 1692 | + ); | ||
| 1693 | + let reply = send( | ||
| 1694 | + &fx.router, | ||
| 1695 | + "POST", | ||
| 1696 | + "/settings/security/2fa/confirm", | ||
| 1697 | + true, | ||
| 1698 | + &too_long, | ||
| 1699 | + ) | ||
| 1700 | + .await; | ||
| 1701 | + assert!(reply.body.contains("at most 40 characters")); | ||
| 1702 | + assert!( | ||
| 1703 | + !fx.state | ||
| 1704 | + .store | ||
| 1705 | + .totp_state(&fx.user.id) | ||
| 1706 | + .await | ||
| 1707 | + .unwrap() | ||
| 1708 | + .unwrap() | ||
| 1709 | + .enabled | ||
| 1710 | + ); | ||
| 1711 | + | ||
| 1712 | + let ok = format!("csrf={CSRF}&code={}&name=Work+phone", now_code(&shared)); | ||
| 1713 | + let reply = send( | ||
| 1714 | + &fx.router, | ||
| 1715 | + "POST", | ||
| 1716 | + "/settings/security/2fa/confirm", | ||
| 1717 | + true, | ||
| 1718 | + &ok, | ||
| 1719 | + ) | ||
| 1720 | + .await; | ||
| 1721 | + assert!(reply.body.contains("Recovery codes")); | ||
| 1722 | + let on = fx | ||
| 1723 | + .state | ||
| 1724 | + .store | ||
| 1725 | + .totp_state(&fx.user.id) | ||
| 1726 | + .await | ||
| 1727 | + .unwrap() | ||
| 1728 | + .unwrap(); | ||
| 1729 | + assert!(on.enabled); | ||
| 1730 | + assert_eq!(on.name.as_deref(), Some("Work phone")); | ||
| 1731 | + assert!(on.created_at.is_some()); | ||
| 1732 | + assert!(on.last_used_at.is_some()); | ||
| 1733 | + let page = send(&fx.router, "GET", "/settings/security", true, "").await; | ||
| 1734 | + assert!(page.body.contains("Work phone")); | ||
| 1735 | + } | ||
| 1736 | + | ||
| 1737 | + #[tokio::test] | ||
| 1738 | + async fn a_wrong_password_on_turn_off_reopens_only_that_panel() { | ||
| 1739 | + let fx = fixture().await; | ||
| 1740 | + let shared = enable_totp_directly(&fx).await; | ||
| 1741 | + let bad = format!( | ||
| 1742 | + "csrf={CSRF}¤t_password=nope&code={}", | ||
| 1743 | + now_code(&shared) | ||
| 1744 | + ); | ||
| 1745 | + let reply = send( | ||
| 1746 | + &fx.router, | ||
| 1747 | + "POST", | ||
| 1748 | + "/settings/security/2fa/disable", | ||
| 1749 | + true, | ||
| 1750 | + &bad, | ||
| 1751 | + ) | ||
| 1752 | + .await; | ||
| 1753 | + assert!(reply.body.contains("Current password is incorrect.")); | ||
| 1754 | + assert!( | ||
| 1755 | + reply.body.contains("security-action danger\" open"), | ||
| 1756 | + "turn-off panel should stay open: {}", | ||
| 1757 | + reply.body | ||
| 1758 | + ); | ||
| 1759 | + assert!( | ||
| 1760 | + !reply.body.contains("security-action\" open"), | ||
| 1761 | + "only the turn-off panel should be open" | ||
| 1762 | + ); | ||
| 1763 | + } | ||
| 1354 | } | 1764 | } |
crates/forge-web/src/views/mod.rsmodified+67 -1
| @@ -161,6 +161,12 @@ pub async fn shell( | |||
| 161 | let back = uri(__cx).path_and_query().map(|p| p.as_str().to_owned()); | 161 | let back = uri(__cx).path_and_query().map(|p| p.as_str().to_owned()); |
| 162 | let lang = i18n::lang(__cx, viewer.map(|(user, _)| user)); | 162 | let lang = i18n::lang(__cx, viewer.map(|(user, _)| user)); |
| 163 | let theme_attr = crate::theme::data_theme(__cx, viewer.map(|(user, _)| user)); | 163 | let theme_attr = crate::theme::data_theme(__cx, viewer.map(|(user, _)| user)); |
| 164 | + // Always set, sage included, so a page never keeps the accent of the one before it. | ||
| 165 | + let stored_accent = match viewer { | ||
| 166 | + Some((user, _)) => user.accent.as_str(), | ||
| 167 | + None => crate::accent_palette::DEFAULT, | ||
| 168 | + }; | ||
| 169 | + let accent_id = crate::accent::resolve(stored_accent).id; | ||
| 164 | // The stored preference, "auto" included, drives the button: its icon, its label and the | 170 | // The stored preference, "auto" included, drives the button: its icon, its label and the |
| 165 | // value it posts (the next preference in the cycle auto, light, dark). | 171 | // value it posts (the next preference in the cycle auto, light, dark). |
| 166 | let theme_pref = crate::theme::preference(__cx, viewer.map(|(user, _)| user)); | 172 | let theme_pref = crate::theme::preference(__cx, viewer.map(|(user, _)| user)); |
| @@ -190,7 +196,7 @@ pub async fn shell( | |||
| 190 | let unread_aside = unread_badge.clone(); | 196 | let unread_aside = unread_badge.clone(); |
| 191 | Ok(view! { | 197 | Ok(view! { |
| 192 | <!DOCTYPE html> | 198 | <!DOCTYPE html> |
| 193 | - <html lang=(lang.code()) data-theme=(theme_attr)> | 199 | + <html lang=(lang.code()) data-theme=(theme_attr) data-accent=(accent_id)> |
| 194 | <head> | 200 | <head> |
| 195 | <meta charset="utf-8"> | 201 | <meta charset="utf-8"> |
| 196 | <meta name="viewport" content="width=device-width, initial-scale=1"> | 202 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| @@ -948,4 +954,64 @@ mod shell_tests { | |||
| 948 | assert!(html.contains("<main tabindex=\"-1\">")); | 954 | assert!(html.contains("<main tabindex=\"-1\">")); |
| 949 | assert!(html.contains("data-hard=\"true\" method=\"post\" action=\"/login\"")); | 955 | assert!(html.contains("data-hard=\"true\" method=\"post\" action=\"/login\"")); |
| 950 | } | 956 | } |
| 957 | + | ||
| 958 | + /// The `<html …>` start tag of a page. | ||
| 959 | + fn html_tag(page: &str) -> &str { | ||
| 960 | + let at = page.find("<html").expect("the page has an html tag"); | ||
| 961 | + let len = page[at..].find('>').expect("the html tag closes"); | ||
| 962 | + &page[at..at + len + 1] | ||
| 963 | + } | ||
| 964 | + | ||
| 965 | + /// The `<html>` tag of `/settings/sessions` for a signed-in user whose stored accent is `accent`. | ||
| 966 | + async fn html_tag_for_accent(accent: &str) -> String { | ||
| 967 | + use crate::auth::SESSION_COOKIE; | ||
| 968 | + let dir = tempfile::tempdir().expect("tempdir"); | ||
| 969 | + let state = crate::test_support::test_state(dir.path()).await; | ||
| 970 | + let store = state.store.clone(); | ||
| 971 | + let router = crate::test_support::app_router(state); | ||
| 972 | + let user = store | ||
| 973 | + .create_user("tahinli", None, "x", false) | ||
| 974 | + .await | ||
| 975 | + .expect("user"); | ||
| 976 | + store.set_accent(&user.id, accent).await.expect("accent"); | ||
| 977 | + crate::test_support::create_session(&store, &user.id, "accent-token", "accent-csrf").await; | ||
| 978 | + let req = Request::builder() | ||
| 979 | + .method("GET") | ||
| 980 | + .uri("/settings/sessions") | ||
| 981 | + .header("cookie", format!("__Host-{SESSION_COOKIE}=accent-token")) | ||
| 982 | + .body(Body::empty()) | ||
| 983 | + .unwrap(); | ||
| 984 | + let res = router.handle(req).await; | ||
| 985 | + assert_eq!(res.status().as_u16(), 200); | ||
| 986 | + let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap(); | ||
| 987 | + html_tag(&String::from_utf8_lossy(&bytes)).to_owned() | ||
| 988 | + } | ||
| 989 | + | ||
| 990 | + #[tokio::test] | ||
| 991 | + async fn the_html_tag_carries_the_viewers_accent() { | ||
| 992 | + let ocean = html_tag_for_accent("ocean").await; | ||
| 993 | + assert!(ocean.contains("data-accent=\"ocean\""), "{ocean}"); | ||
| 994 | + let sage = html_tag_for_accent("sage").await; | ||
| 995 | + assert!(sage.contains("data-accent=\"sage\""), "{sage}"); | ||
| 996 | + // A stored id that is no longer offered falls back to the default, never to nothing. | ||
| 997 | + let removed = html_tag_for_accent("removed-palette").await; | ||
| 998 | + assert!(removed.contains("data-accent=\"sage\""), "{removed}"); | ||
| 999 | + } | ||
| 1000 | + | ||
| 1001 | + #[tokio::test] | ||
| 1002 | + async fn anonymous_pages_render_the_default_accent() { | ||
| 1003 | + let dir = tempfile::tempdir().expect("tempdir"); | ||
| 1004 | + let state = crate::test_support::test_state(dir.path()).await; | ||
| 1005 | + let router = crate::test_support::app_router(state); | ||
| 1006 | + let req = Request::builder() | ||
| 1007 | + .method("GET") | ||
| 1008 | + .uri("/login") | ||
| 1009 | + .body(Body::empty()) | ||
| 1010 | + .unwrap(); | ||
| 1011 | + let res = router.handle(req).await; | ||
| 1012 | + let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap(); | ||
| 1013 | + let html = String::from_utf8_lossy(&bytes); | ||
| 1014 | + let tag = html_tag(&html); | ||
| 1015 | + assert!(tag.contains("data-accent=\"sage\""), "{tag}"); | ||
| 1016 | + } | ||
| 951 | } | 1017 | } |
crates/forge-web/tests/ui_prefs_e2e.rsmodified+112 -2
| @@ -110,6 +110,24 @@ fn html_theme(body: &str) -> Option<String> { | |||
| 110 | doc.root_element().attr("data-theme").map(str::to_owned) | 110 | doc.root_element().attr("data-theme").map(str::to_owned) |
| 111 | } | 111 | } |
| 112 | 112 | ||
| 113 | +/// The `data-accent` attribute of `<html>`. | ||
| 114 | +fn html_accent(body: &str) -> Option<String> { | ||
| 115 | + let doc = scraper::Html::parse_document(body); | ||
| 116 | + doc.root_element().attr("data-accent").map(str::to_owned) | ||
| 117 | +} | ||
| 118 | + | ||
| 119 | +/// The value of the checked radio button in the group `name` on a page. | ||
| 120 | +fn checked_radio(body: &str, name: &str) -> Option<String> { | ||
| 121 | + let doc = scraper::Html::parse_document(body); | ||
| 122 | + let selector = | ||
| 123 | + scraper::Selector::parse(&format!("input[type=\"radio\"][name=\"{name}\"][checked]")) | ||
| 124 | + .expect("selector"); | ||
| 125 | + doc.select(&selector) | ||
| 126 | + .next() | ||
| 127 | + .and_then(|el| el.value().attr("value")) | ||
| 128 | + .map(str::to_owned) | ||
| 129 | +} | ||
| 130 | + | ||
| 113 | /// The option value that is selected in the `<select name="...">` on a page. | 131 | /// The option value that is selected in the `<select name="...">` on a page. |
| 114 | fn selected_option(body: &str, select: &str) -> Option<String> { | 132 | fn selected_option(body: &str, select: &str) -> Option<String> { |
| 115 | let doc = scraper::Html::parse_document(body); | 133 | let doc = scraper::Html::parse_document(body); |
| @@ -228,7 +246,12 @@ async fn appearance_setting_persists_and_renders_the_html_attribute() { | |||
| 228 | .http | 246 | .http |
| 229 | .post_form( | 247 | .post_form( |
| 230 | "/settings/appearance", | 248 | "/settings/appearance", |
| 231 | - &[("csrf", &csrf), ("theme", "dark"), ("language", "tr")], | 249 | + &[ |
| 250 | + ("csrf", &csrf), | ||
| 251 | + ("theme", "dark"), | ||
| 252 | + ("accent", "sage"), | ||
| 253 | + ("language", "tr"), | ||
| 254 | + ], | ||
| 232 | Some(&session), | 255 | Some(&session), |
| 233 | ) | 256 | ) |
| 234 | .await; | 257 | .await; |
| @@ -265,6 +288,88 @@ async fn appearance_setting_persists_and_renders_the_html_attribute() { | |||
| 265 | ); | 288 | ); |
| 266 | } | 289 | } |
| 267 | 290 | ||
| 291 | +#[tokio::test] | ||
| 292 | +async fn accent_setting_persists_and_renders_the_html_attribute() { | ||
| 293 | + let env = start().await; | ||
| 294 | + let session = login(&env.http, "tahinli").await; | ||
| 295 | + | ||
| 296 | + let page = env.http.get("/settings/appearance", Some(&session)).await; | ||
| 297 | + assert_eq!(checked_radio(&page.body, "accent").as_deref(), Some("sage")); | ||
| 298 | + assert_eq!(html_accent(&page.body).as_deref(), Some("sage")); | ||
| 299 | + let csrf = input_value(&page.body, "csrf"); | ||
| 300 | + | ||
| 301 | + let saved = env | ||
| 302 | + .http | ||
| 303 | + .post_form( | ||
| 304 | + "/settings/appearance", | ||
| 305 | + &[ | ||
| 306 | + ("csrf", &csrf), | ||
| 307 | + ("theme", "light"), | ||
| 308 | + ("accent", "ocean"), | ||
| 309 | + ("language", "en"), | ||
| 310 | + ], | ||
| 311 | + Some(&session), | ||
| 312 | + ) | ||
| 313 | + .await; | ||
| 314 | + assert_eq!(saved.status, 303, "save: {}", saved.body); | ||
| 315 | + | ||
| 316 | + let page = env.http.get("/settings/appearance", Some(&session)).await; | ||
| 317 | + assert_eq!( | ||
| 318 | + checked_radio(&page.body, "accent").as_deref(), | ||
| 319 | + Some("ocean") | ||
| 320 | + ); | ||
| 321 | + assert_eq!(html_accent(&page.body).as_deref(), Some("ocean")); | ||
| 322 | + | ||
| 323 | + // Malformed or unknown ids change nothing. | ||
| 324 | + for accent in ["Ocean", "../x", "neon", ""] { | ||
| 325 | + let form = [ | ||
| 326 | + ("csrf", csrf.as_str()), | ||
| 327 | + ("theme", "light"), | ||
| 328 | + ("language", "en"), | ||
| 329 | + ("accent", accent), | ||
| 330 | + ]; | ||
| 331 | + let res = env | ||
| 332 | + .http | ||
| 333 | + .post_form("/settings/appearance", &form, Some(&session)) | ||
| 334 | + .await; | ||
| 335 | + assert_ne!(res.status, 303, "bad accent {accent:?} must not save"); | ||
| 336 | + } | ||
| 337 | + let page = env.http.get("/settings/appearance", Some(&session)).await; | ||
| 338 | + assert_eq!( | ||
| 339 | + checked_radio(&page.body, "accent").as_deref(), | ||
| 340 | + Some("ocean") | ||
| 341 | + ); | ||
| 342 | + assert_eq!(html_accent(&page.body).as_deref(), Some("ocean")); | ||
| 343 | +} | ||
| 344 | + | ||
| 345 | +#[tokio::test] | ||
| 346 | +async fn appearance_save_without_accent_keeps_the_stored_accent() { | ||
| 347 | + let env = start().await; | ||
| 348 | + let session = login(&env.http, "tahinli").await; | ||
| 349 | + | ||
| 350 | + let page = env.http.get("/settings/appearance", Some(&session)).await; | ||
| 351 | + let csrf = input_value(&page.body, "csrf"); | ||
| 352 | + let before = checked_radio(&page.body, "accent"); | ||
| 353 | + assert!(before.is_some(), "an accent is always selected"); | ||
| 354 | + let saved = env | ||
| 355 | + .http | ||
| 356 | + .post_form( | ||
| 357 | + "/settings/appearance", | ||
| 358 | + &[("csrf", &csrf), ("theme", "dark"), ("language", "en")], | ||
| 359 | + Some(&session), | ||
| 360 | + ) | ||
| 361 | + .await; | ||
| 362 | + assert_eq!(saved.status, 303, "save without accent: {}", saved.body); | ||
| 363 | + | ||
| 364 | + let page = env.http.get("/settings/appearance", Some(&session)).await; | ||
| 365 | + assert_eq!( | ||
| 366 | + selected_option(&page.body, "theme").as_deref(), | ||
| 367 | + Some("dark") | ||
| 368 | + ); | ||
| 369 | + assert_eq!(checked_radio(&page.body, "accent"), before); | ||
| 370 | + assert_eq!(html_accent(&page.body), before); | ||
| 371 | +} | ||
| 372 | + | ||
| 268 | #[tokio::test] | 373 | #[tokio::test] |
| 269 | async fn appearance_save_without_a_valid_csrf_token_is_403() { | 374 | async fn appearance_save_without_a_valid_csrf_token_is_403() { |
| 270 | let env = start().await; | 375 | let env = start().await; |
| @@ -397,7 +502,12 @@ async fn signed_in_toggle_saves_the_preference_and_returns_to_back() { | |||
| 397 | .http | 502 | .http |
| 398 | .post_form( | 503 | .post_form( |
| 399 | "/settings/appearance", | 504 | "/settings/appearance", |
| 400 | - &[("csrf", &csrf), ("theme", "auto"), ("language", "tr")], | 505 | + &[ |
| 506 | + ("csrf", &csrf), | ||
| 507 | + ("theme", "auto"), | ||
| 508 | + ("accent", "sage"), | ||
| 509 | + ("language", "tr"), | ||
| 510 | + ], | ||
| 401 | Some(&session), | 511 | Some(&session), |
| 402 | ) | 512 | ) |
| 403 | .await; | 513 | .await; |
docs/ci.mdmodified+2 -2
| @@ -130,10 +130,10 @@ The left half of the badge, its label, is picked in this order: | |||
| 130 | ignored. Labels are cut at 64 characters. | 130 | ignored. Labels are cut at 64 characters. |
| 131 | 2. The job name, when `&job=` is given. | 131 | 2. The job name, when `&job=` is given. |
| 132 | 3. The `name` from `.forge/ci.toml` at the run's commit. | 132 | 3. The `name` from `.forge/ci.toml` at the run's commit. |
| 133 | -4. `ci`. | 133 | +4. `build`. |
| 134 | 134 | ||
| 135 | With no run on the branch the badge says `no status`, and the label is `?label=`, or the job name, | 135 | With no run on the branch the badge says `no status`, and the label is `?label=`, or the job name, |
| 136 | -or `ci`. | 136 | +or `build`. |
| 137 | 137 | ||
| 138 | ## Security model | 138 | ## Security model |
| 139 | 139 | ||
style/main.scssmodified+700 -405
| @@ -59,8 +59,11 @@ | |||
| 59 | src: url("/assets/fonts/ibm-plex-mono-2.5.0-400-italic.woff2") format("woff2"); | 59 | src: url("/assets/fonts/ibm-plex-mono-2.5.0-400-italic.woff2") format("woff2"); |
| 60 | } | 60 | } |
| 61 | 61 | ||
| 62 | -// Palette: sage mock tokens. The dark values are repeated in the two dark blocks | 62 | +// Accent tokens (light and dark) are generated into _accents.scss from src/accent_palette.rs. |
| 63 | -// below and must stay identical. | 63 | +// They are imported here so they keep their place in the cascade; the neutral tokens follow. |
| 64 | +@import "accents"; | ||
| 65 | + | ||
| 66 | +// The neutral dark values are repeated in the two dark blocks below and must stay identical. | ||
| 64 | :root { | 67 | :root { |
| 65 | --bg: #F6F8F5; | 68 | --bg: #F6F8F5; |
| 66 | --surface: #FFFFFF; | 69 | --surface: #FFFFFF; |
| @@ -70,11 +73,6 @@ | |||
| 70 | --muted: #69736B; | 73 | --muted: #69736B; |
| 71 | --border: #DDE3DB; | 74 | --border: #DDE3DB; |
| 72 | --border-strong: #C5CFC3; | 75 | --border-strong: #C5CFC3; |
| 73 | - --accent: #5E7D63; | ||
| 74 | - --accent-ink: #4A6750; | ||
| 75 | - --accent-soft: #E4ECE3; | ||
| 76 | - --accent-text: #FFFFFF; | ||
| 77 | - --focus: #4A6750; | ||
| 78 | --ok: #1D7A62; | 76 | --ok: #1D7A62; |
| 79 | --warn: #9A6200; | 77 | --warn: #9A6200; |
| 80 | --bad: #B0413A; | 78 | --bad: #B0413A; |
| @@ -84,8 +82,6 @@ | |||
| 84 | --alert-bg: #F8E1DE; | 82 | --alert-bg: #F8E1DE; |
| 85 | --alert-text: #7D2B25; | 83 | --alert-text: #7D2B25; |
| 86 | --code-bg: #EEF2EC; | 84 | --code-bg: #EEF2EC; |
| 87 | - --public-bg: #E4ECE3; | ||
| 88 | - --public-text: #4A6750; | ||
| 89 | --private-bg: #EEF2EC; | 85 | --private-bg: #EEF2EC; |
| 90 | --private-text: #3A433D; | 86 | --private-text: #3A433D; |
| 91 | --add-bg: #DCF2EA; | 87 | --add-bg: #DCF2EA; |
| @@ -94,19 +90,11 @@ | |||
| 94 | --del-bg: #F8E1DE; | 90 | --del-bg: #F8E1DE; |
| 95 | --del-text: #7D2B25; | 91 | --del-text: #7D2B25; |
| 96 | --del-mark: #B0413A; | 92 | --del-mark: #B0413A; |
| 97 | - --hunk-bg: #EDF1EB; | ||
| 98 | - --hunk-text: #3F5F46; | ||
| 99 | --ln-text: #69736B; | 93 | --ln-text: #69736B; |
| 100 | --row-target: #FFF4C2; | 94 | --row-target: #FFF4C2; |
| 101 | - --note: #4A6750; | ||
| 102 | --tip: #1D7A62; | 95 | --tip: #1D7A62; |
| 103 | --important: #6A4BB0; | 96 | --important: #6A4BB0; |
| 104 | --warning: #9A6200; | 97 | --warning: #9A6200; |
| 105 | - --h0: #E6ECE4; | ||
| 106 | - --h1: #C6D9C8; | ||
| 107 | - --h2: #9DBDA2; | ||
| 108 | - --h3: #6F9676; | ||
| 109 | - --h4: #3F5F46; | ||
| 110 | --shadow: 0 10px 28px rgba(30, 36, 32, .10); | 98 | --shadow: 0 10px 28px rgba(30, 36, 32, .10); |
| 111 | --radius: 10px; | 99 | --radius: 10px; |
| 112 | --font: "Figtree", system-ui, -apple-system, "Segoe UI", sans-serif; | 100 | --font: "Figtree", system-ui, -apple-system, "Segoe UI", sans-serif; |
| @@ -128,11 +116,6 @@ | |||
| 128 | --muted: #97A198; | 116 | --muted: #97A198; |
| 129 | --border: #2A322C; | 117 | --border: #2A322C; |
| 130 | --border-strong: #3A443C; | 118 | --border-strong: #3A443C; |
| 131 | - --accent: #9DBEA2; | ||
| 132 | - --accent-ink: #B5D2B9; | ||
| 133 | - --accent-soft: #233026; | ||
| 134 | - --accent-text: #0F1510; | ||
| 135 | - --focus: #9DBEA2; | ||
| 136 | --ok: #7CCBAE; | 119 | --ok: #7CCBAE; |
| 137 | --warn: #E6B765; | 120 | --warn: #E6B765; |
| 138 | --bad: #F09A90; | 121 | --bad: #F09A90; |
| @@ -142,8 +125,6 @@ | |||
| 142 | --alert-bg: #3A1E1C; | 125 | --alert-bg: #3A1E1C; |
| 143 | --alert-text: #F2B8B0; | 126 | --alert-text: #F2B8B0; |
| 144 | --code-bg: #1F261F; | 127 | --code-bg: #1F261F; |
| 145 | - --public-bg: #233026; | ||
| 146 | - --public-text: #B5D2B9; | ||
| 147 | --private-bg: #1F261F; | 128 | --private-bg: #1F261F; |
| 148 | --private-text: #C4CCC3; | 129 | --private-text: #C4CCC3; |
| 149 | --add-bg: #143029; | 130 | --add-bg: #143029; |
| @@ -152,19 +133,11 @@ | |||
| 152 | --del-bg: #3A1E1C; | 133 | --del-bg: #3A1E1C; |
| 153 | --del-text: #F2B8B0; | 134 | --del-text: #F2B8B0; |
| 154 | --del-mark: #F09A90; | 135 | --del-mark: #F09A90; |
| 155 | - --hunk-bg: #1E2620; | ||
| 156 | - --hunk-text: #9DBEA2; | ||
| 157 | --ln-text: #97A198; | 136 | --ln-text: #97A198; |
| 158 | --row-target: #3A3510; | 137 | --row-target: #3A3510; |
| 159 | - --note: #B5D2B9; | ||
| 160 | --tip: #7CCBAE; | 138 | --tip: #7CCBAE; |
| 161 | --important: #C4A7FF; | 139 | --important: #C4A7FF; |
| 162 | --warning: #E6B765; | 140 | --warning: #E6B765; |
| 163 | - --h0: #1F2722; | ||
| 164 | - --h1: #2D3D31; | ||
| 165 | - --h2: #41604A; | ||
| 166 | - --h3: #628A6C; | ||
| 167 | - --h4: #9DBEA2; | ||
| 168 | --shadow: 0 10px 28px rgba(0, 0, 0, .45); | 141 | --shadow: 0 10px 28px rgba(0, 0, 0, .45); |
| 169 | color-scheme: dark; | 142 | color-scheme: dark; |
| 170 | } | 143 | } |
| @@ -183,11 +156,6 @@ | |||
| 183 | --muted: #97A198; | 156 | --muted: #97A198; |
| 184 | --border: #2A322C; | 157 | --border: #2A322C; |
| 185 | --border-strong: #3A443C; | 158 | --border-strong: #3A443C; |
| 186 | - --accent: #9DBEA2; | ||
| 187 | - --accent-ink: #B5D2B9; | ||
| 188 | - --accent-soft: #233026; | ||
| 189 | - --accent-text: #0F1510; | ||
| 190 | - --focus: #9DBEA2; | ||
| 191 | --ok: #7CCBAE; | 159 | --ok: #7CCBAE; |
| 192 | --warn: #E6B765; | 160 | --warn: #E6B765; |
| 193 | --bad: #F09A90; | 161 | --bad: #F09A90; |
| @@ -197,8 +165,6 @@ | |||
| 197 | --alert-bg: #3A1E1C; | 165 | --alert-bg: #3A1E1C; |
| 198 | --alert-text: #F2B8B0; | 166 | --alert-text: #F2B8B0; |
| 199 | --code-bg: #1F261F; | 167 | --code-bg: #1F261F; |
| 200 | - --public-bg: #233026; | ||
| 201 | - --public-text: #B5D2B9; | ||
| 202 | --private-bg: #1F261F; | 168 | --private-bg: #1F261F; |
| 203 | --private-text: #C4CCC3; | 169 | --private-text: #C4CCC3; |
| 204 | --add-bg: #143029; | 170 | --add-bg: #143029; |
| @@ -207,19 +173,11 @@ | |||
| 207 | --del-bg: #3A1E1C; | 173 | --del-bg: #3A1E1C; |
| 208 | --del-text: #F2B8B0; | 174 | --del-text: #F2B8B0; |
| 209 | --del-mark: #F09A90; | 175 | --del-mark: #F09A90; |
| 210 | - --hunk-bg: #1E2620; | ||
| 211 | - --hunk-text: #9DBEA2; | ||
| 212 | --ln-text: #97A198; | 176 | --ln-text: #97A198; |
| 213 | --row-target: #3A3510; | 177 | --row-target: #3A3510; |
| 214 | - --note: #B5D2B9; | ||
| 215 | --tip: #7CCBAE; | 178 | --tip: #7CCBAE; |
| 216 | --important: #C4A7FF; | 179 | --important: #C4A7FF; |
| 217 | --warning: #E6B765; | 180 | --warning: #E6B765; |
| 218 | - --h0: #1F2722; | ||
| 219 | - --h1: #2D3D31; | ||
| 220 | - --h2: #41604A; | ||
| 221 | - --h3: #628A6C; | ||
| 222 | - --h4: #9DBEA2; | ||
| 223 | --shadow: 0 10px 28px rgba(0, 0, 0, .45); | 181 | --shadow: 0 10px 28px rgba(0, 0, 0, .45); |
| 224 | color-scheme: dark; | 182 | color-scheme: dark; |
| 225 | } | 183 | } |
| @@ -259,6 +217,13 @@ a { | |||
| 259 | border-radius: 6px; | 217 | border-radius: 6px; |
| 260 | } | 218 | } |
| 261 | 219 | ||
| 220 | +// <main tabindex="-1"> only takes focus from nav.js after a soft navigation, so screen readers | ||
| 221 | +// announce the new page. It is never a keyboard target; without this, returning to the window | ||
| 222 | +// (alt+tab) draws the focus ring around the whole content column. | ||
| 223 | +main[tabindex="-1"]:focus { | ||
| 224 | + outline: none; | ||
| 225 | +} | ||
| 226 | + | ||
| 262 | h1, | 227 | h1, |
| 263 | h2 { | 228 | h2 { |
| 264 | line-height: 1.25; | 229 | line-height: 1.25; |
| @@ -1718,15 +1683,10 @@ code { | |||
| 1718 | } | 1683 | } |
| 1719 | } | 1684 | } |
| 1720 | 1685 | ||
| 1721 | -// Profile: the owner's edit button, the pinned repo grid and the section heads. | 1686 | +// Profile: the owner's edit button, the pinned repo grid and the section heads. The button keeps |
| 1687 | +// its natural width (the `.button` base) and sits under the local-time line in the header. | ||
| 1722 | .profile-edit { | 1688 | .profile-edit { |
| 1723 | - display: flex; | 1689 | + margin-top: 12px; |
| 1724 | - align-items: center; | ||
| 1725 | - justify-content: center; | ||
| 1726 | - width: 100%; | ||
| 1727 | - height: 34px; | ||
| 1728 | - box-sizing: border-box; | ||
| 1729 | - text-align: center; | ||
| 1730 | } | 1690 | } |
| 1731 | 1691 | ||
| 1732 | // Profile tabs: a horizontal underline strip under the header, at every width. Reuses the | 1692 | // Profile tabs: a horizontal underline strip under the header, at every width. Reuses the |
| @@ -1897,6 +1857,64 @@ code { | |||
| 1897 | max-width: 24rem; | 1857 | max-width: 24rem; |
| 1898 | } | 1858 | } |
| 1899 | 1859 | ||
| 1860 | +// Accent picker (appearance settings). Each choice is a native radio, so the keyboard and screen | ||
| 1861 | +// readers work as usual; the swatch beside it shows the colour. The swatch colours come from the | ||
| 1862 | +// generated _accents.scss, so nothing here names a colour. | ||
| 1863 | +.accent-picker { | ||
| 1864 | + display: grid; | ||
| 1865 | + gap: 8px; | ||
| 1866 | + min-width: 0; | ||
| 1867 | + margin: 0; | ||
| 1868 | + padding: 0; | ||
| 1869 | + border: 0; | ||
| 1870 | + | ||
| 1871 | + legend { | ||
| 1872 | + padding: 0; | ||
| 1873 | + margin-bottom: 6px; | ||
| 1874 | + font-weight: 600; | ||
| 1875 | + } | ||
| 1876 | +} | ||
| 1877 | + | ||
| 1878 | +.accent-choices { | ||
| 1879 | + display: flex; | ||
| 1880 | + flex-wrap: wrap; | ||
| 1881 | + gap: 10px 18px; | ||
| 1882 | +} | ||
| 1883 | + | ||
| 1884 | +.accent-choice { | ||
| 1885 | + display: inline-flex; | ||
| 1886 | + align-items: center; | ||
| 1887 | + gap: 8px; | ||
| 1888 | + position: relative; | ||
| 1889 | + cursor: pointer; | ||
| 1890 | + | ||
| 1891 | + input { | ||
| 1892 | + position: absolute; | ||
| 1893 | + width: 1px; | ||
| 1894 | + height: 1px; | ||
| 1895 | + margin: 0; | ||
| 1896 | + opacity: 0; | ||
| 1897 | + } | ||
| 1898 | + | ||
| 1899 | + input:focus-visible + .accent-swatch { | ||
| 1900 | + outline: 2px solid var(--focus); | ||
| 1901 | + outline-offset: 3px; | ||
| 1902 | + } | ||
| 1903 | + | ||
| 1904 | + input:checked + .accent-swatch { | ||
| 1905 | + box-shadow: 0 0 0 2px var(--surface), 0 0 0 4px var(--focus); | ||
| 1906 | + } | ||
| 1907 | +} | ||
| 1908 | + | ||
| 1909 | +.accent-swatch { | ||
| 1910 | + display: inline-block; | ||
| 1911 | + flex: none; | ||
| 1912 | + width: 28px; | ||
| 1913 | + height: 28px; | ||
| 1914 | + border-radius: 50%; | ||
| 1915 | + border: 1px solid var(--border-strong); | ||
| 1916 | +} | ||
| 1917 | + | ||
| 1900 | // branch protection | 1918 | // branch protection |
| 1901 | // Settings page: rules table with a Remove form per row, then the add/update form. | 1919 | // Settings page: rules table with a Remove form per row, then the add/update form. |
| 1902 | .branch-rules { | 1920 | .branch-rules { |
| @@ -2044,6 +2062,32 @@ code { | |||
| 2044 | 2062 | ||
| 2045 | // issues | 2063 | // issues |
| 2046 | // Issue list and new-issue form. Label chip colors come from the per-repo labels.css. | 2064 | // Issue list and new-issue form. Label chip colors come from the per-repo labels.css. |
| 2065 | +.mail-filters { | ||
| 2066 | + display: flex; | ||
| 2067 | + flex-wrap: wrap; | ||
| 2068 | + gap: 8px; | ||
| 2069 | + margin: 12px 0; | ||
| 2070 | +} | ||
| 2071 | + | ||
| 2072 | +.mail-filters .subnav-link { | ||
| 2073 | + padding: 4px 10px; | ||
| 2074 | + border: 1px solid var(--border); | ||
| 2075 | + border-radius: 999px; | ||
| 2076 | +} | ||
| 2077 | + | ||
| 2078 | +.mail-filters .subnav-link.current { | ||
| 2079 | + border-color: var(--accent); | ||
| 2080 | +} | ||
| 2081 | + | ||
| 2082 | +.mail-queue .mail-actions { | ||
| 2083 | + white-space: nowrap; | ||
| 2084 | +} | ||
| 2085 | + | ||
| 2086 | +.mail-queue .mail-actions form { | ||
| 2087 | + display: inline; | ||
| 2088 | + margin-right: 6px; | ||
| 2089 | +} | ||
| 2090 | + | ||
| 2047 | .tab-count { | 2091 | .tab-count { |
| 2048 | display: inline-block; | 2092 | display: inline-block; |
| 2049 | min-width: 1.6em; | 2093 | min-width: 1.6em; |
| @@ -3502,6 +3546,7 @@ span.reaction { | |||
| 3502 | // CI: run list, run page, job page and log. | 3546 | // CI: run list, run page, job page and log. |
| 3503 | .ci-state { | 3547 | .ci-state { |
| 3504 | display: inline-block; | 3548 | display: inline-block; |
| 3549 | + white-space: nowrap; | ||
| 3505 | font-size: 0.75rem; | 3550 | font-size: 0.75rem; |
| 3506 | font-weight: 600; | 3551 | font-weight: 600; |
| 3507 | padding: 2px 8px; | 3552 | padding: 2px 8px; |
| @@ -3574,55 +3619,194 @@ span.reaction { | |||
| 3574 | padding-left: 20px; | 3619 | padding-left: 20px; |
| 3575 | } | 3620 | } |
| 3576 | 3621 | ||
| 3577 | -// CI runs list. The header holds the title, the run count and two menus (Run workflow and the | 3622 | +// CI: runs list and run detail. The split view has the runs on the left and the selected run on the |
| 3578 | -// status badge). The count and the card sit in the live region, which is display: contents, so | 3623 | +// right. Bars and the timeline are SVG, so their sizes are in viewBox units and need no inline style. |
| 3579 | -// they share the header's flex row and the card wraps onto its own line. | 3624 | +// The timeline sizes match the constants in crates/forge-web/src/pages/ci_runs.rs. |
| 3580 | -.ci-list-head { | 3625 | +.ci-split { |
| 3581 | - display: flex; | 3626 | + display: grid; |
| 3582 | - flex-wrap: wrap; | 3627 | + grid-template-columns: minmax(0, 2fr) minmax(0, 3fr); |
| 3583 | - align-items: center; | 3628 | + gap: 20px; |
| 3584 | - gap: 8px 12px; | 3629 | + align-items: start; |
| 3585 | - margin-bottom: 12px; | 3630 | +} |
| 3631 | + | ||
| 3632 | +// The hatch pattern lives in a zero-size SVG at the top of the split view. | ||
| 3633 | +.ci-defs { | ||
| 3634 | + position: absolute; | ||
| 3635 | + width: 0; | ||
| 3636 | + height: 0; | ||
| 3637 | + overflow: hidden; | ||
| 3638 | +} | ||
| 3639 | + | ||
| 3640 | +.ci-hatch-ink { | ||
| 3641 | + fill: var(--border-strong); | ||
| 3586 | } | 3642 | } |
| 3587 | 3643 | ||
| 3588 | -.ci-list-title { | 3644 | +.ci-side, |
| 3645 | +.ci-main { | ||
| 3646 | + min-width: 0; | ||
| 3589 | margin: 0; | 3647 | margin: 0; |
| 3590 | - font-size: 1.25rem; | ||
| 3591 | } | 3648 | } |
| 3592 | 3649 | ||
| 3593 | -.ci-tools { | 3650 | +.ci-side-head { |
| 3594 | display: flex; | 3651 | display: flex; |
| 3595 | flex-wrap: wrap; | 3652 | flex-wrap: wrap; |
| 3596 | align-items: center; | 3653 | align-items: center; |
| 3597 | - gap: 8px; | 3654 | + justify-content: space-between; |
| 3598 | - order: 1; | 3655 | + gap: 8px 12px; |
| 3599 | - margin-left: auto; | 3656 | + margin-bottom: 10px; |
| 3600 | } | 3657 | } |
| 3601 | 3658 | ||
| 3602 | -.ci-live { | 3659 | +.ci-side-title { |
| 3603 | - display: contents; | 3660 | + display: flex; |
| 3661 | + align-items: center; | ||
| 3662 | + gap: 8px; | ||
| 3663 | + margin: 0; | ||
| 3664 | + font-size: 0.75rem; | ||
| 3665 | + font-weight: 600; | ||
| 3666 | + letter-spacing: 0.06em; | ||
| 3667 | + text-transform: uppercase; | ||
| 3668 | + color: var(--muted); | ||
| 3604 | } | 3669 | } |
| 3605 | 3670 | ||
| 3606 | .ci-count { | 3671 | .ci-count { |
| 3607 | - align-self: center; | ||
| 3608 | padding: 1px 8px; | 3672 | padding: 1px 8px; |
| 3609 | border-radius: 999px; | 3673 | border-radius: 999px; |
| 3610 | background: var(--surface-2); | 3674 | background: var(--surface-2); |
| 3611 | color: var(--muted); | 3675 | color: var(--muted); |
| 3612 | font-size: 0.8125rem; | 3676 | font-size: 0.8125rem; |
| 3613 | font-weight: 600; | 3677 | font-weight: 600; |
| 3678 | + letter-spacing: 0; | ||
| 3679 | + text-transform: none; | ||
| 3614 | } | 3680 | } |
| 3615 | 3681 | ||
| 3616 | -.ci-list-card { | 3682 | +.ci-tools { |
| 3617 | - order: 2; | 3683 | + display: flex; |
| 3618 | - flex: 1 1 100%; | 3684 | + flex-wrap: wrap; |
| 3619 | - min-width: 0; | 3685 | + align-items: center; |
| 3686 | + gap: 8px; | ||
| 3687 | +} | ||
| 3688 | + | ||
| 3689 | +.ci-scale { | ||
| 3690 | + margin: 0 0 10px; | ||
| 3691 | + font-family: var(--mono); | ||
| 3692 | + font-size: 0.72rem; | ||
| 3693 | + color: var(--muted); | ||
| 3694 | +} | ||
| 3695 | + | ||
| 3696 | +.ci-empty { | ||
| 3697 | + padding: 40px 16px; | ||
| 3698 | + text-align: center; | ||
| 3699 | + | ||
| 3700 | + p { | ||
| 3701 | + margin: 0 0 6px; | ||
| 3702 | + } | ||
| 3703 | +} | ||
| 3704 | + | ||
| 3705 | +.ci-side .pager { | ||
| 3706 | + margin: 14px -20px -20px; | ||
| 3707 | + padding: 12px 20px; | ||
| 3708 | + border-top: 1px solid var(--border); | ||
| 3709 | +} | ||
| 3710 | + | ||
| 3711 | +// The run rows of the list. Each row is a link: a title, its bar and its duration, then its meta line. | ||
| 3712 | +.ci-run-list { | ||
| 3713 | + display: flex; | ||
| 3714 | + flex-direction: column; | ||
| 3715 | + gap: 2px; | ||
| 3620 | margin: 0; | 3716 | margin: 0; |
| 3621 | padding: 0; | 3717 | padding: 0; |
| 3718 | + list-style: none; | ||
| 3719 | +} | ||
| 3720 | + | ||
| 3721 | +.ci-row { | ||
| 3722 | + display: flex; | ||
| 3723 | + flex-direction: column; | ||
| 3724 | + gap: 6px; | ||
| 3725 | + min-width: 0; | ||
| 3726 | + padding: 9px 10px; | ||
| 3727 | + border-radius: 8px; | ||
| 3728 | + color: inherit; | ||
| 3729 | + text-decoration: none; | ||
| 3730 | + | ||
| 3731 | + &:hover { | ||
| 3732 | + background: var(--surface-2); | ||
| 3733 | + } | ||
| 3734 | + | ||
| 3735 | + &[aria-current="true"] { | ||
| 3736 | + background: var(--accent-soft); | ||
| 3737 | + box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent); | ||
| 3738 | + } | ||
| 3739 | +} | ||
| 3740 | + | ||
| 3741 | +.ci-row-title { | ||
| 3742 | + min-width: 0; | ||
| 3743 | + overflow: hidden; | ||
| 3744 | + white-space: nowrap; | ||
| 3745 | + text-overflow: ellipsis; | ||
| 3746 | + font-size: 0.875rem; | ||
| 3747 | + font-weight: 500; | ||
| 3748 | + color: var(--text); | ||
| 3749 | +} | ||
| 3750 | + | ||
| 3751 | +.ci-row[aria-current="true"] .ci-row-title { | ||
| 3752 | + font-weight: 600; | ||
| 3753 | +} | ||
| 3754 | + | ||
| 3755 | +.ci-row-line { | ||
| 3756 | + display: flex; | ||
| 3757 | + align-items: center; | ||
| 3758 | + gap: 10px; | ||
| 3759 | + min-width: 0; | ||
| 3760 | +} | ||
| 3761 | + | ||
| 3762 | +.ci-bar { | ||
| 3763 | + display: block; | ||
| 3764 | + flex: 1 1 0; | ||
| 3765 | + min-width: 0; | ||
| 3766 | + height: 6px; | ||
| 3767 | + border-radius: 3px; | ||
| 3768 | + background: var(--surface-2); | ||
| 3769 | + overflow: hidden; | ||
| 3770 | +} | ||
| 3771 | + | ||
| 3772 | +.ci-row-dur { | ||
| 3773 | + flex: none; | ||
| 3774 | + font-family: var(--mono); | ||
| 3775 | + font-size: 0.78rem; | ||
| 3776 | + color: var(--text-2); | ||
| 3777 | + white-space: nowrap; | ||
| 3778 | +} | ||
| 3779 | + | ||
| 3780 | +.ci-row-meta { | ||
| 3622 | overflow: hidden; | 3781 | overflow: hidden; |
| 3782 | + white-space: nowrap; | ||
| 3783 | + text-overflow: ellipsis; | ||
| 3784 | + font-size: 0.8rem; | ||
| 3785 | + color: var(--muted); | ||
| 3786 | +} | ||
| 3787 | + | ||
| 3788 | +.ci-seg { | ||
| 3789 | + &.ci-ok { | ||
| 3790 | + fill: var(--ok); | ||
| 3791 | + } | ||
| 3792 | + | ||
| 3793 | + &.ci-bad { | ||
| 3794 | + fill: var(--bad); | ||
| 3795 | + } | ||
| 3796 | + | ||
| 3797 | + &.ci-run { | ||
| 3798 | + fill: var(--warn); | ||
| 3799 | + } | ||
| 3800 | + | ||
| 3801 | + &.ci-muted { | ||
| 3802 | + fill: var(--border-strong); | ||
| 3803 | + } | ||
| 3804 | + | ||
| 3805 | + &.ci-rest { | ||
| 3806 | + fill: url(#ci-hatch); | ||
| 3807 | + } | ||
| 3623 | } | 3808 | } |
| 3624 | 3809 | ||
| 3625 | -// The header menus reuse the `.menu` dropdown. The trigger is a compact button with a chevron. | ||
| 3626 | .ci-tool > summary { | 3810 | .ci-tool > summary { |
| 3627 | display: inline-flex; | 3811 | display: inline-flex; |
| 3628 | align-items: center; | 3812 | align-items: center; |
| @@ -3677,410 +3861,263 @@ span.reaction { | |||
| 3677 | } | 3861 | } |
| 3678 | } | 3862 | } |
| 3679 | 3863 | ||
| 3680 | -.ci-empty { | ||
| 3681 | - padding: 40px 16px; | ||
| 3682 | - text-align: center; | ||
| 3683 | 3864 | ||
| 3684 | - p { | 3865 | +// The timeline. The labels take the left column and the track the rest; each box is positioned in |
| 3685 | - margin: 0 0 6px; | 3866 | +// SVG units by the server, so the widths follow the track. |
| 3686 | - } | 3867 | +.ci-gantt-scroll { |
| 3868 | + margin: 0 -4px; | ||
| 3869 | + padding: 0 4px 2px; | ||
| 3870 | + overflow-x: auto; | ||
| 3687 | } | 3871 | } |
| 3688 | 3872 | ||
| 3689 | -.ci-list-card .pager { | 3873 | +.ci-gantt { |
| 3690 | - margin: 0; | 3874 | + display: block; |
| 3691 | - padding: 12px 16px; | 3875 | + width: 100%; |
| 3692 | - border-top: 1px solid var(--border); | 3876 | + min-width: 480px; |
| 3877 | + height: auto; | ||
| 3878 | + font-family: var(--mono); | ||
| 3693 | } | 3879 | } |
| 3694 | 3880 | ||
| 3695 | -.ci-run-list { | 3881 | +.ci-grid { |
| 3696 | - margin: 0; | 3882 | + fill: var(--border); |
| 3697 | - padding: 0; | ||
| 3698 | - list-style: none; | ||
| 3699 | } | 3883 | } |
| 3700 | 3884 | ||
| 3701 | -// Each row is a grid: state icon, title and meta, then the duration and age on the right. | 3885 | +.ci-tick { |
| 3702 | -.ci-run-row { | 3886 | + font-size: 11px; |
| 3703 | - position: relative; | 3887 | + fill: var(--muted); |
| 3704 | - display: grid; | 3888 | +} |
| 3705 | - grid-template-columns: auto minmax(0, 1fr) auto; | ||
| 3706 | - align-items: center; | ||
| 3707 | - gap: 12px; | ||
| 3708 | - padding: 12px 16px; | ||
| 3709 | - cursor: pointer; | ||
| 3710 | 3889 | ||
| 3711 | - &:hover { | 3890 | +.ci-gname { |
| 3712 | - background: var(--surface-2); | 3891 | + font-size: 13px; |
| 3713 | - } | 3892 | + fill: var(--text-2); |
| 3714 | } | 3893 | } |
| 3715 | 3894 | ||
| 3716 | -.ci-run-row + .ci-run-row { | 3895 | +.ci-gsub { |
| 3717 | - border-top: 1px solid var(--border); | 3896 | + font-family: var(--font); |
| 3897 | + font-size: 11px; | ||
| 3898 | + fill: var(--muted); | ||
| 3718 | } | 3899 | } |
| 3719 | 3900 | ||
| 3720 | -// The title link stretches over its row (no JS). The commit link sits above it. | 3901 | +.ci-gbar { |
| 3721 | -.ci-run-link { | 3902 | + rx: 4px; |
| 3722 | - color: var(--text); | ||
| 3723 | - text-decoration: none; | ||
| 3724 | 3903 | ||
| 3725 | - &::after { | 3904 | + &.ci-ok { |
| 3726 | - content: ""; | 3905 | + fill: var(--ok); |
| 3727 | - position: absolute; | ||
| 3728 | - inset: 0; | ||
| 3729 | } | 3906 | } |
| 3730 | 3907 | ||
| 3731 | - &:hover { | 3908 | + &.ci-bad { |
| 3732 | - color: var(--accent-ink); | 3909 | + fill: var(--bad); |
| 3910 | + } | ||
| 3911 | + | ||
| 3912 | + &.ci-run { | ||
| 3913 | + fill: var(--warn); | ||
| 3914 | + } | ||
| 3915 | + | ||
| 3916 | + &.ci-muted { | ||
| 3917 | + fill: var(--surface-2); | ||
| 3918 | + stroke: var(--border-strong); | ||
| 3919 | + stroke-width: 1; | ||
| 3920 | + } | ||
| 3921 | + | ||
| 3922 | + &.ci-wait { | ||
| 3923 | + fill: none; | ||
| 3924 | + stroke: var(--border-strong); | ||
| 3925 | + stroke-width: 1; | ||
| 3926 | + stroke-dasharray: 4 3; | ||
| 3733 | } | 3927 | } |
| 3734 | } | 3928 | } |
| 3735 | 3929 | ||
| 3736 | -.ci-run-commit { | 3930 | +.ci-glead { |
| 3737 | - position: relative; | 3931 | + fill: url(#ci-hatch); |
| 3738 | - z-index: 1; | ||
| 3739 | } | 3932 | } |
| 3740 | 3933 | ||
| 3741 | -.ci-run-body { | 3934 | +// The right edge of a running box breathes. Reduced motion holds it still. |
| 3742 | - min-width: 0; | 3935 | +.ci-gedge { |
| 3936 | + fill: var(--surface); | ||
| 3937 | + animation: ci-breathe 1.8s ease-in-out infinite; | ||
| 3743 | } | 3938 | } |
| 3744 | 3939 | ||
| 3745 | -.ci-run-title { | 3940 | +.ci-gon, |
| 3746 | - margin: 0 0 2px; | 3941 | +.ci-goff { |
| 3747 | - overflow: hidden; | 3942 | + font-size: 11px; |
| 3748 | - font-weight: 600; | ||
| 3749 | - text-overflow: ellipsis; | ||
| 3750 | - white-space: nowrap; | ||
| 3751 | } | 3943 | } |
| 3752 | 3944 | ||
| 3753 | -.ci-run-sub { | 3945 | +.ci-gon { |
| 3754 | - margin: 0; | 3946 | + fill: var(--surface); |
| 3755 | - overflow: hidden; | ||
| 3756 | - text-overflow: ellipsis; | ||
| 3757 | - white-space: nowrap; | ||
| 3758 | - | ||
| 3759 | - code { | ||
| 3760 | - font-size: 0.8125rem; | ||
| 3761 | - } | ||
| 3762 | -} | ||
| 3763 | - | ||
| 3764 | -.ci-branch { | ||
| 3765 | - padding: 0 6px; | ||
| 3766 | - border: 1px solid var(--border); | ||
| 3767 | - border-radius: 999px; | ||
| 3768 | - background: var(--surface); | ||
| 3769 | - color: var(--text-2); | ||
| 3770 | -} | ||
| 3771 | - | ||
| 3772 | -.ci-run-side { | ||
| 3773 | - display: flex; | ||
| 3774 | - flex-direction: column; | ||
| 3775 | - align-items: flex-end; | ||
| 3776 | - gap: 2px; | ||
| 3777 | - text-align: right; | ||
| 3778 | - white-space: nowrap; | ||
| 3779 | - font-variant-numeric: tabular-nums; | ||
| 3780 | } | 3947 | } |
| 3781 | 3948 | ||
| 3782 | -.ci-run-dur { | 3949 | +.ci-goff { |
| 3783 | - display: inline-flex; | 3950 | + fill: var(--muted); |
| 3784 | - align-items: center; | ||
| 3785 | - gap: 4px; | ||
| 3786 | } | 3951 | } |
| 3787 | 3952 | ||
| 3788 | -.ci-clock { | 3953 | +.ci-glink { |
| 3789 | - width: 12px; | ||
| 3790 | - height: 12px; | ||
| 3791 | - flex-shrink: 0; | ||
| 3792 | fill: none; | 3954 | fill: none; |
| 3793 | - stroke: currentColor; | 3955 | + stroke: var(--muted); |
| 3794 | - stroke-width: 1.75; | 3956 | + stroke-width: 1; |
| 3795 | - stroke-linecap: round; | 3957 | + stroke-dasharray: 3 3; |
| 3796 | - stroke-linejoin: round; | 3958 | + vector-effect: non-scaling-stroke; |
| 3797 | -} | ||
| 3798 | - | ||
| 3799 | -// The state icon: a disc with a glyph for finished runs, a ring for running and queued ones. | ||
| 3800 | -.ci-run-icon { | ||
| 3801 | - --ci-icon: var(--muted); | ||
| 3802 | - | ||
| 3803 | - display: inline-flex; | ||
| 3804 | - align-items: center; | ||
| 3805 | - justify-content: center; | ||
| 3806 | - box-sizing: border-box; | ||
| 3807 | - width: 20px; | ||
| 3808 | - height: 20px; | ||
| 3809 | - border-radius: 50%; | ||
| 3810 | - background: var(--ci-icon); | ||
| 3811 | - color: var(--accent-text); | ||
| 3812 | - | ||
| 3813 | - svg { | ||
| 3814 | - width: 12px; | ||
| 3815 | - height: 12px; | ||
| 3816 | - fill: none; | ||
| 3817 | - stroke: currentColor; | ||
| 3818 | - stroke-width: 2; | ||
| 3819 | - stroke-linecap: round; | ||
| 3820 | - stroke-linejoin: round; | ||
| 3821 | - } | ||
| 3822 | - | ||
| 3823 | - &.ci-success { | ||
| 3824 | - --ci-icon: var(--public-text); | ||
| 3825 | - } | ||
| 3826 | - | ||
| 3827 | - &.ci-failure, | ||
| 3828 | - &.ci-error { | ||
| 3829 | - --ci-icon: var(--danger); | ||
| 3830 | - } | ||
| 3831 | - | ||
| 3832 | - &.ci-cancelled, | ||
| 3833 | - &.ci-blocked, | ||
| 3834 | - &.ci-skipped { | ||
| 3835 | - --ci-icon: var(--muted); | ||
| 3836 | - } | ||
| 3837 | - | ||
| 3838 | - &.ci-running, | ||
| 3839 | - &.ci-queued, | ||
| 3840 | - &.ci-waiting_approval { | ||
| 3841 | - --ci-icon: var(--warning); | ||
| 3842 | - | ||
| 3843 | - background: transparent; | ||
| 3844 | - border: 2px solid var(--ci-icon); | ||
| 3845 | - } | ||
| 3846 | - | ||
| 3847 | - &.ci-running { | ||
| 3848 | - border-top-color: transparent; | ||
| 3849 | - animation: ci-spin 0.9s linear infinite; | ||
| 3850 | - } | ||
| 3851 | - | ||
| 3852 | - &.ci-queued::after, | ||
| 3853 | - &.ci-waiting_approval::after { | ||
| 3854 | - content: ""; | ||
| 3855 | - width: 4px; | ||
| 3856 | - height: 4px; | ||
| 3857 | - border-radius: 50%; | ||
| 3858 | - background: var(--ci-icon); | ||
| 3859 | - } | ||
| 3860 | -} | ||
| 3861 | - | ||
| 3862 | -@keyframes ci-spin { | ||
| 3863 | - to { | ||
| 3864 | - transform: rotate(360deg); | ||
| 3865 | - } | ||
| 3866 | } | 3959 | } |
| 3867 | 3960 | ||
| 3868 | -@media (prefers-reduced-motion: reduce) { | 3961 | +@keyframes ci-breathe { |
| 3869 | - .ci-run-icon.ci-running { | 3962 | + 50% { |
| 3870 | - animation: none; | 3963 | + opacity: 0.55; |
| 3871 | } | 3964 | } |
| 3872 | } | 3965 | } |
| 3873 | 3966 | ||
| 3874 | -// Phone width: the duration and age move under the meta line, and the row keeps its icon. | 3967 | +// The jobs of the run: one line each, a link to the job page. |
| 3875 | -@media (max-width: 600px) { | 3968 | +.ci-job-list { |
| 3876 | - .ci-run-row { | 3969 | + margin: 16px 0 0; |
| 3877 | - grid-template-columns: auto minmax(0, 1fr); | 3970 | + padding: 0; |
| 3878 | - row-gap: 6px; | 3971 | + list-style: none; |
| 3879 | - } | 3972 | + border-top: 1px solid var(--border); |
| 3880 | - | ||
| 3881 | - .ci-run-icon { | ||
| 3882 | - grid-row: 1 / span 2; | ||
| 3883 | - } | ||
| 3884 | - | ||
| 3885 | - .ci-run-body, | ||
| 3886 | - .ci-run-side { | ||
| 3887 | - grid-column: 2; | ||
| 3888 | - } | ||
| 3889 | - | ||
| 3890 | - .ci-run-side { | ||
| 3891 | - flex-direction: row; | ||
| 3892 | - align-items: center; | ||
| 3893 | - gap: 10px; | ||
| 3894 | - text-align: left; | ||
| 3895 | - } | ||
| 3896 | - | ||
| 3897 | - // The meta line wraps here, so the commit and the author stay in view. | ||
| 3898 | - .ci-run-sub { | ||
| 3899 | - white-space: normal; | ||
| 3900 | - overflow-wrap: anywhere; | ||
| 3901 | - } | ||
| 3902 | -} | ||
| 3903 | - | ||
| 3904 | -// CI run page: header and job graph. | ||
| 3905 | -// Sizes below match the GRAPH_* constants in crates/forge-web/src/pages/ci_runs.rs: the card is | ||
| 3906 | -// 200x56, columns are 48px apart, cards in a column 16px apart, and the box is padded 16px. | ||
| 3907 | -.ci-run-head { | ||
| 3908 | - display: flex; | ||
| 3909 | - align-items: flex-start; | ||
| 3910 | - justify-content: space-between; | ||
| 3911 | - flex-wrap: wrap; | ||
| 3912 | - gap: 16px; | ||
| 3913 | 3973 | ||
| 3914 | - .ci-actions { | 3974 | + li { |
| 3915 | - margin-top: 0; | 3975 | + border-bottom: 1px solid var(--border); |
| 3916 | } | 3976 | } |
| 3917 | } | 3977 | } |
| 3918 | 3978 | ||
| 3919 | -.ci-run-head-main { | 3979 | +.ci-job-line { |
| 3920 | - flex: 1 1 320px; | 3980 | + display: grid; |
| 3921 | - min-width: 0; | 3981 | + grid-template-columns: 8px minmax(0, 1fr) auto auto 12px; |
| 3922 | -} | 3982 | + gap: 12px; |
| 3923 | - | ||
| 3924 | -.ci-run-title { | ||
| 3925 | - display: flex; | ||
| 3926 | align-items: center; | 3983 | align-items: center; |
| 3927 | - flex-wrap: wrap; | 3984 | + padding: 10px 6px; |
| 3928 | - gap: 8px; | 3985 | + font-size: 0.875rem; |
| 3929 | - margin: 0 0 6px; | 3986 | + color: var(--text-2); |
| 3930 | - overflow-wrap: anywhere; | 3987 | + text-decoration: none; |
| 3931 | 3988 | ||
| 3932 | - .ci-state { | 3989 | + &:hover { |
| 3933 | - font-size: 0.8rem; | 3990 | + background: var(--surface-2); |
| 3991 | + color: var(--text); | ||
| 3934 | } | 3992 | } |
| 3935 | } | 3993 | } |
| 3936 | 3994 | ||
| 3937 | -.ci-run-meta { | 3995 | +.ci-job-main { |
| 3938 | - margin: 0; | 3996 | + display: block; |
| 3939 | - overflow-wrap: anywhere; | 3997 | + min-width: 0; |
| 3998 | + overflow: hidden; | ||
| 3999 | + white-space: nowrap; | ||
| 4000 | + text-overflow: ellipsis; | ||
| 3940 | } | 4001 | } |
| 3941 | 4002 | ||
| 3942 | -.ci-graph { | 4003 | +.ci-job-name { |
| 3943 | - max-width: 100%; | 4004 | + font-weight: 500; |
| 3944 | - overflow-x: auto; | 4005 | + color: var(--text); |
| 3945 | - border: 1px solid var(--border); | ||
| 3946 | - border-radius: 8px; | ||
| 3947 | - background: var(--bg); | ||
| 3948 | - | ||
| 3949 | - &:focus-visible { | ||
| 3950 | - outline: 2px solid var(--focus); | ||
| 3951 | - outline-offset: 2px; | ||
| 3952 | - } | ||
| 3953 | } | 4006 | } |
| 3954 | 4007 | ||
| 3955 | -.ci-graph-canvas { | 4008 | +.ci-job-runner { |
| 3956 | - position: relative; | 4009 | + font-size: 0.8125rem; |
| 3957 | - display: flex; | 4010 | + color: var(--muted); |
| 3958 | - gap: 48px; | 4011 | + white-space: nowrap; |
| 3959 | - width: max-content; | ||
| 3960 | - padding: 16px; | ||
| 3961 | } | 4012 | } |
| 3962 | 4013 | ||
| 3963 | -.ci-graph-col { | 4014 | +.ci-job-dur { |
| 3964 | - display: flex; | 4015 | + font-family: var(--mono); |
| 3965 | - flex-direction: column; | 4016 | + font-size: 0.8125rem; |
| 3966 | - flex-shrink: 0; | 4017 | + white-space: nowrap; |
| 3967 | - gap: 16px; | ||
| 3968 | - width: 200px; | ||
| 3969 | } | 4018 | } |
| 3970 | 4019 | ||
| 3971 | -// Connectors sit under the cards: the SVG comes first and the cards are positioned. | 4020 | +.ci-chev { |
| 3972 | -.ci-graph-lines { | 4021 | + justify-self: end; |
| 3973 | - position: absolute; | 4022 | + width: 6px; |
| 3974 | - top: 0; | 4023 | + height: 6px; |
| 3975 | - left: 0; | 4024 | + margin-right: 4px; |
| 3976 | - overflow: visible; | 4025 | + border-right: 1.5px solid var(--muted); |
| 3977 | - pointer-events: none; | 4026 | + border-bottom: 1.5px solid var(--muted); |
| 3978 | - | 4027 | + transform: rotate(-45deg); |
| 3979 | - path { | ||
| 3980 | - fill: none; | ||
| 3981 | - stroke: var(--border-strong); | ||
| 3982 | - stroke-width: 2; | ||
| 3983 | - } | ||
| 3984 | } | 4028 | } |
| 3985 | 4029 | ||
| 3986 | -.ci-graph-card { | 4030 | +.ci-dot { |
| 3987 | - --ci-icon: var(--muted); | 4031 | + display: inline-block; |
| 3988 | - | 4032 | + flex: none; |
| 3989 | - position: relative; | 4033 | + width: 8px; |
| 3990 | - display: flex; | 4034 | + height: 8px; |
| 3991 | - flex-direction: column; | 4035 | + border-radius: 50%; |
| 3992 | - justify-content: center; | 4036 | + background: currentColor; |
| 3993 | - flex-shrink: 0; | 4037 | + color: var(--muted); |
| 3994 | - gap: 2px; | ||
| 3995 | - box-sizing: border-box; | ||
| 3996 | - width: 200px; | ||
| 3997 | - height: 56px; | ||
| 3998 | - padding: 6px 12px; | ||
| 3999 | - border: 1px solid var(--border); | ||
| 4000 | - border-radius: 8px; | ||
| 4001 | - background: var(--surface); | ||
| 4002 | - color: var(--text); | ||
| 4003 | - text-decoration: none; | ||
| 4004 | 4038 | ||
| 4005 | - &:hover { | 4039 | + &.ci-success { |
| 4006 | - border-color: var(--border-strong); | 4040 | + color: var(--ok); |
| 4007 | - background: var(--surface-2); | ||
| 4008 | } | 4041 | } |
| 4009 | 4042 | ||
| 4010 | - &:focus-visible { | 4043 | + &.ci-failure, |
| 4011 | - outline: 2px solid var(--focus); | 4044 | + &.ci-error { |
| 4012 | - outline-offset: 2px; | 4045 | + color: var(--bad); |
| 4013 | } | 4046 | } |
| 4014 | 4047 | ||
| 4015 | - &.ci-success { | 4048 | + &.ci-running { |
| 4016 | - --ci-icon: var(--public-text); | 4049 | + color: var(--warn); |
| 4017 | } | 4050 | } |
| 4051 | +} | ||
| 4018 | 4052 | ||
| 4019 | - &.ci-queued, | 4053 | +// The run's header: its number, its title, its state and meta line. |
| 4020 | - &.ci-running, | 4054 | +.ci-main-head { |
| 4021 | - &.ci-blocked, | 4055 | + display: flex; |
| 4022 | - &.ci-waiting_approval { | 4056 | + flex-wrap: wrap; |
| 4023 | - --ci-icon: var(--warning); | 4057 | + align-items: center; |
| 4024 | - } | 4058 | + justify-content: space-between; |
| 4059 | + gap: 8px 12px; | ||
| 4060 | + margin-bottom: 8px; | ||
| 4061 | +} | ||
| 4025 | 4062 | ||
| 4026 | - &.ci-failure, | 4063 | +.ci-eyebrow { |
| 4027 | - &.ci-error { | 4064 | + margin: 0; |
| 4028 | - --ci-icon: var(--danger); | 4065 | + font-size: 0.75rem; |
| 4029 | - } | 4066 | + font-weight: 600; |
| 4067 | + letter-spacing: 0.06em; | ||
| 4068 | + text-transform: uppercase; | ||
| 4069 | + color: var(--muted); | ||
| 4030 | } | 4070 | } |
| 4031 | 4071 | ||
| 4032 | -.ci-graph-name { | 4072 | +.ci-run-title { |
| 4033 | - overflow: hidden; | 4073 | + margin: 0 0 8px; |
| 4034 | - font-size: 0.9375rem; | 4074 | + font-size: 1.25rem; |
| 4035 | font-weight: 600; | 4075 | font-weight: 600; |
| 4036 | - line-height: 1.5; | 4076 | + letter-spacing: -0.01em; |
| 4037 | - text-overflow: ellipsis; | 4077 | + overflow-wrap: anywhere; |
| 4038 | - white-space: nowrap; | ||
| 4039 | } | 4078 | } |
| 4040 | 4079 | ||
| 4041 | -.ci-graph-meta { | 4080 | +.ci-run-top { |
| 4042 | display: flex; | 4081 | display: flex; |
| 4082 | + flex-wrap: wrap; | ||
| 4043 | align-items: center; | 4083 | align-items: center; |
| 4044 | - gap: 6px; | 4084 | + gap: 8px 12px; |
| 4045 | - overflow: hidden; | 4085 | + margin: 0 0 16px; |
| 4086 | + font-size: 0.8125rem; | ||
| 4046 | color: var(--muted); | 4087 | color: var(--muted); |
| 4047 | - font-size: 0.75rem; | ||
| 4048 | - line-height: 1.4; | ||
| 4049 | - white-space: nowrap; | ||
| 4050 | } | 4088 | } |
| 4051 | 4089 | ||
| 4052 | -.ci-graph-icon { | 4090 | +.ci-cap { |
| 4053 | - flex-shrink: 0; | 4091 | + margin: 14px 0 0; |
| 4054 | - width: 8px; | 4092 | + font-size: 0.8125rem; |
| 4055 | - height: 8px; | 4093 | + color: var(--muted); |
| 4056 | - border-radius: 50%; | ||
| 4057 | - background: var(--ci-icon); | ||
| 4058 | } | 4094 | } |
| 4059 | 4095 | ||
| 4060 | -// CI run page: job rows link through the whole row (no JS). The name link stretches over its row | 4096 | +.ci-logpre { |
| 4061 | -// and the other controls in the row sit above it. | 4097 | + max-width: 100%; |
| 4062 | -.ci-jobs tbody tr { | 4098 | + margin: 8px 0 0; |
| 4063 | - position: relative; | 4099 | + padding: 10px 12px; |
| 4064 | - cursor: pointer; | 4100 | + font-family: var(--mono); |
| 4065 | - | 4101 | + font-size: 0.78rem; |
| 4066 | - &:hover { | 4102 | + line-height: 1.6; |
| 4067 | - background: var(--surface-2); | 4103 | + white-space: pre; |
| 4068 | - } | 4104 | + overflow-x: auto; |
| 4105 | + color: var(--text-2); | ||
| 4106 | + background: var(--code-bg); | ||
| 4107 | + border-radius: 8px; | ||
| 4069 | } | 4108 | } |
| 4070 | 4109 | ||
| 4071 | -.ci-jobs .ci-job-link::after { | 4110 | +// Phone width: the list stacks over the run. The timeline keeps its own scroll box. |
| 4072 | - content: ""; | 4111 | +@media (max-width: 760px) { |
| 4073 | - position: absolute; | 4112 | + .ci-split { |
| 4074 | - inset: 0; | 4113 | + grid-template-columns: minmax(0, 1fr); |
| 4114 | + } | ||
| 4075 | } | 4115 | } |
| 4076 | 4116 | ||
| 4077 | -.ci-jobs tbody a:not(.ci-job-link), | 4117 | +@media (prefers-reduced-motion: reduce) { |
| 4078 | -.ci-jobs tbody button, | 4118 | + .ci-gedge { |
| 4079 | -.ci-jobs tbody input, | 4119 | + animation: none; |
| 4080 | -.ci-jobs tbody select, | 4120 | + } |
| 4081 | -.ci-jobs tbody textarea { | ||
| 4082 | - position: relative; | ||
| 4083 | - z-index: 1; | ||
| 4084 | } | 4121 | } |
| 4085 | 4122 | ||
| 4086 | /* Theme and language preferences (T1). The palettes live at the top of this file: the dark | 4123 | /* Theme and language preferences (T1). The palettes live at the top of this file: the dark |
| @@ -4850,3 +4887,261 @@ span.reaction { | |||
| 4850 | order: -1; | 4887 | order: -1; |
| 4851 | } | 4888 | } |
| 4852 | } | 4889 | } |
| 4890 | + | ||
| 4891 | +// --------------------------------------------------------------------------- | ||
| 4892 | +// Settings: account security (/settings/security). One card of rows (icon, title, one-line | ||
| 4893 | +// status, action). An action opens in place as a <details> panel under its row. The danger | ||
| 4894 | +// zone is its own card with a red border. | ||
| 4895 | +// --------------------------------------------------------------------------- | ||
| 4896 | + | ||
| 4897 | +.security-card { | ||
| 4898 | + padding: 0; | ||
| 4899 | + overflow: hidden; | ||
| 4900 | + | ||
| 4901 | + > * + * { | ||
| 4902 | + border-top: 1px solid var(--border); | ||
| 4903 | + } | ||
| 4904 | +} | ||
| 4905 | + | ||
| 4906 | +.security-row { | ||
| 4907 | + position: relative; | ||
| 4908 | + display: flex; | ||
| 4909 | + flex-wrap: wrap; | ||
| 4910 | + align-items: center; | ||
| 4911 | + gap: 10px 16px; | ||
| 4912 | + padding: 16px 20px; | ||
| 4913 | + min-width: 0; | ||
| 4914 | + | ||
| 4915 | + // While an action is open its summary stays on this heading row, so keep the title clear of it. | ||
| 4916 | + &:has(> .security-action[open]) > .security-row-main { | ||
| 4917 | + padding-right: 150px; | ||
| 4918 | + } | ||
| 4919 | +} | ||
| 4920 | + | ||
| 4921 | +.security-block { | ||
| 4922 | + display: flex; | ||
| 4923 | + flex-direction: column; | ||
| 4924 | + min-width: 0; | ||
| 4925 | +} | ||
| 4926 | + | ||
| 4927 | +.security-icon { | ||
| 4928 | + flex: none; | ||
| 4929 | + width: 20px; | ||
| 4930 | + height: 20px; | ||
| 4931 | + fill: none; | ||
| 4932 | + stroke: var(--muted); | ||
| 4933 | + stroke-width: 1.8; | ||
| 4934 | + stroke-linecap: round; | ||
| 4935 | + stroke-linejoin: round; | ||
| 4936 | +} | ||
| 4937 | + | ||
| 4938 | +.security-row-main { | ||
| 4939 | + flex: 1 1 200px; | ||
| 4940 | + min-width: 0; | ||
| 4941 | + display: flex; | ||
| 4942 | + flex-direction: column; | ||
| 4943 | + gap: 2px; | ||
| 4944 | +} | ||
| 4945 | + | ||
| 4946 | +.security-row-title { | ||
| 4947 | + display: flex; | ||
| 4948 | + flex-wrap: wrap; | ||
| 4949 | + align-items: center; | ||
| 4950 | + gap: 8px; | ||
| 4951 | + margin: 0; | ||
| 4952 | + font-size: 0.9375rem; | ||
| 4953 | + font-weight: 600; | ||
| 4954 | + line-height: 1.4; | ||
| 4955 | + color: var(--text); | ||
| 4956 | + border: 0; | ||
| 4957 | + padding: 0; | ||
| 4958 | +} | ||
| 4959 | + | ||
| 4960 | +.security-row-status { | ||
| 4961 | + margin: 0; | ||
| 4962 | + font-size: 0.8125rem; | ||
| 4963 | + line-height: 1.45; | ||
| 4964 | + color: var(--muted); | ||
| 4965 | + overflow-wrap: anywhere; | ||
| 4966 | + | ||
| 4967 | + &.warn { | ||
| 4968 | + color: var(--warn); | ||
| 4969 | + font-weight: 600; | ||
| 4970 | + } | ||
| 4971 | +} | ||
| 4972 | + | ||
| 4973 | +.security-email { | ||
| 4974 | + color: var(--text-2); | ||
| 4975 | +} | ||
| 4976 | + | ||
| 4977 | +.security-pill { | ||
| 4978 | + display: inline-block; | ||
| 4979 | + padding: 0 8px; | ||
| 4980 | + border: 1px solid transparent; | ||
| 4981 | + border-radius: 999px; | ||
| 4982 | + font-size: 0.75rem; | ||
| 4983 | + font-weight: 600; | ||
| 4984 | + line-height: 1.6; | ||
| 4985 | + white-space: nowrap; | ||
| 4986 | + | ||
| 4987 | + &.on { | ||
| 4988 | + background: var(--add-bg); | ||
| 4989 | + color: var(--add-text); | ||
| 4990 | + } | ||
| 4991 | + | ||
| 4992 | + &.off { | ||
| 4993 | + background: var(--surface-2); | ||
| 4994 | + color: var(--muted); | ||
| 4995 | + border-color: var(--border); | ||
| 4996 | + } | ||
| 4997 | + | ||
| 4998 | + &.warn { | ||
| 4999 | + background: var(--surface-2); | ||
| 5000 | + color: var(--warn); | ||
| 5001 | + border-color: var(--warn); | ||
| 5002 | + } | ||
| 5003 | +} | ||
| 5004 | + | ||
| 5005 | +.security-inline-form { | ||
| 5006 | + margin: 0; | ||
| 5007 | +} | ||
| 5008 | + | ||
| 5009 | +.security-action { | ||
| 5010 | + margin-left: auto; | ||
| 5011 | + | ||
| 5012 | + > summary { | ||
| 5013 | + display: inline-block; | ||
| 5014 | + padding: 6px 12px; | ||
| 5015 | + border: 1px solid var(--border-strong); | ||
| 5016 | + border-radius: var(--radius); | ||
| 5017 | + background: var(--surface); | ||
| 5018 | + color: var(--text-2); | ||
| 5019 | + font-size: 0.875rem; | ||
| 5020 | + font-weight: 600; | ||
| 5021 | + cursor: pointer; | ||
| 5022 | + list-style: none; | ||
| 5023 | + white-space: nowrap; | ||
| 5024 | + | ||
| 5025 | + &::-webkit-details-marker { | ||
| 5026 | + display: none; | ||
| 5027 | + } | ||
| 5028 | + | ||
| 5029 | + &:hover { | ||
| 5030 | + background: var(--surface-2); | ||
| 5031 | + } | ||
| 5032 | + } | ||
| 5033 | + | ||
| 5034 | + &.danger > summary { | ||
| 5035 | + color: var(--danger); | ||
| 5036 | + border-color: var(--danger); | ||
| 5037 | + } | ||
| 5038 | + | ||
| 5039 | + // An open panel takes the whole row below the title. Its summary is lifted out of the flow | ||
| 5040 | + // and pinned to the right of the heading row (the row is the containing block), so the | ||
| 5041 | + // summary stays where it is when closed and only the panel moves below. | ||
| 5042 | + &[open] { | ||
| 5043 | + flex-basis: 100%; | ||
| 5044 | + margin-left: 0; | ||
| 5045 | + | ||
| 5046 | + > summary { | ||
| 5047 | + position: absolute; | ||
| 5048 | + top: 11px; | ||
| 5049 | + right: 20px; | ||
| 5050 | + } | ||
| 5051 | + | ||
| 5052 | + // Lines up with the title, past the row icon (20px) and its gap (16px). | ||
| 5053 | + > .security-panel { | ||
| 5054 | + width: auto; | ||
| 5055 | + margin-left: 36px; | ||
| 5056 | + } | ||
| 5057 | + } | ||
| 5058 | +} | ||
| 5059 | + | ||
| 5060 | +.security-panel { | ||
| 5061 | + display: flex; | ||
| 5062 | + flex-direction: column; | ||
| 5063 | + gap: 12px; | ||
| 5064 | + width: 100%; | ||
| 5065 | + max-width: 420px; | ||
| 5066 | + margin-top: 12px; | ||
| 5067 | + padding-top: 14px; | ||
| 5068 | + border-top: 1px solid var(--border); | ||
| 5069 | + min-width: 0; | ||
| 5070 | + | ||
| 5071 | + .alert { | ||
| 5072 | + margin: 0; | ||
| 5073 | + } | ||
| 5074 | + | ||
| 5075 | + small { | ||
| 5076 | + font-size: 0.8125rem; | ||
| 5077 | + } | ||
| 5078 | +} | ||
| 5079 | + | ||
| 5080 | +.security-devices { | ||
| 5081 | + display: flex; | ||
| 5082 | + flex-direction: column; | ||
| 5083 | + gap: 10px; | ||
| 5084 | + margin: 0; | ||
| 5085 | + padding: 0 20px 16px 56px; | ||
| 5086 | + list-style: none; | ||
| 5087 | + | ||
| 5088 | + > .security-device { | ||
| 5089 | + padding: 12px 14px; | ||
| 5090 | + border: 1px solid var(--border); | ||
| 5091 | + border-radius: var(--radius); | ||
| 5092 | + background: var(--surface-2); | ||
| 5093 | + } | ||
| 5094 | +} | ||
| 5095 | + | ||
| 5096 | +.security-setup { | ||
| 5097 | + max-width: none; | ||
| 5098 | + margin: 0; | ||
| 5099 | + padding: 4px 20px 18px 56px; | ||
| 5100 | + border-top: 0; | ||
| 5101 | +} | ||
| 5102 | + | ||
| 5103 | +.security-danger { | ||
| 5104 | + border-color: var(--bad); | ||
| 5105 | + | ||
| 5106 | + .security-danger-label { | ||
| 5107 | + margin: 0; | ||
| 5108 | + padding: 12px 20px 0; | ||
| 5109 | + font-size: 0.75rem; | ||
| 5110 | + font-weight: 700; | ||
| 5111 | + letter-spacing: 0.06em; | ||
| 5112 | + text-transform: uppercase; | ||
| 5113 | + color: var(--bad); | ||
| 5114 | + } | ||
| 5115 | + | ||
| 5116 | + .security-row-title { | ||
| 5117 | + color: var(--bad); | ||
| 5118 | + } | ||
| 5119 | + | ||
| 5120 | + .security-icon { | ||
| 5121 | + stroke: var(--bad); | ||
| 5122 | + } | ||
| 5123 | + | ||
| 5124 | + .security-repos { | ||
| 5125 | + flex-basis: 100%; | ||
| 5126 | + margin: 0; | ||
| 5127 | + padding-left: 56px; | ||
| 5128 | + } | ||
| 5129 | +} | ||
| 5130 | + | ||
| 5131 | +@media (max-width: 600px) { | ||
| 5132 | + .security-row { | ||
| 5133 | + padding: 14px 16px; | ||
| 5134 | + } | ||
| 5135 | + | ||
| 5136 | + .security-devices { | ||
| 5137 | + padding: 0 16px 14px 16px; | ||
| 5138 | + } | ||
| 5139 | + | ||
| 5140 | + .security-setup { | ||
| 5141 | + padding: 4px 16px 16px 16px; | ||
| 5142 | + } | ||
| 5143 | + | ||
| 5144 | + .security-danger .security-repos { | ||
| 5145 | + padding-left: 0; | ||
| 5146 | + } | ||
| 5147 | +} | ||