Forum: answers to me as the only count, reply box in the branch, keyboard-safe inputs
- The "Követett" tab becomes "Válaszok": its count is the unread answers to the member (a reply to their post, a first-level reply in their thread, or a post naming them), listed on /forum/valaszok with "Mind olvasott"; the followed threads are its second view. The other counts are gone from the menu; listeners see the waiting threads on their card on the front page. - Replying to a post opens the box at the bottom of its branch and scrolls there; another branch moves it (with the text typed so far). - Phones: while typing, the forum's bottom menu and floating bars step aside and the box with its send button is scrolled above the keyboard (KeyboardSafe, site-wide; Android resizes the page for the keyboard). - The "Meghallgató" badge is now "Kísérő", with a new icon. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -174,9 +174,20 @@ pub async fn home(state: St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
||||
let people = super::authors(&state.db, present.iter().copied()).await?;
|
||||
let online: Vec<Value> = present.iter().filter_map(|id| people.get(id).cloned()).collect();
|
||||
|
||||
// Volunteer listeners: threads asking to be heard, still without a reply.
|
||||
let waiting = match &viewer.member {
|
||||
Some(m) if m.listener => Some(waiting_count(&state, &viewer).await?),
|
||||
_ => None,
|
||||
};
|
||||
let replies = match &viewer.member {
|
||||
Some(m) => Some(super::replies::unread_count(&state.db, &viewer, m.user_id).await?),
|
||||
None => None,
|
||||
};
|
||||
Ok(Json(json!({
|
||||
"viewer": viewer_json(&viewer),
|
||||
"followed": followed,
|
||||
"replies": replies,
|
||||
"waiting": waiting,
|
||||
"online": online,
|
||||
"topics": topics,
|
||||
"unanswered": cards_json(&state.db, unanswered).await?,
|
||||
@@ -234,17 +245,16 @@ pub async fn nav(state: St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// Volunteer listeners: threads asking to be heard, still without a reply.
|
||||
let waiting = match &viewer.member {
|
||||
Some(m) if m.listener => Some(waiting_count(&state, &viewer).await?),
|
||||
_ => None,
|
||||
// The only count on the forum tab: unread answers to the member.
|
||||
let replies = match &viewer.member {
|
||||
Some(m) => Some(super::replies::unread_count(&state.db, &viewer, m.user_id).await?),
|
||||
None => None,
|
||||
};
|
||||
Ok(Json(json!({
|
||||
"viewer": viewer_json(&viewer),
|
||||
"followed": followed_counts(&state, &viewer).await?,
|
||||
"replies": replies,
|
||||
"messages": messages,
|
||||
"reports": reports,
|
||||
"waiting": waiting,
|
||||
})))
|
||||
}
|
||||
|
||||
|
||||
@@ -164,7 +164,7 @@ pub async fn save_me(
|
||||
if req.listener == Some(true) {
|
||||
let newcomer = viewer.member.as_ref().is_none_or(|m| m.rank(OffsetDateTime::now_utc()).is_newcomer());
|
||||
if newcomer && !viewer.is_moderator() {
|
||||
return Err(ApiError::Forbidden("Meghallgatónak a Kereső rangtól jelentkezhetsz.".into()));
|
||||
return Err(ApiError::Forbidden("Kísérőnek a Kereső rangtól jelentkezhetsz.".into()));
|
||||
}
|
||||
}
|
||||
if req.supporter_badge == Some(true) && !super::has_purchase(&state.db, user.id).await? {
|
||||
|
||||
@@ -12,6 +12,7 @@ mod mentions;
|
||||
mod messages;
|
||||
mod moderation;
|
||||
mod posts;
|
||||
mod replies;
|
||||
mod reports;
|
||||
mod threads;
|
||||
mod topics;
|
||||
@@ -48,6 +49,8 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
.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/followed", get(home::followed))
|
||||
.route("/v1/forum/replies", get(replies::list))
|
||||
.route("/v1/forum/replies/read", post(replies::read_all))
|
||||
.route("/v1/forum/threads", post(threads::create))
|
||||
.route("/v1/forum/threads/{id}", get(threads::show).patch(threads::update).delete(threads::remove))
|
||||
.route("/v1/forum/threads/{id}/restore", post(threads::restore))
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
//! "Válaszok": what answers the member. A reply to one of their posts (also
|
||||
//! a reply to a reply of theirs, `reply_to_id`), a first-level reply in a
|
||||
//! thread they opened, or a post that names them ("@Holdfény"). One stays
|
||||
//! unread until the member has read that far in the thread; the forum menu
|
||||
//! shows only this count.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Query, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::PgPool;
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{St, rfc3339, visible_topics};
|
||||
use crate::auth::Viewer;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
|
||||
/// The posts that answer `$1`, from the threads the viewer may read.
|
||||
fn answers(viewer: &Viewer) -> String {
|
||||
format!(
|
||||
"FROM forum.posts p \
|
||||
JOIN forum.threads th ON th.id = p.thread_id \
|
||||
JOIN forum.topics tp ON tp.id = th.topic_id \
|
||||
LEFT JOIN forum.posts target ON target.id = COALESCE(p.reply_to_id, p.parent_id) \
|
||||
LEFT JOIN forum.reads r ON r.user_id = $1 AND r.thread_id = p.thread_id \
|
||||
WHERE p.deleted_at IS NULL AND th.deleted_at IS NULL AND NOT p.is_opening AND NOT p.system \
|
||||
AND p.author_id IS DISTINCT FROM $1 AND ({}) \
|
||||
AND (target.author_id = $1 \
|
||||
OR (p.parent_id IS NULL AND th.author_id = $1) \
|
||||
OR EXISTS (SELECT 1 FROM forum.mentions mn WHERE mn.post_id = p.id AND mn.user_id = $1))",
|
||||
visible_topics(viewer)
|
||||
)
|
||||
}
|
||||
|
||||
const UNREAD: &str = "p.id > COALESCE(r.last_post_id, 0)";
|
||||
|
||||
/// How many answers wait unread (for the menu), at most 100.
|
||||
pub async fn unread_count(db: &PgPool, viewer: &Viewer, me: Uuid) -> Result<i64, sqlx::Error> {
|
||||
sqlx::query_scalar(&format!("SELECT count(*) FROM (SELECT 1 {} AND {UNREAD} LIMIT 100) x", answers(viewer)))
|
||||
.bind(me)
|
||||
.fetch_one(db)
|
||||
.await
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ListQuery {
|
||||
#[serde(default)]
|
||||
page: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct Row {
|
||||
id: i64,
|
||||
thread_id: i64,
|
||||
title: String,
|
||||
author_id: Option<Uuid>,
|
||||
body: String,
|
||||
created_at: OffsetDateTime,
|
||||
kind: String,
|
||||
unread: bool,
|
||||
}
|
||||
|
||||
const PAGE: i64 = 30;
|
||||
|
||||
/// The member's answers, newest first.
|
||||
pub async fn list(
|
||||
State(state): St,
|
||||
viewer: Viewer,
|
||||
WithRejection(Query(q), _): WithRejection<Query<ListQuery>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let member = viewer.require_member()?;
|
||||
let page = q.page.unwrap_or(1).clamp(1, 1000);
|
||||
let rows: Vec<Row> = sqlx::query_as(&format!(
|
||||
"SELECT p.id, p.thread_id, th.title, p.author_id, p.body, p.created_at, \
|
||||
CASE WHEN target.author_id = $1 THEN 'reply' \
|
||||
WHEN p.parent_id IS NULL AND th.author_id = $1 THEN 'thread' \
|
||||
ELSE 'mention' END AS kind, \
|
||||
{UNREAD} AS unread \
|
||||
{} ORDER BY p.id DESC LIMIT {} OFFSET $2",
|
||||
answers(&viewer),
|
||||
PAGE + 1
|
||||
))
|
||||
.bind(member.user_id)
|
||||
.bind((page - 1) * PAGE)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
let more = rows.len() as i64 > PAGE;
|
||||
let rows = &rows[..rows.len().min(PAGE as usize)];
|
||||
let authors = super::authors(&state.db, rows.iter().filter_map(|r| r.author_id)).await?;
|
||||
let replies: Vec<Value> = rows
|
||||
.iter()
|
||||
.map(|r| {
|
||||
json!({
|
||||
"id": r.id,
|
||||
"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()),
|
||||
"excerpt": excerpt(&r.body),
|
||||
"created_at": rfc3339(r.created_at),
|
||||
"kind": r.kind,
|
||||
"unread": r.unread,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let unread = unread_count(&state.db, &viewer, member.user_id).await?;
|
||||
Ok(Json(json!({ "replies": replies, "unread": unread, "page": page, "more": more })))
|
||||
}
|
||||
|
||||
/// "Mind olvasott": the threads with unread answers count as read up to them.
|
||||
pub async fn read_all(State(state): St, viewer: Viewer) -> ApiResult<StatusCode> {
|
||||
let member = viewer.require_member()?;
|
||||
sqlx::query(&format!(
|
||||
"INSERT INTO forum.reads (user_id, thread_id, last_post_id) \
|
||||
SELECT $1, p.thread_id, max(p.id) {} AND {UNREAD} GROUP BY p.thread_id \
|
||||
ON CONFLICT (user_id, thread_id) DO UPDATE \
|
||||
SET last_post_id = GREATEST(forum.reads.last_post_id, EXCLUDED.last_post_id), read_at = now()",
|
||||
answers(&viewer)
|
||||
))
|
||||
.bind(member.user_id)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -1044,8 +1044,8 @@ async fn mentions_listeners_supporters_and_who_is_here(pool: PgPool) {
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(app.get("/v1/forum/nav", Some(&bea)).await["waiting"], 1);
|
||||
assert!(app.get("/v1/forum/nav", Some(&cili)).await["waiting"].is_null());
|
||||
assert_eq!(app.get("/v1/forum/home", Some(&bea)).await["waiting"], 1);
|
||||
assert!(app.get("/v1/forum/home", Some(&cili)).await["waiting"].is_null());
|
||||
let shown = app.get(&format!("/v1/forum/threads/{thread}"), Some(&anna)).await;
|
||||
assert!(shown["posts"].as_array().unwrap().iter().all(|p| p["author"]["supporter"] == false));
|
||||
|
||||
@@ -1080,3 +1080,53 @@ async fn mentions_listeners_supporters_and_who_is_here(pool: PgPool) {
|
||||
.collect();
|
||||
assert!(here.contains(&"Zöldág".to_string()) && !here.contains(&"Csendesvíz".to_string()));
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn answers_to_the_member(pool: PgPool) {
|
||||
let app = TestApp::new(pool);
|
||||
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
|
||||
let bea = app.member("bea@example.com", "Holdfény", &["user"]).await;
|
||||
let cili = app.member("cili@example.com", "Zöldág", &["user"]).await;
|
||||
let answers = |v: Value| -> Vec<(i64, String, bool)> {
|
||||
v["replies"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|r| (r["id"].as_i64().unwrap(), r["kind"].as_str().unwrap().to_string(), r["unread"] == true))
|
||||
.collect()
|
||||
};
|
||||
|
||||
// Anna's thread: Bea replies to it, Anna answers, Cili answers Anna's answer
|
||||
// (on the second level, under Bea's post) and names Bea elsewhere.
|
||||
let thread = app.thread(&anna, "torzsasztal", "Téli levesek").await;
|
||||
let first = app.reply(&bea, thread, "Gulyás.", None).await["id"].as_i64().unwrap();
|
||||
let second = app.reply(&anna, thread, "Az jó ötlet.", Some(first)).await["id"].as_i64().unwrap();
|
||||
let third = app.reply(&cili, thread, "Szerintem is.", Some(second)).await["id"].as_i64().unwrap();
|
||||
let fourth = app.reply(&cili, thread, "@Holdfény, babbal?", None).await["id"].as_i64().unwrap();
|
||||
|
||||
// Anna: Bea's reply in her thread (read once she answered it), Cili's answer
|
||||
// to her, and Cili's first-level post in her thread.
|
||||
assert_eq!(
|
||||
answers(app.get("/v1/forum/replies", Some(&anna)).await),
|
||||
vec![(fourth, "thread".into(), true), (third, "reply".into(), true), (first, "thread".into(), false)]
|
||||
);
|
||||
assert_eq!(app.get("/v1/forum/nav", Some(&anna)).await["replies"], 2);
|
||||
// Bea: Anna answered her; Cili named her. Cili's answer was to Anna, not to her.
|
||||
assert_eq!(
|
||||
answers(app.get("/v1/forum/replies", Some(&bea)).await),
|
||||
vec![(fourth, "mention".into(), true), (second, "reply".into(), true)]
|
||||
);
|
||||
// Nothing for Cili; a visitor gets nothing.
|
||||
assert_eq!(app.get("/v1/forum/nav", Some(&cili)).await["replies"], 0);
|
||||
assert!(app.get("/v1/forum/nav", None).await["replies"].is_null());
|
||||
|
||||
// Reading the thread clears them; so does "Mind olvasott".
|
||||
let (status, _) =
|
||||
app.call("POST", &format!("/v1/forum/threads/{thread}/read"), Some(&anna), json!({ "post_id": fourth })).await;
|
||||
assert_eq!(status, StatusCode::NO_CONTENT);
|
||||
assert_eq!(app.get("/v1/forum/nav", Some(&anna)).await["replies"], 0);
|
||||
let (status, _) = app.call("POST", "/v1/forum/replies/read", Some(&bea), Value::Null).await;
|
||||
assert_eq!(status, StatusCode::NO_CONTENT);
|
||||
assert_eq!(app.get("/v1/forum/nav", Some(&bea)).await["replies"], 0);
|
||||
assert_eq!(answers(app.get("/v1/forum/replies", Some(&bea)).await).len(), 2, "the list stays");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user