Skip to content

armgit / kanzo

Public Imported from GitHub
0

Self-hosted, sharable kanban for humans and agents. One 4.7 MB binary, 5 MB of RAM, 10 to 60 tokens per agent reply, starts in 3 ms, zero setup.

Give projects a colour from a fixed list

emanuele-emd946d75d34d2
diff --git a/src/app.js b/src/app.js
index fa1f477..7b52198 100644
--- a/src/app.js
+++ b/src/app.js
@@ -69,6 +69,7 @@ const ICONS = {
trash: '<path d="M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6M10 11v6M14 11v6"/>',
text: '<path d="M17 6H3M21 12H3M15 18H3"/>',
comment: '<path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/>',
+ check: '<path d="M20 6 9 17l-5-5"/>',
};
function icon(name, color) {
@@ -88,10 +89,24 @@ function toast(message) {
toastTimer = setTimeout(() => t.remove(), 3500);
}
-function projectColor(slug) {
+// The colours a project can be given; the names match PROJECT_COLORS in store.rs.
+const PROJECT_COLORS = {
+ gray: "#8e8e93", red: "#ef4444", orange: "#f97316", yellow: "#eab308", green: "#22c55e",
+ teal: "#14b8a6", blue: "#3b82f6", purple: "#a855f7", pink: "#ec4899",
+};
+
+// The colour picked for a project, or until then one chosen from its slug.
+function projectColorName(slug) {
+ const picked = state.board?.projects.find((p) => p.slug === slug)?.color;
+ if (PROJECT_COLORS[picked]) return picked;
+ const names = Object.keys(PROJECT_COLORS).filter((n) => n !== "gray");
let h = 0;
- for (const c of slug) h = (h * 31 + c.charCodeAt(0)) % 360;
- return `hsl(${h} 55% 52%)`;
+ for (const c of slug) h = (h * 31 + c.charCodeAt(0)) % 997;
+ return names[h % names.length];
+}
+
+function projectColor(slug) {
+ return PROJECT_COLORS[projectColorName(slug)];
}
function statusColor(status) {
@@ -283,15 +298,32 @@ function toggleProjectMenu(p, button) {
if (wasOpen) return;
state.menu = p.slug;
button.closest(".item").classList.add("menu-open");
- const remove = el("button", { class: "danger", role: "menuitem", onclick: () => { closeMenu(); deleteProject(p); } },
+ const swatches = el("div", { class: "swatches", role: "group", "aria-label": "Color" });
+ const drawSwatches = () => swatches.replaceChildren(...Object.entries(PROJECT_COLORS).map(([name, hex]) => {
+ const current = projectColorName(p.slug) === name;
+ return el("button", { class: "swatch", style: `background:${hex}`, title: name, "aria-label": name,
+ "aria-pressed": String(current), onclick: () => pickColor(p.slug, name).then(drawSwatches) },
+ current ? icon("check") : null);
+ }));
+ drawSwatches();
+ const remove = el("button", { class: "danger", onclick: () => { closeMenu(); deleteProject(p); } },
icon("trash"), "Delete project");
- const menu = el("div", { class: "menu", role: "menu" }, remove);
+ const menu = el("div", { class: "menu", role: "menu", tabindex: "-1" },
+ el("div", { class: "label" }, "Color"), swatches, el("div", { class: "sep" }), remove);
document.body.append(menu);
const r = button.getBoundingClientRect();
const below = r.bottom + 4 + menu.offsetHeight <= innerHeight;
menu.style.top = `${below ? r.bottom + 4 : r.top - 4 - menu.offsetHeight}px`;
menu.style.left = `${Math.max(8, Math.min(r.left, innerWidth - menu.offsetWidth - 8))}px`;
- remove.focus();
+ // Focus the menu itself, so Tab reaches its buttons without one looking selected.
+ menu.focus();
+}
+
+async function pickColor(slug, color) {
+ try {
+ await api("PATCH", `/projects/${encodeURIComponent(slug)}`, { color });
+ await loadBoard();
+ } catch (err) { toast(err.message); }
}
function closeMenu() {
diff --git a/src/index.html b/src/index.html
index 3094ad9..98b8239 100644
--- a/src/index.html
+++ b/src/index.html
@@ -78,6 +78,15 @@ aside {
}
.menu button:hover, .menu button:focus-visible { background: var(--hover); }
.menu button.danger { color: var(--danger); }
+.menu .label { color: var(--faint); font-size: 12px; padding: 4px 10px 0; }
+.menu .swatches { display: flex; gap: 6px; padding: 8px 10px 10px; }
+.menu .swatch {
+ width: 20px; height: 20px; padding: 0; border-radius: 50%; display: grid; place-items: center; flex: none;
+ color: #fff; transition: transform .1s;
+}
+.menu .swatch:hover, .menu .swatch:focus-visible { transform: scale(1.15); }
+.menu .swatch .icon svg { width: 13px; height: 13px; stroke-width: 3; }
+.menu .sep { height: 1px; background: var(--border); margin: 0 4px 6px; }
.menu button.danger:hover, .menu button.danger:focus-visible { background: var(--danger-bg); }
form.new-project { display: flex; flex-direction: column; gap: 6px; padding: 4px 2px 10px; }
form.new-project .row { display: flex; gap: 6px; margin-top: 2px; }
diff --git a/src/store.rs b/src/store.rs
index 0fa9703..5e07f38 100644
--- a/src/store.rs
+++ b/src/store.rs
@@ -13,7 +13,14 @@ use rusqlite::{Connection, OptionalExtension, Row, params};
use serde::Serialize;
/// Schema migrations, applied in order. Index + 1 is the `schema_version` they lead to.
-const MIGRATIONS: &[&str] = &[include_str!("schema.sql")];
+const MIGRATIONS: &[&str] = &[
+ include_str!("schema.sql"),
+ // 2: a colour picked for the project; NULL leaves the board to choose one.
+ "ALTER TABLE projects ADD COLUMN color TEXT;",
+];
+
+/// The colours a project can be given; the board maps each name to a shade.
+pub const PROJECT_COLORS: &[&str] = &["gray", "red", "orange", "yellow", "green", "teal", "blue", "purple", "pink"];
const NOW: &str = "strftime('%Y-%m-%dT%H:%M:%SZ', 'now')";
@@ -58,6 +65,8 @@ pub struct Project {
pub slug: String,
pub name: String,
pub repo: Option<String>,
+ /// One of `PROJECT_COLORS`, or `None` when never picked.
+ pub color: Option<String>,
pub created_at: String,
/// Tasks not in the last (done) column.
pub open: i64,
@@ -210,7 +219,7 @@ impl Store {
// Projects
- const PROJECT_SELECT: &str = "SELECT p.id, p.slug, p.name, p.repo, p.created_at,
+ const PROJECT_SELECT: &str = "SELECT p.id, p.slug, p.name, p.repo, p.color, p.created_at,
(SELECT count(*) FROM tasks t WHERE t.project_id = p.id AND t.status <> ?1),
(SELECT count(*) FROM tasks t WHERE t.project_id = p.id)
FROM projects p";
@@ -221,9 +230,10 @@ impl Store {
slug: r.get(1)?,
name: r.get(2)?,
repo: r.get(3)?,
- created_at: r.get(4)?,
- open: r.get(5)?,
- total: r.get(6)?,
+ color: r.get(4)?,
+ created_at: r.get(5)?,
+ open: r.get(6)?,
+ total: r.get(7)?,
})
}
@@ -307,6 +317,15 @@ impl Store {
self.find_project(&slug)
}
+ pub fn set_project_color(&self, slug: &str, color: &str) -> Result<Project> {
+ if !PROJECT_COLORS.contains(&color) {
+ return Err(Error::Invalid(format!("unknown color {color:?}; use one of: {}", PROJECT_COLORS.join(", "))));
+ }
+ let project = self.find_project(slug)?;
+ self.conn.execute("UPDATE projects SET color = ?1 WHERE id = ?2", params![color, project.id])?;
+ self.find_project(&project.slug)
+ }
+
/// Deletes a project with all its tasks and their comments; returns the project as it was.
pub fn delete_project(&self, slug: &str) -> Result<Project> {
let project = self.find_project(slug)?;
@@ -664,7 +683,9 @@ mod tests {
assert!(s.create_project("web", "", Some("me/api")).unwrap_err().to_string().contains("already linked"));
assert!(s.create_project("bad slug", "", None).is_err());
let web = s.create_project("web", "", None).unwrap();
- assert_eq!(web.name, "web");
+ assert_eq!((web.name.as_str(), web.color.as_deref()), ("web", None));
+ assert_eq!(s.set_project_color("web", "teal").unwrap().color.as_deref(), Some("teal"));
+ assert!(s.set_project_color("web", "#ff0000").is_err());
assert!(s.find_project("nope").unwrap_err().to_string().contains("api, web"));
}
diff --git a/src/web.rs b/src/web.rs
index 79b8955..3270a48 100644
--- a/src/web.rs
+++ b/src/web.rs
@@ -8,7 +8,7 @@ use axum::extract::{Path, Query, Request, State};
use axum::http::{HeaderValue, StatusCode, header};
use axum::middleware::{self, Next};
use axum::response::{Html, IntoResponse, Response};
-use axum::routing::{delete, get, post};
+use axum::routing::{get, patch, post};
use axum::{Json, Router};
use serde::{Deserialize, Serialize};
use serde_json::json;
@@ -122,7 +122,7 @@ fn router(home: Home, guard: Guard, shutdown: CancellationToken) -> Router {
.route("/api/changes", get(changes))
.route("/api/board", get(board))
.route("/api/projects", post(create_project))
- .route("/api/projects/{slug}", delete(delete_project))
+ .route("/api/projects/{slug}", patch(update_project).delete(delete_project))
.route("/api/tasks", post(create_task))
.route("/api/tasks/{id}", get(get_task).patch(update_task).delete(delete_task))
.route("/api/tasks/{id}/move", post(move_task))
@@ -277,6 +277,15 @@ async fn create_project(State(home): Shared, Json(p): Json<NewProject>) -> Respo
with_store(home, move |_, s| s.create_project(&p.slug, &p.name, p.repo.as_deref())).await
}
+#[derive(Deserialize)]
+struct ProjectPatch {
+ color: String,
+}
+
+async fn update_project(State(home): Shared, Path(slug): Path<String>, Json(p): Json<ProjectPatch>) -> Response {
+ with_store(home, move |_, s| s.set_project_color(&slug, &p.color)).await
+}
+
async fn delete_project(State(home): Shared, Path(slug): Path<String>) -> Response {
with_store(home, move |_, s| s.delete_project(&slug)).await
}