Compare commits

..
Author SHA1 Message Date
fecoandClaude Opus 5.5 8150247503 Forum: thread cards with the start of the opening post, latest threads and pinned threads on the front page
CI / test (push) Successful in 3m19s
CI / build (push) Skipped
CI / deploy (push) Skipped
- Every thread card shows the start of the opening post (two lines on a
  computer, three on a phone), its topic with the icon (a lock for
  members-only and restricted ones), pinned and the wish; the replies, the
  last activity and what is new on the right (in the bottom line on a
  phone). The same card in topics, search and followed threads.
- The front page: "Legutóbbi szálak" below the topics, from every topic
  the viewer may read (not the archived ones), the latest activity first,
  20 a page with a pager; pinned threads in "Kitűzve" above the topics.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-26 18:15:43 +00:00
9 changed files with 213 additions and 48 deletions
+37
View File
@@ -152,6 +152,16 @@ pub async fn home(state: St, viewer: Viewer) -> ApiResult<Json<Value>> {
.fetch_all(&state.db) .fetch_all(&state.db)
.await?; .await?;
// Pinned threads (the daily sky too) stand above the topics.
let pinned: Vec<CardRow> = sqlx::query_as(&format!(
"{} AND th.pinned AND tp.archived_at IS NULL ORDER BY th.last_post_at DESC LIMIT 5",
card_sql(&viewer)
))
.bind(me)
.bind(since)
.fetch_all(&state.db)
.await?;
let hot: Vec<CardRow> = sqlx::query_as(&format!( let hot: Vec<CardRow> = sqlx::query_as(&format!(
"WITH recent AS (SELECT thread_id, count(*) AS n FROM forum.posts \ "WITH recent AS (SELECT thread_id, count(*) AS n FROM forum.posts \
WHERE created_at > now() - interval '24 hours' AND deleted_at IS NULL AND NOT is_opening \ WHERE created_at > now() - interval '24 hours' AND deleted_at IS NULL AND NOT is_opening \
@@ -195,6 +205,7 @@ pub async fn home(state: St, viewer: Viewer) -> ApiResult<Json<Value>> {
"online": online, "online": online,
"topics": topics, "topics": topics,
"unanswered": cards_json(&state.db, unanswered).await?, "unanswered": cards_json(&state.db, unanswered).await?,
"pinned": cards_json(&state.db, pinned).await?,
"hot": cards_json(&state.db, hot).await?, "hot": cards_json(&state.db, hot).await?,
}))) })))
} }
@@ -318,6 +329,32 @@ pub async fn topic(
}))) })))
} }
/// "Legutóbbi szálak" on the front page: the threads of every topic the
/// viewer may read (not the archived ones), the latest activity first.
const LATEST_PAGE: i64 = 20;
pub async fn latest(
State(state): St,
viewer: Viewer,
WithRejection(Query(q), _): WithRejection<Query<PageQuery>, ApiError>,
) -> ApiResult<Json<Value>> {
let page = q.page.unwrap_or(1).clamp(1, 10_000);
let (me, since) = card_params(&viewer);
let rows: Vec<CardRow> = sqlx::query_as(&format!(
"{} AND tp.archived_at IS NULL ORDER BY th.last_post_at DESC LIMIT $3 OFFSET $4",
card_sql(&viewer)
))
.bind(me)
.bind(since)
.bind(LATEST_PAGE + 1)
.bind((page - 1) * LATEST_PAGE)
.fetch_all(&state.db)
.await?;
let has_more = rows.len() as i64 > LATEST_PAGE;
let rows = rows.into_iter().take(LATEST_PAGE as usize).collect();
Ok(Json(json!({ "threads": cards_json(&state.db, rows).await?, "page": page, "has_more": has_more })))
}
/// The threads the member follows, the latest activity first, with what is unread. /// The threads the member follows, the latest activity first, with what is unread.
pub async fn followed(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> { pub async fn followed(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
viewer.require_member()?; viewer.require_member()?;
+10 -2
View File
@@ -52,6 +52,7 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/v1/forum/topics/{slug}/join", post(topics::join).delete(topics::leave)) .route("/v1/forum/topics/{slug}/join", post(topics::join).delete(topics::leave))
.route("/v1/forum/mod/topic-requests", get(topics::requests).post(topics::decide)) .route("/v1/forum/mod/topic-requests", get(topics::requests).post(topics::decide))
.route("/v1/forum/followed", get(home::followed)) .route("/v1/forum/followed", get(home::followed))
.route("/v1/forum/latest", get(home::latest))
.route("/v1/forum/replies", get(replies::list)) .route("/v1/forum/replies", get(replies::list))
.route("/v1/forum/search", get(search::search)) .route("/v1/forum/search", get(search::search))
.route("/v1/forum/share-card/{slug}", get(attachments::preview)) .route("/v1/forum/share-card/{slug}", get(attachments::preview))
@@ -155,6 +156,9 @@ pub struct CardRow {
pub unread: Option<i64>, pub unread: Option<i64>,
/// The site's own thread (the daily sky). /// The site's own thread (the daily sky).
pub system: bool, pub system: bool,
pub topic_visibility: String,
/// The opening post's text (for the excerpt on the card).
pub opening: Option<String>,
} }
/// `SELECT` of [`CardRow`]s over the threads the viewer may read; `$1` is /// `SELECT` of [`CardRow`]s over the threads the viewer may read; `$1` is
@@ -177,7 +181,9 @@ pub fn card_sql(viewer: &Viewer) -> String {
AND p.created_at > $2::timestamptz AND {} \ AND p.created_at > $2::timestamptz AND {} \
AND p.id > COALESCE((SELECT r.last_post_id FROM forum.reads r \ AND p.id > COALESCE((SELECT r.last_post_id FROM forum.reads r \
WHERE r.user_id = $1 AND r.thread_id = th.id), 0)) END AS unread, \ WHERE r.user_id = $1 AND r.thread_id = th.id), 0)) END AS unread, \
th.system \ th.system, tp.visibility AS topic_visibility, \
(SELECT p.body FROM forum.posts p WHERE p.thread_id = th.id AND p.is_opening \
AND p.deleted_at IS NULL LIMIT 1) AS opening \
FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \ FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \
WHERE th.deleted_at IS NULL AND ({}) AND {}", WHERE th.deleted_at IS NULL AND ({}) AND {}",
not_muted("p.author_id"), not_muted("p.author_id"),
@@ -204,8 +210,10 @@ pub async fn cards_json(db: &PgPool, rows: Vec<CardRow>) -> Result<Vec<Value>, s
"slug": crate::text::slug(&r.title), "slug": crate::text::slug(&r.title),
"title": r.title, "title": r.title,
"intent": r.intent, "intent": r.intent,
"topic": { "slug": r.topic_slug, "name": r.topic_name }, "topic": { "slug": r.topic_slug, "name": r.topic_name, "visibility": r.topic_visibility },
"author": r.author_id.and_then(|id| people.get(&id).cloned()), "author": r.author_id.and_then(|id| people.get(&id).cloned()),
// The start of the opening post, as much as a card shows.
"excerpt": r.opening.as_deref().map(|b| crate::text::excerpt(b, 280)),
"created_at": rfc3339(r.created_at), "created_at": rfc3339(r.created_at),
"last_post_at": rfc3339(r.last_post_at), "last_post_at": rfc3339(r.last_post_at),
"reply_count": r.reply_count, "reply_count": r.reply_count,
+1 -10
View File
@@ -98,7 +98,7 @@ pub async fn list(
"id": r.id, "id": r.id,
"thread": { "id": r.thread_id, "title": r.title, "slug": crate::text::slug(&r.title) }, "thread": { "id": r.thread_id, "title": r.title, "slug": crate::text::slug(&r.title) },
"author": r.author_id.and_then(|a| authors.get(&a).cloned()), "author": r.author_id.and_then(|a| authors.get(&a).cloned()),
"excerpt": excerpt(&r.body), "excerpt": crate::text::excerpt(&r.body, 160),
"created_at": rfc3339(r.created_at), "created_at": rfc3339(r.created_at),
"kind": r.kind, "kind": r.kind,
"unread": r.unread, "unread": r.unread,
@@ -124,12 +124,3 @@ pub async fn read_all(State(state): St, viewer: Viewer) -> ApiResult<StatusCode>
.await?; .await?;
Ok(StatusCode::NO_CONTENT) Ok(StatusCode::NO_CONTENT)
} }
/// The start of a post, on one line.
fn excerpt(body: &str) -> String {
let line = body.split_whitespace().collect::<Vec<_>>().join(" ");
match line.char_indices().nth(160) {
Some((at, _)) => format!("{}…", line[..at].trim_end()),
None => line,
}
}
+28
View File
@@ -1408,3 +1408,31 @@ async fn any_member_may_upload_an_avatar(pool: PgPool) {
assert_eq!(status, StatusCode::FORBIDDEN); assert_eq!(status, StatusCode::FORBIDDEN);
assert!(body.to_string().contains("nem érhető el"), "{body}"); assert!(body.to_string().contains("nem érhető el"), "{body}");
} }
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn latest_threads_with_their_beginning(pool: PgPool) {
let app = TestApp::new(pool);
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
let public = app.thread(&anna, "torzsasztal", "Téli levesek").await;
let members = app.thread(&anna, "ami-a-szivemen-van", "Nehéz napok").await;
app.reply(&anna, public, "Még egy gondolat.", None).await;
let ids =
|v: Value| -> Vec<i64> { v["threads"].as_array().unwrap().iter().map(|t| t["id"].as_i64().unwrap()).collect() };
// Members see every topic they may read, the latest activity first; visitors the public ones.
assert_eq!(ids(app.get("/v1/forum/latest", Some(&anna)).await), vec![public, members]);
let visitor = app.get("/v1/forum/latest", None).await;
assert_eq!(ids(visitor.clone()), vec![public]);
assert_eq!(visitor["has_more"], false);
// The card carries the start of the opening post and the topic's visibility.
let card = &visitor["threads"][0];
assert!(card["excerpt"].as_str().unwrap().len() > 3, "{card}");
assert_eq!(card["topic"]["visibility"], "public");
// A pinned thread stands above the topics on the front page.
let admin = app.member("admin@example.com", "Gondnok", &["admin"]).await;
let (status, _) =
app.call("PATCH", &format!("/v1/forum/threads/{public}"), Some(&admin), json!({ "pinned": true })).await;
assert_eq!(status, StatusCode::NO_CONTENT);
let home = app.get("/v1/forum/home", None).await;
assert_eq!(home["pinned"][0]["id"], public);
}
+14
View File
@@ -142,6 +142,20 @@ pub fn default_avatar(key: &str) -> String {
format!("{}-{}", AVATAR_GLYPHS[n % AVATAR_GLYPHS.len()], AVATAR_COLOURS[(n / 7) % AVATAR_COLOURS.len()]) format!("{}-{}", AVATAR_GLYPHS[n % AVATAR_GLYPHS.len()], AVATAR_COLOURS[(n / 7) % AVATAR_COLOURS.len()])
} }
/// The start of a text on one line, at most `max` characters (cut at a word, with "…").
pub fn excerpt(body: &str, max: usize) -> String {
let line = body.split_whitespace().collect::<Vec<_>>().join(" ");
if line.chars().count() <= max {
return line;
}
let cut: String = line.chars().take(max).collect();
let cut = match cut.rfind(' ') {
Some(at) if at > max / 2 => &cut[..at],
_ => &cut[..],
};
format!("{}…", cut.trim_end_matches([',', ';', ':', '–', '-', ' ']))
}
/// The readable part of a thread's address: `nem-tudom-elengedni-anyukam-hazat`. /// The readable part of a thread's address: `nem-tudom-elengedni-anyukam-hazat`.
pub fn slug(title: &str) -> String { pub fn slug(title: &str) -> String {
let ascii = deunicode::deunicode(title).to_lowercase(); let ascii = deunicode::deunicode(title).to_lowercase();
+19
View File
@@ -786,3 +786,22 @@ a.fh-online-item:hover { color: var(--gold); }
display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap;
padding: 10px 12px 10px 18px; border-top: 1px solid var(--line); background: var(--f-tint); padding: 10px 12px 10px 18px; border-top: 1px solid var(--line); background: var(--f-tint);
} }
/* --- thread cards with the start of the opening post --- */
.ft-row { align-items: flex-start; }
.ft-tags { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 8px; font-size: 13px; color: var(--ink-2); }
.ft-topic { display: inline-flex; align-items: center; gap: 5px; }
.ft-topic .topic-icon { width: 14px; height: 14px; }
.ft-lock { width: 11px; height: 11px; fill: none; stroke: var(--muted); stroke-width: 2; stroke-linecap: round; }
.ft-row .ft-excerpt { font-size: 14.5px; line-height: 1.5; -webkit-line-clamp: 3; }
.ft-meta { flex-wrap: wrap; font-size: 13px; }
.ft-who { color: var(--ink); font-weight: 500; }
.ft-m-new { margin-left: auto; }
.ft-side { display: none; }
@media (min-width: 760px) {
.ft-row { display: grid; grid-template-columns: minmax(0, 1fr) 140px; gap: 0 24px; padding: 16px 20px; align-items: center; }
.ft-row .ft-excerpt { font-size: 15px; -webkit-line-clamp: 2; }
.ft-side { display: flex; flex-direction: column; align-items: flex-end; gap: 4px; text-align: right; font-size: 15px; color: var(--ink); }
.ft-side .hint { font-size: 13px; }
.ft-side strong { font-weight: 600; }
}
+39 -3
View File
@@ -8,7 +8,7 @@ import { TopicIcon } from "@/components/forum/TopicIcon";
import { ThreadList, WaitingCard } from "@/components/forum/ThreadList"; import { ThreadList, WaitingCard } from "@/components/forum/ThreadList";
import { MoonPhaseIcon } from "@/components/MoonChip"; import { MoonPhaseIcon } from "@/components/MoonChip";
import { MOON_PHASES, SIGNS } from "@/lib/astro"; import { MOON_PHASES, SIGNS } from "@/lib/astro";
import { type ForumHome, ago, memberHref } from "@/lib/forum"; import { type ForumHome, type ThreadCard, ago, memberHref } from "@/lib/forum";
import { forumGet } from "@/lib/forumServer"; import { forumGet } from "@/lib/forumServer";
import { loadSky } from "@/lib/sky"; import { loadSky } from "@/lib/sky";
import { MOON_IN_SIGN, SIGN_IN, withArticle } from "@/lib/skyText"; import { MOON_IN_SIGN, SIGN_IN, withArticle } from "@/lib/skyText";
@@ -61,10 +61,16 @@ function SkyCard({ sky }: { sky: SkyNow }) {
); );
} }
export default async function ForumHomePage() { export default async function ForumHomePage({ searchParams }: { searchParams: Promise<{ oldal?: string }> }) {
const [home, sky] = await Promise.all([forumGet<ForumHome>("/v1/forum/home"), loadSky()]); const page = Math.max(1, Number((await searchParams).oldal) || 1);
const [home, sky, latest] = await Promise.all([
forumGet<ForumHome>("/v1/forum/home"),
loadSky(),
forumGet<{ threads: ThreadCard[]; has_more: boolean }>(`/v1/forum/latest?page=${page}`),
]);
if (!home.ok) notFound(); if (!home.ok) notFound();
const { viewer, replies, waiting, topics, unanswered, hot } = home.data; const { viewer, replies, waiting, topics, unanswered, hot } = home.data;
const pinned = home.data.pinned ?? [];
return ( return (
<div className="fh fh-home"> <div className="fh fh-home">
@@ -135,6 +141,17 @@ export default async function ForumHomePage() {
</section> </section>
)} )}
{pinned.length > 0 && (
<section className="fh-section o-6" aria-labelledby="fh-pinned">
<div className="fh-section-head">
<h2 id="fh-pinned">Kitűzve</h2>
</div>
<div className="fh-card fh-flush">
<ThreadList threads={pinned} />
</div>
</section>
)}
<section className="fh-section o-6" aria-labelledby="fh-topics"> <section className="fh-section o-6" aria-labelledby="fh-topics">
<div className="fh-section-head"> <div className="fh-section-head">
<h2 id="fh-topics">Témák</h2> <h2 id="fh-topics">Témák</h2>
@@ -234,6 +251,25 @@ export default async function ForumHomePage() {
</details> </details>
)} )}
</section> </section>
{latest.ok && (latest.data.threads.length > 0 || page > 1) && (
<section className="fh-section o-6" id="legutobbi" aria-labelledby="fh-latest">
<div className="fh-section-head">
<h2 id="fh-latest">Legutóbbi szálak</h2>
<span className="hint">a legfrissebb beszélgetések elöl</span>
</div>
<div className="fh-card fh-flush">
<ThreadList threads={latest.data.threads} />
</div>
{(page > 1 || latest.data.has_more) && (
<nav className="forum-pager" aria-label="Lapozás">
{page > 1 ? <Link href={`/forum?oldal=${page - 1}#legutobbi`}>‹ Újabbak</Link> : <span />}
<span className="hint">{page}. oldal</span>
{latest.data.has_more ? <Link href={`/forum?oldal=${page + 1}#legutobbi`}>Régebbiek ›</Link> : <span />}
</nav>
)}
</section>
)}
</div> </div>
<aside className="fh-col fh-col-side" aria-label="Oldalsáv"> <aside className="fh-col fh-col-side" aria-label="Oldalsáv">
@@ -3,6 +3,7 @@ import Link from "next/link";
import { INTENTS, type ThreadCard, ago, threadHref } from "@/lib/forum"; import { INTENTS, type ThreadCard, ago, threadHref } from "@/lib/forum";
import { Avatar } from "./Avatar"; import { Avatar } from "./Avatar";
import { TopicIcon } from "./TopicIcon";
export function IntentTag({ intent, long = false }: { intent: ThreadCard["intent"]; long?: boolean }) { export function IntentTag({ intent, long = false }: { intent: ThreadCard["intent"]; long?: boolean }) {
if (!intent) return null; if (!intent) return null;
@@ -10,53 +11,80 @@ export function IntentTag({ intent, long = false }: { intent: ThreadCard["intent
return <span className={`ft-intent ft-intent-${intent}`}>{text}</span>; return <span className={`ft-intent ft-intent-${intent}`}>{text}</span>;
} }
function UnreadPill({ n }: { n: number | null }) { function UnreadPill({ n, onlyNew = false }: { n: number | null; onlyNew?: boolean }) {
if (n === null) return null; if (n === null) return null;
if (n === 0) return <span className="ft-read">olvasva</span>; if (n === 0) return onlyNew ? null : <span className="ft-read">olvasva</span>;
return <span className="ft-new">{n > 99 ? "99+" : n} új</span>; return <span className="ft-new">{n > 99 ? "99+" : n} új</span>;
} }
/** Threads in a list: title, topic, replies, the starter, what is new. */ /**
* Threads in a list. Each card: the topic (with a lock for members-only and
* restricted ones), pinned and the wish, the title, the start of the opening
* post (two lines on a computer, three on a phone), the starter; replies,
* the last activity and what is new on the right on a computer, in the
* bottom line on a phone.
*/
export function ThreadList({ threads, showTopic = true }: { threads: ThreadCard[]; showTopic?: boolean }) { export function ThreadList({ threads, showTopic = true }: { threads: ThreadCard[]; showTopic?: boolean }) {
return ( return (
<ul className="ft-list"> <ul className="ft-list">
{threads.map((t) => ( {threads.map((t) => {
const closed = t.topic.visibility !== undefined && t.topic.visibility !== "public";
const tags = showTopic || t.pinned || t.locked || t.intent;
return (
<li key={t.id}> <li key={t.id}>
<Link href={threadHref(t)} className="ft-row"> <Link href={threadHref(t)} className="ft-row">
<span className="ft-main"> <span className="ft-main">
<span className="ft-title"> {tags && (
<span className="ft-tags">
{showTopic && (
<span className="ft-topic">
<TopicIcon slug={t.topic.slug} />
{t.topic.name}
{closed && (
<svg viewBox="0 0 24 24" className="ft-lock" role="img" aria-label="Nem nyilvános téma">
<rect x="5" y="11" width="14" height="9" rx="2" />
<path d="M8 11V8a4 4 0 0 1 8 0v3" />
</svg>
)}
</span>
)}
{t.pinned && <span className="ft-pin">Kitűzve</span>} {t.pinned && <span className="ft-pin">Kitűzve</span>}
{t.locked && <span className="ft-pin">Lezárva</span>} {t.locked && <span className="ft-pin">Lezárva</span>}
{t.title} <IntentTag intent={t.intent} />
</span> </span>
)}
<span className="ft-title">{t.title}</span>
{t.excerpt && <span className="ft-excerpt">{t.excerpt}</span>}
<span className="ft-meta"> <span className="ft-meta">
{t.author && <Avatar avatar={t.author.avatar} size={20} online={t.author.online} />} {t.author && <Avatar avatar={t.author.avatar} size={20} online={t.author.online} />}
<span> <span className="ft-who">{t.system ? "Sorsfonalak" : (t.author?.nickname ?? "Törölt tag")}</span>
{t.system ? "Sorsfonalak" : (t.author?.nickname ?? "Törölt tag")}
{showTopic && ` · ${t.topic.name}`}
<span className="ft-m-narrow"> <span className="ft-m-narrow">
{" "}
· {t.reply_count} válasz ·{" "} · {t.reply_count} válasz ·{" "}
<time suppressHydrationWarning dateTime={t.last_post_at}> <time suppressHydrationWarning dateTime={t.last_post_at}>
{ago(t.last_post_at)} {ago(t.last_post_at)}
</time> </time>
</span> </span>
<span className="ft-m-narrow ft-m-new">
<UnreadPill n={t.unread} onlyNew />
</span> </span>
</span> </span>
</span> </span>
<span className="ft-col ft-col-replies"> <span className="ft-side">
<span>
<strong>{t.reply_count}</strong> válasz <strong>{t.reply_count}</strong> válasz
{t.participants > 1 && <span className="hint">{t.participants} résztvevő</span>}
</span> </span>
<span className="ft-col ft-col-last"> <span className="hint">
utoljára{" "}
<time suppressHydrationWarning dateTime={t.last_post_at}> <time suppressHydrationWarning dateTime={t.last_post_at}>
{ago(t.last_post_at)} {ago(t.last_post_at)}
</time> </time>
</span> </span>
<UnreadPill n={t.unread} /> <UnreadPill n={t.unread} />
</span>
</Link> </Link>
</li> </li>
))} );
})}
</ul> </ul>
); );
} }
+5 -1
View File
@@ -61,8 +61,10 @@ export interface ThreadCard {
slug: string; slug: string;
title: string; title: string;
intent: "listen" | "advice" | null; intent: "listen" | "advice" | null;
topic: TopicRef; topic: TopicRef & { visibility?: string };
author: ForumAuthor | null; author: ForumAuthor | null;
/** The start of the opening post (as much as a card shows). */
excerpt?: string | null;
created_at: string; created_at: string;
last_post_at: string; last_post_at: string;
reply_count: number; reply_count: number;
@@ -86,6 +88,8 @@ export interface ForumHome {
topics: ForumTopic[]; topics: ForumTopic[];
unanswered: ThreadCard[]; unanswered: ThreadCard[];
hot: ThreadCard[]; hot: ThreadCard[];
/** Pinned threads, above the topics. */
pinned?: ThreadCard[];
} }
export interface TopicPage { export interface TopicPage {