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.

Drag selected tasks together

emanuele-emc6568baeaedb
diff --git a/README.md b/README.md
index 49efbd5..4e5df87 100644
--- a/README.md
+++ b/README.md
@@ -60,7 +60,7 @@ kanzo
The board opens at http://localhost:4242. That's all the setup there is: the first run creates `~/kanzo`, and the whole board lives in it.
-`n` adds a task, `/` or `⌘K` searches every project, `⌘`-click or a drag on empty board space selects tasks to move, tag or delete together, `f` filters the board and `↵` keeps the filter, the list icon shows the same tasks as rows to sort and group, `Tab` moves to the description, `⌘↵` saves and closes. `Esc` leaves a description or tags with what you typed saved, and cancels other fields. In Chrome or Edge, **Install app** at the bottom of the sidebar makes the board an app of its own; on macOS `kanzo` then opens it instead of a tab, on the default port. In the app, `⌘1`–`⌘8` pick a project, `⌘9` the last one and `⌘0` all of them.
+`n` adds a task, `/` or `⌘K` searches every project, `⌘`-click or a drag on empty board space selects tasks to move, tag or delete together, and dragging one takes the rest along, `f` filters the board and `↵` keeps the filter, the list icon shows the same tasks as rows to sort and group, `Tab` moves to the description, `⌘↵` saves and closes. `Esc` leaves a description or tags with what you typed saved, and cancels other fields. In Chrome or Edge, **Install app** at the bottom of the sidebar makes the board an app of its own; on macOS `kanzo` then opens it instead of a tab, on the default port. In the app, `⌘1`–`⌘8` pick a project, `⌘9` the last one and `⌘0` all of them.
Drag the left edge of a task's panel to resize it, or expand it to the whole window; double-click the edge to reset it. The panel button beside search folds the sidebar to its icons. Drag a project there to reorder the list, for everyone on a shared board.
diff --git a/src/app.js b/src/app.js
index de7919d..cdac602 100644
--- a/src/app.js
+++ b/src/app.js
@@ -589,7 +589,7 @@ function renderColumns() {
}
// During a drag the DOM is being moved by hand; refresh once it ends.
- if (state.dragging || state.sweeping) return;
+ if (state.dragging || state.sweeping || state.settling) return;
const all = state.project === "all";
const humanOnly = isHumanOnly();
const query = filterQuery();
@@ -905,6 +905,79 @@ function plainText(md) {
.trim();
}
+// Dragging a selected card takes the others along: they fly behind it, and spread out where it lands.
+const MOTION = { duration: 180, easing: "ease-out" };
+const MOST_FLYING = 30;
+const STACK_TOP = 8;
+
+function calm() {
+ return matchMedia("(prefers-reduced-motion: reduce)").matches;
+}
+
+function inView(card) {
+ const r = card.getBoundingClientRect(), list = card.parentNode.getBoundingClientRect();
+ return r.width > 0 && r.bottom > list.top && r.top < list.bottom;
+}
+
+// The browser draws the dragged image, and only from what's on the page when the drag starts.
+function stackImage(card, count) {
+ const stack = el("div", { class: "stack", style: `width:${card.offsetWidth}px` },
+ card.cloneNode(true), el("span", { class: "stack-count" }, String(count)));
+ document.body.append(stack);
+ requestAnimationFrame(() => stack.remove());
+ return stack;
+}
+
+// A copy above the board, so that its column can't clip it.
+function fly(card, from, to, fade) {
+ const { width, height } = card.getBoundingClientRect();
+ const ghost = card.cloneNode(true);
+ ghost.classList.add("flying");
+ ghost.style.cssText = `left:${from.left}px;top:${from.top}px;width:${width}px;height:${height}px`;
+ document.body.append(ghost);
+ const end = `translate(${to.left - from.left}px,${to.top - from.top}px)`;
+ const flight = ghost.animate([{ transform: "none", opacity: 1 }, { transform: end, opacity: fade ? 0 : 1 }], MOTION);
+ return new Promise((done) => { flight.onfinish = () => { ghost.remove(); done(); }; });
+}
+
+// Makes a change to the board, then glides the cards it moved from where they were.
+function shift(change) {
+ const tops = new Map(calm() ? [] : [...$("#columns").querySelectorAll(".card:not(.gathered)")].filter(inView)
+ .map((c) => [c, c.getBoundingClientRect().top]));
+ change();
+ tops.forEach((top, c) => {
+ const r = c.getBoundingClientRect();
+ if (r.width && r.top !== top) c.animate([{ transform: `translateY(${top - r.top}px)` }, { transform: "none" }], MOTION);
+ });
+}
+
+function gather(group, grabbed) {
+ const to = grabbed.getBoundingClientRect();
+ const others = group.filter((c) => c !== grabbed);
+ if (!calm()) others.filter(inView).slice(0, MOST_FLYING).forEach((c) => fly(c, c.getBoundingClientRect(), to, true));
+ shift(() => {
+ grabbed.classList.add("dragging");
+ others.forEach((c) => c.classList.add("dragging", "gathered"));
+ });
+}
+
+// `place` puts the cards where they land. A refresh waits, as it would replace what's flying.
+async function spread(group, grabbed, from, place) {
+ state.settling = true;
+ shift(() => {
+ place();
+ group.forEach((c) => c.classList.remove("dragging", "gathered"));
+ });
+ const others = calm() ? [] : group.filter((c) => c !== grabbed && inView(c)).slice(0, MOST_FLYING);
+ const flying = calm() || !inView(grabbed) ? others : [...others, grabbed];
+ await Promise.all(flying.map((c) => {
+ const landed = fly(c, from, c.getBoundingClientRect(), false);
+ c.classList.add("landing");
+ return landed.then(() => c.classList.remove("landing"));
+ }));
+ state.settling = false;
+}
+
// In the list, a row: no drag to reorder, since a sorted list has no one position to drop into.
function card(t, showProject, row) {
const node = el("div", { class: "card" + (row ? " row" : "") + (state.task === t.id ? " open" : "") + (t.waiting_on ? " waiting" : "") + (state.selected.has(t.id) ? " selected" : ""),
@@ -921,15 +994,26 @@ function card(t, showProject, row) {
state.dragging = t.id;
e.dataTransfer.effectAllowed = "move";
e.dataTransfer.setData("text/plain", String(t.id));
- requestAnimationFrame(() => node.classList.add("dragging"));
+ const selected = state.selected.has(t.id) ? [...$("#columns").querySelectorAll(".card.selected")] : [];
+ const group = state.group = selected.length > 1 ? selected : null;
+ if (group) {
+ const r = node.getBoundingClientRect();
+ state.grip = { x: e.clientX - r.left, y: e.clientY - r.top };
+ e.dataTransfer.setDragImage(stackImage(node, group.length), state.grip.x, state.grip.y + STACK_TOP);
+ }
+ requestAnimationFrame(() => { if (group) gather(group, node); else node.classList.add("dragging"); });
});
- node.addEventListener("dragend", () => {
+ node.addEventListener("dragend", async () => {
node.classList.remove("dragging");
document.querySelectorAll(".drop-line").forEach((d) => d.remove());
state.dragging = null;
- // A drop reloads once the move is saved; a cancelled drag puts the card back.
- if (!state.dropped) loadBoard();
+ const { dropped, group } = state;
state.dropped = false;
+ state.group = null;
+ // A drop reloads once the move is saved; a cancelled drag puts the card back.
+ if (dropped) return;
+ if (group) await spread(group, node, node.getBoundingClientRect(), () => {});
+ loadBoard();
});
return node;
}
@@ -956,11 +1040,28 @@ function wireDrop(col, list, status) {
if (!id) return;
const after = cardAfter(e.clientY);
const dragged = document.querySelector(`.card[data-id="${id}"]`);
- if (dragged) list.insertBefore(dragged, line.parentNode === list ? line : null);
- line.remove();
+ const spot = line.parentNode === list ? line : null;
state.dropped = true;
if (fresh === id) fresh = null;
const before = after ? Number(after.dataset.id) : null;
+ const { group } = state;
+ if (group) {
+ const from = { left: e.clientX - state.grip.x, top: e.clientY - state.grip.y };
+ const ids = group.map((c) => Number(c.dataset.id));
+ const landed = spread(group, dragged, from, () => {
+ group.forEach((c) => list.insertBefore(c, spot));
+ line.remove();
+ });
+ try {
+ await api("POST", "/tasks/move", { ids, status, before });
+ if (ids.includes(state.task)) refreshTask();
+ } catch (err) { toast(err.message); }
+ await landed;
+ loadBoard();
+ return;
+ }
+ if (dragged) list.insertBefore(dragged, spot);
+ line.remove();
try {
await api("POST", `/tasks/${id}/move`, { status, before });
if (state.task === id) refreshTask();
diff --git a/src/index.html b/src/index.html
index ece3b8a..96f881e 100644
--- a/src/index.html
+++ b/src/index.html
@@ -237,6 +237,15 @@ html:not([data-hide~="waiting"]) .card.waiting:not(:hover) { opacity: .6; }
.bulk .field { width: 120px; padding: 5px 12px; }
.bulk select { text-transform: capitalize; }
.card.dragging { opacity: .4; }
+.card.gathered { display: none; }
+.card.landing { visibility: hidden; }
+.card.flying { position: fixed; z-index: 20; margin: 0; pointer-events: none; }
+.stack { position: fixed; left: -9999px; top: 0; isolation: isolate; box-sizing: content-box; padding: 8px 10px 10px 0; }
+.stack .card { position: relative; box-sizing: border-box; }
+.stack::before, .stack::after { content: ""; position: absolute; z-index: -1; background: var(--card-hover); border: 1px solid var(--active); border-radius: 14px; }
+.stack::before { top: 18px; left: 10px; right: 0; bottom: 0; }
+.stack::after { top: 13px; left: 5px; right: 5px; bottom: 5px; }
+.stack-count { position: absolute; top: 0; right: 2px; min-width: 22px; padding: 2px 6px; border-radius: 99px; background: var(--link); color: #fff; font-size: 12px; font-weight: 600; text-align: center; }
.card .head { display: flex; align-items: flex-start; gap: 10px; }
.card .title { overflow-wrap: anywhere; flex: 1; min-width: 0; }
.card .num {
diff --git a/src/store.rs b/src/store.rs
index 0757a27..8205f50 100644
--- a/src/store.rs
+++ b/src/store.rs
@@ -833,51 +833,58 @@ impl Store {
pub fn move_task(&self, id: i64, status: &str, before: Option<i64>) -> Result<Task> {
self.check_status(status)?;
- self.write(|c| {
- let current = self.get_task(id)?;
- let before = before.filter(|b| *b != id);
- let anchor: Option<(i64, f64)> = match before {
- Some(b) => c
- .query_row("SELECT position FROM tasks WHERE id = ?1 AND status = ?2", params![b, status], |r| {
- r.get(0)
- })
- .optional()?
- .map(|p| (b, p)),
- None => None,
- };
- let position = match anchor {
- None => Self::end_of_column(c, status, id)?,
- Some((before, mut next)) => {
- let prev_of = |next: f64| -> Result<Option<f64>> {
- Ok(c.query_row(
- "SELECT max(position) FROM tasks WHERE status = ?1 AND position < ?2 AND id <> ?3",
- params![status, next, id],
- |r| r.get(0),
- )?)
- };
- let mut prev = prev_of(next)?;
- if prev.is_some_and(|p| next - p < 1e-9) {
- // Out of float room between two neighbours.
- Self::renumber(c, status)?;
- next = c.query_row("SELECT position FROM tasks WHERE id = ?1", [before], |r| r.get(0))?;
- prev = prev_of(next)?;
- }
- match prev {
- Some(p) => (p + next) / 2.0,
- None => next - 1.0,
- }
- }
- };
- let touched = if current.status != status { format!(", updated_at = {NOW}") } else { String::new() };
- c.execute(
- &format!("UPDATE tasks SET status = ?1, position = ?2{touched} WHERE id = ?3"),
- params![status, position, id],
- )?;
- Ok(())
- })?;
+ self.write(|c| self.place(c, id, status, before))?;
self.get_task(id)
}
+ /// In one write, so nobody sees the group half moved. They keep the order of `ids`.
+ pub fn move_tasks(&self, ids: &[i64], status: &str, before: Option<i64>) -> Result<()> {
+ self.check_status(status)?;
+ let before = before.filter(|b| !ids.contains(b));
+ self.write(|c| ids.iter().try_for_each(|&id| self.place(c, id, status, before)))
+ }
+
+ fn place(&self, c: &Connection, id: i64, status: &str, before: Option<i64>) -> Result<()> {
+ let current = self.get_task(id)?;
+ let before = before.filter(|b| *b != id);
+ let anchor: Option<(i64, f64)> = match before {
+ Some(b) => c
+ .query_row("SELECT position FROM tasks WHERE id = ?1 AND status = ?2", params![b, status], |r| r.get(0))
+ .optional()?
+ .map(|p| (b, p)),
+ None => None,
+ };
+ let position = match anchor {
+ None => Self::end_of_column(c, status, id)?,
+ Some((before, mut next)) => {
+ let prev_of = |next: f64| -> Result<Option<f64>> {
+ Ok(c.query_row(
+ "SELECT max(position) FROM tasks WHERE status = ?1 AND position < ?2 AND id <> ?3",
+ params![status, next, id],
+ |r| r.get(0),
+ )?)
+ };
+ let mut prev = prev_of(next)?;
+ if prev.is_some_and(|p| next - p < 1e-9) {
+ // Out of float room between two neighbours.
+ Self::renumber(c, status)?;
+ next = c.query_row("SELECT position FROM tasks WHERE id = ?1", [before], |r| r.get(0))?;
+ prev = prev_of(next)?;
+ }
+ match prev {
+ Some(p) => (p + next) / 2.0,
+ None => next - 1.0,
+ }
+ }
+ };
+ let touched = if current.status != status { format!(", updated_at = {NOW}") } else { String::new() };
+ c.execute(
+ &format!("UPDATE tasks SET status = ?1, position = ?2{touched} WHERE id = ?3"),
+ params![status, position, id],
+ )?;
+ Ok(())
+ }
+
fn renumber(c: &Connection, status: &str) -> Result<()> {
let ids: Vec<i64> = c
.prepare("SELECT id FROM tasks WHERE status = ?1 ORDER BY position")?
@@ -2133,4 +2140,37 @@ mod tests {
assert_eq!(s.project_by_repo("acme/backend/web").unwrap().unwrap().id, web.id);
assert!(s.create_project("api2", "", Some("acme/backend/api")).is_err(), "still one project per repo");
}
+
+ #[test]
+ fn moves_several_tasks_in_one_write() {
+ let (_tmp, s) = store();
+ let p = s.create_project("api", "", None).unwrap().id;
+ let task = |title: &str| s.create_task(p, title, "").unwrap().id;
+ let (a, b, c, d, x, y) = (task("a"), task("b"), task("c"), task("d"), task("x"), task("y"));
+ s.move_tasks(&[x, y], "doing", None).unwrap();
+ let order =
+ |status: &str| -> Vec<i64> { s.list_tasks(None, Some(status)).unwrap().iter().map(|t| t.id).collect() };
+
+ s.move_tasks(&[c, a], "doing", Some(y)).unwrap();
+ assert_eq!(order("doing"), [x, c, a, y]);
+ assert_eq!(order("todo"), [b, d]);
+
+ // To the end, within a column, and past an anchor that's moving too.
+ s.move_tasks(&[x, c], "doing", None).unwrap();
+ assert_eq!(order("doing"), [a, y, x, c]);
+ s.move_tasks(&[a, y], "doing", Some(a)).unwrap();
+ assert_eq!(order("doing"), [x, c, a, y]);
+
+ // More moves than there is float room between two neighbours.
+ let many: Vec<i64> = (0..80).map(|i| task(&format!("m{i}"))).collect();
+ s.move_tasks(&many, "doing", Some(y)).unwrap();
+ let doing = order("doing");
+ assert_eq!(&doing[3..83], &many[..]);
+ assert_eq!(doing.last(), Some(&y));
+
+ // All or nothing.
+ assert!(s.move_tasks(&[b, 99999], "doing", None).is_err());
+ assert!(order("todo").contains(&b));
+ assert!(s.move_tasks(&[b], "nope", None).is_err());
+ }
}
diff --git a/src/web.rs b/src/web.rs
index 5ebff43..b5697bc 100644
--- a/src/web.rs
+++ b/src/web.rs
@@ -163,6 +163,7 @@ fn router(home: Home, guard: Arc<Guard>, shutdown: CancellationToken) -> Router
.route("/api/projects/{slug}/move", post(move_project))
.route("/api/tasks", post(create_task))
.route("/api/tasks/bulk", post(bulk_tasks))
+ .route("/api/tasks/move", post(move_tasks))
.route("/api/tasks/{id}", get(get_task).patch(update_task).delete(delete_task))
.route("/api/tasks/{id}/move", post(move_task))
.route("/api/tasks/{id}/comments", post(add_comment))
@@ -613,6 +614,17 @@ async fn move_task(State(home): Shared, Path(id): Path<i64>, Json(m): Json<Move>
with_store(home, move |_, s| s.move_task(id, &m.status, m.before)).await
}
+#[derive(Deserialize)]
+struct MoveMany {
+ ids: Vec<i64>,
+ status: String,
+ before: Option<i64>,
+}
+
+async fn move_tasks(State(home): Shared, Json(m): Json<MoveMany>) -> Response {
+ with_store(home, move |_, s| s.move_tasks(&m.ids, &m.status, m.before)).await
+}
+
async fn delete_task(State(home): Shared, Path(id): Path<i64>) -> Response {
with_store(home, move |h, s| h.deleting_images(s, ImagesOf::Task(id), || s.delete_task(id))).await
}