diff --git a/crates/izlek-core/src/store/mod.rs b/crates/izlek-core/src/store/mod.rs index 4145968..4eda171 100644 --- a/crates/izlek-core/src/store/mod.rs +++ b/crates/izlek-core/src/store/mod.rs @@ -442,6 +442,31 @@ pub enum FeedPage { After(FeedCursor), } +/// Which end of the activity feed reading order starts at. `Before` always +/// means further along in this order (an "Older" turn from `Newest`, a +/// "toward the end" turn from `Oldest`); `After` always means back toward +/// the start — the two feel symmetric to the reader regardless of which +/// direction is currently in play. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum Dir { + Newest, + Oldest, +} + +/// The activity tab's narrowing: every field is an AND'd equality (or a +/// half-open range for `day`), and an absent field matches everything. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ActivityFilter { + /// A user id, or the literal `"system"` for a row with no actor. + pub actor: Option, + /// An `ActivityKind::as_str()` value. + pub kind: Option, + pub task_key: Option, + /// Half-open `[start, end)` in UTC, already resolved from the admin's + /// timezone. + pub day: Option<(OffsetDateTime, OffsetDateTime)>, +} + /// A deletion that freed something, kept so a mail owed because of it can be /// rebuilt later. The task it names is gone by the time anyone reads this, so /// its key and title are copied rather than looked up. @@ -982,11 +1007,45 @@ pub trait Store: BoardReads + DetailReads + 'static { /// failed and may be tried again. async fn mail_queue(&self, limit: u32, page: FeedPage) -> Result>; + /// How many rows `mail_queue` draws from, unpaged — for the tab's + /// position note. + async fn count_mail_queue(&self) -> Result; + + /// How many queue rows sit strictly ahead of `cursor` in the queue's own + /// order (soonest first); `None` (the newest page) is `0`. + async fn count_mail_queue_preceding(&self, cursor: Option<&FeedCursor>) -> Result; + /// Every send, whatever its state, newest first. async fn recent_sends(&self, limit: u32) -> Result>; - /// The workspace's activity feed across every task, newest first. - async fn recent_activity(&self, limit: u32, page: FeedPage) -> Result>; + /// How many decisions there are in all, unpaged. + async fn count_mail_decisions(&self) -> Result; + + /// How many decision rows sit strictly ahead of `cursor` in the + /// decisions' own order (newest first); `None` is `0`. + async fn count_mail_decisions_preceding(&self, cursor: Option<&FeedCursor>) -> Result; + + /// The workspace's activity feed across every task, matching `filter`, + /// ordered per `dir`. + async fn recent_activity( + &self, + limit: u32, + page: FeedPage, + dir: Dir, + filter: &ActivityFilter, + ) -> Result>; + + /// How many activity rows match `filter`, unpaged. + async fn count_activity(&self, filter: &ActivityFilter) -> Result; + + /// How many rows matching `filter` sit strictly ahead of `cursor` in + /// `dir`'s reading order; `None` (the newest/oldest page) is `0`. + async fn count_activity_preceding( + &self, + filter: &ActivityFilter, + dir: Dir, + cursor: Option<&FeedCursor>, + ) -> Result; // -- who gets mailed --------------------------------------------------- diff --git a/crates/izlek-core/src/store/turso_store.rs b/crates/izlek-core/src/store/turso_store.rs index 2d7c777..f1ca0bd 100644 --- a/crates/izlek-core/src/store/turso_store.rs +++ b/crates/izlek-core/src/store/turso_store.rs @@ -10,15 +10,15 @@ use rand::Rng; use time::OffsetDateTime; use time::format_description::well_known::Rfc3339; use turso::transaction::TransactionBehavior; -use turso::{Builder, Connection, Row, params}; +use turso::{Builder, Connection, Row, Value, params}; use ulid::Ulid; use super::secret; use super::{ - ActivityEvent, ActivityLine, Attachment, Audience, CommentWritten, Deletion, Event, FeedPage, - Freeing, MailDecision, MailOutcome, MailRule, MailSend, NewAttachment, NewSender, NewTask, - NewUser, Recipient, Result, SendKind, SendState, SenderTest, Session, SigninLink, Store, - StoreError, TaskCreated, Trigger, User, Workspace, + ActivityEvent, ActivityFilter, ActivityLine, Attachment, Audience, CommentWritten, Deletion, + Dir, Event, FeedCursor, FeedPage, Freeing, MailDecision, MailOutcome, MailRule, MailSend, + NewAttachment, NewSender, NewTask, NewUser, Recipient, Result, SendKind, SendState, + SenderTest, Session, SigninLink, Store, StoreError, TaskCreated, Trigger, User, Workspace, }; use crate::Role; use crate::board::{BoardMeta, BoardReads, Column, Moved, Person, TaskRow, Transition}; @@ -530,6 +530,41 @@ fn count_of(row: &Row) -> Result { row.get::(0).map_err(backend).map(|n| n.max(0) as u64) } +/// The activity filter's AND clauses, as SQL text (leading `AND `, empty +/// when the filter matches everything) and the values it binds, in the order +/// the placeholders appear. +fn activity_filter_sql(filter: &ActivityFilter) -> Result<(String, Vec)> { + let mut clauses: Vec = Vec::new(); + let mut vals: Vec = Vec::new(); + match filter.actor.as_deref() { + Some("system") => clauses.push("a.actor_id IS NULL".to_string()), + Some(actor) => { + clauses.push("a.actor_id = ?".to_string()); + vals.push(actor.to_string().into()); + } + None => {} + } + if let Some(kind) = &filter.kind { + clauses.push("a.kind = ?".to_string()); + vals.push(kind.clone().into()); + } + if let Some(task_key) = &filter.task_key { + clauses.push("t.task_key = ?".to_string()); + vals.push(task_key.clone().into()); + } + if let Some((start, end)) = &filter.day { + clauses.push("(a.created_at >= ? AND a.created_at < ?)".to_string()); + vals.push(stamp(*start)?.into()); + vals.push(stamp(*end)?.into()); + } + let sql = if clauses.is_empty() { + String::new() + } else { + format!(" AND {}", clauses.join(" AND ")) + }; + Ok((sql, vals)) +} + fn workspace_from(row: &Row) -> Result { let types_json = text(row, 4)?; let allowed_file_types: Vec = if types_json.trim().is_empty() { @@ -2732,6 +2767,25 @@ impl Store for TursoStore { Ok(out) } + async fn count_mail_decisions(&self) -> Result { + let row = self + .one_row("SELECT COUNT(*) FROM mail_decision", ()) + .await?; + row.as_ref().map(count_of).unwrap_or(Ok(0)) + } + + async fn count_mail_decisions_preceding(&self, cursor: Option<&FeedCursor>) -> Result { + let Some(cursor) = cursor else { return Ok(0) }; + let row = self + .one_row( + "SELECT COUNT(*) FROM mail_decision \ + WHERE created_at > ?1 OR (created_at = ?1 AND id > ?2)", + params![stamp(cursor.at)?, cursor.id.clone()], + ) + .await?; + row.as_ref().map(count_of).unwrap_or(Ok(0)) + } + async fn mail_rule_last_decision(&self) -> Result> { let conn = self.conn.lock().await; let mut rows = conn @@ -2801,6 +2855,28 @@ impl Store for TursoStore { Ok(out) } + async fn count_mail_queue(&self) -> Result { + let row = self + .one_row( + "SELECT COUNT(*) FROM mail_send WHERE state IN ('pending', 'failed')", + (), + ) + .await?; + row.as_ref().map(count_of).unwrap_or(Ok(0)) + } + + async fn count_mail_queue_preceding(&self, cursor: Option<&FeedCursor>) -> Result { + let Some(cursor) = cursor else { return Ok(0) }; + let row = self + .one_row( + "SELECT COUNT(*) FROM mail_send WHERE state IN ('pending', 'failed') \ + AND (next_attempt_at < ?1 OR (next_attempt_at = ?1 AND id < ?2))", + params![stamp(cursor.at)?, cursor.id.clone()], + ) + .await?; + row.as_ref().map(count_of).unwrap_or(Ok(0)) + } + async fn recent_sends(&self, limit: u32) -> Result> { let conn = self.conn.lock().await; let sql = format!( @@ -2817,42 +2893,76 @@ impl Store for TursoStore { Ok(out) } - async fn recent_activity(&self, limit: u32, page: FeedPage) -> Result> { + async fn recent_activity( + &self, + limit: u32, + page: FeedPage, + dir: Dir, + filter: &ActivityFilter, + ) -> Result> { const SELECT: &str = "SELECT a.id, a.task_id, t.title, u.display_name, a.kind, a.detail, \ a.created_at FROM activity a \ LEFT JOIN task t ON t.id = a.task_id \ LEFT JOIN user u ON u.id = a.actor_id"; let conn = self.conn.lock().await; + let (filter_sql, filter_vals) = activity_filter_sql(filter)?; + // The base order is the feed's own reading direction; `After` scans + // the opposite way (back toward the start) and the caller reverses + // the page below to restore it. + let base = match dir { + Dir::Newest => "DESC", + Dir::Oldest => "ASC", + }; + let opp = match dir { + Dir::Newest => "ASC", + Dir::Oldest => "DESC", + }; let reverse = matches!(page, FeedPage::After(_)); - let mut rows = match &page { + let mut vals: Vec = Vec::new(); + let sql = match &page { FeedPage::Newest => { - let sql = format!("{SELECT} ORDER BY a.created_at DESC, a.id DESC LIMIT ?1"); - conn.query(&sql, params![i64::from(limit)]).await + vals.extend(filter_vals); + vals.push(i64::from(limit).into()); + format!("{SELECT} WHERE 1=1{filter_sql} ORDER BY a.created_at {base}, a.id {base} LIMIT ?") } FeedPage::Before(cursor) => { - let sql = format!( - "{SELECT} WHERE a.created_at < ?2 OR (a.created_at = ?2 AND a.id < ?3) \ - ORDER BY a.created_at DESC, a.id DESC LIMIT ?1" - ); - conn.query( - &sql, - params![i64::from(limit), stamp(cursor.at)?, cursor.id.clone()], + // Further along in `dir`'s reading order: older when + // Newest, newer when Oldest. + let cmp = match dir { + Dir::Newest => "<", + Dir::Oldest => ">", + }; + let at = stamp(cursor.at)?; + vals.push(at.clone().into()); + vals.push(at.into()); + vals.push(cursor.id.clone().into()); + vals.extend(filter_vals); + vals.push(i64::from(limit).into()); + format!( + "{SELECT} WHERE (a.created_at {cmp} ? OR (a.created_at = ? AND a.id {cmp} ?)){filter_sql} \ + ORDER BY a.created_at {base}, a.id {base} LIMIT ?" ) - .await } FeedPage::After(cursor) => { - let sql = format!( - "{SELECT} WHERE a.created_at > ?2 OR (a.created_at = ?2 AND a.id > ?3) \ - ORDER BY a.created_at ASC, a.id ASC LIMIT ?1" - ); - conn.query( - &sql, - params![i64::from(limit), stamp(cursor.at)?, cursor.id.clone()], + // Back toward the start: newer when Newest, older when + // Oldest — scanned in the opposite order, then reversed. + let cmp = match dir { + Dir::Newest => ">", + Dir::Oldest => "<", + }; + let at = stamp(cursor.at)?; + vals.push(at.clone().into()); + vals.push(at.into()); + vals.push(cursor.id.clone().into()); + vals.extend(filter_vals); + vals.push(i64::from(limit).into()); + format!( + "{SELECT} WHERE (a.created_at {cmp} ? OR (a.created_at = ? AND a.id {cmp} ?)){filter_sql} \ + ORDER BY a.created_at {opp}, a.id {opp} LIMIT ?" ) - .await } - } - .map_err(backend)?; + }; + let mut rows = conn.query(&sql, vals).await.map_err(backend)?; let mut out = Vec::new(); while let Some(row) = rows.next().await.map_err(backend)? { out.push(ActivityLine { @@ -2871,6 +2981,45 @@ impl Store for TursoStore { Ok(out) } + async fn count_activity(&self, filter: &ActivityFilter) -> Result { + let (filter_sql, filter_vals) = activity_filter_sql(filter)?; + let sql = format!( + "SELECT COUNT(*) FROM activity a \ + LEFT JOIN task t ON t.id = a.task_id \ + LEFT JOIN user u ON u.id = a.actor_id WHERE 1=1{filter_sql}" + ); + let row = self.one_row(&sql, filter_vals).await?; + row.as_ref().map(count_of).unwrap_or(Ok(0)) + } + + async fn count_activity_preceding( + &self, + filter: &ActivityFilter, + dir: Dir, + cursor: Option<&FeedCursor>, + ) -> Result { + let Some(cursor) = cursor else { return Ok(0) }; + let (filter_sql, filter_vals) = activity_filter_sql(filter)?; + // Preceding = already shown on an earlier page: back toward the + // start of `dir`'s reading order, the same side `FeedPage::After` + // reads from. + let cmp = match dir { + Dir::Newest => ">", + Dir::Oldest => "<", + }; + let at = stamp(cursor.at)?; + let mut vals: Vec = vec![at.clone().into(), at.into(), cursor.id.clone().into()]; + vals.extend(filter_vals); + let sql = format!( + "SELECT COUNT(*) FROM activity a \ + LEFT JOIN task t ON t.id = a.task_id \ + LEFT JOIN user u ON u.id = a.actor_id \ + WHERE (a.created_at {cmp} ? OR (a.created_at = ? AND a.id {cmp} ?)){filter_sql}" + ); + let row = self.one_row(&sql, vals).await?; + row.as_ref().map(count_of).unwrap_or(Ok(0)) + } + // -- who gets mailed --------------------------------------------------- async fn recipients_for_task(&self, task_id: &str) -> Result> { diff --git a/crates/izlek-core/tests/store.rs b/crates/izlek-core/tests/store.rs index cf6ce07..04627ff 100644 --- a/crates/izlek-core/tests/store.rs +++ b/crates/izlek-core/tests/store.rs @@ -2044,6 +2044,61 @@ async fn add_task( .id } +/// The counting fns agree with a full read, and a filtered keyset walk +/// covers exactly the filtered set — no row skipped or repeated. +#[tokio::test] +async fn count_and_filtered_keyset_walk_cover_exactly_the_filtered_set() { + use izlek_core::store::{ActivityFilter, Dir, FeedCursor, FeedPage}; + + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let other = member(store, &workspace, "sam@izlek.sh", "Sam").await; + let t0 = OffsetDateTime::now_utc(); + for i in 0..20 { + let actor = if i % 2 == 0 { &admin } else { &other }; + store + .record_event( + Some(actor), + &izlek_core::detail::ActivityKind::Other("row".to_string()), + &format!("row {i}"), + t0 + Duration::seconds(i), + ) + .await + .unwrap(); + } + + let filter = ActivityFilter { actor: Some(admin.clone()), ..Default::default() }; + let total = store.count_activity(&filter).await.unwrap(); + assert_eq!(total, 10); + + let mut walked = Vec::new(); + let mut page = FeedPage::Newest; + loop { + let rows = store + .recent_activity(3, page, Dir::Newest, &filter) + .await + .unwrap(); + if rows.is_empty() { + break; + } + let last = rows.last().unwrap(); + page = FeedPage::Before(FeedCursor { at: last.at, id: last.id.clone() }); + walked.extend(rows); + } + assert_eq!(walked.len(), 10); + assert!(walked.iter().all(|r| r.actor_name.as_deref() == Some("Ada"))); + + let preceding = store + .count_activity_preceding( + &filter, + Dir::Newest, + Some(&FeedCursor { at: walked[3].at, id: walked[3].id.clone() }), + ) + .await + .unwrap(); + assert_eq!(preceding, 3); +} + #[tokio::test] async fn a_claimed_workspace_starts_with_four_named_columns() { let (scratch, workspace, _admin) = workspace_with_admin().await; @@ -4732,7 +4787,7 @@ async fn the_activity_feed_is_the_whole_workspace_newest_first() { .await .unwrap(); - let feed = store.recent_activity(10, izlek_core::store::FeedPage::Newest).await.unwrap(); + let feed = store.recent_activity(10, izlek_core::store::FeedPage::Newest, izlek_core::store::Dir::Newest, &izlek_core::store::ActivityFilter::default()).await.unwrap(); // Two "created" lines came free with the two tasks; the two just recorded // sit newest first, ahead of both of those. assert_eq!(feed.len(), 4); @@ -4768,13 +4823,13 @@ async fn keyset_paging_covers_every_activity_row_once() { } let _ = workspace; - let whole = store.recent_activity(100, FeedPage::Newest).await.unwrap(); + let whole = store.recent_activity(100, FeedPage::Newest, izlek_core::store::Dir::Newest, &izlek_core::store::ActivityFilter::default()).await.unwrap(); assert_eq!(whole.len(), 23); let mut walked = Vec::new(); let mut page = FeedPage::Newest; loop { - let rows = store.recent_activity(7, page).await.unwrap(); + let rows = store.recent_activity(7, page, izlek_core::store::Dir::Newest, &izlek_core::store::ActivityFilter::default()).await.unwrap(); if rows.is_empty() { break; } @@ -4811,7 +4866,7 @@ async fn an_account_event_rides_the_feed_without_a_task() { .await .unwrap(); - let feed = store.recent_activity(10, izlek_core::store::FeedPage::Newest).await.unwrap(); + let feed = store.recent_activity(10, izlek_core::store::FeedPage::Newest, izlek_core::store::Dir::Newest, &izlek_core::store::ActivityFilter::default()).await.unwrap(); // The sign-in sits newest with no task on it; the task's own lines below // still name theirs. assert_eq!(feed[0].kind, ActivityKind::SignedIn); diff --git a/crates/izlek-web/src/detail.rs b/crates/izlek-web/src/detail.rs index 617ec6b..2eed4de 100644 --- a/crates/izlek-web/src/detail.rs +++ b/crates/izlek-web/src/detail.rs @@ -899,7 +899,7 @@ async fn deadline_control(
- (datepicker_grid(cx, "deadline", &input_value, lang).await?) + (datepicker_grid(cx, "deadline", &input_value, false, lang).await?)
@@ -916,10 +916,16 @@ async fn deadline_control( /// grid — the grid cells and month title are blank until `datepicker_script` /// fills them in on open (see that function's doc comment for why the fill /// happens in JS rather than here). -async fn datepicker_grid(cx: &Cx, name: &str, value: &str, lang: Lang) -> Result { +pub(crate) async fn datepicker_grid( + cx: &Cx, + name: &str, + value: &str, + autosubmit: bool, + lang: Lang, +) -> Result { view! { cx => - +
@@ -945,7 +951,7 @@ async fn datepicker_grid(cx: &Cx, name: &str, value: &str, lang: Lang) -> Result /// `Escape` closes the panel through the datepick resolver `board.rs`'s /// `card_menu_script` registers (priority 100 — see the table on /// `layout.rs`'s `escape_manager_script`). -async fn datepicker_script(cx: &Cx, lang: Lang) -> Result { +pub(crate) async fn datepicker_script(cx: &Cx, lang: Lang) -> Result { use crate::i18n::datepicker_js_literals; use topcoat::view::Unescaped; let (months, weekdays) = datepicker_js_literals(lang); @@ -986,6 +992,7 @@ async fn datepicker_script(cx: &Cx, lang: Lang) -> Result { if (label) {{ label.textContent = ymd ? (MONTHS[ymd.m - 1].slice(0, 3) + ' ' + pad(ymd.d)) : label.dataset.empty; }}\ var toggle = pop.querySelector('.edit-toggle');\ if (toggle) {{ toggle.checked = false; }}\ + if (input.hasAttribute('data-autosubmit') && input.form) {{ input.form.requestSubmit(); }}\ }}\ document.addEventListener('change', function(e) {{\ var toggle = e.target.closest('.datepick-pop > .edit-toggle');\ @@ -1653,7 +1660,7 @@ pub async fn new_task_modal(cx: &Cx, columns: &[(String, String)], lang: Lang) - (t(lang, Key::NoDeadline))
- (datepicker_grid(cx, "deadline", "", lang).await?) + (datepicker_grid(cx, "deadline", "", false, lang).await?)
diff --git a/crates/izlek-web/src/i18n.rs b/crates/izlek-web/src/i18n.rs index 00f49c9..a9c94e2 100644 --- a/crates/izlek-web/src/i18n.rs +++ b/crates/izlek-web/src/i18n.rs @@ -289,6 +289,11 @@ pub enum Key { MonthOctober, MonthNovember, MonthDecember, + All, + Task, + LogSystem, + Newest, + Oldest, } /// The lone templated phrase — a name in the middle reads worse as two @@ -816,6 +821,16 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (MonthNovember, Tr) => "Kasım", (MonthDecember, En) => "December", (MonthDecember, Tr) => "Aralık", + (All, En) => "All", + (All, Tr) => "Tümü", + (Task, En) => "Task", + (Task, Tr) => "Görev", + (LogSystem, En) => "System", + (LogSystem, Tr) => "Sistem", + (Newest, En) => "Newest", + (Newest, Tr) => "En yeni", + (Oldest, En) => "Oldest", + (Oldest, Tr) => "En eski", } } diff --git a/crates/izlek-web/src/logs.rs b/crates/izlek-web/src/logs.rs index 781718a..67df8ec 100644 --- a/crates/izlek-web/src/logs.rs +++ b/crates/izlek-web/src/logs.rs @@ -8,7 +8,7 @@ //! every request, so `snapshot` — the shared read — backs both the page and //! the JSON route `tests/http.rs` polls. -use izlek_core::store::{FeedCursor, FeedPage}; +use izlek_core::store::{ActivityFilter, Dir, FeedCursor, FeedPage}; use serde::{Deserialize, Serialize}; use time::OffsetDateTime; use time::format_description::well_known::Rfc3339; @@ -18,7 +18,7 @@ use topcoat::router::content::Json; use topcoat::router::{page, route}; use topcoat::view::view; -use crate::detail::Me; +use crate::detail::{Me, datepicker_grid}; use crate::i18n::{Key, Lang, t}; use crate::server::{Refusal, accounts, require_admin}; use crate::settings::{decode_q, encode_q}; @@ -84,6 +84,43 @@ struct LogsSnapshot { /// capped so the screen stays a read a person can finish. const LIMIT: u32 = 50; +/// Every `ActivityKind::as_str()` value but `Other` — the Type filter's +/// options. +const ACTIVITY_KINDS: &[&str] = &[ + "created", + "retitled", + "described", + "deadline_set", + "deadline_cleared", + "assigned", + "unassigned", + "linked", + "unlinked", + "moved", + "unblocked", + "deleted", + "commented", + "workspace_claimed", + "invited", + "link_resent", + "joined", + "signed_in", + "signed_out", + "sign_in_failed", + "password_changed", + "role_changed", + "profile_saved", + "sender_saved", + "limits_saved", + "test_mail_sent", + "rule_created", + "rule_edited", + "rule_toggled", + "rule_deleted", + "file_added", + "file_removed", +]; + /// The word the decisions panel prints for an outcome. Terse: the panel is /// read, not explained. fn outcome_word(outcome: izlek_core::store::MailOutcome, lang: Lang) -> &'static str { @@ -264,17 +301,29 @@ async fn decision_detail( } /// Query width and cursor for one section's list: the extra row beyond -/// `LIMIT` only signals that an older page exists — it is trimmed before -/// rendering. Only the section actually showing is paged; the rest always -/// read the newest `LIMIT`. -fn feed_window(active: Section, target: Section, page: &FeedPage) -> (u32, FeedPage) { +/// `limit` only signals that an older page exists — it is trimmed before +/// rendering. Only the section actually showing is paged, at its own +/// `limit`; the rest always read the newest `LIMIT`. +fn feed_window(active: Section, target: Section, page: &FeedPage, limit: u32) -> (u32, FeedPage) { if active == target { - (LIMIT + 1, page.clone()) + (limit + 1, page.clone()) } else { (LIMIT, FeedPage::Newest) } } +/// The active section's own page size: from `izlek_rows_
`, the +/// cookie the page's own fit script sets once it has measured the browser's +/// real viewport, clamped so a stale or tampered cookie can't ask for an +/// absurd window. `LIMIT` — the same default the unpaged JSON route reads — +/// when the cookie is absent or unparsable. +fn resolve_limit(cx: &Cx, section: Section) -> u32 { + crate::server::presented_cookie(cx, &format!("izlek_rows_{}", section_slug(section))) + .and_then(|raw| raw.parse::().ok()) + .map(|rows| rows.clamp(10, 200)) + .unwrap_or(LIMIT) +} + /// Where the reader can turn from the active section's current page: the /// query fragment (`before=…`/`after=…`, already encoded) for each /// direction the rail may still show a link for. @@ -283,6 +332,9 @@ struct PageLinks { show_older: bool, newer_q: Option, older_q: Option, + /// (X, Y, N) for the active section's "X–Y / N" note: rendered rows are + /// X through Y of N matching rows. Absent when the list is empty. + position: Option<(u64, u64, u64)>, } fn cursor_q(param: &str, cursor: &FeedCursor) -> String { @@ -311,6 +363,57 @@ fn parse_page(query: &str) -> FeedPage { } } +/// `dir=oldest` reverses the activity tab; anything else, including +/// absence, reads newest first. +fn parse_dir(query: &str) -> Dir { + match query_value(query, "dir") { + Some("oldest") => Dir::Oldest, + _ => Dir::Newest, + } +} + +/// `on=YYYY-MM-DD`, resolved to a half-open UTC range in the admin's own +/// timezone. Unparsable or absent is no filter, never a 500. +fn parse_day(raw: &str, zone: time::UtcOffset) -> Option<(OffsetDateTime, OffsetDateTime)> { + use time::macros::format_description; + let day = time::Date::parse(raw, format_description!("[year]-[month]-[day]")).ok()?; + let start = day + .with_hms(0, 0, 0) + .ok()? + .assume_offset(zone) + .to_offset(time::UtcOffset::UTC); + Some((start, start + time::Duration::hours(24))) +} + +/// The activity tab's filter, straight off the query: an absent or empty +/// value narrows nothing. +fn parse_activity_filter(query: &str, zone: time::UtcOffset) -> ActivityFilter { + ActivityFilter { + actor: query_value(query, "actor").filter(|v| !v.is_empty()).map(str::to_string), + kind: query_value(query, "kind").filter(|v| !v.is_empty()).map(str::to_string), + task_key: query_value(query, "task") + .filter(|v| !v.is_empty()) + .map(|v| v.to_uppercase()), + day: query_value(query, "on").and_then(|raw| parse_day(raw, zone)), + } +} + +/// Every active activity-filter param, as a query fragment (leading `&`, +/// empty when nothing is set) — round-tripped onto cursor hrefs and the +/// filter form's own action so a page turn never drops a filter. +fn activity_query_suffix(query: &str) -> String { + let mut out = String::new(); + for key in ["actor", "kind", "task", "on", "dir"] { + if let Some(value) = query_value(query, key).filter(|v| !v.is_empty()) { + out.push('&'); + out.push_str(key); + out.push('='); + out.push_str(value); + } + } + out +} + /// The queue, the decisions, and the activity, admin only. Shared by the /// `/logs` page and the `/api/current_logs` route so both answer the same /// read the same way. `active`/`page` widen and cursor only the section @@ -320,6 +423,9 @@ async fn snapshot( cx: &Cx, active: Section, page: FeedPage, + dir: Dir, + filter: &ActivityFilter, + limit: u32, ) -> Result> { use izlek_core::store::SendState; @@ -339,15 +445,15 @@ async fn snapshot( let mut newer_cursor: Option = None; let mut older_cursor: Option = None; - let (queue_limit, queue_page) = feed_window(active, Section::Queue, &page); + let (queue_limit, queue_page) = feed_window(active, Section::Queue, &page, limit); let mut sends = store.mail_queue(queue_limit, queue_page).await?; if active == Section::Queue && matches!(page, FeedPage::After(_)) && sends.is_empty() { effective_page = FeedPage::Newest; - sends = store.mail_queue(LIMIT + 1, FeedPage::Newest).await?; + sends = store.mail_queue(limit + 1, FeedPage::Newest).await?; } - if active == Section::Queue && sends.len() as u32 > LIMIT { + if active == Section::Queue && sends.len() as u32 > limit { has_more = true; - sends.truncate(LIMIT as usize); + sends.truncate(limit as usize); } if active == Section::Queue { newer_cursor = sends @@ -357,6 +463,7 @@ async fn snapshot( .last() .and_then(|s| s.next_attempt_at.map(|at| FeedCursor { at, id: s.id.clone() })); } + let queue_shown = sends.len() as u64; let mut queue = Vec::with_capacity(sends.len()); for send in sends { let subject = match &send.subject { @@ -392,16 +499,16 @@ async fn snapshot( }); } - let (decisions_limit, decisions_page) = feed_window(active, Section::Decisions, &page); + let (decisions_limit, decisions_page) = feed_window(active, Section::Decisions, &page, limit); let mut raw_decisions = store.recent_mail_decisions(decisions_limit, decisions_page).await?; if active == Section::Decisions && matches!(page, FeedPage::After(_)) && raw_decisions.is_empty() { effective_page = FeedPage::Newest; - raw_decisions = store.recent_mail_decisions(LIMIT + 1, FeedPage::Newest).await?; + raw_decisions = store.recent_mail_decisions(limit + 1, FeedPage::Newest).await?; } - if active == Section::Decisions && raw_decisions.len() as u32 > LIMIT { + if active == Section::Decisions && raw_decisions.len() as u32 > limit { has_more = true; - raw_decisions.truncate(LIMIT as usize); + raw_decisions.truncate(limit as usize); } // Cursors come from the raw rows, before grouping by event — a group // split across a page boundary is accepted, unchanged from the offset @@ -414,6 +521,7 @@ async fn snapshot( .last() .map(|d| FeedCursor { at: d.at, id: d.id.clone() }); } + let decisions_shown = raw_decisions.len() as u64; let mut decisions: Vec = Vec::new(); let mut columns_cache: std::collections::HashMap> = std::collections::HashMap::new(); @@ -460,16 +568,23 @@ async fn snapshot( }); } - let (activity_limit, activity_page) = feed_window(active, Section::Activity, &page); - let mut raw_activity = store.recent_activity(activity_limit, activity_page).await?; + let (activity_limit, activity_page) = feed_window(active, Section::Activity, &page, limit); + let activity_filter = if active == Section::Activity { + filter.clone() + } else { + ActivityFilter::default() + }; + let mut raw_activity = + store.recent_activity(activity_limit, activity_page, dir, &activity_filter).await?; if active == Section::Activity && matches!(page, FeedPage::After(_)) && raw_activity.is_empty() { effective_page = FeedPage::Newest; - raw_activity = store.recent_activity(LIMIT + 1, FeedPage::Newest).await?; + raw_activity = + store.recent_activity(limit + 1, FeedPage::Newest, dir, &activity_filter).await?; } - if active == Section::Activity && raw_activity.len() as u32 > LIMIT { + if active == Section::Activity && raw_activity.len() as u32 > limit { has_more = true; - raw_activity.truncate(LIMIT as usize); + raw_activity.truncate(limit as usize); } if active == Section::Activity { newer_cursor = raw_activity @@ -479,6 +594,7 @@ async fn snapshot( .last() .map(|line| FeedCursor { at: line.at, id: line.id.clone() }); } + let activity_shown = raw_activity.len() as u64; let activity = raw_activity .into_iter() .map(|line| ActivityRow { @@ -494,11 +610,34 @@ async fn snapshot( let show_older = matches!(effective_page, FeedPage::After(_)) || has_more; let show_newer = matches!(effective_page, FeedPage::Before(_)) || (matches!(effective_page, FeedPage::After(_)) && has_more); + + let position = match active { + Section::Queue if queue_shown > 0 => { + let total = store.count_mail_queue().await?; + let preceding = store.count_mail_queue_preceding(newer_cursor.as_ref()).await?; + Some((preceding + 1, preceding + queue_shown, total)) + } + Section::Decisions if decisions_shown > 0 => { + let total = store.count_mail_decisions().await?; + let preceding = store.count_mail_decisions_preceding(newer_cursor.as_ref()).await?; + Some((preceding + 1, preceding + decisions_shown, total)) + } + Section::Activity if activity_shown > 0 => { + let total = store.count_activity(&activity_filter).await?; + let preceding = store + .count_activity_preceding(&activity_filter, dir, newer_cursor.as_ref()) + .await?; + Some((preceding + 1, preceding + activity_shown, total)) + } + _ => None, + }; + let links = PageLinks { show_newer, show_older, newer_q: newer_cursor.as_ref().map(|c| cursor_q("after", c)), older_q: older_cursor.as_ref().map(|c| cursor_q("before", c)), + position, }; Ok(Ok(( @@ -517,9 +656,16 @@ async fn snapshot( #[route(POST "/api/current_logs")] async fn current_logs(cx: &Cx) -> Result>> { Ok(Json( - snapshot(cx, Section::Activity, FeedPage::Newest) - .await? - .map(|(snapshot, _links)| snapshot), + snapshot( + cx, + Section::Activity, + FeedPage::Newest, + Dir::Newest, + &ActivityFilter::default(), + LIMIT, + ) + .await? + .map(|(snapshot, _links)| snapshot), )) } @@ -554,15 +700,25 @@ fn rail_class(current: Section, target: Section) -> &'static str { #[page("/logs")] async fn logs_page(cx: &Cx) -> Result { let lang = Lang::En; - let query = topcoat::router::request::uri(cx).query().unwrap_or(""); - let section = match query_value(query, "section") { + let query = topcoat::router::request::uri(cx).query().unwrap_or("").to_string(); + let section = match query_value(&query, "section") { Some("queue") => Section::Queue, Some("decisions") => Section::Decisions, _ => Section::Activity, }; - let page = parse_page(query); - match snapshot(cx, section, page).await { - Ok(Ok((snapshot, links))) => logs_screen(cx, snapshot, section, links).await, + let page = parse_page(&query); + let dir = parse_dir(&query); + // The admin's own timezone resolves `on=` before the session is known to + // `snapshot` itself, so a signed-out visitor still gets a clean refusal + // rather than a second, redundant lookup here. + let zone = match require_admin(cx).await { + Ok(user) => izlek_core::detail::parse_zone(&user.timezone), + Err(_) => time::UtcOffset::UTC, + }; + let filter = parse_activity_filter(&query, zone); + let limit = resolve_limit(cx, section); + match snapshot(cx, section, page, dir, &filter, limit).await { + Ok(Ok((snapshot, links))) => logs_screen(cx, snapshot, section, links, &query, limit).await, // No `Me` here to read a language off of when the refusal itself is // "no session" — English, same as the other admin pages' own gate. Ok(Err(refusal)) => view! { @@ -590,7 +746,14 @@ fn section_slug(section: Section) -> &'static str { } } -async fn logs_screen(cx: &Cx, snapshot: LogsSnapshot, section: Section, links: PageLinks) -> Result { +async fn logs_screen( + cx: &Cx, + snapshot: LogsSnapshot, + section: Section, + links: PageLinks, + query: &str, + limit: u32, +) -> Result { let lang = Lang::from_code(&snapshot.me.language); let me = snapshot.me; let queue = snapshot.queue; @@ -600,14 +763,38 @@ async fn logs_screen(cx: &Cx, snapshot: LogsSnapshot, section: Section, links: P let decisions_empty = decisions.is_empty(); let activity_empty = activity.is_empty(); let slug = section_slug(section); + let extra = if section == Section::Activity { activity_query_suffix(query) } else { String::new() }; let newer_href = links .newer_q .filter(|_| links.show_newer) - .map(|q| format!("/logs?section={slug}&{q}")); + .map(|q| format!("/logs?section={slug}&{q}{extra}")); let older_href = links .older_q .filter(|_| links.show_older) - .map(|q| format!("/logs?section={slug}&{q}")); + .map(|q| format!("/logs?section={slug}&{q}{extra}")); + let position_note = links.position.map(|(x, y, n)| format!("{x}\u{2013}{y} / {n}")); + + let (filter_actor, filter_kind, filter_task, filter_on, filter_dir) = ( + query_value(query, "actor").unwrap_or("").to_string(), + query_value(query, "kind").unwrap_or("").to_string(), + query_value(query, "task").unwrap_or("").to_string(), + query_value(query, "on").unwrap_or("").to_string(), + query_value(query, "dir").unwrap_or("").to_string(), + ); + let members: Vec<(String, String)> = if section == Section::Activity { + let store = accounts(cx).store().clone(); + match store.user(&me.id).await? { + Some(admin) => store + .users(&admin.workspace_id) + .await? + .into_iter() + .map(|u| (u.id, u.display_name)) + .collect(), + None => Vec::new(), + } + } else { + Vec::new() + }; view! { cx => @@ -639,7 +826,7 @@ async fn logs_screen(cx: &Cx, snapshot: LogsSnapshot, section: Section, links: P

(t(lang, Key::MailQueue))

-
+
for line in queue { let is_failed_or_held = line.state_kind == "failed" || line.state_kind == "held"; let state_note = if is_failed_or_held { @@ -664,9 +851,12 @@ async fn logs_screen(cx: &Cx, snapshot: LogsSnapshot, section: Section, links: P }
- if newer_href.is_some() || older_href.is_some() { + if !queue_empty {
+ if let Some(note) = position_note.clone() { + (note) + } if let Some(newer_href) = newer_href.clone() { (t(lang, Key::Newer)) } @@ -687,7 +877,7 @@ async fn logs_screen(cx: &Cx, snapshot: LogsSnapshot, section: Section, links: P

(t(lang, Key::MailDecisions))

-
+
for group in decisions { let header = match group.happened { Some(happened) => format!("{} · {}", group.task, happened), @@ -715,9 +905,12 @@ async fn logs_screen(cx: &Cx, snapshot: LogsSnapshot, section: Section, links: P }
- if newer_href.is_some() || older_href.is_some() { + if !decisions_empty {
+ if let Some(note) = position_note.clone() { + (note) + } if let Some(newer_href) = newer_href.clone() { (t(lang, Key::Newer)) } @@ -738,7 +931,37 @@ async fn logs_screen(cx: &Cx, snapshot: LogsSnapshot, section: Section, links: P

(t(lang, Key::Activity))

-
+ + + + + +
+ + +
+ (datepicker_grid(cx, "on", &filter_on, true, lang).await?) +
+
+ + +
for line in activity { let title = line.title;
@@ -755,9 +978,12 @@ async fn logs_screen(cx: &Cx, snapshot: LogsSnapshot, section: Section, links: P }
- if newer_href.is_some() || older_href.is_some() { + if !activity_empty {
+ if let Some(note) = position_note.clone() { + (note) + } if let Some(newer_href) = newer_href.clone() { (t(lang, Key::Newer)) } @@ -773,6 +999,39 @@ async fn logs_screen(cx: &Cx, snapshot: LogsSnapshot, section: Section, links: P }
+ (crate::dropdown::dropdown_script(cx).await?) (crate::layout::escape_script(cx).await?) + (crate::detail::datepicker_script(cx, lang).await?) + (log_fit_script(cx).await?) } } + +/// Fits the active tab's page size to the browser's own viewport: measured +/// once per load/swap against the first rendered row, never against a guess +/// at the row height. A fit that would change the page size reloads once +/// through a fresh `izlek_rows_
` cookie; the `sessionStorage` guard, +/// keyed to the exact fit computed, stops a borderline measurement from +/// reloading forever. A container too short to measure (no rows yet, or a +/// stage not yet laid out) is left alone rather than guessed at. +async fn log_fit_script(cx: &Cx) -> Result { + use topcoat::view::Unescaped; + let js = "(function() {\ + var list = document.querySelector('.rule-list[data-rows], .log-list[data-rows]');\ + if (!list) { return; }\ + var section = list.dataset.section;\ + var current = parseInt(list.dataset.rows, 10);\ + var row = list.firstElementChild;\ + if (!row || !row.offsetHeight) { return; }\ + var stage = list.closest('.settings-stage');\ + if (!stage) { return; }\ + var avail = stage.getBoundingClientRect().bottom - list.getBoundingClientRect().top - 44;\ + var fit = Math.max(10, Math.floor(avail / row.offsetHeight));\ + if (fit === current) { return; }\ + var guard = 'izlekLogFit:' + section + ':' + fit;\ + if (window.sessionStorage.getItem(guard)) { return; }\ + window.sessionStorage.setItem(guard, '1');\ + document.cookie = 'izlek_rows_' + section + '=' + fit + ';path=/';\ + location.replace(location.href);\ + })();"; + view! { cx => } +} diff --git a/crates/izlek-web/src/server.rs b/crates/izlek-web/src/server.rs index 0f0cd98..fd6c56e 100644 --- a/crates/izlek-web/src/server.rs +++ b/crates/izlek-web/src/server.rs @@ -174,6 +174,13 @@ pub fn presented_session(cx: &Cx) -> Option { .map(|c| c.value().to_string()) } +/// Any other cookie the request presented, by name — the client-set, +/// non-`HttpOnly` ones (e.g. `izlek_rows_
`) that JS reads and +/// writes on its own. +pub fn presented_cookie(cx: &Cx, name: &str) -> Option { + cookies(cx).get(name).map(|c| c.value().to_string()) +} + /// A stable-enough label for the client, for rate limiting. A proxy header is /// only trusted because Izlek is meant to sit behind one; the address bucket is /// the limit that actually protects the Argon2 work either way. diff --git a/crates/izlek-web/tests/http.rs b/crates/izlek-web/tests/http.rs index 3d90bea..26c3cc6 100644 --- a/crates/izlek-web/tests/http.rs +++ b/crates/izlek-web/tests/http.rs @@ -132,6 +132,19 @@ impl App { /// regardless — [`Router::handle`] never follows a redirect, so the answer /// is read straight off this response, same as `oneshot` did before. async fn post(&self, path: &str, cookie: Option<&str>, form: &[(&str, &str)]) -> Answer { + self.post_with_extra_cookie(path, cookie, form, None).await + } + + /// Like `post`, but with a second `Cookie` header of the caller's own + /// naming — for the `izlek_rows_
` page-size cookie, which lives + /// beside the session cookie rather than replacing it. + async fn post_with_extra_cookie( + &self, + path: &str, + cookie: Option<&str>, + form: &[(&str, &str)], + extra_cookie: Option<&str>, + ) -> Answer { let body = form .iter() .map(|(key, value)| format!("{}={}", encode(key), encode(value))) @@ -148,6 +161,9 @@ impl App { HeaderValue::from_str(&format!("{SESSION_COOKIE}={cookie}")).unwrap(), ); } + if let Some(extra) = extra_cookie { + request = request.header(header::COOKIE, HeaderValue::from_str(extra).unwrap()); + } let response = self .router .handle(request.body(Body::from(body)).unwrap()) @@ -251,16 +267,23 @@ impl App { self.get_with_range(path, cookie, None).await } + /// Like `get`, but with a second `Cookie` header of the caller's own + /// naming — for the `izlek_rows_
` page-size cookie, which + /// lives beside the session cookie rather than replacing it. + async fn get_with_extra_cookie(&self, path: &str, cookie: Option<&str>, extra: &str) -> Raw { + self.get_with(path, cookie, None, None, Some(extra)).await + } + /// Like `get`, but with a `Range` header, for exercising the /// `/files/{id}` partial-content path. async fn get_with_range(&self, path: &str, cookie: Option<&str>, range: Option<&str>) -> Raw { - self.get_with(path, cookie, range, None).await + self.get_with(path, cookie, range, None, None).await } /// Like `get`, but with `If-None-Match`, for the `/photo/{user_id}` /// revalidate path. async fn get_with_if_none_match(&self, path: &str, cookie: Option<&str>, etag: &str) -> Raw { - self.get_with(path, cookie, None, Some(etag)).await + self.get_with(path, cookie, None, Some(etag), None).await } async fn get_with( @@ -269,6 +292,7 @@ impl App { cookie: Option<&str>, range: Option<&str>, if_none_match: Option<&str>, + extra_cookie: Option<&str>, ) -> Raw { let mut request = Request::builder().method("GET").uri(path); if let Some(cookie) = cookie { @@ -277,6 +301,9 @@ impl App { HeaderValue::from_str(&format!("{SESSION_COOKIE}={cookie}")).unwrap(), ); } + if let Some(extra) = extra_cookie { + request = request.header(header::COOKIE, HeaderValue::from_str(extra).unwrap()); + } if let Some(range) = range { request = request.header(header::RANGE, range); } @@ -4705,6 +4732,271 @@ async fn the_logs_page_pages_past_the_truncation() { assert!(garbage_html.contains("row 59"), "{garbage_html}"); } +/// The activity filter row narrows the feed by actor, kind, task and day, +/// and the pager foot's position note counts against the filtered total — +/// not the whole feed. +#[tokio::test] +async fn the_activity_filter_narrows_and_the_position_note_counts_the_match() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + let admin_id = user_id(&app, "ada@izlek.sh").await; + let member = invited(&app, &admin_cookie, "deniz@izlek.sh", "Deniz", Role::Member).await; + let member_id = user_id(&app, "deniz@izlek.sh").await; + + let t0 = time::OffsetDateTime::now_utc(); + for i in 0..60 { + let actor = if i % 2 == 0 { Some(admin_id.as_str()) } else { Some(member_id.as_str()) }; + app.store + .record_event( + actor, + &izlek_core::detail::ActivityKind::Other("row".to_string()), + &format!("row {i}"), + t0 + time::Duration::seconds(i), + ) + .await + .unwrap(); + } + + let all = app.get("/logs?section=activity&kind=row", Some(&admin_cookie)).await; + let all_html = String::from_utf8_lossy(&all.bytes).into_owned(); + assert!(all_html.contains("1\u{2013}"), "{all_html}"); + assert!(all_html.contains("/ 60"), "{all_html}"); + + let by_actor = app + .get(&format!("/logs?section=activity&kind=row&actor={member_id}"), Some(&admin_cookie)) + .await; + let by_actor_html = String::from_utf8_lossy(&by_actor.bytes).into_owned(); + assert!(by_actor_html.contains("/ 30"), "{by_actor_html}"); + + let oldest = app.get("/logs?section=activity&kind=row&dir=oldest", Some(&admin_cookie)).await; + let oldest_html = String::from_utf8_lossy(&oldest.bytes).into_owned(); + assert!(oldest_html.contains("row 0<"), "{oldest_html}"); + + let garbage = app + .get("/logs?section=activity&actor=zz&kind=zz&on=zz", Some(&admin_cookie)) + .await; + assert_eq!(garbage.status, 200); + + let refused = app.get("/logs?section=activity&actor=x", Some(&member)).await; + let refused_html = String::from_utf8_lossy(&refused.bytes); + assert!(refused_html.contains("Not permitted."), "{refused_html}"); +} + +/// `kind=` alone narrows the feed to one activity kind, leaving the other +/// kind's rows out of the body entirely. +#[tokio::test] +async fn the_kind_filter_shows_only_that_kinds_rows() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + + let t0 = time::OffsetDateTime::now_utc(); + for i in 0..5 { + app.store + .record_event(None, &izlek_core::detail::ActivityKind::Created, "", t0 + time::Duration::seconds(i)) + .await + .unwrap(); + } + for i in 0..3 { + app.store + .record_event( + None, + &izlek_core::detail::ActivityKind::Commented, + "", + t0 + time::Duration::seconds(100 + i), + ) + .await + .unwrap(); + } + + let narrowed = app + .get("/logs?section=activity&kind=created", Some(&admin_cookie)) + .await; + let html = String::from_utf8_lossy(&narrowed.bytes).into_owned(); + assert!(html.contains("created this task"), "{html}"); + assert!(!html.contains("log-line\">commented<"), "{html}"); + assert!(html.contains("/ 5"), "{html}"); +} + +/// `task=` narrows the feed to one task's rows, by its key — not any other +/// task's, even one created in the same run. +#[tokio::test] +async fn the_task_filter_shows_only_that_tasks_rows() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + let column = first_column(&app).await; + let alpha = a_task(&app, &admin_cookie, &column, "Task Alpha").await; + let _beta = a_task(&app, &admin_cookie, &column, "Task Beta").await; + let alpha_key = app + .store + .task(&alpha) + .await + .unwrap() + .expect("alpha task gone") + .row + .task_key; + + let narrowed = app + .get(&format!("/logs?section=activity&task={alpha_key}"), Some(&admin_cookie)) + .await; + let html = String::from_utf8_lossy(&narrowed.bytes).into_owned(); + assert!(html.contains("Task Alpha"), "{html}"); + assert!(!html.contains("Task Beta"), "{html}"); +} + +/// `on=YYYY-MM-DD` keeps only the rows recorded that day, in the admin's own +/// timezone (UTC by default in this fixture). +#[tokio::test] +async fn the_day_filter_keeps_only_that_days_rows() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + + let today = time::OffsetDateTime::now_utc(); + let two_days_ago = today - time::Duration::days(2); + for i in 0..5 { + app.store + .record_event( + None, + &izlek_core::detail::ActivityKind::Other("row".to_string()), + &format!("today-row {i}"), + today + time::Duration::seconds(i), + ) + .await + .unwrap(); + } + for i in 0..5 { + app.store + .record_event( + None, + &izlek_core::detail::ActivityKind::Other("row".to_string()), + &format!("old-row {i}"), + two_days_ago + time::Duration::seconds(i), + ) + .await + .unwrap(); + } + let on = format!("{:04}-{:02}-{:02}", today.year(), today.month() as u8, today.day()); + + let narrowed = app + .get(&format!("/logs?section=activity&on={on}"), Some(&admin_cookie)) + .await; + let html = String::from_utf8_lossy(&narrowed.bytes).into_owned(); + assert!(html.contains("today-row"), "{html}"); + assert!(!html.contains("old-row"), "{html}"); +} + +/// The `izlek_rows_activity` cookie the page's own fit script sets caps the +/// page at that many rows, no more. +#[tokio::test] +async fn the_rows_cookie_caps_the_page_size() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + + let t0 = time::OffsetDateTime::now_utc(); + for i in 0..60 { + app.store + .record_event( + None, + &izlek_core::detail::ActivityKind::Other("row".to_string()), + &format!("row {i}"), + t0 + time::Duration::seconds(i), + ) + .await + .unwrap(); + } + + let capped = app + .get_with_extra_cookie( + "/logs?section=activity", + Some(&admin_cookie), + "izlek_rows_activity=15", + ) + .await; + let html = String::from_utf8_lossy(&capped.bytes).into_owned(); + assert_eq!(html.matches("class=\"log-row\"").count(), 15, "{html}"); + assert!(html.contains("\">Older"), "{html}"); +} + +/// The Older href carries an active `kind=`/`dir=oldest` filter along with +/// its own cursor, and following it never turns up the other kind's rows. +#[tokio::test] +async fn the_older_href_round_trips_the_active_filter() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + + let t0 = time::OffsetDateTime::now_utc(); + for i in 0..60 { + app.store + .record_event( + None, + &izlek_core::detail::ActivityKind::Other("target".to_string()), + &format!("target {i}"), + t0 + time::Duration::seconds(i), + ) + .await + .unwrap(); + } + for i in 0..5 { + app.store + .record_event( + None, + &izlek_core::detail::ActivityKind::Other("foreign".to_string()), + &format!("foreign {i}"), + t0 + time::Duration::seconds(1000 + i), + ) + .await + .unwrap(); + } + + let first = app + .get("/logs?section=activity&kind=target&dir=oldest", Some(&admin_cookie)) + .await; + let first_html = String::from_utf8_lossy(&first.bytes).into_owned(); + assert!(!first_html.contains("foreign"), "{first_html}"); + let older_href = extract_href(&first_html, "/logs?section=activity&before=").replace("&", "&"); + assert!(older_href.contains("kind=target"), "{older_href}"); + assert!(older_href.contains("dir=oldest"), "{older_href}"); + + let second = app.get(&older_href, Some(&admin_cookie)).await; + let second_html = String::from_utf8_lossy(&second.bytes).into_owned(); + assert!(!second_html.contains("foreign"), "{second_html}"); +} + +/// `/api/current_logs` keeps reading the unpaged newest page regardless of a +/// small `izlek_rows_activity` cookie — the JSON route never widened by the +/// page's own fit cookie. +#[tokio::test] +async fn current_logs_json_ignores_the_rows_cookie() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + + let t0 = time::OffsetDateTime::now_utc(); + for i in 0..60 { + app.store + .record_event( + None, + &izlek_core::detail::ActivityKind::Other("row".to_string()), + &format!("row {i}"), + t0 + time::Duration::seconds(i), + ) + .await + .unwrap(); + } + + let answer = app + .post_with_extra_cookie( + "/api/current_logs", + Some(&admin_cookie), + &[], + Some("izlek_rows_activity=5"), + ) + .await; + assert!(answer.body.contains("\"queue\""), "{}", answer.body); + assert!(answer.body.contains("\"decisions\""), "{}", answer.body); + assert!(answer.body.contains("\"activity\""), "{}", answer.body); + let activity_rows = answer.body.matches("\"sentence\":").count(); + assert!(activity_rows <= 50, "{} rows: {}", activity_rows, answer.body); +} + /// A photo needs a session: signed out gets the same 404 an unknown id /// gets, and a second workspace's admin cannot see across the fence. #[tokio::test] diff --git a/style/main.scss b/style/main.scss index 4d9b01c..39e9056 100644 --- a/style/main.scss +++ b/style/main.scss @@ -2893,6 +2893,25 @@ input[type="radio"] { min-width: 0; font-size: 13px; color: var(--ink-soft); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +// The filter row above `.log-list`: house field boxes, wrapping rather than +// squeezing when the rail narrows the stage. +.log-filterbar { + height: auto; + flex-wrap: wrap; + gap: 10px; + padding: 14px 18px; +} + +// The pager foot's read of where the rendered rows sit in the whole feed. +.log-count { + font-family: var(--font-mono); + font-size: 10px; + color: var(--muted); } .log-title {