24.0 KiB · text History da3a685
//! Visual mode: 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.
//!
//! * `/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;

/// Anonymous viewers' remembered view (signed-in users: `users.preferred_view`).
pub const VIEW_COOKIE: &str = "recourse_view";

/// How many compact squares a subcategory column shows before "+N more".
const COLUMN_LIMIT: usize = 24;
/// Compact squares per category on the visual 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;

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ViewMode {
    List,
    Focus,
}

impl ViewMode {
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "list" => Some(Self::List),
            "focus" | "visual" => Some(Self::Focus),
            _ => None,
        }
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Self::List => "list",
            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 view to render, and a `Set-Cookie` to send with it.
pub struct ViewChoice {
    pub mode: ViewMode,
    pub set_cookie: Option<HeaderValue>,
}

impl ViewChoice {
    /// Attach the cookie (if any) to a rendered page.
    pub fn respond(self, page: Html<String>) -> Response {
        match self.set_cookie {
            Some(c) => {
                let mut headers = HeaderMap::new();
                headers.insert(axum::http::header::SET_COOKIE, c);
                (headers, page).into_response()
            }
            None => page.into_response(),
        }
    }
}

/// Like the topic sort: an explicit `?view=` wins and is remembered (on the
/// account when signed in, else in a cookie); otherwise the remembered
/// choice; otherwise the list.
pub async fn resolve_view(
    state: &AppState,
    requested: Option<&str>,
    uc: Option<&UserContext>,
    headers: &HeaderMap,
) -> ViewChoice {
    let requested = requested.and_then(ViewMode::parse);
    let remembered = match uc {
        Some(c) => ViewMode::parse(&c.user.preferred_view),
        None => cookie_value(headers, VIEW_COOKIE).and_then(ViewMode::parse),
    };
    let mut set_cookie = None;
    if let Some(req) = requested.filter(|r| Some(*r) != remembered) {
        match uc {
            Some(c) => {
                let mut am: users::ActiveModel = c.user.clone().into();
                am.preferred_view = Set(req.as_str().to_string());
                let _ = am.update(state.db.as_ref()).await;
            }
            None => {
                let secure = if state.config.secure_cookies() { "; Secure" } else { "" };
                set_cookie = HeaderValue::from_str(&format!(
                    "{VIEW_COOKIE}={}; Path=/; Max-Age=31536000; SameSite=Lax{secure}",
                    req.as_str()
                ))
                .ok();
            }
        }
    }
    ViewChoice {
        mode: requested.or(remembered).unwrap_or(ViewMode::List),
        set_cookie,
    }
}

/// `/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)]
struct RailItem {
    name: String,
    slug: String,
    href: String,
    widget_bg: String,
    count: u64,
    current: bool,
}

#[derive(Serialize)]
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)]
    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,
    #[serde(skip)]
    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)]
struct StripItem {
    id: Uuid,
    title: String,
    widget_bg: String,
    current: bool,
    unread: bool,
}

#[derive(Serialize)]
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.
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,
                category_id,
                row,
            }
        })
        .collect())
}

/// 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 viewer_id = uc.map(|c| c.user.id);
    let base = focus_url(&category.slug, sort);

    // Every visible topic under the category, in the current sort: the
    // filmstrip and the stepping order (the list view's order).
    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.iter().copied()))
        .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);

    // The reader: only for a topic in this list (so never one the viewer
    // can't see, nor a deleted one). Counts a view and marks it read exactly
    // as the topic page does.
    let reader = 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);
            Some((i, topic.clone(), author.as_ref().map(|u| u.username.clone()), cat.map(|c| (c.name.clone(), c.slug.clone())), posts))
        }
        None => None,
    };

    let tiles = decorate(state, tree, loaded, viewer_id).await?;
    let reader = reader.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: 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 == topic.id,
                    unread: t.row.id != topic.id && (t.is_new || t.unread > 0),
                })
                .collect(),
            topic,
        }
    });

    let user = uc.map(|c| c.user.clone());
    let can_write = uc.is_some_and(|c| super::may_write(state, &c.user));
    if headers.get("hx-target").and_then(|v| v.to_str().ok()) == Some("reader") {
        return super::render(
            state,
            "forum/_reader.html",
            context! { reader => reader, base => base, user => user, can_write => can_write },
        );
    }

    // 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,
        });
    }

    // The rail: the category and its siblings, as pin_flip's focus_siblings.
    let siblings: Vec<Uuid> = match category.parent_id {
        Some(p) => tree.children(p).to_vec(),
        None => tree.roots().to_vec(),
    };
    let rail: Vec<RailItem> = 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();
    // `..`: the parent (visible, since the category is), or the visual home.
    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() },
    };
    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("list"), Some(ViewMode::List));
        assert_eq!(ViewMode::parse("grid"), None);
    }

    #[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");
    }
}