diff --git a/Cargo.lock b/Cargo.lock index d230fcc..e6d54cc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1817,6 +1817,7 @@ dependencies = [ "hex", "http", "iz-core", + "jiff", "jsonwebtoken", "rand 0.10.3", "reqwest", diff --git a/crates/iz-core/src/store/migrate.rs b/crates/iz-core/src/store/migrate.rs index 45f74be..6490cfe 100644 --- a/crates/iz-core/src/store/migrate.rs +++ b/crates/iz-core/src/store/migrate.rs @@ -10,7 +10,10 @@ use crate::time::now_stamp; /// `(version, sql)` in ascending order. pub const MIGRATIONS: &[(u32, &str)] = &[ (1, include_str!("../../migrations/0001_init.sql")), - (2, include_str!("../../migrations/0002_session_id_token.sql")), + ( + 2, + include_str!("../../migrations/0002_session_id_token.sql"), + ), ]; fn migration_err(e: turso::Error) -> Error { diff --git a/crates/iz-core/src/store/tasks.rs b/crates/iz-core/src/store/tasks.rs index ba049d9..318a598 100644 --- a/crates/iz-core/src/store/tasks.rs +++ b/crates/iz-core/src/store/tasks.rs @@ -376,6 +376,29 @@ async fn next_position(conn: &Connection, column_id: &str) -> Result { Ok(position_between(last, None)) } +/// Position for a task placed at `index` among the top-level cards of a column, between its neighbours +/// there. The moving task itself is left out, so a card never sits between itself and a neighbour. An +/// index past the end places the task last. +async fn position_at( + conn: &Connection, + column_id: &str, + moving_id: &str, + index: usize, +) -> Result { + let positions = fetch_all( + conn, + "SELECT position FROM tasks WHERE column_id = ?1 AND id <> ?2 AND parent_id IS NULL \ + AND deleted_at IS NULL ORDER BY position, id", + (column_id.to_owned(), moving_id.to_owned()), + |row| col_real(row, 0), + ) + .await?; + let index = index.min(positions.len()); + let before = index.checked_sub(1).map(|i| positions[i]); + let after = positions.get(index).copied(); + Ok(position_between(before, after)) +} + /// Appends a row to the transitions table. `from` is `None` for the first placement. async fn record_transition( tx: &Transaction<'_>, @@ -679,12 +702,16 @@ impl Store { /// Moves a task to `to_column` if it is still in `expected_from`. Entering the done column stamps /// `done_at` and is refused while subtasks are open; leaving it clears `done_at`. Each real move writes /// one transition and one `task_moved` activity row. + /// + /// `index` is the place among the column's top-level cards (0 is the top); `None` appends. A move + /// inside the same column is `Unchanged`: reordering within a column is not a move. pub async fn move_task( &self, board_id: &str, task_id: &str, expected_from: &str, to_column: &str, + index: Option, actor: &str, ) -> Result { let conn = self.inner.conn.lock().await; @@ -714,7 +741,10 @@ impl Store { return Ok(MoveOutcome::SubtasksOpen); } } - let position = next_position(&tx, &target.id).await?; + let position = match index { + Some(index) => position_at(&tx, &target.id, task_id, index).await?, + None => next_position(&tx, &target.id).await?, + }; let now = now_stamp(); let done_at = target.is_done.then(|| now.clone()); tx.execute( @@ -1079,6 +1109,40 @@ impl Store { finish(tx, outcome).await } + /// A cheap summary of everything the board page shows: counts and the newest change of the board's + /// tasks, assignments, links, comments, columns and projects. The live stream sends `changed` only + /// when this text changes, so it must change whenever any of those rows does. + pub async fn board_fingerprint(&self, board_id: &str) -> Result { + let conn = self.read_conn().await; + let row = fetch_opt( + &conn, + "SELECT \ + (SELECT COUNT(*) FROM tasks WHERE board_id = ?1), \ + (SELECT COALESCE(MAX(updated_at), '') FROM tasks WHERE board_id = ?1), \ + (SELECT COUNT(*) FROM task_assignees a JOIN tasks t ON t.id = a.task_id WHERE t.board_id = ?1), \ + (SELECT COUNT(*) FROM dependencies d JOIN tasks t ON t.id = d.blocked_id \ + WHERE t.board_id = ?1 AND d.cleared_at IS NULL), \ + (SELECT COUNT(*) FROM comments c JOIN tasks t ON t.id = c.task_id WHERE t.board_id = ?1), \ + (SELECT COUNT(*) FROM columns WHERE board_id = ?1), \ + (SELECT COUNT(*) FROM tags WHERE board_id = ?1)", + (board_id.to_owned(),), + |row| { + Ok(format!( + "{}|{}|{}|{}|{}|{}|{}", + col_int(row, 0)?, + col_text(row, 1)?, + col_int(row, 2)?, + col_int(row, 3)?, + col_int(row, 4)?, + col_int(row, 5)?, + col_int(row, 6)?, + )) + }, + ) + .await?; + Ok(row.unwrap_or_default()) + } + /// The board for one viewer: live columns with their top-level cards, after the filter and sort. /// Overdue uses `viewer_zone` for day-only deadlines. Blocked means not done with an uncleared blocker /// that is itself not done and not deleted. The search folds Turkish i (see `board::fold_for_search`). @@ -1448,17 +1512,17 @@ mod tests { .await .unwrap(); let outcome = store - .move_task(&board, &parent.id, &backlog, &done.id, "ada") + .move_task(&board, &parent.id, &backlog, &done.id, None, "ada") .await .unwrap(); assert_eq!(outcome, MoveOutcome::SubtasksOpen); // Finishing the subtask first lets the parent through. store - .move_task(&board, &child.id, &backlog, &done.id, "ada") + .move_task(&board, &child.id, &backlog, &done.id, None, "ada") .await .unwrap(); let outcome = store - .move_task(&board, &parent.id, &backlog, &done.id, "ada") + .move_task(&board, &parent.id, &backlog, &done.id, None, "ada") .await .unwrap(); assert_eq!(outcome, MoveOutcome::Moved); @@ -1478,16 +1542,16 @@ mod tests { .unwrap(); // Someone else already moved it, so the client's view of "from" is out of date. store - .move_task(&board, &task.id, &backlog, &progress, "bo") + .move_task(&board, &task.id, &backlog, &progress, None, "bo") .await .unwrap(); let stale = store - .move_task(&board, &task.id, &backlog, &columns[2].id, "ada") + .move_task(&board, &task.id, &backlog, &columns[2].id, None, "ada") .await .unwrap(); assert_eq!(stale, MoveOutcome::Stale); let same = store - .move_task(&board, &task.id, &progress, &progress, "ada") + .move_task(&board, &task.id, &progress, &progress, None, "ada") .await .unwrap(); assert_eq!(same, MoveOutcome::Unchanged); diff --git a/crates/iz-web/Cargo.toml b/crates/iz-web/Cargo.toml index 54bef2d..02619ec 100644 --- a/crates/iz-web/Cargo.toml +++ b/crates/iz-web/Cargo.toml @@ -16,6 +16,7 @@ futures-util.workspace = true hex.workspace = true http.workspace = true iz-core.workspace = true +jiff.workspace = true jsonwebtoken.workspace = true rand.workspace = true reqwest.workspace = true diff --git a/crates/iz-web/assets/board.js b/crates/iz-web/assets/board.js new file mode 100644 index 0000000..9c4675d --- /dev/null +++ b/crates/iz-web/assets/board.js @@ -0,0 +1,175 @@ +/* + * board.js: drag and drop of cards on the board page. It is progressive enhancement. Without it every + * card still has a "move to" form that works as a plain POST, so nothing here is needed for a move. + * + * What it does, for a member (the page has data-board-write on its section): + * - A card is dragged into another column. The card moves in the page as the pointer moves, so the + * place it would land in is visible. Dropping it sends one POST to /tasks/{id}/move with the + * column the page last showed (`from`), the target column (`to`) and the place (`position`), and + * asks for JSON. The server's answer decides: {ok: true} keeps the card where it was dropped; + * anything else puts it back and shows a toast with the server's translated message. + * - A drag that ends outside any column puts the card back where it was. + * + * What it never does: decide anything about the move itself. The server checks the column, the + * subtasks, the role and the token; this script only shows the result. Dropping onto the card's own + * column is nothing to send, so it puts the card back. + * + * The CSRF token comes from data-csrf on the section, which the server renders for this session. The + * file is one IIFE with no globals, and it is loaded with `defer`. + */ +(function () { + "use strict"; + + const board = document.querySelector("[data-board-write]"); + if (!board || !window.fetch || !window.URLSearchParams) { + return; + } + + /** How long a toast stays on the page, in milliseconds. */ + const TOAST_MS = 5000; + + /** The session's CSRF token, rendered by the server into the board section. */ + const csrf = board.dataset.csrf || ""; + + /** The text shown when the request never got an answer. Rendered in the page's language. */ + const failedText = board.dataset.msgFailed || "The card could not be moved. Try again."; + + /** The card being dragged, its place before the drag, and the column it started in. */ + let dragged = null; + let origin = null; + + /** The column the page showed the card in: the one the server is told about. */ + function columnOf(list) { + return list.dataset.columnId; + } + + /** Puts `card` back where `start` says it was before the drag. */ + function restore(card, start) { + if (start.next && start.next.parentNode === start.parent) { + start.parent.insertBefore(card, start.next); + } else { + start.parent.appendChild(card); + } + card.dataset.columnId = columnOf(start.parent); + } + + /** The card's index among the cards of its column, counting only cards (not other children). */ + function indexIn(list, card) { + return Array.from(list.children) + .filter((child) => child.classList.contains("card")) + .indexOf(card); + } + + /** Puts the card before the first other card whose middle is below the pointer. */ + function placeAt(list, card, clientY) { + const others = Array.from(list.children).filter( + (child) => child.classList.contains("card") && child !== card + ); + const before = others.find((other) => { + const rect = other.getBoundingClientRect(); + return clientY < rect.top + rect.height / 2; + }); + if (before) { + list.insertBefore(card, before); + } else { + list.appendChild(card); + } + } + + /** Shows a short message that goes away by itself. Created in the page, never from user input. */ + function toast(text) { + const el = document.createElement("div"); + el.className = "toast"; + el.setAttribute("role", "alert"); + el.textContent = text; + document.body.appendChild(el); + setTimeout(() => el.remove(), TOAST_MS); + } + + /** Sends the move and applies the answer. A card the server refused goes back to its place. */ + async function send(card, start, from, to, index) { + const id = card.dataset.taskId; + const body = new URLSearchParams({ csrf, from, to, position: String(index) }); + let answer = null; + let data = null; + try { + answer = await fetch(`/tasks/${encodeURIComponent(id)}/move`, { + method: "POST", + body, + headers: { Accept: "application/json" }, + credentials: "same-origin", + }); + data = await answer.json(); + } catch (error) { + data = null; + } + if (answer && answer.ok && data && data.ok) { + const input = card.querySelector('input[name="from"]'); + if (input) input.value = to; + return; + } + restore(card, start); + toast((data && data.message) || failedText); + } + + /** Records where a drag started, so a refused or cancelled drop can put the card back. */ + function onDragStart(event) { + const card = event.target.closest(".card[data-task-id]"); + if (!card) return; + dragged = card; + origin = { parent: card.parentNode, next: card.nextSibling }; + card.classList.add("is-dragging"); + event.dataTransfer.effectAllowed = "move"; + event.dataTransfer.setData("text/plain", card.dataset.taskId || ""); + } + + /** Moves the card in the page while the pointer is over another column. */ + function onDragOver(event) { + if (!dragged) return; + const list = event.currentTarget; + if (columnOf(list) === columnOf(origin.parent)) { + restore(dragged, origin); + return; + } + event.preventDefault(); + event.dataTransfer.dropEffect = "move"; + placeAt(list, dragged, event.clientY); + dragged.dataset.columnId = columnOf(list); + } + + /** A drop in another column sends the move. A drop in the same column changes nothing. */ + function onDrop(event) { + if (!dragged) return; + const list = event.currentTarget; + event.preventDefault(); + const card = dragged; + const start = origin; + const from = columnOf(start.parent); + const to = columnOf(list); + const index = indexIn(list, card); + dragged = null; + origin = null; + card.classList.remove("is-dragging"); + if (from === to) { + restore(card, start); + return; + } + send(card, start, from, to, index); + } + + /** A drag that ends without a drop (Escape, a drop outside) puts the card back. */ + function onDragEnd() { + if (!dragged) return; + restore(dragged, origin); + dragged.classList.remove("is-dragging"); + dragged = null; + origin = null; + } + + board.addEventListener("dragstart", onDragStart); + board.addEventListener("dragend", onDragEnd); + for (const list of board.querySelectorAll(".column-cards[data-column-id]")) { + list.addEventListener("dragover", onDragOver); + list.addEventListener("drop", onDrop); + } +})(); diff --git a/crates/iz-web/build.rs b/crates/iz-web/build.rs index 3066a19..213b1a2 100644 --- a/crates/iz-web/build.rs +++ b/crates/iz-web/build.rs @@ -1,6 +1,6 @@ //! Build script of the `iz` binary. It compiles `style/main.scss` into `OUT_DIR/main.css`, and it //! emits the build identity and the content hashes that the page links use as cache-busting -//! queries: `IZ_MAIN_CSS_V`, `IZ_NAV_JS_V`, `IZ_PAGES_JS_V` and `IZ_BUILD_SHA`. +//! queries: `IZ_MAIN_CSS_V`, `IZ_NAV_JS_V`, `IZ_PAGES_JS_V`, `IZ_BOARD_JS_V` and `IZ_BUILD_SHA`. //! //! It does not decide what is served: `src/assets.rs` embeds the files. It does not decide what a //! page links to either: `src/assets.rs` builds the `?v=` URLs from these values. It only compiles @@ -45,6 +45,7 @@ fn main() { for (var, file) in [ ("IZ_NAV_JS_V", "assets/nav.js"), ("IZ_PAGES_JS_V", "assets/pages.js"), + ("IZ_BOARD_JS_V", "assets/board.js"), ] { let bytes = fs::read(manifest.join(file)).unwrap_or_else(|e| panic!("reading {file}: {e}")); println!("cargo:rustc-env={var}={}", content_version(&bytes)); diff --git a/crates/iz-web/src/assets.rs b/crates/iz-web/src/assets.rs index b66e5ef..d3010cd 100644 --- a/crates/iz-web/src/assets.rs +++ b/crates/iz-web/src/assets.rs @@ -18,9 +18,13 @@ pub const NAV_JS_HREF: &str = concat!("/assets/nav.js?v=", env!("IZ_NAV_JS_V")); /// Link to the script of individual pages. pub const PAGES_JS_HREF: &str = concat!("/assets/pages.js?v=", env!("IZ_PAGES_JS_V")); +/// Link to the drag and drop script of the board page. Only that page links it. +pub const BOARD_JS_HREF: &str = concat!("/assets/board.js?v=", env!("IZ_BOARD_JS_V")); + const MAIN_CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/main.css")); const NAV_JS: &str = include_str!("../assets/nav.js"); const PAGES_JS: &str = include_str!("../assets/pages.js"); +const BOARD_JS: &str = include_str!("../assets/board.js"); const OFFLINE_HTML: &str = include_str!("../assets/offline.html"); const SW_JS: &str = include_str!("../assets/sw.js"); @@ -59,6 +63,12 @@ async fn pages_js() -> Result { Ok(asset("text/javascript; charset=utf-8", IMMUTABLE, PAGES_JS)) } +/// `GET /assets/board.js`. +#[route(GET "/assets/board.js")] +async fn board_js() -> Result { + Ok(asset("text/javascript; charset=utf-8", IMMUTABLE, BOARD_JS)) +} + /// `GET /assets/offline.html`. Also precached by the service worker. #[route(GET "/assets/offline.html")] async fn offline_html() -> Result { diff --git a/crates/iz-web/src/auth.rs b/crates/iz-web/src/auth.rs index a11a3e2..d35d580 100644 --- a/crates/iz-web/src/auth.rs +++ b/crates/iz-web/src/auth.rs @@ -36,15 +36,14 @@ const MAX_NEXT_LEN: usize = 2048; /// Longest user agent stored with a session, in bytes. Reason: the value is only shown to admins. const MAX_USER_AGENT_LEN: usize = 256; -/// The level a page or a write needs. Maps to one authorization action. +/// The level a page or a write needs. Maps to one authorization action. The administrator level is +/// added with the admin pages. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Need { /// Reading the board. Viewer, /// Creating and changing tasks, comments and files. Member, - /// Settings, roles, tags, columns and rules. - Admin, } /// A signed-in member and the session that carries them. @@ -123,14 +122,13 @@ pub async fn require_member(cx: &Cx) -> Result { } } -/// The signed-in member with the level `need`. A shortfall is `404` for admin pages, which must not -/// reveal that they exist, and `403` for a write that a viewer tried. +/// The signed-in member with the level `need`. A viewer who tries a write gets `403`; a member +/// with no access, or a disabled one, gets `404`, so the page does not reveal that it exists. pub async fn require_role(cx: &Cx, need: Need) -> Result { let me = require_member(cx).await?; let action = match need { Need::Viewer => Action::ReadBoard, Need::Member => Action::WriteTask, - Need::Admin => Action::Administer, }; match authorize(&me.actor(), &action) { Ok(()) => Ok(me), @@ -139,10 +137,11 @@ pub async fn require_role(cx: &Cx, need: Need) -> Result { } } -/// The signed-in member, after the CSRF check. A missing or wrong `csrf` is `403`, and the check runs -/// before any side effect of the handler. -pub async fn require_csrf(cx: &Cx, submitted: &str) -> Result { - let me = require_member(cx).await?; +/// The signed-in member with the level `need`, after the CSRF check. The level is checked first, so a +/// viewer gets `403` whatever token they send. A missing or wrong `csrf` is `403`. Both run before any +/// side effect of the handler. +pub async fn require_csrf(cx: &Cx, need: Need, submitted: &str) -> Result { + let me = require_role(cx, need).await?; if me.csrf_matches(submitted) { Ok(me) } else { @@ -219,6 +218,11 @@ pub fn user_agent(cx: &Cx) -> Option { .map(|value| value.chars().take(MAX_USER_AGENT_LEN).collect()) } +/// The raw query string of the request, without the `?`. `None` when the request has none. +pub fn uri_query(cx: &Cx) -> Option { + uri(cx).query().map(str::to_owned) +} + /// One query parameter of the request, decoded. `None` when it is absent. pub fn query_param(cx: &Cx, name: &str) -> Option { let mut url = Url::parse("http://iz.invalid/").ok()?; @@ -247,7 +251,7 @@ fn is_local_path(path: &str) -> bool { } /// Percent-encodes everything except unreserved characters and `/`, for a `next` value in a URL. -fn percent_encode(input: &str) -> String { +pub fn percent_encode(input: &str) -> String { let mut out = String::with_capacity(input.len()); for b in input.bytes() { match b { diff --git a/crates/iz-web/src/boot.rs b/crates/iz-web/src/boot.rs index 24b8c1b..6dc83db 100644 --- a/crates/iz-web/src/boot.rs +++ b/crates/iz-web/src/boot.rs @@ -27,6 +27,8 @@ use crate::state::AppState; /// Name of the instance key file inside the data directory. const KEY_FILE: &str = "iz.key"; +/// The prefix of task keys (`IZ-42`) until the setting that changes it exists. Two to six capitals. +const DEFAULT_KEY_PREFIX: &str = "IZ"; /// Runs the server until a stop signal arrives. Returns once every connection has finished. pub async fn serve(config_path: &Path) -> iz_core::Result<()> { @@ -79,6 +81,8 @@ async fn open_state(config: Config) -> iz_core::Result { } let key = secret::load_or_create_key(&data_dir.join(KEY_FILE))?; let store = Store::open(&config.database).await?; + // The one board of this installation, with its columns and default project, made on first boot. + store.ensure_board(DEFAULT_KEY_PREFIX).await?; let oidc = match &config.oidc { Some(oidc_config) => { let secret = oidc::read_client_secret(&oidc_config.client_secret_file)?; diff --git a/crates/iz-web/src/directory.rs b/crates/iz-web/src/directory.rs index 3fe107b..dd004aa 100644 --- a/crates/iz-web/src/directory.rs +++ b/crates/iz-web/src/directory.rs @@ -16,8 +16,8 @@ use std::time::Duration; use futures_util::StreamExt; use iz_core::authz::Role; -use iz_core::store::members::DirectoryMember; use iz_core::store::Store; +use iz_core::store::members::DirectoryMember; use serde_json::Value; use tokio::sync::watch; @@ -142,9 +142,13 @@ async fn mirror_once( async fn full_read(state: &AppState, oidc: &OidcClient) -> std::result::Result<(), MirrorError> { let token = oidc.service_token().await?; let url = format!("{}/api/v1/directory", oidc.issuer()); - let response = oidc.http().get(url).bearer_auth(token).send().await.map_err(|e| { - ImError::Unavailable(e.to_string()) - })?; + let response = oidc + .http() + .get(url) + .bearer_auth(token) + .send() + .await + .map_err(|e| ImError::Unavailable(e.to_string()))?; if !response.status().is_success() { return Err(ImError::BadResponse(format!( "the directory answered {}", @@ -170,7 +174,10 @@ async fn full_read(state: &AppState, oidc: &OidcClient) -> std::result::Result<( state.store.delete_sessions_by_sub(&local.sub).await?; } } - state.store.set_setting(CURSOR_SETTING, &roster.cursor).await?; + state + .store + .set_setting(CURSOR_SETTING, &roster.cursor) + .await?; Ok(()) } @@ -227,12 +234,17 @@ async fn stream( }; for event in parser.feed(&chunk).map_err(ImError::BadResponse)? { match event.name.as_str() { - "member" => match serde_json::from_str::(&event.data).ok().and_then(parse_member) { + "member" => match serde_json::from_str::(&event.data) + .ok() + .and_then(parse_member) + { Some(member) => { let default_role = default_role(&state.store).await?; apply(state, &member, default_role).await?; } - None => tracing::warn!("directory: skipping a member event that does not parse"), + None => { + tracing::warn!("directory: skipping a member event that does not parse") + } }, "deleted" => match serde_json::from_str::(&event.data) .ok() @@ -261,7 +273,11 @@ async fn apply( member: &DirectoryMember, default_role: Role, ) -> std::result::Result<(), MirrorError> { - match state.store.apply_directory_member(member, default_role).await { + match state + .store + .apply_directory_member(member, default_role) + .await + { Ok(stored) => { if stored.disabled { state.store.delete_sessions_by_sub(&stored.sub).await?; @@ -432,7 +448,14 @@ pub async fn fetch_photo(oidc: &OidcClient, sub: &str) -> ImResult &'static str { + match (key, lang) { + (K::BoardTitle, Lang::En) => "Board", + (K::BoardTitle, Lang::Tr) => "Pano", + (K::NewTask, Lang::En) => "New task", + (K::NewTask, Lang::Tr) => "Yeni görev", + (K::NewTaskHeading, Lang::En) => "New task", + (K::NewTaskHeading, Lang::Tr) => "Yeni görev", + (K::FieldTitle, Lang::En) => "Title", + (K::FieldTitle, Lang::Tr) => "Başlık", + (K::FieldColumn, Lang::En) => "Column", + (K::FieldColumn, Lang::Tr) => "Sütun", + (K::FieldProject, Lang::En) => "Project", + (K::FieldProject, Lang::Tr) => "Proje", + (K::FieldDescription, Lang::En) => "Description", + (K::FieldDescription, Lang::Tr) => "Açıklama", + (K::FieldDeadline, Lang::En) => "Deadline", + (K::FieldDeadline, Lang::Tr) => "Son tarih", + (K::DeadlineHint, Lang::En) => "A day, as YYYY-MM-DD", + (K::DeadlineHint, Lang::Tr) => "Bir gün, YYYY-AA-GG biçiminde", + (K::CreateTask, Lang::En) => "Create task", + (K::CreateTask, Lang::Tr) => "Görevi oluştur", + (K::Cancel, Lang::En) => "Cancel", + (K::Cancel, Lang::Tr) => "Vazgeç", + (K::FilterProject, Lang::En) => "Project", + (K::FilterProject, Lang::Tr) => "Proje", + (K::FilterAllProjects, Lang::En) => "All projects", + (K::FilterAllProjects, Lang::Tr) => "Tüm projeler", + (K::FilterAssignee, Lang::En) => "Assignee", + (K::FilterAssignee, Lang::Tr) => "Atanan", + (K::FilterAnyone, Lang::En) => "Anyone", + (K::FilterAnyone, Lang::Tr) => "Herkes", + (K::FilterNobody, Lang::En) => "Nobody", + (K::FilterNobody, Lang::Tr) => "Kimse", + (K::FilterSort, Lang::En) => "Sort", + (K::FilterSort, Lang::Tr) => "Sırala", + (K::SortDeadline, Lang::En) => "Deadline", + (K::SortDeadline, Lang::Tr) => "Son tarih", + (K::SortCreated, Lang::En) => "Newest first", + (K::SortCreated, Lang::Tr) => "En yeni", + (K::SortTitle, Lang::En) => "Title", + (K::SortTitle, Lang::Tr) => "Başlık", + (K::FilterSearch, Lang::En) => "Search", + (K::FilterSearch, Lang::Tr) => "Ara", + (K::SearchHint, Lang::En) => "Key or title", + (K::SearchHint, Lang::Tr) => "Anahtar veya başlık", + (K::Apply, Lang::En) => "Apply", + (K::Apply, Lang::Tr) => "Uygula", + (K::ClearFilters, Lang::En) => "Clear filters", + (K::ClearFilters, Lang::Tr) => "Filtreleri temizle", + (K::NoTasks, Lang::En) => "No tasks", + (K::NoTasks, Lang::Tr) => "Görev yok", + (K::NoMatches, Lang::En) => "No task matches the filters.", + (K::NoMatches, Lang::Tr) => "Filtrelere uyan görev yok.", + (K::Overdue, Lang::En) => "Overdue", + (K::Overdue, Lang::Tr) => "Gecikmiş", + (K::Blocked, Lang::En) => "Blocked", + (K::Blocked, Lang::Tr) => "Engelli", + (K::Due, Lang::En) => "Due", + (K::Due, Lang::Tr) => "Son", + (K::MoveTo, Lang::En) => "Move to", + (K::MoveTo, Lang::Tr) => "Taşı", + (K::Move, Lang::En) => "Move", + (K::Move, Lang::Tr) => "Taşı", + (K::Delete, Lang::En) => "Delete", + (K::Delete, Lang::Tr) => "Sil", + (K::ReadOnly, Lang::En) => "You can read the board. A member can change it.", + (K::ReadOnly, Lang::Tr) => "Panoyu görebilirsiniz. Değişiklikleri bir üye yapabilir.", + (K::DragHint, Lang::En) => "Drag a card to another column to move it.", + (K::DragHint, Lang::Tr) => "Bir kartı başka bir sütuna sürükleyerek taşıyın.", + (K::NoticeCreated, Lang::En) => "The task was created.", + (K::NoticeCreated, Lang::Tr) => "Görev oluşturuldu.", + (K::NoticeDeleted, Lang::En) => "The task was deleted.", + (K::NoticeDeleted, Lang::Tr) => "Görev silindi.", + (K::MovedAlready, Lang::En) => { + "Someone else moved this card. The board shows where it is now." + } + (K::MovedAlready, Lang::Tr) => { + "Bu kartı başka biri taşıdı. Pano kartın şu anki yerini gösteriyor." + } + (K::SubtasksOpen, Lang::En) => "Finish the open subtasks before moving this card to Done.", + (K::SubtasksOpen, Lang::Tr) => { + "Bu kartı Tamamlandı sütununa taşımadan önce açık alt görevleri bitirin." + } + (K::TitleInvalid, Lang::En) => "Enter a title of up to 200 characters.", + (K::TitleInvalid, Lang::Tr) => "En fazla 200 karakterlik bir başlık girin.", + (K::DescriptionTooLong, Lang::En) => "The description is longer than 20 000 characters.", + (K::DescriptionTooLong, Lang::Tr) => "Açıklama 20 000 karakterden uzun.", + (K::DeadlineInvalid, Lang::En) => "Use a deadline day such as 2026-10-28.", + (K::DeadlineInvalid, Lang::Tr) => "Son tarih için 2026-10-28 gibi bir gün yazın.", + (K::ColumnUnknown, Lang::En) => "That column does not exist on this board.", + (K::ColumnUnknown, Lang::Tr) => "Bu pano üzerinde böyle bir sütun yok.", + (K::ProjectUnknown, Lang::En) => "That project does not exist on this board.", + (K::ProjectUnknown, Lang::Tr) => "Bu pano üzerinde böyle bir proje yok.", + (K::TaskNotFound, Lang::En) => "That task does not exist any more.", + (K::TaskNotFound, Lang::Tr) => "Bu görev artık yok.", + (K::Forbidden, Lang::En) => "Your account cannot change the board.", + (K::Forbidden, Lang::Tr) => "Hesabınız panoda değişiklik yapamaz.", + (K::InvalidForm, Lang::En) => "Check the form and try again.", + (K::InvalidForm, Lang::Tr) => "Formu kontrol edip yeniden deneyin.", + (K::MoveFailed, Lang::En) => "The card could not be moved. Try again.", + (K::MoveFailed, Lang::Tr) => "Kart taşınamadı. Yeniden deneyin.", + (K::ColumnBacklog, Lang::En) => "Backlog", + (K::ColumnBacklog, Lang::Tr) => "Yapılacak", + (K::ColumnInProgress, Lang::En) => "In Progress", + (K::ColumnInProgress, Lang::Tr) => "Devam ediyor", + (K::ColumnReview, Lang::En) => "Review", + (K::ColumnReview, Lang::Tr) => "İnceleme", + (K::ColumnDone, Lang::En) => "Done", + (K::ColumnDone, Lang::Tr) => "Tamamlandı", + } +} + +/// The name of a column for display. The four seeded names are translated; any other name is shown as +/// the admin wrote it. +pub fn column_title(lang: Lang, name: &str) -> String { + let key = match name { + "Backlog" => K::ColumnBacklog, + "In Progress" => K::ColumnInProgress, + "Review" => K::ColumnReview, + "Done" => K::ColumnDone, + other => return other.to_owned(), + }; + t(lang, key).to_owned() +} + +/// The subtask count of a card, as `done/total` with the word for subtasks. +pub fn subtasks(lang: Lang, done: i64, total: i64) -> String { + match lang { + Lang::En => format!("{done}/{total} subtasks"), + Lang::Tr => format!("{done}/{total} alt görev"), + } +} + +/// The notice after a write, by the name the redirect carries. `None` for an unknown name. +pub fn notice(lang: Lang, name: &str) -> Option<&'static str> { + match name { + "created" => Some(t(lang, K::NoticeCreated)), + "deleted" => Some(t(lang, K::NoticeDeleted)), + _ => None, + } +} diff --git a/crates/iz-web/src/i18n/mod.rs b/crates/iz-web/src/i18n/mod.rs index 69524b5..29ae9f5 100644 --- a/crates/iz-web/src/i18n/mod.rs +++ b/crates/iz-web/src/i18n/mod.rs @@ -7,6 +7,7 @@ //! This module decides the language. It does not format sentences with values; those get small //! helper functions next to their keys. +pub mod board; pub mod shell; use topcoat::context::Cx; diff --git a/crates/iz-web/src/i18n/shell.rs b/crates/iz-web/src/i18n/shell.rs index c2525e2..4421b23 100644 --- a/crates/iz-web/src/i18n/shell.rs +++ b/crates/iz-web/src/i18n/shell.rs @@ -12,8 +12,6 @@ pub enum K { BackHome, /// The sentence under the 404 title. NotFoundBody, - /// The sentence on the start page for a signed-in member, before the board exists. - BoardComesNext, /// The title of the page that says a sign-in did not finish. SignInFailedTitle, /// The sentence under that title. @@ -50,8 +48,6 @@ pub fn t(lang: Lang, key: K) -> &'static str { (K::Admin, Lang::En) => "Admin", (K::Admin, Lang::Tr) => "Yönetici", (K::BackHome, Lang::En) => "Back to the start", - (K::BoardComesNext, Lang::En) => "The board comes next. There is nothing to show yet.", - (K::BoardComesNext, Lang::Tr) => "Pano sırada. Henüz gösterilecek bir şey yok.", (K::SignIn, Lang::En) => "Sign in", (K::SignIn, Lang::Tr) => "Oturum aç", (K::SignOut, Lang::En) => "Sign out", @@ -97,11 +93,3 @@ pub fn t(lang: Lang, key: K) -> &'static str { (K::SkipToContent, Lang::Tr) => "İçeriğe geç", } } - -/// The greeting of a signed-in member, with their name. -pub fn greeting(lang: Lang, name: &str) -> String { - match lang { - Lang::En => format!("Hello, {name}"), - Lang::Tr => format!("Merhaba, {name}"), - } -} diff --git a/crates/iz-web/src/main.rs b/crates/iz-web/src/main.rs index d2318f8..35a42ca 100644 --- a/crates/iz-web/src/main.rs +++ b/crates/iz-web/src/main.rs @@ -5,8 +5,6 @@ //! then `IZ_CONFIG`, then `config/iz.toml`. Exit status 0 is success, 1 a failure, 2 a usage error. mod assets; -// The board pages that come next call these helpers; until then they have no caller. -#[allow(dead_code)] mod auth; mod boot; mod directory; diff --git a/crates/iz-web/src/oidc.rs b/crates/iz-web/src/oidc.rs index 8941ec9..49b6698 100644 --- a/crates/iz-web/src/oidc.rs +++ b/crates/iz-web/src/oidc.rs @@ -225,7 +225,11 @@ struct KeyCache { impl OidcClient { /// Builds the client. `base_url` is the public origin of iz, from which the callback and the /// post-logout URIs are derived; `im` has these registered for the client. - pub fn new(config: &OidcConfig, base_url: &str, client_secret: String) -> iz_core::Result { + pub fn new( + config: &OidcConfig, + base_url: &str, + client_secret: String, + ) -> iz_core::Result { // Redirects are never followed: a token call that is redirected would send the client // secret to another host. let http = reqwest::Client::builder() @@ -343,9 +347,9 @@ impl OidcClient { Err(ImError::UnknownKey) => { let keys = self.key_set(true).await?; match check(&keys) { - Err(ImError::UnknownKey) => Err(ImError::Rejected( - "the signing key is not published".into(), - )), + Err(ImError::UnknownKey) => { + Err(ImError::Rejected("the signing key is not published".into())) + } other => other, } } @@ -354,7 +358,12 @@ impl OidcClient { } /// The authorization URL for a sign-in, with PKCE (S256) and the state and nonce of this flight. - pub async fn authorize_url(&self, state: &str, nonce: &str, challenge: &str) -> ImResult { + pub async fn authorize_url( + &self, + state: &str, + nonce: &str, + challenge: &str, + ) -> ImResult { let discovery = self.discovery().await?; let mut url = reqwest::Url::parse(&discovery.authorization_endpoint) .map_err(|e| ImError::BadResponse(format!("authorization endpoint: {e}")))?; @@ -372,7 +381,11 @@ impl OidcClient { /// The end-session URL of RP-initiated logout (contracts.md 2.5). `id_token_hint` is omitted when /// the session has no stored ID token. - pub async fn end_session_url(&self, id_token_hint: Option<&str>, state: &str) -> ImResult { + pub async fn end_session_url( + &self, + id_token_hint: Option<&str>, + state: &str, + ) -> ImResult { let discovery = self.discovery().await?; let endpoint = discovery .end_session_endpoint @@ -456,8 +469,10 @@ impl OidcClient { /// Verifies an ID token against the current keys, and the nonce of the flight. pub async fn verify_id_token(&self, token: &str, nonce: &str) -> ImResult { let now = unix_now(); - self.with_keys(|keys| verify_id_token(keys, &self.issuer, &self.client_id, token, nonce, now)) - .await + self.with_keys(|keys| { + verify_id_token(keys, &self.issuer, &self.client_id, token, nonce, now) + }) + .await } /// Verifies a back-channel logout token against the current keys. @@ -494,7 +509,9 @@ pub fn verify_id_token( let sent = str_claim(&claims, "nonce") .ok_or_else(|| ImError::Rejected("the nonce claim is missing".into()))?; if !constant_time_eq(sent.as_bytes(), nonce.as_bytes()) { - return Err(ImError::Rejected("the nonce does not match this sign-in".into())); + return Err(ImError::Rejected( + "the nonce does not match this sign-in".into(), + )); } let id: IdClaims = serde_json::from_value(Value::Object(claims)) .map_err(|e| ImError::Rejected(format!("the claims are malformed: {e}")))?; @@ -517,21 +534,27 @@ pub fn verify_logout_token( let claims = verify_signature(keys, issuer, client_id, token)?; check_iat(&claims, now)?; if claims.contains_key("nonce") { - return Err(ImError::Rejected("a logout token must not carry a nonce".into())); + return Err(ImError::Rejected( + "a logout token must not carry a nonce".into(), + )); } let events = claims .get("events") .and_then(Value::as_object) .ok_or_else(|| ImError::Rejected("the events claim is missing".into()))?; if !events.contains_key(BACKCHANNEL_EVENT) { - return Err(ImError::Rejected("the event is not back-channel logout".into())); + return Err(ImError::Rejected( + "the event is not back-channel logout".into(), + )); } let jti = str_claim(&claims, "jti") .ok_or_else(|| ImError::Rejected("the jti claim is missing".into()))?; let sid = str_claim(&claims, "sid"); let sub = str_claim(&claims, "sub"); if sid.is_none() && sub.is_none() { - return Err(ImError::Rejected("the token names neither sid nor sub".into())); + return Err(ImError::Rejected( + "the token names neither sid nor sub".into(), + )); } Ok(LogoutClaims { jti, sid, sub }) } diff --git a/crates/iz-web/src/pages/backchannel.rs b/crates/iz-web/src/pages/backchannel.rs index 9b4a7f7..d1c7a05 100644 --- a/crates/iz-web/src/pages/backchannel.rs +++ b/crates/iz-web/src/pages/backchannel.rs @@ -51,7 +51,10 @@ struct BackchannelForm { /// /// The id is recorded first and atomically (`seen_jti` inserts and reports a repeat), so two copies /// of one token cannot both succeed. -pub async fn end_sessions(store: &Store, claims: &LogoutClaims) -> std::result::Result { +pub async fn end_sessions( + store: &Store, + claims: &LogoutClaims, +) -> std::result::Result { if store.seen_jti(&claims.jti, JTI_LIFETIME).await? { return Err(BackchannelError::Replay); } @@ -183,7 +186,14 @@ mod tests { .await .expect("member"); store - .create_session(&member.sub, Some("sid-1"), None, Duration::from_secs(3600), None, None) + .create_session( + &member.sub, + Some("sid-1"), + None, + Duration::from_secs(3600), + None, + None, + ) .await .expect("session"); diff --git a/crates/iz-web/src/pages/board.rs b/crates/iz-web/src/pages/board.rs new file mode 100644 index 0000000..1295617 --- /dev/null +++ b/crates/iz-web/src/pages/board.rs @@ -0,0 +1,547 @@ +//! The board page (`GET /`) and its live stream (`GET /board/live`). +//! +//! The page is the board as one viewer sees it: the live columns in order, their cards with the chips +//! the store computed, the filter bar, and, for a member, the write controls. The filters and the sort +//! are applied by the store (`Store::board_view`), so the page and the search use one rule. A viewer +//! sees no write control. Writes (`pages/tasks.rs`) answer with this page again when they are refused. +//! +//! Anyone without access (no role, or disabled) gets the sign-in card, not a "forbidden" page: the +//! page does not say that the board exists. + +use iz_core::authz::{Action, Role, authorize}; +use iz_core::store::Store; +use iz_core::store::board::{Board, Tag}; +use iz_core::store::members::Member; +use iz_core::store::tasks::{AssigneeFilter, BoardFilter, BoardView, SortBy}; +use iz_core::zones::parse_zone; +use jiff::tz::TimeZone; +use reqwest::Url; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::error::not_found; +use topcoat::router::response::Response; +use topcoat::router::route; +use topcoat::view::view; + +use crate::assets::BOARD_JS_HREF; +use crate::auth::{ + CurrentMember, Need, current_member, percent_encode, query_param, require_role, uri_query, +}; +use crate::i18n::board::K; +use crate::i18n::{Lang, lang}; +use crate::live::{Topic, stream_changes}; +use crate::state::AppState; +use crate::views::board::{board_content, signed_out_card}; +use crate::views::{ViewerInfo, respond, shell}; + +/// Longest search text kept, in characters. Reason: a search is a few words; longer text only costs time. +pub const SEARCH_MAX: usize = 200; + +/// The new-task form as it is shown: the typed values, the choices, and the refusal to show above it. +#[derive(Debug, Clone, Default)] +pub struct NewForm { + /// The title as typed. + pub title: String, + /// The description as typed. + pub description: String, + /// The deadline as typed, `YYYY-MM-DD` or empty. + pub deadline: String, + /// The column id chosen. + pub column: String, + /// The project id chosen. + pub tag: String, + /// The refusal to show above the form, when the last try was refused. + pub error: Option, +} + +/// The filters of the page, as the store reads them and as the form shows them. +#[derive(Debug, Clone, Default)] +pub struct Filters { + /// What the store filters and sorts by. + pub filter: BoardFilter, + /// The project id selected, or empty for all projects. + pub tag: String, + /// `none` for nobody, a member id, or empty for anyone. + pub assignee: String, + /// `deadline` (the default), `created` or `title`. + pub sort: &'static str, + /// The search text, trimmed and at most [`SEARCH_MAX`] characters. + pub query: String, +} + +impl Filters { + /// Whether any filter narrows the board or changes its order. + pub fn active(&self) -> bool { + !self.tag.is_empty() + || !self.assignee.is_empty() + || self.sort != "deadline" + || !self.query.is_empty() + } +} + +/// Everything the board page shows for one request. +pub struct BoardPage { + /// The language of the page. + pub lang: Lang, + /// The signed-in person, for the topbar. + pub viewer: ViewerInfo, + /// Whether the viewer may change the board (a member or an admin). + pub can_write: bool, + /// The viewer's zone, for deadlines and meeting times. + pub zone: TimeZone, + /// The live columns with their cards, after the filters. + pub view: BoardView, + /// The projects of the board, in order. + pub tags: Vec, + /// The members who may be assigned, for the assignee filter. + pub members: Vec, + /// The filters in effect. + pub filters: Filters, + /// This page's URL with its filters, so a form can return here. + pub next: String, + /// The new-task form, when `?new=1` asked for it. + pub new_form: Option, + /// The refusal of the last write, shown above the board. + pub alert: Option, + /// The notice of the last write, shown above the board. + pub notice: Option<&'static str>, +} + +/// The board of this installation. The board is created at boot, so its absence is a missing page. +pub async fn the_board(store: &Store) -> Result { + match store.board().await? { + Some(board) => Ok(board), + None => Err(not_found().into()), + } +} + +/// The query pairs of a query string, decoded. Empty for an empty string. +pub fn pairs(query: &str) -> Vec<(String, String)> { + let Ok(mut url) = Url::parse("http://iz.invalid/") else { + return Vec::new(); + }; + url.set_query(Some(query)); + url.query_pairs() + .map(|(key, value)| (key.into_owned(), value.into_owned())) + .collect() +} + +/// The query part of a path such as `/?tag=x`, without the `?`. `None` when there is none. +pub fn query_of(path: &str) -> Option<&str> { + path.split_once('?').map(|(_, query)| query) +} + +/// Reads the filters from a query string. A bogus project or member id is dropped, as the page would +/// otherwise show an empty board for a filter the viewer cannot see. An unknown sort falls back to the +/// deadline order. +pub fn parse_filters(query: Option<&str>, tags: &[Tag], members: &[Member]) -> Filters { + let pairs = pairs(query.unwrap_or("")); + let get = |name: &str| { + pairs + .iter() + .find(|(key, _)| key == name) + .map(|(_, value)| value.trim().to_owned()) + .unwrap_or_default() + }; + let tag = get("tag"); + let tag = if tags.iter().any(|t| t.id == tag) { + tag + } else { + String::new() + }; + let assignee_raw = get("assignee"); + let assignee = if assignee_raw == "none" { + "none".to_owned() + } else if members.iter().any(|m| m.sub == assignee_raw) { + assignee_raw + } else { + String::new() + }; + let (sort, sort_by) = match get("sort").as_str() { + "created" => ("created", SortBy::Created), + "title" => ("title", SortBy::Title), + _ => ("deadline", SortBy::Deadline), + }; + let query: String = get("q").chars().take(SEARCH_MAX).collect(); + let filter = BoardFilter { + tag_id: (!tag.is_empty()).then(|| tag.clone()), + assignee: match assignee.as_str() { + "" => None, + "none" => Some(AssigneeFilter::Nobody), + sub => Some(AssigneeFilter::Member(sub.to_owned())), + }, + query: (!query.is_empty()).then(|| query.clone()), + sort: sort_by, + }; + Filters { + filter, + tag, + assignee, + sort, + query, + } +} + +/// The URL of the board with these filters, plus `extra` pairs. `/` when nothing is set. +pub fn board_url(filters: &Filters, extra: &[(&str, &str)]) -> String { + let mut parts: Vec = Vec::new(); + if !filters.tag.is_empty() { + parts.push(format!("tag={}", percent_encode(&filters.tag))); + } + if !filters.assignee.is_empty() { + parts.push(format!("assignee={}", percent_encode(&filters.assignee))); + } + if filters.sort != "deadline" { + parts.push(format!("sort={}", filters.sort)); + } + if !filters.query.is_empty() { + parts.push(format!("q={}", percent_encode(&filters.query))); + } + for (key, value) in extra { + parts.push(format!("{key}={}", percent_encode(value))); + } + if parts.is_empty() { + "/".to_owned() + } else { + format!("/?{}", parts.join("&")) + } +} + +/// Whether a member may be assigned: enabled, and an admin or a member (not a viewer or no-access). +fn assignable(member: &Member) -> bool { + !member.disabled && matches!(member.role, Role::Admin | Role::Member) +} + +/// Loads the board for `me` with the filters of `query`. The caller sets the form, alert and notice. +pub async fn load( + store: &Store, + me: &CurrentMember, + lang: Lang, + query: Option<&str>, +) -> Result { + let board = the_board(store).await?; + let zone = parse_zone(&me.member.zoneinfo).unwrap_or(TimeZone::UTC); + let tags = store.tags(&board.id).await?; + let members: Vec = store + .list_members() + .await? + .into_iter() + .filter(assignable) + .collect(); + let filters = parse_filters(query, &tags, &members); + let view = store.board_view(&board.id, &filters.filter, &zone).await?; + let can_write = authorize(&me.actor(), &Action::WriteTask).is_ok(); + let viewer = ViewerInfo { + name: me.member.name.clone(), + is_admin: me.member.im_admin || me.member.role == Role::Admin, + csrf: me.session.csrf_token.clone(), + }; + Ok(BoardPage { + lang, + viewer, + can_write, + zone, + view, + tags, + members, + next: board_url(&filters, &[]), + filters, + new_form: None, + alert: None, + notice: None, + }) +} + +/// Renders the page as a response. The page is one document; its own status (for a refused write) +/// is set by the caller through `status`. +pub async fn render( + cx: &Cx, + page: &BoardPage, + status: Option, +) -> Result { + let status = status.unwrap_or(topcoat::router::StatusCode::OK); + let document = view! { + cx => + (status) + shell(title: crate::i18n::board::t(page.lang, K::BoardTitle), lang: page.lang, + viewer: Some(&page.viewer), page_script: Some(BOARD_JS_HREF), + board_content(page: page) + ) + }; + respond(cx, document).await +} + +/// Renders the sign-in card for a visitor who is not signed in, or has no access to the board. +async fn signed_out(cx: &Cx, no_access: bool) -> Result { + let lang = lang(cx, None); + let document = view! { + cx => + shell(title: crate::i18n::shell::t(lang, crate::i18n::shell::K::SignedOutTitle), lang: lang, + viewer: None, page_script: None, + signed_out_card(lang: lang, no_access: no_access) + ) + }; + respond(cx, document).await +} + +/// `GET /`. Shows the board to a signed-in viewer; the sign-in card to anyone else. +#[route(GET "/")] +async fn board_page(cx: &Cx) -> Result { + let state = app_context::(cx); + let Some(me) = current_member(cx).await? else { + return signed_out(cx, false).await; + }; + if authorize(&me.actor(), &Action::ReadBoard).is_err() { + return signed_out(cx, true).await; + } + let lang = lang(cx, me.member.locale_override.as_deref()); + let query = uri_query(cx); + let mut page = load(&state.store, &me, lang, query.as_deref()).await?; + let new_wanted = query_param(cx, "new").is_some_and(|v| v == "1"); + if new_wanted && page.can_write { + page.new_form = Some(blank_form(&page)); + } + page.notice = + query_param(cx, "notice").and_then(|name| crate::i18n::board::notice(lang, &name)); + render(cx, &page, None).await +} + +/// The new-task form with the first column and the default project chosen. +pub fn blank_form(page: &BoardPage) -> NewForm { + let column = page + .view + .columns + .first() + .map(|c| c.column.id.clone()) + .unwrap_or_default(); + let tag = page + .tags + .iter() + .find(|t| t.is_default) + .or_else(|| page.tags.first()) + .map(|t| t.id.clone()) + .unwrap_or_default(); + NewForm { + column, + tag, + ..NewForm::default() + } +} + +/// `GET /board/live`. A `changed` event whenever the board's counts or newest change move on. The +/// browser then fetches the page again (`nav.js`). Anyone who may read the board may hold it. +#[route(GET "/board/live")] +async fn board_live(cx: &Cx) -> Result { + let state = app_context::(cx); + require_role(cx, Need::Viewer).await?; + let board = the_board(&state.store).await?; + let store = state.store.clone(); + let board_id = board.id.clone(); + stream_changes( + cx, + &state.live, + &[Topic::Board(board.id.clone())], + move || { + let store = store.clone(); + let board_id = board_id.clone(); + async move { + let fingerprint: iz_core::Result = store.board_fingerprint(&board_id).await; + Ok(fingerprint?) + } + }, + ) + .await +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn board_url_keeps_only_set_filters() { + let mut filters = Filters { + sort: "deadline", + ..Filters::default() + }; + assert_eq!(board_url(&filters, &[]), "/"); + filters.query = "a b&c".into(); + filters.sort = "title"; + assert_eq!(board_url(&filters, &[]), "/?sort=title&q=a%20b%26c"); + } + + #[test] + fn unknown_sort_and_empty_filters_fall_back() { + let filters = parse_filters(Some("sort=bogus&tag=nope&assignee=nobody-here"), &[], &[]); + assert_eq!(filters.sort, "deadline"); + assert!(filters.tag.is_empty()); + assert!(filters.assignee.is_empty()); + assert!(!filters.active()); + } +} + +/// Test support: a member of the given role with a live session, made through the store. Returns the +/// session's cookie token and its CSRF token. +#[cfg(test)] +use iz_core::store::tasks::NewTask; + +#[cfg(test)] +pub(crate) async fn sign_in_as(state: &AppState, sub: &str, role: Role) -> (String, String) { + use crate::auth::SESSION_LIFETIME; + use iz_core::store::members::DirectoryMember; + let member = DirectoryMember { + sub: sub.into(), + email: format!("{sub}@example.com"), + name: format!("Member {sub}"), + im_admin: false, + disabled: false, + locale: None, + zoneinfo: "Europe/Istanbul".into(), + picture_version: 0, + }; + state + .store + .apply_directory_member(&member, role) + .await + .expect("member"); + let issued = state + .store + .create_session(sub, Some("sid-test"), None, SESSION_LIFETIME, None, None) + .await + .expect("session"); + (issued.token, issued.csrf_token) +} + +/// Test support: the cookie header of a session. +#[cfg(test)] +pub(crate) fn cookie_of(token: &str) -> String { + format!("__Host-iz_session={token}") +} + +/// Test support: makes the board and one card in its first column, as the store makes them. Returns the +/// card's id and the board's first column id. `actor` must be a member of the store, since a card +/// names its creator. +#[cfg(test)] +pub(crate) async fn one_card(state: &AppState, title: &str, actor: &str) -> (String, String) { + let board = state.store.ensure_board("IZ").await.expect("board"); + let columns = state.store.columns(&board.id).await.expect("columns"); + let tags = state.store.tags(&board.id).await.expect("tags"); + let task = state + .store + .create_task( + &board.id, + NewTask { + title: title.into(), + description: String::new(), + column_id: columns[0].id.clone(), + tag_id: tags[0].id.clone(), + deadline: None, + meeting_at: None, + assignees: Vec::new(), + parent_id: None, + link: None, + }, + actor, + ) + .await + .expect("task"); + (task.id, columns[0].id.clone()) +} + +#[cfg(test)] +mod render_tests { + use http::header::COOKIE; + use iz_core::authz::Role; + use iz_core::store::tasks::NewTask; + use topcoat::router::{Body, to_bytes}; + + use super::{cookie_of, one_card, sign_in_as}; + use crate::boot::{router, test_state}; + + /// The member who creates the test cards. Their row must exist: a card names its creator. + const AUTHOR: &str = "01ADAAAAAAAAAAAAAAAAAAAAAA"; + + /// The board page of a signed-in viewer, as text. + async fn get_page(state: &crate::state::AppState, path: &str, token: &str) -> (u16, String) { + let request = http::Request::get(path) + .header(COOKIE, cookie_of(token)) + .body(Body::empty()) + .expect("request"); + let response = router(state.clone()).handle(request).await; + let status = response.status().as_u16(); + let bytes = to_bytes(response.into_body(), 1024 * 1024) + .await + .expect("body"); + (status, String::from_utf8_lossy(&bytes).into_owned()) + } + + /// A search folds Turkish dotted capital I: `istanbul` finds `İstanbul`, and the other card stays + /// out of the page. + #[tokio::test] + async fn search_folds_turkish_capital_i() { + let (_dir, state) = test_state().await; + let (token, _) = sign_in_as(&state, AUTHOR, Role::Member).await; + one_card(&state, "İstanbul ofisi", AUTHOR).await; + let board = state.store.board().await.expect("board").expect("some"); + let tags = state.store.tags(&board.id).await.expect("tags"); + let columns = state.store.columns(&board.id).await.expect("columns"); + state + .store + .create_task( + &board.id, + NewTask { + title: "Ankara ofisi".into(), + description: String::new(), + column_id: columns[0].id.clone(), + tag_id: tags[0].id.clone(), + deadline: None, + meeting_at: None, + assignees: Vec::new(), + parent_id: None, + link: None, + }, + AUTHOR, + ) + .await + .expect("second task"); + let (status, html) = get_page(&state, "/?q=ISTANBUL", &token).await; + assert_eq!(status, 200); + assert!(html.contains("İstanbul ofisi"), "match missing: {html}"); + assert!(!html.contains("Ankara ofisi"), "non-match shown: {html}"); + } + + /// A title that is markup reaches the page as text: escaped, never as a script element. + #[tokio::test] + async fn a_script_title_is_escaped_on_the_board() { + let (_dir, state) = test_state().await; + let (token, _) = sign_in_as(&state, AUTHOR, Role::Member).await; + one_card(&state, "", AUTHOR).await; + let (status, html) = get_page(&state, "/", &token).await; + assert_eq!(status, 200); + assert!( + html.contains("<script>alert(1)</script>"), + "not escaped: {html}" + ); + assert!( + !html.contains(" + if let Some(src) = page_script { + + } @@ -93,7 +102,6 @@ pub async fn message_page( } /// An error message for a failed action. Forms show it above their fields. -#[allow(dead_code)] // The first form that can fail a check uses it. #[component] pub async fn alert(message: &str) -> Result { Ok(view! { }) @@ -115,3 +123,10 @@ pub async fn empty_state(title: &str, #[default] child: Child<'_>) -> Result }) } + +/// Turns a rendered view into the response of a handler. For a handler that answers with a view on one +/// path and with a redirect or JSON on another. +pub async fn respond(cx: &Cx, view: impl View) -> Result { + let handle = view.first().await?; + handle.into_response(cx) +} diff --git a/style/_board.scss b/style/_board.scss new file mode 100644 index 0000000..466e715 --- /dev/null +++ b/style/_board.scss @@ -0,0 +1,295 @@ +//! The board page: the filter bar, the columns with their cards, the card chips and avatars, the +//! new-task form and the toast of a refused drag. Chip colours come from a fixed palette of eight +//! tones; no user-written CSS reaches the page. + +// --- Palette of project tones (fixed, eight entries) ------------------------------------------- + +@mixin tone($n, $bg, $fg) { + .tone-#{$n} { + background: $bg; + color: $fg; + } +} + +@include tone(0, #e6ebff, #2a43a8); +@include tone(1, #e4f4ea, #1e6b35); +@include tone(2, #fff4d6, #7a4f00); +@include tone(3, #fdecea, #9b2219); +@include tone(4, #efe6ff, #5a2a9e); +@include tone(5, #e0f3f5, #1c6470); +@include tone(6, #fbe9f3, #8c2a64); +@include tone(7, #eeeeea, #3e4250); + +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) { + .tone-0 { background: #1f2a4f; color: #c2d0ff; } + .tone-1 { background: #173424; color: #9fe0b4; } + .tone-2 { background: #3a2e10; color: #f2c265; } + .tone-3 { background: #3a1d1b; color: #ffb4ac; } + .tone-4 { background: #2e2245; color: #d7c2ff; } + .tone-5 { background: #15313a; color: #9fdbe6; } + .tone-6 { background: #3a1d2c; color: #f3b3d3; } + .tone-7 { background: #2a2d35; color: #d0d4dd; } + } +} + +:root[data-theme="dark"] { + .tone-0 { background: #1f2a4f; color: #c2d0ff; } + .tone-1 { background: #173424; color: #9fe0b4; } + .tone-2 { background: #3a2e10; color: #f2c265; } + .tone-3 { background: #3a1d1b; color: #ffb4ac; } + .tone-4 { background: #2e2245; color: #d7c2ff; } + .tone-5 { background: #15313a; color: #9fdbe6; } + .tone-6 { background: #3a1d2c; color: #f3b3d3; } + .tone-7 { background: #2a2d35; color: #d0d4dd; } +} + +// --- Page ------------------------------------------------------------------------------------- + +.board { + display: grid; + gap: var(--space-4); + width: 100%; + padding: var(--space-4) var(--space-4) var(--space-8); +} + +.board-toolbar { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + justify-content: space-between; + gap: var(--space-3); +} + +.board-summary { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--space-2); +} + +.filters { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + gap: var(--space-3); +} + +.filters .field { + min-width: 9rem; +} + +.filters .field-search { + min-width: 14rem; +} + +.filters .field label, +.new-task label { + margin-bottom: 0; +} + +.filters-actions { + display: flex; + align-items: center; + gap: var(--space-2); +} + +// --- Columns and cards ------------------------------------------------------------------------ + +.columns { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); + gap: var(--space-4); + align-items: start; +} + +.board-column { + display: grid; + gap: var(--space-2); + padding: var(--space-3); + min-height: 8rem; + background: var(--surface-2); + border: 1px solid var(--border); + border-radius: var(--radius); +} + +.board-column-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-2); + padding: 0 var(--space-1); + font-weight: 650; +} + +.column-cards { + display: grid; + gap: var(--space-2); + margin: 0; + padding: 0; + list-style: none; + min-height: 3rem; +} + +.column-cards.is-target { + outline: 2px dashed var(--focus); + outline-offset: 2px; + border-radius: var(--radius-sm); +} + +.task-card { + display: grid; + gap: var(--space-2); + padding: var(--space-3); + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-sm); + box-shadow: var(--shadow); +} + +.task-card[draggable="true"] { + cursor: grab; +} + +.task-card.is-dragging { + opacity: 0.5; +} + +.task-card.is-done { + opacity: 0.65; +} + +.task-key { + color: var(--muted); + font-family: var(--font-mono); + font-size: 0.8rem; +} + +.task-title { + margin: 0; + font-size: 1rem; + overflow-wrap: anywhere; +} + +.task-meta { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--space-1); + font-size: var(--text-sm); + color: var(--muted); +} + +.task-actions { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + gap: var(--space-2); + padding-top: var(--space-2); + border-top: 1px solid var(--border); +} + +.task-actions .field { + flex: 1 1 8rem; +} + +.task-actions .field label { + font-size: 0.8rem; +} + +.task-actions .button { + min-height: 2.25rem; +} + +// --- Chips and avatars ------------------------------------------------------------------------ + +.chip { + display: inline-block; + padding: 0.1rem var(--space-2); + border-radius: 999px; + background: var(--surface-2); + color: var(--muted); + font-size: 0.78rem; + font-weight: 600; + white-space: nowrap; +} + +.chip.overdue { + background: var(--danger-soft); + color: var(--danger); +} + +.chip.blocked { + background: var(--warn-soft); + color: var(--warn); +} + +.avatars { + display: flex; + margin: 0; + padding: 0; + list-style: none; +} + +.avatars li + li { + margin-left: -0.4rem; +} + +.avatar { + display: block; + width: 1.6rem; + height: 1.6rem; + border-radius: 50%; + border: 2px solid var(--surface); + background: var(--surface-2); + object-fit: cover; + font-size: 0.7rem; +} + +// --- New task, notices, toast ----------------------------------------------------------------- + +.new-task { + display: grid; + gap: var(--space-3); +} + +.new-task-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr)); + gap: var(--space-3); +} + +.new-task-grid .field-wide { + grid-column: 1 / -1; +} + +.new-task-actions { + display: flex; + align-items: center; + gap: var(--space-3); +} + +.toast { + position: fixed; + left: 50%; + bottom: var(--space-6); + transform: translateX(-50%); + max-width: min(90vw, 32rem); + padding: var(--space-3) var(--space-4); + background: var(--danger-soft); + color: var(--danger); + border: 1px solid var(--danger); + border-radius: var(--radius-sm); + box-shadow: var(--shadow-lift); + z-index: 10; +} + +@media (max-width: 720px) { + .board { + padding: var(--space-2) var(--space-2) var(--space-6); + } + + .columns { + grid-template-columns: 1fr; + } +} diff --git a/style/main.scss b/style/main.scss index 8986579..00a9ad7 100644 --- a/style/main.scss +++ b/style/main.scss @@ -6,3 +6,4 @@ @use "base"; @use "layout"; @use "components"; +@use "board";