Board page: columns, cards, filters, search, new task, move rules, drag and drop
Browse files at this commit8b14dabb26fad08f8fad550564775ca7aef4adebParent: b06a190- feat
- board page: columns, cards, filters, search, new task, move rules, drag and drop
27 changed files +2431 -115
- Cargo.lock +1 -0
- crates/iz-core/src/store/migrate.rs +4 -1
- crates/iz-core/src/store/tasks.rs +71 -7
- crates/iz-web/Cargo.toml +1 -0
- crates/iz-web/assets/board.js +175 -0
- crates/iz-web/build.rs +2 -1
- crates/iz-web/src/assets.rs +10 -0
- crates/iz-web/src/auth.rs +15 -11
- crates/iz-web/src/boot.rs +4 -0
- crates/iz-web/src/directory.rs +38 -10
- crates/iz-web/src/i18n/board.rs +256 -0
- crates/iz-web/src/i18n/mod.rs +1 -0
- crates/iz-web/src/i18n/shell.rs +0 -12
- crates/iz-web/src/main.rs +0 -2
- crates/iz-web/src/oidc.rs +35 -12
- crates/iz-web/src/pages/backchannel.rs +12 -2
- crates/iz-web/src/pages/board.rs +547 -0
- crates/iz-web/src/pages/home.rs +0 -45
- crates/iz-web/src/pages/mod.rs +2 -1
- crates/iz-web/src/pages/not_found.rs +1 -1
- crates/iz-web/src/pages/photo.rs +1 -3
- crates/iz-web/src/pages/sign_in.rs +18 -4
- crates/iz-web/src/pages/tasks.rs +565 -0
- crates/iz-web/src/views/board.rs +358 -0
- crates/iz-web/src/views/mod.rs +18 -3
- style/_board.scss +295 -0
- style/main.scss +1 -0
Cargo.lockmodified+1 -0
| @@ -1817,6 +1817,7 @@ dependencies = [ | |||
| 1817 | "hex", | 1817 | "hex", |
| 1818 | "http", | 1818 | "http", |
| 1819 | "iz-core", | 1819 | "iz-core", |
| 1820 | + "jiff", | ||
| 1820 | "jsonwebtoken", | 1821 | "jsonwebtoken", |
| 1821 | "rand 0.10.3", | 1822 | "rand 0.10.3", |
| 1822 | "reqwest", | 1823 | "reqwest", |
crates/iz-core/src/store/migrate.rsmodified+4 -1
| @@ -10,7 +10,10 @@ use crate::time::now_stamp; | |||
| 10 | /// `(version, sql)` in ascending order. | 10 | /// `(version, sql)` in ascending order. |
| 11 | pub const MIGRATIONS: &[(u32, &str)] = &[ | 11 | pub const MIGRATIONS: &[(u32, &str)] = &[ |
| 12 | (1, include_str!("../../migrations/0001_init.sql")), | 12 | (1, include_str!("../../migrations/0001_init.sql")), |
| 13 | - (2, include_str!("../../migrations/0002_session_id_token.sql")), | 13 | + ( |
| 14 | + 2, | ||
| 15 | + include_str!("../../migrations/0002_session_id_token.sql"), | ||
| 16 | + ), | ||
| 14 | ]; | 17 | ]; |
| 15 | 18 | ||
| 16 | fn migration_err(e: turso::Error) -> Error { | 19 | fn migration_err(e: turso::Error) -> Error { |
crates/iz-core/src/store/tasks.rsmodified+71 -7
| @@ -376,6 +376,29 @@ async fn next_position(conn: &Connection, column_id: &str) -> Result<f64> { | |||
| 376 | Ok(position_between(last, None)) | 376 | Ok(position_between(last, None)) |
| 377 | } | 377 | } |
| 378 | 378 | ||
| 379 | +/// Position for a task placed at `index` among the top-level cards of a column, between its neighbours | ||
| 380 | +/// there. The moving task itself is left out, so a card never sits between itself and a neighbour. An | ||
| 381 | +/// index past the end places the task last. | ||
| 382 | +async fn position_at( | ||
| 383 | + conn: &Connection, | ||
| 384 | + column_id: &str, | ||
| 385 | + moving_id: &str, | ||
| 386 | + index: usize, | ||
| 387 | +) -> Result<f64> { | ||
| 388 | + let positions = fetch_all( | ||
| 389 | + conn, | ||
| 390 | + "SELECT position FROM tasks WHERE column_id = ?1 AND id <> ?2 AND parent_id IS NULL \ | ||
| 391 | + AND deleted_at IS NULL ORDER BY position, id", | ||
| 392 | + (column_id.to_owned(), moving_id.to_owned()), | ||
| 393 | + |row| col_real(row, 0), | ||
| 394 | + ) | ||
| 395 | + .await?; | ||
| 396 | + let index = index.min(positions.len()); | ||
| 397 | + let before = index.checked_sub(1).map(|i| positions[i]); | ||
| 398 | + let after = positions.get(index).copied(); | ||
| 399 | + Ok(position_between(before, after)) | ||
| 400 | +} | ||
| 401 | + | ||
| 379 | /// Appends a row to the transitions table. `from` is `None` for the first placement. | 402 | /// Appends a row to the transitions table. `from` is `None` for the first placement. |
| 380 | async fn record_transition( | 403 | async fn record_transition( |
| 381 | tx: &Transaction<'_>, | 404 | tx: &Transaction<'_>, |
| @@ -679,12 +702,16 @@ impl Store { | |||
| 679 | /// Moves a task to `to_column` if it is still in `expected_from`. Entering the done column stamps | 702 | /// Moves a task to `to_column` if it is still in `expected_from`. Entering the done column stamps |
| 680 | /// `done_at` and is refused while subtasks are open; leaving it clears `done_at`. Each real move writes | 703 | /// `done_at` and is refused while subtasks are open; leaving it clears `done_at`. Each real move writes |
| 681 | /// one transition and one `task_moved` activity row. | 704 | /// one transition and one `task_moved` activity row. |
| 705 | + /// | ||
| 706 | + /// `index` is the place among the column's top-level cards (0 is the top); `None` appends. A move | ||
| 707 | + /// inside the same column is `Unchanged`: reordering within a column is not a move. | ||
| 682 | pub async fn move_task( | 708 | pub async fn move_task( |
| 683 | &self, | 709 | &self, |
| 684 | board_id: &str, | 710 | board_id: &str, |
| 685 | task_id: &str, | 711 | task_id: &str, |
| 686 | expected_from: &str, | 712 | expected_from: &str, |
| 687 | to_column: &str, | 713 | to_column: &str, |
| 714 | + index: Option<usize>, | ||
| 688 | actor: &str, | 715 | actor: &str, |
| 689 | ) -> Result<MoveOutcome> { | 716 | ) -> Result<MoveOutcome> { |
| 690 | let conn = self.inner.conn.lock().await; | 717 | let conn = self.inner.conn.lock().await; |
| @@ -714,7 +741,10 @@ impl Store { | |||
| 714 | return Ok(MoveOutcome::SubtasksOpen); | 741 | return Ok(MoveOutcome::SubtasksOpen); |
| 715 | } | 742 | } |
| 716 | } | 743 | } |
| 717 | - let position = next_position(&tx, &target.id).await?; | 744 | + let position = match index { |
| 745 | + Some(index) => position_at(&tx, &target.id, task_id, index).await?, | ||
| 746 | + None => next_position(&tx, &target.id).await?, | ||
| 747 | + }; | ||
| 718 | let now = now_stamp(); | 748 | let now = now_stamp(); |
| 719 | let done_at = target.is_done.then(|| now.clone()); | 749 | let done_at = target.is_done.then(|| now.clone()); |
| 720 | tx.execute( | 750 | tx.execute( |
| @@ -1079,6 +1109,40 @@ impl Store { | |||
| 1079 | finish(tx, outcome).await | 1109 | finish(tx, outcome).await |
| 1080 | } | 1110 | } |
| 1081 | 1111 | ||
| 1112 | + /// A cheap summary of everything the board page shows: counts and the newest change of the board's | ||
| 1113 | + /// tasks, assignments, links, comments, columns and projects. The live stream sends `changed` only | ||
| 1114 | + /// when this text changes, so it must change whenever any of those rows does. | ||
| 1115 | + pub async fn board_fingerprint(&self, board_id: &str) -> Result<String> { | ||
| 1116 | + let conn = self.read_conn().await; | ||
| 1117 | + let row = fetch_opt( | ||
| 1118 | + &conn, | ||
| 1119 | + "SELECT \ | ||
| 1120 | + (SELECT COUNT(*) FROM tasks WHERE board_id = ?1), \ | ||
| 1121 | + (SELECT COALESCE(MAX(updated_at), '') FROM tasks WHERE board_id = ?1), \ | ||
| 1122 | + (SELECT COUNT(*) FROM task_assignees a JOIN tasks t ON t.id = a.task_id WHERE t.board_id = ?1), \ | ||
| 1123 | + (SELECT COUNT(*) FROM dependencies d JOIN tasks t ON t.id = d.blocked_id \ | ||
| 1124 | + WHERE t.board_id = ?1 AND d.cleared_at IS NULL), \ | ||
| 1125 | + (SELECT COUNT(*) FROM comments c JOIN tasks t ON t.id = c.task_id WHERE t.board_id = ?1), \ | ||
| 1126 | + (SELECT COUNT(*) FROM columns WHERE board_id = ?1), \ | ||
| 1127 | + (SELECT COUNT(*) FROM tags WHERE board_id = ?1)", | ||
| 1128 | + (board_id.to_owned(),), | ||
| 1129 | + |row| { | ||
| 1130 | + Ok(format!( | ||
| 1131 | + "{}|{}|{}|{}|{}|{}|{}", | ||
| 1132 | + col_int(row, 0)?, | ||
| 1133 | + col_text(row, 1)?, | ||
| 1134 | + col_int(row, 2)?, | ||
| 1135 | + col_int(row, 3)?, | ||
| 1136 | + col_int(row, 4)?, | ||
| 1137 | + col_int(row, 5)?, | ||
| 1138 | + col_int(row, 6)?, | ||
| 1139 | + )) | ||
| 1140 | + }, | ||
| 1141 | + ) | ||
| 1142 | + .await?; | ||
| 1143 | + Ok(row.unwrap_or_default()) | ||
| 1144 | + } | ||
| 1145 | + | ||
| 1082 | /// The board for one viewer: live columns with their top-level cards, after the filter and sort. | 1146 | /// The board for one viewer: live columns with their top-level cards, after the filter and sort. |
| 1083 | /// Overdue uses `viewer_zone` for day-only deadlines. Blocked means not done with an uncleared blocker | 1147 | /// Overdue uses `viewer_zone` for day-only deadlines. Blocked means not done with an uncleared blocker |
| 1084 | /// that is itself not done and not deleted. The search folds Turkish i (see `board::fold_for_search`). | 1148 | /// that is itself not done and not deleted. The search folds Turkish i (see `board::fold_for_search`). |
| @@ -1448,17 +1512,17 @@ mod tests { | |||
| 1448 | .await | 1512 | .await |
| 1449 | .unwrap(); | 1513 | .unwrap(); |
| 1450 | let outcome = store | 1514 | let outcome = store |
| 1451 | - .move_task(&board, &parent.id, &backlog, &done.id, "ada") | 1515 | + .move_task(&board, &parent.id, &backlog, &done.id, None, "ada") |
| 1452 | .await | 1516 | .await |
| 1453 | .unwrap(); | 1517 | .unwrap(); |
| 1454 | assert_eq!(outcome, MoveOutcome::SubtasksOpen); | 1518 | assert_eq!(outcome, MoveOutcome::SubtasksOpen); |
| 1455 | // Finishing the subtask first lets the parent through. | 1519 | // Finishing the subtask first lets the parent through. |
| 1456 | store | 1520 | store |
| 1457 | - .move_task(&board, &child.id, &backlog, &done.id, "ada") | 1521 | + .move_task(&board, &child.id, &backlog, &done.id, None, "ada") |
| 1458 | .await | 1522 | .await |
| 1459 | .unwrap(); | 1523 | .unwrap(); |
| 1460 | let outcome = store | 1524 | let outcome = store |
| 1461 | - .move_task(&board, &parent.id, &backlog, &done.id, "ada") | 1525 | + .move_task(&board, &parent.id, &backlog, &done.id, None, "ada") |
| 1462 | .await | 1526 | .await |
| 1463 | .unwrap(); | 1527 | .unwrap(); |
| 1464 | assert_eq!(outcome, MoveOutcome::Moved); | 1528 | assert_eq!(outcome, MoveOutcome::Moved); |
| @@ -1478,16 +1542,16 @@ mod tests { | |||
| 1478 | .unwrap(); | 1542 | .unwrap(); |
| 1479 | // Someone else already moved it, so the client's view of "from" is out of date. | 1543 | // Someone else already moved it, so the client's view of "from" is out of date. |
| 1480 | store | 1544 | store |
| 1481 | - .move_task(&board, &task.id, &backlog, &progress, "bo") | 1545 | + .move_task(&board, &task.id, &backlog, &progress, None, "bo") |
| 1482 | .await | 1546 | .await |
| 1483 | .unwrap(); | 1547 | .unwrap(); |
| 1484 | let stale = store | 1548 | let stale = store |
| 1485 | - .move_task(&board, &task.id, &backlog, &columns[2].id, "ada") | 1549 | + .move_task(&board, &task.id, &backlog, &columns[2].id, None, "ada") |
| 1486 | .await | 1550 | .await |
| 1487 | .unwrap(); | 1551 | .unwrap(); |
| 1488 | assert_eq!(stale, MoveOutcome::Stale); | 1552 | assert_eq!(stale, MoveOutcome::Stale); |
| 1489 | let same = store | 1553 | let same = store |
| 1490 | - .move_task(&board, &task.id, &progress, &progress, "ada") | 1554 | + .move_task(&board, &task.id, &progress, &progress, None, "ada") |
| 1491 | .await | 1555 | .await |
| 1492 | .unwrap(); | 1556 | .unwrap(); |
| 1493 | assert_eq!(same, MoveOutcome::Unchanged); | 1557 | assert_eq!(same, MoveOutcome::Unchanged); |
crates/iz-web/Cargo.tomlmodified+1 -0
| @@ -16,6 +16,7 @@ futures-util.workspace = true | |||
| 16 | hex.workspace = true | 16 | hex.workspace = true |
| 17 | http.workspace = true | 17 | http.workspace = true |
| 18 | iz-core.workspace = true | 18 | iz-core.workspace = true |
| 19 | +jiff.workspace = true | ||
| 19 | jsonwebtoken.workspace = true | 20 | jsonwebtoken.workspace = true |
| 20 | rand.workspace = true | 21 | rand.workspace = true |
| 21 | reqwest.workspace = true | 22 | reqwest.workspace = true |
crates/iz-web/assets/board.jsadded+175 -0
| @@ -0,0 +1,175 @@ | |||
| 1 | +/* | ||
| 2 | + * board.js: drag and drop of cards on the board page. It is progressive enhancement. Without it every | ||
| 3 | + * card still has a "move to" form that works as a plain POST, so nothing here is needed for a move. | ||
| 4 | + * | ||
| 5 | + * What it does, for a member (the page has data-board-write on its section): | ||
| 6 | + * - A card is dragged into another column. The card moves in the page as the pointer moves, so the | ||
| 7 | + * place it would land in is visible. Dropping it sends one POST to /tasks/{id}/move with the | ||
| 8 | + * column the page last showed (`from`), the target column (`to`) and the place (`position`), and | ||
| 9 | + * asks for JSON. The server's answer decides: {ok: true} keeps the card where it was dropped; | ||
| 10 | + * anything else puts it back and shows a toast with the server's translated message. | ||
| 11 | + * - A drag that ends outside any column puts the card back where it was. | ||
| 12 | + * | ||
| 13 | + * What it never does: decide anything about the move itself. The server checks the column, the | ||
| 14 | + * subtasks, the role and the token; this script only shows the result. Dropping onto the card's own | ||
| 15 | + * column is nothing to send, so it puts the card back. | ||
| 16 | + * | ||
| 17 | + * The CSRF token comes from data-csrf on the section, which the server renders for this session. The | ||
| 18 | + * file is one IIFE with no globals, and it is loaded with `defer`. | ||
| 19 | + */ | ||
| 20 | +(function () { | ||
| 21 | + "use strict"; | ||
| 22 | + | ||
| 23 | + const board = document.querySelector("[data-board-write]"); | ||
| 24 | + if (!board || !window.fetch || !window.URLSearchParams) { | ||
| 25 | + return; | ||
| 26 | + } | ||
| 27 | + | ||
| 28 | + /** How long a toast stays on the page, in milliseconds. */ | ||
| 29 | + const TOAST_MS = 5000; | ||
| 30 | + | ||
| 31 | + /** The session's CSRF token, rendered by the server into the board section. */ | ||
| 32 | + const csrf = board.dataset.csrf || ""; | ||
| 33 | + | ||
| 34 | + /** The text shown when the request never got an answer. Rendered in the page's language. */ | ||
| 35 | + const failedText = board.dataset.msgFailed || "The card could not be moved. Try again."; | ||
| 36 | + | ||
| 37 | + /** The card being dragged, its place before the drag, and the column it started in. */ | ||
| 38 | + let dragged = null; | ||
| 39 | + let origin = null; | ||
| 40 | + | ||
| 41 | + /** The column the page showed the card in: the one the server is told about. */ | ||
| 42 | + function columnOf(list) { | ||
| 43 | + return list.dataset.columnId; | ||
| 44 | + } | ||
| 45 | + | ||
| 46 | + /** Puts `card` back where `start` says it was before the drag. */ | ||
| 47 | + function restore(card, start) { | ||
| 48 | + if (start.next && start.next.parentNode === start.parent) { | ||
| 49 | + start.parent.insertBefore(card, start.next); | ||
| 50 | + } else { | ||
| 51 | + start.parent.appendChild(card); | ||
| 52 | + } | ||
| 53 | + card.dataset.columnId = columnOf(start.parent); | ||
| 54 | + } | ||
| 55 | + | ||
| 56 | + /** The card's index among the cards of its column, counting only cards (not other children). */ | ||
| 57 | + function indexIn(list, card) { | ||
| 58 | + return Array.from(list.children) | ||
| 59 | + .filter((child) => child.classList.contains("card")) | ||
| 60 | + .indexOf(card); | ||
| 61 | + } | ||
| 62 | + | ||
| 63 | + /** Puts the card before the first other card whose middle is below the pointer. */ | ||
| 64 | + function placeAt(list, card, clientY) { | ||
| 65 | + const others = Array.from(list.children).filter( | ||
| 66 | + (child) => child.classList.contains("card") && child !== card | ||
| 67 | + ); | ||
| 68 | + const before = others.find((other) => { | ||
| 69 | + const rect = other.getBoundingClientRect(); | ||
| 70 | + return clientY < rect.top + rect.height / 2; | ||
| 71 | + }); | ||
| 72 | + if (before) { | ||
| 73 | + list.insertBefore(card, before); | ||
| 74 | + } else { | ||
| 75 | + list.appendChild(card); | ||
| 76 | + } | ||
| 77 | + } | ||
| 78 | + | ||
| 79 | + /** Shows a short message that goes away by itself. Created in the page, never from user input. */ | ||
| 80 | + function toast(text) { | ||
| 81 | + const el = document.createElement("div"); | ||
| 82 | + el.className = "toast"; | ||
| 83 | + el.setAttribute("role", "alert"); | ||
| 84 | + el.textContent = text; | ||
| 85 | + document.body.appendChild(el); | ||
| 86 | + setTimeout(() => el.remove(), TOAST_MS); | ||
| 87 | + } | ||
| 88 | + | ||
| 89 | + /** Sends the move and applies the answer. A card the server refused goes back to its place. */ | ||
| 90 | + async function send(card, start, from, to, index) { | ||
| 91 | + const id = card.dataset.taskId; | ||
| 92 | + const body = new URLSearchParams({ csrf, from, to, position: String(index) }); | ||
| 93 | + let answer = null; | ||
| 94 | + let data = null; | ||
| 95 | + try { | ||
| 96 | + answer = await fetch(`/tasks/${encodeURIComponent(id)}/move`, { | ||
| 97 | + method: "POST", | ||
| 98 | + body, | ||
| 99 | + headers: { Accept: "application/json" }, | ||
| 100 | + credentials: "same-origin", | ||
| 101 | + }); | ||
| 102 | + data = await answer.json(); | ||
| 103 | + } catch (error) { | ||
| 104 | + data = null; | ||
| 105 | + } | ||
| 106 | + if (answer && answer.ok && data && data.ok) { | ||
| 107 | + const input = card.querySelector('input[name="from"]'); | ||
| 108 | + if (input) input.value = to; | ||
| 109 | + return; | ||
| 110 | + } | ||
| 111 | + restore(card, start); | ||
| 112 | + toast((data && data.message) || failedText); | ||
| 113 | + } | ||
| 114 | + | ||
| 115 | + /** Records where a drag started, so a refused or cancelled drop can put the card back. */ | ||
| 116 | + function onDragStart(event) { | ||
| 117 | + const card = event.target.closest(".card[data-task-id]"); | ||
| 118 | + if (!card) return; | ||
| 119 | + dragged = card; | ||
| 120 | + origin = { parent: card.parentNode, next: card.nextSibling }; | ||
| 121 | + card.classList.add("is-dragging"); | ||
| 122 | + event.dataTransfer.effectAllowed = "move"; | ||
| 123 | + event.dataTransfer.setData("text/plain", card.dataset.taskId || ""); | ||
| 124 | + } | ||
| 125 | + | ||
| 126 | + /** Moves the card in the page while the pointer is over another column. */ | ||
| 127 | + function onDragOver(event) { | ||
| 128 | + if (!dragged) return; | ||
| 129 | + const list = event.currentTarget; | ||
| 130 | + if (columnOf(list) === columnOf(origin.parent)) { | ||
| 131 | + restore(dragged, origin); | ||
| 132 | + return; | ||
| 133 | + } | ||
| 134 | + event.preventDefault(); | ||
| 135 | + event.dataTransfer.dropEffect = "move"; | ||
| 136 | + placeAt(list, dragged, event.clientY); | ||
| 137 | + dragged.dataset.columnId = columnOf(list); | ||
| 138 | + } | ||
| 139 | + | ||
| 140 | + /** A drop in another column sends the move. A drop in the same column changes nothing. */ | ||
| 141 | + function onDrop(event) { | ||
| 142 | + if (!dragged) return; | ||
| 143 | + const list = event.currentTarget; | ||
| 144 | + event.preventDefault(); | ||
| 145 | + const card = dragged; | ||
| 146 | + const start = origin; | ||
| 147 | + const from = columnOf(start.parent); | ||
| 148 | + const to = columnOf(list); | ||
| 149 | + const index = indexIn(list, card); | ||
| 150 | + dragged = null; | ||
| 151 | + origin = null; | ||
| 152 | + card.classList.remove("is-dragging"); | ||
| 153 | + if (from === to) { | ||
| 154 | + restore(card, start); | ||
| 155 | + return; | ||
| 156 | + } | ||
| 157 | + send(card, start, from, to, index); | ||
| 158 | + } | ||
| 159 | + | ||
| 160 | + /** A drag that ends without a drop (Escape, a drop outside) puts the card back. */ | ||
| 161 | + function onDragEnd() { | ||
| 162 | + if (!dragged) return; | ||
| 163 | + restore(dragged, origin); | ||
| 164 | + dragged.classList.remove("is-dragging"); | ||
| 165 | + dragged = null; | ||
| 166 | + origin = null; | ||
| 167 | + } | ||
| 168 | + | ||
| 169 | + board.addEventListener("dragstart", onDragStart); | ||
| 170 | + board.addEventListener("dragend", onDragEnd); | ||
| 171 | + for (const list of board.querySelectorAll(".column-cards[data-column-id]")) { | ||
| 172 | + list.addEventListener("dragover", onDragOver); | ||
| 173 | + list.addEventListener("drop", onDrop); | ||
| 174 | + } | ||
| 175 | +})(); | ||
crates/iz-web/build.rsmodified+2 -1
| @@ -1,6 +1,6 @@ | |||
| 1 | //! Build script of the `iz` binary. It compiles `style/main.scss` into `OUT_DIR/main.css`, and it | 1 | //! Build script of the `iz` binary. It compiles `style/main.scss` into `OUT_DIR/main.css`, and it |
| 2 | //! emits the build identity and the content hashes that the page links use as cache-busting | 2 | //! emits the build identity and the content hashes that the page links use as cache-busting |
| 3 | -//! queries: `IZ_MAIN_CSS_V`, `IZ_NAV_JS_V`, `IZ_PAGES_JS_V` and `IZ_BUILD_SHA`. | 3 | +//! queries: `IZ_MAIN_CSS_V`, `IZ_NAV_JS_V`, `IZ_PAGES_JS_V`, `IZ_BOARD_JS_V` and `IZ_BUILD_SHA`. |
| 4 | //! | 4 | //! |
| 5 | //! It does not decide what is served: `src/assets.rs` embeds the files. It does not decide what a | 5 | //! It does not decide what is served: `src/assets.rs` embeds the files. It does not decide what a |
| 6 | //! page links to either: `src/assets.rs` builds the `?v=` URLs from these values. It only compiles | 6 | //! page links to either: `src/assets.rs` builds the `?v=` URLs from these values. It only compiles |
| @@ -45,6 +45,7 @@ fn main() { | |||
| 45 | for (var, file) in [ | 45 | for (var, file) in [ |
| 46 | ("IZ_NAV_JS_V", "assets/nav.js"), | 46 | ("IZ_NAV_JS_V", "assets/nav.js"), |
| 47 | ("IZ_PAGES_JS_V", "assets/pages.js"), | 47 | ("IZ_PAGES_JS_V", "assets/pages.js"), |
| 48 | + ("IZ_BOARD_JS_V", "assets/board.js"), | ||
| 48 | ] { | 49 | ] { |
| 49 | let bytes = fs::read(manifest.join(file)).unwrap_or_else(|e| panic!("reading {file}: {e}")); | 50 | let bytes = fs::read(manifest.join(file)).unwrap_or_else(|e| panic!("reading {file}: {e}")); |
| 50 | println!("cargo:rustc-env={var}={}", content_version(&bytes)); | 51 | println!("cargo:rustc-env={var}={}", content_version(&bytes)); |
crates/iz-web/src/assets.rsmodified+10 -0
| @@ -18,9 +18,13 @@ pub const NAV_JS_HREF: &str = concat!("/assets/nav.js?v=", env!("IZ_NAV_JS_V")); | |||
| 18 | /// Link to the script of individual pages. | 18 | /// Link to the script of individual pages. |
| 19 | pub const PAGES_JS_HREF: &str = concat!("/assets/pages.js?v=", env!("IZ_PAGES_JS_V")); | 19 | pub const PAGES_JS_HREF: &str = concat!("/assets/pages.js?v=", env!("IZ_PAGES_JS_V")); |
| 20 | 20 | ||
| 21 | +/// Link to the drag and drop script of the board page. Only that page links it. | ||
| 22 | +pub const BOARD_JS_HREF: &str = concat!("/assets/board.js?v=", env!("IZ_BOARD_JS_V")); | ||
| 23 | + | ||
| 21 | const MAIN_CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/main.css")); | 24 | const MAIN_CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/main.css")); |
| 22 | const NAV_JS: &str = include_str!("../assets/nav.js"); | 25 | const NAV_JS: &str = include_str!("../assets/nav.js"); |
| 23 | const PAGES_JS: &str = include_str!("../assets/pages.js"); | 26 | const PAGES_JS: &str = include_str!("../assets/pages.js"); |
| 27 | +const BOARD_JS: &str = include_str!("../assets/board.js"); | ||
| 24 | const OFFLINE_HTML: &str = include_str!("../assets/offline.html"); | 28 | const OFFLINE_HTML: &str = include_str!("../assets/offline.html"); |
| 25 | const SW_JS: &str = include_str!("../assets/sw.js"); | 29 | const SW_JS: &str = include_str!("../assets/sw.js"); |
| 26 | 30 | ||
| @@ -59,6 +63,12 @@ async fn pages_js() -> Result<Asset> { | |||
| 59 | Ok(asset("text/javascript; charset=utf-8", IMMUTABLE, PAGES_JS)) | 63 | Ok(asset("text/javascript; charset=utf-8", IMMUTABLE, PAGES_JS)) |
| 60 | } | 64 | } |
| 61 | 65 | ||
| 66 | +/// `GET /assets/board.js`. | ||
| 67 | +#[route(GET "/assets/board.js")] | ||
| 68 | +async fn board_js() -> Result<Asset> { | ||
| 69 | + Ok(asset("text/javascript; charset=utf-8", IMMUTABLE, BOARD_JS)) | ||
| 70 | +} | ||
| 71 | + | ||
| 62 | /// `GET /assets/offline.html`. Also precached by the service worker. | 72 | /// `GET /assets/offline.html`. Also precached by the service worker. |
| 63 | #[route(GET "/assets/offline.html")] | 73 | #[route(GET "/assets/offline.html")] |
| 64 | async fn offline_html() -> Result<Asset> { | 74 | async fn offline_html() -> Result<Asset> { |
crates/iz-web/src/auth.rsmodified+15 -11
| @@ -36,15 +36,14 @@ const MAX_NEXT_LEN: usize = 2048; | |||
| 36 | /// Longest user agent stored with a session, in bytes. Reason: the value is only shown to admins. | 36 | /// Longest user agent stored with a session, in bytes. Reason: the value is only shown to admins. |
| 37 | const MAX_USER_AGENT_LEN: usize = 256; | 37 | const MAX_USER_AGENT_LEN: usize = 256; |
| 38 | 38 | ||
| 39 | -/// The level a page or a write needs. Maps to one authorization action. | 39 | +/// The level a page or a write needs. Maps to one authorization action. The administrator level is |
| 40 | +/// added with the admin pages. | ||
| 40 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] | 41 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 41 | pub enum Need { | 42 | pub enum Need { |
| 42 | /// Reading the board. | 43 | /// Reading the board. |
| 43 | Viewer, | 44 | Viewer, |
| 44 | /// Creating and changing tasks, comments and files. | 45 | /// Creating and changing tasks, comments and files. |
| 45 | Member, | 46 | Member, |
| 46 | - /// Settings, roles, tags, columns and rules. | ||
| 47 | - Admin, | ||
| 48 | } | 47 | } |
| 49 | 48 | ||
| 50 | /// A signed-in member and the session that carries them. | 49 | /// A signed-in member and the session that carries them. |
| @@ -123,14 +122,13 @@ pub async fn require_member(cx: &Cx) -> Result<CurrentMember> { | |||
| 123 | } | 122 | } |
| 124 | } | 123 | } |
| 125 | 124 | ||
| 126 | -/// The signed-in member with the level `need`. A shortfall is `404` for admin pages, which must not | 125 | +/// The signed-in member with the level `need`. A viewer who tries a write gets `403`; a member |
| 127 | -/// reveal that they exist, and `403` for a write that a viewer tried. | 126 | +/// with no access, or a disabled one, gets `404`, so the page does not reveal that it exists. |
| 128 | pub async fn require_role(cx: &Cx, need: Need) -> Result<CurrentMember> { | 127 | pub async fn require_role(cx: &Cx, need: Need) -> Result<CurrentMember> { |
| 129 | let me = require_member(cx).await?; | 128 | let me = require_member(cx).await?; |
| 130 | let action = match need { | 129 | let action = match need { |
| 131 | Need::Viewer => Action::ReadBoard, | 130 | Need::Viewer => Action::ReadBoard, |
| 132 | Need::Member => Action::WriteTask, | 131 | Need::Member => Action::WriteTask, |
| 133 | - Need::Admin => Action::Administer, | ||
| 134 | }; | 132 | }; |
| 135 | match authorize(&me.actor(), &action) { | 133 | match authorize(&me.actor(), &action) { |
| 136 | Ok(()) => Ok(me), | 134 | Ok(()) => Ok(me), |
| @@ -139,10 +137,11 @@ pub async fn require_role(cx: &Cx, need: Need) -> Result<CurrentMember> { | |||
| 139 | } | 137 | } |
| 140 | } | 138 | } |
| 141 | 139 | ||
| 142 | -/// The signed-in member, after the CSRF check. A missing or wrong `csrf` is `403`, and the check runs | 140 | +/// The signed-in member with the level `need`, after the CSRF check. The level is checked first, so a |
| 143 | -/// before any side effect of the handler. | 141 | +/// viewer gets `403` whatever token they send. A missing or wrong `csrf` is `403`. Both run before any |
| 144 | -pub async fn require_csrf(cx: &Cx, submitted: &str) -> Result<CurrentMember> { | 142 | +/// side effect of the handler. |
| 145 | - let me = require_member(cx).await?; | 143 | +pub async fn require_csrf(cx: &Cx, need: Need, submitted: &str) -> Result<CurrentMember> { |
| 144 | + let me = require_role(cx, need).await?; | ||
| 146 | if me.csrf_matches(submitted) { | 145 | if me.csrf_matches(submitted) { |
| 147 | Ok(me) | 146 | Ok(me) |
| 148 | } else { | 147 | } else { |
| @@ -219,6 +218,11 @@ pub fn user_agent(cx: &Cx) -> Option<String> { | |||
| 219 | .map(|value| value.chars().take(MAX_USER_AGENT_LEN).collect()) | 218 | .map(|value| value.chars().take(MAX_USER_AGENT_LEN).collect()) |
| 220 | } | 219 | } |
| 221 | 220 | ||
| 221 | +/// The raw query string of the request, without the `?`. `None` when the request has none. | ||
| 222 | +pub fn uri_query(cx: &Cx) -> Option<String> { | ||
| 223 | + uri(cx).query().map(str::to_owned) | ||
| 224 | +} | ||
| 225 | + | ||
| 222 | /// One query parameter of the request, decoded. `None` when it is absent. | 226 | /// One query parameter of the request, decoded. `None` when it is absent. |
| 223 | pub fn query_param(cx: &Cx, name: &str) -> Option<String> { | 227 | pub fn query_param(cx: &Cx, name: &str) -> Option<String> { |
| 224 | let mut url = Url::parse("http://iz.invalid/").ok()?; | 228 | let mut url = Url::parse("http://iz.invalid/").ok()?; |
| @@ -247,7 +251,7 @@ fn is_local_path(path: &str) -> bool { | |||
| 247 | } | 251 | } |
| 248 | 252 | ||
| 249 | /// Percent-encodes everything except unreserved characters and `/`, for a `next` value in a URL. | 253 | /// Percent-encodes everything except unreserved characters and `/`, for a `next` value in a URL. |
| 250 | -fn percent_encode(input: &str) -> String { | 254 | +pub fn percent_encode(input: &str) -> String { |
| 251 | let mut out = String::with_capacity(input.len()); | 255 | let mut out = String::with_capacity(input.len()); |
| 252 | for b in input.bytes() { | 256 | for b in input.bytes() { |
| 253 | match b { | 257 | match b { |
crates/iz-web/src/boot.rsmodified+4 -0
| @@ -27,6 +27,8 @@ use crate::state::AppState; | |||
| 27 | 27 | ||
| 28 | /// Name of the instance key file inside the data directory. | 28 | /// Name of the instance key file inside the data directory. |
| 29 | const KEY_FILE: &str = "iz.key"; | 29 | const KEY_FILE: &str = "iz.key"; |
| 30 | +/// The prefix of task keys (`IZ-42`) until the setting that changes it exists. Two to six capitals. | ||
| 31 | +const DEFAULT_KEY_PREFIX: &str = "IZ"; | ||
| 30 | 32 | ||
| 31 | /// Runs the server until a stop signal arrives. Returns once every connection has finished. | 33 | /// Runs the server until a stop signal arrives. Returns once every connection has finished. |
| 32 | pub async fn serve(config_path: &Path) -> iz_core::Result<()> { | 34 | pub async fn serve(config_path: &Path) -> iz_core::Result<()> { |
| @@ -79,6 +81,8 @@ async fn open_state(config: Config) -> iz_core::Result<AppState> { | |||
| 79 | } | 81 | } |
| 80 | let key = secret::load_or_create_key(&data_dir.join(KEY_FILE))?; | 82 | let key = secret::load_or_create_key(&data_dir.join(KEY_FILE))?; |
| 81 | let store = Store::open(&config.database).await?; | 83 | let store = Store::open(&config.database).await?; |
| 84 | + // The one board of this installation, with its columns and default project, made on first boot. | ||
| 85 | + store.ensure_board(DEFAULT_KEY_PREFIX).await?; | ||
| 82 | let oidc = match &config.oidc { | 86 | let oidc = match &config.oidc { |
| 83 | Some(oidc_config) => { | 87 | Some(oidc_config) => { |
| 84 | let secret = oidc::read_client_secret(&oidc_config.client_secret_file)?; | 88 | let secret = oidc::read_client_secret(&oidc_config.client_secret_file)?; |
crates/iz-web/src/directory.rsmodified+38 -10
| @@ -16,8 +16,8 @@ use std::time::Duration; | |||
| 16 | 16 | ||
| 17 | use futures_util::StreamExt; | 17 | use futures_util::StreamExt; |
| 18 | use iz_core::authz::Role; | 18 | use iz_core::authz::Role; |
| 19 | -use iz_core::store::members::DirectoryMember; | ||
| 20 | use iz_core::store::Store; | 19 | use iz_core::store::Store; |
| 20 | +use iz_core::store::members::DirectoryMember; | ||
| 21 | use serde_json::Value; | 21 | use serde_json::Value; |
| 22 | use tokio::sync::watch; | 22 | use tokio::sync::watch; |
| 23 | 23 | ||
| @@ -142,9 +142,13 @@ async fn mirror_once( | |||
| 142 | async fn full_read(state: &AppState, oidc: &OidcClient) -> std::result::Result<(), MirrorError> { | 142 | async fn full_read(state: &AppState, oidc: &OidcClient) -> std::result::Result<(), MirrorError> { |
| 143 | let token = oidc.service_token().await?; | 143 | let token = oidc.service_token().await?; |
| 144 | let url = format!("{}/api/v1/directory", oidc.issuer()); | 144 | let url = format!("{}/api/v1/directory", oidc.issuer()); |
| 145 | - let response = oidc.http().get(url).bearer_auth(token).send().await.map_err(|e| { | 145 | + let response = oidc |
| 146 | - ImError::Unavailable(e.to_string()) | 146 | + .http() |
| 147 | - })?; | 147 | + .get(url) |
| 148 | + .bearer_auth(token) | ||
| 149 | + .send() | ||
| 150 | + .await | ||
| 151 | + .map_err(|e| ImError::Unavailable(e.to_string()))?; | ||
| 148 | if !response.status().is_success() { | 152 | if !response.status().is_success() { |
| 149 | return Err(ImError::BadResponse(format!( | 153 | return Err(ImError::BadResponse(format!( |
| 150 | "the directory answered {}", | 154 | "the directory answered {}", |
| @@ -170,7 +174,10 @@ async fn full_read(state: &AppState, oidc: &OidcClient) -> std::result::Result<( | |||
| 170 | state.store.delete_sessions_by_sub(&local.sub).await?; | 174 | state.store.delete_sessions_by_sub(&local.sub).await?; |
| 171 | } | 175 | } |
| 172 | } | 176 | } |
| 173 | - state.store.set_setting(CURSOR_SETTING, &roster.cursor).await?; | 177 | + state |
| 178 | + .store | ||
| 179 | + .set_setting(CURSOR_SETTING, &roster.cursor) | ||
| 180 | + .await?; | ||
| 174 | Ok(()) | 181 | Ok(()) |
| 175 | } | 182 | } |
| 176 | 183 | ||
| @@ -227,12 +234,17 @@ async fn stream( | |||
| 227 | }; | 234 | }; |
| 228 | for event in parser.feed(&chunk).map_err(ImError::BadResponse)? { | 235 | for event in parser.feed(&chunk).map_err(ImError::BadResponse)? { |
| 229 | match event.name.as_str() { | 236 | match event.name.as_str() { |
| 230 | - "member" => match serde_json::from_str::<Value>(&event.data).ok().and_then(parse_member) { | 237 | + "member" => match serde_json::from_str::<Value>(&event.data) |
| 238 | + .ok() | ||
| 239 | + .and_then(parse_member) | ||
| 240 | + { | ||
| 231 | Some(member) => { | 241 | Some(member) => { |
| 232 | let default_role = default_role(&state.store).await?; | 242 | let default_role = default_role(&state.store).await?; |
| 233 | apply(state, &member, default_role).await?; | 243 | apply(state, &member, default_role).await?; |
| 234 | } | 244 | } |
| 235 | - None => tracing::warn!("directory: skipping a member event that does not parse"), | 245 | + None => { |
| 246 | + tracing::warn!("directory: skipping a member event that does not parse") | ||
| 247 | + } | ||
| 236 | }, | 248 | }, |
| 237 | "deleted" => match serde_json::from_str::<Value>(&event.data) | 249 | "deleted" => match serde_json::from_str::<Value>(&event.data) |
| 238 | .ok() | 250 | .ok() |
| @@ -261,7 +273,11 @@ async fn apply( | |||
| 261 | member: &DirectoryMember, | 273 | member: &DirectoryMember, |
| 262 | default_role: Role, | 274 | default_role: Role, |
| 263 | ) -> std::result::Result<(), MirrorError> { | 275 | ) -> std::result::Result<(), MirrorError> { |
| 264 | - match state.store.apply_directory_member(member, default_role).await { | 276 | + match state |
| 277 | + .store | ||
| 278 | + .apply_directory_member(member, default_role) | ||
| 279 | + .await | ||
| 280 | + { | ||
| 265 | Ok(stored) => { | 281 | Ok(stored) => { |
| 266 | if stored.disabled { | 282 | if stored.disabled { |
| 267 | state.store.delete_sessions_by_sub(&stored.sub).await?; | 283 | state.store.delete_sessions_by_sub(&stored.sub).await?; |
| @@ -432,7 +448,14 @@ pub async fn fetch_photo(oidc: &OidcClient, sub: &str) -> ImResult<Option<(Strin | |||
| 432 | .headers() | 448 | .headers() |
| 433 | .get(reqwest::header::CONTENT_TYPE) | 449 | .get(reqwest::header::CONTENT_TYPE) |
| 434 | .and_then(|value| value.to_str().ok()) | 450 | .and_then(|value| value.to_str().ok()) |
| 435 | - .map(|value| value.split(';').next().unwrap_or_default().trim().to_ascii_lowercase()) | 451 | + .map(|value| { |
| 452 | + value | ||
| 453 | + .split(';') | ||
| 454 | + .next() | ||
| 455 | + .unwrap_or_default() | ||
| 456 | + .trim() | ||
| 457 | + .to_ascii_lowercase() | ||
| 458 | + }) | ||
| 436 | .unwrap_or_default(); | 459 | .unwrap_or_default(); |
| 437 | if !PHOTO_TYPES.contains(&mime.as_str()) { | 460 | if !PHOTO_TYPES.contains(&mime.as_str()) { |
| 438 | return Ok(None); | 461 | return Ok(None); |
| @@ -448,7 +471,12 @@ mod tests { | |||
| 448 | #[test] | 471 | #[test] |
| 449 | fn sse_events_split_across_chunks_and_resume_ids() { | 472 | fn sse_events_split_across_chunks_and_resume_ids() { |
| 450 | let mut parser = SseParser::default(); | 473 | let mut parser = SseParser::default(); |
| 451 | - assert!(parser.feed(b": keep-alive\n\nevent: mem").unwrap().is_empty()); | 474 | + assert!( |
| 475 | + parser | ||
| 476 | + .feed(b": keep-alive\n\nevent: mem") | ||
| 477 | + .unwrap() | ||
| 478 | + .is_empty() | ||
| 479 | + ); | ||
| 452 | let events = parser | 480 | let events = parser |
| 453 | .feed(b"ber\nid: 01CURSOR\ndata: {\"sub\":\"a\"}\ndata: more\r\n\r\n") | 481 | .feed(b"ber\nid: 01CURSOR\ndata: {\"sub\":\"a\"}\ndata: more\r\n\r\n") |
| 454 | .unwrap(); | 482 | .unwrap(); |
crates/iz-web/src/i18n/board.rsadded+256 -0
| @@ -0,0 +1,256 @@ | |||
| 1 | +//! Strings of the board page: the cards, the filters, the new-task form, the notices, and the messages | ||
| 2 | +//! for every refused write. The seeded column names are translated for display only; a column the | ||
| 3 | +//! admin named passes through unchanged (`docs/reference/old-inventory.md` 2.2). | ||
| 4 | + | ||
| 5 | +use super::Lang; | ||
| 6 | + | ||
| 7 | +/// One variant per phrase of the board. Add a variant, then its English and Turkish texts in [`t`]. | ||
| 8 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
| 9 | +pub enum K { | ||
| 10 | + /// The heading of the board page. | ||
| 11 | + BoardTitle, | ||
| 12 | + /// The button that opens the new-task form. | ||
| 13 | + NewTask, | ||
| 14 | + /// The heading of the new-task form. | ||
| 15 | + NewTaskHeading, | ||
| 16 | + /// The label of the title field. | ||
| 17 | + FieldTitle, | ||
| 18 | + /// The label of the column field of the new-task form. | ||
| 19 | + FieldColumn, | ||
| 20 | + /// The label of a project (tag) field. | ||
| 21 | + FieldProject, | ||
| 22 | + /// The label of the description field. | ||
| 23 | + FieldDescription, | ||
| 24 | + /// The label of the deadline field. | ||
| 25 | + FieldDeadline, | ||
| 26 | + /// The hint under the deadline field: the format it takes. | ||
| 27 | + DeadlineHint, | ||
| 28 | + /// The submit button of the new-task form. | ||
| 29 | + CreateTask, | ||
| 30 | + /// The link that closes the new-task form. | ||
| 31 | + Cancel, | ||
| 32 | + /// The label of the project filter. | ||
| 33 | + FilterProject, | ||
| 34 | + /// The first entry of the project filter: no filter. | ||
| 35 | + FilterAllProjects, | ||
| 36 | + /// The label of the assignee filter. | ||
| 37 | + FilterAssignee, | ||
| 38 | + /// The first entry of the assignee filter: no filter. | ||
| 39 | + FilterAnyone, | ||
| 40 | + /// The entry of the assignee filter for cards with nobody assigned. | ||
| 41 | + FilterNobody, | ||
| 42 | + /// The label of the sort order. | ||
| 43 | + FilterSort, | ||
| 44 | + /// The sort order by deadline (the default). | ||
| 45 | + SortDeadline, | ||
| 46 | + /// The sort order newest first. | ||
| 47 | + SortCreated, | ||
| 48 | + /// The sort order by title. | ||
| 49 | + SortTitle, | ||
| 50 | + /// The label of the search box. | ||
| 51 | + FilterSearch, | ||
| 52 | + /// The placeholder of the search box. | ||
| 53 | + SearchHint, | ||
| 54 | + /// The button that applies the filters. | ||
| 55 | + Apply, | ||
| 56 | + /// The link that removes every filter. | ||
| 57 | + ClearFilters, | ||
| 58 | + /// The text of a column with no cards. | ||
| 59 | + NoTasks, | ||
| 60 | + /// The text when the filters hide every card. | ||
| 61 | + NoMatches, | ||
| 62 | + /// The chip of a card whose deadline has passed. | ||
| 63 | + Overdue, | ||
| 64 | + /// The chip of a card waiting for an unfinished task. | ||
| 65 | + Blocked, | ||
| 66 | + /// The label before a card's deadline. | ||
| 67 | + Due, | ||
| 68 | + /// The label of the target column of the keyboard move. | ||
| 69 | + MoveTo, | ||
| 70 | + /// The button that moves a card with the keyboard form. | ||
| 71 | + Move, | ||
| 72 | + /// The button that deletes a card. | ||
| 73 | + Delete, | ||
| 74 | + /// The sentence that tells a viewer the board cannot be changed. | ||
| 75 | + ReadOnly, | ||
| 76 | + /// The sentence that tells a member cards can be dragged. | ||
| 77 | + DragHint, | ||
| 78 | + /// The notice after a task was created. | ||
| 79 | + NoticeCreated, | ||
| 80 | + /// The notice after a task was deleted. | ||
| 81 | + NoticeDeleted, | ||
| 82 | + /// Refused: the card is no longer in the column the page showed. | ||
| 83 | + MovedAlready, | ||
| 84 | + /// Refused: the card still has open subtasks, so it cannot enter Done. | ||
| 85 | + SubtasksOpen, | ||
| 86 | + /// Refused: the title is empty or longer than the limit. | ||
| 87 | + TitleInvalid, | ||
| 88 | + /// Refused: the description is longer than the limit. | ||
| 89 | + DescriptionTooLong, | ||
| 90 | + /// Refused: the deadline is not a day in the form `YYYY-MM-DD`. | ||
| 91 | + DeadlineInvalid, | ||
| 92 | + /// Refused: the column is not a column of this board. | ||
| 93 | + ColumnUnknown, | ||
| 94 | + /// Refused: the project is not a project of this board. | ||
| 95 | + ProjectUnknown, | ||
| 96 | + /// Refused: the task does not exist (or is deleted, or is on another board). | ||
| 97 | + TaskNotFound, | ||
| 98 | + /// Refused: the account may not change the board. | ||
| 99 | + Forbidden, | ||
| 100 | + /// Refused: some other field is not acceptable. | ||
| 101 | + InvalidForm, | ||
| 102 | + /// A drag could not reach the server. Shown in the toast. | ||
| 103 | + MoveFailed, | ||
| 104 | + /// The seeded column "Backlog". | ||
| 105 | + ColumnBacklog, | ||
| 106 | + /// The seeded column "In Progress". | ||
| 107 | + ColumnInProgress, | ||
| 108 | + /// The seeded column "Review". | ||
| 109 | + ColumnReview, | ||
| 110 | + /// The seeded column "Done". | ||
| 111 | + ColumnDone, | ||
| 112 | +} | ||
| 113 | + | ||
| 114 | +/// The text of `key` in `lang`. | ||
| 115 | +pub fn t(lang: Lang, key: K) -> &'static str { | ||
| 116 | + match (key, lang) { | ||
| 117 | + (K::BoardTitle, Lang::En) => "Board", | ||
| 118 | + (K::BoardTitle, Lang::Tr) => "Pano", | ||
| 119 | + (K::NewTask, Lang::En) => "New task", | ||
| 120 | + (K::NewTask, Lang::Tr) => "Yeni görev", | ||
| 121 | + (K::NewTaskHeading, Lang::En) => "New task", | ||
| 122 | + (K::NewTaskHeading, Lang::Tr) => "Yeni görev", | ||
| 123 | + (K::FieldTitle, Lang::En) => "Title", | ||
| 124 | + (K::FieldTitle, Lang::Tr) => "Başlık", | ||
| 125 | + (K::FieldColumn, Lang::En) => "Column", | ||
| 126 | + (K::FieldColumn, Lang::Tr) => "Sütun", | ||
| 127 | + (K::FieldProject, Lang::En) => "Project", | ||
| 128 | + (K::FieldProject, Lang::Tr) => "Proje", | ||
| 129 | + (K::FieldDescription, Lang::En) => "Description", | ||
| 130 | + (K::FieldDescription, Lang::Tr) => "Açıklama", | ||
| 131 | + (K::FieldDeadline, Lang::En) => "Deadline", | ||
| 132 | + (K::FieldDeadline, Lang::Tr) => "Son tarih", | ||
| 133 | + (K::DeadlineHint, Lang::En) => "A day, as YYYY-MM-DD", | ||
| 134 | + (K::DeadlineHint, Lang::Tr) => "Bir gün, YYYY-AA-GG biçiminde", | ||
| 135 | + (K::CreateTask, Lang::En) => "Create task", | ||
| 136 | + (K::CreateTask, Lang::Tr) => "Görevi oluştur", | ||
| 137 | + (K::Cancel, Lang::En) => "Cancel", | ||
| 138 | + (K::Cancel, Lang::Tr) => "Vazgeç", | ||
| 139 | + (K::FilterProject, Lang::En) => "Project", | ||
| 140 | + (K::FilterProject, Lang::Tr) => "Proje", | ||
| 141 | + (K::FilterAllProjects, Lang::En) => "All projects", | ||
| 142 | + (K::FilterAllProjects, Lang::Tr) => "Tüm projeler", | ||
| 143 | + (K::FilterAssignee, Lang::En) => "Assignee", | ||
| 144 | + (K::FilterAssignee, Lang::Tr) => "Atanan", | ||
| 145 | + (K::FilterAnyone, Lang::En) => "Anyone", | ||
| 146 | + (K::FilterAnyone, Lang::Tr) => "Herkes", | ||
| 147 | + (K::FilterNobody, Lang::En) => "Nobody", | ||
| 148 | + (K::FilterNobody, Lang::Tr) => "Kimse", | ||
| 149 | + (K::FilterSort, Lang::En) => "Sort", | ||
| 150 | + (K::FilterSort, Lang::Tr) => "Sırala", | ||
| 151 | + (K::SortDeadline, Lang::En) => "Deadline", | ||
| 152 | + (K::SortDeadline, Lang::Tr) => "Son tarih", | ||
| 153 | + (K::SortCreated, Lang::En) => "Newest first", | ||
| 154 | + (K::SortCreated, Lang::Tr) => "En yeni", | ||
| 155 | + (K::SortTitle, Lang::En) => "Title", | ||
| 156 | + (K::SortTitle, Lang::Tr) => "Başlık", | ||
| 157 | + (K::FilterSearch, Lang::En) => "Search", | ||
| 158 | + (K::FilterSearch, Lang::Tr) => "Ara", | ||
| 159 | + (K::SearchHint, Lang::En) => "Key or title", | ||
| 160 | + (K::SearchHint, Lang::Tr) => "Anahtar veya başlık", | ||
| 161 | + (K::Apply, Lang::En) => "Apply", | ||
| 162 | + (K::Apply, Lang::Tr) => "Uygula", | ||
| 163 | + (K::ClearFilters, Lang::En) => "Clear filters", | ||
| 164 | + (K::ClearFilters, Lang::Tr) => "Filtreleri temizle", | ||
| 165 | + (K::NoTasks, Lang::En) => "No tasks", | ||
| 166 | + (K::NoTasks, Lang::Tr) => "Görev yok", | ||
| 167 | + (K::NoMatches, Lang::En) => "No task matches the filters.", | ||
| 168 | + (K::NoMatches, Lang::Tr) => "Filtrelere uyan görev yok.", | ||
| 169 | + (K::Overdue, Lang::En) => "Overdue", | ||
| 170 | + (K::Overdue, Lang::Tr) => "Gecikmiş", | ||
| 171 | + (K::Blocked, Lang::En) => "Blocked", | ||
| 172 | + (K::Blocked, Lang::Tr) => "Engelli", | ||
| 173 | + (K::Due, Lang::En) => "Due", | ||
| 174 | + (K::Due, Lang::Tr) => "Son", | ||
| 175 | + (K::MoveTo, Lang::En) => "Move to", | ||
| 176 | + (K::MoveTo, Lang::Tr) => "Taşı", | ||
| 177 | + (K::Move, Lang::En) => "Move", | ||
| 178 | + (K::Move, Lang::Tr) => "Taşı", | ||
| 179 | + (K::Delete, Lang::En) => "Delete", | ||
| 180 | + (K::Delete, Lang::Tr) => "Sil", | ||
| 181 | + (K::ReadOnly, Lang::En) => "You can read the board. A member can change it.", | ||
| 182 | + (K::ReadOnly, Lang::Tr) => "Panoyu görebilirsiniz. Değişiklikleri bir üye yapabilir.", | ||
| 183 | + (K::DragHint, Lang::En) => "Drag a card to another column to move it.", | ||
| 184 | + (K::DragHint, Lang::Tr) => "Bir kartı başka bir sütuna sürükleyerek taşıyın.", | ||
| 185 | + (K::NoticeCreated, Lang::En) => "The task was created.", | ||
| 186 | + (K::NoticeCreated, Lang::Tr) => "Görev oluşturuldu.", | ||
| 187 | + (K::NoticeDeleted, Lang::En) => "The task was deleted.", | ||
| 188 | + (K::NoticeDeleted, Lang::Tr) => "Görev silindi.", | ||
| 189 | + (K::MovedAlready, Lang::En) => { | ||
| 190 | + "Someone else moved this card. The board shows where it is now." | ||
| 191 | + } | ||
| 192 | + (K::MovedAlready, Lang::Tr) => { | ||
| 193 | + "Bu kartı başka biri taşıdı. Pano kartın şu anki yerini gösteriyor." | ||
| 194 | + } | ||
| 195 | + (K::SubtasksOpen, Lang::En) => "Finish the open subtasks before moving this card to Done.", | ||
| 196 | + (K::SubtasksOpen, Lang::Tr) => { | ||
| 197 | + "Bu kartı Tamamlandı sütununa taşımadan önce açık alt görevleri bitirin." | ||
| 198 | + } | ||
| 199 | + (K::TitleInvalid, Lang::En) => "Enter a title of up to 200 characters.", | ||
| 200 | + (K::TitleInvalid, Lang::Tr) => "En fazla 200 karakterlik bir başlık girin.", | ||
| 201 | + (K::DescriptionTooLong, Lang::En) => "The description is longer than 20 000 characters.", | ||
| 202 | + (K::DescriptionTooLong, Lang::Tr) => "Açıklama 20 000 karakterden uzun.", | ||
| 203 | + (K::DeadlineInvalid, Lang::En) => "Use a deadline day such as 2026-10-28.", | ||
| 204 | + (K::DeadlineInvalid, Lang::Tr) => "Son tarih için 2026-10-28 gibi bir gün yazın.", | ||
| 205 | + (K::ColumnUnknown, Lang::En) => "That column does not exist on this board.", | ||
| 206 | + (K::ColumnUnknown, Lang::Tr) => "Bu pano üzerinde böyle bir sütun yok.", | ||
| 207 | + (K::ProjectUnknown, Lang::En) => "That project does not exist on this board.", | ||
| 208 | + (K::ProjectUnknown, Lang::Tr) => "Bu pano üzerinde böyle bir proje yok.", | ||
| 209 | + (K::TaskNotFound, Lang::En) => "That task does not exist any more.", | ||
| 210 | + (K::TaskNotFound, Lang::Tr) => "Bu görev artık yok.", | ||
| 211 | + (K::Forbidden, Lang::En) => "Your account cannot change the board.", | ||
| 212 | + (K::Forbidden, Lang::Tr) => "Hesabınız panoda değişiklik yapamaz.", | ||
| 213 | + (K::InvalidForm, Lang::En) => "Check the form and try again.", | ||
| 214 | + (K::InvalidForm, Lang::Tr) => "Formu kontrol edip yeniden deneyin.", | ||
| 215 | + (K::MoveFailed, Lang::En) => "The card could not be moved. Try again.", | ||
| 216 | + (K::MoveFailed, Lang::Tr) => "Kart taşınamadı. Yeniden deneyin.", | ||
| 217 | + (K::ColumnBacklog, Lang::En) => "Backlog", | ||
| 218 | + (K::ColumnBacklog, Lang::Tr) => "Yapılacak", | ||
| 219 | + (K::ColumnInProgress, Lang::En) => "In Progress", | ||
| 220 | + (K::ColumnInProgress, Lang::Tr) => "Devam ediyor", | ||
| 221 | + (K::ColumnReview, Lang::En) => "Review", | ||
| 222 | + (K::ColumnReview, Lang::Tr) => "İnceleme", | ||
| 223 | + (K::ColumnDone, Lang::En) => "Done", | ||
| 224 | + (K::ColumnDone, Lang::Tr) => "Tamamlandı", | ||
| 225 | + } | ||
| 226 | +} | ||
| 227 | + | ||
| 228 | +/// The name of a column for display. The four seeded names are translated; any other name is shown as | ||
| 229 | +/// the admin wrote it. | ||
| 230 | +pub fn column_title(lang: Lang, name: &str) -> String { | ||
| 231 | + let key = match name { | ||
| 232 | + "Backlog" => K::ColumnBacklog, | ||
| 233 | + "In Progress" => K::ColumnInProgress, | ||
| 234 | + "Review" => K::ColumnReview, | ||
| 235 | + "Done" => K::ColumnDone, | ||
| 236 | + other => return other.to_owned(), | ||
| 237 | + }; | ||
| 238 | + t(lang, key).to_owned() | ||
| 239 | +} | ||
| 240 | + | ||
| 241 | +/// The subtask count of a card, as `done/total` with the word for subtasks. | ||
| 242 | +pub fn subtasks(lang: Lang, done: i64, total: i64) -> String { | ||
| 243 | + match lang { | ||
| 244 | + Lang::En => format!("{done}/{total} subtasks"), | ||
| 245 | + Lang::Tr => format!("{done}/{total} alt görev"), | ||
| 246 | + } | ||
| 247 | +} | ||
| 248 | + | ||
| 249 | +/// The notice after a write, by the name the redirect carries. `None` for an unknown name. | ||
| 250 | +pub fn notice(lang: Lang, name: &str) -> Option<&'static str> { | ||
| 251 | + match name { | ||
| 252 | + "created" => Some(t(lang, K::NoticeCreated)), | ||
| 253 | + "deleted" => Some(t(lang, K::NoticeDeleted)), | ||
| 254 | + _ => None, | ||
| 255 | + } | ||
| 256 | +} | ||
crates/iz-web/src/i18n/mod.rsmodified+1 -0
| @@ -7,6 +7,7 @@ | |||
| 7 | //! This module decides the language. It does not format sentences with values; those get small | 7 | //! This module decides the language. It does not format sentences with values; those get small |
| 8 | //! helper functions next to their keys. | 8 | //! helper functions next to their keys. |
| 9 | 9 | ||
| 10 | +pub mod board; | ||
| 10 | pub mod shell; | 11 | pub mod shell; |
| 11 | 12 | ||
| 12 | use topcoat::context::Cx; | 13 | use topcoat::context::Cx; |
crates/iz-web/src/i18n/shell.rsmodified+0 -12
| @@ -12,8 +12,6 @@ pub enum K { | |||
| 12 | BackHome, | 12 | BackHome, |
| 13 | /// The sentence under the 404 title. | 13 | /// The sentence under the 404 title. |
| 14 | NotFoundBody, | 14 | NotFoundBody, |
| 15 | - /// The sentence on the start page for a signed-in member, before the board exists. | ||
| 16 | - BoardComesNext, | ||
| 17 | /// The title of the page that says a sign-in did not finish. | 15 | /// The title of the page that says a sign-in did not finish. |
| 18 | SignInFailedTitle, | 16 | SignInFailedTitle, |
| 19 | /// The sentence under that title. | 17 | /// The sentence under that title. |
| @@ -50,8 +48,6 @@ pub fn t(lang: Lang, key: K) -> &'static str { | |||
| 50 | (K::Admin, Lang::En) => "Admin", | 48 | (K::Admin, Lang::En) => "Admin", |
| 51 | (K::Admin, Lang::Tr) => "Yönetici", | 49 | (K::Admin, Lang::Tr) => "Yönetici", |
| 52 | (K::BackHome, Lang::En) => "Back to the start", | 50 | (K::BackHome, Lang::En) => "Back to the start", |
| 53 | - (K::BoardComesNext, Lang::En) => "The board comes next. There is nothing to show yet.", | ||
| 54 | - (K::BoardComesNext, Lang::Tr) => "Pano sırada. Henüz gösterilecek bir şey yok.", | ||
| 55 | (K::SignIn, Lang::En) => "Sign in", | 51 | (K::SignIn, Lang::En) => "Sign in", |
| 56 | (K::SignIn, Lang::Tr) => "Oturum aç", | 52 | (K::SignIn, Lang::Tr) => "Oturum aç", |
| 57 | (K::SignOut, Lang::En) => "Sign out", | 53 | (K::SignOut, Lang::En) => "Sign out", |
| @@ -97,11 +93,3 @@ pub fn t(lang: Lang, key: K) -> &'static str { | |||
| 97 | (K::SkipToContent, Lang::Tr) => "İçeriğe geç", | 93 | (K::SkipToContent, Lang::Tr) => "İçeriğe geç", |
| 98 | } | 94 | } |
| 99 | } | 95 | } |
| 100 | - | ||
| 101 | -/// The greeting of a signed-in member, with their name. | ||
| 102 | -pub fn greeting(lang: Lang, name: &str) -> String { | ||
| 103 | - match lang { | ||
| 104 | - Lang::En => format!("Hello, {name}"), | ||
| 105 | - Lang::Tr => format!("Merhaba, {name}"), | ||
| 106 | - } | ||
| 107 | -} | ||
crates/iz-web/src/main.rsmodified+0 -2
| @@ -5,8 +5,6 @@ | |||
| 5 | //! then `IZ_CONFIG`, then `config/iz.toml`. Exit status 0 is success, 1 a failure, 2 a usage error. | 5 | //! then `IZ_CONFIG`, then `config/iz.toml`. Exit status 0 is success, 1 a failure, 2 a usage error. |
| 6 | 6 | ||
| 7 | mod assets; | 7 | mod assets; |
| 8 | -// The board pages that come next call these helpers; until then they have no caller. | ||
| 9 | -#[allow(dead_code)] | ||
| 10 | mod auth; | 8 | mod auth; |
| 11 | mod boot; | 9 | mod boot; |
| 12 | mod directory; | 10 | mod directory; |
crates/iz-web/src/oidc.rsmodified+35 -12
| @@ -225,7 +225,11 @@ struct KeyCache { | |||
| 225 | impl OidcClient { | 225 | impl OidcClient { |
| 226 | /// Builds the client. `base_url` is the public origin of iz, from which the callback and the | 226 | /// Builds the client. `base_url` is the public origin of iz, from which the callback and the |
| 227 | /// post-logout URIs are derived; `im` has these registered for the client. | 227 | /// post-logout URIs are derived; `im` has these registered for the client. |
| 228 | - pub fn new(config: &OidcConfig, base_url: &str, client_secret: String) -> iz_core::Result<Self> { | 228 | + pub fn new( |
| 229 | + config: &OidcConfig, | ||
| 230 | + base_url: &str, | ||
| 231 | + client_secret: String, | ||
| 232 | + ) -> iz_core::Result<Self> { | ||
| 229 | // Redirects are never followed: a token call that is redirected would send the client | 233 | // Redirects are never followed: a token call that is redirected would send the client |
| 230 | // secret to another host. | 234 | // secret to another host. |
| 231 | let http = reqwest::Client::builder() | 235 | let http = reqwest::Client::builder() |
| @@ -343,9 +347,9 @@ impl OidcClient { | |||
| 343 | Err(ImError::UnknownKey) => { | 347 | Err(ImError::UnknownKey) => { |
| 344 | let keys = self.key_set(true).await?; | 348 | let keys = self.key_set(true).await?; |
| 345 | match check(&keys) { | 349 | match check(&keys) { |
| 346 | - Err(ImError::UnknownKey) => Err(ImError::Rejected( | 350 | + Err(ImError::UnknownKey) => { |
| 347 | - "the signing key is not published".into(), | 351 | + Err(ImError::Rejected("the signing key is not published".into())) |
| 348 | - )), | 352 | + } |
| 349 | other => other, | 353 | other => other, |
| 350 | } | 354 | } |
| 351 | } | 355 | } |
| @@ -354,7 +358,12 @@ impl OidcClient { | |||
| 354 | } | 358 | } |
| 355 | 359 | ||
| 356 | /// The authorization URL for a sign-in, with PKCE (S256) and the state and nonce of this flight. | 360 | /// The authorization URL for a sign-in, with PKCE (S256) and the state and nonce of this flight. |
| 357 | - pub async fn authorize_url(&self, state: &str, nonce: &str, challenge: &str) -> ImResult<String> { | 361 | + pub async fn authorize_url( |
| 362 | + &self, | ||
| 363 | + state: &str, | ||
| 364 | + nonce: &str, | ||
| 365 | + challenge: &str, | ||
| 366 | + ) -> ImResult<String> { | ||
| 358 | let discovery = self.discovery().await?; | 367 | let discovery = self.discovery().await?; |
| 359 | let mut url = reqwest::Url::parse(&discovery.authorization_endpoint) | 368 | let mut url = reqwest::Url::parse(&discovery.authorization_endpoint) |
| 360 | .map_err(|e| ImError::BadResponse(format!("authorization endpoint: {e}")))?; | 369 | .map_err(|e| ImError::BadResponse(format!("authorization endpoint: {e}")))?; |
| @@ -372,7 +381,11 @@ impl OidcClient { | |||
| 372 | 381 | ||
| 373 | /// The end-session URL of RP-initiated logout (contracts.md 2.5). `id_token_hint` is omitted when | 382 | /// The end-session URL of RP-initiated logout (contracts.md 2.5). `id_token_hint` is omitted when |
| 374 | /// the session has no stored ID token. | 383 | /// the session has no stored ID token. |
| 375 | - pub async fn end_session_url(&self, id_token_hint: Option<&str>, state: &str) -> ImResult<String> { | 384 | + pub async fn end_session_url( |
| 385 | + &self, | ||
| 386 | + id_token_hint: Option<&str>, | ||
| 387 | + state: &str, | ||
| 388 | + ) -> ImResult<String> { | ||
| 376 | let discovery = self.discovery().await?; | 389 | let discovery = self.discovery().await?; |
| 377 | let endpoint = discovery | 390 | let endpoint = discovery |
| 378 | .end_session_endpoint | 391 | .end_session_endpoint |
| @@ -456,8 +469,10 @@ impl OidcClient { | |||
| 456 | /// Verifies an ID token against the current keys, and the nonce of the flight. | 469 | /// Verifies an ID token against the current keys, and the nonce of the flight. |
| 457 | pub async fn verify_id_token(&self, token: &str, nonce: &str) -> ImResult<IdClaims> { | 470 | pub async fn verify_id_token(&self, token: &str, nonce: &str) -> ImResult<IdClaims> { |
| 458 | let now = unix_now(); | 471 | let now = unix_now(); |
| 459 | - self.with_keys(|keys| verify_id_token(keys, &self.issuer, &self.client_id, token, nonce, now)) | 472 | + self.with_keys(|keys| { |
| 460 | - .await | 473 | + verify_id_token(keys, &self.issuer, &self.client_id, token, nonce, now) |
| 474 | + }) | ||
| 475 | + .await | ||
| 461 | } | 476 | } |
| 462 | 477 | ||
| 463 | /// Verifies a back-channel logout token against the current keys. | 478 | /// Verifies a back-channel logout token against the current keys. |
| @@ -494,7 +509,9 @@ pub fn verify_id_token( | |||
| 494 | let sent = str_claim(&claims, "nonce") | 509 | let sent = str_claim(&claims, "nonce") |
| 495 | .ok_or_else(|| ImError::Rejected("the nonce claim is missing".into()))?; | 510 | .ok_or_else(|| ImError::Rejected("the nonce claim is missing".into()))?; |
| 496 | if !constant_time_eq(sent.as_bytes(), nonce.as_bytes()) { | 511 | if !constant_time_eq(sent.as_bytes(), nonce.as_bytes()) { |
| 497 | - return Err(ImError::Rejected("the nonce does not match this sign-in".into())); | 512 | + return Err(ImError::Rejected( |
| 513 | + "the nonce does not match this sign-in".into(), | ||
| 514 | + )); | ||
| 498 | } | 515 | } |
| 499 | let id: IdClaims = serde_json::from_value(Value::Object(claims)) | 516 | let id: IdClaims = serde_json::from_value(Value::Object(claims)) |
| 500 | .map_err(|e| ImError::Rejected(format!("the claims are malformed: {e}")))?; | 517 | .map_err(|e| ImError::Rejected(format!("the claims are malformed: {e}")))?; |
| @@ -517,21 +534,27 @@ pub fn verify_logout_token( | |||
| 517 | let claims = verify_signature(keys, issuer, client_id, token)?; | 534 | let claims = verify_signature(keys, issuer, client_id, token)?; |
| 518 | check_iat(&claims, now)?; | 535 | check_iat(&claims, now)?; |
| 519 | if claims.contains_key("nonce") { | 536 | if claims.contains_key("nonce") { |
| 520 | - return Err(ImError::Rejected("a logout token must not carry a nonce".into())); | 537 | + return Err(ImError::Rejected( |
| 538 | + "a logout token must not carry a nonce".into(), | ||
| 539 | + )); | ||
| 521 | } | 540 | } |
| 522 | let events = claims | 541 | let events = claims |
| 523 | .get("events") | 542 | .get("events") |
| 524 | .and_then(Value::as_object) | 543 | .and_then(Value::as_object) |
| 525 | .ok_or_else(|| ImError::Rejected("the events claim is missing".into()))?; | 544 | .ok_or_else(|| ImError::Rejected("the events claim is missing".into()))?; |
| 526 | if !events.contains_key(BACKCHANNEL_EVENT) { | 545 | if !events.contains_key(BACKCHANNEL_EVENT) { |
| 527 | - return Err(ImError::Rejected("the event is not back-channel logout".into())); | 546 | + return Err(ImError::Rejected( |
| 547 | + "the event is not back-channel logout".into(), | ||
| 548 | + )); | ||
| 528 | } | 549 | } |
| 529 | let jti = str_claim(&claims, "jti") | 550 | let jti = str_claim(&claims, "jti") |
| 530 | .ok_or_else(|| ImError::Rejected("the jti claim is missing".into()))?; | 551 | .ok_or_else(|| ImError::Rejected("the jti claim is missing".into()))?; |
| 531 | let sid = str_claim(&claims, "sid"); | 552 | let sid = str_claim(&claims, "sid"); |
| 532 | let sub = str_claim(&claims, "sub"); | 553 | let sub = str_claim(&claims, "sub"); |
| 533 | if sid.is_none() && sub.is_none() { | 554 | if sid.is_none() && sub.is_none() { |
| 534 | - return Err(ImError::Rejected("the token names neither sid nor sub".into())); | 555 | + return Err(ImError::Rejected( |
| 556 | + "the token names neither sid nor sub".into(), | ||
| 557 | + )); | ||
| 535 | } | 558 | } |
| 536 | Ok(LogoutClaims { jti, sid, sub }) | 559 | Ok(LogoutClaims { jti, sid, sub }) |
| 537 | } | 560 | } |
crates/iz-web/src/pages/backchannel.rsmodified+12 -2
| @@ -51,7 +51,10 @@ struct BackchannelForm { | |||
| 51 | /// | 51 | /// |
| 52 | /// The id is recorded first and atomically (`seen_jti` inserts and reports a repeat), so two copies | 52 | /// The id is recorded first and atomically (`seen_jti` inserts and reports a repeat), so two copies |
| 53 | /// of one token cannot both succeed. | 53 | /// of one token cannot both succeed. |
| 54 | -pub async fn end_sessions(store: &Store, claims: &LogoutClaims) -> std::result::Result<u64, BackchannelError> { | 54 | +pub async fn end_sessions( |
| 55 | + store: &Store, | ||
| 56 | + claims: &LogoutClaims, | ||
| 57 | +) -> std::result::Result<u64, BackchannelError> { | ||
| 55 | if store.seen_jti(&claims.jti, JTI_LIFETIME).await? { | 58 | if store.seen_jti(&claims.jti, JTI_LIFETIME).await? { |
| 56 | return Err(BackchannelError::Replay); | 59 | return Err(BackchannelError::Replay); |
| 57 | } | 60 | } |
| @@ -183,7 +186,14 @@ mod tests { | |||
| 183 | .await | 186 | .await |
| 184 | .expect("member"); | 187 | .expect("member"); |
| 185 | store | 188 | store |
| 186 | - .create_session(&member.sub, Some("sid-1"), None, Duration::from_secs(3600), None, None) | 189 | + .create_session( |
| 190 | + &member.sub, | ||
| 191 | + Some("sid-1"), | ||
| 192 | + None, | ||
| 193 | + Duration::from_secs(3600), | ||
| 194 | + None, | ||
| 195 | + None, | ||
| 196 | + ) | ||
| 187 | .await | 197 | .await |
| 188 | .expect("session"); | 198 | .expect("session"); |
| 189 | 199 | ||
crates/iz-web/src/pages/board.rsadded+547 -0
| @@ -0,0 +1,547 @@ | |||
| 1 | +//! The board page (`GET /`) and its live stream (`GET /board/live`). | ||
| 2 | +//! | ||
| 3 | +//! The page is the board as one viewer sees it: the live columns in order, their cards with the chips | ||
| 4 | +//! the store computed, the filter bar, and, for a member, the write controls. The filters and the sort | ||
| 5 | +//! are applied by the store (`Store::board_view`), so the page and the search use one rule. A viewer | ||
| 6 | +//! sees no write control. Writes (`pages/tasks.rs`) answer with this page again when they are refused. | ||
| 7 | +//! | ||
| 8 | +//! Anyone without access (no role, or disabled) gets the sign-in card, not a "forbidden" page: the | ||
| 9 | +//! page does not say that the board exists. | ||
| 10 | + | ||
| 11 | +use iz_core::authz::{Action, Role, authorize}; | ||
| 12 | +use iz_core::store::Store; | ||
| 13 | +use iz_core::store::board::{Board, Tag}; | ||
| 14 | +use iz_core::store::members::Member; | ||
| 15 | +use iz_core::store::tasks::{AssigneeFilter, BoardFilter, BoardView, SortBy}; | ||
| 16 | +use iz_core::zones::parse_zone; | ||
| 17 | +use jiff::tz::TimeZone; | ||
| 18 | +use reqwest::Url; | ||
| 19 | +use topcoat::Result; | ||
| 20 | +use topcoat::context::{Cx, app_context}; | ||
| 21 | +use topcoat::router::error::not_found; | ||
| 22 | +use topcoat::router::response::Response; | ||
| 23 | +use topcoat::router::route; | ||
| 24 | +use topcoat::view::view; | ||
| 25 | + | ||
| 26 | +use crate::assets::BOARD_JS_HREF; | ||
| 27 | +use crate::auth::{ | ||
| 28 | + CurrentMember, Need, current_member, percent_encode, query_param, require_role, uri_query, | ||
| 29 | +}; | ||
| 30 | +use crate::i18n::board::K; | ||
| 31 | +use crate::i18n::{Lang, lang}; | ||
| 32 | +use crate::live::{Topic, stream_changes}; | ||
| 33 | +use crate::state::AppState; | ||
| 34 | +use crate::views::board::{board_content, signed_out_card}; | ||
| 35 | +use crate::views::{ViewerInfo, respond, shell}; | ||
| 36 | + | ||
| 37 | +/// Longest search text kept, in characters. Reason: a search is a few words; longer text only costs time. | ||
| 38 | +pub const SEARCH_MAX: usize = 200; | ||
| 39 | + | ||
| 40 | +/// The new-task form as it is shown: the typed values, the choices, and the refusal to show above it. | ||
| 41 | +#[derive(Debug, Clone, Default)] | ||
| 42 | +pub struct NewForm { | ||
| 43 | + /// The title as typed. | ||
| 44 | + pub title: String, | ||
| 45 | + /// The description as typed. | ||
| 46 | + pub description: String, | ||
| 47 | + /// The deadline as typed, `YYYY-MM-DD` or empty. | ||
| 48 | + pub deadline: String, | ||
| 49 | + /// The column id chosen. | ||
| 50 | + pub column: String, | ||
| 51 | + /// The project id chosen. | ||
| 52 | + pub tag: String, | ||
| 53 | + /// The refusal to show above the form, when the last try was refused. | ||
| 54 | + pub error: Option<K>, | ||
| 55 | +} | ||
| 56 | + | ||
| 57 | +/// The filters of the page, as the store reads them and as the form shows them. | ||
| 58 | +#[derive(Debug, Clone, Default)] | ||
| 59 | +pub struct Filters { | ||
| 60 | + /// What the store filters and sorts by. | ||
| 61 | + pub filter: BoardFilter, | ||
| 62 | + /// The project id selected, or empty for all projects. | ||
| 63 | + pub tag: String, | ||
| 64 | + /// `none` for nobody, a member id, or empty for anyone. | ||
| 65 | + pub assignee: String, | ||
| 66 | + /// `deadline` (the default), `created` or `title`. | ||
| 67 | + pub sort: &'static str, | ||
| 68 | + /// The search text, trimmed and at most [`SEARCH_MAX`] characters. | ||
| 69 | + pub query: String, | ||
| 70 | +} | ||
| 71 | + | ||
| 72 | +impl Filters { | ||
| 73 | + /// Whether any filter narrows the board or changes its order. | ||
| 74 | + pub fn active(&self) -> bool { | ||
| 75 | + !self.tag.is_empty() | ||
| 76 | + || !self.assignee.is_empty() | ||
| 77 | + || self.sort != "deadline" | ||
| 78 | + || !self.query.is_empty() | ||
| 79 | + } | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +/// Everything the board page shows for one request. | ||
| 83 | +pub struct BoardPage { | ||
| 84 | + /// The language of the page. | ||
| 85 | + pub lang: Lang, | ||
| 86 | + /// The signed-in person, for the topbar. | ||
| 87 | + pub viewer: ViewerInfo, | ||
| 88 | + /// Whether the viewer may change the board (a member or an admin). | ||
| 89 | + pub can_write: bool, | ||
| 90 | + /// The viewer's zone, for deadlines and meeting times. | ||
| 91 | + pub zone: TimeZone, | ||
| 92 | + /// The live columns with their cards, after the filters. | ||
| 93 | + pub view: BoardView, | ||
| 94 | + /// The projects of the board, in order. | ||
| 95 | + pub tags: Vec<Tag>, | ||
| 96 | + /// The members who may be assigned, for the assignee filter. | ||
| 97 | + pub members: Vec<Member>, | ||
| 98 | + /// The filters in effect. | ||
| 99 | + pub filters: Filters, | ||
| 100 | + /// This page's URL with its filters, so a form can return here. | ||
| 101 | + pub next: String, | ||
| 102 | + /// The new-task form, when `?new=1` asked for it. | ||
| 103 | + pub new_form: Option<NewForm>, | ||
| 104 | + /// The refusal of the last write, shown above the board. | ||
| 105 | + pub alert: Option<K>, | ||
| 106 | + /// The notice of the last write, shown above the board. | ||
| 107 | + pub notice: Option<&'static str>, | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +/// The board of this installation. The board is created at boot, so its absence is a missing page. | ||
| 111 | +pub async fn the_board(store: &Store) -> Result<Board> { | ||
| 112 | + match store.board().await? { | ||
| 113 | + Some(board) => Ok(board), | ||
| 114 | + None => Err(not_found().into()), | ||
| 115 | + } | ||
| 116 | +} | ||
| 117 | + | ||
| 118 | +/// The query pairs of a query string, decoded. Empty for an empty string. | ||
| 119 | +pub fn pairs(query: &str) -> Vec<(String, String)> { | ||
| 120 | + let Ok(mut url) = Url::parse("http://iz.invalid/") else { | ||
| 121 | + return Vec::new(); | ||
| 122 | + }; | ||
| 123 | + url.set_query(Some(query)); | ||
| 124 | + url.query_pairs() | ||
| 125 | + .map(|(key, value)| (key.into_owned(), value.into_owned())) | ||
| 126 | + .collect() | ||
| 127 | +} | ||
| 128 | + | ||
| 129 | +/// The query part of a path such as `/?tag=x`, without the `?`. `None` when there is none. | ||
| 130 | +pub fn query_of(path: &str) -> Option<&str> { | ||
| 131 | + path.split_once('?').map(|(_, query)| query) | ||
| 132 | +} | ||
| 133 | + | ||
| 134 | +/// Reads the filters from a query string. A bogus project or member id is dropped, as the page would | ||
| 135 | +/// otherwise show an empty board for a filter the viewer cannot see. An unknown sort falls back to the | ||
| 136 | +/// deadline order. | ||
| 137 | +pub fn parse_filters(query: Option<&str>, tags: &[Tag], members: &[Member]) -> Filters { | ||
| 138 | + let pairs = pairs(query.unwrap_or("")); | ||
| 139 | + let get = |name: &str| { | ||
| 140 | + pairs | ||
| 141 | + .iter() | ||
| 142 | + .find(|(key, _)| key == name) | ||
| 143 | + .map(|(_, value)| value.trim().to_owned()) | ||
| 144 | + .unwrap_or_default() | ||
| 145 | + }; | ||
| 146 | + let tag = get("tag"); | ||
| 147 | + let tag = if tags.iter().any(|t| t.id == tag) { | ||
| 148 | + tag | ||
| 149 | + } else { | ||
| 150 | + String::new() | ||
| 151 | + }; | ||
| 152 | + let assignee_raw = get("assignee"); | ||
| 153 | + let assignee = if assignee_raw == "none" { | ||
| 154 | + "none".to_owned() | ||
| 155 | + } else if members.iter().any(|m| m.sub == assignee_raw) { | ||
| 156 | + assignee_raw | ||
| 157 | + } else { | ||
| 158 | + String::new() | ||
| 159 | + }; | ||
| 160 | + let (sort, sort_by) = match get("sort").as_str() { | ||
| 161 | + "created" => ("created", SortBy::Created), | ||
| 162 | + "title" => ("title", SortBy::Title), | ||
| 163 | + _ => ("deadline", SortBy::Deadline), | ||
| 164 | + }; | ||
| 165 | + let query: String = get("q").chars().take(SEARCH_MAX).collect(); | ||
| 166 | + let filter = BoardFilter { | ||
| 167 | + tag_id: (!tag.is_empty()).then(|| tag.clone()), | ||
| 168 | + assignee: match assignee.as_str() { | ||
| 169 | + "" => None, | ||
| 170 | + "none" => Some(AssigneeFilter::Nobody), | ||
| 171 | + sub => Some(AssigneeFilter::Member(sub.to_owned())), | ||
| 172 | + }, | ||
| 173 | + query: (!query.is_empty()).then(|| query.clone()), | ||
| 174 | + sort: sort_by, | ||
| 175 | + }; | ||
| 176 | + Filters { | ||
| 177 | + filter, | ||
| 178 | + tag, | ||
| 179 | + assignee, | ||
| 180 | + sort, | ||
| 181 | + query, | ||
| 182 | + } | ||
| 183 | +} | ||
| 184 | + | ||
| 185 | +/// The URL of the board with these filters, plus `extra` pairs. `/` when nothing is set. | ||
| 186 | +pub fn board_url(filters: &Filters, extra: &[(&str, &str)]) -> String { | ||
| 187 | + let mut parts: Vec<String> = Vec::new(); | ||
| 188 | + if !filters.tag.is_empty() { | ||
| 189 | + parts.push(format!("tag={}", percent_encode(&filters.tag))); | ||
| 190 | + } | ||
| 191 | + if !filters.assignee.is_empty() { | ||
| 192 | + parts.push(format!("assignee={}", percent_encode(&filters.assignee))); | ||
| 193 | + } | ||
| 194 | + if filters.sort != "deadline" { | ||
| 195 | + parts.push(format!("sort={}", filters.sort)); | ||
| 196 | + } | ||
| 197 | + if !filters.query.is_empty() { | ||
| 198 | + parts.push(format!("q={}", percent_encode(&filters.query))); | ||
| 199 | + } | ||
| 200 | + for (key, value) in extra { | ||
| 201 | + parts.push(format!("{key}={}", percent_encode(value))); | ||
| 202 | + } | ||
| 203 | + if parts.is_empty() { | ||
| 204 | + "/".to_owned() | ||
| 205 | + } else { | ||
| 206 | + format!("/?{}", parts.join("&")) | ||
| 207 | + } | ||
| 208 | +} | ||
| 209 | + | ||
| 210 | +/// Whether a member may be assigned: enabled, and an admin or a member (not a viewer or no-access). | ||
| 211 | +fn assignable(member: &Member) -> bool { | ||
| 212 | + !member.disabled && matches!(member.role, Role::Admin | Role::Member) | ||
| 213 | +} | ||
| 214 | + | ||
| 215 | +/// Loads the board for `me` with the filters of `query`. The caller sets the form, alert and notice. | ||
| 216 | +pub async fn load( | ||
| 217 | + store: &Store, | ||
| 218 | + me: &CurrentMember, | ||
| 219 | + lang: Lang, | ||
| 220 | + query: Option<&str>, | ||
| 221 | +) -> Result<BoardPage> { | ||
| 222 | + let board = the_board(store).await?; | ||
| 223 | + let zone = parse_zone(&me.member.zoneinfo).unwrap_or(TimeZone::UTC); | ||
| 224 | + let tags = store.tags(&board.id).await?; | ||
| 225 | + let members: Vec<Member> = store | ||
| 226 | + .list_members() | ||
| 227 | + .await? | ||
| 228 | + .into_iter() | ||
| 229 | + .filter(assignable) | ||
| 230 | + .collect(); | ||
| 231 | + let filters = parse_filters(query, &tags, &members); | ||
| 232 | + let view = store.board_view(&board.id, &filters.filter, &zone).await?; | ||
| 233 | + let can_write = authorize(&me.actor(), &Action::WriteTask).is_ok(); | ||
| 234 | + let viewer = ViewerInfo { | ||
| 235 | + name: me.member.name.clone(), | ||
| 236 | + is_admin: me.member.im_admin || me.member.role == Role::Admin, | ||
| 237 | + csrf: me.session.csrf_token.clone(), | ||
| 238 | + }; | ||
| 239 | + Ok(BoardPage { | ||
| 240 | + lang, | ||
| 241 | + viewer, | ||
| 242 | + can_write, | ||
| 243 | + zone, | ||
| 244 | + view, | ||
| 245 | + tags, | ||
| 246 | + members, | ||
| 247 | + next: board_url(&filters, &[]), | ||
| 248 | + filters, | ||
| 249 | + new_form: None, | ||
| 250 | + alert: None, | ||
| 251 | + notice: None, | ||
| 252 | + }) | ||
| 253 | +} | ||
| 254 | + | ||
| 255 | +/// Renders the page as a response. The page is one document; its own status (for a refused write) | ||
| 256 | +/// is set by the caller through `status`. | ||
| 257 | +pub async fn render( | ||
| 258 | + cx: &Cx, | ||
| 259 | + page: &BoardPage, | ||
| 260 | + status: Option<topcoat::router::StatusCode>, | ||
| 261 | +) -> Result<Response> { | ||
| 262 | + let status = status.unwrap_or(topcoat::router::StatusCode::OK); | ||
| 263 | + let document = view! { | ||
| 264 | + cx => | ||
| 265 | + (status) | ||
| 266 | + shell(title: crate::i18n::board::t(page.lang, K::BoardTitle), lang: page.lang, | ||
| 267 | + viewer: Some(&page.viewer), page_script: Some(BOARD_JS_HREF), | ||
| 268 | + board_content(page: page) | ||
| 269 | + ) | ||
| 270 | + }; | ||
| 271 | + respond(cx, document).await | ||
| 272 | +} | ||
| 273 | + | ||
| 274 | +/// Renders the sign-in card for a visitor who is not signed in, or has no access to the board. | ||
| 275 | +async fn signed_out(cx: &Cx, no_access: bool) -> Result<Response> { | ||
| 276 | + let lang = lang(cx, None); | ||
| 277 | + let document = view! { | ||
| 278 | + cx => | ||
| 279 | + shell(title: crate::i18n::shell::t(lang, crate::i18n::shell::K::SignedOutTitle), lang: lang, | ||
| 280 | + viewer: None, page_script: None, | ||
| 281 | + signed_out_card(lang: lang, no_access: no_access) | ||
| 282 | + ) | ||
| 283 | + }; | ||
| 284 | + respond(cx, document).await | ||
| 285 | +} | ||
| 286 | + | ||
| 287 | +/// `GET /`. Shows the board to a signed-in viewer; the sign-in card to anyone else. | ||
| 288 | +#[route(GET "/")] | ||
| 289 | +async fn board_page(cx: &Cx) -> Result<Response> { | ||
| 290 | + let state = app_context::<AppState>(cx); | ||
| 291 | + let Some(me) = current_member(cx).await? else { | ||
| 292 | + return signed_out(cx, false).await; | ||
| 293 | + }; | ||
| 294 | + if authorize(&me.actor(), &Action::ReadBoard).is_err() { | ||
| 295 | + return signed_out(cx, true).await; | ||
| 296 | + } | ||
| 297 | + let lang = lang(cx, me.member.locale_override.as_deref()); | ||
| 298 | + let query = uri_query(cx); | ||
| 299 | + let mut page = load(&state.store, &me, lang, query.as_deref()).await?; | ||
| 300 | + let new_wanted = query_param(cx, "new").is_some_and(|v| v == "1"); | ||
| 301 | + if new_wanted && page.can_write { | ||
| 302 | + page.new_form = Some(blank_form(&page)); | ||
| 303 | + } | ||
| 304 | + page.notice = | ||
| 305 | + query_param(cx, "notice").and_then(|name| crate::i18n::board::notice(lang, &name)); | ||
| 306 | + render(cx, &page, None).await | ||
| 307 | +} | ||
| 308 | + | ||
| 309 | +/// The new-task form with the first column and the default project chosen. | ||
| 310 | +pub fn blank_form(page: &BoardPage) -> NewForm { | ||
| 311 | + let column = page | ||
| 312 | + .view | ||
| 313 | + .columns | ||
| 314 | + .first() | ||
| 315 | + .map(|c| c.column.id.clone()) | ||
| 316 | + .unwrap_or_default(); | ||
| 317 | + let tag = page | ||
| 318 | + .tags | ||
| 319 | + .iter() | ||
| 320 | + .find(|t| t.is_default) | ||
| 321 | + .or_else(|| page.tags.first()) | ||
| 322 | + .map(|t| t.id.clone()) | ||
| 323 | + .unwrap_or_default(); | ||
| 324 | + NewForm { | ||
| 325 | + column, | ||
| 326 | + tag, | ||
| 327 | + ..NewForm::default() | ||
| 328 | + } | ||
| 329 | +} | ||
| 330 | + | ||
| 331 | +/// `GET /board/live`. A `changed` event whenever the board's counts or newest change move on. The | ||
| 332 | +/// browser then fetches the page again (`nav.js`). Anyone who may read the board may hold it. | ||
| 333 | +#[route(GET "/board/live")] | ||
| 334 | +async fn board_live(cx: &Cx) -> Result<Response> { | ||
| 335 | + let state = app_context::<AppState>(cx); | ||
| 336 | + require_role(cx, Need::Viewer).await?; | ||
| 337 | + let board = the_board(&state.store).await?; | ||
| 338 | + let store = state.store.clone(); | ||
| 339 | + let board_id = board.id.clone(); | ||
| 340 | + stream_changes( | ||
| 341 | + cx, | ||
| 342 | + &state.live, | ||
| 343 | + &[Topic::Board(board.id.clone())], | ||
| 344 | + move || { | ||
| 345 | + let store = store.clone(); | ||
| 346 | + let board_id = board_id.clone(); | ||
| 347 | + async move { | ||
| 348 | + let fingerprint: iz_core::Result<String> = store.board_fingerprint(&board_id).await; | ||
| 349 | + Ok(fingerprint?) | ||
| 350 | + } | ||
| 351 | + }, | ||
| 352 | + ) | ||
| 353 | + .await | ||
| 354 | +} | ||
| 355 | + | ||
| 356 | +#[cfg(test)] | ||
| 357 | +mod tests { | ||
| 358 | + use super::*; | ||
| 359 | + | ||
| 360 | + #[test] | ||
| 361 | + fn board_url_keeps_only_set_filters() { | ||
| 362 | + let mut filters = Filters { | ||
| 363 | + sort: "deadline", | ||
| 364 | + ..Filters::default() | ||
| 365 | + }; | ||
| 366 | + assert_eq!(board_url(&filters, &[]), "/"); | ||
| 367 | + filters.query = "a b&c".into(); | ||
| 368 | + filters.sort = "title"; | ||
| 369 | + assert_eq!(board_url(&filters, &[]), "/?sort=title&q=a%20b%26c"); | ||
| 370 | + } | ||
| 371 | + | ||
| 372 | + #[test] | ||
| 373 | + fn unknown_sort_and_empty_filters_fall_back() { | ||
| 374 | + let filters = parse_filters(Some("sort=bogus&tag=nope&assignee=nobody-here"), &[], &[]); | ||
| 375 | + assert_eq!(filters.sort, "deadline"); | ||
| 376 | + assert!(filters.tag.is_empty()); | ||
| 377 | + assert!(filters.assignee.is_empty()); | ||
| 378 | + assert!(!filters.active()); | ||
| 379 | + } | ||
| 380 | +} | ||
| 381 | + | ||
| 382 | +/// Test support: a member of the given role with a live session, made through the store. Returns the | ||
| 383 | +/// session's cookie token and its CSRF token. | ||
| 384 | +#[cfg(test)] | ||
| 385 | +use iz_core::store::tasks::NewTask; | ||
| 386 | + | ||
| 387 | +#[cfg(test)] | ||
| 388 | +pub(crate) async fn sign_in_as(state: &AppState, sub: &str, role: Role) -> (String, String) { | ||
| 389 | + use crate::auth::SESSION_LIFETIME; | ||
| 390 | + use iz_core::store::members::DirectoryMember; | ||
| 391 | + let member = DirectoryMember { | ||
| 392 | + sub: sub.into(), | ||
| 393 | + email: format!("{sub}@example.com"), | ||
| 394 | + name: format!("Member {sub}"), | ||
| 395 | + im_admin: false, | ||
| 396 | + disabled: false, | ||
| 397 | + locale: None, | ||
| 398 | + zoneinfo: "Europe/Istanbul".into(), | ||
| 399 | + picture_version: 0, | ||
| 400 | + }; | ||
| 401 | + state | ||
| 402 | + .store | ||
| 403 | + .apply_directory_member(&member, role) | ||
| 404 | + .await | ||
| 405 | + .expect("member"); | ||
| 406 | + let issued = state | ||
| 407 | + .store | ||
| 408 | + .create_session(sub, Some("sid-test"), None, SESSION_LIFETIME, None, None) | ||
| 409 | + .await | ||
| 410 | + .expect("session"); | ||
| 411 | + (issued.token, issued.csrf_token) | ||
| 412 | +} | ||
| 413 | + | ||
| 414 | +/// Test support: the cookie header of a session. | ||
| 415 | +#[cfg(test)] | ||
| 416 | +pub(crate) fn cookie_of(token: &str) -> String { | ||
| 417 | + format!("__Host-iz_session={token}") | ||
| 418 | +} | ||
| 419 | + | ||
| 420 | +/// Test support: makes the board and one card in its first column, as the store makes them. Returns the | ||
| 421 | +/// card's id and the board's first column id. `actor` must be a member of the store, since a card | ||
| 422 | +/// names its creator. | ||
| 423 | +#[cfg(test)] | ||
| 424 | +pub(crate) async fn one_card(state: &AppState, title: &str, actor: &str) -> (String, String) { | ||
| 425 | + let board = state.store.ensure_board("IZ").await.expect("board"); | ||
| 426 | + let columns = state.store.columns(&board.id).await.expect("columns"); | ||
| 427 | + let tags = state.store.tags(&board.id).await.expect("tags"); | ||
| 428 | + let task = state | ||
| 429 | + .store | ||
| 430 | + .create_task( | ||
| 431 | + &board.id, | ||
| 432 | + NewTask { | ||
| 433 | + title: title.into(), | ||
| 434 | + description: String::new(), | ||
| 435 | + column_id: columns[0].id.clone(), | ||
| 436 | + tag_id: tags[0].id.clone(), | ||
| 437 | + deadline: None, | ||
| 438 | + meeting_at: None, | ||
| 439 | + assignees: Vec::new(), | ||
| 440 | + parent_id: None, | ||
| 441 | + link: None, | ||
| 442 | + }, | ||
| 443 | + actor, | ||
| 444 | + ) | ||
| 445 | + .await | ||
| 446 | + .expect("task"); | ||
| 447 | + (task.id, columns[0].id.clone()) | ||
| 448 | +} | ||
| 449 | + | ||
| 450 | +#[cfg(test)] | ||
| 451 | +mod render_tests { | ||
| 452 | + use http::header::COOKIE; | ||
| 453 | + use iz_core::authz::Role; | ||
| 454 | + use iz_core::store::tasks::NewTask; | ||
| 455 | + use topcoat::router::{Body, to_bytes}; | ||
| 456 | + | ||
| 457 | + use super::{cookie_of, one_card, sign_in_as}; | ||
| 458 | + use crate::boot::{router, test_state}; | ||
| 459 | + | ||
| 460 | + /// The member who creates the test cards. Their row must exist: a card names its creator. | ||
| 461 | + const AUTHOR: &str = "01ADAAAAAAAAAAAAAAAAAAAAAA"; | ||
| 462 | + | ||
| 463 | + /// The board page of a signed-in viewer, as text. | ||
| 464 | + async fn get_page(state: &crate::state::AppState, path: &str, token: &str) -> (u16, String) { | ||
| 465 | + let request = http::Request::get(path) | ||
| 466 | + .header(COOKIE, cookie_of(token)) | ||
| 467 | + .body(Body::empty()) | ||
| 468 | + .expect("request"); | ||
| 469 | + let response = router(state.clone()).handle(request).await; | ||
| 470 | + let status = response.status().as_u16(); | ||
| 471 | + let bytes = to_bytes(response.into_body(), 1024 * 1024) | ||
| 472 | + .await | ||
| 473 | + .expect("body"); | ||
| 474 | + (status, String::from_utf8_lossy(&bytes).into_owned()) | ||
| 475 | + } | ||
| 476 | + | ||
| 477 | + /// A search folds Turkish dotted capital I: `istanbul` finds `İstanbul`, and the other card stays | ||
| 478 | + /// out of the page. | ||
| 479 | + #[tokio::test] | ||
| 480 | + async fn search_folds_turkish_capital_i() { | ||
| 481 | + let (_dir, state) = test_state().await; | ||
| 482 | + let (token, _) = sign_in_as(&state, AUTHOR, Role::Member).await; | ||
| 483 | + one_card(&state, "İstanbul ofisi", AUTHOR).await; | ||
| 484 | + let board = state.store.board().await.expect("board").expect("some"); | ||
| 485 | + let tags = state.store.tags(&board.id).await.expect("tags"); | ||
| 486 | + let columns = state.store.columns(&board.id).await.expect("columns"); | ||
| 487 | + state | ||
| 488 | + .store | ||
| 489 | + .create_task( | ||
| 490 | + &board.id, | ||
| 491 | + NewTask { | ||
| 492 | + title: "Ankara ofisi".into(), | ||
| 493 | + description: String::new(), | ||
| 494 | + column_id: columns[0].id.clone(), | ||
| 495 | + tag_id: tags[0].id.clone(), | ||
| 496 | + deadline: None, | ||
| 497 | + meeting_at: None, | ||
| 498 | + assignees: Vec::new(), | ||
| 499 | + parent_id: None, | ||
| 500 | + link: None, | ||
| 501 | + }, | ||
| 502 | + AUTHOR, | ||
| 503 | + ) | ||
| 504 | + .await | ||
| 505 | + .expect("second task"); | ||
| 506 | + let (status, html) = get_page(&state, "/?q=ISTANBUL", &token).await; | ||
| 507 | + assert_eq!(status, 200); | ||
| 508 | + assert!(html.contains("İstanbul ofisi"), "match missing: {html}"); | ||
| 509 | + assert!(!html.contains("Ankara ofisi"), "non-match shown: {html}"); | ||
| 510 | + } | ||
| 511 | + | ||
| 512 | + /// A title that is markup reaches the page as text: escaped, never as a script element. | ||
| 513 | + #[tokio::test] | ||
| 514 | + async fn a_script_title_is_escaped_on_the_board() { | ||
| 515 | + let (_dir, state) = test_state().await; | ||
| 516 | + let (token, _) = sign_in_as(&state, AUTHOR, Role::Member).await; | ||
| 517 | + one_card(&state, "<script>alert(1)</script>", AUTHOR).await; | ||
| 518 | + let (status, html) = get_page(&state, "/", &token).await; | ||
| 519 | + assert_eq!(status, 200); | ||
| 520 | + assert!( | ||
| 521 | + html.contains("<script>alert(1)</script>"), | ||
| 522 | + "not escaped: {html}" | ||
| 523 | + ); | ||
| 524 | + assert!( | ||
| 525 | + !html.contains("<script>alert(1)"), | ||
| 526 | + "raw script shown: {html}" | ||
| 527 | + ); | ||
| 528 | + } | ||
| 529 | + | ||
| 530 | + /// A viewer sees the card and no write control. The new-task form is never shown to them. | ||
| 531 | + #[tokio::test] | ||
| 532 | + async fn a_viewer_sees_no_write_control() { | ||
| 533 | + let (_dir, state) = test_state().await; | ||
| 534 | + sign_in_as(&state, AUTHOR, Role::Member).await; | ||
| 535 | + let (token, _) = sign_in_as(&state, "01BOAAAAAAAAAAAAAAAAAAAAAA", Role::Viewer).await; | ||
| 536 | + one_card(&state, "Read only card", AUTHOR).await; | ||
| 537 | + let (status, html) = get_page(&state, "/?new=1", &token).await; | ||
| 538 | + assert_eq!(status, 200); | ||
| 539 | + assert!(html.contains("Read only card")); | ||
| 540 | + assert!( | ||
| 541 | + !html.contains("action=\"/tasks\""), | ||
| 542 | + "create form shown to a viewer" | ||
| 543 | + ); | ||
| 544 | + assert!(!html.contains("/move\""), "move form shown to a viewer"); | ||
| 545 | + assert!(!html.contains("draggable"), "drag enabled for a viewer"); | ||
| 546 | + } | ||
| 547 | +} | ||
crates/iz-web/src/pages/home.rsdeleted+0 -45
| @@ -1,45 +0,0 @@ | |||
| 1 | -//! The start page. A signed-out visitor sees the app name and a sign-in button. A signed-in member | ||
| 2 | -//! sees a greeting; the board itself comes later, so the page says that. | ||
| 3 | - | ||
| 4 | -use topcoat::Result; | ||
| 5 | -use topcoat::context::Cx; | ||
| 6 | -use topcoat::router::page; | ||
| 7 | -use topcoat::view::{View, view}; | ||
| 8 | - | ||
| 9 | -use crate::auth::current_member; | ||
| 10 | -use crate::i18n::shell::{K, greeting, t}; | ||
| 11 | -use crate::i18n::lang; | ||
| 12 | -use crate::views::{ViewerInfo, shell}; | ||
| 13 | -use iz_core::authz::Role; | ||
| 14 | - | ||
| 15 | -/// `GET /`. | ||
| 16 | -#[page("/")] | ||
| 17 | -async fn home(cx: &Cx) -> Result<impl View> { | ||
| 18 | - let me = current_member(cx).await?; | ||
| 19 | - let lang = lang( | ||
| 20 | - cx, | ||
| 21 | - me.as_ref() | ||
| 22 | - .and_then(|me| me.member.locale_override.as_deref()), | ||
| 23 | - ); | ||
| 24 | - let viewer = me.as_ref().map(|me| ViewerInfo { | ||
| 25 | - name: me.member.name.clone(), | ||
| 26 | - is_admin: me.member.im_admin || me.member.role == Role::Admin, | ||
| 27 | - csrf: me.session.csrf_token.clone(), | ||
| 28 | - }); | ||
| 29 | - let name = me.as_ref().map(|me| me.member.name.clone()); | ||
| 30 | - Ok(view! { | ||
| 31 | - shell(title: t(lang, K::SignedOutTitle), lang: lang, viewer: viewer.as_ref(), | ||
| 32 | - <section class="card"> | ||
| 33 | - <p class="kicker">"iz"</p> | ||
| 34 | - if let Some(name) = name { | ||
| 35 | - <h1>(greeting(lang, &name))</h1> | ||
| 36 | - <p>(t(lang, K::BoardComesNext))</p> | ||
| 37 | - } else { | ||
| 38 | - <h1>(t(lang, K::SignedOutTitle))</h1> | ||
| 39 | - <p>(t(lang, K::SignedOutBody))</p> | ||
| 40 | - <a class="button primary" href="/auth/login">(t(lang, K::SignIn))</a> | ||
| 41 | - } | ||
| 42 | - </section> | ||
| 43 | - ) | ||
| 44 | - }) | ||
| 45 | -} | ||
crates/iz-web/src/pages/mod.rsmodified+2 -1
| @@ -1,7 +1,8 @@ | |||
| 1 | //! The pages and the page-level layers. One file per page. | 1 | //! The pages and the page-level layers. One file per page. |
| 2 | 2 | ||
| 3 | pub mod backchannel; | 3 | pub mod backchannel; |
| 4 | -pub mod home; | 4 | +pub mod board; |
| 5 | pub mod not_found; | 5 | pub mod not_found; |
| 6 | pub mod photo; | 6 | pub mod photo; |
| 7 | pub mod sign_in; | 7 | pub mod sign_in; |
| 8 | +pub mod tasks; | ||
crates/iz-web/src/pages/not_found.rsmodified+1 -1
| @@ -55,7 +55,7 @@ async fn not_found_page(cx: &Cx) -> Result<impl View> { | |||
| 55 | let lang = lang(cx, None); | 55 | let lang = lang(cx, None); |
| 56 | Ok(view! { | 56 | Ok(view! { |
| 57 | (StatusCode::NOT_FOUND) | 57 | (StatusCode::NOT_FOUND) |
| 58 | - shell(title: t(lang, K::NotFoundTitle), lang: lang, viewer: None, not_found_body(lang: lang)) | 58 | + shell(title: t(lang, K::NotFoundTitle), lang: lang, viewer: None, page_script: None, not_found_body(lang: lang)) |
| 59 | }) | 59 | }) |
| 60 | } | 60 | } |
| 61 | 61 | ||
crates/iz-web/src/pages/photo.rsmodified+1 -3
| @@ -9,9 +9,7 @@ | |||
| 9 | 9 | ||
| 10 | use std::path::{Path, PathBuf}; | 10 | use std::path::{Path, PathBuf}; |
| 11 | 11 | ||
| 12 | -use http::header::{ | 12 | +use http::header::{CACHE_CONTROL, CONTENT_TYPE, ETAG, IF_NONE_MATCH, X_CONTENT_TYPE_OPTIONS}; |
| 13 | - CACHE_CONTROL, CONTENT_TYPE, ETAG, IF_NONE_MATCH, X_CONTENT_TYPE_OPTIONS, | ||
| 14 | -}; | ||
| 15 | use topcoat::Result; | 13 | use topcoat::Result; |
| 16 | use topcoat::context::{Cx, app_context}; | 14 | use topcoat::context::{Cx, app_context}; |
| 17 | use topcoat::router::error::not_found; | 15 | use topcoat::router::error::not_found; |
crates/iz-web/src/pages/sign_in.rsmodified+18 -4
| @@ -42,7 +42,7 @@ async fn message( | |||
| 42 | let lang: Lang = lang(cx, None); | 42 | let lang: Lang = lang(cx, None); |
| 43 | Ok(view! { | 43 | Ok(view! { |
| 44 | cx => | 44 | cx => |
| 45 | - shell(title: t(lang, title), lang: lang, viewer: None, | 45 | + shell(title: t(lang, title), lang: lang, viewer: None, page_script: None, |
| 46 | (status) | 46 | (status) |
| 47 | message_page(lang: lang, title: title, body: body, detail: detail) | 47 | message_page(lang: lang, title: title, body: body, detail: detail) |
| 48 | ) | 48 | ) |
| @@ -89,7 +89,11 @@ async fn login(cx: &Cx) -> Result<impl View> { | |||
| 89 | expires: unix_now() + STATE_LIFETIME.as_secs(), | 89 | expires: unix_now() + STATE_LIFETIME.as_secs(), |
| 90 | }; | 90 | }; |
| 91 | let url = match client | 91 | let url = match client |
| 92 | - .authorize_url(&flight.state, &flight.nonce, &pkce_challenge(&flight.verifier)) | 92 | + .authorize_url( |
| 93 | + &flight.state, | ||
| 94 | + &flight.nonce, | ||
| 95 | + &pkce_challenge(&flight.verifier), | ||
| 96 | + ) | ||
| 93 | .await | 97 | .await |
| 94 | { | 98 | { |
| 95 | Ok(url) => url, | 99 | Ok(url) => url, |
| @@ -308,7 +312,10 @@ struct LogoutForm { | |||
| 308 | /// `POST /auth/logout`: ends the local session, then sends the browser to `im`'s end-session endpoint with | 312 | /// `POST /auth/logout`: ends the local session, then sends the browser to `im`'s end-session endpoint with |
| 309 | /// the stored ID token as the hint (contracts.md 2.5). The CSRF check runs before any side effect. | 313 | /// the stored ID token as the hint (contracts.md 2.5). The CSRF check runs before any side effect. |
| 310 | #[route(POST "/auth/logout")] | 314 | #[route(POST "/auth/logout")] |
| 311 | -async fn logout(cx: &Cx, form: Option<Form<LogoutForm>>) -> Result<topcoat::router::error::SeeOther> { | 315 | +async fn logout( |
| 316 | + cx: &Cx, | ||
| 317 | + form: Option<Form<LogoutForm>>, | ||
| 318 | +) -> Result<topcoat::router::error::SeeOther> { | ||
| 312 | let state = app_context::<AppState>(cx); | 319 | let state = app_context::<AppState>(cx); |
| 313 | let Some(me) = current_member(cx).await? else { | 320 | let Some(me) = current_member(cx).await? else { |
| 314 | // Nothing to end: the session is already gone. | 321 | // Nothing to end: the session is already gone. |
| @@ -375,7 +382,14 @@ mod tests { | |||
| 375 | .unwrap(); | 382 | .unwrap(); |
| 376 | let issued = state | 383 | let issued = state |
| 377 | .store | 384 | .store |
| 378 | - .create_session(&member.sub, Some("sid-1"), None, SESSION_LIFETIME, None, None) | 385 | + .create_session( |
| 386 | + &member.sub, | ||
| 387 | + Some("sid-1"), | ||
| 388 | + None, | ||
| 389 | + SESSION_LIFETIME, | ||
| 390 | + None, | ||
| 391 | + None, | ||
| 392 | + ) | ||
| 379 | .await | 393 | .await |
| 380 | .unwrap(); | 394 | .unwrap(); |
| 381 | let request = http::Request::post("/auth/logout") | 395 | let request = http::Request::post("/auth/logout") |
crates/iz-web/src/pages/tasks.rsadded+565 -0
| @@ -0,0 +1,565 @@ | |||
| 1 | +//! The board's writes: create a task, move it to another column, delete it (`docs/architecture.md` | ||
| 2 | +//! section 4). Task editing, assignees and links come with the task modal. | ||
| 3 | +//! | ||
| 4 | +//! Every write passes the same gate before anything else: a signed-in member with the write level, and | ||
| 5 | +//! the session's CSRF token (`auth::require_csrf`). A viewer is refused with `403` whatever the form | ||
| 6 | +//! says. The rules (a stale move, open subtasks, the title length) are the store's, and a refused write | ||
| 7 | +//! changes nothing. | ||
| 8 | +//! | ||
| 9 | +//! A refused write is answered two ways. A `fetch` that sends `Accept: application/json` gets | ||
| 10 | +//! `{"error": code, "message": text}` with the real status. A form gets the board page again with the | ||
| 11 | +//! message above it, at the refusal's status; a missing task or a missing right gets the framework's | ||
| 12 | +//! 404 or 403 page. A write that goes through redirects to the board it came from (Post/Redirect/Get), | ||
| 13 | +//! with a notice in the query string. Every change calls `live.bump` after its commit, so other open | ||
| 14 | +//! boards refresh. | ||
| 15 | + | ||
| 16 | +use std::result::Result as StdResult; | ||
| 17 | + | ||
| 18 | +use http::header::{ACCEPT, CACHE_CONTROL, CONTENT_TYPE}; | ||
| 19 | +use iz_core::limits::{DESCRIPTION_MAX, TITLE_MAX}; | ||
| 20 | +use iz_core::store::board::{Column, Tag}; | ||
| 21 | +use iz_core::store::tasks::{MoveOutcome, NewTask}; | ||
| 22 | +use jiff::civil::Date; | ||
| 23 | +use serde::Deserialize; | ||
| 24 | +use serde_json::json; | ||
| 25 | +use topcoat::Result; | ||
| 26 | +use topcoat::context::{Cx, app_context}; | ||
| 27 | +use topcoat::router::content::Form; | ||
| 28 | +use topcoat::router::error::{ | ||
| 29 | + ForbiddenError, NotFoundError, SeeOther, forbidden, not_found, see_other, | ||
| 30 | +}; | ||
| 31 | +use topcoat::router::request::headers; | ||
| 32 | +use topcoat::router::response::{IntoResponse, Response}; | ||
| 33 | +use topcoat::router::{HeaderMap, HeaderValue, StatusCode, path_param_segment, route}; | ||
| 34 | + | ||
| 35 | +use crate::auth::{CurrentMember, Need, percent_encode, require_csrf, safe_next}; | ||
| 36 | +use crate::i18n::board::{K, t}; | ||
| 37 | +use crate::i18n::{Lang, lang}; | ||
| 38 | +use crate::live::Topic; | ||
| 39 | +use crate::pages::board::{NewForm, load, query_of, render, the_board}; | ||
| 40 | +use crate::state::AppState; | ||
| 41 | + | ||
| 42 | +/// A refused write: the status, the code a client reads, and the message a person reads. | ||
| 43 | +struct Refused { | ||
| 44 | + status: StatusCode, | ||
| 45 | + code: &'static str, | ||
| 46 | + message: K, | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +/// Builds a refusal. `status` is a plain HTTP status number. | ||
| 50 | +fn refused(status: u16, code: &'static str, message: K) -> Refused { | ||
| 51 | + Refused { | ||
| 52 | + status: StatusCode::from_u16(status).unwrap_or(StatusCode::BAD_REQUEST), | ||
| 53 | + code, | ||
| 54 | + message, | ||
| 55 | + } | ||
| 56 | +} | ||
| 57 | + | ||
| 58 | +/// Why the gate of a write stopped it before any change. | ||
| 59 | +enum Stop { | ||
| 60 | + /// No session: the browser goes to sign-in, a `fetch` gets `401`. | ||
| 61 | + Anonymous, | ||
| 62 | + /// The member may not write, or the token is wrong (`403`), or the member has no access (`404`). | ||
| 63 | + Refused(Refused), | ||
| 64 | + /// Any other failure (a database error while the member is read), answered as the framework does. | ||
| 65 | + Failed(topcoat::Error), | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +/// The form of `POST /tasks/{id}/move`. Every field is optional on the wire; a missing one is refused. | ||
| 69 | +#[derive(Deserialize, Default)] | ||
| 70 | +struct MoveForm { | ||
| 71 | + #[serde(default)] | ||
| 72 | + csrf: String, | ||
| 73 | + /// The column the page showed the card in. | ||
| 74 | + #[serde(default)] | ||
| 75 | + from: String, | ||
| 76 | + /// The column the card goes to. | ||
| 77 | + #[serde(default)] | ||
| 78 | + to: String, | ||
| 79 | + /// The place among the column's cards, from the top. Empty appends. | ||
| 80 | + #[serde(default)] | ||
| 81 | + position: String, | ||
| 82 | + /// The board URL the form was on, so a form answer returns there. | ||
| 83 | + #[serde(default)] | ||
| 84 | + next: String, | ||
| 85 | +} | ||
| 86 | + | ||
| 87 | +/// The form of `POST /tasks/{id}/delete`. | ||
| 88 | +#[derive(Deserialize, Default)] | ||
| 89 | +struct DeleteForm { | ||
| 90 | + #[serde(default)] | ||
| 91 | + csrf: String, | ||
| 92 | + #[serde(default)] | ||
| 93 | + next: String, | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +/// The form of `POST /tasks`, the new-task form. | ||
| 97 | +#[derive(Deserialize, Default)] | ||
| 98 | +struct CreateForm { | ||
| 99 | + #[serde(default)] | ||
| 100 | + csrf: String, | ||
| 101 | + #[serde(default)] | ||
| 102 | + title: String, | ||
| 103 | + #[serde(default)] | ||
| 104 | + description: String, | ||
| 105 | + #[serde(default)] | ||
| 106 | + deadline: String, | ||
| 107 | + #[serde(default)] | ||
| 108 | + column: String, | ||
| 109 | + #[serde(default)] | ||
| 110 | + tag: String, | ||
| 111 | + #[serde(default)] | ||
| 112 | + next: String, | ||
| 113 | +} | ||
| 114 | + | ||
| 115 | +/// Whether the request asks for JSON. A `fetch` from `board.js` does; a form does not. | ||
| 116 | +fn wants_json(cx: &Cx) -> bool { | ||
| 117 | + headers(cx) | ||
| 118 | + .get(ACCEPT) | ||
| 119 | + .and_then(|value| value.to_str().ok()) | ||
| 120 | + .is_some_and(|value| value.contains("application/json")) | ||
| 121 | +} | ||
| 122 | + | ||
| 123 | +/// A JSON answer with a status. | ||
| 124 | +fn json_answer(cx: &Cx, status: StatusCode, body: serde_json::Value) -> Result<Response> { | ||
| 125 | + let mut headers = HeaderMap::new(); | ||
| 126 | + headers.insert( | ||
| 127 | + CONTENT_TYPE, | ||
| 128 | + HeaderValue::from_static("application/json; charset=utf-8"), | ||
| 129 | + ); | ||
| 130 | + headers.insert(CACHE_CONTROL, HeaderValue::from_static("no-store")); | ||
| 131 | + (status, headers, body.to_string()).into_response(cx) | ||
| 132 | +} | ||
| 133 | + | ||
| 134 | +/// The board path a form returns to. Only a local path is used. | ||
| 135 | +fn return_to(next: &str) -> &str { | ||
| 136 | + safe_next(Some(next)) | ||
| 137 | +} | ||
| 138 | + | ||
| 139 | +/// `path` with one more query pair added. | ||
| 140 | +fn with_pair(path: &str, pair: &str) -> String { | ||
| 141 | + if path.contains('?') { | ||
| 142 | + format!("{path}&{pair}") | ||
| 143 | + } else { | ||
| 144 | + format!("{path}?{pair}") | ||
| 145 | + } | ||
| 146 | +} | ||
| 147 | + | ||
| 148 | +/// Reads the position of a move. Empty means "last"; anything else must be a number. | ||
| 149 | +fn parse_position(text: &str) -> StdResult<Option<usize>, ()> { | ||
| 150 | + let text = text.trim(); | ||
| 151 | + if text.is_empty() { | ||
| 152 | + return Ok(None); | ||
| 153 | + } | ||
| 154 | + text.parse::<usize>().map(Some).map_err(|_| ()) | ||
| 155 | +} | ||
| 156 | + | ||
| 157 | +/// The gate of every write: the member with the write level, and the CSRF token. The level is checked | ||
| 158 | +/// first, so a viewer gets `403` whatever token they send. | ||
| 159 | +async fn writer(cx: &Cx, csrf: &str) -> StdResult<CurrentMember, Stop> { | ||
| 160 | + match require_csrf(cx, Need::Member, csrf).await { | ||
| 161 | + Ok(me) => Ok(me), | ||
| 162 | + Err(error) if error.downcast_ref::<ForbiddenError>().is_some() => { | ||
| 163 | + Err(Stop::Refused(refused(403, "forbidden", K::Forbidden))) | ||
| 164 | + } | ||
| 165 | + Err(error) if error.downcast_ref::<NotFoundError>().is_some() => { | ||
| 166 | + Err(Stop::Refused(refused(404, "not_found", K::TaskNotFound))) | ||
| 167 | + } | ||
| 168 | + Err(error) if error.downcast_ref::<SeeOther>().is_some() => Err(Stop::Anonymous), | ||
| 169 | + Err(error) => Err(Stop::Failed(error)), | ||
| 170 | + } | ||
| 171 | +} | ||
| 172 | + | ||
| 173 | +/// Answers a gate stop: sign-in for the anonymous, the refusal for the rest. Gate refusals are always | ||
| 174 | +/// `403` or `404`, so they never need the board page. | ||
| 175 | +async fn answer_stop( | ||
| 176 | + cx: &Cx, | ||
| 177 | + stop: Stop, | ||
| 178 | + json: bool, | ||
| 179 | + next: &str, | ||
| 180 | + language: Lang, | ||
| 181 | +) -> Result<Response> { | ||
| 182 | + match stop { | ||
| 183 | + Stop::Anonymous if json => json_answer( | ||
| 184 | + cx, | ||
| 185 | + StatusCode::UNAUTHORIZED, | ||
| 186 | + json!({"error": "signin", "message": t(language, K::Forbidden)}), | ||
| 187 | + ), | ||
| 188 | + Stop::Anonymous => { | ||
| 189 | + let target = format!("/auth/login?next={}", percent_encode(return_to(next))); | ||
| 190 | + Err(see_other(target).into()) | ||
| 191 | + } | ||
| 192 | + Stop::Refused(refusal) => plain_refusal(cx, refusal, json, language), | ||
| 193 | + Stop::Failed(error) => Err(error), | ||
| 194 | + } | ||
| 195 | +} | ||
| 196 | + | ||
| 197 | +/// A refusal with no board page: JSON, or the framework's 403 or 404 page. | ||
| 198 | +fn plain_refusal(cx: &Cx, refusal: Refused, json: bool, language: Lang) -> Result<Response> { | ||
| 199 | + if json { | ||
| 200 | + return json_answer( | ||
| 201 | + cx, | ||
| 202 | + refusal.status, | ||
| 203 | + json!({"error": refusal.code, "message": t(language, refusal.message)}), | ||
| 204 | + ); | ||
| 205 | + } | ||
| 206 | + if refusal.status == StatusCode::NOT_FOUND { | ||
| 207 | + Err(not_found().into()) | ||
| 208 | + } else { | ||
| 209 | + Err(forbidden().into()) | ||
| 210 | + } | ||
| 211 | +} | ||
| 212 | + | ||
| 213 | +/// What one write attempt is: the request, the member and the language, so a refusal can answer it. | ||
| 214 | +struct Attempt<'a> { | ||
| 215 | + cx: &'a Cx, | ||
| 216 | + state: &'a AppState, | ||
| 217 | + me: &'a CurrentMember, | ||
| 218 | + language: Lang, | ||
| 219 | + json: bool, | ||
| 220 | + /// The board URL the form was on. | ||
| 221 | + next: &'a str, | ||
| 222 | +} | ||
| 223 | + | ||
| 224 | +/// A refusal of a write the member made: JSON, or the board again with the message above it, at the | ||
| 225 | +/// refusal's status. `new_form` carries what was typed in the new-task form, so it is not lost. | ||
| 226 | +async fn refuse_write( | ||
| 227 | + at: &Attempt<'_>, | ||
| 228 | + refusal: Refused, | ||
| 229 | + new_form: Option<NewForm>, | ||
| 230 | +) -> Result<Response> { | ||
| 231 | + let state_refusal = refusal.status == StatusCode::UNPROCESSABLE_ENTITY | ||
| 232 | + || refusal.status == StatusCode::CONFLICT; | ||
| 233 | + if at.json || !state_refusal { | ||
| 234 | + return plain_refusal(at.cx, refusal, at.json, at.language); | ||
| 235 | + } | ||
| 236 | + let mut page = load( | ||
| 237 | + &at.state.store, | ||
| 238 | + at.me, | ||
| 239 | + at.language, | ||
| 240 | + query_of(return_to(at.next)), | ||
| 241 | + ) | ||
| 242 | + .await?; | ||
| 243 | + page.alert = Some(refusal.message); | ||
| 244 | + page.new_form = new_form.map(|mut form| { | ||
| 245 | + form.error = Some(refusal.message); | ||
| 246 | + form | ||
| 247 | + }); | ||
| 248 | + render(at.cx, &page, Some(refusal.status)).await | ||
| 249 | +} | ||
| 250 | + | ||
| 251 | +/// `POST /tasks`: creates a task in a column, with a project, a description and a deadline day. | ||
| 252 | +#[route(POST "/tasks")] | ||
| 253 | +async fn create_task(cx: &Cx, form: Option<Form<CreateForm>>) -> Result<Response> { | ||
| 254 | + let state = app_context::<AppState>(cx); | ||
| 255 | + let form = form.map(|Form(form)| form).unwrap_or_default(); | ||
| 256 | + let json = wants_json(cx); | ||
| 257 | + let me = match writer(cx, &form.csrf).await { | ||
| 258 | + Ok(me) => me, | ||
| 259 | + Err(stop) => return answer_stop(cx, stop, json, &form.next, lang(cx, None)).await, | ||
| 260 | + }; | ||
| 261 | + let language = lang(cx, me.member.locale_override.as_deref()); | ||
| 262 | + let at = Attempt { | ||
| 263 | + cx, | ||
| 264 | + state, | ||
| 265 | + me: &me, | ||
| 266 | + language, | ||
| 267 | + json, | ||
| 268 | + next: &form.next, | ||
| 269 | + }; | ||
| 270 | + let board = the_board(&state.store).await?; | ||
| 271 | + let typed = NewForm { | ||
| 272 | + title: form.title.clone(), | ||
| 273 | + description: form.description.clone(), | ||
| 274 | + deadline: form.deadline.clone(), | ||
| 275 | + column: form.column.clone(), | ||
| 276 | + tag: form.tag.clone(), | ||
| 277 | + error: None, | ||
| 278 | + }; | ||
| 279 | + let columns = state.store.columns(&board.id).await?; | ||
| 280 | + let tags = state.store.tags(&board.id).await?; | ||
| 281 | + let input = match new_task_input(&form, &columns, &tags) { | ||
| 282 | + Ok(input) => input, | ||
| 283 | + Err(message) => { | ||
| 284 | + let refusal = refused(422, "invalid", message); | ||
| 285 | + return refuse_write(&at, refusal, Some(typed)).await; | ||
| 286 | + } | ||
| 287 | + }; | ||
| 288 | + match state | ||
| 289 | + .store | ||
| 290 | + .create_task(&board.id, input, &me.member.sub) | ||
| 291 | + .await | ||
| 292 | + { | ||
| 293 | + Ok(_) => { | ||
| 294 | + state.live.bump(&Topic::Board(board.id.clone())); | ||
| 295 | + Err(see_other(with_pair(return_to(&form.next), "notice=created")).into()) | ||
| 296 | + } | ||
| 297 | + Err(iz_core::Error::Invalid(_)) => { | ||
| 298 | + let refusal = refused(422, "invalid", K::InvalidForm); | ||
| 299 | + refuse_write(&at, refusal, Some(typed)).await | ||
| 300 | + } | ||
| 301 | + Err(error) => Err(error.into()), | ||
| 302 | + } | ||
| 303 | +} | ||
| 304 | + | ||
| 305 | +/// Checks the new-task form and turns it into the store's input. The first problem found is the | ||
| 306 | +/// message. The column and the project must be on this board, and the project defaults to the board's | ||
| 307 | +/// default one. | ||
| 308 | +fn new_task_input(form: &CreateForm, columns: &[Column], tags: &[Tag]) -> StdResult<NewTask, K> { | ||
| 309 | + let title = form.title.trim(); | ||
| 310 | + if title.is_empty() || title.chars().count() > TITLE_MAX { | ||
| 311 | + return Err(K::TitleInvalid); | ||
| 312 | + } | ||
| 313 | + if form.description.chars().count() > DESCRIPTION_MAX { | ||
| 314 | + return Err(K::DescriptionTooLong); | ||
| 315 | + } | ||
| 316 | + let deadline = match form.deadline.trim() { | ||
| 317 | + "" => None, | ||
| 318 | + text => Some(text.parse::<Date>().map_err(|_| K::DeadlineInvalid)?), | ||
| 319 | + }; | ||
| 320 | + let column = columns | ||
| 321 | + .iter() | ||
| 322 | + .find(|c| c.id == form.column) | ||
| 323 | + .ok_or(K::ColumnUnknown)?; | ||
| 324 | + let tag = if form.tag.trim().is_empty() { | ||
| 325 | + tags.iter().find(|t| t.is_default).or_else(|| tags.first()) | ||
| 326 | + } else { | ||
| 327 | + tags.iter().find(|t| t.id == form.tag) | ||
| 328 | + } | ||
| 329 | + .ok_or(K::ProjectUnknown)?; | ||
| 330 | + Ok(NewTask { | ||
| 331 | + title: title.to_owned(), | ||
| 332 | + description: form.description.clone(), | ||
| 333 | + column_id: column.id.clone(), | ||
| 334 | + tag_id: tag.id.clone(), | ||
| 335 | + deadline, | ||
| 336 | + meeting_at: None, | ||
| 337 | + assignees: Vec::new(), | ||
| 338 | + parent_id: None, | ||
| 339 | + link: None, | ||
| 340 | + }) | ||
| 341 | +} | ||
| 342 | + | ||
| 343 | +/// `POST /tasks/{id}/move`: moves a card to another column. The store refuses a move of a card the page | ||
| 344 | +/// no longer shows (`moved_already`) and a move into Done with open subtasks (`subtasks_open`). | ||
| 345 | +#[route(POST "/tasks/{id}/move")] | ||
| 346 | +async fn move_task(cx: &Cx, form: Option<Form<MoveForm>>) -> Result<Response> { | ||
| 347 | + let state = app_context::<AppState>(cx); | ||
| 348 | + let form = form.map(|Form(form)| form).unwrap_or_default(); | ||
| 349 | + let json = wants_json(cx); | ||
| 350 | + let task_id = path_param_segment(cx, "id").to_owned(); | ||
| 351 | + let me = match writer(cx, &form.csrf).await { | ||
| 352 | + Ok(me) => me, | ||
| 353 | + Err(stop) => return answer_stop(cx, stop, json, &form.next, lang(cx, None)).await, | ||
| 354 | + }; | ||
| 355 | + let language = lang(cx, me.member.locale_override.as_deref()); | ||
| 356 | + let at = Attempt { | ||
| 357 | + cx, | ||
| 358 | + state, | ||
| 359 | + me: &me, | ||
| 360 | + language, | ||
| 361 | + json, | ||
| 362 | + next: &form.next, | ||
| 363 | + }; | ||
| 364 | + let board = the_board(&state.store).await?; | ||
| 365 | + let Ok(index) = parse_position(&form.position) else { | ||
| 366 | + let refusal = refused(422, "invalid", K::InvalidForm); | ||
| 367 | + return refuse_write(&at, refusal, None).await; | ||
| 368 | + }; | ||
| 369 | + let outcome = state | ||
| 370 | + .store | ||
| 371 | + .move_task( | ||
| 372 | + &board.id, | ||
| 373 | + &task_id, | ||
| 374 | + &form.from, | ||
| 375 | + &form.to, | ||
| 376 | + index, | ||
| 377 | + &me.member.sub, | ||
| 378 | + ) | ||
| 379 | + .await; | ||
| 380 | + let outcome = match outcome { | ||
| 381 | + Ok(outcome) => outcome, | ||
| 382 | + Err(iz_core::Error::NotFound) => { | ||
| 383 | + let refusal = refused(404, "not_found", K::TaskNotFound); | ||
| 384 | + return refuse_write(&at, refusal, None).await; | ||
| 385 | + } | ||
| 386 | + Err(iz_core::Error::Invalid(_)) => { | ||
| 387 | + let refusal = refused(422, "invalid", K::ColumnUnknown); | ||
| 388 | + return refuse_write(&at, refusal, None).await; | ||
| 389 | + } | ||
| 390 | + Err(error) => return Err(error.into()), | ||
| 391 | + }; | ||
| 392 | + let refusal = match outcome { | ||
| 393 | + MoveOutcome::Moved | MoveOutcome::Unchanged => { | ||
| 394 | + if outcome == MoveOutcome::Moved { | ||
| 395 | + state.live.bump(&Topic::Board(board.id.clone())); | ||
| 396 | + } | ||
| 397 | + if json { | ||
| 398 | + return json_answer(cx, StatusCode::OK, json!({"ok": true})); | ||
| 399 | + } | ||
| 400 | + return Err(see_other(return_to(&form.next)).into()); | ||
| 401 | + } | ||
| 402 | + MoveOutcome::Stale => refused(409, "moved_already", K::MovedAlready), | ||
| 403 | + MoveOutcome::SubtasksOpen => refused(409, "subtasks_open", K::SubtasksOpen), | ||
| 404 | + }; | ||
| 405 | + refuse_write(&at, refusal, None).await | ||
| 406 | +} | ||
| 407 | + | ||
| 408 | +/// `POST /tasks/{id}/delete`: soft-deletes a task and its subtasks. There is no undo. | ||
| 409 | +#[route(POST "/tasks/{id}/delete")] | ||
| 410 | +async fn delete_task(cx: &Cx, form: Option<Form<DeleteForm>>) -> Result<Response> { | ||
| 411 | + let state = app_context::<AppState>(cx); | ||
| 412 | + let form = form.map(|Form(form)| form).unwrap_or_default(); | ||
| 413 | + let json = wants_json(cx); | ||
| 414 | + let task_id = path_param_segment(cx, "id").to_owned(); | ||
| 415 | + let me = match writer(cx, &form.csrf).await { | ||
| 416 | + Ok(me) => me, | ||
| 417 | + Err(stop) => return answer_stop(cx, stop, json, &form.next, lang(cx, None)).await, | ||
| 418 | + }; | ||
| 419 | + let language = lang(cx, me.member.locale_override.as_deref()); | ||
| 420 | + let at = Attempt { | ||
| 421 | + cx, | ||
| 422 | + state, | ||
| 423 | + me: &me, | ||
| 424 | + language, | ||
| 425 | + json, | ||
| 426 | + next: &form.next, | ||
| 427 | + }; | ||
| 428 | + let board = the_board(&state.store).await?; | ||
| 429 | + match state | ||
| 430 | + .store | ||
| 431 | + .delete_task(&board.id, &task_id, &me.member.sub) | ||
| 432 | + .await | ||
| 433 | + { | ||
| 434 | + Ok(_) => { | ||
| 435 | + state.live.bump(&Topic::Board(board.id.clone())); | ||
| 436 | + Err(see_other(with_pair(return_to(&form.next), "notice=deleted")).into()) | ||
| 437 | + } | ||
| 438 | + Err(iz_core::Error::NotFound) => { | ||
| 439 | + let refusal = refused(404, "not_found", K::TaskNotFound); | ||
| 440 | + refuse_write(&at, refusal, None).await | ||
| 441 | + } | ||
| 442 | + Err(error) => Err(error.into()), | ||
| 443 | + } | ||
| 444 | +} | ||
| 445 | + | ||
| 446 | +#[cfg(test)] | ||
| 447 | +mod tests { | ||
| 448 | + use super::*; | ||
| 449 | + | ||
| 450 | + #[test] | ||
| 451 | + fn position_is_a_number_or_nothing() { | ||
| 452 | + assert_eq!(parse_position(""), Ok(None)); | ||
| 453 | + assert_eq!(parse_position(" 3 "), Ok(Some(3))); | ||
| 454 | + assert!(parse_position("-1").is_err()); | ||
| 455 | + assert!(parse_position("a").is_err()); | ||
| 456 | + } | ||
| 457 | + | ||
| 458 | + #[test] | ||
| 459 | + fn a_new_task_needs_a_title_and_a_known_column() { | ||
| 460 | + let form = CreateForm { | ||
| 461 | + title: " ".into(), | ||
| 462 | + ..CreateForm::default() | ||
| 463 | + }; | ||
| 464 | + assert_eq!(new_task_input(&form, &[], &[]).err(), Some(K::TitleInvalid)); | ||
| 465 | + let form = CreateForm { | ||
| 466 | + title: "Milk".into(), | ||
| 467 | + column: "nope".into(), | ||
| 468 | + ..CreateForm::default() | ||
| 469 | + }; | ||
| 470 | + assert_eq!( | ||
| 471 | + new_task_input(&form, &[], &[]).err(), | ||
| 472 | + Some(K::ColumnUnknown) | ||
| 473 | + ); | ||
| 474 | + } | ||
| 475 | + | ||
| 476 | + #[test] | ||
| 477 | + fn return_paths_stay_local() { | ||
| 478 | + assert_eq!(return_to("//evil.example"), "/"); | ||
| 479 | + assert_eq!( | ||
| 480 | + with_pair("/?tag=a", "notice=created"), | ||
| 481 | + "/?tag=a¬ice=created" | ||
| 482 | + ); | ||
| 483 | + assert_eq!(with_pair("/", "notice=deleted"), "/?notice=deleted"); | ||
| 484 | + } | ||
| 485 | + | ||
| 486 | + /// A viewer's POST to create a task is refused with `403`, and nothing is created. | ||
| 487 | + #[tokio::test] | ||
| 488 | + async fn a_viewer_cannot_create_a_task() { | ||
| 489 | + use http::header::{CONTENT_TYPE, COOKIE}; | ||
| 490 | + use iz_core::authz::Role; | ||
| 491 | + use topcoat::router::{Body, to_bytes}; | ||
| 492 | + | ||
| 493 | + use crate::boot::{router, test_state}; | ||
| 494 | + use crate::pages::board::{cookie_of, sign_in_as}; | ||
| 495 | + | ||
| 496 | + let (_dir, state) = test_state().await; | ||
| 497 | + sign_in_as(&state, "01ADAAAAAAAAAAAAAAAAAAAAAA", Role::Member).await; | ||
| 498 | + let (token, csrf) = sign_in_as(&state, "01BOAAAAAAAAAAAAAAAAAAAAAA", Role::Viewer).await; | ||
| 499 | + let board = state.store.ensure_board("IZ").await.expect("board"); | ||
| 500 | + let column = state.store.columns(&board.id).await.expect("columns")[0] | ||
| 501 | + .id | ||
| 502 | + .clone(); | ||
| 503 | + let body = format!("csrf={csrf}&title=Sneaky&column={column}"); | ||
| 504 | + let request = http::Request::post("/tasks") | ||
| 505 | + .header(CONTENT_TYPE, "application/x-www-form-urlencoded") | ||
| 506 | + .header(COOKIE, cookie_of(&token)) | ||
| 507 | + .body(Body::from(body)) | ||
| 508 | + .expect("request"); | ||
| 509 | + let response = router(state.clone()).handle(request).await; | ||
| 510 | + assert_eq!(response.status(), 403); | ||
| 511 | + let _ = to_bytes(response.into_body(), 4096).await; | ||
| 512 | + let view = state | ||
| 513 | + .store | ||
| 514 | + .board_view(&board.id, &Default::default(), &jiff::tz::TimeZone::UTC) | ||
| 515 | + .await | ||
| 516 | + .expect("view"); | ||
| 517 | + assert!(view.columns.iter().all(|c| c.cards.is_empty())); | ||
| 518 | + } | ||
| 519 | + | ||
| 520 | + /// A move from a column the card has already left is refused as `moved_already`, with `409` and a | ||
| 521 | + /// JSON body for a `fetch`. | ||
| 522 | + #[tokio::test] | ||
| 523 | + async fn a_stale_move_answers_409_json() { | ||
| 524 | + use http::header::{ACCEPT, CONTENT_TYPE, COOKIE}; | ||
| 525 | + use iz_core::authz::Role; | ||
| 526 | + use topcoat::router::{Body, to_bytes}; | ||
| 527 | + | ||
| 528 | + use crate::boot::{router, test_state}; | ||
| 529 | + use crate::pages::board::{cookie_of, one_card, sign_in_as}; | ||
| 530 | + | ||
| 531 | + let (_dir, state) = test_state().await; | ||
| 532 | + let (token, csrf) = sign_in_as(&state, "01ADAAAAAAAAAAAAAAAAAAAAAA", Role::Member).await; | ||
| 533 | + let (task_id, first) = one_card(&state, "Milk", "01ADAAAAAAAAAAAAAAAAAAAAAA").await; | ||
| 534 | + let board = state.store.board().await.expect("board").expect("some"); | ||
| 535 | + let columns = state.store.columns(&board.id).await.expect("columns"); | ||
| 536 | + let second = columns[1].id.clone(); | ||
| 537 | + let third = columns[2].id.clone(); | ||
| 538 | + // Somebody else moves the card first; this page still shows it in `first`. | ||
| 539 | + state | ||
| 540 | + .store | ||
| 541 | + .move_task( | ||
| 542 | + &board.id, | ||
| 543 | + &task_id, | ||
| 544 | + &first, | ||
| 545 | + &second, | ||
| 546 | + None, | ||
| 547 | + "01ADAAAAAAAAAAAAAAAAAAAAAA", | ||
| 548 | + ) | ||
| 549 | + .await | ||
| 550 | + .expect("first move"); | ||
| 551 | + let body = format!("csrf={csrf}&from={first}&to={third}&position=0"); | ||
| 552 | + let request = http::Request::post(format!("/tasks/{task_id}/move").as_str()) | ||
| 553 | + .header(CONTENT_TYPE, "application/x-www-form-urlencoded") | ||
| 554 | + .header(COOKIE, cookie_of(&token)) | ||
| 555 | + .header(ACCEPT, "application/json") | ||
| 556 | + .body(Body::from(body)) | ||
| 557 | + .expect("request"); | ||
| 558 | + let response = router(state.clone()).handle(request).await; | ||
| 559 | + assert_eq!(response.status(), 409); | ||
| 560 | + let bytes = to_bytes(response.into_body(), 4096).await.expect("body"); | ||
| 561 | + let answer: serde_json::Value = serde_json::from_slice(&bytes).expect("json"); | ||
| 562 | + assert_eq!(answer["error"], "moved_already"); | ||
| 563 | + assert!(answer["message"].as_str().is_some_and(|m| !m.is_empty())); | ||
| 564 | + } | ||
| 565 | +} | ||
crates/iz-web/src/views/board.rsadded+358 -0
| @@ -0,0 +1,358 @@ | |||
| 1 | +//! The components of the board page: the section with its toolbar, the filter bar, the columns, the | ||
| 2 | +//! cards and the new-task form. Each write control is rendered only for a member; a viewer gets the | ||
| 3 | +//! same cards with no control on them. | ||
| 4 | +//! | ||
| 5 | +//! Chips take their colour from a fixed palette (`tone-0` to `tone-7`), chosen by the project's | ||
| 6 | +//! position or its stored colour name. No text from a user becomes a class or a style. | ||
| 7 | + | ||
| 8 | +use iz_core::store::board::Tag; | ||
| 9 | +use iz_core::store::tasks::Card; | ||
| 10 | +use iz_core::zones::utc_to_local; | ||
| 11 | +use jiff::tz::TimeZone; | ||
| 12 | +use topcoat::Result; | ||
| 13 | +use topcoat::view::{View, component, view}; | ||
| 14 | + | ||
| 15 | +use crate::i18n::Lang; | ||
| 16 | +use crate::i18n::board::{K, column_title, subtasks, t}; | ||
| 17 | +use crate::pages::board::{BoardPage, Filters, NewForm, board_url}; | ||
| 18 | +use crate::views::{alert, notice}; | ||
| 19 | + | ||
| 20 | +/// Number of palette tones a project chip can take. | ||
| 21 | +const TONES: usize = 8; | ||
| 22 | + | ||
| 23 | +/// The palette tone of a project: the stored colour name `cN` when it names one, else the project's | ||
| 24 | +/// place in the board's list, so each project keeps its colour across the page. | ||
| 25 | +pub fn tone(tags: &[Tag], tag_id: &str) -> usize { | ||
| 26 | + let Some(index) = tags.iter().position(|t| t.id == tag_id) else { | ||
| 27 | + return 0; | ||
| 28 | + }; | ||
| 29 | + let named = tags[index] | ||
| 30 | + .color | ||
| 31 | + .as_deref() | ||
| 32 | + .and_then(|color| color.strip_prefix('c')) | ||
| 33 | + .and_then(|n| n.parse::<usize>().ok()) | ||
| 34 | + .filter(|n| *n < TONES); | ||
| 35 | + named.unwrap_or(index % TONES) | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +/// The value of an attribute that is present only when `on`. | ||
| 39 | +fn flag(on: bool) -> Option<&'static str> { | ||
| 40 | + on.then_some("") | ||
| 41 | +} | ||
| 42 | + | ||
| 43 | +/// The local clock of a meeting in the viewer's zone, as `HH:MM`. `None` when the stored value does | ||
| 44 | +/// not parse, which the store never writes. | ||
| 45 | +fn clock_of(meeting: &str, zone: &TimeZone) -> Option<String> { | ||
| 46 | + let at = iz_core::clock::timestamp_of(meeting).ok()?; | ||
| 47 | + let local = utc_to_local(zone, at); | ||
| 48 | + Some(format!("{:02}:{:02}", local.hour(), local.minute())) | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +/// The section of the board page: the toolbar, the notices, the new-task form, the filters and the | ||
| 52 | +/// columns. The section carries the live stream address, the CSRF token for `board.js`, and (for a | ||
| 53 | +/// member) the marker that turns on drag and drop. | ||
| 54 | +#[component] | ||
| 55 | +pub async fn board_content(page: &BoardPage) -> Result<impl View> { | ||
| 56 | + let lang = page.lang; | ||
| 57 | + let overdue = page.view.overdue; | ||
| 58 | + let blocked = page.view.blocked; | ||
| 59 | + let shown: usize = page.view.columns.iter().map(|c| c.cards.len()).sum(); | ||
| 60 | + let nothing_matches = shown == 0 && page.filters.active(); | ||
| 61 | + Ok(view! { | ||
| 62 | + <section class="board" data-live="/board/live" | ||
| 63 | + data-board-write=(flag(page.can_write)) | ||
| 64 | + data-csrf=(page.viewer.csrf.as_str()) | ||
| 65 | + data-msg-failed=(t(lang, K::MoveFailed))> | ||
| 66 | + <div class="board-toolbar"> | ||
| 67 | + <div class="board-summary"> | ||
| 68 | + if overdue > 0 { | ||
| 69 | + <span class="chip overdue">(format!("{} {overdue}", t(lang, K::Overdue)))</span> | ||
| 70 | + } | ||
| 71 | + if blocked > 0 { | ||
| 72 | + <span class="chip blocked">(format!("{} {blocked}", t(lang, K::Blocked)))</span> | ||
| 73 | + } | ||
| 74 | + </div> | ||
| 75 | + if page.can_write { | ||
| 76 | + <a class="button primary" href=(board_url(&page.filters, &[("new", "1")]))>(t(lang, K::NewTask))</a> | ||
| 77 | + } | ||
| 78 | + </div> | ||
| 79 | + if let Some(key) = page.alert { | ||
| 80 | + alert(message: t(lang, key)) | ||
| 81 | + } | ||
| 82 | + if let Some(text) = page.notice { | ||
| 83 | + notice(message: text) | ||
| 84 | + } | ||
| 85 | + if page.can_write { | ||
| 86 | + <p class="muted">(t(lang, K::DragHint))</p> | ||
| 87 | + } else { | ||
| 88 | + <p class="muted">(t(lang, K::ReadOnly))</p> | ||
| 89 | + } | ||
| 90 | + if nothing_matches { | ||
| 91 | + <p class="muted">(t(lang, K::NoMatches))</p> | ||
| 92 | + } | ||
| 93 | + if let Some(form) = page.new_form.as_ref() { | ||
| 94 | + new_task_form(page: page, form: form) | ||
| 95 | + } | ||
| 96 | + filter_bar(page: page) | ||
| 97 | + <div class="columns"> | ||
| 98 | + for column in page.view.columns.iter() { | ||
| 99 | + column_block(page: page, column: column) | ||
| 100 | + } | ||
| 101 | + </div> | ||
| 102 | + </section> | ||
| 103 | + }) | ||
| 104 | +} | ||
| 105 | + | ||
| 106 | +/// The filter bar: project, assignee, sort and search, sent as a GET form to the board. Without | ||
| 107 | +/// JavaScript the form still works; with it, `nav.js` takes the submit. | ||
| 108 | +#[component] | ||
| 109 | +pub async fn filter_bar(page: &BoardPage) -> Result<impl View> { | ||
| 110 | + let lang = page.lang; | ||
| 111 | + let filters: &Filters = &page.filters; | ||
| 112 | + let active = filters.active(); | ||
| 113 | + Ok(view! { | ||
| 114 | + <form class="filters" method="get" action="/"> | ||
| 115 | + <div class="field"> | ||
| 116 | + <label for="f-tag">(t(lang, K::FilterProject))</label> | ||
| 117 | + <select id="f-tag" name="tag"> | ||
| 118 | + <option value="" selected=(flag(filters.tag.is_empty()))>(t(lang, K::FilterAllProjects))</option> | ||
| 119 | + for tag in page.tags.iter() { | ||
| 120 | + <option value=(tag.id.as_str()) selected=(flag(filters.tag == tag.id))>(tag.name.as_str())</option> | ||
| 121 | + } | ||
| 122 | + </select> | ||
| 123 | + </div> | ||
| 124 | + <div class="field"> | ||
| 125 | + <label for="f-assignee">(t(lang, K::FilterAssignee))</label> | ||
| 126 | + <select id="f-assignee" name="assignee"> | ||
| 127 | + <option value="" selected=(flag(filters.assignee.is_empty()))>(t(lang, K::FilterAnyone))</option> | ||
| 128 | + <option value="none" selected=(flag(filters.assignee == "none"))>(t(lang, K::FilterNobody))</option> | ||
| 129 | + for member in page.members.iter() { | ||
| 130 | + <option value=(member.sub.as_str()) selected=(flag(filters.assignee == member.sub))>(member.name.as_str())</option> | ||
| 131 | + } | ||
| 132 | + </select> | ||
| 133 | + </div> | ||
| 134 | + <div class="field"> | ||
| 135 | + <label for="f-sort">(t(lang, K::FilterSort))</label> | ||
| 136 | + <select id="f-sort" name="sort"> | ||
| 137 | + <option value="deadline" selected=(flag(filters.sort == "deadline"))>(t(lang, K::SortDeadline))</option> | ||
| 138 | + <option value="created" selected=(flag(filters.sort == "created"))>(t(lang, K::SortCreated))</option> | ||
| 139 | + <option value="title" selected=(flag(filters.sort == "title"))>(t(lang, K::SortTitle))</option> | ||
| 140 | + </select> | ||
| 141 | + </div> | ||
| 142 | + <div class="field field-search"> | ||
| 143 | + <label for="f-q">(t(lang, K::FilterSearch))</label> | ||
| 144 | + <input id="f-q" type="search" name="q" value=(filters.query.as_str()) placeholder=(t(lang, K::SearchHint))> | ||
| 145 | + </div> | ||
| 146 | + <div class="filters-actions"> | ||
| 147 | + <button class="button" type="submit">(t(lang, K::Apply))</button> | ||
| 148 | + if active { | ||
| 149 | + <a class="button ghost" href="/">(t(lang, K::ClearFilters))</a> | ||
| 150 | + } | ||
| 151 | + </div> | ||
| 152 | + </form> | ||
| 153 | + }) | ||
| 154 | +} | ||
| 155 | + | ||
| 156 | +/// One column: its name and count, then its cards in order. The list is the drop target of the | ||
| 157 | +/// drag and drop, and says which column it is. | ||
| 158 | +#[component] | ||
| 159 | +pub async fn column_block( | ||
| 160 | + page: &BoardPage, | ||
| 161 | + column: &iz_core::store::tasks::ColumnCards, | ||
| 162 | +) -> Result<impl View> { | ||
| 163 | + let lang = page.lang; | ||
| 164 | + let column_id = column.column.id.as_str(); | ||
| 165 | + let heading_id = format!("col-{column_id}"); | ||
| 166 | + let title = column_title(lang, &column.column.name); | ||
| 167 | + let count = column.cards.len(); | ||
| 168 | + Ok(view! { | ||
| 169 | + <section class="board-column" aria-labelledby=(heading_id.as_str())> | ||
| 170 | + <header class="board-column-head"> | ||
| 171 | + <h2 id=(heading_id.as_str())>(title)</h2> | ||
| 172 | + <span class="muted">(count)</span> | ||
| 173 | + </header> | ||
| 174 | + <ol class="column-cards" data-column-id=(column_id)> | ||
| 175 | + if column.cards.is_empty() { | ||
| 176 | + <li class="muted">(t(lang, K::NoTasks))</li> | ||
| 177 | + } | ||
| 178 | + for card in column.cards.iter() { | ||
| 179 | + task_card(page: page, card: card) | ||
| 180 | + } | ||
| 181 | + </ol> | ||
| 182 | + </section> | ||
| 183 | + }) | ||
| 184 | +} | ||
| 185 | + | ||
| 186 | +/// One card. Its header is the key and the title; its chips are the project, the deadline with its | ||
| 187 | +/// overdue mark, the blocked mark and the subtask count; its avatars are the assignees. A member also | ||
| 188 | +/// gets the move form (the keyboard way to move, and the form behind the drag) and the delete form. | ||
| 189 | +#[component] | ||
| 190 | +pub async fn task_card(page: &BoardPage, card: &Card) -> Result<impl View> { | ||
| 191 | + let lang = page.lang; | ||
| 192 | + let task = &card.task; | ||
| 193 | + let id = task.id.as_str(); | ||
| 194 | + let current = task.column_id.as_str(); | ||
| 195 | + let next = page.next.as_str(); | ||
| 196 | + let tone_class = format!("chip tone-{}", tone(&page.tags, &task.tag_id)); | ||
| 197 | + let deadline = task.deadline.map(|day| day.to_string()); | ||
| 198 | + let clock = task | ||
| 199 | + .meeting_at | ||
| 200 | + .as_deref() | ||
| 201 | + .and_then(|meeting| clock_of(meeting, &page.zone)); | ||
| 202 | + let due = match (&deadline, &clock) { | ||
| 203 | + (Some(day), Some(time)) => Some(format!("{day} {time}")), | ||
| 204 | + (Some(day), None) => Some(day.clone()), | ||
| 205 | + _ => None, | ||
| 206 | + }; | ||
| 207 | + let has_subtasks = card.subtasks_total > 0; | ||
| 208 | + let subtask_text = subtasks(lang, card.subtasks_done, card.subtasks_total); | ||
| 209 | + let move_id = format!("mv-{id}"); | ||
| 210 | + let targets: Vec<(&str, String)> = page | ||
| 211 | + .view | ||
| 212 | + .columns | ||
| 213 | + .iter() | ||
| 214 | + .filter(|c| c.column.id != current) | ||
| 215 | + .map(|c| (c.column.id.as_str(), column_title(lang, &c.column.name))) | ||
| 216 | + .collect(); | ||
| 217 | + let can_move = page.can_write && !targets.is_empty(); | ||
| 218 | + let card_class = if task.done_at.is_some() { | ||
| 219 | + "task-card is-done" | ||
| 220 | + } else { | ||
| 221 | + "task-card" | ||
| 222 | + }; | ||
| 223 | + let draggable = page.can_write.then_some("true"); | ||
| 224 | + let deadline_attr = deadline.clone().unwrap_or_default(); | ||
| 225 | + let avatar_src: Vec<(String, String)> = card | ||
| 226 | + .assignees | ||
| 227 | + .iter() | ||
| 228 | + .map(|person| (format!("/avatar/{}", person.sub), person.name.clone())) | ||
| 229 | + .collect(); | ||
| 230 | + let move_action = format!("/tasks/{id}/move"); | ||
| 231 | + let delete_action = format!("/tasks/{id}/delete"); | ||
| 232 | + Ok(view! { | ||
| 233 | + <li class=(card_class) data-task-id=(id) data-column-id=(current) draggable=(draggable)> | ||
| 234 | + <p class="task-key">(task.key.as_str())</p> | ||
| 235 | + <h3 class="task-title">(task.title.as_str())</h3> | ||
| 236 | + <div class="task-meta"> | ||
| 237 | + <span class=(tone_class.as_str())>(page.tags.iter().find(|t| t.id == task.tag_id).map_or("", |t| t.name.as_str()))</span> | ||
| 238 | + if let Some(due) = due { | ||
| 239 | + <span>(t(lang, K::Due)) " " <time datetime=(deadline_attr.as_str())>(due.as_str())</time></span> | ||
| 240 | + } | ||
| 241 | + if card.overdue { | ||
| 242 | + <span class="chip overdue">(t(lang, K::Overdue))</span> | ||
| 243 | + } | ||
| 244 | + if card.blocked { | ||
| 245 | + <span class="chip blocked">(t(lang, K::Blocked))</span> | ||
| 246 | + } | ||
| 247 | + if has_subtasks { | ||
| 248 | + <span class="chip">(subtask_text.as_str())</span> | ||
| 249 | + } | ||
| 250 | + </div> | ||
| 251 | + if !avatar_src.is_empty() { | ||
| 252 | + <ul class="avatars" aria-label="Assignees"> | ||
| 253 | + for (src, name) in avatar_src.iter() { | ||
| 254 | + <li><img class="avatar" src=(src.as_str()) alt=(name.as_str()) width="26" height="26" loading="lazy"></li> | ||
| 255 | + } | ||
| 256 | + </ul> | ||
| 257 | + } | ||
| 258 | + if can_move { | ||
| 259 | + <form class="task-actions" method="post" action=(move_action.as_str())> | ||
| 260 | + <input type="hidden" name="csrf" value=(page.viewer.csrf.as_str())> | ||
| 261 | + <input type="hidden" name="from" value=(current)> | ||
| 262 | + <input type="hidden" name="next" value=(next)> | ||
| 263 | + <div class="field"> | ||
| 264 | + <label for=(move_id.as_str())>(t(lang, K::MoveTo))</label> | ||
| 265 | + <select id=(move_id.as_str()) name="to"> | ||
| 266 | + for (target_id, target_name) in targets.iter() { | ||
| 267 | + <option value=(*target_id)>(target_name.as_str())</option> | ||
| 268 | + } | ||
| 269 | + </select> | ||
| 270 | + </div> | ||
| 271 | + <button class="button" type="submit">(t(lang, K::Move))</button> | ||
| 272 | + </form> | ||
| 273 | + } | ||
| 274 | + if page.can_write { | ||
| 275 | + <form class="task-actions" method="post" action=(delete_action.as_str())> | ||
| 276 | + <input type="hidden" name="csrf" value=(page.viewer.csrf.as_str())> | ||
| 277 | + <input type="hidden" name="next" value=(next)> | ||
| 278 | + <button class="button danger ghost" type="submit">(t(lang, K::Delete))</button> | ||
| 279 | + </form> | ||
| 280 | + } | ||
| 281 | + </li> | ||
| 282 | + }) | ||
| 283 | +} | ||
| 284 | + | ||
| 285 | +/// The new-task form, shown above the board for `?new=1`. A refused try shows its message above the | ||
| 286 | +/// fields, and keeps what was typed. | ||
| 287 | +#[component] | ||
| 288 | +pub async fn new_task_form(page: &BoardPage, form: &NewForm) -> Result<impl View> { | ||
| 289 | + let lang = page.lang; | ||
| 290 | + let next = board_url(&page.filters, &[]); | ||
| 291 | + Ok(view! { | ||
| 292 | + <section class="card new-task" aria-labelledby="new-task-heading"> | ||
| 293 | + <h2 id="new-task-heading">(t(lang, K::NewTaskHeading))</h2> | ||
| 294 | + if let Some(key) = form.error { | ||
| 295 | + alert(message: t(lang, key)) | ||
| 296 | + } | ||
| 297 | + <form class="new-task" method="post" action="/tasks"> | ||
| 298 | + <input type="hidden" name="csrf" value=(page.viewer.csrf.as_str())> | ||
| 299 | + <input type="hidden" name="next" value=(next.as_str())> | ||
| 300 | + <div class="new-task-grid"> | ||
| 301 | + <div class="field field-wide"> | ||
| 302 | + <label for="nt-title">(t(lang, K::FieldTitle))</label> | ||
| 303 | + <input id="nt-title" name="title" maxlength="200" required="" value=(form.title.as_str())> | ||
| 304 | + </div> | ||
| 305 | + <div class="field"> | ||
| 306 | + <label for="nt-column">(t(lang, K::FieldColumn))</label> | ||
| 307 | + <select id="nt-column" name="column"> | ||
| 308 | + for column in page.view.columns.iter() { | ||
| 309 | + <option value=(column.column.id.as_str()) selected=(flag(form.column == column.column.id))>(column_title(lang, &column.column.name))</option> | ||
| 310 | + } | ||
| 311 | + </select> | ||
| 312 | + </div> | ||
| 313 | + <div class="field"> | ||
| 314 | + <label for="nt-tag">(t(lang, K::FieldProject))</label> | ||
| 315 | + <select id="nt-tag" name="tag"> | ||
| 316 | + for tag in page.tags.iter() { | ||
| 317 | + <option value=(tag.id.as_str()) selected=(flag(form.tag == tag.id))>(tag.name.as_str())</option> | ||
| 318 | + } | ||
| 319 | + </select> | ||
| 320 | + </div> | ||
| 321 | + <div class="field"> | ||
| 322 | + <label for="nt-deadline">(t(lang, K::FieldDeadline))</label> | ||
| 323 | + <input id="nt-deadline" type="date" name="deadline" value=(form.deadline.as_str())> | ||
| 324 | + <p class="field-hint">(t(lang, K::DeadlineHint))</p> | ||
| 325 | + </div> | ||
| 326 | + <div class="field field-wide"> | ||
| 327 | + <label for="nt-description">(t(lang, K::FieldDescription))</label> | ||
| 328 | + <textarea id="nt-description" name="description">(form.description.as_str())</textarea> | ||
| 329 | + </div> | ||
| 330 | + </div> | ||
| 331 | + <div class="new-task-actions"> | ||
| 332 | + <button class="button primary" type="submit">(t(lang, K::CreateTask))</button> | ||
| 333 | + <a class="button ghost" href=(next.as_str())>(t(lang, K::Cancel))</a> | ||
| 334 | + </div> | ||
| 335 | + </form> | ||
| 336 | + </section> | ||
| 337 | + }) | ||
| 338 | +} | ||
| 339 | + | ||
| 340 | +/// The sign-in card for a visitor. For someone who has an account but no access, the card says so | ||
| 341 | +/// and shows no sign-in button, so the page does not loop through sign-in. | ||
| 342 | +#[component] | ||
| 343 | +pub async fn signed_out_card(lang: Lang, no_access: bool) -> Result<impl View> { | ||
| 344 | + let shell_t = crate::i18n::shell::t; | ||
| 345 | + Ok(view! { | ||
| 346 | + <section class="card"> | ||
| 347 | + <p class="kicker">"iz"</p> | ||
| 348 | + if no_access { | ||
| 349 | + <h1>(shell_t(lang, crate::i18n::shell::K::NoAccessTitle))</h1> | ||
| 350 | + <p>(shell_t(lang, crate::i18n::shell::K::NoAccessBody))</p> | ||
| 351 | + } else { | ||
| 352 | + <h1>(shell_t(lang, crate::i18n::shell::K::SignedOutTitle))</h1> | ||
| 353 | + <p>(shell_t(lang, crate::i18n::shell::K::SignedOutBody))</p> | ||
| 354 | + <a class="button primary" href="/auth/login">(shell_t(lang, crate::i18n::shell::K::SignIn))</a> | ||
| 355 | + } | ||
| 356 | + </section> | ||
| 357 | + }) | ||
| 358 | +} | ||
crates/iz-web/src/views/mod.rsmodified+18 -3
| @@ -4,7 +4,11 @@ | |||
| 4 | //! emits an inline script, style or event handler; see `security.rs`. | 4 | //! emits an inline script, style or event handler; see `security.rs`. |
| 5 | 5 | ||
| 6 | use topcoat::Result; | 6 | use topcoat::Result; |
| 7 | -use topcoat::view::{Child, View, component, view}; | 7 | +use topcoat::context::Cx; |
| 8 | +use topcoat::router::response::{IntoResponse, Response}; | ||
| 9 | +use topcoat::view::{Child, View, ViewExt, component, view}; | ||
| 10 | + | ||
| 11 | +pub mod board; | ||
| 8 | 12 | ||
| 9 | use crate::assets::{MAIN_CSS_HREF, NAV_JS_HREF, PAGES_JS_HREF}; | 13 | use crate::assets::{MAIN_CSS_HREF, NAV_JS_HREF, PAGES_JS_HREF}; |
| 10 | use crate::i18n::Lang; | 14 | use crate::i18n::Lang; |
| @@ -22,7 +26,8 @@ pub struct ViewerInfo { | |||
| 22 | } | 26 | } |
| 23 | 27 | ||
| 24 | /// The HTML document around a page. `title` is the page's own title; the document title adds the | 28 | /// The HTML document around a page. `title` is the page's own title; the document title adds the |
| 25 | -/// app name. `child` is the page, placed in `<main>`. | 29 | +/// app name. `child` is the page, placed in `<main>`. `page_script` is the one script of this page |
| 30 | +/// (for example `board.js`), or `None`; it is loaded with `defer` and only on the page that needs it. | ||
| 26 | /// | 31 | /// |
| 27 | /// The topbar has the wordmark on the left, the service switcher in the middle (empty for now) and | 32 | /// The topbar has the wordmark on the left, the service switcher in the middle (empty for now) and |
| 28 | /// the viewer's name on the right. `nav.js` reads the restart text from `<body data-restart-text>`. | 33 | /// the viewer's name on the right. `nav.js` reads the restart text from `<body data-restart-text>`. |
| @@ -31,6 +36,7 @@ pub async fn shell( | |||
| 31 | title: &str, | 36 | title: &str, |
| 32 | lang: Lang, | 37 | lang: Lang, |
| 33 | viewer: Option<&ViewerInfo>, | 38 | viewer: Option<&ViewerInfo>, |
| 39 | + page_script: Option<&str>, | ||
| 34 | #[default] child: Child<'_>, | 40 | #[default] child: Child<'_>, |
| 35 | ) -> Result<impl View> { | 41 | ) -> Result<impl View> { |
| 36 | let document_title = format!("{title} \u{b7} iz"); | 42 | let document_title = format!("{title} \u{b7} iz"); |
| @@ -44,6 +50,9 @@ pub async fn shell( | |||
| 44 | <link rel="stylesheet" href=(MAIN_CSS_HREF)> | 50 | <link rel="stylesheet" href=(MAIN_CSS_HREF)> |
| 45 | <script src=(NAV_JS_HREF) defer=""></script> | 51 | <script src=(NAV_JS_HREF) defer=""></script> |
| 46 | <script src=(PAGES_JS_HREF) defer=""></script> | 52 | <script src=(PAGES_JS_HREF) defer=""></script> |
| 53 | + if let Some(src) = page_script { | ||
| 54 | + <script src=(src) defer=""></script> | ||
| 55 | + } | ||
| 47 | </head> | 56 | </head> |
| 48 | <body data-restart-text=(t(lang, K::ServerRestarting))> | 57 | <body data-restart-text=(t(lang, K::ServerRestarting))> |
| 49 | <a class="skip-link" href="#main">(t(lang, K::SkipToContent))</a> | 58 | <a class="skip-link" href="#main">(t(lang, K::SkipToContent))</a> |
| @@ -93,7 +102,6 @@ pub async fn message_page( | |||
| 93 | } | 102 | } |
| 94 | 103 | ||
| 95 | /// An error message for a failed action. Forms show it above their fields. | 104 | /// An error message for a failed action. Forms show it above their fields. |
| 96 | -#[allow(dead_code)] // The first form that can fail a check uses it. | ||
| 97 | #[component] | 105 | #[component] |
| 98 | pub async fn alert(message: &str) -> Result<impl View> { | 106 | pub async fn alert(message: &str) -> Result<impl View> { |
| 99 | Ok(view! { <div class="alert" role="alert">(message)</div> }) | 107 | Ok(view! { <div class="alert" role="alert">(message)</div> }) |
| @@ -115,3 +123,10 @@ pub async fn empty_state(title: &str, #[default] child: Child<'_>) -> Result<imp | |||
| 115 | </section> | 123 | </section> |
| 116 | }) | 124 | }) |
| 117 | } | 125 | } |
| 126 | + | ||
| 127 | +/// Turns a rendered view into the response of a handler. For a handler that answers with a view on one | ||
| 128 | +/// path and with a redirect or JSON on another. | ||
| 129 | +pub async fn respond(cx: &Cx, view: impl View) -> Result<Response> { | ||
| 130 | + let handle = view.first().await?; | ||
| 131 | + handle.into_response(cx) | ||
| 132 | +} | ||
style/_board.scssadded+295 -0
| @@ -0,0 +1,295 @@ | |||
| 1 | +//! The board page: the filter bar, the columns with their cards, the card chips and avatars, the | ||
| 2 | +//! new-task form and the toast of a refused drag. Chip colours come from a fixed palette of eight | ||
| 3 | +//! tones; no user-written CSS reaches the page. | ||
| 4 | + | ||
| 5 | +// --- Palette of project tones (fixed, eight entries) ------------------------------------------- | ||
| 6 | + | ||
| 7 | +@mixin tone($n, $bg, $fg) { | ||
| 8 | + .tone-#{$n} { | ||
| 9 | + background: $bg; | ||
| 10 | + color: $fg; | ||
| 11 | + } | ||
| 12 | +} | ||
| 13 | + | ||
| 14 | +@include tone(0, #e6ebff, #2a43a8); | ||
| 15 | +@include tone(1, #e4f4ea, #1e6b35); | ||
| 16 | +@include tone(2, #fff4d6, #7a4f00); | ||
| 17 | +@include tone(3, #fdecea, #9b2219); | ||
| 18 | +@include tone(4, #efe6ff, #5a2a9e); | ||
| 19 | +@include tone(5, #e0f3f5, #1c6470); | ||
| 20 | +@include tone(6, #fbe9f3, #8c2a64); | ||
| 21 | +@include tone(7, #eeeeea, #3e4250); | ||
| 22 | + | ||
| 23 | +@media (prefers-color-scheme: dark) { | ||
| 24 | + :root:not([data-theme="light"]) { | ||
| 25 | + .tone-0 { background: #1f2a4f; color: #c2d0ff; } | ||
| 26 | + .tone-1 { background: #173424; color: #9fe0b4; } | ||
| 27 | + .tone-2 { background: #3a2e10; color: #f2c265; } | ||
| 28 | + .tone-3 { background: #3a1d1b; color: #ffb4ac; } | ||
| 29 | + .tone-4 { background: #2e2245; color: #d7c2ff; } | ||
| 30 | + .tone-5 { background: #15313a; color: #9fdbe6; } | ||
| 31 | + .tone-6 { background: #3a1d2c; color: #f3b3d3; } | ||
| 32 | + .tone-7 { background: #2a2d35; color: #d0d4dd; } | ||
| 33 | + } | ||
| 34 | +} | ||
| 35 | + | ||
| 36 | +:root[data-theme="dark"] { | ||
| 37 | + .tone-0 { background: #1f2a4f; color: #c2d0ff; } | ||
| 38 | + .tone-1 { background: #173424; color: #9fe0b4; } | ||
| 39 | + .tone-2 { background: #3a2e10; color: #f2c265; } | ||
| 40 | + .tone-3 { background: #3a1d1b; color: #ffb4ac; } | ||
| 41 | + .tone-4 { background: #2e2245; color: #d7c2ff; } | ||
| 42 | + .tone-5 { background: #15313a; color: #9fdbe6; } | ||
| 43 | + .tone-6 { background: #3a1d2c; color: #f3b3d3; } | ||
| 44 | + .tone-7 { background: #2a2d35; color: #d0d4dd; } | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +// --- Page ------------------------------------------------------------------------------------- | ||
| 48 | + | ||
| 49 | +.board { | ||
| 50 | + display: grid; | ||
| 51 | + gap: var(--space-4); | ||
| 52 | + width: 100%; | ||
| 53 | + padding: var(--space-4) var(--space-4) var(--space-8); | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +.board-toolbar { | ||
| 57 | + display: flex; | ||
| 58 | + flex-wrap: wrap; | ||
| 59 | + align-items: flex-end; | ||
| 60 | + justify-content: space-between; | ||
| 61 | + gap: var(--space-3); | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +.board-summary { | ||
| 65 | + display: flex; | ||
| 66 | + flex-wrap: wrap; | ||
| 67 | + align-items: center; | ||
| 68 | + gap: var(--space-2); | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +.filters { | ||
| 72 | + display: flex; | ||
| 73 | + flex-wrap: wrap; | ||
| 74 | + align-items: flex-end; | ||
| 75 | + gap: var(--space-3); | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +.filters .field { | ||
| 79 | + min-width: 9rem; | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +.filters .field-search { | ||
| 83 | + min-width: 14rem; | ||
| 84 | +} | ||
| 85 | + | ||
| 86 | +.filters .field label, | ||
| 87 | +.new-task label { | ||
| 88 | + margin-bottom: 0; | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +.filters-actions { | ||
| 92 | + display: flex; | ||
| 93 | + align-items: center; | ||
| 94 | + gap: var(--space-2); | ||
| 95 | +} | ||
| 96 | + | ||
| 97 | +// --- Columns and cards ------------------------------------------------------------------------ | ||
| 98 | + | ||
| 99 | +.columns { | ||
| 100 | + display: grid; | ||
| 101 | + grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); | ||
| 102 | + gap: var(--space-4); | ||
| 103 | + align-items: start; | ||
| 104 | +} | ||
| 105 | + | ||
| 106 | +.board-column { | ||
| 107 | + display: grid; | ||
| 108 | + gap: var(--space-2); | ||
| 109 | + padding: var(--space-3); | ||
| 110 | + min-height: 8rem; | ||
| 111 | + background: var(--surface-2); | ||
| 112 | + border: 1px solid var(--border); | ||
| 113 | + border-radius: var(--radius); | ||
| 114 | +} | ||
| 115 | + | ||
| 116 | +.board-column-head { | ||
| 117 | + display: flex; | ||
| 118 | + align-items: center; | ||
| 119 | + justify-content: space-between; | ||
| 120 | + gap: var(--space-2); | ||
| 121 | + padding: 0 var(--space-1); | ||
| 122 | + font-weight: 650; | ||
| 123 | +} | ||
| 124 | + | ||
| 125 | +.column-cards { | ||
| 126 | + display: grid; | ||
| 127 | + gap: var(--space-2); | ||
| 128 | + margin: 0; | ||
| 129 | + padding: 0; | ||
| 130 | + list-style: none; | ||
| 131 | + min-height: 3rem; | ||
| 132 | +} | ||
| 133 | + | ||
| 134 | +.column-cards.is-target { | ||
| 135 | + outline: 2px dashed var(--focus); | ||
| 136 | + outline-offset: 2px; | ||
| 137 | + border-radius: var(--radius-sm); | ||
| 138 | +} | ||
| 139 | + | ||
| 140 | +.task-card { | ||
| 141 | + display: grid; | ||
| 142 | + gap: var(--space-2); | ||
| 143 | + padding: var(--space-3); | ||
| 144 | + background: var(--surface); | ||
| 145 | + border: 1px solid var(--border); | ||
| 146 | + border-radius: var(--radius-sm); | ||
| 147 | + box-shadow: var(--shadow); | ||
| 148 | +} | ||
| 149 | + | ||
| 150 | +.task-card[draggable="true"] { | ||
| 151 | + cursor: grab; | ||
| 152 | +} | ||
| 153 | + | ||
| 154 | +.task-card.is-dragging { | ||
| 155 | + opacity: 0.5; | ||
| 156 | +} | ||
| 157 | + | ||
| 158 | +.task-card.is-done { | ||
| 159 | + opacity: 0.65; | ||
| 160 | +} | ||
| 161 | + | ||
| 162 | +.task-key { | ||
| 163 | + color: var(--muted); | ||
| 164 | + font-family: var(--font-mono); | ||
| 165 | + font-size: 0.8rem; | ||
| 166 | +} | ||
| 167 | + | ||
| 168 | +.task-title { | ||
| 169 | + margin: 0; | ||
| 170 | + font-size: 1rem; | ||
| 171 | + overflow-wrap: anywhere; | ||
| 172 | +} | ||
| 173 | + | ||
| 174 | +.task-meta { | ||
| 175 | + display: flex; | ||
| 176 | + flex-wrap: wrap; | ||
| 177 | + align-items: center; | ||
| 178 | + gap: var(--space-1); | ||
| 179 | + font-size: var(--text-sm); | ||
| 180 | + color: var(--muted); | ||
| 181 | +} | ||
| 182 | + | ||
| 183 | +.task-actions { | ||
| 184 | + display: flex; | ||
| 185 | + flex-wrap: wrap; | ||
| 186 | + align-items: flex-end; | ||
| 187 | + gap: var(--space-2); | ||
| 188 | + padding-top: var(--space-2); | ||
| 189 | + border-top: 1px solid var(--border); | ||
| 190 | +} | ||
| 191 | + | ||
| 192 | +.task-actions .field { | ||
| 193 | + flex: 1 1 8rem; | ||
| 194 | +} | ||
| 195 | + | ||
| 196 | +.task-actions .field label { | ||
| 197 | + font-size: 0.8rem; | ||
| 198 | +} | ||
| 199 | + | ||
| 200 | +.task-actions .button { | ||
| 201 | + min-height: 2.25rem; | ||
| 202 | +} | ||
| 203 | + | ||
| 204 | +// --- Chips and avatars ------------------------------------------------------------------------ | ||
| 205 | + | ||
| 206 | +.chip { | ||
| 207 | + display: inline-block; | ||
| 208 | + padding: 0.1rem var(--space-2); | ||
| 209 | + border-radius: 999px; | ||
| 210 | + background: var(--surface-2); | ||
| 211 | + color: var(--muted); | ||
| 212 | + font-size: 0.78rem; | ||
| 213 | + font-weight: 600; | ||
| 214 | + white-space: nowrap; | ||
| 215 | +} | ||
| 216 | + | ||
| 217 | +.chip.overdue { | ||
| 218 | + background: var(--danger-soft); | ||
| 219 | + color: var(--danger); | ||
| 220 | +} | ||
| 221 | + | ||
| 222 | +.chip.blocked { | ||
| 223 | + background: var(--warn-soft); | ||
| 224 | + color: var(--warn); | ||
| 225 | +} | ||
| 226 | + | ||
| 227 | +.avatars { | ||
| 228 | + display: flex; | ||
| 229 | + margin: 0; | ||
| 230 | + padding: 0; | ||
| 231 | + list-style: none; | ||
| 232 | +} | ||
| 233 | + | ||
| 234 | +.avatars li + li { | ||
| 235 | + margin-left: -0.4rem; | ||
| 236 | +} | ||
| 237 | + | ||
| 238 | +.avatar { | ||
| 239 | + display: block; | ||
| 240 | + width: 1.6rem; | ||
| 241 | + height: 1.6rem; | ||
| 242 | + border-radius: 50%; | ||
| 243 | + border: 2px solid var(--surface); | ||
| 244 | + background: var(--surface-2); | ||
| 245 | + object-fit: cover; | ||
| 246 | + font-size: 0.7rem; | ||
| 247 | +} | ||
| 248 | + | ||
| 249 | +// --- New task, notices, toast ----------------------------------------------------------------- | ||
| 250 | + | ||
| 251 | +.new-task { | ||
| 252 | + display: grid; | ||
| 253 | + gap: var(--space-3); | ||
| 254 | +} | ||
| 255 | + | ||
| 256 | +.new-task-grid { | ||
| 257 | + display: grid; | ||
| 258 | + grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr)); | ||
| 259 | + gap: var(--space-3); | ||
| 260 | +} | ||
| 261 | + | ||
| 262 | +.new-task-grid .field-wide { | ||
| 263 | + grid-column: 1 / -1; | ||
| 264 | +} | ||
| 265 | + | ||
| 266 | +.new-task-actions { | ||
| 267 | + display: flex; | ||
| 268 | + align-items: center; | ||
| 269 | + gap: var(--space-3); | ||
| 270 | +} | ||
| 271 | + | ||
| 272 | +.toast { | ||
| 273 | + position: fixed; | ||
| 274 | + left: 50%; | ||
| 275 | + bottom: var(--space-6); | ||
| 276 | + transform: translateX(-50%); | ||
| 277 | + max-width: min(90vw, 32rem); | ||
| 278 | + padding: var(--space-3) var(--space-4); | ||
| 279 | + background: var(--danger-soft); | ||
| 280 | + color: var(--danger); | ||
| 281 | + border: 1px solid var(--danger); | ||
| 282 | + border-radius: var(--radius-sm); | ||
| 283 | + box-shadow: var(--shadow-lift); | ||
| 284 | + z-index: 10; | ||
| 285 | +} | ||
| 286 | + | ||
| 287 | +@media (max-width: 720px) { | ||
| 288 | + .board { | ||
| 289 | + padding: var(--space-2) var(--space-2) var(--space-6); | ||
| 290 | + } | ||
| 291 | + | ||
| 292 | + .columns { | ||
| 293 | + grid-template-columns: 1fr; | ||
| 294 | + } | ||
| 295 | +} | ||
style/main.scssmodified+1 -0
| @@ -6,3 +6,4 @@ | |||
| 6 | @use "base"; | 6 | @use "base"; |
| 7 | @use "layout"; | 7 | @use "layout"; |
| 8 | @use "components"; | 8 | @use "components"; |
| 9 | +@use "board"; | ||