5.2 KiB · text History 644543b
//! The landing page (`/`): two columns in both layouts. Categories on the
//! left (the visible top level, each with its visible children), the latest
//! topics across everything the viewer can see on the right. Classic shows
//! the latest as the usual topic table; Focus as tiles, with the reader
//! (`&topic=<id>`) stepping through that same list.
//!
//! The full categories page that used to be the landing lives at `/c/`
//! ([`super::forum::categories_index`]).

use std::collections::HashSet;

use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode};
use axum::response::Response;
use minijinja::context;
use sea_orm::*;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use super::focus::{self, subtree_count, topic_counts, ViewMode};
use super::forum::{build_topic_rows, ise, viewer_of, TopicSort};
use crate::category_tree::{color_widget_css, CategoryTree};
use crate::entities::{topics, users};
use crate::middleware::UserContext;
use crate::AppState;

/// How many topics the latest column shows.
pub(crate) const LATEST_LIMIT: u64 = 30;

#[derive(Debug, Deserialize)]
pub struct LandingQuery {
    /// `classic` or `focus` (or the old `list`/`visual`); see
    /// [`focus::resolve_view`].
    pub view: Option<String>,
    /// Focus: open the reader at this topic.
    pub topic: Option<Uuid>,
}

#[derive(Serialize)]
struct SideCategory {
    name: String,
    slug: String,
    href: String,
    widget_bg: String,
    count: u64,
    children: Vec<SideCategory>,
}

/// The newest-activity live topics in categories the viewer can see.
pub(crate) async fn latest_topics(
    state: &AppState,
    vis: &HashSet<Uuid>,
    limit: u64,
) -> Result<Vec<(topics::Model, Option<users::Model>)>, StatusCode> {
    if vis.is_empty() {
        return Ok(Vec::new());
    }
    topics::Entity::find()
        .filter(topics::Column::CategoryId.is_in(vis.iter().copied()))
        .filter(topics::Column::DeletedAt.is_null())
        .order_by_desc(topics::Column::BumpedAt)
        .limit(limit)
        .find_also_related(users::Entity)
        .all(state.db.as_ref())
        .await
        .map_err(ise("load latest topics"))
}

pub async fn home(
    State(state): State<AppState>,
    Query(q): Query<LandingQuery>,
    headers: HeaderMap,
    user_context: Option<UserContext>,
) -> Result<Response, StatusCode> {
    let uc = user_context.as_ref();
    let view = focus::view_for(&state, q.view.as_deref(), uc, &headers);
    let is_focus = view.mode == ViewMode::Focus;

    let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load category tree"))?;
    let vis = tree.visible_category_ids(viewer_of(&user_context));
    let loaded = latest_topics(&state, &vis, LATEST_LIMIT).await?;

    // Focus: the reader's own htmx requests need only #reader.
    let base = "/?view=focus".to_string();
    if is_focus && focus::wants_reader(&headers) {
        let (_, reader) = focus::tiles_and_reader(&state, &tree, loaded, uc, &headers, q.topic).await?;
        return Ok(view.respond(focus::reader_fragment(&state, reader, &base, uc)?));
    }

    let counts = topic_counts(&state).await?;
    let sort = uc
        .and_then(|c| TopicSort::parse(&c.user.preferred_sort))
        .unwrap_or(TopicSort::Latest);
    let href = |slug: &str| {
        if is_focus { focus::focus_url(slug, sort) } else { format!("/c/{slug}") }
    };
    let side = |id: Uuid| -> Option<SideCategory> {
        let c = tree.get(id)?;
        Some(SideCategory {
            name: c.name.clone(),
            slug: c.slug.clone(),
            href: href(&c.slug),
            widget_bg: color_widget_css(&tree.widget_colors(id)),
            count: subtree_count(&tree, &vis, &counts, id),
            children: Vec::new(),
        })
    };
    let categories: Vec<SideCategory> = tree
        .roots()
        .iter()
        .filter(|id| vis.contains(id))
        .filter_map(|&root| {
            let mut row = side(root)?;
            row.children = tree
                .children(root)
                .iter()
                .filter(|id| vis.contains(id))
                .filter_map(|&id| side(id))
                .collect();
            Some(row)
        })
        .collect();

    let user = uc.map(|c| c.user.clone());
    let can_write = uc.is_some_and(|c| super::may_write(&state, &c.user));
    let page = if is_focus {
        let (tiles, reader) = focus::tiles_and_reader(&state, &tree, loaded, uc, &headers, q.topic).await?;
        super::render(
            &state,
            "forum/landing_focus.html",
            context! {
                title => "Home",
                app_name => state.config.app_name,
                user => user,
                can_write => can_write,
                categories => categories,
                topics => tiles,
                reader => reader,
                base => base,
            },
        )?
    } else {
        let rows = build_topic_rows(&state, &tree, loaded).await?;
        super::render(
            &state,
            "forum/landing.html",
            context! {
                title => "Home",
                app_name => state.config.app_name,
                user => user,
                can_write => can_write,
                categories => categories,
                topics => rows,
            },
        )?
    };
    Ok(view.respond(page))
}