diff --git a/.codex b/.codex new file mode 100644 index 0000000..e69de29 diff --git a/docs/superpowers/plans/2026-04-18-near-term-chat-features.md b/docs/superpowers/plans/2026-04-18-near-term-chat-features.md new file mode 100644 index 0000000..a9be976 --- /dev/null +++ b/docs/superpowers/plans/2026-04-18-near-term-chat-features.md @@ -0,0 +1,338 @@ +# Near-Term Chat Features Implementation Plan + +> **For agentic workers:** Use this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. Prefer small, verified slices over one large migration. + +**Goal:** Implement the seven highest-impact improvements from the modern chat backlog: direct messages, unread counts and notifications, message editing/reactions/replies, user search, pagination, room membership/private rooms, and stronger token/input safety. + +**Architecture:** Move Oxyde from public global rooms toward permissioned conversations. Introduce room membership and room kind first, then layer direct messages, unread state, richer message metadata, search, pagination, notifications, and security hardening on top. Frontend state should keep room summaries separate from loaded message pages so sidebar updates do not force full message reloads. + +**Tech Stack:** SvelteKit 5, TypeScript, Tauri 2, Rust, SurrealDB 3, Tauri plugins. + +--- + +## Delivery Order + +1. Room membership and private rooms. +2. User search instead of raw user IDs. +3. Direct messages. +4. Message pagination and scroll behavior. +5. Unread counts and notifications. +6. Message editing, reactions, and replies. +7. Secure token storage and validation limits. + +This order reduces rework: direct messages and unread counts both depend on membership; richer messages are easier after pagination and room summaries are in place. + +--- + +## Shared Data Model Target + +### Tables + +| Table | Purpose | +|---|---| +| `room` | Conversation container. Add `kind`, `name`, `created_by`, `created`, `updated`. | +| `room_member` | Membership and per-user room state. Stores `room`, `user`, `role`, `joined`, `last_read_at`, `muted`. | +| `message` | Message body and metadata. Add `updated`, `deleted`, `reply_to`. | +| `message_reaction` | One reaction per user/message/emoji. | +| `contact` | Existing contact graph. Keep, then improve with search/request flows later. | + +### Permission Rules + +- Users can select rooms only when they are members. +- Users can select messages only for rooms where they are members. +- Users can create messages only in rooms where they are members. +- Users can update/delete only their own messages. +- Users can select room members only for rooms where they are members. +- Direct-message rooms should only include the two participants. + +### Suggested Models + +Update `src-tauri/src/models.rs` and `src/lib/types.ts` to include: + +```ts +export interface Room { + id: any; + name?: string; + kind: 'public' | 'private' | 'direct'; + created_by?: any; + created: string; + updated?: string; + last_message?: Message; + unread_count?: number; +} + +export interface RoomMember { + id: any; + room: any; + user: any; + role: 'owner' | 'member'; + joined: string; + last_read_at?: string; + muted?: boolean; +} + +export interface Message { + id: any; + room: any; + author: any; + author_username?: string; + body: string; + created: string; + updated?: string; + deleted?: boolean; + reply_to?: any; + reactions?: MessageReactionSummary[]; +} + +export interface MessageReactionSummary { + emoji: string; + count: number; + reacted_by_me: boolean; +} +``` + +--- + +## File Map + +| File | Change | +|---|---| +| `surreal/schema.surql` | Add membership, richer message fields, reaction table, indexes, permissions, validation. | +| `src-tauri/src/models.rs` | Add `RoomMember`, richer `Room`, richer `Message`, reaction models, room summary structs. | +| `src/lib/types.ts` | Mirror backend types for frontend state. | +| `src-tauri/src/commands/chat.rs` | Add membership-aware room/message queries, pagination, edit/reply/reaction/read commands. | +| `src-tauri/src/commands/user.rs` | Add user search and eventually credential/profile validation improvements. | +| `src-tauri/src/commands/mod.rs` | Register any new command modules if split. | +| `src-tauri/src/lib.rs` | Register new commands and notification/keychain plugins if used. | +| `src/routes/+page.svelte` | Split room summaries, active room, message page state, unread updates, notification hooks. | +| `src/lib/components/Sidebar.svelte` | User search, direct-message entry points, unread counts, private room UI. | +| `src/lib/components/ChatMain.svelte` | Pagination, edit UI, reply UI, reactions, read markers. | +| `src/lib/components/AuthCard.svelte` | Validation and copy changes if encryption wording changes. | +| `src/lib/helpers.ts` | Add date/cursor helpers and user display helpers as needed. | + +--- + +## Task 1: Room Membership And Private Rooms + +**Goal:** Replace global room visibility with explicit membership. Support public rooms as joinable conversations and private rooms as invite-only conversations. + +**Files:** +- Modify: `surreal/schema.surql` +- Modify: `src-tauri/src/models.rs` +- Modify: `src/lib/types.ts` +- Modify: `src-tauri/src/commands/chat.rs` +- Modify: `src/routes/+page.svelte` +- Modify: `src/lib/components/Sidebar.svelte` + +- [ ] Add `kind` to `room`: `public`, `private`, `direct`. +- [ ] Add `created_by` and `updated` to `room`. +- [ ] Add `room_member` table with `room`, `user`, `role`, `joined`, `last_read_at`, `muted`. +- [ ] Add unique index on `room_member(room, user)`. +- [ ] Update room permissions so `select` requires membership, except optionally public room discovery. +- [ ] Update message permissions so `select` and `create` require room membership. +- [ ] Update `create_room` to create the room and insert the creator as owner/member in one command. +- [ ] Update `get_rooms` to return only rooms where the current user is a member. +- [ ] Add `join_public_room(room_id)` if public room discovery remains available. +- [ ] Add `invite_to_room(room_id, user_id)` for owner/member invitation, depending on chosen rules. +- [ ] Add UI affordances for private/public room creation. +- [ ] Verify old public-room behavior still works for rooms the user creates. + +**Acceptance Criteria:** +- A user cannot see rooms they are not a member of. +- A user cannot fetch or send messages in rooms they are not a member of. +- Creating a room makes the creator a member. +- Existing room list and message send flows still work for the creator. + +--- + +## Task 2: User Search Instead Of Raw User IDs + +**Goal:** Let users find people by username or email instead of manually copying record IDs. + +**Files:** +- Modify: `surreal/schema.surql` +- Modify: `src-tauri/src/commands/user.rs` +- Modify: `src-tauri/src/lib.rs` +- Modify: `src/lib/types.ts` +- Modify: `src/lib/components/Sidebar.svelte` +- Modify: `src/routes/+page.svelte` + +- [ ] Add indexes for searchable fields, at least `username`; keep `email` unique. +- [ ] Add validation and privacy rules for what search returns. +- [ ] Add `search_users(query: String) -> Vec`. +- [ ] Exclude the current user from search results. +- [ ] Return safe user fields only: id, username, avatar, maybe email only if product rules allow it. +- [ ] Replace add-contact raw ID field with a search box and selectable results. +- [ ] Use selected search result IDs for `add_contact`, `invite_to_room`, and direct-message creation. +- [ ] Add debouncing in the frontend so search does not run on every keystroke immediately. + +**Acceptance Criteria:** +- Contacts can be added without knowing a raw SurrealDB record ID. +- Empty/short searches do not spam the backend. +- Search results do not expose password/token/internal fields. + +--- + +## Task 3: Direct Messages + +**Goal:** Add one-to-one conversations that behave like rooms but are created from contacts or user search. + +**Files:** +- Modify: `surreal/schema.surql` +- Modify: `src-tauri/src/models.rs` +- Modify: `src-tauri/src/commands/chat.rs` +- Modify: `src/lib/types.ts` +- Modify: `src/routes/+page.svelte` +- Modify: `src/lib/components/Sidebar.svelte` +- Modify: `src/lib/components/ChatMain.svelte` + +- [ ] Add `room.kind = 'direct'`. +- [ ] Decide direct room naming: no stored name, display as other participant's username. +- [ ] Add a stable uniqueness guard for direct rooms. Use a deterministic participant key if SurrealDB indexes cannot enforce two-member uniqueness directly. +- [ ] Add `get_or_create_direct_room(user_id) -> Room`. +- [ ] Insert both participants into `room_member` when creating a direct room. +- [ ] Add command/query support to hydrate direct-room display names and avatars. +- [ ] Add "Message" action to contacts/search results. +- [ ] Show direct messages in a separate sidebar section or mixed with rooms using clear labels. + +**Acceptance Criteria:** +- Starting a DM with the same user opens the existing direct room. +- Both participants can see and send messages in the DM. +- No third user can read or join the DM. + +--- + +## Task 4: Pagination And Scroll Behavior + +**Goal:** Avoid loading every message at once and preserve a stable reading experience. + +**Files:** +- Modify: `src-tauri/src/commands/chat.rs` +- Modify: `src/lib/types.ts` +- Modify: `src/routes/+page.svelte` +- Modify: `src/lib/components/ChatMain.svelte` +- Modify: `src/lib/helpers.ts` + +- [ ] Change `get_messages(room_id)` into a paginated command, for example `get_messages(room_id, before?: datetime, limit?: number)`. +- [ ] Return messages newest-page aware but render oldest-to-newest in the UI. +- [ ] Add an index on `message(room, created)`. +- [ ] Track `hasOlderMessages`, `isLoadingOlder`, and `oldestCursor` in page state. +- [ ] Load older messages when the user scrolls near the top. +- [ ] Preserve scroll offset after prepending older messages. +- [ ] Only auto-scroll to bottom when the user is already near the bottom or the message is authored by the current user. +- [ ] Keep the live subscription for new messages in the active room. + +**Acceptance Criteria:** +- Opening a room loads a bounded number of messages. +- Scrolling upward loads older messages without jumping. +- New incoming messages do not force-scroll users who are reading history. + +--- + +## Task 5: Unread Counts And Notifications + +**Goal:** Make missed messages visible in the sidebar and via desktop notifications when appropriate. + +**Files:** +- Modify: `surreal/schema.surql` +- Modify: `src-tauri/src/models.rs` +- Modify: `src-tauri/src/commands/chat.rs` +- Modify: `src-tauri/src/lib.rs` +- Modify: `src/lib/types.ts` +- Modify: `src/routes/+page.svelte` +- Modify: `src/lib/components/Sidebar.svelte` + +- [ ] Add or use `room_member.last_read_at`. +- [ ] Add `mark_room_read(room_id)` command. +- [ ] Update room summary query to include `last_message` and `unread_count`. +- [ ] Mark the active room read when opened and when the user reaches the bottom. +- [ ] Increment/update unread room summaries when live events arrive for inactive rooms. +- [ ] Add visual unread badges in the sidebar. +- [ ] Add Tauri notification plugin if not already available. +- [ ] Request notification permission at a sensible moment. +- [ ] Send native notifications for messages in inactive rooms when the app is unfocused and the room is not muted. +- [ ] Add `muted` support from `room_member.muted` to suppress notifications. + +**Acceptance Criteria:** +- Inactive room messages increase unread count. +- Opening or reading a room clears its unread count for the current user. +- Desktop notifications fire only when useful and respect muted rooms. + +--- + +## Task 6: Message Editing, Reactions, And Replies + +**Goal:** Add the message interactions users expect without disrupting the current simple composer. + +**Files:** +- Modify: `surreal/schema.surql` +- Modify: `src-tauri/src/models.rs` +- Modify: `src-tauri/src/commands/chat.rs` +- Modify: `src/lib/types.ts` +- Modify: `src/routes/+page.svelte` +- Modify: `src/lib/components/ChatMain.svelte` +- Modify: `src/lib/components/ContextMenu.svelte` if richer menu state is needed. + +- [ ] Add `updated`, `deleted`, and `reply_to` fields to `message`. +- [ ] Replace hard delete with soft delete for normal message deletion. +- [ ] Add `edit_message(message_id, body)` command with author-only permission. +- [ ] Add `send_message(room_id, body, reply_to?)`. +- [ ] Add `message_reaction` table with `message`, `user`, `emoji`, `created`. +- [ ] Add unique index on `message_reaction(message, user, emoji)`. +- [ ] Add `toggle_reaction(message_id, emoji)` command. +- [ ] Include reaction summaries when fetching messages. +- [ ] Add context menu actions for edit, reply, delete, copy. +- [ ] Add inline edit mode for the user's own messages. +- [ ] Add reply preview above the composer and reply reference rendering in the message list. +- [ ] Add a small reaction picker or a short default emoji row. +- [ ] Ensure live update events update edited messages, deleted messages, and reactions. + +**Acceptance Criteria:** +- Users can edit only their own messages. +- Replies show enough context to identify the parent message. +- Reactions toggle reliably and aggregate counts across users. +- Deleted messages leave a useful placeholder instead of breaking replies. + +--- + +## Task 7: Secure Token Storage And Validation Limits + +**Goal:** Reduce security and data-quality risks before the app grows more social features. + +**Files:** +- Modify: `src-tauri/Cargo.toml` +- Modify: `src-tauri/src/lib.rs` +- Modify: `src-tauri/src/commands/user.rs` +- Modify: `src-tauri/src/commands/chat.rs` +- Modify: `surreal/schema.surql` +- Modify: `src/lib/components/AuthCard.svelte` +- Modify: `src/lib/components/Sidebar.svelte` +- Modify: `src/lib/components/ChatMain.svelte` + +- [ ] Replace plain `tauri-plugin-store` token persistence with OS-backed secure storage where practical. +- [ ] If secure storage is not immediately available on every target platform, isolate token storage behind helper functions so the backend can swap implementations later. +- [ ] Add username length and character validation. +- [ ] Add email length validation. +- [ ] Add password minimum length in signup. +- [ ] Add room name length validation. +- [ ] Add message body length validation. +- [ ] Add avatar URL validation or remove avatar URL until uploads/proxying exist. +- [ ] Add SurrealDB schema assertions where possible, and duplicate key user-facing errors in Rust for better messages. +- [ ] Remove or revise the auth tagline claim `encrypted` unless end-to-end encryption is implemented. +- [ ] Add tests for validation boundaries in Rust command-level helpers where possible. + +**Acceptance Criteria:** +- Session tokens are not stored as plain JSON when a supported secure storage path is available. +- Invalid inputs fail before they create malformed records. +- Error messages are useful to users. +- Product copy no longer overclaims encryption. + +--- + +## Verification Plan + +- [ ] Run `pnpm check` after each frontend slice. +- [ ] Run `cargo test` or `cargo check` inside `src-tauri` after each Rust slice. +- [ ] Manually test with two users: public room, private room, direct message, message send, edit, reply, reaction, unread clear, notification, and signout/session restore. +- [ ] Test permission failures by trying to fetch a room/message as a non-member. +- [ ] Test scroll pagination with enough messages to require at least three pages. diff --git a/docs/superpowers/specs/2026-04-18-modern-chat-todo.md b/docs/superpowers/specs/2026-04-18-modern-chat-todo.md new file mode 100644 index 0000000..1fbe645 --- /dev/null +++ b/docs/superpowers/specs/2026-04-18-modern-chat-todo.md @@ -0,0 +1,93 @@ +# Modern Chat App Todo + +**Date:** 2026-04-18 +**Status:** Draft + +## Overview + +Oxyde currently has a compact chat foundation: authentication, persistent session restore, public rooms, live message updates, contacts, profile editing, message delete, and context menus. This backlog lists user-facing improvements that would make it feel closer to a modern desktop chat app. + +## Core Chat + +- [ ] Add message editing, with an edited timestamp or marker. +- [ ] Add replies or lightweight threads so users can respond to a specific message. +- [ ] Add reactions, starting with emoji reactions on messages. +- [ ] Add read receipts or "seen by" state for direct and group conversations. +- [ ] Add typing indicators per room. +- [ ] Add message pagination or infinite scroll instead of loading every message in a room. +- [ ] Add message search across the current room and all rooms. +- [ ] Add link previews for URLs in messages. +- [ ] Add file and image attachments with preview support. +- [ ] Add Markdown-style formatting for code, links, bold text, lists, and multiline blocks. + +## Rooms And Conversations + +- [ ] Add private direct messages between contacts. +- [ ] Add room membership instead of fully public rooms. +- [ ] Add invite flows for rooms and contacts instead of requiring raw user IDs. +- [ ] Add room settings: rename room, delete room, leave room. +- [ ] Add pinned messages per room. +- [ ] Add room unread counts and last-message previews in the sidebar. +- [ ] Add notification badges when messages arrive outside the active room. +- [ ] Add muted rooms or per-room notification settings. + +## Contacts And Identity + +- [ ] Replace "add contact by user ID" with user search by username or email. +- [ ] Add contact requests and approval instead of immediately adding contacts. +- [ ] Show real avatars instead of only username initials. +- [ ] Add presence states: online, idle, offline, and do-not-disturb. +- [ ] Add profile cards when clicking or right-clicking a user. +- [ ] Add account settings for email and password changes. +- [ ] Add password reset or recovery flow. + +## Reliability And UX + +- [ ] Add optimistic sending states: sending, sent, failed, retry. +- [ ] Add offline handling and reconnect indicators. +- [ ] Add local draft persistence per room. +- [ ] Preserve scroll position when switching rooms. +- [ ] Avoid always auto-scrolling if the user is reading older messages. +- [ ] Add empty, error, and loading states for room list, contacts, and messages. +- [ ] Add toast notifications for copy, delete, save, and failed actions. +- [ ] Add keyboard shortcuts: room switcher, search, focus composer, escape modals. +- [ ] Add accessibility pass: focus states, ARIA labels, keyboard context menus. + +## Security And Privacy + +- [ ] Clarify whether "encrypted" is real; the auth screen says encrypted, but messages currently appear stored as plain text. +- [ ] Add end-to-end encryption or remove encryption claims until implemented. +- [ ] Store session tokens more securely where possible, ideally via OS keychain or credential storage instead of plain app store JSON. +- [ ] Add rate limits or abuse protection for room and message creation. +- [ ] Add validation and length limits for usernames, room names, avatars, and message bodies. +- [ ] Add block and report user flows. + +## Desktop App Polish + +- [ ] Add native notifications for background messages. +- [ ] Add tray behavior or "minimize to tray" settings. +- [ ] Add app update flow. +- [ ] Add deep links or app links for room invites. +- [ ] Add platform-specific menu items: preferences, quit, about. +- [ ] Add window state persistence: size, position, last active room. +- [ ] Add themes, including light, dark, and system options. +- [ ] Add responsive layout for narrower windows. + +## Data Model And Backend + +- [ ] Add room membership tables and permissions. Rooms and messages are currently broadly selectable in `surreal/schema.surql`. +- [ ] Add message metadata fields like `updated`, `deleted`, `reply_to`, `attachments`, and `reactions`. +- [ ] Add indexes for common queries: messages by room and created timestamp, contacts by owner, room memberships. +- [ ] Add proper soft delete for messages instead of hard delete. +- [ ] Add migrations or versioning for schema changes. +- [ ] Add tests around auth permissions, contact visibility, message ownership, and live subscriptions. + +## Near-Term Best Bets + +- [ ] Direct messages. +- [ ] Unread counts and notifications. +- [ ] Message editing, reactions, and replies. +- [ ] User search instead of raw user IDs. +- [ ] Pagination or infinite scroll. +- [ ] Room membership and private rooms. +- [ ] Secure token storage and validation limits. diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index c84c064..fedfbf1 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -3824,7 +3824,7 @@ dependencies = [ [[package]] name = "oxyde" -version = "0.1.0" +version = "0.1.1" dependencies = [ "futures-util", "serde", diff --git a/src-tauri/src/commands/chat.rs b/src-tauri/src/commands/chat.rs index 3256c5c..126e0ac 100644 --- a/src-tauri/src/commands/chat.rs +++ b/src-tauri/src/commands/chat.rs @@ -1,11 +1,18 @@ -use tauri::{AppHandle, Emitter, State}; -use uuid::Uuid; +use std::collections::HashMap; + use futures_util::StreamExt; use surrealdb::Notification; +use tauri::{AppHandle, Emitter, State}; +use uuid::Uuid; use crate::db::AppState; use crate::error::{into_err, AppError}; -use crate::models::{Message, Room}; +use crate::models::{Message, MessageReaction, MessageReactionSummary, Room, User}; + +const DEFAULT_PAGE_SIZE: i64 = 50; +const MAX_PAGE_SIZE: i64 = 100; +const MAX_MESSAGE_LEN: usize = 4000; +const MAX_ROOM_NAME_LEN: usize = 80; /// Wrapper emitted to the frontend for each LIVE query notification. /// Includes the action type so the frontend can distinguish create/update/delete. @@ -15,92 +22,379 @@ struct LiveMessageEvent<'a> { data: &'a Message, } -/// Create a new chat room. +fn validate_room_name(name: &str) -> Result<(), String> { + let trimmed = name.trim(); + if trimmed.is_empty() { + return Err(AppError::Auth("room name is required".into()).to_string()); + } + if trimmed.chars().count() > MAX_ROOM_NAME_LEN { + return Err(AppError::Auth(format!( + "room name must be {MAX_ROOM_NAME_LEN} characters or less" + )) + .to_string()); + } + Ok(()) +} + +fn validate_message_body(body: &str) -> Result<(), String> { + let trimmed = body.trim(); + if trimmed.is_empty() { + return Err(AppError::Auth("message cannot be empty".into()).to_string()); + } + if trimmed.chars().count() > MAX_MESSAGE_LEN { + return Err(AppError::Auth(format!( + "message must be {MAX_MESSAGE_LEN} characters or less" + )) + .to_string()); + } + Ok(()) +} + +async fn current_user(state: &State<'_, AppState>) -> Result { + let mut result: Vec = state + .db + .query("SELECT * FROM $auth") + .await + .map_err(into_err)? + .take(0) + .map_err(into_err)?; + + result + .pop() + .ok_or_else(|| into_err(AppError::Auth("not authenticated".into()))) +} + +async fn hydrate_reactions( + state: &State<'_, AppState>, + user: &User, + messages: &mut [Message], +) -> Result<(), String> { + for message in messages { + let reactions: Vec = state + .db + .query("SELECT * FROM message_reaction WHERE message = $message") + .bind(("message", message.id.clone())) + .await + .map_err(into_err)? + .take(0) + .map_err(into_err)?; + + let mut grouped: HashMap = HashMap::new(); + for reaction in reactions { + let entry = grouped + .entry(reaction.emoji.clone()) + .or_insert(MessageReactionSummary { + emoji: reaction.emoji, + count: 0, + reacted_by_me: false, + }); + entry.count += 1; + if reaction.user == user.id { + entry.reacted_by_me = true; + } + } + + let mut summaries: Vec = grouped.into_values().collect(); + summaries.sort_by(|a, b| a.emoji.cmp(&b.emoji)); + message.reactions = Some(summaries); + } + + Ok(()) +} + +async fn hydrate_direct_rooms( + state: &State<'_, AppState>, + rooms: &mut [Room], +) -> Result<(), String> { + for room in rooms.iter_mut().filter(|room| room.kind == "direct") { + let mut users: Vec = state + .db + .query( + "SELECT * FROM user + WHERE id IN ( + SELECT VALUE user FROM room_member + WHERE room = $room AND user != $auth + ) + LIMIT 1", + ) + .bind(("room", room.id.clone())) + .await + .map_err(into_err)? + .take(0) + .map_err(into_err)?; + + room.other_user = users.pop(); + } + + Ok(()) +} + +/// Create a new chat room and add the creator as owner. #[tauri::command] pub async fn create_room( state: State<'_, AppState>, name: String, + kind: Option, ) -> Result { + validate_room_name(&name)?; + let room_kind = kind.unwrap_or_else(|| "public".to_string()); + if !matches!(room_kind.as_str(), "public" | "private") { + return Err(AppError::Auth("room kind must be public or private".into()).to_string()); + } + let mut result: Vec = state .db - .query("CREATE room SET name = $name, created = time::now()") - .bind(("name", name)) + .query( + "CREATE room SET + name = $name, + kind = $kind, + created_by = $auth, + created = time::now(), + updated = time::now()", + ) + .bind(("name", name.trim().to_string())) + .bind(("kind", room_kind)) .await .map_err(into_err)? .take(0) .map_err(into_err)?; - result.pop().ok_or_else(|| into_err(AppError::NotFound("room after create".into()))) + let room = result + .pop() + .ok_or_else(|| into_err(AppError::NotFound("room after create".into())))?; + + state + .db + .query( + "CREATE room_member SET + room = $room, + user = $auth, + role = 'owner', + joined = time::now(), + last_read_at = time::now(), + muted = false", + ) + .bind(("room", room.id.clone())) + .await + .map_err(into_err)?; + + Ok(room) } -/// Fetch all rooms. +/// Fetch public rooms and rooms the current user belongs to. #[tauri::command] pub async fn get_rooms(state: State<'_, AppState>) -> Result, String> { - let result: Vec = state + let mut result: Vec = state .db - .query("SELECT * FROM room ORDER BY created DESC") + .query( + "SELECT * FROM room + WHERE kind = 'public' OR id IN (SELECT VALUE room FROM room_member WHERE user = $auth) + ORDER BY updated DESC, created DESC", + ) .await .map_err(into_err)? .take(0) .map_err(into_err)?; + hydrate_direct_rooms(&state, &mut result).await?; Ok(result) } +/// Add a user to a room. Room owners can invite others. +#[tauri::command] +pub async fn invite_to_room( + state: State<'_, AppState>, + room_id: String, + user_id: String, +) -> Result<(), String> { + state + .db + .query( + "CREATE room_member SET + room = type::record('room', $room_id), + user = type::record('user', $user_id), + role = 'member', + joined = time::now(), + muted = false", + ) + .bind(("room_id", room_id)) + .bind(("user_id", user_id)) + .await + .map_err(into_err)?; + + Ok(()) +} + +/// Return an existing direct room for two users or create it. +#[tauri::command] +pub async fn get_or_create_direct_room( + state: State<'_, AppState>, + user_id: String, +) -> Result { + let me = current_user(&state).await?; + let me_key = + serde_json::to_string(&me.id).map_err(|e| into_err(AppError::Auth(e.to_string())))?; + let target_key = serde_json::json!({ + "table": "user", + "key": { "String": user_id.clone() } + }) + .to_string(); + let mut participants = [me_key, target_key]; + participants.sort(); + let direct_key = participants.join("|"); + + let mut existing: Vec = state + .db + .query("SELECT * FROM room WHERE kind = 'direct' AND direct_key = $direct_key LIMIT 1") + .bind(("direct_key", direct_key.clone())) + .await + .map_err(into_err)? + .take(0) + .map_err(into_err)?; + + if let Some(mut room) = existing.pop() { + hydrate_direct_rooms(&state, std::slice::from_mut(&mut room)).await?; + return Ok(room); + } + + let mut created: Vec = state + .db + .query( + "CREATE room SET + name = NONE, + kind = 'direct', + direct_key = $direct_key, + created_by = $auth, + created = time::now(), + updated = time::now()", + ) + .bind(("direct_key", direct_key)) + .await + .map_err(into_err)? + .take(0) + .map_err(into_err)?; + + let room = created + .pop() + .ok_or_else(|| into_err(AppError::NotFound("direct room after create".into())))?; + + state + .db + .query( + "CREATE room_member SET room = $room, user = $auth, role = 'owner', joined = time::now(), last_read_at = time::now(), muted = false; + CREATE room_member SET room = $room, user = type::record('user', $user_id), role = 'member', joined = time::now(), muted = false;", + ) + .bind(("room", room.id.clone())) + .bind(("user_id", user_id)) + .await + .map_err(into_err)?; + + let mut room = room; + hydrate_direct_rooms(&state, std::slice::from_mut(&mut room)).await?; + Ok(room) +} + /// Send a message to a room. #[tauri::command] pub async fn send_message( state: State<'_, AppState>, room_id: String, body: String, + reply_to: Option, ) -> Result { - let mut result: Vec = state - .db - .query( - "CREATE message SET + validate_message_body(&body)?; + + let query = if reply_to.is_some() { + "CREATE message SET room = type::record('room', $room_id), author = $auth, author_username = $auth.username, body = $body, - created = time::now()", - ) + reply_to = type::record('message', $reply_to), + deleted = false, + created = time::now(); + UPDATE type::record('room', $room_id) SET updated = time::now();" + } else { + "CREATE message SET + room = type::record('room', $room_id), + author = $auth, + author_username = $auth.username, + body = $body, + deleted = false, + created = time::now(); + UPDATE type::record('room', $room_id) SET updated = time::now();" + }; + + let mut response = state + .db + .query(query) .bind(("room_id", room_id)) - .bind(("body", body)) + .bind(("body", body.trim().to_string())); + + if let Some(reply_to) = reply_to { + response = response.bind(("reply_to", reply_to)); + } + + let mut result: Vec = response .await .map_err(into_err)? .take(0) .map_err(into_err)?; - result.pop().ok_or_else(|| into_err(AppError::NotFound("message after create".into()))) + result + .pop() + .ok_or_else(|| into_err(AppError::NotFound("message after create".into()))) } -/// Fetch all messages in a room, oldest first. +/// Fetch a bounded page of messages in a room, oldest first. #[tauri::command] pub async fn get_messages( state: State<'_, AppState>, room_id: String, + before: Option, + limit: Option, ) -> Result, String> { - let result: Vec = state + let limit = limit.unwrap_or(DEFAULT_PAGE_SIZE).clamp(1, MAX_PAGE_SIZE); + let query = if before.is_some() { + "SELECT * FROM message + WHERE room = type::record('room', $room_id) AND created < $before + ORDER BY created DESC + LIMIT $limit" + } else { + "SELECT * FROM message + WHERE room = type::record('room', $room_id) + ORDER BY created DESC + LIMIT $limit" + }; + + let mut response = state .db - .query("SELECT * FROM message WHERE room = type::record('room', $room_id) ORDER BY created ASC") + .query(query) .bind(("room_id", room_id)) + .bind(("limit", limit)); + + if let Some(before) = before { + response = response.bind(("before", before)); + } + + let mut result: Vec = response .await .map_err(into_err)? .take(0) .map_err(into_err)?; + result.reverse(); + let user = current_user(&state).await?; + hydrate_reactions(&state, &user, &mut result).await?; Ok(result) } -/// Delete a message by its ID string (e.g. "message:abc123"). +/// Soft-delete a message by its ID string. #[tauri::command] -pub async fn delete_message( - state: State<'_, AppState>, - message_id: String, -) -> Result<(), String> { +pub async fn delete_message(state: State<'_, AppState>, message_id: String) -> Result<(), String> { state .db - .query("DELETE type::record($id) WHERE author = $auth") + .query("UPDATE type::record($id) SET deleted = true, body = '', updated = time::now() WHERE author = $auth") .bind(("id", message_id)) .await .map_err(into_err)?; @@ -108,6 +402,85 @@ pub async fn delete_message( Ok(()) } +/// Edit the current user's message. +#[tauri::command] +pub async fn edit_message( + state: State<'_, AppState>, + message_id: String, + body: String, +) -> Result { + validate_message_body(&body)?; + let mut result: Vec = state + .db + .query("UPDATE type::record($id) SET body = $body, updated = time::now() WHERE author = $auth RETURN AFTER") + .bind(("id", message_id)) + .bind(("body", body.trim().to_string())) + .await + .map_err(into_err)? + .take(0) + .map_err(into_err)?; + + result + .pop() + .ok_or_else(|| into_err(AppError::NotFound("message".into()))) +} + +/// Toggle one emoji reaction for the current user. +#[tauri::command] +pub async fn toggle_reaction( + state: State<'_, AppState>, + message_id: String, + emoji: String, +) -> Result<(), String> { + let emoji = emoji.trim(); + if emoji.is_empty() || emoji.chars().count() > 16 { + return Err(AppError::Auth("invalid reaction".into()).to_string()); + } + + let existing: Vec = state + .db + .query("SELECT * FROM message_reaction WHERE message = type::record($message_id) AND user = $auth AND emoji = $emoji") + .bind(("message_id", message_id.clone())) + .bind(("emoji", emoji.to_string())) + .await + .map_err(into_err)? + .take(0) + .map_err(into_err)?; + + if existing.is_empty() { + state + .db + .query("CREATE message_reaction SET message = type::record($message_id), user = $auth, emoji = $emoji, created = time::now()") + .bind(("message_id", message_id)) + .bind(("emoji", emoji.to_string())) + .await + .map_err(into_err)?; + } else { + state + .db + .query("DELETE message_reaction WHERE message = type::record($message_id) AND user = $auth AND emoji = $emoji") + .bind(("message_id", message_id)) + .bind(("emoji", emoji.to_string())) + .await + .map_err(into_err)?; + } + + Ok(()) +} + +/// Mark the room read for the current user. +#[tauri::command] +pub async fn mark_room_read(state: State<'_, AppState>, room_id: String) -> Result<(), String> { + state + .db + .query("UPDATE room_member SET last_read_at = time::now() WHERE room = type::record('room', $room_id) AND user = $auth") + .bind(("room_id", room_id)) + .await + .map_err(into_err)?; + + Ok(()) +} + /// Start a LIVE query for new messages in a room. /// Spawns a background tokio task that emits "chat:message" Tauri events. /// @@ -133,10 +506,13 @@ pub async fn subscribe_room( let handle = tokio::spawn(async move { while let Some(Ok(notification)) = stream.next().await { - let _ = app_handle.emit("chat:message", &LiveMessageEvent { - action: format!("{:?}", notification.action), - data: ¬ification.data, - }); + let _ = app_handle.emit( + "chat:message", + &LiveMessageEvent { + action: format!("{:?}", notification.action), + data: ¬ification.data, + }, + ); } }); @@ -148,10 +524,7 @@ pub async fn subscribe_room( /// Stop a LIVE query subscription. /// Aborts the background task — dropping the stream closes the LIVE query. #[tauri::command] -pub async fn unsubscribe_room( - state: State<'_, AppState>, - sub_id: String, -) -> Result<(), String> { +pub async fn unsubscribe_room(state: State<'_, AppState>, sub_id: String) -> Result<(), String> { let uuid = sub_id .parse::() .map_err(|e| into_err(AppError::Subscription(e.to_string())))?; diff --git a/src-tauri/src/commands/user.rs b/src-tauri/src/commands/user.rs index a608f38..58bae53 100644 --- a/src-tauri/src/commands/user.rs +++ b/src-tauri/src/commands/user.rs @@ -7,6 +7,58 @@ use crate::models::{Contact, User}; const SESSION_STORE: &str = "session.json"; const TOKEN_KEY: &str = "token"; +const MIN_PASSWORD_LEN: usize = 8; +const MAX_USERNAME_LEN: usize = 32; +const MAX_EMAIL_LEN: usize = 254; + +fn validate_email(email: &str) -> Result<(), String> { + let email = email.trim(); + if email.is_empty() || email.len() > MAX_EMAIL_LEN || !email.contains('@') { + return Err(AppError::Auth("enter a valid email address".into()).to_string()); + } + Ok(()) +} + +fn validate_password(password: &str) -> Result<(), String> { + if password.chars().count() < MIN_PASSWORD_LEN { + return Err(AppError::Auth(format!( + "password must be at least {MIN_PASSWORD_LEN} characters" + )) + .to_string()); + } + Ok(()) +} + +fn validate_username(username: &str) -> Result<(), String> { + let username = username.trim(); + if username.is_empty() || username.chars().count() > MAX_USERNAME_LEN { + return Err( + AppError::Auth(format!("username must be 1-{MAX_USERNAME_LEN} characters")).to_string(), + ); + } + if !username + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.') + { + return Err( + AppError::Auth("username can use letters, numbers, _, -, and .".into()).to_string(), + ); + } + Ok(()) +} + +fn validate_avatar(avatar: &Option) -> Result<(), String> { + if let Some(avatar) = avatar { + let avatar = avatar.trim(); + if !avatar.is_empty() && !(avatar.starts_with("https://") || avatar.starts_with("http://")) + { + return Err( + AppError::Auth("avatar must be a valid http or https URL".into()).to_string(), + ); + } + } + Ok(()) +} /// Create a new user account via SurrealDB Record Auth SIGNUP. /// Returns the created User record. Persists the JWT token to disk. @@ -18,13 +70,17 @@ pub async fn signup( username: String, password: String, ) -> Result { + validate_email(&email)?; + validate_username(&username)?; + validate_password(&password)?; + let credentials = surrealdb::opt::auth::Record { access: SURREAL_ACCESS.to_string(), namespace: SURREAL_NS.to_string(), database: SURREAL_DB.to_string(), params: serde_json::json!({ - "email": email, - "username": username, + "email": email.trim(), + "username": username.trim(), "password": password, }), }; @@ -41,7 +97,9 @@ pub async fn signup( .take(0) .map_err(into_err)?; - result.pop().ok_or_else(|| into_err(AppError::Auth("signup succeeded but $auth not set".into()))) + result + .pop() + .ok_or_else(|| into_err(AppError::Auth("signup succeeded but $auth not set".into()))) } /// Authenticate an existing user via SurrealDB Record Auth SIGNIN. @@ -53,16 +111,25 @@ pub async fn signin( email: String, password: String, ) -> Result { + validate_email(&email)?; + validate_password(&password)?; + let credentials = surrealdb::opt::auth::Record { access: SURREAL_ACCESS.to_string(), namespace: SURREAL_NS.to_string(), database: SURREAL_DB.to_string(), params: serde_json::json!({ - "email": email, + "email": email.trim(), "password": password, }), }; - let token_str = state.db.signin(credentials).await.map_err(into_err)?.access.into_insecure_token(); + let token_str = state + .db + .signin(credentials) + .await + .map_err(into_err)? + .access + .into_insecure_token(); *state.token.lock().unwrap() = Some(token_str.clone()); save_token(&app_handle, &token_str)?; Ok(token_str) @@ -70,10 +137,7 @@ pub async fn signin( /// Clear the current session. Invalidates the token in state and removes it from disk. #[tauri::command] -pub async fn signout( - state: State<'_, AppState>, - app_handle: AppHandle, -) -> Result<(), String> { +pub async fn signout(state: State<'_, AppState>, app_handle: AppHandle) -> Result<(), String> { state.db.invalidate().await.map_err(into_err)?; *state.token.lock().unwrap() = None; clear_token(&app_handle)?; @@ -89,11 +153,14 @@ pub async fn restore_session( state: State<'_, AppState>, app_handle: AppHandle, ) -> Result { - let token_str = load_token(&app_handle)?.ok_or_else(|| { - AppError::Auth("no saved session".into()).to_string() - })?; + let token_str = load_token(&app_handle)? + .ok_or_else(|| AppError::Auth("no saved session".into()).to_string())?; - match state.db.authenticate(surrealdb::opt::auth::Token::from(token_str.clone())).await { + match state + .db + .authenticate(surrealdb::opt::auth::Token::from(token_str.clone())) + .await + { Ok(_) => { *state.token.lock().unwrap() = Some(token_str); @@ -105,7 +172,9 @@ pub async fn restore_session( .take(0) .map_err(into_err)?; - result.pop().ok_or_else(|| into_err(AppError::Auth("session restored but $auth not set".into()))) + result.pop().ok_or_else(|| { + into_err(AppError::Auth("session restored but $auth not set".into())) + }) } Err(_) => { let _ = clear_token(&app_handle); @@ -126,7 +195,9 @@ pub async fn get_me(state: State<'_, AppState>) -> Result { .take(0) .map_err(into_err)?; - result.pop().ok_or_else(|| into_err(AppError::Auth("not authenticated".into()))) + result + .pop() + .ok_or_else(|| into_err(AppError::Auth("not authenticated".into()))) } /// Update mutable profile fields. Only provided fields are changed. @@ -136,6 +207,11 @@ pub async fn update_profile( username: Option, avatar: Option, ) -> Result { + if let Some(username) = &username { + validate_username(username)?; + } + validate_avatar(&avatar)?; + let mut result: Vec = state .db .query( @@ -144,14 +220,46 @@ pub async fn update_profile( avatar = $avatar ?? avatar RETURN AFTER", ) - .bind(("username", username)) - .bind(("avatar", avatar)) + .bind(("username", username.map(|s| s.trim().to_string()))) + .bind(( + "avatar", + avatar + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()), + )) .await .map_err(into_err)? .take(0) .map_err(into_err)?; - result.pop().ok_or_else(|| into_err(AppError::NotFound("user".into()))) + result + .pop() + .ok_or_else(|| into_err(AppError::NotFound("user".into()))) +} + +/// Search users by username. Returns safe profile fields only. +#[tauri::command] +pub async fn search_users(state: State<'_, AppState>, query: String) -> Result, String> { + let query = query.trim(); + if query.chars().count() < 2 { + return Ok(Vec::new()); + } + + let result: Vec = state + .db + .query( + "SELECT id, username, email, avatar, created FROM user + WHERE id != $auth AND string::lowercase(username) CONTAINS string::lowercase($query) + ORDER BY username + LIMIT 10", + ) + .bind(("query", query.to_string())) + .await + .map_err(into_err)? + .take(0) + .map_err(into_err)?; + + Ok(result) } /// Return the contacts list for the current user. @@ -159,7 +267,11 @@ pub async fn update_profile( pub async fn get_contacts(state: State<'_, AppState>) -> Result, String> { let result: Vec = state .db - .query("SELECT target.* FROM contact WHERE owner = $auth") + .query( + "SELECT * FROM user + WHERE id IN (SELECT VALUE target FROM contact WHERE owner = $auth) + ORDER BY username", + ) .await .map_err(into_err)? .take(0) @@ -170,10 +282,7 @@ pub async fn get_contacts(state: State<'_, AppState>) -> Result, Strin /// Add a user to the current user's contact list. #[tauri::command] -pub async fn add_contact( - state: State<'_, AppState>, - user_id: String, -) -> Result { +pub async fn add_contact(state: State<'_, AppState>, user_id: String) -> Result { let mut result: Vec = state .db .query("CREATE contact SET owner = $auth, target = type::record('user', $uid)") @@ -183,7 +292,9 @@ pub async fn add_contact( .take(0) .map_err(into_err)?; - result.pop().ok_or_else(|| into_err(AppError::NotFound("contact after create".into()))) + result + .pop() + .ok_or_else(|| into_err(AppError::NotFound("contact after create".into()))) } // ── Private helpers ─────────────────────────────────────────────────────────── @@ -196,7 +307,9 @@ fn save_token(app: &AppHandle, token: &str) -> Result<(), String> { fn load_token(app: &AppHandle) -> Result, String> { let store = app.store(SESSION_STORE).map_err(|e| e.to_string())?; - Ok(store.get(TOKEN_KEY).and_then(|v| v.as_str().map(String::from))) + Ok(store + .get(TOKEN_KEY) + .and_then(|v| v.as_str().map(String::from))) } fn clear_token(app: &AppHandle) -> Result<(), String> { diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 24f21a1..a56d076 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -18,9 +18,13 @@ pub fn run() { .setup(|app| { let app_handle = app.handle().clone(); tauri::async_runtime::block_on(async move { - let surreal = init_db(SURREAL_URL.as_str(), SURREAL_NS.as_str(), SURREAL_DB.as_str()) - .await - .expect("Failed to connect to SurrealDB"); + let surreal = init_db( + SURREAL_URL.as_str(), + SURREAL_NS.as_str(), + SURREAL_DB.as_str(), + ) + .await + .expect("Failed to connect to SurrealDB"); let state = AppState { db: Arc::new(surreal), @@ -39,13 +43,19 @@ pub fn run() { commands::user::get_me, commands::user::restore_session, commands::user::update_profile, + commands::user::search_users, commands::user::get_contacts, commands::user::add_contact, commands::chat::create_room, commands::chat::get_rooms, + commands::chat::invite_to_room, + commands::chat::get_or_create_direct_room, commands::chat::send_message, commands::chat::get_messages, commands::chat::delete_message, + commands::chat::edit_message, + commands::chat::toggle_reaction, + commands::chat::mark_room_read, commands::chat::subscribe_room, commands::chat::unsubscribe_room, ]) diff --git a/src-tauri/src/models.rs b/src-tauri/src/models.rs index ded1e60..b2fb98b 100644 --- a/src-tauri/src/models.rs +++ b/src-tauri/src/models.rs @@ -6,7 +6,7 @@ use surrealdb_types::SurrealValue; pub struct User { pub id: RecordId, pub username: String, - pub email: String, + pub email: Option, pub avatar: Option, pub created: Datetime, } @@ -14,8 +14,27 @@ pub struct User { #[derive(Debug, Clone, Serialize, Deserialize, SurrealValue)] pub struct Room { pub id: RecordId, - pub name: String, + pub name: Option, + pub kind: String, + pub created_by: Option, + pub direct_key: Option, pub created: Datetime, + pub updated: Option, + pub last_message: Option, + pub unread_count: Option, + pub other_user: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize, SurrealValue)] +#[allow(dead_code)] +pub struct RoomMember { + pub id: RecordId, + pub room: RecordId, + pub user: RecordId, + pub role: String, + pub joined: Datetime, + pub last_read_at: Option, + pub muted: Option, } #[derive(Debug, Clone, Serialize, Deserialize, SurrealValue)] @@ -26,6 +45,26 @@ pub struct Message { pub author_username: Option, pub body: String, pub created: Datetime, + pub updated: Option, + pub deleted: Option, + pub reply_to: Option, + pub reactions: Option>, +} + +#[derive(Debug, Clone, Serialize, Deserialize, SurrealValue)] +pub struct MessageReaction { + pub id: RecordId, + pub message: RecordId, + pub user: RecordId, + pub emoji: String, + pub created: Datetime, +} + +#[derive(Debug, Clone, Serialize, Deserialize, SurrealValue)] +pub struct MessageReactionSummary { + pub emoji: String, + pub count: i64, + pub reacted_by_me: bool, } #[derive(Debug, Clone, Serialize, Deserialize, SurrealValue)] @@ -45,7 +84,10 @@ mod tests { fn _assert_serialize Deserialize<'de>>() {} _assert_serialize::(); _assert_serialize::(); + _assert_serialize::(); _assert_serialize::(); + _assert_serialize::(); + _assert_serialize::(); _assert_serialize::(); } } diff --git a/src/lib/components/AuthCard.svelte b/src/lib/components/AuthCard.svelte index aa04d58..bebc535 100644 --- a/src/lib/components/AuthCard.svelte +++ b/src/lib/components/AuthCard.svelte @@ -25,7 +25,7 @@

OXYDE

-

encrypted · realtime · distributed

+

realtime · native · focused

{#if err}
{err}
diff --git a/src/lib/components/ChatMain.svelte b/src/lib/components/ChatMain.svelte index 7460932..8abf03b 100644 --- a/src/lib/components/ChatMain.svelte +++ b/src/lib/components/ChatMain.svelte @@ -8,9 +8,15 @@ messages: Message[]; user: User | null; err: string; + hasOlderMessages: boolean; + isLoadingOlder: boolean; fMsg: string; + replyTo: Message | null; + onLoadOlderMessages: () => void; onSendMessage: () => void; onDeleteMessage: (msgId: string) => void; + onEditMessage: (msgId: string, body: string) => void; + onToggleReaction: (msgId: string, emoji: string) => void; onShowMenu: (e: MouseEvent, items: ContextMenuItem[]) => void; } @@ -19,14 +25,22 @@ messages, user, err, + hasOlderMessages, + isLoadingOlder, fMsg = $bindable(), + replyTo = $bindable(), + onLoadOlderMessages, onSendMessage, onDeleteMessage, + onEditMessage, + onToggleReaction, onShowMenu, }: Props = $props(); let msgEl: HTMLElement; let inputEl: HTMLTextAreaElement; + let editingId = $state(null); + let editBody = $state(''); function scrollBottom() { tick().then(() => { if (msgEl) msgEl.scrollTop = msgEl.scrollHeight; }); @@ -42,11 +56,34 @@ if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); onSendMessage(); } } + function roomLabel(room: Room | null): string { + if (!room) return 'select a room'; + if (room.kind === 'direct') return room.other_user?.username ?? room.name ?? 'direct message'; + return room.name ?? 'untitled'; + } + function isGrouped(i: number): boolean { if (i === 0) return false; + if (messages[i].deleted || messages[i - 1].deleted) return false; return full(messages[i].author) === full(messages[i - 1].author); } + function beginEdit(msg: Message) { + editingId = full(msg.id); + editBody = msg.body; + } + + function submitEdit(msg: Message) { + if (!editBody.trim()) return; + onEditMessage(full(msg.id), editBody.trim()); + editingId = null; + editBody = ''; + } + + function quickReact(msg: Message) { + onToggleReaction(full(msg.id), '+1'); + } + // Scroll to bottom when messages change $effect(() => { messages.length; // track length @@ -63,8 +100,8 @@
- # - {activeRoom?.name ?? 'select a room'} + {activeRoom?.kind === 'direct' ? '@' : '#'} + {roomLabel(activeRoom)} {#if err}{err}{/if}
@@ -81,15 +118,24 @@

no messages yet — say hello

{:else} + {#if hasOlderMessages} + + {/if} {#each messages as msg, i (full(msg.id))}
{ const items: ContextMenuItem[] = [ { label: 'Copy message', action: () => navigator.clipboard.writeText(msg.body) }, + { label: 'Reply', action: () => replyTo = msg }, + { label: 'React +1', action: () => onToggleReaction(full(msg.id), '+1') }, ]; - if (user && full(msg.author) === full(user.id)) { + if (user && full(msg.author) === full(user.id) && !msg.deleted) { + items.push({ label: 'Edit message', action: () => beginEdit(msg) }); items.push({ label: 'Delete message', action: () => onDeleteMessage(full(msg.id)) }); } onShowMenu(e, items); @@ -99,26 +145,70 @@
{ e.stopPropagation(); onShowMenu(e, [ { label: 'Copy username', action: () => navigator.clipboard.writeText(msg.author_username ?? sid(msg.author)) }, { label: 'Copy user ID', action: () => navigator.clipboard.writeText(sid(msg.author)) }, ]); }} >{msg.author_username ?? sid(msg.author)} {fmt(msg.created)} + {#if msg.updated}edited{/if} +
+ {/if} + {#if msg.reply_to} +
replying to {sid(msg.reply_to)}
+ {/if} + {#if !msg.deleted} +
+ + + {#if user && full(msg.author) === full(user.id)} + + {/if} +
+ {/if} + {#if msg.deleted} +

message deleted

+ {:else if editingId === full(msg.id)} +
+ + + +
+ {:else} +

{msg.body}

+ {/if} + {#if msg.reactions?.length} +
+ {#each msg.reactions as reaction} + + {/each}
{/if} -

{msg.body}

{/each} {/if}
+ {#if replyTo} +
+ replying to {replyTo.author_username ?? sid(replyTo.author)} + +
+ {/if}