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:
+14
-1
@@ -136,6 +136,19 @@ Jelölés: ami mellett **(javaslat)** áll, azt még nem hagytuk jóvá, a több
|
|||||||
- Élesben a Caddy küldi a `/api/v1/forum/ws`-t közvetlenül a fórumszolgáltatásnak (`deploy/Caddyfile`).
|
- Élesben a Caddy küldi a `/api/v1/forum/ws`-t közvetlenül a fórumszolgáltatásnak (`deploy/Caddyfile`).
|
||||||
- Fejlesztéskor a frontend `FORUM_WS_URL` változója mutat rá (`ws://localhost:8083/v1/forum/ws`). SSH-alagúton át a 8083-as portot is át kell vinni, különben marad a 30 másodperces lekérdezés.
|
- Fejlesztéskor a frontend `FORUM_WS_URL` változója mutat rá (`ws://localhost:8083/v1/forum/ws`). SSH-alagúton át a 8083-as portot is át kell vinni, különben marad a 30 másodperces lekérdezés.
|
||||||
|
|
||||||
|
### Apró módosítások (5. kör)
|
||||||
|
|
||||||
|
- **Gépelésjelzés:**
|
||||||
|
- A szálban és a privát beszélgetésben látszik, ha valaki épp ír: „Holdfény gépel…”, három halványan mozgó pöttyel.
|
||||||
|
- Az oldal gépelés közben 3 másodpercenként szól a WebSocketen (`{"typing":"thread"|"conversation","id":…}`).
|
||||||
|
- A szerver ellenőrzi, hogy a tag láthatja-e az adott helyet (szál vagy elfogadott beszélgetés), és csak a többieknek adja tovább. A jelzés 6 másodperc után eltűnik, és akkor is, amikor megjön a hozzászólás.
|
||||||
|
- WebSocket nélkül nincs gépelésjelzés.
|
||||||
|
- **Az emojiválasztó kikerült** a szövegdoboz alól. Mobilon úgyis ott az emojibillentyűzet.
|
||||||
|
- **Karakterkódok:** gépelés közben emojivá alakulnak, amint szóköz vagy új sor jön utánuk; elküldéskor a sor végén lévők is. A szerver ugyanazt a listát alkalmazza mentéskor, a címekre is.
|
||||||
|
- A lista: `:)` `:-)` `(:` → 🙂, `:D` → 😄, `xD` → 😆, `;)` → 😉, `:(` → 🙁, `:'(` → 😢, `:P` → 😛, `:O` → 😮, `:*` → 😘, `:/` → 😕, `:|` → 😐, `B)` → 😎, `^^` → 😊, `<3` → ❤️, `</3` → 💔.
|
||||||
|
- Csak az önálló kód alakul át, így a linkek változatlanok maradnak.
|
||||||
|
- **Színes emojik:** a fórum betűtípus-sorában ott vannak a rendszer színes emojibetűi (Apple, Segoe, Noto Color Emoji).
|
||||||
|
|
||||||
### Élesítéskor
|
### Élesítéskor
|
||||||
|
|
||||||
- `FORUM_URL=http://forum:8083` az éles `.env`-be.
|
- `FORUM_URL=http://forum:8083` az éles `.env`-be.
|
||||||
@@ -250,7 +263,7 @@ A **rang automatikus, a szerepkör kiosztott:** admin, moderátor, témamoderát
|
|||||||
## Média
|
## Média
|
||||||
|
|
||||||
- **GIF nincs.**
|
- **GIF nincs.**
|
||||||
- **Emoji van,** a hozzászólásokban is. Emojiválasztó, kiemelve a csillagjegyekkel (♈–♓) és a holdfázisokkal (🌑–🌕), és a régi fórumos `:)` → 🙂 és `<3` → 🤍 átalakítás. (a részletek javaslatok)
|
- **Emoji van,** a hozzászólásokban is: a telefon emojibillentyűzete, és a régi fórumos karakterkódok (`:)`, `<3` stb.) gépelés közben emojivá alakulnak. Külön emojiválasztó nincs.
|
||||||
- **Videó** nem játszódik le helyben, a link sima szöveges linkként jelenik meg, előnézet nélkül. (javaslat)
|
- **Videó** nem játszódik le helyben, a link sima szöveges linkként jelenik meg, előnézet nélkül. (javaslat)
|
||||||
- **Kép:** az elején nincs, később hozzászólásonként legfeljebb egy, rang fölött, kis méretben. (javaslat)
|
- **Kép:** az elején nincs, később hozzászólásonként legfeljebb egy, rang fölött, kis méretben. (javaslat)
|
||||||
- Az aláírás csak szöveg lehet. (javaslat)
|
- Az aláírás csak szöveg lehet. (javaslat)
|
||||||
|
|||||||
+114
-9
@@ -1,7 +1,9 @@
|
|||||||
//! Live notices over WebSocket: a doorbell, never the data. The server only
|
//! Live notices over WebSocket: a doorbell, never the data. The server only
|
||||||
//! says "something changed" (`{"t":"nav"}`: the menu's counts; `{"t":"thread",
|
//! says "something changed" (`{"t":"nav"}`: the menu's counts; `{"t":"thread",
|
||||||
//! "id":…}`: a thread; `{"t":"conversation","id":…}`), and the page fetches the
|
//! "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.
|
//! again when it reconnects, and polls while it cannot.
|
||||||
//!
|
//!
|
||||||
//! Events go through Postgres (`NOTIFY forum_events`), so every instance of the
|
//! 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).
|
/// The moderators' menu (the open reports).
|
||||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||||
pub moderators: bool,
|
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 {
|
impl Event {
|
||||||
@@ -64,6 +81,14 @@ impl Event {
|
|||||||
|
|
||||||
/// The messages one connection gets from this event.
|
/// The messages one connection gets from this event.
|
||||||
pub fn messages_for(&self, user: Uuid, moderator: bool) -> Vec<String> {
|
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 mine = self.everyone || self.users.contains(&user);
|
||||||
let mut out = Vec::new();
|
let mut out = Vec::new();
|
||||||
if let Some(id) = self.thread {
|
if let Some(id) = self.thread {
|
||||||
@@ -158,19 +183,71 @@ pub async fn connect(
|
|||||||
return StatusCode::FORBIDDEN.into_response();
|
return StatusCode::FORBIDDEN.into_response();
|
||||||
}
|
}
|
||||||
let Some(member) = viewer.member.clone() else { return StatusCode::UNAUTHORIZED.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 rx = state.hub.subscribe();
|
||||||
let db = state.db.clone();
|
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(
|
/// Who is on the other end of a connection.
|
||||||
mut socket: WebSocket,
|
struct Me {
|
||||||
mut rx: broadcast::Receiver<Arc<Event>>,
|
|
||||||
db: PgPool,
|
|
||||||
user: Uuid,
|
user: Uuid,
|
||||||
|
nickname: String,
|
||||||
moderator: bool,
|
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);
|
let mut ping = tokio::time::interval(PING);
|
||||||
ping.tick().await;
|
ping.tick().await;
|
||||||
loop {
|
loop {
|
||||||
@@ -202,7 +279,19 @@ async fn serve(
|
|||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
incoming = socket.recv() => match incoming {
|
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(Message::Close(_))) | None | Some(Err(_)) => break,
|
||||||
Some(Ok(_)) => {}
|
Some(Ok(_)) => {}
|
||||||
},
|
},
|
||||||
@@ -240,5 +329,21 @@ mod tests {
|
|||||||
assert!(many.everyone && many.users.is_empty());
|
assert!(many.everyone && many.users.is_empty());
|
||||||
let round: Event = serde_json::from_str(&serde_json::to_string(&post).unwrap()).unwrap();
|
let round: Event = serde_json::from_str(&serde_json::to_string(&post).unwrap()).unwrap();
|
||||||
assert_eq!(round, post);
|
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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -529,7 +529,7 @@ async fn profiles_share_signs_never_degrees(pool: PgPool) {
|
|||||||
profile["member"]["author"]["signs"],
|
profile["member"]["author"]["signs"],
|
||||||
json!({"sun": "pisces", "moon": "cancer", "venus": "aries", "ascendant": "virgo"})
|
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"));
|
assert!(!profile.to_string().contains("longitude") && !profile.to_string().contains("345"));
|
||||||
let (status, _) = app
|
let (status, _) = app
|
||||||
.call("PUT", "/v1/forum/me", Some(&anna), json!({ "nickname": "Csendesvíz", "bio": "www.gyogyitas.hu" }))
|
.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"}))
|
.call("POST", &format!("/v1/forum/conversations/{id}/messages"), Some(&anna), json!({"body": "Hahó <3"}))
|
||||||
.await;
|
.await;
|
||||||
assert_eq!(status, StatusCode::CREATED);
|
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);
|
assert_eq!(app.get("/v1/forum/nav", Some(&bea)).await["messages"], 1);
|
||||||
let shown = app.get(&format!("/v1/forum/conversations/{id}"), Some(&bea)).await;
|
let shown = app.get(&format!("/v1/forum/conversations/{id}"), Some(&bea)).await;
|
||||||
assert_eq!(shown["conversation"]["state"], "accepted");
|
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()]);
|
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.
|
/// The next text message of a test WebSocket.
|
||||||
|
|||||||
+38
-13
@@ -90,7 +90,7 @@ pub fn title(raw: &str) -> Result<String, ApiError> {
|
|||||||
if len > TITLE_MAX {
|
if len > TITLE_MAX {
|
||||||
return Err(ApiError::bad(format!("A cím legfeljebb {TITLE_MAX} karakter lehet.")));
|
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,
|
/// 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()
|
out.trim().to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `:)`, `:D`, `;)`, `:(`, `:P` and `<3` standing alone become emoji, as on the
|
/// The old forums' character smileys and their emoji. A smiley becomes the
|
||||||
/// old forums.
|
/// 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 {
|
fn smileys(text: &str) -> String {
|
||||||
let mut out = String::with_capacity(text.len());
|
let mut out = String::with_capacity(text.len());
|
||||||
let mut word = String::new();
|
let mut word = String::new();
|
||||||
let flush = |word: &mut String, out: &mut String| {
|
let flush = |word: &mut String, out: &mut String| {
|
||||||
let emoji = match word.as_str() {
|
let emoji = EMOTICONS.iter().find(|(code, _)| code == word).map(|(_, e)| *e);
|
||||||
":)" | ":-)" => Some("🙂"),
|
|
||||||
":D" | ":-D" => Some("😄"),
|
|
||||||
";)" | ";-)" => Some("😉"),
|
|
||||||
":(" | ":-(" => Some("🙁"),
|
|
||||||
":P" | ":-P" | ":p" => Some("😛"),
|
|
||||||
"<3" => Some("🤍"),
|
|
||||||
_ => None,
|
|
||||||
};
|
|
||||||
out.push_str(emoji.unwrap_or(word));
|
out.push_str(emoji.unwrap_or(word));
|
||||||
word.clear();
|
word.clear();
|
||||||
};
|
};
|
||||||
@@ -233,7 +257,8 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn bodies() {
|
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_eq!(body("http://x.hu/:)").unwrap(), "http://x.hu/:)", "only smileys standing alone");
|
||||||
assert!(body(" \n\t ").is_err());
|
assert!(body(" \n\t ").is_err());
|
||||||
assert_eq!(body("a\u{0007}b").unwrap(), "ab");
|
assert_eq!(body("a\u{0007}b").unwrap(), "ab");
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { useEffect, useState } from "react";
|
|||||||
import { AVATAR_COLOURS, AVATAR_GLYPHS, Avatar, GLYPH_NAMES } from "@/components/forum/Avatar";
|
import { AVATAR_COLOURS, AVATAR_GLYPHS, Avatar, GLYPH_NAMES } from "@/components/forum/Avatar";
|
||||||
import { signsText } from "@/components/forum/AuthorLine";
|
import { signsText } from "@/components/forum/AuthorLine";
|
||||||
import { api, errorText } from "@/lib/api";
|
import { api, errorText } from "@/lib/api";
|
||||||
|
import { withEmoji } from "@/lib/emoticons";
|
||||||
import { type ChartShare, type EmailSettings, type ForumMe, banText, memberHref } from "@/lib/forum";
|
import { type ChartShare, type EmailSettings, type ForumMe, banText, memberHref } from "@/lib/forum";
|
||||||
|
|
||||||
const SHARE_LEVELS: { value: ChartShare; label: string }[] = [
|
const SHARE_LEVELS: { value: ChartShare; label: string }[] = [
|
||||||
@@ -144,7 +145,7 @@ export function ProfileForm({ me, back }: { me: ForumMe; back: string | null })
|
|||||||
rows={4}
|
rows={4}
|
||||||
maxLength={500}
|
maxLength={500}
|
||||||
value={bio}
|
value={bio}
|
||||||
onChange={(e) => setBio(e.target.value)}
|
onChange={(e) => withEmoji(e, setBio)}
|
||||||
placeholder="Pár mondat magadról, ha szeretnéd."
|
placeholder="Pár mondat magadról, ha szeretnéd."
|
||||||
/>
|
/>
|
||||||
<span className="hint">{bio.length}/500 · link nem tehető bele</span>
|
<span className="hint">{bio.length}/500 · link nem tehető bele</span>
|
||||||
|
|||||||
@@ -6,6 +6,9 @@
|
|||||||
|
|
||||||
/* --- themes --- */
|
/* --- themes --- */
|
||||||
.forum {
|
.forum {
|
||||||
|
/* Colour emoji wherever the system has them (no monochrome symbol fonts). */
|
||||||
|
--font-body: var(--font-inter), Inter, system-ui, "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", sans-serif;
|
||||||
|
font-family: var(--font-body);
|
||||||
--f-hover: rgba(255, 255, 255, 0.04);
|
--f-hover: rgba(255, 255, 255, 0.04);
|
||||||
--f-tint: rgba(217, 180, 106, 0.1);
|
--f-tint: rgba(217, 180, 106, 0.1);
|
||||||
--f-tint-strong: rgba(217, 180, 106, 0.14);
|
--f-tint-strong: rgba(217, 180, 106, 0.14);
|
||||||
@@ -395,16 +398,6 @@ body:has(.forum[data-theme="light"]) .site-footer { background: #0d1220; }
|
|||||||
}
|
}
|
||||||
.fc-icon-btn:hover, .fc-icon-btn[aria-expanded="true"] { color: var(--gold); background: var(--f-tint); }
|
.fc-icon-btn:hover, .fc-icon-btn[aria-expanded="true"] { color: var(--gold); background: var(--f-tint); }
|
||||||
.fc-icon-btn svg { width: 24px; height: 24px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; }
|
.fc-icon-btn svg { width: 24px; height: 24px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; }
|
||||||
.fc-tray {
|
|
||||||
display: grid; grid-template-columns: repeat(auto-fill, minmax(42px, 1fr)); gap: 2px; padding: 8px;
|
|
||||||
border: 1px solid var(--line-2); border-radius: 12px; background: var(--panel-2);
|
|
||||||
}
|
|
||||||
.fc-emoji {
|
|
||||||
width: 100%; height: 42px; border: 0; border-radius: 8px; background: none; color: var(--ink);
|
|
||||||
font-size: 22px; cursor: pointer; font-family: var(--font-symbols), sans-serif;
|
|
||||||
}
|
|
||||||
.fc-emoji:hover { background: var(--f-hover); }
|
|
||||||
|
|
||||||
/* --- new thread and profile forms --- */
|
/* --- new thread and profile forms --- */
|
||||||
.fnew, .fprof { display: flex; flex-direction: column; gap: 22px; width: 100%; max-width: 760px; }
|
.fnew, .fprof { display: flex; flex-direction: column; gap: 22px; width: 100%; max-width: 760px; }
|
||||||
.fnew-set { border: 0; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 10px; min-width: 0; }
|
.fnew-set { border: 0; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 10px; min-width: 0; }
|
||||||
@@ -503,3 +496,12 @@ body:has(.forum[data-theme="light"]) .site-footer { background: #0d1220; }
|
|||||||
.fprof-mail { display: grid; gap: 6px; }
|
.fprof-mail { display: grid; gap: 6px; }
|
||||||
.fprof-mail label { font-size: 14px; font-weight: 500; margin-top: 8px; }
|
.fprof-mail label { font-size: 14px; font-weight: 500; margin-top: 8px; }
|
||||||
.fprof-mail label:first-child { margin-top: 0; }
|
.fprof-mail label:first-child { margin-top: 0; }
|
||||||
|
|
||||||
|
/* --- "… gépel" --- */
|
||||||
|
.ftyping { min-height: 22px; display: flex; align-items: center; gap: 8px; font-size: 14px; color: var(--muted); margin: 0; }
|
||||||
|
.ftyping-dots { display: inline-flex; gap: 3px; }
|
||||||
|
.ftyping-dots span { width: 5px; height: 5px; border-radius: 50%; background: var(--muted); animation: ftyping 1.2s infinite ease-in-out; }
|
||||||
|
.ftyping-dots span:nth-child(2) { animation-delay: 0.15s; }
|
||||||
|
.ftyping-dots span:nth-child(3) { animation-delay: 0.3s; }
|
||||||
|
@keyframes ftyping { 0%, 60%, 100% { opacity: 0.25; transform: translateY(0); } 30% { opacity: 1; transform: translateY(-3px); } }
|
||||||
|
@media (prefers-reduced-motion: reduce) { .ftyping-dots span { animation: none; opacity: 0.6; } }
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { useRouter } from "next/navigation";
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
|
|
||||||
import { api, errorText } from "@/lib/api";
|
import { api, errorText } from "@/lib/api";
|
||||||
|
import { withEmoji } from "@/lib/emoticons";
|
||||||
import type { MemberRelation } from "@/lib/forum";
|
import type { MemberRelation } from "@/lib/forum";
|
||||||
|
|
||||||
const INTRO_MAX = 200;
|
const INTRO_MAX = 200;
|
||||||
@@ -74,7 +75,7 @@ export function RequestPanel({ nickname, relation }: { nickname: string; relatio
|
|||||||
rows={3}
|
rows={3}
|
||||||
maxLength={INTRO_MAX}
|
maxLength={INTRO_MAX}
|
||||||
value={intro}
|
value={intro}
|
||||||
onChange={(e) => setIntro(e.target.value)}
|
onChange={(e) => withEmoji(e, setIntro)}
|
||||||
placeholder="Szia! Olvastam a hozzászólásodat a…"
|
placeholder="Szia! Olvastam a hozzászólásodat a…"
|
||||||
/>
|
/>
|
||||||
<span className="hint">
|
<span className="hint">
|
||||||
|
|||||||
@@ -5,7 +5,8 @@ import { useRouter } from "next/navigation";
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
|
|
||||||
import { api, errorText } from "@/lib/api";
|
import { api, errorText } from "@/lib/api";
|
||||||
import { EMOJI, type ForumTopic, threadHref } from "@/lib/forum";
|
import { convertEmoticons, withEmoji } from "@/lib/emoticons";
|
||||||
|
import { type ForumTopic, threadHref } from "@/lib/forum";
|
||||||
|
|
||||||
type Intent = "listen" | "advice" | "";
|
type Intent = "listen" | "advice" | "";
|
||||||
|
|
||||||
@@ -16,7 +17,6 @@ export function NewThreadForm({ topics, initialTopic }: { topics: ForumTopic[];
|
|||||||
const [intent, setIntent] = useState<Intent>(listening ? "listen" : "");
|
const [intent, setIntent] = useState<Intent>(listening ? "listen" : "");
|
||||||
const [title, setTitle] = useState("");
|
const [title, setTitle] = useState("");
|
||||||
const [body, setBody] = useState("");
|
const [body, setBody] = useState("");
|
||||||
const [tray, setTray] = useState(false);
|
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
@@ -32,7 +32,12 @@ export function NewThreadForm({ topics, initialTopic }: { topics: ForumTopic[];
|
|||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const created = await api<{ id: number; slug: string }>("/forum/threads", {
|
const created = await api<{ id: number; slug: string }>("/forum/threads", {
|
||||||
body: { topic, title, body, intent: intent || null },
|
body: {
|
||||||
|
topic,
|
||||||
|
title: convertEmoticons(title, title.length, true).text,
|
||||||
|
body: convertEmoticons(body, body.length, true).text,
|
||||||
|
intent: intent || null,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
router.push(threadHref(created));
|
router.push(threadHref(created));
|
||||||
router.refresh();
|
router.refresh();
|
||||||
@@ -100,7 +105,7 @@ export function NewThreadForm({ topics, initialTopic }: { topics: ForumTopic[];
|
|||||||
id="fnew-title"
|
id="fnew-title"
|
||||||
className="inp"
|
className="inp"
|
||||||
value={title}
|
value={title}
|
||||||
onChange={(e) => setTitle(e.target.value)}
|
onChange={(e) => withEmoji(e, setTitle)}
|
||||||
maxLength={120}
|
maxLength={120}
|
||||||
required
|
required
|
||||||
placeholder="Miről szeretnél beszélgetni?"
|
placeholder="Miről szeretnél beszélgetni?"
|
||||||
@@ -114,45 +119,16 @@ export function NewThreadForm({ topics, initialTopic }: { topics: ForumTopic[];
|
|||||||
className="fc-text"
|
className="fc-text"
|
||||||
rows={8}
|
rows={8}
|
||||||
value={body}
|
value={body}
|
||||||
onChange={(e) => setBody(e.target.value)}
|
onChange={(e) => withEmoji(e, setBody)}
|
||||||
maxLength={10000}
|
maxLength={10000}
|
||||||
required
|
required
|
||||||
placeholder={intent === "listen" ? "Írd le, ami benned van…" : "Írd le a gondolataidat…"}
|
placeholder={intent === "listen" ? "Írd le, ami benned van…" : "Írd le a gondolataidat…"}
|
||||||
/>
|
/>
|
||||||
<div className="fc-actions">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className="fc-icon-btn"
|
|
||||||
aria-label="Emoji"
|
|
||||||
aria-expanded={tray}
|
|
||||||
onClick={() => setTray((t) => !t)}
|
|
||||||
>
|
|
||||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
|
||||||
<circle cx="12" cy="12" r="9" />
|
|
||||||
<path d="M8.5 14.5a4 4 0 0 0 7 0" />
|
|
||||||
<path d="M9 9.5h.01M15 9.5h.01" strokeWidth="2.6" />
|
|
||||||
</svg>
|
|
||||||
</button>
|
|
||||||
<span className="hint">
|
<span className="hint">
|
||||||
Szöveg és emoji. Képet és videót nem lehet beilleszteni, a linkek sima szövegként látszanak.
|
Szöveg és emoji: a :) és a {"<3"} magától emojivá alakul. Képet és videót nem lehet beilleszteni, a linkek
|
||||||
|
sima szövegként látszanak.
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
{tray && (
|
|
||||||
<div className="fc-tray" role="group" aria-label="Emoji">
|
|
||||||
{EMOJI.map((em) => (
|
|
||||||
<button
|
|
||||||
key={em}
|
|
||||||
type="button"
|
|
||||||
className="fc-emoji"
|
|
||||||
onClick={() => setBody((b) => b + em)}
|
|
||||||
aria-label={`${em} beszúrása`}
|
|
||||||
>
|
|
||||||
{em}
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<p className="hint">
|
<p className="hint">
|
||||||
Írás előtt érdemes elolvasni a <Link href="/aszf#forum">fórum házirendjét</Link>: tisztelettel, kéretlen tanács
|
Írás előtt érdemes elolvasni a <Link href="/aszf#forum">fórum házirendjét</Link>: tisztelettel, kéretlen tanács
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { Composer } from "@/components/forum/Composer";
|
|||||||
import { PostBody } from "@/components/forum/PostBody";
|
import { PostBody } from "@/components/forum/PostBody";
|
||||||
import type { LiveNotice } from "@/components/forum/ForumNav";
|
import type { LiveNotice } from "@/components/forum/ForumNav";
|
||||||
import { ReportButton } from "@/components/forum/ReportButton";
|
import { ReportButton } from "@/components/forum/ReportButton";
|
||||||
|
import { TypingLine, useTypingSender, useTypingWatch } from "@/components/forum/typing";
|
||||||
import { api, errorText } from "@/lib/api";
|
import { api, errorText } from "@/lib/api";
|
||||||
import { type ChatMessage, type ConversationPage, memberHref } from "@/lib/forum";
|
import { type ChatMessage, type ConversationPage, memberHref } from "@/lib/forum";
|
||||||
|
|
||||||
@@ -36,6 +37,8 @@ export function Chat({ initial }: { initial: ConversationPage }) {
|
|||||||
const base = `/forum/conversations/${c.id}`;
|
const base = `/forum/conversations/${c.id}`;
|
||||||
const lastId = messages.length ? messages[messages.length - 1].id : 0;
|
const lastId = messages.length ? messages[messages.length - 1].id : 0;
|
||||||
const other = c.other?.nickname ?? "Törölt tag";
|
const other = c.other?.nickname ?? "Törölt tag";
|
||||||
|
const typingNow = useTypingWatch("conversation", initial.conversation.id);
|
||||||
|
const imTyping = useTypingSender("conversation", initial.conversation.id);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (lastId) api(`${base}/read`, { body: { message_id: lastId } }).catch(() => {});
|
if (lastId) api(`${base}/read`, { body: { message_id: lastId } }).catch(() => {});
|
||||||
@@ -190,6 +193,7 @@ export function Chat({ initial }: { initial: ConversationPage }) {
|
|||||||
))}
|
))}
|
||||||
</ol>
|
</ol>
|
||||||
)}
|
)}
|
||||||
|
{c.state === "accepted" && <TypingLine text={typingNow} />}
|
||||||
<div ref={bottom} />
|
<div ref={bottom} />
|
||||||
|
|
||||||
{error && (
|
{error && (
|
||||||
@@ -200,7 +204,15 @@ export function Chat({ initial }: { initial: ConversationPage }) {
|
|||||||
|
|
||||||
{c.state === "accepted" && (
|
{c.state === "accepted" && (
|
||||||
<div className="fchat-compose">
|
<div className="fchat-compose">
|
||||||
<Composer id="uzenet" label="Üzeneted" placeholder="Írj üzenetet…" rows={2} busy={busy} onSubmit={send} />
|
<Composer
|
||||||
|
onTyping={imTyping}
|
||||||
|
id="uzenet"
|
||||||
|
label="Üzeneted"
|
||||||
|
placeholder="Írj üzenetet…"
|
||||||
|
rows={2}
|
||||||
|
busy={busy}
|
||||||
|
onSubmit={send}
|
||||||
|
/>
|
||||||
<p className="hint">
|
<p className="hint">
|
||||||
Csak szöveg és emoji. A linkek nem kattinthatók. A moderátorok csak jelentett üzenetet látnak.
|
Csak szöveg és emoji. A linkek nem kattinthatók. A moderátorok csak jelentett üzenetet látnak.
|
||||||
</p>
|
</p>
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useRef, useState } from "react";
|
import { useState } from "react";
|
||||||
|
|
||||||
import { EMOJI } from "@/lib/forum";
|
import { convertEmoticons, withEmoji } from "@/lib/emoticons";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The text box with an emoji tray (phones have emoji on the keyboard; the
|
* The text box and the send button. Character smileys (`:)`, `<3`) turn into
|
||||||
* tray is mostly for computers) and the send button.
|
* emoji as they are typed; phones bring their own emoji keyboard.
|
||||||
|
* `onTyping`: called on every keystroke (the "… gépel" notice).
|
||||||
*/
|
*/
|
||||||
export function Composer({
|
export function Composer({
|
||||||
id,
|
id,
|
||||||
@@ -17,6 +18,7 @@ export function Composer({
|
|||||||
busy,
|
busy,
|
||||||
onSubmit,
|
onSubmit,
|
||||||
onCancel,
|
onCancel,
|
||||||
|
onTyping,
|
||||||
rows = 3,
|
rows = 3,
|
||||||
autoFocus = false,
|
autoFocus = false,
|
||||||
}: {
|
}: {
|
||||||
@@ -28,36 +30,17 @@ export function Composer({
|
|||||||
busy: boolean;
|
busy: boolean;
|
||||||
onSubmit: (text: string) => Promise<boolean>;
|
onSubmit: (text: string) => Promise<boolean>;
|
||||||
onCancel?: () => void;
|
onCancel?: () => void;
|
||||||
|
onTyping?: () => void;
|
||||||
rows?: number;
|
rows?: number;
|
||||||
autoFocus?: boolean;
|
autoFocus?: boolean;
|
||||||
}) {
|
}) {
|
||||||
const [text, setText] = useState(initial);
|
const [text, setText] = useState(initial);
|
||||||
const [tray, setTray] = useState(false);
|
|
||||||
const area = useRef<HTMLTextAreaElement>(null);
|
|
||||||
|
|
||||||
function insert(emoji: string) {
|
|
||||||
const el = area.current;
|
|
||||||
if (!el) {
|
|
||||||
setText((t) => t + emoji);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const start = el.selectionStart ?? text.length;
|
|
||||||
const end = el.selectionEnd ?? text.length;
|
|
||||||
const next = text.slice(0, start) + emoji + text.slice(end);
|
|
||||||
setText(next);
|
|
||||||
requestAnimationFrame(() => {
|
|
||||||
el.focus();
|
|
||||||
el.setSelectionRange(start + emoji.length, start + emoji.length);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async function submit(e: React.FormEvent) {
|
async function submit(e: React.FormEvent) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (!text.trim() || busy) return;
|
if (!text.trim() || busy) return;
|
||||||
if (await onSubmit(text)) {
|
const final = convertEmoticons(text, text.length, true).text;
|
||||||
setText("");
|
if (await onSubmit(final)) setText("");
|
||||||
setTray(false);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -67,38 +50,18 @@ export function Composer({
|
|||||||
</label>
|
</label>
|
||||||
<textarea
|
<textarea
|
||||||
id={id}
|
id={id}
|
||||||
ref={area}
|
|
||||||
className="fc-text"
|
className="fc-text"
|
||||||
rows={rows}
|
rows={rows}
|
||||||
placeholder={placeholder}
|
placeholder={placeholder}
|
||||||
value={text}
|
value={text}
|
||||||
onChange={(e) => setText(e.target.value)}
|
onChange={(e) => {
|
||||||
|
withEmoji(e, setText);
|
||||||
|
onTyping?.();
|
||||||
|
}}
|
||||||
maxLength={10000}
|
maxLength={10000}
|
||||||
autoFocus={autoFocus}
|
autoFocus={autoFocus}
|
||||||
/>
|
/>
|
||||||
{tray && (
|
|
||||||
<div className="fc-tray" role="group" aria-label="Emoji">
|
|
||||||
{EMOJI.map((e) => (
|
|
||||||
<button key={e} type="button" className="fc-emoji" onClick={() => insert(e)} aria-label={`${e} beszúrása`}>
|
|
||||||
{e}
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div className="fc-actions">
|
<div className="fc-actions">
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className="fc-icon-btn"
|
|
||||||
aria-label="Emoji"
|
|
||||||
aria-expanded={tray}
|
|
||||||
onClick={() => setTray((t) => !t)}
|
|
||||||
>
|
|
||||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
|
||||||
<circle cx="12" cy="12" r="9" />
|
|
||||||
<path d="M8.5 14.5a4 4 0 0 0 7 0" />
|
|
||||||
<path d="M9 9.5h.01M15 9.5h.01" strokeWidth="2.6" />
|
|
||||||
</svg>
|
|
||||||
</button>
|
|
||||||
<span className="fc-spacer" />
|
<span className="fc-spacer" />
|
||||||
{onCancel && (
|
{onCancel && (
|
||||||
<button type="button" className="btn btn-ghost btn-sm" onClick={onCancel}>
|
<button type="button" className="btn btn-ghost btn-sm" onClick={onCancel}>
|
||||||
|
|||||||
@@ -16,8 +16,11 @@ export interface NavCounts {
|
|||||||
|
|
||||||
/** The live notice a page listens to (`window` event `forum:live`). */
|
/** The live notice a page listens to (`window` event `forum:live`). */
|
||||||
export interface LiveNotice {
|
export interface LiveNotice {
|
||||||
t: "thread" | "conversation" | "nav";
|
t: "thread" | "conversation" | "nav" | "typing";
|
||||||
id?: number;
|
id?: number;
|
||||||
|
/** For `typing`: where (`thread` or `conversation`) and who. */
|
||||||
|
kind?: string;
|
||||||
|
who?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** How often the counts are asked for while there is no live connection (also the online dot). */
|
/** How often the counts are asked for while there is no live connection (also the online dot). */
|
||||||
@@ -68,6 +71,14 @@ function useLive(member: boolean, wsUrl: string, refresh: () => void) {
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
connect();
|
connect();
|
||||||
|
// The page says its member is typing somewhere: passed on while connected.
|
||||||
|
const typing = (e: Event) => {
|
||||||
|
const out = (e as CustomEvent<{ kind: string; id: number }>).detail;
|
||||||
|
if (open.current && socket?.readyState === WebSocket.OPEN) {
|
||||||
|
socket.send(JSON.stringify({ typing: out.kind, id: out.id }));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
window.addEventListener("forum:typing-out", typing);
|
||||||
// Polling while there is no connection; and when the page comes back to the front.
|
// Polling while there is no connection; and when the page comes back to the front.
|
||||||
const poll = window.setInterval(() => {
|
const poll = window.setInterval(() => {
|
||||||
if (!open.current && document.visibilityState === "visible") refresh();
|
if (!open.current && document.visibilityState === "visible") refresh();
|
||||||
@@ -81,6 +92,7 @@ function useLive(member: boolean, wsUrl: string, refresh: () => void) {
|
|||||||
window.clearTimeout(timer);
|
window.clearTimeout(timer);
|
||||||
window.clearInterval(poll);
|
window.clearInterval(poll);
|
||||||
document.removeEventListener("visibilitychange", visible);
|
document.removeEventListener("visibilitychange", visible);
|
||||||
|
window.removeEventListener("forum:typing-out", typing);
|
||||||
socket?.close();
|
socket?.close();
|
||||||
};
|
};
|
||||||
}, [member, wsUrl, refresh]);
|
}, [member, wsUrl, refresh]);
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import { Composer } from "./Composer";
|
|||||||
import { PostBody } from "./PostBody";
|
import { PostBody } from "./PostBody";
|
||||||
import type { LiveNotice } from "./ForumNav";
|
import type { LiveNotice } from "./ForumNav";
|
||||||
import { ReportButton } from "./ReportButton";
|
import { ReportButton } from "./ReportButton";
|
||||||
|
import { TypingLine, useTypingSender, useTypingWatch } from "./typing";
|
||||||
|
|
||||||
/** How often the open thread looks for new replies (while the page is in front). */
|
/** How often the open thread looks for new replies (while the page is in front). */
|
||||||
const POLL_MS = 30_000;
|
const POLL_MS = 30_000;
|
||||||
@@ -329,6 +330,8 @@ export function ThreadView({ initial }: { initial: ThreadPage }) {
|
|||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
// Where the visitor stopped reading when they opened the page.
|
// Where the visitor stopped reading when they opened the page.
|
||||||
const [readUpTo] = useState(initial.access?.last_read_post_id ?? null);
|
const [readUpTo] = useState(initial.access?.last_read_post_id ?? null);
|
||||||
|
const typingNow = useTypingWatch("thread", initial.thread.id);
|
||||||
|
const imTyping = useTypingSender("thread", initial.thread.id);
|
||||||
const composer = useRef<HTMLDivElement>(null);
|
const composer = useRef<HTMLDivElement>(null);
|
||||||
const { viewer, thread, access } = page;
|
const { viewer, thread, access } = page;
|
||||||
const member = viewer.member !== null;
|
const member = viewer.member !== null;
|
||||||
@@ -594,6 +597,8 @@ export function ThreadView({ initial }: { initial: ThreadPage }) {
|
|||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<TypingLine text={typingNow} />
|
||||||
|
|
||||||
<div className="ftv-compose" id="valasz" ref={composer}>
|
<div className="ftv-compose" id="valasz" ref={composer}>
|
||||||
{thread.deleted ? null : !viewer.logged_in ? (
|
{thread.deleted ? null : !viewer.logged_in ? (
|
||||||
<p className="ftv-gate">
|
<p className="ftv-gate">
|
||||||
@@ -630,6 +635,7 @@ export function ThreadView({ initial }: { initial: ThreadPage }) {
|
|||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
<Composer
|
<Composer
|
||||||
|
onTyping={imTyping}
|
||||||
id="valasz-szoveg"
|
id="valasz-szoveg"
|
||||||
label="Válaszod"
|
label="Válaszod"
|
||||||
placeholder={thread.topic.listening ? "Írd le, ami benned van…" : "Írd meg a válaszod…"}
|
placeholder={thread.topic.listening ? "Írd le, ami benned van…" : "Írd meg a válaszod…"}
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
|
|
||||||
|
import type { LiveNotice } from "./ForumNav";
|
||||||
|
|
||||||
|
/** The live connection's outgoing "I am typing" (ForumNav sends it). */
|
||||||
|
export interface TypingOut {
|
||||||
|
kind: "thread" | "conversation";
|
||||||
|
id: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A typing notice is sent at most this often while typing. */
|
||||||
|
const SEND_EVERY_MS = 3000;
|
||||||
|
/** "X gépel…" disappears this long after the last notice. */
|
||||||
|
const SHOW_MS = 6000;
|
||||||
|
|
||||||
|
/** Call on every keystroke: tells the others (now and then) that the member is typing here. */
|
||||||
|
export function useTypingSender(kind: TypingOut["kind"], id: number) {
|
||||||
|
const last = useRef(0);
|
||||||
|
return useCallback(() => {
|
||||||
|
const now = Date.now();
|
||||||
|
if (now - last.current < SEND_EVERY_MS) return;
|
||||||
|
last.current = now;
|
||||||
|
window.dispatchEvent(new CustomEvent<TypingOut>("forum:typing-out", { detail: { kind, id } }));
|
||||||
|
}, [kind, id]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Who is typing here now: "Holdfény gépel…", "Holdfény és Zöldág gépel…", or null. */
|
||||||
|
export function useTypingWatch(kind: TypingOut["kind"], id: number): string | null {
|
||||||
|
const [who, setWho] = useState<Record<string, number>>({});
|
||||||
|
useEffect(() => {
|
||||||
|
const live = (e: Event) => {
|
||||||
|
const n = (e as CustomEvent<LiveNotice & { kind?: string; who?: string }>).detail;
|
||||||
|
if (n.t === "typing" && n.kind === kind && n.id === id && n.who) {
|
||||||
|
setWho((w) => ({ ...w, [n.who as string]: Date.now() }));
|
||||||
|
}
|
||||||
|
// Their post or message arrived: they are done.
|
||||||
|
if ((n.t === "thread" && kind === "thread" && n.id === id) || (n.t === "conversation" && n.id === id)) {
|
||||||
|
setWho({});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
window.addEventListener("forum:live", live);
|
||||||
|
const timer = window.setInterval(() => {
|
||||||
|
setWho((w) => {
|
||||||
|
const now = Date.now();
|
||||||
|
const kept = Object.fromEntries(Object.entries(w).filter(([, at]) => now - at < SHOW_MS));
|
||||||
|
return Object.keys(kept).length === Object.keys(w).length ? w : kept;
|
||||||
|
});
|
||||||
|
}, 1000);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener("forum:live", live);
|
||||||
|
window.clearInterval(timer);
|
||||||
|
};
|
||||||
|
}, [kind, id]);
|
||||||
|
const names = Object.keys(who);
|
||||||
|
if (names.length === 0) return null;
|
||||||
|
if (names.length === 1) return `${names[0]} gépel…`;
|
||||||
|
if (names.length === 2) return `${names[0]} és ${names[1]} gépel…`;
|
||||||
|
return `${names.length} tag gépel…`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The "… gépel" line with three soft dots. */
|
||||||
|
export function TypingLine({ text }: { text: string | null }) {
|
||||||
|
return (
|
||||||
|
<p className="ftyping" aria-live="polite">
|
||||||
|
{text && (
|
||||||
|
<>
|
||||||
|
<span className="ftyping-dots" aria-hidden="true">
|
||||||
|
<span />
|
||||||
|
<span />
|
||||||
|
<span />
|
||||||
|
</span>
|
||||||
|
{text}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
// The old forums' character smileys, turned into emoji while typing (the
|
||||||
|
// forum service converts the same list on save: services/forum/src/text.rs).
|
||||||
|
// A smiley converts only standing alone, once a space or line break follows
|
||||||
|
// it, so links and the like stay as typed.
|
||||||
|
|
||||||
|
export const EMOTICONS: [string, string][] = [
|
||||||
|
[":)", "🙂"],
|
||||||
|
[":-)", "🙂"],
|
||||||
|
["(:", "🙂"],
|
||||||
|
[":D", "😄"],
|
||||||
|
[":-D", "😄"],
|
||||||
|
["xD", "😆"],
|
||||||
|
["XD", "😆"],
|
||||||
|
[";)", "😉"],
|
||||||
|
[";-)", "😉"],
|
||||||
|
[":(", "🙁"],
|
||||||
|
[":-(", "🙁"],
|
||||||
|
[":'(", "😢"],
|
||||||
|
[":P", "😛"],
|
||||||
|
[":-P", "😛"],
|
||||||
|
[":p", "😛"],
|
||||||
|
[":O", "😮"],
|
||||||
|
[":o", "😮"],
|
||||||
|
[":-O", "😮"],
|
||||||
|
[":*", "😘"],
|
||||||
|
[":-*", "😘"],
|
||||||
|
[":/", "😕"],
|
||||||
|
[":|", "😐"],
|
||||||
|
["B)", "😎"],
|
||||||
|
["^^", "😊"],
|
||||||
|
["^_^", "😊"],
|
||||||
|
["<3", "❤️"],
|
||||||
|
["</3", "💔"],
|
||||||
|
];
|
||||||
|
|
||||||
|
const LOOKUP = new Map(EMOTICONS);
|
||||||
|
const ALTERNATIVES = [...LOOKUP.keys()]
|
||||||
|
.sort((a, b) => b.length - a.length)
|
||||||
|
.map((code) => code.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
|
||||||
|
.join("|");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The text with its finished smileys as emoji, and where the caret goes.
|
||||||
|
* `atEnd`: also a smiley at the very end (when sending).
|
||||||
|
*/
|
||||||
|
export function convertEmoticons(text: string, caret: number, atEnd = false): { text: string; caret: number } {
|
||||||
|
const pattern = new RegExp(`(^|\\s)(${ALTERNATIVES})(?=\\s${atEnd ? "|$" : ""})`, "g");
|
||||||
|
let shift = 0;
|
||||||
|
const converted = text.replace(pattern, (match, space: string, code: string, offset: number) => {
|
||||||
|
const emoji = LOOKUP.get(code) ?? code;
|
||||||
|
if (offset + space.length < caret) shift += emoji.length - code.length;
|
||||||
|
return space + emoji;
|
||||||
|
});
|
||||||
|
return { text: converted, caret: caret + shift };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* For a text field's change: converts and puts the caret back where it was
|
||||||
|
* (a controlled field would jump it to the end).
|
||||||
|
*/
|
||||||
|
export function withEmoji(e: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>, set: (text: string) => void) {
|
||||||
|
const el = e.target;
|
||||||
|
const { text, caret } = convertEmoticons(el.value, el.selectionStart ?? el.value.length);
|
||||||
|
set(text);
|
||||||
|
if (text !== el.value) {
|
||||||
|
requestAnimationFrame(() => el.setSelectionRange(caret, caret));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -198,38 +198,6 @@ export const INTENTS = {
|
|||||||
advice: { label: "Tanácsot, véleményt kér", short: "Tanácsot kér" },
|
advice: { label: "Tanácsot, véleményt kér", short: "Tanácsot kér" },
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
/** The emoji offered first in the composer: the Moon, the signs, warmth. */
|
|
||||||
export const EMOJI = [
|
|
||||||
"🙂",
|
|
||||||
"😊",
|
|
||||||
"🤍",
|
|
||||||
"🙏",
|
|
||||||
"✨",
|
|
||||||
"🌙",
|
|
||||||
"🌕",
|
|
||||||
"🌑",
|
|
||||||
"⭐",
|
|
||||||
"🌸",
|
|
||||||
"🍀",
|
|
||||||
"🕯️",
|
|
||||||
"🌿",
|
|
||||||
"☕",
|
|
||||||
"😢",
|
|
||||||
"🤗",
|
|
||||||
"♈",
|
|
||||||
"♉",
|
|
||||||
"♊",
|
|
||||||
"♋",
|
|
||||||
"♌",
|
|
||||||
"♍",
|
|
||||||
"♎",
|
|
||||||
"♏",
|
|
||||||
"♐",
|
|
||||||
"♑",
|
|
||||||
"♒",
|
|
||||||
"♓",
|
|
||||||
];
|
|
||||||
|
|
||||||
/** `/forum/szal/123-nem-tudom-elengedni`: the number decides, the words are for reading. */
|
/** `/forum/szal/123-nem-tudom-elengedni`: the number decides, the words are for reading. */
|
||||||
export function threadHref(t: { id: number; slug: string }, postId?: number): string {
|
export function threadHref(t: { id: number; slug: string }, postId?: number): string {
|
||||||
const path = t.slug ? `/forum/szal/${t.id}-${t.slug}` : `/forum/szal/${t.id}`;
|
const path = t.slug ? `/forum/szal/${t.id}-${t.slug}` : `/forum/szal/${t.id}`;
|
||||||
|
|||||||
Reference in New Issue
Block a user