Forum: typing notices, smileys to emoji while typing, no emoji tray

"Holdfény gépel…" shows in threads and private conversations: the page
says over the live connection (every few seconds while typing) that its
member types, and the forum service passes it to those who may see that
place, never back to the typer. The emoji tray is gone (phones have their
emoji keyboard); character smileys turn into emoji as they are typed,
from a longer list shared with the server (which also converts titles
now; <3 is a red heart). Emoji show in colour: the forum's font stack
names the systems' colour emoji fonts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
feco
2026-11-26 11:50:09 +00:00
co-authored by Claude Opus 5.5
parent 2cf7266fc1
commit ee16974c77
15 changed files with 402 additions and 159 deletions
+114 -9
View File
@@ -1,7 +1,9 @@
//! Live notices over WebSocket: a doorbell, never the data. The server only
//! says "something changed" (`{"t":"nav"}`: the menu's counts; `{"t":"thread",
//! "id":…}`: a thread; `{"t":"conversation","id":…}`), and the page fetches the
//! news over HTTP as before. A dropped connection loses nothing: the page asks
//! news over HTTP as before. The one thing a page says is that its member is
//! typing (`{"typing":"thread"|"conversation","id":…}`, every few seconds while
//! they type); the others there get `{"t":"typing","kind":…,"id":…,"who":…}`. A dropped connection loses nothing: the page asks
//! again when it reconnects, and polls while it cannot.
//!
//! Events go through Postgres (`NOTIFY forum_events`), so every instance of the
@@ -50,6 +52,21 @@ pub struct Event {
/// The moderators' menu (the open reports).
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub moderators: bool,
/// Someone is typing in a thread (everyone there sees it) or a
/// conversation (the other member, in `users`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub typing: Option<Typing>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Typing {
/// `thread` or `conversation`.
pub kind: String,
pub id: i64,
/// The nickname shown ("Holdfény gépel…").
pub who: String,
/// Who types (they do not hear of themselves).
pub from: Uuid,
}
impl Event {
@@ -64,6 +81,14 @@ impl Event {
/// The messages one connection gets from this event.
pub fn messages_for(&self, user: Uuid, moderator: bool) -> Vec<String> {
if let Some(t) = &self.typing {
let hears = t.from != user && (t.kind == "thread" || self.users.contains(&user));
return if hears {
vec![json!({ "t": "typing", "kind": t.kind, "id": t.id, "who": t.who }).to_string()]
} else {
Vec::new()
};
}
let mine = self.everyone || self.users.contains(&user);
let mut out = Vec::new();
if let Some(id) = self.thread {
@@ -158,19 +183,71 @@ pub async fn connect(
return StatusCode::FORBIDDEN.into_response();
}
let Some(member) = viewer.member.clone() else { return StatusCode::UNAUTHORIZED.into_response() };
let moderator = viewer.is_moderator();
let me = Me { user: member.user_id, nickname: member.nickname, moderator: viewer.is_moderator() };
let rx = state.hub.subscribe();
let db = state.db.clone();
ws.on_upgrade(move |socket| serve(socket, rx, db, member.user_id, moderator))
ws.on_upgrade(move |socket| serve(socket, rx, db, me))
}
async fn serve(
mut socket: WebSocket,
mut rx: broadcast::Receiver<Arc<Event>>,
db: PgPool,
/// Who is on the other end of a connection.
struct Me {
user: Uuid,
nickname: String,
moderator: bool,
) {
}
#[derive(Deserialize)]
struct Incoming {
typing: String,
id: i64,
}
/// At most one typing notice per target in this time.
const TYPING_EVERY: Duration = Duration::from_secs(2);
/// "I am typing", from the page: passed on to those who may see that place.
async fn typing(db: &PgPool, me: &Me, text: &str) -> Option<Event> {
let incoming: Incoming = serde_json::from_str(text).ok()?;
let users = match incoming.typing.as_str() {
"conversation" => {
let other: Option<Uuid> = sqlx::query_scalar(
"SELECT CASE WHEN user_a = $2 THEN user_b ELSE user_a END FROM forum.conversations \
WHERE id = $1 AND status = 'accepted' AND $2 IN (user_a, user_b)",
)
.bind(incoming.id)
.bind(me.user)
.fetch_optional(db)
.await
.ok()?;
vec![other?]
}
"thread" => {
let visibility: Option<String> = sqlx::query_scalar(
"SELECT tp.visibility FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \
WHERE th.id = $1 AND th.deleted_at IS NULL AND (NOT th.locked OR $2)",
)
.bind(incoming.id)
.bind(me.moderator)
.fetch_optional(db)
.await
.ok()?;
if visibility? == "restricted" && !me.moderator {
return None;
}
Vec::new()
}
_ => return None,
};
Some(Event {
users,
typing: Some(Typing { kind: incoming.typing, id: incoming.id, who: me.nickname.clone(), from: me.user }),
..Default::default()
})
}
async fn serve(mut socket: WebSocket, mut rx: broadcast::Receiver<Arc<Event>>, db: PgPool, me: Me) {
let (user, moderator) = (me.user, me.moderator);
let mut last_typing: Option<(String, std::time::Instant)> = None;
let mut ping = tokio::time::interval(PING);
ping.tick().await;
loop {
@@ -202,7 +279,19 @@ async fn serve(
.await;
}
incoming = socket.recv() => match incoming {
// The page has nothing to say; pongs and the like are fine.
Some(Ok(Message::Text(text))) => {
// Typing notices, a few seconds apart per place.
let fresh = last_typing
.as_ref()
.is_none_or(|(place, at)| *place != text.as_str() || at.elapsed() >= TYPING_EVERY);
if fresh {
last_typing = Some((text.to_string(), std::time::Instant::now()));
if let Some(event) = typing(&db, &me, &text).await {
emit(&db, event).await;
}
}
}
// Pongs and the like are fine.
Some(Ok(Message::Close(_))) | None | Some(Err(_)) => break,
Some(Ok(_)) => {}
},
@@ -240,5 +329,21 @@ mod tests {
assert!(many.everyone && many.users.is_empty());
let round: Event = serde_json::from_str(&serde_json::to_string(&post).unwrap()).unwrap();
assert_eq!(round, post);
// Typing: never to oneself; a conversation only to the other member.
let typing = |kind: &str, users: Vec<Uuid>| Event {
users,
typing: Some(Typing { kind: kind.into(), id: 9, who: "Holdfény".into(), from: bea }),
..Default::default()
};
let in_thread = typing("thread", vec![]);
assert_eq!(
in_thread.messages_for(anna, false),
vec![r#"{"id":9,"kind":"thread","t":"typing","who":"Holdfény"}"#]
);
assert!(in_thread.messages_for(bea, false).is_empty());
let in_chat = typing("conversation", vec![anna]);
assert_eq!(in_chat.messages_for(anna, false).len(), 1);
assert!(in_chat.messages_for(Uuid::now_v7(), true).is_empty());
}
}