//! In-memory view of the category hierarchy.
//!
//! Categories are few, so each request that needs hierarchy loads them all once
//! and walks the tree in Rust rather than issuing recursive SQL. Nesting is
//! capped at [`MAX_DEPTH`] levels.
use crate::entities::categories;
use sea_orm::*;
use std::collections::{HashMap, HashSet};
use uuid::Uuid;
/// Maximum nesting depth (top level = 1).
pub const MAX_DEPTH: i32 = 3;
/// A viewer's read capability: their trust level (None = anonymous), whether
/// they're staff (staff see everything) and who they are (their own held
/// topics).
#[derive(Clone, Copy)]
pub struct Viewer {
pub level: Option<i32>,
pub staff: bool,
pub id: Option<Uuid>,
}
impl Viewer {
pub fn anonymous() -> Self {
Self { level: None, staff: false, id: None }
}
/// The topic rule beyond its category: a topic whose opening post is
/// held for review (`held_at`) is seen only by its author and staff.
/// Deleted topics are each caller's business (staff see tombstones).
pub fn sees_topic(&self, t: &crate::entities::topics::Model) -> bool {
t.held_at.is_none() || self.staff || self.id == Some(t.user_id)
}
/// [`Self::sees_topic`] for topic queries (sea-orm).
pub fn topic_condition(&self) -> Condition {
use crate::entities::topics;
let mut c = Condition::any().add(topics::Column::HeldAt.is_null());
if self.staff {
return Condition::all();
}
if let Some(id) = self.id {
c = c.add(topics::Column::UserId.eq(id));
}
c
}
/// [`Self::sees_topic`] as SQL for raw queries, on topics aliased `t`.
pub fn topic_sql(&self, t: &str) -> String {
match (self.staff, self.id) {
(true, _) => "TRUE".into(),
(false, Some(id)) => format!("({t}.held_at IS NULL OR {t}.user_id = '{id}')"),
(false, None) => format!("{t}.held_at IS NULL"),
}
}
}
/// The categories a viewer may read, and the viewer (for the topic rule):
/// what topic lists filter by. Derefs to the category id set.
#[derive(Clone)]
pub struct Visible {
pub cats: HashSet<Uuid>,
pub viewer: Viewer,
}
impl Visible {
/// The viewer may see this topic: its category, and [`Viewer::sees_topic`].
pub fn sees(&self, t: &crate::entities::topics::Model) -> bool {
self.cats.contains(&t.category_id) && self.viewer.sees_topic(t)
}
}
impl std::ops::Deref for Visible {
type Target = HashSet<Uuid>;
fn deref(&self) -> &HashSet<Uuid> {
&self.cats
}
}
/// Does a single category's `min_trust_level` admit this viewer?
fn category_admits(min: Option<i32>, v: Viewer) -> bool {
if v.staff {
return true;
}
match min {
None => true, // public
Some(m) => v.level.is_some_and(|l| l >= m),
}
}
/// Build a CSS `background` for the combined color widget. One color → a solid
/// full circle; two → halves; three → thirds (an even `conic-gradient`). The
/// number of slices is the category's depth, so nesting level reads at a glance.
pub fn color_widget_css(colors: &[String]) -> String {
match colors {
[] => "#888888".to_string(),
[one] => one.clone(),
many => {
let step = 360.0 / many.len() as f64;
let segments: Vec<String> = many
.iter()
.enumerate()
.map(|(i, c)| {
let a = i as f64 * step;
let b = (i + 1) as f64 * step;
format!("{c} {a:.3}deg {b:.3}deg")
})
.collect();
format!("conic-gradient({})", segments.join(", "))
}
}
}
pub struct CategoryTree {
by_id: HashMap<Uuid, categories::Model>,
children: HashMap<Uuid, Vec<Uuid>>,
roots: Vec<Uuid>,
}
impl CategoryTree {
/// Load every category and build the tree, ordered by (position, name).
pub async fn load(db: &DatabaseConnection) -> Result<Self, DbErr> {
let cats = categories::Entity::find()
.order_by_asc(categories::Column::Position)
.order_by_asc(categories::Column::Name)
.all(db)
.await?;
let mut by_id = HashMap::with_capacity(cats.len());
let mut children: HashMap<Uuid, Vec<Uuid>> = HashMap::new();
let mut roots = Vec::new();
for c in cats {
match c.parent_id {
Some(p) => children.entry(p).or_default().push(c.id),
None => roots.push(c.id),
}
by_id.insert(c.id, c);
}
Ok(Self { by_id, children, roots })
}
pub fn get(&self, id: Uuid) -> Option<&categories::Model> {
self.by_id.get(&id)
}
pub fn roots(&self) -> &[Uuid] {
&self.roots
}
pub fn children(&self, id: Uuid) -> &[Uuid] {
self.children.get(&id).map(|v| v.as_slice()).unwrap_or(&[])
}
/// Depth of a category (top level = 1).
pub fn depth(&self, id: Uuid) -> i32 {
let mut depth = 1;
let mut cur = self.by_id.get(&id).and_then(|c| c.parent_id);
let mut guard = 0;
while let Some(p) = cur {
depth += 1;
cur = self.by_id.get(&p).and_then(|c| c.parent_id);
guard += 1;
if guard > MAX_DEPTH + 2 {
break; // defensive against cycles
}
}
depth
}
/// Height of the subtree rooted at `id` (0 if it has no children).
pub fn subtree_height(&self, id: Uuid) -> i32 {
self.children(id)
.iter()
.map(|&c| 1 + self.subtree_height(c))
.max()
.unwrap_or(0)
}
/// All descendants of `id` (excludes `id`), preorder.
pub fn descendants(&self, id: Uuid) -> Vec<Uuid> {
let mut out = Vec::new();
self.collect_descendants(id, &mut out);
out
}
fn collect_descendants(&self, id: Uuid, out: &mut Vec<Uuid>) {
for &c in self.children(id) {
out.push(c);
self.collect_descendants(c, out);
}
}
/// Descendants with depth relative to `id` (direct children = 1).
pub fn descendants_with_depth(&self, id: Uuid) -> Vec<(Uuid, i32)> {
let mut out = Vec::new();
self.collect_with_depth(id, 1, &mut out);
out
}
fn collect_with_depth(&self, id: Uuid, depth: i32, out: &mut Vec<(Uuid, i32)>) {
for &c in self.children(id) {
out.push((c, depth));
self.collect_with_depth(c, depth + 1, out);
}
}
/// Ancestors of `id`, ordered top → immediate parent (for breadcrumbs).
pub fn ancestors(&self, id: Uuid) -> Vec<Uuid> {
let mut chain = Vec::new();
let mut cur = self.by_id.get(&id).and_then(|c| c.parent_id);
let mut guard = 0;
while let Some(p) = cur {
chain.push(p);
cur = self.by_id.get(&p).and_then(|c| c.parent_id);
guard += 1;
if guard > MAX_DEPTH + 2 {
break;
}
}
chain.reverse();
chain
}
/// Colors for the combined widget: the ancestor lineage (top → parent) then
/// the category's own color. Length equals the category's depth, so the
/// widget renders as a full circle (level 1), halves (level 2), or thirds
/// (level 3).
pub fn widget_colors(&self, id: Uuid) -> Vec<String> {
let mut colors: Vec<String> = self
.ancestors(id)
.into_iter()
.filter_map(|a| self.get(a).map(|c| c.color.clone()))
.collect();
if let Some(c) = self.get(id) {
colors.push(c.color.clone());
}
colors
}
/// Whether a viewer can read a category — it and every ancestor must admit
/// them (so you can't reach a child of a hidden parent).
pub fn can_view(&self, id: Uuid, v: Viewer) -> bool {
if v.staff {
return true;
}
let mut chain = self.ancestors(id);
chain.push(id);
chain.iter().all(|cid| {
self.get(*cid)
.is_some_and(|c| category_admits(c.min_trust_level, v))
})
}
/// The set of category ids a viewer can read (self + ancestors all admit).
pub fn visible_category_ids(&self, v: Viewer) -> Visible {
let mut vis = HashSet::new();
// flatten() is preorder, so a parent is decided before its children.
for (id, _) in self.flatten() {
if let Some(c) = self.get(id) {
let parent_ok = c.parent_id.map_or(true, |p| vis.contains(&p));
if parent_ok && category_admits(c.min_trust_level, v) {
vis.insert(id);
}
}
}
Visible { cats: vis, viewer: v }
}
/// `id` plus all its descendants — the set whose topics roll up into `id`.
pub fn self_and_descendants(&self, id: Uuid) -> Vec<Uuid> {
let mut v = vec![id];
v.extend(self.descendants(id));
v
}
/// Whole tree flattened preorder as (id, absolute depth).
pub fn flatten(&self) -> Vec<(Uuid, i32)> {
let mut out = Vec::new();
for &r in &self.roots {
out.push((r, 1));
for (id, d) in self.descendants_with_depth(r) {
out.push((id, d + 1));
}
}
out
}
/// Candidate parents for a category (or a new one when `editing` is None):
/// excludes the category itself and its descendants, and only those where
/// attaching keeps the whole subtree within [`MAX_DEPTH`].
pub fn candidate_parents(&self, editing: Option<Uuid>) -> Vec<(Uuid, i32)> {
let height = editing.map(|e| self.subtree_height(e)).unwrap_or(0);
let mut excluded: HashSet<Uuid> = HashSet::new();
if let Some(e) = editing {
excluded.insert(e);
excluded.extend(self.descendants(e));
}
self.flatten()
.into_iter()
.filter(|(id, depth)| !excluded.contains(id) && depth + 1 + height <= MAX_DEPTH)
.collect()
}
/// Validate setting `parent` on category `editing` (None = creating new).
/// Returns the validated parent id (or None) or an error message.
pub fn validate_parent(
&self,
parent: Option<Uuid>,
editing: Option<Uuid>,
) -> Result<Option<Uuid>, &'static str> {
let Some(pid) = parent else {
return Ok(None);
};
if Some(pid) == editing {
return Err("A category can't be its own parent.");
}
if !self.by_id.contains_key(&pid) {
return Err("Selected parent category does not exist.");
}
if let Some(e) = editing {
if self.descendants(e).contains(&pid) {
return Err("Can't move a category under one of its own descendants.");
}
}
let height = editing.map(|e| self.subtree_height(e)).unwrap_or(0);
if self.depth(pid) + 1 + height > MAX_DEPTH {
return Err("That would exceed the maximum nesting depth of 3.");
}
Ok(Some(pid))
}
}
neiam
/recourse
public · Issues · Pulls · Labels · Forks · Compare · Actions queued · Badges · Packages
⭐
Log in to mark this repository.
11.0 KiB · text
History
4ed675a