//! Where tiles go on a canvas's strip of columns, the same for a person on //! their page and an agent through the tools. A column is a head (a tile //! stacked under none) and the tiles stacked under it, at most three in //! all; columns run left to right by their heads' `order`, a stack top to //! bottom from its head by its tiles' own. //! //! A tile placed is given an `order` between its new neighbours', so only //! it is rewritten; only where two neighbours' numbers have no room left //! between them (some fifty halvings in one place) are the line's numbers //! made 1, 2, 3… again. A tile added goes: with `stack`, at the end of that //! tile's column; else with `from`, right after the run of columns that //! starts at `from`'s and holds only what was opened from it, through //! `from` links; else with `after`, right after that tile's column; else //! at the end. use super::{Beside, MAX_STACK, Refused, Tile, Width}; use std::collections::{HashMap, HashSet}; /// A column: its head and the tiles stacked under it, in order, as indices /// into the canvas's tiles. pub(crate) struct Column { pub head: usize, pub members: Vec, } impl Column { fn len(&self) -> usize { 1 + self.members.len() } /// Its tiles, top to bottom. fn tiles(&self) -> impl Iterator + '_ { std::iter::once(self.head).chain(self.members.iter().copied()) } } /// Where a tile added goes: a column of its own at `order`, or stacked /// under `head` at `order`. #[derive(Debug, PartialEq)] pub(crate) enum Spot { Column { order: f64 }, Stacked { head: String, order: f64 }, } /// The columns, left to right. A tile stacked under one that is not a /// head (gone, or stacked itself) is a head. pub(crate) fn columns(tiles: &[Tile]) -> Vec { let index: HashMap<&str, usize> = tiles .iter() .enumerate() .map(|(i, t)| (t.id.as_str(), i)) .collect(); let head_of = |i: usize| { let h = *index.get(tiles[i].stack.as_deref()?)?; (h != i && tiles[h].stack.is_none()).then_some(h) }; let by_order = |a: &usize, b: &usize| { let (a, b) = (&tiles[*a], &tiles[*b]); a.order.total_cmp(&b.order).then_with(|| a.id.cmp(&b.id)) }; let mut heads: Vec = (0..tiles.len()).filter(|&i| head_of(i).is_none()).collect(); heads.sort_by(by_order); let at: HashMap = heads.iter().enumerate().map(|(c, &h)| (h, c)).collect(); let mut cols: Vec = heads .into_iter() .map(|head| Column { head, members: Vec::new(), }) .collect(); for i in 0..tiles.len() { if let Some(h) = head_of(i) { cols[at[&h]].members.push(i); } } for c in &mut cols { c.members.sort_by(by_order); } cols } /// The tiles in strip order: each column's head, then those stacked under it. pub(crate) fn in_order(tiles: &[Tile]) -> Vec<&Tile> { columns(tiles) .iter() .flat_map(|c| c.tiles().map(|i| &tiles[i]).collect::>()) .collect() } /// The index of a tile, and of its column. fn find(tiles: &[Tile], cols: &[Column], id: &str) -> Result<(usize, usize), Refused> { let i = tiles .iter() .position(|t| t.id == id) .ok_or_else(|| Refused::NoTile(id.to_string()))?; // Every tile heads a column or is stacked in one (`columns`). let c = cols .iter() .position(|c| c.tiles().any(|t| t == i)) .expect("every tile is in a column"); Ok((i, c)) } /// A number between `lo` and `hi`, either end open; none if there is no /// room between them. fn between(lo: Option, hi: Option) -> Option { match (lo, hi) { (None, None) => Some(1.0), (Some(l), None) => Some(l.floor() + 1.0), (None, Some(h)) => Some(h.ceil() - 1.0), (Some(l), Some(h)) => { let m = l + (h - l) / 2.0; (m > l && m < h).then_some(m) } } } /// The order a tile put at `pos` in `line` (tiles in order, it not among /// them) takes; where there is no room, the line numbered 1, 2, 3… again, /// leaving `pos` free. fn slot(tiles: &mut [Tile], line: &[usize], pos: usize) -> f64 { let lo = pos.checked_sub(1).map(|p| tiles[line[p]].order); let hi = line.get(pos).map(|&i| tiles[i].order); if let Some(order) = between(lo, hi) { return order; } for (k, &i) in line.iter().enumerate() { tiles[i].order = (k + 1 + usize::from(k >= pos)) as f64; } (pos + 1) as f64 } /// The heads of `cols`, but the column `skip`'s. fn heads(cols: &[Column], skip: Option) -> Vec { cols.iter() .enumerate() .filter(|(c, _)| Some(*c) != skip) .map(|(_, col)| col.head) .collect() } /// The order a tile stacked at the end of `col` takes. fn stack_end(tiles: &mut [Tile], col: &Column) -> f64 { slot(tiles, &col.members, col.members.len()) } /// Where a tile added goes, as the module says. A `from` or `after` not /// on the canvas is no place; a `stack` not on it is refused, and one /// whose column is full. pub(crate) fn spot( tiles: &mut [Tile], from: Option<&str>, after: Option<&str>, stack: Option<&str>, ) -> Result { let cols = columns(tiles); if let Some(s) = stack { let (_, c) = find(tiles, &cols, s)?; if cols[c].len() >= MAX_STACK { return Err(full()); } return Ok(Spot::Stacked { head: tiles[cols[c].head].id.clone(), order: stack_end(tiles, &cols[c]), }); } let opened = from.and_then(|f| Some((f, find(tiles, &cols, f).ok()?.1))); let pos = match (opened, after.and_then(|a| find(tiles, &cols, a).ok())) { (Some((f, c)), _) => { let mine = descendants(tiles, f); let mut last = c; while last + 1 < cols.len() && cols[last + 1] .tiles() .all(|i| mine.contains(tiles[i].id.as_str())) { last += 1; } last + 1 } (None, Some((_, c))) => c + 1, (None, None) => cols.len(), }; Ok(Spot::Column { order: slot(tiles, &heads(&cols, None), pos), }) } /// The tiles opened from `id`, through `from` links, transitively. fn descendants<'a>(tiles: &'a [Tile], id: &str) -> HashSet<&'a str> { let mut found: HashSet<&str> = HashSet::new(); let mut pending = vec![id.to_string()]; while let Some(parent) = pending.pop() { for t in tiles { if t.from.as_deref() == Some(parent.as_str()) && t.id != id && found.insert(&t.id) { pending.push(t.id.clone()); } } } found } fn full() -> Refused { Refused::Limit(format!( "A column holds {MAX_STACK} tiles at most: stack into another" )) } /// Put tile `id` right before or after another. Within one column, it /// moves in its stack, heading the column if put before its head. Else /// its column moves beside the other's; a stacked tile comes out as a /// column of its own. The tile placed. pub(crate) fn place(tiles: &mut [Tile], id: &str, to: &Beside) -> Result { let (target, after) = match to { Beside::Before(t) => (t.as_str(), false), Beside::After(t) => (t.as_str(), true), }; if target == id { return Err(Refused::Invalid( "A tile is placed beside another, not itself".into(), )); } let cols = columns(tiles); let (i, ci) = find(tiles, &cols, id)?; let (t, ct) = find(tiles, &cols, target)?; if ci == ct { let col = &cols[ci]; let mut line: Vec = col.tiles().filter(|&x| x != i).collect(); let at = line.iter().position(|&x| x == t).unwrap_or(0) + usize::from(after); line.insert(at, i); if line[0] == col.head { let others: Vec = line[1..].iter().copied().filter(|&x| x != i).collect(); tiles[i].order = slot(tiles, &others, at - 1); } else { let (new, old) = (line[0], col.head); tiles[new].order = tiles[old].order; tiles[new].width = tiles[old].width; tiles[new].stack = None; let head = tiles[new].id.clone(); for (k, &m) in line[1..].iter().enumerate() { tiles[m].stack = Some(head.clone()); tiles[m].order = (k + 1) as f64; } } return Ok(id.to_string()); } let moving_column = cols[ci].head == i; let line = heads(&cols, moving_column.then_some(ci)); let target_at = line .iter() .position(|&h| h == cols[ct].head) .unwrap_or(line.len()); tiles[i].order = slot(tiles, &line, target_at + usize::from(after)); tiles[i].stack = None; Ok(id.to_string()) } /// Stack tile `id` at the end of `into`'s column; a head brings the tiles /// stacked under it along. The tile stacked. pub(crate) fn stack(tiles: &mut [Tile], id: &str, into: &str) -> Result { let cols = columns(tiles); let (i, ci) = find(tiles, &cols, id)?; let (_, ct) = find(tiles, &cols, into)?; if ci == ct { return Err(Refused::Invalid( "The tile is in that column already".into(), )); } let moving: Vec = if cols[ci].head == i { cols[ci].tiles().collect() } else { vec![i] }; if cols[ct].len() + moving.len() > MAX_STACK { return Err(full()); } let head = tiles[cols[ct].head].id.clone(); let base = stack_end(tiles, &cols[ct]); for (k, &m) in moving.iter().enumerate() { tiles[m].stack = Some(head.clone()); tiles[m].order = base + k as f64; } Ok(id.to_string()) } /// Take stacked tile `id` out, as a column of its own right after its /// column. The tile. pub(crate) fn unstack(tiles: &mut [Tile], id: &str) -> Result { let cols = columns(tiles); let (i, ci) = find(tiles, &cols, id)?; if cols[ci].head == i { return Err(Refused::Invalid("The tile is not stacked".into())); } tiles[i].order = slot(tiles, &heads(&cols, None), ci + 1); tiles[i].stack = None; Ok(id.to_string()) } /// Set the width of tile `id`'s column, which its head holds. The head. pub(crate) fn set_width(tiles: &mut [Tile], id: &str, width: Width) -> Result { let cols = columns(tiles); let (_, c) = find(tiles, &cols, id)?; let head = cols[c].head; tiles[head].width = width; Ok(tiles[head].id.clone()) } /// Take tile `id` off; a head taken off, the next in its stack heads the /// column, in its place and at its width. The tile taken off. pub(crate) fn remove(tiles: &mut Vec, id: &str) -> Result { let cols = columns(tiles); let (i, c) = find(tiles, &cols, id)?; let col = &cols[c]; if col.head == i && let Some((&next, rest)) = col.members.split_first() { tiles[next].order = tiles[i].order; tiles[next].width = tiles[i].width; tiles[next].stack = None; let head = tiles[next].id.clone(); for &m in rest { tiles[m].stack = Some(head.clone()); } } Ok(tiles.remove(i)) } #[cfg(test)] mod tests { use super::*; use crate::canvas::By; use serde_json::json; /// A tile `n` at `order`, opened from `from`, stacked under `stack`. fn tile(n: u8, order: f64, from: Option, stack: Option) -> Tile { let id = |n: u8| format!("{n:012x}"); Tile { id: id(n), tool: "describe_repo".into(), arguments: json!({}), title: format!("t{n}"), order, width: Width::Third, stack: stack.map(id), by: By::Person, author: "did:plc:a".into(), at: "2026-11-14T00:00:00.000Z".into(), from: from.map(id), } } fn id(n: u8) -> String { format!("{n:012x}") } /// The strip as columns of tile numbers. fn strip(tiles: &[Tile]) -> Vec> { columns(tiles) .iter() .map(|c| { c.tiles() .map(|i| u8::from_str_radix(&tiles[i].id, 16).unwrap()) .collect() }) .collect() } /// Add tile `n` where `spot` puts it. fn add(tiles: &mut Vec, n: u8, from: Option, after: Option, stack_: Option) { let (f, a, s) = (from.map(id), after.map(id), stack_.map(id)); let spot = spot(tiles, f.as_deref(), a.as_deref(), s.as_deref()).unwrap(); let mut t = tile(n, 0.0, from, None); match spot { Spot::Column { order } => t.order = order, Spot::Stacked { head, order } => (t.order, t.stack) = (order, Some(head)), } tiles.push(t); } #[test] fn opened_lands_after_its_sources_descendants() { // Following | A | B, both opened from Following. let mut tiles = vec![tile(1, 1.0, None, None)]; add(&mut tiles, 2, Some(1), None, None); add(&mut tiles, 3, Some(1), None, None); assert_eq!(strip(&tiles), [[1], [2], [3]]); // A's child goes between A and B. add(&mut tiles, 4, Some(2), None, None); assert_eq!(strip(&tiles), [[1], [2], [4], [3]]); // A grandchild of Following's counts as its descendant: another // from Following goes at the run's end. add(&mut tiles, 5, Some(1), None, None); assert_eq!(strip(&tiles), [[1], [2], [4], [3], [5]]); // The run stops at the first column holding what is not its own. add(&mut tiles, 6, None, None, None); add(&mut tiles, 7, Some(1), None, None); assert_eq!(strip(&tiles), [[1], [2], [4], [3], [5], [7], [6]]); // With after, right of that column; with neither, at the end; // from wins over after; a from not on the canvas is no place. add(&mut tiles, 8, None, Some(1), None); assert_eq!(strip(&tiles)[1], [8]); add(&mut tiles, 9, Some(6), Some(1), None); assert_eq!(strip(&tiles).last().unwrap(), &[9]); add(&mut tiles, 10, Some(99), Some(2), None); assert_eq!(strip(&tiles)[3], [10]); // Nothing but each new tile's order was written. let orders: Vec = tiles.iter().map(|t| t.order).collect(); assert_eq!(&orders[..4], [1.0, 2.0, 3.0, 2.5]); } #[test] fn stacks_hold_three() { let mut tiles = vec![tile(1, 1.0, None, None), tile(2, 2.0, None, None)]; add(&mut tiles, 3, None, None, Some(1)); add(&mut tiles, 4, None, None, Some(3)); assert_eq!(strip(&tiles), [vec![1, 3, 4], vec![2]]); let (f, s) = (None, Some(id(4))); assert!(matches!( spot(&mut tiles, f, None, s.as_deref()), Err(Refused::Limit(_)) )); assert!(matches!( spot(&mut tiles, None, None, Some(&id(99))), Err(Refused::NoTile(_)) )); // A column with tiles stacked under it moves whole. place(&mut tiles, &id(1), &Beside::After(id(2))).unwrap(); assert_eq!(strip(&tiles), [vec![2], vec![1, 3, 4]]); // Within the stack: reordered; before the head, it heads it, at // the head's place and width. tiles[0].width = Width::Full; let w = |tiles: &[Tile], n: u8| tiles.iter().find(|t| t.id == id(n)).unwrap().width; set_width(&mut tiles, &id(4), Width::Half).unwrap(); assert_eq!(w(&tiles, 1), Width::Half); place(&mut tiles, &id(4), &Beside::Before(id(3))).unwrap(); assert_eq!(strip(&tiles), [vec![2], vec![1, 4, 3]]); place(&mut tiles, &id(3), &Beside::Before(id(1))).unwrap(); assert_eq!(strip(&tiles), [vec![2], vec![3, 1, 4]]); assert_eq!(w(&tiles, 3), Width::Half); // A stacked tile placed beside another column comes out. place(&mut tiles, &id(4), &Beside::Before(id(2))).unwrap(); assert_eq!(strip(&tiles), [vec![4], vec![2], vec![3, 1]]); // Unstacked: right after its column. unstack(&mut tiles, &id(1)).unwrap(); assert_eq!(strip(&tiles), [[4], [2], [3], [1]]); assert!(matches!( unstack(&mut tiles, &id(1)), Err(Refused::Invalid(_)) )); // Stacked into another column: a head brings its own along. stack(&mut tiles, &id(1), &id(3)).unwrap(); stack(&mut tiles, &id(4), &id(2)).unwrap(); assert_eq!(strip(&tiles), [vec![2, 4], vec![3, 1]]); assert!(matches!( stack(&mut tiles, &id(2), &id(3)), Err(Refused::Limit(_)) )); assert!(matches!( stack(&mut tiles, &id(4), &id(2)), Err(Refused::Invalid(_)) )); // A head taken off: the next in its stack heads the column. let gone = remove(&mut tiles, &id(2)).unwrap(); assert_eq!(gone.id, id(2)); assert_eq!(strip(&tiles), [vec![4], vec![3, 1]]); assert!(matches!( place(&mut tiles, &id(4), &Beside::After(id(4))), Err(Refused::Invalid(_)) )); } #[test] fn room_runs_out_and_the_line_is_renumbered() { let mut tiles = vec![tile(1, 1.0, None, None), tile(2, 2.0, None, None)]; // Always right after the first: the gap halves until it is gone. let mut renumbered = false; for n in 3..90 { add(&mut tiles, n, None, Some(1), None); let cols = strip(&tiles); assert_eq!((cols[0][0], cols[1][0]), (1, n), "{n}"); assert_eq!(cols.last().unwrap(), &[2]); renumbered |= tiles[1].order != 2.0; } assert!(renumbered); // In order still, every column where it was. assert_eq!(in_order(&tiles).len(), tiles.len()); // An empty strip starts at 1; before the first goes below it. let mut empty = Vec::new(); assert_eq!( spot(&mut empty, None, None, None), Ok(Spot::Column { order: 1.0 }) ); let mut one = vec![tile(1, 1.0, None, None), tile(2, 2.0, None, None)]; place(&mut one, &id(2), &Beside::Before(id(1))).unwrap(); assert_eq!(one[1].order, 0.0); } #[test] fn broken_stacks_read_as_heads() { let tiles = vec![ tile(1, 1.0, None, Some(9)), tile(2, 1.0, None, Some(1)), tile(3, 2.0, None, Some(3)), ]; assert_eq!(strip(&tiles), [[1], [2], [3]]); } #[test] fn stacked_tiles_move_alone_and_follow_a_new_head() { let mut tiles = vec![ tile(1, 1.0, None, None), tile(2, 2.0, None, Some(1)), tile(3, 3.0, None, Some(1)), tile(4, 4.0, None, None), ]; // A stacked tile stacked into another column goes alone. stack(&mut tiles, &id(3), &id(4)).unwrap(); assert_eq!(strip(&tiles), [vec![1, 2], vec![4, 3]]); // A head with two under it taken off: the next heads the rest. stack(&mut tiles, &id(3), &id(1)).unwrap(); remove(&mut tiles, &id(1)).unwrap(); assert_eq!(strip(&tiles), [vec![2, 3], vec![4]]); assert_eq!(tiles[1].stack.as_deref(), Some(id(2).as_str())); } }