Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions docs/EVOLUCAO_FASE_4_PLANO.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
13 changes: 13 additions & 0 deletions frontend/src/css/components/avatar.css
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
20 changes: 20 additions & 0 deletions frontend/src/css/components/message.css
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
5 changes: 5 additions & 0 deletions frontend/src/i18n/strings.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,17 @@ 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.",
announceFailed: "Sua mensagem não foi enviada: {reason}",
},
message: {
announcement: "Aviso",
departed: "saiu",
spoilerShow: "Mostrar spoiler",
spoilerHide: "Esconder spoiler",
private: "Só você vê isto",
Expand Down Expand Up @@ -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",
Expand Down
104 changes: 102 additions & 2 deletions frontend/src/main.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
// @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";
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";
Expand Down Expand Up @@ -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<string, string>}
*/
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<string, {conversationId: string, text: string}>}
*/
const inFlight = new Map();

/** Recusas em que o servidor certamente NÃO guardou a mensagem. @type {Set<string>} */
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.
Expand All @@ -188,14 +235,15 @@ 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. */
const goHome = () => {
typingSignal.stop();
typingTracker.clear();
memberCard.close({ restoreFocus: false });
syncDraft(null);
store.actions.goHome();
};

Expand Down Expand Up @@ -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}`,
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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"]} */
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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");
}
Expand Down Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions frontend/src/protocol.js
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
25 changes: 25 additions & 0 deletions frontend/src/state/departed.js
Original file line number Diff line number Diff line change
@@ -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<import("./store.js").State, "room" | "authorsLeft" | "authorsSeen" | "messages">} state
* @returns {Set<string>}
*/
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;
};
Loading
Loading