diff --git a/docs/EVOLUCAO_FASE_4_PLANO.md b/docs/EVOLUCAO_FASE_4_PLANO.md index 5eaec31..bed07e0 100644 --- a/docs/EVOLUCAO_FASE_4_PLANO.md +++ b/docs/EVOLUCAO_FASE_4_PLANO.md @@ -136,6 +136,12 @@ navegador com servidor real cobrindo os 44 passos abaixo: - celular; - axe. -Ainda faltam: a marca de "saiu" no histórico, a cor do avatar por autor, o total de -não lidas no título da aba, o rascunho por conversa e o botão de conversa privada no -cartão de pessoa. +## Continuação (branch `feat/conversation-polish`) + +| Item | Como ficou | +| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Quem saiu | A mensagem de quem saiu da conversa ganha o selo "saiu", em texto e com contorno tracejado (forma e texto, não só cor). O nome fica no tom secundário e a autoria não muda. A chave é `@` + número de autor: quem pega o mesmo `@` depois tem outro número e não herda nem apaga a marca. Quem saiu é quem teve `user_left` enquanto você estava, mais quem escreveu no histórico e não esteve na sala desde que você entrou. Quem volta com o mesmo número perde a marca. Conversa privada não marca ninguém, porque a outra pessoa sair encerra a conversa. | +| Cor por autor | A cor vem do número de autor da conversa (1, 2, 3… percorrem a paleta em ordem), então quem entrou em seguida tem cores diferentes. É a mesma na mensagem, na lista e no cartão, e não usa o id interno. A paleta é a já aprovada no contraste. | +| Não lidas no título | O título da aba mostra "(n) …" com o total. Com a aba escondida, mensagens da conversa aberta também contam, e voltar à aba zera. As suas não contam, e trocar de conversa preserva a contagem das outras. | +| Rascunhos | Cada conversa tem o seu, só em memória. Trocar de conversa, passar pelo início ou sair da conversa aberta nunca leva texto de uma para outra. O rascunho some quando é enviado: a mensagem fica na conversa como "enviando…" e, se falhar, como "não enviada" com "Tentar de novo", então o texto nunca se perde. | +| Conversa privada pelo cartão | O botão "Conversa privada" no cartão da pessoa usa o `@` exato, não aparece no seu próprio cartão e reabre a conversa existente em vez de duplicar. Bloqueio e disponibilidade continuam decididos pelo servidor. | diff --git a/frontend/src/css/components/avatar.css b/frontend/src/css/components/avatar.css index 001b771..251ab60 100644 --- a/frontend/src/css/components/avatar.css +++ b/frontend/src/css/components/avatar.css @@ -113,3 +113,16 @@ background-color: var(--color-accent-2-soft); color: var(--color-accent-2); } + +/* "saiu": a pessoa não está mais na conversa. Contorno tracejado (forma) + além do texto; o selo só aparece quando a marca vale (atributo hidden). */ +.c-badge--departed { + border-style: dashed; + border-color: var(--color-outline-control); + background-color: transparent; + color: var(--color-text-2); +} + +.c-badge[hidden] { + display: none; +} diff --git a/frontend/src/css/components/message.css b/frontend/src/css/components/message.css index 81402d8..17bf4c5 100644 --- a/frontend/src/css/components/message.css +++ b/frontend/src/css/components/message.css @@ -294,3 +294,23 @@ font-size: var(--text-xs); color: var(--color-text-3); } + +/* Mensagem de quem saiu: o nome perde o destaque (continua legível, no tom + secundário); a autoria não muda. */ +.c-message--departed .c-identity__name { + color: var(--color-text-2); +} + +/* Enviada: ✓ discreto ao lado, sem ocupar uma linha própria. */ +.c-message__status[data-state="confirmed"] { + position: absolute; + right: var(--space-2); + bottom: var(--space-1); +} + +.c-message__sent { + display: inline-flex; + align-items: center; + color: var(--color-text-2); + font-size: var(--text-xs); +} diff --git a/frontend/src/i18n/strings.js b/frontend/src/i18n/strings.js index 6bb4a2e..4e4e4c8 100644 --- a/frontend/src/i18n/strings.js +++ b/frontend/src/i18n/strings.js @@ -65,6 +65,9 @@ export const strings = { }, delivery: { pending: "enviando…", + retrying: "reenviando… (tentativa {n})", + sent: "enviada", + returned: "Sua mensagem não foi enviada ({reason}) e voltou para o campo de texto.", failed: "não enviada", retry: "Tentar de novo", timeout: "O servidor não confirmou o recebimento.", @@ -72,6 +75,7 @@ export const strings = { }, message: { announcement: "Aviso", + departed: "saiu", spoilerShow: "Mostrar spoiler", spoilerHide: "Esconder spoiler", private: "Só você vê isto", @@ -102,6 +106,7 @@ export const strings = { openCard: "{name}: abrir cartão", }, memberCard: { + direct: "Conversa privada", roleAdmin: "Administrador", roleHost: "Anfitrião da sala", roleMember: "Participante", diff --git a/frontend/src/main.js b/frontend/src/main.js index 7f78885..1f7addc 100644 --- a/frontend/src/main.js +++ b/frontend/src/main.js @@ -1,7 +1,7 @@ // @ts-check import { SOCKET_URL, TIMING } from "./config.js"; -import { CLIENT_EVENTS, CLOSE_CODES } from "./protocol.js"; +import { CLIENT_EVENTS, CLOSE_CODES, ERROR_CODES } from "./protocol.js"; import { routeInput } from "./commands/input.js"; import { helpReply, timeReply } from "./commands/local.js"; import { createCommandSuggestions } from "./ui/commandSuggestions.js"; @@ -9,6 +9,7 @@ import { createAnnouncer } from "./a11y/announce.js"; import { format, strings } from "./i18n/strings.js"; import { createEventHandler, noticeMessage } from "./state/events.js"; import { createStore } from "./state/store.js"; +import { departedAuthors } from "./state/departed.js"; import { createTypingTracker } from "./state/typing.js"; import { createTypingSignal } from "./state/typingSignal.js"; import { changed, createRenderLoop } from "./state/renderLoop.js"; @@ -175,6 +176,52 @@ const typingSignal = createTypingSignal({ idle: TIMING.typingIdle, }); +/** + * Rascunho de cada conversa (só em memória, como todo o resto): trocar de + * conversa guarda o que estava escrito e traz o da outra. Assim o texto + * nunca "viaja" para a conversa errada. + * @type {Map} + */ +const drafts = new Map(); + +/** + * Mensagens suas a caminho: o texto fica guardado até o servidor confirmar. + * Se o servidor recusar de vez (silenciado, limite, conteúdo inválido), o + * texto volta para o rascunho da conversa certa em vez de se perder. + * @type {Map} + */ +const inFlight = new Map(); + +/** Recusas em que o servidor certamente NÃO guardou a mensagem. @type {Set} */ +const DEFINITE_REJECTIONS = new Set([ + ERROR_CODES.MUTED, + ERROR_CODES.RATE_LIMITED, + ERROR_CODES.INVALID_MESSAGE, +]); + +/** De qual conversa é o texto que está no campo agora. @type {string | null} */ +let composerOwner = null; + +/** + * Põe no campo o rascunho da conversa `id` (ou nada, fora de conversa), + * guardando antes o da conversa dona do texto atual — se ela ainda existe. + * Chamado na troca por clique (na hora) e a cada desenho (para trocas que + * vêm do servidor, como sair ou ser removido da conversa aberta). + * @param {string | null} id + */ +const syncDraft = (id) => { + if (id === composerOwner) return; + if (composerOwner) { + const owner = composerOwner; + const alive = store.getState().conversations.some((e) => e.conversationId === owner); + const text = composer.getValue(); + if (alive && text) drafts.set(owner, text); + else drafts.delete(owner); + } + composer.restore(id ? (drafts.get(id) ?? "") : ""); + composerOwner = id; +}; + /** * Abre uma conversa da lista. A digitação em curso termina na conversa * anterior, e quem estava "digitando" lá some da tela. @@ -188,7 +235,7 @@ const openConversation = (conversationId) => { typingSignal.stop(); typingTracker.clear(); memberCard.close({ restoreFocus: false }); - store.actions.openConversation(conversationId); + if (store.actions.openConversation(conversationId)) syncDraft(conversationId); }; /** Volta ao início; as conversas continuam na lista, recebendo mensagens. */ @@ -196,6 +243,7 @@ const goHome = () => { typingSignal.stop(); typingTracker.clear(); memberCard.close({ restoreFocus: false }); + syncDraft(null); store.actions.goHome(); }; @@ -249,6 +297,8 @@ const sendChat = (content) => { const me = store.getState().me; if (!me) return; const clientMsgId = crypto.randomUUID(); + const conversationId = store.getState().room?.conversationId; + if (conversationId) inFlight.set(clientMsgId, { conversationId, text: content }); const sent = transport.send(CLIENT_EVENTS.CHAT_MESSAGE, inRoom({ content, clientMsgId })); store.actions.addMessage({ id: `local:${clientMsgId}`, @@ -381,6 +431,10 @@ const memberCard = createMemberCard({ }, confirm: (options) => dialog.confirm(options), notify: (text, kind) => toasts.show(text, kind), + openDirect: (username) => { + layout.closeDrawer(); + requestDm(username); + }, }); const roomHeader = createRoomHeader(); @@ -446,6 +500,9 @@ const endParticipation = ({ announce = strings.logout.done, notice } = {}) => { roomRequest = null; pendingDm = null; closingByMe.clear(); + drafts.clear(); + inFlight.clear(); + composerOwner = null; home.clear(); history.replaceState(null, "", location.pathname + location.search); if (notice) toasts.show(notice, "error"); @@ -693,6 +750,28 @@ handleEvent = createEventHandler({ : format(strings.conversations.dmClosedByPeer, { name }); toasts.show(text); }, + onOwnConfirmed: (clientMsgId) => { + inFlight.delete(clientMsgId); + }, + onSendRejected: (clientMsgId, code, reason) => { + const flight = inFlight.get(clientMsgId); + if (!flight || !DEFINITE_REJECTIONS.has(code)) return; + const state = store.getState(); + const alive = state.conversations.some( + (entry) => entry.conversationId === flight.conversationId, + ); + if (!alive) return; + const open = composerOwner === flight.conversationId; + const current = open ? composer.getValue() : (drafts.get(flight.conversationId) ?? ""); + // Só devolve se o rascunho daquela conversa estiver vazio: nunca + // apaga o que a pessoa já começou a escrever depois. + if (current.trim()) return; + inFlight.delete(clientMsgId); + store.actions.discardFailed(clientMsgId); + if (open) composer.restore(flight.text); + else drafts.set(flight.conversationId, flight.text); + announcer.say(format(strings.delivery.returned, { reason }), { force: true }); + }, onDmRefused: (_code, message) => { pendingDm = null; if (store.getState().screen === "home") home.settle(message); @@ -726,6 +805,9 @@ handleEvent = createEventHandler({ }, }); +/** Título da aba sem a contagem de não lidas. */ +const baseTitle = document.title; + /** @type {import("./state/store.js").State["screen"]} */ let lastScreen = "entry"; /** @type {import("./state/store.js").State["link"]} */ @@ -787,6 +869,11 @@ const render = (state, previous) => { } } } + if (changed(state, previous, ["conversations"])) { + // Total de não lidas no título da aba: "(3) web-chat · …". + const total = state.conversations.reduce((sum, entry) => sum + entry.unread, 0); + document.title = total > 0 ? `(${total > 99 ? "99+" : total}) ${baseTitle}` : baseTitle; + } if (changed(state, previous, ["me", "conversations"])) { home.render(state.me, state.conversations.length); } @@ -814,7 +901,13 @@ const render = (state, previous) => { ); } if (changed(state, previous, ["typing"])) typing.render(state.typing); + if (changed(state, previous, ["screen", "room"])) { + syncDraft(inRoom ? (state.room?.conversationId ?? null) : null); + } if (changed(state, previous, ["messages"])) messageList.render(state.messages); + if (changed(state, previous, ["messages", "authorsSeen", "authorsLeft", "room"])) { + messageList.setDeparted(departedAuthors(state)); + } if (changed(state, previous, ["people", "me", "link"])) { people.render(state.people, state.me?.id ?? null, state.link === "online"); } @@ -860,6 +953,13 @@ const render = (state, previous) => { }; const renderLoop = createRenderLoop({ getState: () => store.getState(), render }); + +// Aba escondida: mensagens na conversa aberta contam como não lidas até a +// pessoa voltar a ela. +document.addEventListener("visibilitychange", () => + store.actions.setPageVisible(document.visibilityState === "visible"), +); +store.actions.setPageVisible(document.visibilityState === "visible"); store.subscribe(() => renderLoop.request()); // Estado inicial: pinta a tela de entrada sem esperar por nenhum evento. diff --git a/frontend/src/protocol.js b/frontend/src/protocol.js index 79ab3f1..70d97f0 100644 --- a/frontend/src/protocol.js +++ b/frontend/src/protocol.js @@ -123,6 +123,7 @@ export const ERROR_CODES = Object.freeze({ INVALID_USERNAME: "invalid_username", USERNAME_TAKEN: "username_taken", RATE_LIMITED: "rate_limited", + INVALID_MESSAGE: "invalid_message", MUTED: "muted", INVALID_ROOM_CODE: "invalid_room_code", ROOM_NOT_FOUND: "room_not_found", diff --git a/frontend/src/state/departed.js b/frontend/src/state/departed.js new file mode 100644 index 0000000..28e7e4f --- /dev/null +++ b/frontend/src/state/departed.js @@ -0,0 +1,25 @@ +// @ts-check + +import { authorKey } from "./store.js"; + +/** + * Quem saiu da conversa aberta, pela chave de autor (@ + número): quem + * saiu enquanto você estava, mais quem escreveu no histórico e não está nem + * esteve na sala desde que você entrou. Numa privada, a outra pessoa sair + * encerra a conversa — não há o que marcar. + * @param {Pick} state + * @returns {Set} + */ +export const departedAuthors = (state) => { + if (state.room?.kind === "dm") return new Set(); + const gone = new Set(state.authorsLeft); + const seen = new Set(state.authorsSeen); + // Lista de pessoas ainda não chegou: não dá para afirmar quem saiu. + if (seen.size === 0) return gone; + for (const message of state.messages) { + if (message.kind !== "chat" || message.own) continue; + const key = authorKey(message.username, message.author); + if (key && !seen.has(key)) gone.add(key); + } + return gone; +}; diff --git a/frontend/src/state/events.js b/frontend/src/state/events.js index 83d1333..eab1484 100644 --- a/frontend/src/state/events.js +++ b/frontend/src/state/events.js @@ -2,6 +2,7 @@ import { format, strings } from "../i18n/strings.js"; import { ERROR_CODES, MESSAGE_FORMATS, MESSAGE_KINDS, SERVER_EVENTS, TONES } from "../protocol.js"; +import { authorKey } from "./store.js"; /** * Tradutor de eventos: recebe um fato já decodificado e o transforma em @@ -184,6 +185,8 @@ export const noticeMessage = ({ tone, text: content, title, lines }) => { * onLookup?: (requestId: string | null, user: {name: string, username: string} | null) => void, * onBlockList?: (blocked: {name: string, username: string}[]) => void, * onConversationMessage?: (conversationId: string, message: Message) => void, + * onOwnConfirmed?: (clientMsgId: string) => void, + * onSendRejected?: (clientMsgId: string, code: string, reason: string) => void, * onLoginRejected?: (message: string, field: "name" | "username") => void, * onCommandResult?: (requestId: string | null, result: {tone: string, text: string, title?: string, lines?: string[], code?: string, data?: Record}) => void, * }} deps @@ -204,6 +207,8 @@ export const createEventHandler = ({ onLookup = () => {}, onBlockList = () => {}, onConversationMessage = () => {}, + onOwnConfirmed = () => {}, + onSendRejected = () => {}, onLoginRejected = () => {}, onCommandResult = () => {}, }) => { @@ -383,6 +388,7 @@ export const createEventHandler = ({ // chega, mesmo que o sinal de parada se perca no caminho. if (active) typingTracker.set(message.userId, message.userName, false); store.actions.addMessage(message, scope); + if (message.own && message.clientMsgId) onOwnConfirmed(message.clientMsgId); if (!message.own) { notifier.show(message.userName, message.content); if (scope !== null) onConversationMessage(scope, message); @@ -398,6 +404,11 @@ export const createEventHandler = ({ /** @returns {item is Message} */ (item) => item !== null, ); + // Mensagem sua que voltou no histórico (ex.: depois de uma + // queda): o servidor recebeu — o rascunho em trânsito some. + for (const item of messages) { + if (item.own && item.clientMsgId) onOwnConfirmed(item.clientMsgId); + } const countUnread = scope !== null && freshIncoming.delete(scope); store.actions.mergeHistory(messages, scope, { countUnread }); break; @@ -410,6 +421,7 @@ export const createEventHandler = ({ id: typeof person?.username === "string" ? person.username : "", name: String(person?.name ?? ""), username: typeof person?.username === "string" ? person.username : "", + author: authorNumber(person?.author), status: person?.status === "away" ? "away" : "online", role: person?.role === "admin" @@ -440,6 +452,8 @@ export const createEventHandler = ({ } case SERVER_EVENTS.USER_JOINED: { + const joinedKey = authorKey(payload?.username, authorNumber(payload?.author)); + if (joinedKey) store.actions.setAuthorPresence(joinedKey, true, scope); store.actions.addMessage( systemMessage( format(strings.system.joined, { name: String(payload?.userName ?? "") }), @@ -456,6 +470,10 @@ export const createEventHandler = ({ if (active && typeof payload?.username === "string") { typingTracker.remove?.(payload.username); } + // Quem saiu fica marcado no histórico (pela chave de autor: + // outra pessoa com o mesmo @ depois não herda a marca). + const leftKey = authorKey(payload?.username, authorNumber(payload?.author)); + if (leftKey) store.actions.setAuthorPresence(leftKey, false, scope); // Remoção por administrador já gera um `notice` próprio. if (payload?.reason === "removed") break; store.actions.addMessage( @@ -572,6 +590,7 @@ export const createEventHandler = ({ // Recusa de uma mensagem específica: ela fica marcada como não // enviada, com a opção de tentar de novo. const failedOne = ref !== null && store.actions.failMessage(ref, message); + if (failedOne && ref !== null && code !== null) onSendRejected(ref, code, message); // Mensagem marcada como falha já é anunciada pela lista; o // toast, nesse caso, é só reforço visual (sem anúncio duplo). if (code === ERROR_CODES.RATE_LIMITED) { diff --git a/frontend/src/state/store.js b/frontend/src/state/store.js index ccf6713..c33af39 100644 --- a/frontend/src/state/store.js +++ b/frontend/src/state/store.js @@ -18,8 +18,20 @@ * @property {"online" | "away"} [status] * @property {string} [statusText] * @property {"member" | "admin" | "host"} [role] papel NA SALA (admin é global) + * @property {number | null} [author] número de autor NESTA conversa (dado pelo servidor) */ +/** + * Chave de quem escreveu, dentro de uma conversa: o @ mais o número de autor. + * Distingue duas pessoas que usaram o mesmo @ em momentos diferentes, sem + * nada do id interno. + * @param {string | undefined} username + * @param {number | null | undefined} author + * @returns {string | null} + */ +export const authorKey = (username, author) => + username && typeof author === "number" ? `${username}#${author}` : null; + /** * A outra pessoa de uma conversa privada. * @typedef {object} Peer @@ -74,6 +86,7 @@ * @property {string | null} [clientMsgId] * @property {"confirmed" | "pending" | "failed"} delivery * @property {number | null} [sentAt] quando saiu pela rede (pendentes) + * @property {number} [attempt] tentativa de envio em curso (1 = primeira; 2+ = reenvio) * @property {string} [failReason] * @property {string} [tone] notice/system: info, success, warning, error, result, admin * @property {string} [title] @@ -112,6 +125,9 @@ * @property {number | null} closeCode Fechamento definitivo (ex.: 4003 removido). * @property {CommandInfo[]} catalog * @property {number | null} historyVersion + * @property {string[]} authorsSeen quem esteve na conversa enquanto você estava (chaves de autor) + * @property {string[]} authorsLeft quem saiu da conversa (chaves de autor) + * @property {boolean} pageVisible a aba está à vista (mensagem na conversa aberta com a aba escondida conta como não lida) * @property {RoomInfo | null} room a conversa aberta agora * @property {ConversationEntry[]} conversations todas as conversas desta participação */ @@ -137,13 +153,16 @@ const initialState = () => ({ closeCode: null, catalog: [], historyVersion: null, + authorsSeen: [], + authorsLeft: [], + pageVisible: true, room: null, conversations: [], }); /** * O que é de UMA conversa e precisa sobreviver enquanto outra está aberta. - * @typedef {{messages: Message[], people: Person[], historyVersion: number | null}} View + * @typedef {{messages: Message[], people: Person[], historyVersion: number | null, authorsSeen: string[], authorsLeft: string[]}} View */ /** @@ -158,7 +177,23 @@ const summaryOf = (entry) => { }; /** @returns {View} */ -const emptyView = () => ({ messages: [], people: [], historyVersion: null }); +const emptyView = () => ({ + messages: [], + people: [], + historyVersion: null, + authorsSeen: [], + authorsLeft: [], +}); + +/** Os campos da vista que vivem no estado quando a conversa está aberta. */ +const CLEAR_VIEW = Object.freeze({ + messages: [], + people: [], + typing: [], + historyVersion: null, + authorsSeen: [], + authorsLeft: [], +}); /** Mesma conversa, mesmos dados visíveis? @param {RoomInfo} a @param {RoomInfo} b */ const sameSummary = (a, b) => @@ -268,6 +303,8 @@ export const createStore = () => { messages: state.messages, people: state.people, historyVersion: state.historyVersion, + authorsSeen: state.authorsSeen, + authorsLeft: state.authorsLeft, }); }; @@ -393,6 +430,29 @@ export const createStore = () => { return true; }, + /** + * A aba ficou à vista ou escondida. Ao voltar, a conversa aberta + * é a que está sendo lida: as não lidas dela zeram. + * @param {boolean} visible + */ + setPageVisible(visible) { + if (state.pageVisible === visible) return; + const openId = + visible && state.screen === "room" ? state.room?.conversationId : null; + patch({ + pageVisible: visible, + ...(openId + ? { + conversations: state.conversations.map((entry) => + entry.conversationId === openId && entry.unread + ? { ...entry, unread: 0 } + : entry, + ), + } + : {}), + }); + }, + /** * Tela de início: nenhuma conversa aberta (todas continuam na * lista, recebendo mensagens). @@ -400,14 +460,7 @@ export const createStore = () => { goHome() { if (state.screen === "entry") return; stashActive(); - patch({ - screen: "home", - room: null, - messages: [], - people: [], - typing: [], - historyVersion: null, - }); + patch({ screen: "home", room: null, ...CLEAR_VIEW }); }, /** @@ -447,10 +500,7 @@ export const createStore = () => { conversations, screen: state.screen === "entry" ? "entry" : "home", room: null, - messages: [], - people: [], - typing: [], - historyVersion: null, + ...CLEAR_VIEW, }); return null; }, @@ -462,14 +512,7 @@ export const createStore = () => { forgetRoom() { buffers.clear(); if (state.room === null && state.conversations.length === 0) return; - patch({ - room: null, - conversations: [], - messages: [], - people: [], - typing: [], - historyVersion: null, - }); + patch({ room: null, conversations: [], ...CLEAR_VIEW }); }, /** Sala e sessão aceitas pelo servidor: agora sim, a conversa. */ @@ -535,7 +578,8 @@ export const createStore = () => { leaveRoom() { hidden.clear(); buffers.clear(); - patch({ ...initialState() }); + // A aba continua à vista ou escondida: isso não é da participação. + patch({ ...initialState(), pageVisible: state.pageVisible }); }, /** @@ -560,6 +604,11 @@ export const createStore = () => { if (confirm(message)) return; if (state.messages.some((existing) => existing.id === message.id)) return; patch({ messages: [...state.messages, message] }); + // Aba escondida: a conversa aberta não está sendo lida. + const openId = state.room?.conversationId; + if (!state.pageVisible && openId && message.kind === "chat" && !message.own) { + bumpUnread(openId, 1); + } }, /** @@ -648,6 +697,34 @@ export const createStore = () => { ); }, + /** + * Tira da tela uma mensagem SUA que o servidor recusou de vez (o + * texto volta para o rascunho). Só falhas: uma confirmada nunca + * some, e uma pendente ainda pode chegar. + * @param {string} clientMsgId + * @returns {boolean} + */ + discardFailed(clientMsgId) { + /** @param {Message} m */ + const keep = (m) => + !(m.own && m.clientMsgId === clientMsgId && m.delivery === "failed"); + let removed = false; + for (const [id, view] of buffers) { + const messages = view.messages.filter(keep); + if (messages.length !== view.messages.length) { + removed = true; + buffers.set(id, { ...view, messages }); + } + } + const messages = state.messages.filter(keep); + if (messages.length !== state.messages.length) { + patch({ messages }); + return true; + } + if (removed) notify(); + return removed; + }, + /** * Reenvio: a mensagem volta a "enviando". * @param {string} clientMsgId @@ -662,6 +739,7 @@ export const createStore = () => { delivery: "pending", sentAt, failReason: undefined, + attempt: (message.attempt ?? 1) + 1, }), ); }, @@ -699,13 +777,56 @@ export const createStore = () => { * @param {string | null} [conversationId] outra conversa que não a aberta */ setPeople(people, conversationId = null) { + /** @param {string[]} seen @param {string[]} left */ + const track = (seen, left) => { + const keys = people + .map((person) => authorKey(person.username, person.author)) + .filter(/** @returns {key is string} */ (key) => key !== null); + return { + authorsSeen: [...new Set([...seen, ...keys])], + authorsLeft: left.filter((key) => !keys.includes(key)), + }; + }; if (!isActive(conversationId)) { const id = /** @type {string} */ (conversationId); const view = bufferOf(id); - if (view) buffers.set(id, { ...view, people }); + if (view) { + buffers.set(id, { + ...view, + people, + ...track(view.authorsSeen, view.authorsLeft), + }); + } + return; + } + patch({ people, ...track(state.authorsSeen, state.authorsLeft) }); + }, + + /** + * Alguém entrou (ou voltou) ou saiu de uma conversa: quem saiu + * aparece marcado no histórico; quem voltou, não mais. + * @param {string} key chave de autor (@ + número) + * @param {boolean} present + * @param {string | null} [conversationId] + */ + setAuthorPresence(key, present, conversationId = null) { + /** @param {string[]} seen @param {string[]} left */ + const next = (seen, left) => ({ + authorsSeen: seen.includes(key) ? seen : [...seen, key], + authorsLeft: present + ? left.filter((item) => item !== key) + : left.includes(key) + ? left + : [...left, key], + }); + if (!isActive(conversationId)) { + const id = /** @type {string} */ (conversationId); + const view = bufferOf(id); + if (view) + buffers.set(id, { ...view, ...next(view.authorsSeen, view.authorsLeft) }); return; } - patch({ people }); + patch(next(state.authorsSeen, state.authorsLeft)); }, /** diff --git a/frontend/src/ui/composer.js b/frontend/src/ui/composer.js index 92510b1..b0e987a 100644 --- a/frontend/src/ui/composer.js +++ b/frontend/src/ui/composer.js @@ -75,6 +75,19 @@ export const createComposer = ({ input.focus(); }, + /** O texto no campo agora (rascunho da conversa aberta). */ + getValue: () => input.value, + + /** + * Troca o texto sem mover o foco nem abrir sugestões — usado ao + * trocar de conversa (cada uma tem o seu rascunho). + * @param {string} text + */ + restore(text) { + input.value = text; + onInput("", 0); + }, + /** * Substitui o texto do campo (autocomplete) e põe o cursor no fim. * @param {string} text diff --git a/frontend/src/ui/identity.js b/frontend/src/ui/identity.js index 2720364..6ecd138 100644 --- a/frontend/src/ui/identity.js +++ b/frontend/src/ui/identity.js @@ -20,6 +20,16 @@ export const hueFor = (id) => { return (hash % SENDER_HUES) + 1; }; +/** + * Cor pelo número de autor da conversa: 1, 2, 3… percorrem a paleta em + * ordem, então quem entrou em seguida nunca tem a mesma cor (até a paleta + * dar a volta). Vem do servidor, vale só naquela conversa e não tem nada + * do id interno. + * @param {number} author + * @returns {number} de 1 a SENDER_HUES + */ +export const hueForAuthor = (author) => ((Math.max(1, Math.trunc(author)) - 1) % SENDER_HUES) + 1; + /** * Iniciais para o monograma: no máximo duas letras. * @param {string} name @@ -36,7 +46,8 @@ export const initialsFor = (name) => { /** * Bloco de identidade: avatar (iniciais sobre a cor da pessoa) + nome. * - * A cor sai do id e é a mesma em toda tela. Ela nunca é o único sinal: o + * A cor sai do número de autor da conversa (quando há) ou do arroba, e é a + * mesma em toda tela. Ela nunca é o único sinal: o * nome está sempre escrito, e quem é você recebe o selo "você" em texto * (ver message.js e people.js), não uma cor diferente. * @@ -48,6 +59,7 @@ export const initialsFor = (name) => { * withMonogram?: boolean, * size?: "md" | "lg" | "xl", * presence?: "online" | "away" | null, + * author?: number | null, * }} person * @returns {HTMLElement} */ @@ -59,8 +71,10 @@ export const renderIdentity = ({ withMonogram = true, size = "md", presence = null, + author = null, }) => { - const classes = ["c-identity", `c-identity--sender-${hueFor(id)}`]; + const hue = typeof author === "number" ? hueForAuthor(author) : hueFor(id); + const classes = ["c-identity", `c-identity--sender-${hue}`]; if (own) classes.push("c-identity--self"); if (size !== "md") classes.push(`c-identity--${size}`); const root = el("span", { class: classes.join(" ") }); diff --git a/frontend/src/ui/memberCard.js b/frontend/src/ui/memberCard.js index b748b5b..e7f7fc6 100644 --- a/frontend/src/ui/memberCard.js +++ b/frontend/src/ui/memberCard.js @@ -30,9 +30,17 @@ import { icon } from "./icons.js"; * prefill: (text: string) => void, * confirm: (options: {title: string, body: string, confirmLabel: string}) => Promise, * notify: (text: string, kind?: "info" | "error") => void, + * openDirect?: (username: string) => void, * }} deps */ -export const createMemberCard = ({ getContext, runCommand, prefill, confirm, notify }) => { +export const createMemberCard = ({ + getContext, + runCommand, + prefill, + confirm, + notify, + openDirect, +}) => { const card = /** @type {HTMLElement} */ (must(".c-member-card")); const avatar = /** @type {HTMLElement} */ (must(".c-member-card__avatar", card)); const name = /** @type {HTMLElement} */ (must(".c-member-card__name", card)); @@ -103,6 +111,21 @@ export const createMemberCard = ({ getContext, runCommand, prefill, confirm, not }, ]; + // Conversa privada pelo @ exato (nunca consigo mesmo). Bloqueio e + // disponibilidade são decididos pelo servidor; se já existe uma + // conversa com a pessoa, ela é reaberta, não duplicada. + if (!own && openDirect && person.username) { + const username = person.username; + list.unshift({ + label: strings.memberCard.direct, + iconName: "at", + run: () => { + close({ restoreFocus: false }); + openDirect(username); + }, + }); + } + if (own) { list.push( { @@ -214,6 +237,7 @@ export const createMemberCard = ({ getContext, runCommand, prefill, confirm, not avatar.replaceChildren( renderIdentity({ id: person.id, + author: person.author ?? null, name: person.name, own, withName: false, diff --git a/frontend/src/ui/message.js b/frontend/src/ui/message.js index 5313101..584452b 100644 --- a/frontend/src/ui/message.js +++ b/frontend/src/ui/message.js @@ -1,9 +1,10 @@ // @ts-check -import { strings } from "../i18n/strings.js"; +import { format, strings } from "../i18n/strings.js"; import { el } from "./dom.js"; import { icon } from "./icons.js"; import { badge, renderIdentity } from "./identity.js"; +import { authorKey } from "../state/store.js"; /** * Renderização de uma entrada da transcrição. Só `textContent` e @@ -108,8 +109,15 @@ const renderContent = (message) => { const fillStatus = (slot, message, handlers) => { slot.replaceChildren(); if (message.delivery === "pending") { + const attempt = message.attempt ?? 1; slot.appendChild( - el("span", { class: "c-message__status-text", text: strings.delivery.pending }), + el("span", { + class: "c-message__status-text", + text: + attempt > 1 + ? format(strings.delivery.retrying, { n: attempt }) + : strings.delivery.pending, + }), ); } else if (message.delivery === "failed") { slot.appendChild( @@ -128,7 +136,16 @@ const fillStatus = (slot, message, handlers) => { retry.addEventListener("click", () => handlers.onRetry?.(message)); slot.appendChild(retry); } - slot.hidden = message.delivery === "confirmed"; + // Enviada: sua mensagem confirmada pelo servidor ganha um ✓ discreto, + // com o estado em texto para leitor de tela. + if (message.delivery === "confirmed" && message.own && message.kind === "chat") { + const mark = el("span", { class: "c-message__sent" }); + mark.appendChild(icon("check")); + mark.appendChild(el("span", { class: "sr-only", text: strings.delivery.sent })); + slot.appendChild(mark); + } + slot.hidden = message.delivery === "confirmed" && !message.own; + slot.dataset.state = message.delivery; }; /** @@ -215,6 +232,9 @@ export const renderMessage = (message, handlers = {}, { compact = false } = {}) if (message.own) item.classList.add("c-message--self"); item.dataset.delivery = message.delivery; + // Chave de autor (@ + número na conversa): a lista marca "saiu" por ela. + const key = message.own ? null : authorKey(message.username, message.author); + if (key) item.dataset.authorKey = key; const variant = message.variant ?? "text"; const isAction = variant === "action" || variant === "roll"; const isCompact = compact && !isAction && variant !== "announcement"; @@ -230,6 +250,7 @@ export const renderMessage = (message, handlers = {}, { compact = false } = {}) id: message.userId, name: message.userName, own: message.own, + author: message.author ?? null, withName: false, }), ); @@ -264,6 +285,7 @@ export const renderMessage = (message, handlers = {}, { compact = false } = {}) id: message.userId, name: message.userName, own: message.own, + author: message.author ?? null, withMonogram: false, }), ); @@ -273,6 +295,12 @@ export const renderMessage = (message, handlers = {}, { compact = false } = {}) ); } if (message.own) head.appendChild(badge(strings.room.youBadge)); + if (key) { + // Escondido até a pessoa sair; em texto, não só no tom. + const departed = badge(strings.message.departed, "departed"); + departed.hidden = true; + head.appendChild(departed); + } const time = timeElement(message.timestamp); if (time) head.appendChild(time); body.appendChild(head); diff --git a/frontend/src/ui/messageList.js b/frontend/src/ui/messageList.js index 544574a..5b3ef40 100644 --- a/frontend/src/ui/messageList.js +++ b/frontend/src/ui/messageList.js @@ -54,6 +54,24 @@ export const createMessageList = (handlers = {}) => { root.scrollTop = root.scrollHeight; }; + /** + * Quem saiu da conversa (chaves de autor). Mensagens dessas pessoas + * ganham a marca "saiu" — a autoria continua a mesma, só fica claro que + * a pessoa não está mais lá. + * @type {Set} + */ + let departed = new Set(); + + /** @param {HTMLElement} element */ + const markDeparted = (element) => { + const key = element.dataset.authorKey; + if (!key) return; + const gone = departed.has(key); + element.classList.toggle("c-message--departed", gone); + const mark = element.querySelector(".c-badge--departed"); + if (mark instanceof HTMLElement) mark.hidden = !gone; + }; + return { /** * @param {Message[]} messages @@ -85,6 +103,7 @@ export const createMessageList = (handlers = {}) => { const element = renderMessage(message, handlers, { compact: continuesGroup(messages[index - 1], message), }); + markDeparted(element); items.appendChild(element); painted.set(message.key, { element, message }); added = true; @@ -93,6 +112,18 @@ export const createMessageList = (handlers = {}) => { if (added && stick) scrollToEnd(); }, + /** + * Atualiza a marca "saiu" sem redesenhar (mudar o item faria a + * região `role="log"` anunciá-lo de novo). + * @param {Set} keys + */ + setDeparted(keys) { + departed = keys; + for (const element of items.querySelectorAll("[data-author-key]")) { + if (element instanceof HTMLElement) markDeparted(element); + } + }, + scrollToEnd, }; }; diff --git a/frontend/src/ui/people.js b/frontend/src/ui/people.js index a6fa599..0e16366 100644 --- a/frontend/src/ui/people.js +++ b/frontend/src/ui/people.js @@ -54,6 +54,7 @@ export const createPeople = ({ onSelect }) => { button.appendChild( renderIdentity({ id: person.id, + author: person.author ?? null, name: person.name, own, withName: false, diff --git a/frontend/test/events.test.js b/frontend/test/events.test.js index 59342f5..55f5114 100644 --- a/frontend/test/events.test.js +++ b/frontend/test/events.test.js @@ -205,9 +205,16 @@ describe("presença e digitação", () => { payload: [{ username: "ana", name: "Ana", id: "x" }, null, { username: 2 }], }); assert.deepEqual(store.getState().people, [ - { id: "ana", name: "Ana", username: "ana", status: "online", role: "member" }, - { id: "", name: "", username: "", status: "online", role: "member" }, - { id: "", name: "", username: "", status: "online", role: "member" }, + { + id: "ana", + name: "Ana", + username: "ana", + author: null, + status: "online", + role: "member", + }, + { id: "", name: "", username: "", author: null, status: "online", role: "member" }, + { id: "", name: "", username: "", author: null, status: "online", role: "member" }, ]); handle({ type: "user_list", payload: "lixo" }); assert.deepEqual(store.getState().people, []); diff --git a/frontend/test/polish.test.js b/frontend/test/polish.test.js new file mode 100644 index 0000000..989c7ac --- /dev/null +++ b/frontend/test/polish.test.js @@ -0,0 +1,358 @@ +// Fase 4, continuação: quem saiu, cor por autor, não lidas com a aba +// escondida. (Rascunhos e conversa privada pelo cartão são de main.js e +// têm teste no navegador.) + +import { test, describe } from "node:test"; +import assert from "node:assert/strict"; +import { createEventHandler } from "../src/state/events.js"; +import { createStore, authorKey } from "../src/state/store.js"; +import { departedAuthors } from "../src/state/departed.js"; +import { hueForAuthor, hueFor } from "../src/ui/identity.js"; + +const A = "r_salaA0000001"; +const B = "r_salaB0000002"; + +const setup = () => { + const store = createStore(); + const handle = createEventHandler({ + store, + toasts: { show: () => {} }, + notifier: { show: () => {} }, + typingTracker: { set: () => {}, remove: () => {} }, + }); + store.actions.startJoin({ id: "eu", name: "Eu", username: "eu" }); + handle({ type: "session", payload: { username: "eu", name: "Eu", resumeToken: "t" } }); + const room = (id, author = 1) => + handle({ + type: "room_joined", + conversationId: id, + payload: { code: "abc-defg-hij", name: id, role: "member", author, historyVersion: 0 }, + }); + const list = (id, people) => + handle({ + type: "user_list", + conversationId: id, + payload: people.map(([username, author]) => ({ name: username, username, author })), + }); + const say = (id, msgId, username, author) => + handle({ + type: "chat_message", + id: msgId, + conversationId: id, + payload: { username, userName: username, author, content: msgId }, + }); + return { store, handle, room, list, say }; +}; + +describe("quem saiu da conversa", () => { + test("chave de autor: @ mais o número; sem número não há chave", () => { + assert.equal(authorKey("bia", 2), "bia#2"); + assert.equal(authorKey("bia", null), null); + assert.equal(authorKey(undefined, 2), null); + }); + + test("quem sai fica marcado; quem volta (mesmo número) deixa de estar", () => { + const { store, handle, room, list, say } = setup(); + room(A); + list(A, [ + ["eu", 1], + ["bia", 2], + ]); + say(A, "m1", "bia", 2); + assert.deepEqual([...departedAuthors(store.getState())], []); + handle({ + type: "user_left", + conversationId: A, + payload: { userName: "Bia", username: "bia", author: 2 }, + }); + assert.deepEqual([...departedAuthors(store.getState())], ["bia#2"]); + handle({ + type: "user_joined", + conversationId: A, + payload: { userName: "Bia", username: "bia", author: 2 }, + }); + assert.deepEqual([...departedAuthors(store.getState())], []); + }); + + test("@ reaproveitado: a pessoa nova não tira a marca da antiga", () => { + const { store, handle, room, list, say } = setup(); + room(A); + list(A, [ + ["eu", 1], + ["bia", 2], + ]); + say(A, "m1", "bia", 2); + handle({ type: "user_left", conversationId: A, payload: { username: "bia", author: 2 } }); + handle({ type: "user_joined", conversationId: A, payload: { username: "bia", author: 4 } }); + list(A, [ + ["eu", 1], + ["bia", 4], + ]); + say(A, "m2", "bia", 4); + assert.deepEqual([...departedAuthors(store.getState())], ["bia#2"]); + }); + + test("quem escreveu no histórico e não está na sala desde que você entrou saiu", () => { + const { store, handle, room, list } = setup(); + room(A, 3); + handle({ + type: "message_history", + conversationId: A, + payload: [ + { + id: "h1", + payload: { username: "ana", userName: "Ana", author: 1, content: "x" }, + }, + { + id: "h2", + payload: { username: "bia", userName: "Bia", author: 2, content: "y" }, + }, + ], + }); + assert.deepEqual( + [...departedAuthors(store.getState())], + [], + "sem lista ainda, ninguém é marcado", + ); + list(A, [ + ["bia", 2], + ["eu", 3], + ]); + assert.deepEqual([...departedAuthors(store.getState())], ["ana#1"]); + }); + + test("a marca acompanha cada conversa, também quando ela não está aberta", () => { + const { store, handle, room, list, say } = setup(); + room(A); + room(B); + list(B, [ + ["eu", 1], + ["caio", 2], + ]); + say(B, "b1", "caio", 2); + handle({ type: "user_left", conversationId: B, payload: { username: "caio", author: 2 } }); + assert.deepEqual( + [...departedAuthors(store.getState())], + [], + "a aberta (A) não tem ninguém marcado", + ); + store.actions.openConversation(B); + assert.deepEqual([...departedAuthors(store.getState())], ["caio#2"]); + store.actions.openConversation(A); + store.actions.openConversation(B); + assert.deepEqual([...departedAuthors(store.getState())], ["caio#2"], "sobrevive à troca"); + }); + + test("conversa privada não marca ninguém", () => { + const state = { + room: { conversationId: "d_x", kind: "dm", name: "Bia", role: "member" }, + authorsLeft: ["bia#2"], + authorsSeen: ["bia#2"], + messages: [], + }; + assert.equal(departedAuthors(/** @type {any} */ (state)).size, 0); + }); +}); + +describe("cor por autor", () => { + test("números seguidos têm cores diferentes até a paleta dar a volta", () => { + const hues = [1, 2, 3, 4, 5, 6].map(hueForAuthor); + assert.equal(new Set(hues).size, 6); + assert.equal(hueForAuthor(7), hueForAuthor(1)); + for (const n of [0, -3, 2.7]) { + const hue = hueForAuthor(n); + assert.ok(hue >= 1 && hue <= 6, String(n)); + } + }); + + test("a cor não depende do @ (dois @ com o mesmo número, mesma cor na conversa)", () => { + assert.equal(hueForAuthor(3), hueForAuthor(3)); + assert.ok(hueFor("qualquer") >= 1 && hueFor("qualquer") <= 6, "reserva sem número"); + }); +}); + +describe("não lidas com a aba escondida", () => { + test("na conversa aberta, só contam com a aba escondida; voltar zera", () => { + const { store, room, say } = setup(); + room(A); + say(A, "m1", "bia", 2); + assert.equal(store.getState().conversations[0]?.unread, 0); + store.actions.setPageVisible(false); + say(A, "m2", "bia", 2); + say(A, "m3", "eu", 1); + assert.equal(store.getState().conversations[0]?.unread, 1, "a sua não conta"); + store.actions.setPageVisible(true); + assert.equal(store.getState().conversations[0]?.unread, 0); + }); + + test("trocar de conversa preserva as contagens das outras", () => { + const { store, room, say } = setup(); + room(A); + room(B); + say(B, "b1", "bia", 2); + say(B, "b2", "bia", 2); + store.actions.setPageVisible(false); + say(A, "a1", "ana", 2); + store.actions.setPageVisible(true); + const unread = () => + Object.fromEntries( + store.getState().conversations.map((c) => [c.conversationId, c.unread]), + ); + assert.deepEqual(unread(), { [A]: 0, [B]: 2 }); + store.actions.openConversation(B); + assert.deepEqual(unread(), { [A]: 0, [B]: 0 }); + }); + + test("sair do chat não esquece se a aba está escondida", () => { + const { store } = setup(); + store.actions.setPageVisible(false); + store.actions.leaveRoom(); + assert.equal(store.getState().pageVisible, false); + }); +}); + +describe("ciclo de envio: enviando, enviada, falha, reenvio", () => { + const pending = (clientMsgId) => ({ + id: `local:${clientMsgId}`, + key: `c:${clientMsgId}`, + kind: /** @type {const} */ ("chat"), + userId: "eu", + userName: "Eu", + username: "eu", + content: "texto", + timestamp: new Date().toISOString(), + own: true, + clientMsgId, + delivery: /** @type {const} */ ("pending"), + sentAt: 1, + }); + + const wired = () => { + const store = createStore(); + const calls = { confirmed: [], rejected: [] }; + const handle = createEventHandler({ + store, + toasts: { show: () => {} }, + notifier: { show: () => {} }, + typingTracker: { set: () => {} }, + onOwnConfirmed: (id) => calls.confirmed.push(id), + onSendRejected: (id, code) => calls.rejected.push([id, code]), + }); + store.actions.startJoin({ id: "eu", name: "Eu", username: "eu" }); + handle({ type: "session", payload: { username: "eu", name: "Eu", resumeToken: "t" } }); + handle({ + type: "room_joined", + conversationId: A, + payload: { + code: "abc-defg-hij", + name: "A", + role: "member", + author: 1, + historyVersion: 0, + }, + }); + return { store, handle, calls }; + }; + + test("confirmação do servidor avisa (o rascunho em trânsito pode ser liberado)", () => { + const { store, handle, calls } = wired(); + store.actions.addMessage(pending("c1")); + handle({ + type: "chat_message", + id: "srv-1", + conversationId: A, + payload: { + username: "eu", + userName: "Eu", + author: 1, + content: "texto", + clientMsgId: "c1", + }, + }); + assert.deepEqual(calls.confirmed, ["c1"]); + assert.equal(store.getState().messages.length, 1, "confirmação não duplica"); + assert.equal(store.getState().messages[0]?.delivery, "confirmed"); + }); + + test("confirmação que chega no histórico (depois de uma queda) também conta", () => { + const { store, handle, calls } = wired(); + store.actions.addMessage(pending("c2")); + handle({ + type: "message_history", + conversationId: A, + payload: [ + { + id: "srv-2", + payload: { + username: "eu", + userName: "Eu", + author: 1, + content: "texto", + clientMsgId: "c2", + }, + }, + ], + }); + assert.deepEqual(calls.confirmed, ["c2"]); + assert.equal(store.getState().messages.length, 1); + }); + + test("recusa com ref marca a falha e avisa com o código", () => { + const { store, handle, calls } = wired(); + store.actions.addMessage(pending("c3")); + handle({ type: "error", payload: { code: "muted", message: "silenciado", ref: "c3" } }); + assert.equal(store.getState().messages[0]?.delivery, "failed"); + assert.deepEqual(calls.rejected, [["c3", "muted"]]); + // Recusa de algo que não é sua mensagem pendente não avisa. + handle({ type: "error", payload: { code: "muted", message: "x", ref: "outra" } }); + assert.equal(calls.rejected.length, 1); + }); + + test("falha pode sair da tela (o texto volta ao rascunho); pendente e confirmada, não", () => { + const { store } = wired(); + store.actions.addMessage(pending("c4")); + assert.equal(store.actions.discardFailed("c4"), false, "pendente ainda pode chegar"); + store.actions.failMessage("c4", "silenciado"); + assert.equal(store.actions.discardFailed("c4"), true); + assert.equal(store.getState().messages.length, 0); + }); + + test("reenvio conta a tentativa e mantém o mesmo clientMsgId (sem duplicar)", () => { + const { store, handle } = wired(); + store.actions.addMessage(pending("c5")); + store.actions.failMessage("c5", "sem resposta"); + store.actions.retryMessage("c5", 2); + assert.equal(store.getState().messages[0]?.attempt, 2); + assert.equal(store.getState().messages[0]?.delivery, "pending"); + store.actions.failMessage("c5", "sem resposta"); + store.actions.retryMessage("c5", 3); + assert.equal(store.getState().messages[0]?.attempt, 3); + // O servidor devolve a original (deduplicada): uma mensagem só. + handle({ + type: "chat_message", + id: "srv-5", + conversationId: A, + payload: { + username: "eu", + userName: "Eu", + author: 1, + content: "texto", + clientMsgId: "c5", + }, + }); + handle({ + type: "chat_message", + id: "srv-5", + conversationId: A, + payload: { + username: "eu", + userName: "Eu", + author: 1, + content: "texto", + clientMsgId: "c5", + }, + }); + assert.equal(store.getState().messages.length, 1); + assert.equal(store.getState().messages[0]?.delivery, "confirmed"); + }); +});