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());
}
}
+14 -2
View File
@@ -529,7 +529,7 @@ async fn profiles_share_signs_never_degrees(pool: PgPool) {
profile["member"]["author"]["signs"],
json!({"sun": "pisces", "moon": "cancer", "venus": "aries", "ascendant": "virgo"})
);
assert_eq!(profile["member"]["bio"], "Szia 🤍");
assert_eq!(profile["member"]["bio"], "Szia ❤️");
assert!(!profile.to_string().contains("longitude") && !profile.to_string().contains("345"));
let (status, _) = app
.call("PUT", "/v1/forum/me", Some(&anna), json!({ "nickname": "Csendesvíz", "bio": "www.gyogyitas.hu" }))
@@ -667,7 +667,7 @@ async fn private_messages_start_with_a_request(pool: PgPool) {
.call("POST", &format!("/v1/forum/conversations/{id}/messages"), Some(&anna), json!({"body": "Hahó <3"}))
.await;
assert_eq!(status, StatusCode::CREATED);
assert_eq!(msg["body"], "Hahó 🤍");
assert_eq!(msg["body"], "Hahó ❤️");
assert_eq!(app.get("/v1/forum/nav", Some(&bea)).await["messages"], 1);
let shown = app.get(&format!("/v1/forum/conversations/{id}"), Some(&bea)).await;
assert_eq!(shown["conversation"]["state"], "accepted");
@@ -896,6 +896,18 @@ async fn live_doorbell_over_websocket(pool: PgPool) {
}
}
assert_eq!(heard, vec![format!(r#"{{"id":{thread},"t":"thread"}}"#), r#"{"t":"nav"}"#.to_string()]);
// Anna types in the thread: Bea, there too, sees it; Anna does not hear of herself.
use futures_util::SinkExt;
let (mut bea_ws, _) =
tokio_tungstenite::connect_async(request(&bea.token, Some("https://sorsfonalak.test"))).await.unwrap();
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
let typing = format!(r#"{{"typing":"thread","id":{thread}}}"#);
ws.send(tokio_tungstenite::tungstenite::Message::Text(typing.into())).await.unwrap();
let seen = tokio::time::timeout(std::time::Duration::from_secs(5), futures_next(&mut bea_ws)).await.unwrap();
assert_eq!(seen, Some(format!(r#"{{"id":{thread},"kind":"thread","t":"typing","who":"Csendesvíz"}}"#)));
let echo = tokio::time::timeout(std::time::Duration::from_millis(500), futures_next(&mut ws)).await;
assert!(echo.is_err(), "no echo of one's own typing");
}
/// The next text message of a test WebSocket.
+38 -13
View File
@@ -90,7 +90,7 @@ pub fn title(raw: &str) -> Result<String, ApiError> {
if len > TITLE_MAX {
return Err(ApiError::bad(format!("A cím legfeljebb {TITLE_MAX} karakter lehet.")));
}
Ok(title)
Ok(smileys(&title))
}
/// A post: control characters removed, at most one empty line in a row,
@@ -180,21 +180,45 @@ fn clean_multiline(raw: &str, max_breaks: usize) -> String {
out.trim().to_string()
}
/// `:)`, `:D`, `;)`, `:(`, `:P` and `<3` standing alone become emoji, as on the
/// old forums.
/// The old forums' character smileys and their emoji. A smiley becomes the
/// emoji only standing alone (between spaces), so links and the like stay as
/// typed. The frontend converts the same list while typing
/// (`src/lib/emoticons.ts`); this catches what it did not.
pub const EMOTICONS: [(&str, &str); 27] = [
(":)", "🙂"),
(":-)", "🙂"),
("(:", "🙂"),
(":D", "😄"),
(":-D", "😄"),
("xD", "😆"),
("XD", "😆"),
(";)", "😉"),
(";-)", "😉"),
(":(", "🙁"),
(":-(", "🙁"),
(":'(", "😢"),
(":P", "😛"),
(":-P", "😛"),
(":p", "😛"),
(":O", "😮"),
(":o", "😮"),
(":-O", "😮"),
(":*", "😘"),
(":-*", "😘"),
(":/", "😕"),
(":|", "😐"),
("B)", "😎"),
("^^", "😊"),
("^_^", "😊"),
("<3", "❤️"),
("</3", "💔"),
];
fn smileys(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut word = String::new();
let flush = |word: &mut String, out: &mut String| {
let emoji = match word.as_str() {
":)" | ":-)" => Some("🙂"),
":D" | ":-D" => Some("😄"),
";)" | ";-)" => Some("😉"),
":(" | ":-(" => Some("🙁"),
":P" | ":-P" | ":p" => Some("😛"),
"<3" => Some("🤍"),
_ => None,
};
let emoji = EMOTICONS.iter().find(|(code, _)| code == word).map(|(_, e)| *e);
out.push_str(emoji.unwrap_or(word));
word.clear();
};
@@ -233,7 +257,8 @@ mod tests {
#[test]
fn bodies() {
assert_eq!(body(" Szia :)\r\n\r\n\r\n\r\nMi újság? <3 ").unwrap(), "Szia 🙂\n\nMi újság? 🤍");
assert_eq!(body(" Szia :)\r\n\r\n\r\n\r\nMi újság? <3 ").unwrap(), "Szia 🙂\n\nMi újság? ❤️");
assert_eq!(body("Hiányzol :'( xD ^^").unwrap(), "Hiányzol 😢 😆 😊");
assert_eq!(body("http://x.hu/:)").unwrap(), "http://x.hu/:)", "only smileys standing alone");
assert!(body(" \n\t ").is_err());
assert_eq!(body("a\u{0007}b").unwrap(), "ab");