33.4 KiB · text History 0c61284
//! The Focus layout (Classic is the other): browse the forum the way pin_flip's board focus mode and
//! shared pages do, and step through topics the way cartosnap's shared trip
//! steps through photos.
//!
//! Every list page has a Focus form built from the same pieces: tiles
//! (`_topic_tile`/`_topic_square`), an optional rail, and the reader over the
//! page (`tiles_and_reader` + [`ListPage`]) whose filmstrip is that page's list.
//!
//! * `/c/{slug}?view=focus[&sort=…]` — the category fills the page; its
//!   sibling categories are squares on a rail (the current one accent
//!   bordered), `..` goes up a level (to the visual home at the top), its own
//!   topics are tiles, and each subcategory is a column of compact topic
//!   squares with a "Focus on …" link. Modelled on pin_flip
//!   `share_live/show.ex` (rail, `..`, tiles, subgroup squares) and
//!   `proposal_live/show.ex` (`focus_siblings`, `focused`/`compact`).
//! * `&topic=<id>` — a reader over the focus view with the topic's posts and a
//!   filmstrip of the category's topics in the current sort; ←/→ (j/k) step,
//!   Escape closes (keys in `assets/f/js/src.js`). Modelled on cartosnap
//!   `share_live.ex` (`?photo=`, filmstrip, `phx-window-keydown` stepping) and
//!   pin_flip's lightbox (counter, prev/next, Escape, click outside).
//! * `/?view=focus` — the home page as a grid of top-level category tiles.
//!
//! Everything is in the URL. Navigation is ordinary hx-boost (only `#content`
//! swaps); the reader's links swap just `#reader` (the handler answers a
//! request whose `HX-Target` is `reader` with that fragment alone) and push
//! the URL, so the back button walks back through them.

use std::collections::{HashMap, HashSet};

use axum::http::{header::COOKIE, HeaderMap, HeaderValue, StatusCode};
use axum::response::{Html, IntoResponse, Response};
use chrono::{Duration, Utc};
use minijinja::context;
use sea_orm::*;
use serde::Serialize;
use uuid::Uuid;

use super::forum::{
    build_post_rows, build_topic_rows, ise, load_posts, record_topic_view, sort_topics, PostRow, TopicRow,
    TopicSort,
};
use crate::category_tree::{color_widget_css, CategoryTree, Viewer};
use crate::entities::{categories, post_reactions, posts, reaction_types, topic_reads, topics, users};
use crate::middleware::UserContext;
use crate::AppState;

/// Signed-out visitors' layout (persistent): they have no profile.
pub const VIEW_COOKIE: &str = "recourse_view";
/// Signed-in users' temporary override from the per-page toggle: a session
/// cookie, so it lasts while they browse and never touches the saved
/// profile preference (cleared when they save the profile).
pub const SESSION_VIEW_COOKIE: &str = "recourse_view_session";

/// How many compact squares a subcategory column shows before "+N more".
const COLUMN_LIMIT: usize = 24;
/// Compact squares per category on the focus home.
const HOME_TILE_TOPICS: u64 = 6;
/// A topic the user has never opened counts as "new" if active this recently.
const NEW_WITHIN_DAYS: i64 = 14;

/// The forum's two layouts. User-facing names: Classic and Focus.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ViewMode {
    Classic,
    Focus,
}

impl ViewMode {
    /// `classic` / `focus`, plus the earlier `list` / `visual` as aliases.
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "classic" | "list" => Some(Self::Classic),
            "focus" | "visual" => Some(Self::Focus),
            _ => None,
        }
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Self::Classic => "classic",
            Self::Focus => "focus",
        }
    }
}

fn cookie_value<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
    headers
        .get_all(COOKIE)
        .iter()
        .filter_map(|h| h.to_str().ok())
        .flat_map(|h| h.split(';'))
        .find_map(|c| c.trim().strip_prefix(name)?.strip_prefix('='))
}

/// The layout to render, and a `Set-Cookie` to send with it.
pub struct ViewChoice {
    pub mode: ViewMode,
    pub set_cookie: Option<HeaderValue>,
}

impl ViewChoice {
    pub fn is_focus(&self) -> bool {
        self.mode == ViewMode::Focus
    }

    /// Attach the cookie (if any) to a response.
    pub fn respond(self, page: impl IntoResponse) -> Response {
        let mut res = page.into_response();
        if let Some(c) = self.set_cookie {
            res.headers_mut().append(axum::http::header::SET_COOKIE, c);
        }
        res
    }
}

/// `Set-Cookie` that deletes the signed-in override (profile saved).
pub fn clear_session_view_cookie() -> HeaderValue {
    HeaderValue::from_static("recourse_view_session=; Path=/; Max-Age=0; SameSite=Lax")
}

/// Which layout a page uses.
///
/// * Signed in: the profile's "Layout" (`users.preferred_view`) is the
///   default. `?view=` (the per-page toggle, or any link carrying it) is a
///   temporary override kept in a session cookie, so the pages after it
///   don't flip back; it never changes the profile. Choosing the profile's
///   own layout drops the override.
/// * Signed out: `?view=` is remembered in a long-lived cookie.
/// * Otherwise Classic.
pub fn resolve_view(requested: Option<&str>, uc: Option<&UserContext>, headers: &HeaderMap, secure: bool) -> ViewChoice {
    let requested = requested.and_then(ViewMode::parse);
    let secure = if secure { "; Secure" } else { "" };
    match uc {
        Some(c) => {
            let saved = ViewMode::parse(&c.user.preferred_view).unwrap_or(ViewMode::Classic);
            let session = cookie_value(headers, SESSION_VIEW_COOKIE).and_then(ViewMode::parse);
            match requested {
                Some(req) if req == saved => ViewChoice {
                    mode: req,
                    set_cookie: session.map(|_| clear_session_view_cookie()),
                },
                Some(req) => ViewChoice {
                    mode: req,
                    set_cookie: (session != Some(req))
                        .then(|| {
                            HeaderValue::from_str(&format!(
                                "{SESSION_VIEW_COOKIE}={}; Path=/; SameSite=Lax{secure}",
                                req.as_str()
                            ))
                            .ok()
                        })
                        .flatten(),
                },
                None => ViewChoice { mode: session.unwrap_or(saved), set_cookie: None },
            }
        }
        None => {
            let remembered = cookie_value(headers, VIEW_COOKIE).and_then(ViewMode::parse);
            let set_cookie = requested.filter(|r| Some(*r) != remembered).and_then(|r| {
                HeaderValue::from_str(&format!(
                    "{VIEW_COOKIE}={}; Path=/; Max-Age=31536000; SameSite=Lax{secure}",
                    r.as_str()
                ))
                .ok()
            });
            ViewChoice { mode: requested.or(remembered).unwrap_or(ViewMode::Classic), set_cookie }
        }
    }
}

/// [`resolve_view`] with the app's cookie settings.
pub fn view_for(state: &AppState, requested: Option<&str>, uc: Option<&UserContext>, headers: &HeaderMap) -> ViewChoice {
    resolve_view(requested, uc, headers, state.config.secure_cookies())
}

/// An htmx request that only wants the reader (its links target `#reader`).
pub fn wants_reader(headers: &HeaderMap) -> bool {
    headers.get("hx-target").and_then(|v| v.to_str().ok()) == Some("reader")
}

/// Append a query parameter to a path that may already have a query.
pub fn with_param(path: &str, key: &str, value: &str) -> String {
    let sep = if path.contains('?') { '&' } else { '?' };
    format!("{path}{sep}{key}={}", urlencode(value))
}

/// Percent-encode a query value (everything but RFC 3986 unreserved).
pub fn urlencode(s: &str) -> String {
    s.bytes()
        .map(|b| match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => (b as char).to_string(),
            _ => format!("%{b:02X}"),
        })
        .collect()
}

/// `/c/{slug}?view=focus&sort=…`.
pub(crate) fn focus_url(slug: &str, sort: TopicSort) -> String {
    format!("/c/{slug}?view=focus&sort={}", sort.as_str())
}

#[derive(Serialize)]
pub(crate) struct RailItem {
    name: String,
    slug: String,
    href: String,
    widget_bg: String,
    count: u64,
    current: bool,
}

#[derive(Serialize)]
pub(crate) struct UpLink {
    name: String,
    href: String,
}

#[derive(Serialize, Clone)]
struct Avatar {
    id: Uuid,
    name: String,
    has_avatar: bool,
}

#[derive(Serialize, Clone)]
struct ReactionSum {
    emoji: String,
    count: usize,
}

/// A topic as a tile or a compact square.
#[derive(Serialize)]
pub(crate) struct TopicTile {
    #[serde(flatten)]
    pub(crate) row: TopicRow,
    replies: i32,
    /// The opening poster, then the top repliers.
    posters: Vec<Avatar>,
    reactions: Vec<ReactionSum>,
    /// Signed in, never opened, recently active.
    is_new: bool,
    /// Signed in: posts since they last read it.
    unread: i32,
    /// Extra lines a page adds (bookmarked post, reaction totals,
    /// notifications).
    pub(crate) notes: Vec<String>,
    #[serde(skip)]
    pub(crate) category_id: Uuid,
}

#[derive(Serialize)]
struct SubColumn {
    name: String,
    slug: String,
    href: String,
    widget_bg: String,
    count: u64,
    topics: Vec<TopicTile>,
    more: usize,
}

#[derive(Serialize)]
pub(crate) struct StripItem {
    id: Uuid,
    title: String,
    widget_bg: String,
    current: bool,
    unread: bool,
}

#[derive(Serialize)]
pub(crate) struct Reader {
    topic: topics::Model,
    author: String,
    cat_name: String,
    cat_slug: String,
    posts: Vec<PostRow>,
    index: usize,
    count: usize,
    prev: Option<Uuid>,
    next: Option<Uuid>,
    strip: Vec<StripItem>,
}

/// Non-deleted topic counts per category, for whole-subtree totals.
pub(crate) async fn topic_counts(state: &AppState) -> Result<HashMap<Uuid, u64>, StatusCode> {
    let rows: Vec<(Uuid, i64)> = topics::Entity::find()
        .select_only()
        .column(topics::Column::CategoryId)
        .column_as(topics::Column::Id.count(), "n")
        .filter(topics::Column::DeletedAt.is_null())
        .group_by(topics::Column::CategoryId)
        .into_tuple()
        .all(state.db.as_ref())
        .await
        .map_err(ise("count topics per category"))?;
    Ok(rows.into_iter().map(|(c, n)| (c, n as u64)).collect())
}

fn subtree_count(tree: &CategoryTree, vis: &HashSet<Uuid>, counts: &HashMap<Uuid, u64>, id: Uuid) -> u64 {
    tree.self_and_descendants(id)
        .into_iter()
        .filter(|i| vis.contains(i))
        .map(|i| counts.get(&i).copied().unwrap_or(0))
        .sum()
}

/// Rows plus what tiles show beyond the list: poster avatars, reaction
/// totals, and the signed-in viewer's new/unread state.
pub(crate) async fn decorate(
    state: &AppState,
    tree: &CategoryTree,
    loaded: Vec<(topics::Model, Option<users::Model>)>,
    viewer_id: Option<Uuid>,
) -> Result<Vec<TopicTile>, StatusCode> {
    let ids: Vec<Uuid> = loaded.iter().map(|(t, _)| t.id).collect();
    let meta: Vec<(Uuid, i32, chrono::DateTime<chrono::FixedOffset>)> =
        loaded.iter().map(|(t, _)| (t.category_id, t.posts_count, t.bumped_at)).collect();
    let rows = build_topic_rows(state, tree, loaded).await?;
    if ids.is_empty() {
        return Ok(vec![]);
    }

    // Live posts of these topics: who replied, and what was reacted to.
    let post_rows: Vec<(Uuid, Uuid, Uuid)> = posts::Entity::find()
        .select_only()
        .column(posts::Column::Id)
        .column(posts::Column::TopicId)
        .column(posts::Column::UserId)
        .filter(posts::Column::TopicId.is_in(ids.iter().copied()))
        .filter(posts::Column::DeletedAt.is_null())
        .into_tuple()
        .all(state.db.as_ref())
        .await
        .map_err(ise("load tile posts"))?;
    let post_topic: HashMap<Uuid, Uuid> = post_rows.iter().map(|(p, t, _)| (*p, *t)).collect();
    let mut replies_by: HashMap<Uuid, HashMap<Uuid, usize>> = HashMap::new();
    for (_, t, u) in &post_rows {
        *replies_by.entry(*t).or_default().entry(*u).or_default() += 1;
    }

    let rtypes: HashMap<Uuid, (i32, String)> = reaction_types::Entity::find()
        .all(state.db.as_ref())
        .await
        .map_err(ise("load reaction types"))?
        .into_iter()
        .map(|r| (r.id, (r.position, r.emoji)))
        .collect();
    let mut reactions: HashMap<Uuid, HashMap<Uuid, usize>> = HashMap::new();
    if !post_topic.is_empty() {
        let rs: Vec<(Uuid, Uuid)> = post_reactions::Entity::find()
            .select_only()
            .column(post_reactions::Column::PostId)
            .column(post_reactions::Column::ReactionId)
            .filter(post_reactions::Column::PostId.is_in(post_topic.keys().copied()))
            .into_tuple()
            .all(state.db.as_ref())
            .await
            .map_err(ise("load tile reactions"))?;
        for (p, r) in rs {
            if let Some(t) = post_topic.get(&p) {
                *reactions.entry(*t).or_default().entry(r).or_default() += 1;
            }
        }
    }

    let reads: HashMap<Uuid, i32> = match viewer_id {
        Some(uid) => topic_reads::Entity::find()
            .filter(topic_reads::Column::UserId.eq(uid))
            .filter(topic_reads::Column::TopicId.is_in(ids.iter().copied()))
            .all(state.db.as_ref())
            .await
            .map_err(ise("load topic reads"))?
            .into_iter()
            .map(|r| (r.topic_id, r.last_read_post_number))
            .collect(),
        None => HashMap::new(),
    };

    // Names for repliers (authors are on the rows already).
    let replier_ids: HashSet<Uuid> = replies_by.values().flat_map(|m| m.keys().copied()).collect();
    let names: HashMap<Uuid, (String, bool)> = users::Entity::find()
        .filter(users::Column::Id.is_in(replier_ids))
        .all(state.db.as_ref())
        .await
        .map_err(ise("load repliers"))?
        .into_iter()
        .map(|u| (u.id, (u.username, u.avatar_content_type.is_some())))
        .collect();

    let new_since = Utc::now() - Duration::days(NEW_WITHIN_DAYS);
    Ok(rows
        .into_iter()
        .zip(meta)
        .map(|(row, (category_id, posts_count, bumped_at))| {
            let id = row.id;
            let mut posters = vec![Avatar {
                id: row.author_id,
                name: row.author.clone(),
                has_avatar: row.author_has_avatar,
            }];
            let mut top: Vec<(Uuid, usize)> = replies_by
                .remove(&id)
                .unwrap_or_default()
                .into_iter()
                .filter(|(u, _)| *u != row.author_id)
                .collect();
            top.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| names.get(&a.0).cmp(&names.get(&b.0))));
            posters.extend(top.into_iter().take(3).filter_map(|(u, _)| {
                names.get(&u).map(|(n, a)| Avatar { id: u, name: n.clone(), has_avatar: *a })
            }));
            let mut rs: Vec<(i32, ReactionSum)> = reactions
                .remove(&id)
                .unwrap_or_default()
                .into_iter()
                .filter_map(|(r, count)| {
                    rtypes.get(&r).map(|(pos, emoji)| (*pos, ReactionSum { emoji: emoji.clone(), count }))
                })
                .collect();
            rs.sort_by_key(|(pos, _)| *pos);
            let (is_new, unread) = match (viewer_id, reads.get(&id)) {
                (None, _) => (false, 0),
                (Some(_), None) => (bumped_at.with_timezone(&Utc) > new_since, 0),
                (Some(_), Some(last)) => (false, (posts_count - last).max(0)),
            };
            TopicTile {
                replies: (posts_count - 1).max(0),
                posters,
                reactions: rs.into_iter().map(|(_, r)| r).collect(),
                is_new,
                unread,
                notes: Vec::new(),
                category_id,
                row,
            }
        })
        .collect())
}

/// Tiles for `loaded` (already limited to what the viewer may see, in the
/// page's order), and the reader when `open_topic` is one of them: never a
/// topic outside the list, so never a hidden or deleted one. Opening it
/// counts a view and marks it read exactly as the topic page does.
pub(crate) async fn tiles_and_reader(
    state: &AppState,
    tree: &CategoryTree,
    loaded: Vec<(topics::Model, Option<users::Model>)>,
    uc: Option<&UserContext>,
    headers: &HeaderMap,
    open_topic: Option<Uuid>,
) -> Result<(Vec<TopicTile>, Option<Reader>), StatusCode> {
    let viewer_id = uc.map(|c| c.user.id);
    let open = match open_topic.and_then(|id| loaded.iter().position(|(t, _)| t.id == id)) {
        Some(i) => {
            let (topic, author) = &loaded[i];
            record_topic_view(state, topic, viewer_id, headers).await;
            let posts = build_post_rows(
                state,
                load_posts(state, topic.id).await?,
                uc.map(|c| (c.user.id, c.user.is_staff)),
            )
            .await?;
            let cat = tree.get(topic.category_id).map(|c| (c.name.clone(), c.slug.clone()));
            Some((i, topic.clone(), author.as_ref().map(|u| u.username.clone()), cat, posts))
        }
        None => None,
    };
    let tiles = decorate(state, tree, loaded, viewer_id).await?;
    let reader = open.map(|(i, topic, author, cat, posts)| {
        let (cat_name, cat_slug) = cat.unwrap_or_default();
        Reader {
            author: author.unwrap_or_else(|| "unknown".into()),
            cat_name,
            cat_slug,
            posts,
            index: i + 1,
            count: tiles.len(),
            prev: i.checked_sub(1).map(|j| tiles[j].row.id),
            next: tiles.get(i + 1).map(|t| t.row.id),
            strip: strip(&tiles, topic.id),
            topic,
        }
    });
    Ok((tiles, reader))
}

/// The filmstrip: every tile, `current` marked.
pub(crate) fn strip(tiles: &[TopicTile], current: Uuid) -> Vec<StripItem> {
    tiles
        .iter()
        .map(|t| StripItem {
            id: t.row.id,
            title: t.row.title.clone(),
            widget_bg: t.row.cat_widget_bg.clone(),
            current: t.row.id == current,
            unread: t.row.id != current && (t.is_new || t.unread > 0),
        })
        .collect()
}

/// Just `#reader` (what the reader's own links swap in).
pub(crate) fn reader_fragment(
    state: &AppState,
    reader: Option<Reader>,
    base: &str,
    uc: Option<&UserContext>,
) -> Result<Html<String>, StatusCode> {
    super::render(
        state,
        "forum/_reader.html",
        context! {
            reader => reader,
            base => base,
            user => uc.map(|c| c.user.clone()),
            can_write => uc.is_some_and(|c| super::may_write(state, &c.user)),
        },
    )
}

/// The rail beside a category (or a topic in it): the category and its
/// visible siblings, as pin_flip's `focus_siblings`, and `..` to the parent
/// (visible, since the category is) or the focus home.
pub(crate) fn category_rail(
    tree: &CategoryTree,
    vis: &HashSet<Uuid>,
    counts: &HashMap<Uuid, u64>,
    category: &categories::Model,
    sort: TopicSort,
) -> (UpLink, Vec<RailItem>) {
    let siblings: Vec<Uuid> = match category.parent_id {
        Some(p) => tree.children(p).to_vec(),
        None => tree.roots().to_vec(),
    };
    let rail = siblings
        .into_iter()
        .filter(|i| vis.contains(i))
        .filter_map(|id| {
            tree.get(id).map(|c| RailItem {
                name: c.name.clone(),
                slug: c.slug.clone(),
                href: focus_url(&c.slug, sort),
                widget_bg: color_widget_css(&tree.widget_colors(id)),
                count: subtree_count(tree, vis, counts, id),
                current: id == category.id,
            })
        })
        .collect();
    let up = match category.parent_id.and_then(|p| tree.get(p)) {
        Some(p) => UpLink { name: p.name.clone(), href: focus_url(&p.slug, sort) },
        None => UpLink { name: "All categories".into(), href: "/?view=focus".into() },
    };
    (up, rail)
}

/// A focus page over a list of topics (`forum/focus_list.html`).
pub(crate) struct ListPage {
    /// `data-focus` on the page (tests, scripts).
    pub page_id: &'static str,
    pub heading: String,
    pub heading_icon: &'static str,
    pub subheading: Option<String>,
    pub crumbs: Vec<UpLink>,
    /// This page without `view=` (the Classic/Focus switch adds it).
    pub toggle_base: String,
    /// This page in focus; `&topic=<id>` opens the reader.
    pub base: String,
    pub empty: String,
    pub rail: Option<(UpLink, Vec<RailItem>)>,
    pub rail_label: &'static str,
    pub search_q: Option<String>,
    pub mark_all_read: bool,
    pub others: Vec<minijinja::Value>,
}

impl ListPage {
    pub fn new(page_id: &'static str, heading: impl Into<String>, toggle_base: impl Into<String>) -> Self {
        let toggle_base = toggle_base.into();
        ListPage {
            page_id,
            heading: heading.into(),
            heading_icon: "",
            subheading: None,
            crumbs: vec![],
            base: with_param(&toggle_base, "view", "focus"),
            toggle_base,
            empty: "Nothing here yet.".into(),
            rail: None,
            rail_label: "",
            search_q: None,
            mark_all_read: false,
            others: vec![],
        }
    }

    /// The page, or only `#reader` for the reader's own htmx requests.
    pub fn render(
        self,
        state: &AppState,
        tiles: Vec<TopicTile>,
        reader: Option<Reader>,
        uc: Option<&UserContext>,
        headers: &HeaderMap,
    ) -> Result<Html<String>, StatusCode> {
        if wants_reader(headers) {
            return reader_fragment(state, reader, &self.base, uc);
        }
        let (up, rail) = match self.rail {
            Some((u, r)) => (Some(u), r),
            None => (None, vec![]),
        };
        let mut ctx = context! {
            title => self.heading,
            app_name => state.config.app_name,
            user => uc.map(|c| c.user.clone()),
            can_write => uc.is_some_and(|c| super::may_write(state, &c.user)),
            page_id => self.page_id,
            heading => self.heading,
            heading_icon => self.heading_icon,
            subheading => self.subheading,
            crumbs => self.crumbs,
            toggle_base => self.toggle_base,
            base => self.base,
            empty => self.empty,
            up => up,
            rail => rail,
            rail_label => self.rail_label,
            mark_all_read => self.mark_all_read,
            others => self.others,
            topics => tiles,
            reader => reader,
        };
        if let Some(q) = self.search_q {
            ctx = context! { search_q => q, ..ctx };
        }
        super::render(state, "forum/focus_list.html", ctx)
    }
}

/// A rail item that isn't a category (tags).
impl RailItem {
    pub(crate) fn is_current(&self) -> bool {
        self.current
    }
}

impl TopicTile {
    /// A copy (a topic can appear in several tag tiles).
    pub(crate) fn clone_tile(&self) -> TopicTile {
        TopicTile {
            row: self.row.clone(),
            replies: self.replies,
            posters: self.posters.clone(),
            reactions: self.reactions.clone(),
            is_new: self.is_new,
            unread: self.unread,
            notes: self.notes.clone(),
            category_id: self.category_id,
        }
    }
}

pub(crate) fn rail_item(name: &str, slug: &str, href: String, count: u64, current: bool) -> RailItem {
    RailItem { name: name.into(), slug: slug.into(), href, widget_bg: String::new(), count, current }
}

pub(crate) fn up_link(name: &str, href: &str) -> UpLink {
    UpLink { name: name.into(), href: href.into() }
}

/// Every visible, non-deleted topic under `category`, in `sort` order.
pub(crate) async fn category_topics(
    state: &AppState,
    tree: &CategoryTree,
    vis: &HashSet<Uuid>,
    category_id: Uuid,
    sort: TopicSort,
) -> Result<Vec<(topics::Model, Option<users::Model>)>, StatusCode> {
    let rolled: Vec<Uuid> = tree.self_and_descendants(category_id).into_iter().filter(|i| vis.contains(i)).collect();
    let mut loaded = topics::Entity::find()
        .filter(topics::Column::CategoryId.is_in(rolled))
        .filter(topics::Column::DeletedAt.is_null())
        .find_also_related(users::Entity)
        .all(state.db.as_ref())
        .await
        .map_err(ise("load topics"))?;
    sort_topics(&mut loaded, sort);
    Ok(loaded)
}

/// Everything the focus view of `category` needs, or just the reader when
/// `reader_only` (an htmx request targeting `#reader`).
#[allow(clippy::too_many_arguments)]
pub(crate) async fn category_focus(
    state: &AppState,
    tree: &CategoryTree,
    category: &categories::Model,
    viewer: Viewer,
    sort: TopicSort,
    uc: Option<&UserContext>,
    headers: &HeaderMap,
    open_topic: Option<Uuid>,
) -> Result<Html<String>, StatusCode> {
    let vis = tree.visible_category_ids(viewer);
    let base = focus_url(&category.slug, sort);

    // Every visible topic under the category, in the current sort: the
    // filmstrip and the stepping order (the classic list's order).
    let loaded = category_topics(state, tree, &vis, category.id, sort).await?;
    let (tiles, reader) = tiles_and_reader(state, tree, loaded, uc, headers, open_topic).await?;
    let user = uc.map(|c| c.user.clone());
    let can_write = uc.is_some_and(|c| super::may_write(state, &c.user));
    if wants_reader(headers) {
        return reader_fragment(state, reader, &base, uc);
    }

    // The category's own topics as tiles; each visible subcategory as a
    // column of compact squares (its whole visible subtree), in list order.
    let children: Vec<Uuid> = tree.children(category.id).iter().copied().filter(|i| vis.contains(i)).collect();
    let column_of: HashMap<Uuid, Uuid> = children
        .iter()
        .flat_map(|&child| tree.self_and_descendants(child).into_iter().map(move |d| (d, child)))
        .collect();
    let mut own = Vec::new();
    let mut by_child: HashMap<Uuid, Vec<TopicTile>> = HashMap::new();
    for t in tiles {
        if t.category_id == category.id {
            own.push(t);
        } else if let Some(child) = column_of.get(&t.category_id) {
            by_child.entry(*child).or_default().push(t);
        }
    }
    let counts = topic_counts(state).await?;
    let mut columns = Vec::new();
    for child in children {
        let Some(c) = tree.get(child) else { continue };
        let mut topics = by_child.remove(&child).unwrap_or_default();
        let more = topics.len().saturating_sub(COLUMN_LIMIT);
        topics.truncate(COLUMN_LIMIT);
        columns.push(SubColumn {
            name: c.name.clone(),
            slug: c.slug.clone(),
            href: focus_url(&c.slug, sort),
            widget_bg: color_widget_css(&tree.widget_colors(child)),
            count: subtree_count(tree, &vis, &counts, child),
            topics,
            more,
        });
    }

    let (up, rail) = category_rail(tree, &vis, &counts, category, sort);
    let ancestors: Vec<UpLink> = tree
        .ancestors(category.id)
        .into_iter()
        .filter_map(|id| tree.get(id).map(|c| UpLink { name: c.name.clone(), href: focus_url(&c.slug, sort) }))
        .collect();

    let watching = match uc {
        Some(c) => crate::entities::category_watches::Entity::find()
            .filter(crate::entities::category_watches::Column::UserId.eq(c.user.id))
            .filter(crate::entities::category_watches::Column::CategoryId.eq(category.id))
            .one(state.db.as_ref())
            .await
            .map_err(ise("query watch"))?
            .is_some(),
        None => false,
    };

    super::render(
        state,
        "forum/focus.html",
        context! {
            title => category.name,
            app_name => state.config.app_name,
            user => user,
            can_write => can_write,
            category => category,
            category_widget_bg => color_widget_css(&tree.widget_colors(category.id)),
            slug => category.slug,
            watching => watching,
            ancestors => ancestors,
            up => up,
            rail => rail,
            topics => own,
            columns => columns,
            reader => reader,
            base => base,
            current_sort => sort.as_str(),
        },
    )
}

#[derive(Serialize)]
struct HomeTile {
    name: String,
    slug: String,
    href: String,
    description: Option<String>,
    widget_bg: String,
    count: u64,
    children: Vec<RailItem>,
    topics: Vec<TopicTile>,
}

/// The visual home: one tile per visible top-level category, with its
/// subcategories and its latest topics as compact squares. Each opens that
/// category's focus view (or the reader at a topic).
pub async fn home_focus(
    state: &AppState,
    tree: &CategoryTree,
    viewer: Viewer,
    uc: Option<&UserContext>,
) -> Result<Html<String>, StatusCode> {
    let vis = tree.visible_category_ids(viewer);
    let counts = topic_counts(state).await?;
    let sort = uc
        .and_then(|c| TopicSort::parse(&c.user.preferred_sort))
        .unwrap_or(TopicSort::Latest);

    let mut roots = Vec::new();
    let mut loaded = Vec::new();
    for &root in tree.roots() {
        if !vis.contains(&root) {
            continue;
        }
        let ids: Vec<Uuid> = tree.self_and_descendants(root).into_iter().filter(|i| vis.contains(i)).collect();
        let latest = topics::Entity::find()
            .filter(topics::Column::CategoryId.is_in(ids))
            .filter(topics::Column::DeletedAt.is_null())
            .order_by_desc(topics::Column::BumpedAt)
            .limit(HOME_TILE_TOPICS)
            .find_also_related(users::Entity)
            .all(state.db.as_ref())
            .await
            .map_err(ise("load latest topics"))?;
        roots.push((root, latest.iter().map(|(t, _)| t.id).collect::<Vec<_>>()));
        loaded.extend(latest);
    }
    let mut tiles: HashMap<Uuid, TopicTile> = decorate(state, tree, loaded, uc.map(|c| c.user.id))
        .await?
        .into_iter()
        .map(|t| (t.row.id, t))
        .collect();

    let categories: Vec<HomeTile> = roots
        .into_iter()
        .filter_map(|(root, topic_ids)| {
            let c = tree.get(root)?;
            Some(HomeTile {
                name: c.name.clone(),
                slug: c.slug.clone(),
                href: focus_url(&c.slug, sort),
                description: c.description.clone(),
                widget_bg: color_widget_css(&tree.widget_colors(root)),
                count: subtree_count(tree, &vis, &counts, root),
                children: tree
                    .children(root)
                    .iter()
                    .filter(|i| vis.contains(i))
                    .filter_map(|&id| {
                        tree.get(id).map(|s| RailItem {
                            name: s.name.clone(),
                            slug: s.slug.clone(),
                            href: focus_url(&s.slug, sort),
                            widget_bg: color_widget_css(&tree.widget_colors(id)),
                            count: subtree_count(tree, &vis, &counts, id),
                            current: false,
                        })
                    })
                    .collect(),
                topics: topic_ids.iter().filter_map(|id| tiles.remove(id)).collect(),
            })
        })
        .collect();

    super::render(
        state,
        "forum/home_visual.html",
        context! {
            title => "Home",
            app_name => state.config.app_name,
            user => uc.map(|c| c.user.clone()),
            categories => categories,
            current_sort => sort.as_str(),
        },
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn view_modes_parse() {
        assert_eq!(ViewMode::parse("focus"), Some(ViewMode::Focus));
        assert_eq!(ViewMode::parse("visual"), Some(ViewMode::Focus));
        assert_eq!(ViewMode::parse("classic"), Some(ViewMode::Classic));
        assert_eq!(ViewMode::parse("list"), Some(ViewMode::Classic));
        assert_eq!(ViewMode::parse("grid"), None);
    }

    fn cookies(c: &'static str) -> HeaderMap {
        let mut h = HeaderMap::new();
        h.insert(COOKIE, HeaderValue::from_static(c));
        h
    }

    #[test]
    fn signed_out_layout_lives_in_a_cookie() {
        let none = HeaderMap::new();
        let v = resolve_view(None, None, &none, false);
        assert_eq!((v.mode, v.set_cookie.is_some()), (ViewMode::Classic, false));
        let v = resolve_view(Some("focus"), None, &none, false);
        assert_eq!(v.mode, ViewMode::Focus);
        let c = v.set_cookie.unwrap();
        assert!(c.to_str().unwrap().starts_with("recourse_view=focus;") && c.to_str().unwrap().contains("Max-Age="));
        let v = resolve_view(None, None, &cookies("recourse_view=focus"), true);
        assert_eq!((v.mode, v.set_cookie.is_some()), (ViewMode::Focus, false));
        // The signed-in override cookie means nothing when signed out.
        let v = resolve_view(None, None, &cookies("recourse_view_session=focus"), false);
        assert_eq!(v.mode, ViewMode::Classic);
    }
    #[test]
    fn view_cookie_is_read_among_others() {
        let mut h = HeaderMap::new();
        h.insert(COOKIE, HeaderValue::from_static("session_token=abc; recourse_view=focus; x=y"));
        assert_eq!(cookie_value(&h, VIEW_COOKIE), Some("focus"));
        let mut h = HeaderMap::new();
        h.insert(COOKIE, HeaderValue::from_static("recourse_viewx=list"));
        assert_eq!(cookie_value(&h, VIEW_COOKIE), None);
    }

    #[test]
    fn focus_urls_keep_the_sort() {
        assert_eq!(focus_url("backend", TopicSort::Hot), "/c/backend?view=focus&sort=hot");
    }
}