diff --git a/e2e/10-composer.mjs b/e2e/10-composer.mjs
index b9e8fee..32f100f 100644
--- a/e2e/10-composer.mjs
+++ b/e2e/10-composer.mjs
@@ -28,7 +28,8 @@ export default async ({ open, enter, createRoom, user, ok, axe, RUN }) => {
await bia.waitForSelector(`.c-message:has-text("linha um ${RUN}")`);
const received = await bia.$eval(
`.c-message:has-text("linha um ${RUN}") .c-message__text`,
- (x) => x.textContent,
+ // innerText: o texto como aparece na tela (cada quebra é um
).
+ (x) => /** @type {HTMLElement} */ (x).innerText.replace(/\s*✓?$/, "").trim(),
);
ok(
received === `linha um ${RUN}\nlinha dois\nlinha três`,
diff --git a/e2e/11-historico.mjs b/e2e/11-historico.mjs
new file mode 100644
index 0000000..1aa786b
--- /dev/null
+++ b/e2e/11-historico.mjs
@@ -0,0 +1,173 @@
+// Histórico: Markdown sem HTML, menções, separador de dia, "Novas
+// mensagens", aviso de novas ao rolar, ações da mensagem (barra, menu e
+// teclado), sugestões de @pessoa, dispensar resposta de comando e apagar
+// uma mensagem que não foi enviada.
+export default async ({ open, enter, createRoom, user, ok, axe, RUN }) => {
+ const ana = await open();
+ const anaUser = user("ana");
+ await enter(ana, "Ana Souza", anaUser);
+ const hash = await createRoom(ana, "Histórico");
+ const bia = await open({ hash });
+ const biaUser = user("bia");
+ await enter(bia, "Bia Lima", biaUser);
+ /** @param {import("playwright").Page} page @param {string} text */
+ const say = async (page, text) => {
+ await page.fill("#campo-mensagem", text);
+ await page.press("#campo-mensagem", "Enter");
+ };
+
+ // Markdown: elementos, nunca HTML.
+ await say(bia, `**forte ${RUN}** _leve_ \`código\` https://exemplo.com/a não`);
+ const md = `.c-message:has-text("forte ${RUN}")`;
+ await ana.waitForSelector(md);
+ ok(
+ (await ana.textContent(`${md} strong`))?.trim() === `forte ${RUN}`,
+ "**negrito** vira strong",
+ );
+ ok((await ana.textContent(`${md} em`))?.trim() === "leve", "_itálico_ vira em");
+ ok((await ana.textContent(`${md} code`))?.trim() === "código", "`código` vira code");
+ const rel = await ana.getAttribute(`${md} a`, "rel");
+ ok(
+ Boolean(rel?.includes("noopener") && rel.includes("noreferrer")),
+ "link com noopener e noreferrer",
+ );
+ ok(
+ (await ana.$$(`${md} b`)).length === 0 &&
+ Boolean((await ana.textContent(md))?.includes("não")),
+ "HTML digitado aparece como texto",
+ );
+ await say(bia, "```\nlinha 1\n linha 2\n```");
+ await ana.waitForSelector(".c-message__pre");
+ ok(
+ (await ana.textContent(".c-message__pre code")) === "linha 1\n linha 2",
+ "bloco de código mantém as linhas e a indentação",
+ );
+ ok(
+ await ana.$eval(".c-day-divider", (x) => x.textContent?.trim() === "Hoje"),
+ "separador de dia: Hoje",
+ );
+
+ // Menção a você: destaque e aviso em texto.
+ await say(bia, `@${anaUser} olha isso ${RUN}`);
+ const mention = `.c-message:has-text("olha isso ${RUN}")`;
+ await ana.waitForSelector(`${mention}.c-message--mention`);
+ ok(
+ Boolean((await ana.textContent(mention))?.includes("Menciona você.")),
+ "menção: aviso para o leitor de tela",
+ );
+ ok(!(await bia.$(`${mention}.c-message--mention`)), "quem mencionou não vê o destaque");
+ const issues = await axe(ana);
+ ok(
+ issues.length === 0,
+ `histórico com Markdown e menção sem violações sérias ${issues.join("; ")}`,
+ );
+
+ // Sugestão de @pessoa no campo.
+ await ana.click("#campo-mensagem");
+ await ana.keyboard.type("oi @bi");
+ await ana.waitForSelector(".c-command-suggestions:not([hidden]) [role='option']");
+ await ana.keyboard.press("Enter");
+ ok(
+ (await ana.inputValue("#campo-mensagem")) === `oi @${biaUser} `,
+ "@ sugere e completa a pessoa da conversa",
+ );
+ await ana.fill("#campo-mensagem", "");
+
+ // Barra de ações: Mencionar põe o @ no campo.
+ await ana.hover(mention);
+ await ana.click(`${mention} .c-message-actions [aria-label="Mencionar"]`);
+ ok(
+ (await ana.inputValue("#campo-mensagem")).includes(`@${biaUser}`),
+ "barra de ações: Mencionar",
+ );
+ await ana.fill("#campo-mensagem", "");
+
+ // Teclado: ↑ na lista foca a última mensagem; Shift+F10 abre o menu dela.
+ await ana.focus(".c-message-list");
+ await ana.keyboard.press("ArrowUp");
+ ok(
+ await ana.evaluate(() => document.activeElement?.classList.contains("c-message") ?? false),
+ "↑ na lista foca a última mensagem",
+ );
+ await ana.keyboard.press("Shift+F10");
+ await ana.waitForSelector('.c-menu[role="menu"]');
+ const items = await ana.$$eval(".c-menu .c-menu__item", (xs) =>
+ xs.map((x) => x.textContent?.trim() ?? ""),
+ );
+ ok(
+ items.includes("Copiar texto") && items.includes("Mencionar"),
+ "menu da mensagem pelo teclado",
+ );
+ await ana.keyboard.press("Escape");
+
+ // "Novas mensagens" ao voltar para uma conversa com não lidas.
+ await ana.click("[data-nav-new]");
+ await ana.fill("#nova-sala-nome", "Outra");
+ await ana.keyboard.press("Enter");
+ await ana.waitForFunction(
+ () => document.querySelector(".c-header__title")?.textContent?.trim() === "Outra",
+ );
+ for (let i = 1; i <= 3; i += 1) await say(bia, `nova ${i} ${RUN}`);
+ await ana.waitForSelector('.c-conv:has-text("Histórico") .c-conversation-nav__badge');
+ await ana.click('.c-conv:has-text("Histórico")');
+ await ana.waitForSelector(".c-new-divider");
+ ok(
+ await ana.$eval(
+ ".c-new-divider",
+ (x) => x.nextElementSibling?.textContent?.includes("nova 1") ?? false,
+ ),
+ "a linha 'Novas mensagens' fica antes da primeira não lida",
+ );
+
+ // Rolou para cima: as novas não puxam a tela; aparece o aviso; Esc leva ao fim.
+ for (let i = 0; i < 12; i += 1) await say(bia, `enchendo ${i} ${RUN}`);
+ await ana.waitForSelector(`.c-message:has-text("enchendo 11 ${RUN}")`);
+ await ana.$eval(".c-message-list", (x) => {
+ x.scrollTop = 0;
+ });
+ // O evento de rolagem chega no quadro seguinte: espera dois quadros.
+ await ana.evaluate(
+ () => new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done))),
+ );
+ await say(bia, `durante a rolagem ${RUN}`);
+ await ana.waitForSelector(".c-jump-bar:not([hidden])");
+ ok(
+ await ana.$eval(".c-message-list", (x) => x.scrollTop < 50),
+ "a tela não é puxada para baixo",
+ );
+ await ana.focus("#campo-mensagem");
+ await ana.keyboard.press("Escape");
+ await ana.waitForSelector(".c-jump-bar", { state: "hidden" });
+ ok(
+ await ana.$eval(
+ ".c-message-list",
+ (x) => x.scrollHeight - x.scrollTop - x.clientHeight < 80,
+ ),
+ "Esc no campo leva às mais recentes",
+ );
+
+ // Resposta de comando: "Dispensar".
+ await say(ana, "/time");
+ await ana.waitForSelector(".c-message--notice .c-message__dismiss");
+ await ana.click(".c-message--notice .c-message__dismiss");
+ await ana.waitForSelector(".c-message--notice", { state: "detached" });
+ ok(true, "resposta de comando pode ser dispensada");
+
+ // Mensagem que não foi enviada: "Apagar" (só na sua tela). O quadro
+ // desta mensagem é descartado no próprio navegador (o servidor nunca a
+ // recebe): no prazo de confirmação ela vira "não enviada".
+ await ana.evaluate((marker) => {
+ const original = WebSocket.prototype.send;
+ WebSocket.prototype.send = function (data) {
+ if (String(data).includes(marker)) return undefined;
+ return original.call(this, data);
+ };
+ }, `não vai ${RUN}`);
+ await say(ana, `não vai ${RUN}`);
+ await ana.waitForSelector(`.c-message[data-delivery="failed"]:has-text("não vai ${RUN}")`, {
+ timeout: 20000,
+ });
+ await ana.click(`.c-message:has-text("não vai ${RUN}") .c-message__retry:has-text("Apagar")`);
+ await ana.waitForSelector(`.c-message:has-text("não vai ${RUN}")`, { state: "detached" });
+ ok(true, "mensagem não enviada pode ser apagada da tela");
+};
diff --git a/frontend/index.html b/frontend/index.html
index 4b54de4..7c2f59a 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -671,8 +671,16 @@
Conversa
aria-relevant="additions"
aria-labelledby="conversa-titulo"
>
+
+
+
diff --git a/frontend/src/css/components/message-list.css b/frontend/src/css/components/message-list.css
index a337d33..8740063 100644
--- a/frontend/src/css/components/message-list.css
+++ b/frontend/src/css/components/message-list.css
@@ -19,3 +19,118 @@
.c-message-list:has(> .c-message-list__items:empty) {
display: none;
}
+
+.c-message-list:focus-visible {
+ outline: var(--rule-2) solid var(--color-focus-ring);
+ outline-offset: calc(var(--rule-2) * -1);
+}
+
+/* Começo da conversa, no topo do histórico. */
+.c-conversation-intro {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-1);
+ margin: var(--space-0) var(--space-4) var(--space-4);
+ padding: var(--space-2) var(--space-2) var(--space-4);
+ border-bottom: var(--rule-1) solid var(--color-border-subtle);
+}
+
+.c-conversation-intro__glyph .c-room-glyph,
+.c-conversation-intro__glyph .c-identity__monogram {
+ width: var(--space-16);
+ height: var(--space-16);
+ border-radius: var(--radius-lg);
+ font-size: var(--text-xl);
+}
+
+.c-conversation-intro__glyph .c-identity__monogram {
+ border-radius: var(--radius-full);
+}
+
+.c-conversation-intro__title {
+ margin-top: var(--space-2);
+ font-size: var(--text-2xl);
+ font-weight: var(--weight-bold);
+ letter-spacing: var(--tracking-tight);
+}
+
+.c-conversation-intro__body {
+ max-width: 60ch;
+ color: var(--color-text-2);
+ font-size: var(--text-sm);
+}
+
+/* Separador de dia: pílula centrada sobre a linha. */
+.c-day-divider,
+.c-new-divider {
+ display: flex;
+ gap: var(--space-3);
+ align-items: center;
+ margin: var(--space-4) var(--space-4) var(--space-1);
+ color: var(--color-text-3);
+ font-size: var(--text-xs);
+ font-weight: var(--weight-semibold);
+ list-style: none;
+}
+
+.c-day-divider::before,
+.c-day-divider::after {
+ flex: 1 1 auto;
+ height: var(--rule-1);
+ background-color: var(--color-border-subtle);
+ content: "";
+}
+
+.c-day-divider__label {
+ padding: var(--space-0-5) var(--space-3);
+ border: var(--rule-1) solid var(--color-border-subtle);
+ border-radius: var(--radius-full);
+}
+
+/* "Novas mensagens": linha carmim com o rótulo à direita. */
+.c-new-divider {
+ color: var(--color-brand-text);
+ font-size: var(--text-2xs);
+ letter-spacing: var(--tracking-caps);
+ text-transform: uppercase;
+}
+
+.c-new-divider::before {
+ flex: 1 1 auto;
+ height: var(--rule-1);
+ background-color: var(--color-brand);
+ content: "";
+}
+
+/* "N mensagens novas": acima do campo, só com a lista rolada para cima
+ (a conversa já é a referência de posição). */
+.c-jump-bar {
+ position: absolute;
+ z-index: var(--z-sticky);
+ bottom: var(--space-3);
+ left: 50%;
+ display: inline-flex;
+ gap: var(--space-2);
+ align-items: center;
+ padding: var(--space-1-5) var(--space-2) var(--space-1-5) var(--space-3);
+ border-radius: var(--radius-full);
+ background-color: var(--color-brand);
+ color: var(--color-on-brand);
+ font-size: var(--text-xs);
+ font-weight: var(--weight-semibold);
+ box-shadow: var(--shadow-3);
+ transform: translateX(-50%);
+ cursor: pointer;
+}
+
+.c-jump-bar[hidden] {
+ display: none;
+}
+
+.c-jump-bar__kbd {
+ padding: var(--space-0) var(--space-1-5);
+ border-radius: var(--radius-full);
+ background-color: color-mix(in srgb, var(--color-scrim) 25%, transparent);
+ font-family: var(--font-text);
+ font-size: var(--text-2xs);
+}
diff --git a/frontend/src/css/components/message.css b/frontend/src/css/components/message.css
index 17bf4c5..f1d18c2 100644
--- a/frontend/src/css/components/message.css
+++ b/frontend/src/css/components/message.css
@@ -83,6 +83,8 @@
.c-message__code {
padding: var(--space-0-5) var(--space-1-5);
+ font-family: var(--font-mono);
+ font-size: var(--text-sm);
border: var(--rule-1) solid var(--color-border-subtle);
border-radius: var(--radius-sm);
background-color: var(--color-bg-app);
@@ -301,16 +303,116 @@
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);
+/* Enviada: ✓ logo depois do texto, no fim do último parágrafo. */
+.c-message__status[hidden] {
+ display: none;
+}
+
+.c-message__sent-slot:empty {
+ display: none;
}
.c-message__sent {
display: inline-flex;
align-items: center;
- color: var(--color-text-2);
+ margin-left: var(--space-1-5);
+ color: var(--color-text-3);
font-size: var(--text-xs);
+ vertical-align: middle;
+}
+
+/* ─── Conteúdo em Markdown ────────────────────────────────────────── */
+.c-message__content {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-1);
+}
+
+.c-message__pre {
+ max-width: 100%;
+ margin: var(--space-0-5) var(--space-0);
+ padding: var(--space-2) var(--space-3);
+ overflow-x: auto;
+ border: var(--rule-1) solid var(--color-border-subtle);
+ border-radius: var(--radius-md);
+ background-color: var(--color-bg-app);
+ color: var(--color-text-1);
+ font-family: var(--font-mono);
+ font-size: var(--text-sm);
+ line-height: var(--leading-normal);
+ white-space: pre;
+}
+
+.c-message__quote {
+ padding-left: var(--space-3);
+ border-left: var(--rule-3) solid var(--color-border-subtle);
+ color: var(--color-text-2);
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+}
+
+.c-message__link {
+ color: var(--color-accent-2);
+ text-decoration: underline;
+ text-underline-offset: 0.15em;
+ overflow-wrap: anywhere;
+}
+
+.c-message__text del {
+ color: var(--color-text-2);
+}
+
+.c-mention {
+ padding: var(--space-0) var(--space-0-5);
+ border-radius: var(--radius-sm);
+ background-color: var(--color-accent-2-soft);
+ color: var(--color-accent-2);
+ font-weight: var(--weight-semibold);
+}
+
+.c-mention--self {
+ background-color: color-mix(in srgb, var(--color-warn) 18%, transparent);
+ color: var(--color-warn-text);
+}
+
+/* Menção a você: faixa à esquerda (forma) e fundo âmbar suave (cor). */
+.c-message--mention,
+.c-message--mention:hover {
+ box-shadow: inset var(--rule-3) 0 0 var(--color-warn);
+ background-color: color-mix(in srgb, var(--color-warn) 8%, transparent);
+}
+
+/* Foco por teclado na mensagem (↑/↓ na lista). */
+.c-message:focus-visible {
+ outline: var(--rule-2) solid var(--color-focus-ring);
+ outline-offset: calc(var(--rule-2) * -1);
+}
+
+.c-message__dismiss {
+ align-self: flex-start;
+ min-height: var(--space-6);
+}
+
+/* ─── Barra de ações da mensagem ──────────────────────────────────── */
+.c-message-actions {
+ position: absolute;
+ z-index: var(--z-sticky);
+ top: calc(var(--space-3) * -1);
+ right: var(--space-4);
+ display: flex;
+ gap: var(--space-0-5);
+ padding: var(--space-0-5);
+ border: var(--rule-1) solid var(--color-border-subtle);
+ border-radius: var(--radius-md);
+ background-color: var(--color-bg-elevated);
+ box-shadow: var(--shadow-2);
+}
+
+.c-message--compact .c-message-actions {
+ top: calc(var(--space-4) * -1);
+}
+
+/* Some quando o ponteiro sai e nada dela tem o foco. */
+.c-message:not(:hover, :focus-within) > .c-message-actions {
+ display: none;
}
diff --git a/frontend/src/i18n/strings.js b/frontend/src/i18n/strings.js
index 4ce143f..34d61be 100644
--- a/frontend/src/i18n/strings.js
+++ b/frontend/src/i18n/strings.js
@@ -70,6 +70,7 @@ export const strings = {
returned: "Sua mensagem não foi enviada ({reason}) e voltou para o campo de texto.",
failed: "não enviada",
retry: "Tentar de novo",
+ discard: "Apagar",
timeout: "O servidor não confirmou o recebimento.",
announceFailed: "Sua mensagem não foi enviada: {reason}",
},
@@ -79,9 +80,36 @@ export const strings = {
spoilerShow: "Mostrar spoiler",
spoilerHide: "Esconder spoiler",
private: "Só você vê isto",
+ dismiss: "Dispensar",
+ mentionsYou: "Menciona você.",
+ newMessages: "Novas mensagens",
+ today: "Hoje",
+ yesterday: "Ontem",
+ jumpNew: "{n} mensagens novas",
+ jumpNewOne: "1 mensagem nova",
+ jumpLatest: "Ir para as mais recentes",
+ jumpHint: "Esc",
+ copyText: "Copiar texto",
+ copied: "Texto copiado.",
+ copyFailed: "Não foi possível copiar o texto.",
+ mention: "Mencionar",
+ more: "Mais ações",
+ actionsFor: "Mensagem de {name}",
+ viewProfile: "Ver perfil",
+ directMessage: "Mensagem privada",
+ copyHandle: "Copiar @{username}",
+ introRoom: "{name}",
+ introRoomBody:
+ "Sala efêmera. Só quem tem o convite entra; o histórico guarda as mensagens recentes, e tudo some quando a sala acaba.",
+ introDm: "Conversa privada com {name}",
+ introDmBody:
+ "Só vocês dois leem. Nada fica salvo: a conversa some quando um de vocês sai do chat.",
+ introInvite: "Copiar convite",
+ introCommands: "Ver comandos",
},
commands: {
helpTitle: "Comandos",
+ peopleHeading: "Pessoas nesta conversa",
helpIntro: "Digite / para ver sugestões enquanto escreve.",
helpFooter:
"Detalhes de um comando: /help nome (ex.: /help roll). 🔒 = só administradores.",
diff --git a/frontend/src/main.js b/frontend/src/main.js
index 1cecbe8..485294c 100644
--- a/frontend/src/main.js
+++ b/frontend/src/main.js
@@ -88,7 +88,77 @@ const messageList = createMessageList({
force: true,
},
),
+ // "Apagar" uma mensagem que não foi enviada (só na sua tela).
+ onDiscard: (message) => {
+ if (!message.clientMsgId) return;
+ inFlight.delete(message.clientMsgId);
+ store.actions.discardFailed(message.clientMsgId);
+ composer.focus();
+ },
+ // "Dispensar" uma resposta de comando (só sua).
+ onDismiss: (message) => {
+ store.actions.removeLocal(message.id);
+ composer.focus();
+ },
+ getMe: () => store.getState().me?.username ?? null,
+ actionsFor: (message) => messageActions(message),
});
+
+/**
+ * Ações de uma mensagem (barra ao passar o ponteiro, "⋯", clique direito,
+ * Shift+F10, toque longo). Só ações reais: copiar, mencionar, perfil,
+ * conversa privada e copiar o arroba.
+ * @param {import("./state/store.js").Message} message
+ * @returns {{items: import("./ui/primitives/menuModel.js").MenuItem[], quick: {icon: string, label: string, run: () => void}[]} | null}
+ */
+const messageActions = (message) => {
+ if (message.kind !== "chat") return null;
+ const username = message.username ?? "";
+ const isDm = store.getState().room?.kind === "dm";
+ const copy = () =>
+ void navigator.clipboard
+ ?.writeText(message.content)
+ .then(() => toasts.show(strings.message.copied))
+ .catch(() => toasts.show(strings.message.copyFailed, "error"));
+ const mention = () => {
+ if (!username) return;
+ composer.insert(`@${username} `);
+ };
+ /** @type {{icon: string, label: string, run: () => void}[]} */
+ const quick = [{ icon: "copy", label: strings.message.copyText, run: copy }];
+ if (!message.own && username)
+ quick.push({ icon: "at", label: strings.message.mention, run: mention });
+ /** @type {import("./ui/primitives/menuModel.js").MenuItem[]} */
+ const items = [
+ { label: strings.message.copyText, icon: "copy", run: copy },
+ ...(!message.own && username
+ ? [{ label: strings.message.mention, icon: "at", run: mention }]
+ : []),
+ { type: "separator" },
+ ...(username && !isDm
+ ? [
+ {
+ label: strings.message.viewProfile,
+ icon: "user",
+ run: () => submit(`/profile @${username}`),
+ },
+ ]
+ : []),
+ ...(!message.own && username && !isDm
+ ? [{ label: strings.message.directMessage, icon: "at", run: () => requestDm(username) }]
+ : []),
+ ...(username
+ ? [
+ {
+ label: format(strings.message.copyHandle, { username }),
+ icon: "copy",
+ run: () => void copyText(`@${username}`),
+ },
+ ]
+ : []),
+ ];
+ return { items, quick };
+};
const typing = createTyping();
const notifier = createNotifier();
@@ -298,9 +368,41 @@ const openConversation = (conversationId) => {
typingSignal.stop();
typingTracker.clear();
memberCard.close({ restoreFocus: false });
- if (store.actions.openConversation(conversationId)) syncDraft(conversationId);
+ // Onde começam as não lidas: a linha "Novas mensagens" fica antes da
+ // primeira delas (contadas do fim, só mensagens de outras pessoas).
+ const unread =
+ store.getState().conversations.find((e) => e.conversationId === conversationId)?.unread ??
+ 0;
+ if (store.actions.openConversation(conversationId)) {
+ syncDraft(conversationId);
+ let marker = null;
+ if (unread > 0) {
+ let left = unread;
+ const list = store.getState().messages;
+ for (let i = list.length - 1; i >= 0; i -= 1) {
+ const item = list[i];
+ if (item && item.kind === "chat" && !item.own) {
+ left -= 1;
+ if (left === 0) {
+ marker = item.key;
+ break;
+ }
+ }
+ }
+ }
+ pendingMarker = { conversationId, key: marker };
+ }
};
+/**
+ * Linha "Novas mensagens" a pôr na próxima pintura da conversa aberta.
+ * @type {{conversationId: string, key: string | null} | null}
+ */
+let pendingMarker = null;
+
+/** Onde cada conversa estava rolada (só em memória). @type {Map
} */
+const scrollPositions = new Map();
+
/**
* Conversa da lista por id.
* @param {string} id
@@ -493,7 +595,15 @@ const composer = createComposer({
onSend: submit,
onTyping: () => typingSignal.input(),
onInput: (text, cursor) => suggestions.update(text, cursor),
- onKeyDown: (event) => suggestions.handleKey(event),
+ onKeyDown: (event) => {
+ if (suggestions.handleKey(event)) return true;
+ // Esc (sem sugestões abertas): vai às mais recentes, como no Discord.
+ if (event.key === "Escape" && !event.defaultPrevented) {
+ messageList.scrollToEnd();
+ return false;
+ }
+ return false;
+ },
// Botão "Comandos" do campo: abre as sugestões como se a pessoa
// digitasse "/" (sem apagar o que já estava escrito).
onCommands: () => {
@@ -517,6 +627,22 @@ const suggestions = createCommandSuggestions({
input: composer.input,
getCatalog: () => store.getState().catalog,
onChoose: (text) => composer.setValue(text),
+ // "@": só quem está na conversa aberta (na privada, a outra pessoa).
+ getPeople: () => {
+ const state = store.getState();
+ if (state.room?.kind === "dm" && state.room.peer) {
+ return [
+ {
+ id: state.room.peer.username,
+ name: state.room.peer.name,
+ username: state.room.peer.username,
+ },
+ ];
+ }
+ return state.people;
+ },
+ getMe: () => store.getState().me?.username ?? null,
+ onMention: (start, end, text) => composer.replaceRange(start, end, text),
});
/**
@@ -1591,7 +1717,33 @@ const render = (state, previous) => {
if (changed(state, previous, ["screen", "room"])) {
syncDraft(inRoom ? (state.room?.conversationId ?? null) : null);
}
- if (changed(state, previous, ["messages"])) messageList.render(state.messages);
+ const switchedRoom = previous?.room?.conversationId !== state.room?.conversationId;
+ if (switchedRoom && previous?.room?.conversationId && previous.screen === "room") {
+ scrollPositions.set(previous.room.conversationId, messageList.position());
+ }
+ if (switchedRoom) messageList.setNewMarker(null);
+ if (changed(state, previous, ["messages"])) {
+ const marker =
+ pendingMarker && pendingMarker.conversationId === state.room?.conversationId
+ ? pendingMarker
+ : null;
+ if (marker) messageList.setNewMarker(marker.key);
+ messageList.render(state.messages);
+ if (marker) {
+ pendingMarker = null;
+ // Com não lidas: abre na linha "Novas mensagens"; sem, onde estava.
+ if (marker.key) messageList.revealNewMarker();
+ else {
+ const saved = state.room
+ ? scrollPositions.get(state.room.conversationId)
+ : undefined;
+ if (saved) messageList.restore(saved);
+ else messageList.scrollToEnd();
+ }
+ } else if (switchedRoom) {
+ messageList.scrollToEnd();
+ }
+ }
if (changed(state, previous, ["messages", "authorsSeen", "authorsLeft", "room"])) {
messageList.setDeparted(departedAuthors(state));
}
diff --git a/frontend/src/markdown/parse.js b/frontend/src/markdown/parse.js
new file mode 100644
index 0000000..8daffd3
--- /dev/null
+++ b/frontend/src/markdown/parse.js
@@ -0,0 +1,269 @@
+// @ts-check
+
+/**
+ * Markdown das mensagens (decisão C2): um subconjunto pequeno, previsível e
+ * sem HTML, no espírito do que o Fluxer faz com o interpretador dele (em
+ * Rust/WebAssembly, que exigiria afrouxar a CSP). Este é próprio, em JS
+ * puro e de custo linear no tamanho da mensagem (no máximo 1000 caracteres).
+ *
+ * Blocos:
+ * ```linguagem bloco de código (o texto vai cru, sem marcação)
+ * código
+ * ```
+ * > citação linha de citação
+ * (o resto) parágrafo, com as quebras de linha mantidas
+ *
+ * Em linha:
+ * **negrito** *itálico* ou _itálico_ ~~riscado~~ ||spoiler|| `código`
+ * https://… link (só http e https)
+ * @username menção (o formato do @ do servidor)
+ * \* a barra invertida escapa um marcador
+ *
+ * O resultado é uma árvore de nós simples; quem desenha (render.js) só cria
+ * elementos e nós de texto.
+ *
+ * @typedef {{type: "text", text: string}
+ * | {type: "strong" | "em" | "del" | "spoiler", children: Inline[]}
+ * | {type: "code", text: string}
+ * | {type: "link", href: string, text: string}
+ * | {type: "mention", username: string}
+ * | {type: "br"}} Inline
+ * @typedef {{type: "paragraph", children: Inline[]}
+ * | {type: "quote", children: Inline[]}
+ * | {type: "codeblock", lang: string, text: string}} Block
+ */
+
+/** Marcadores em linha, do mais longo para o mais curto. */
+const DELIMITERS = /** @type {const} */ ([
+ ["**", "strong"],
+ ["~~", "del"],
+ ["||", "spoiler"],
+ ["*", "em"],
+ ["_", "em"],
+]);
+
+const ESCAPABLE = new Set(["*", "_", "~", "|", "`", "\\", "@", ">"]);
+
+/** Caracteres que fazem parte de um @username (formato do servidor). */
+const USERNAME_CHAR = /[a-z0-9._]/;
+
+/** Profundidade máxima de aninhamento (negrito dentro de itálico…). */
+const MAX_DEPTH = 6;
+
+/**
+ * Fim de um link: espaço, ou pontuação final que costuma não ser do link.
+ * @param {string} text
+ * @param {number} start
+ */
+const linkEnd = (text, start) => {
+ let end = start;
+ while (end < text.length && !/\s/.test(text.charAt(end))) end += 1;
+ // Pontuação no fim ("veja https://x.com.") e parêntese sem par saem.
+ while (end > start) {
+ const last = text.charAt(end - 1);
+ if (/[.,;:!?'"]/.test(last)) end -= 1;
+ else if (last === ")" && !text.slice(start, end).includes("(")) end -= 1;
+ else break;
+ }
+ return end;
+};
+
+/**
+ * @param {string} text
+ * @param {number} depth
+ * @returns {Inline[]}
+ */
+export const parseInline = (text, depth = 0) => {
+ /** @type {Inline[]} */
+ const out = [];
+ let buffer = "";
+ const flush = () => {
+ if (buffer) out.push({ type: "text", text: buffer });
+ buffer = "";
+ };
+ let i = 0;
+ while (i < text.length) {
+ const ch = text.charAt(i);
+
+ if (ch === "\\" && i + 1 < text.length && ESCAPABLE.has(text.charAt(i + 1))) {
+ buffer += text.charAt(i + 1);
+ i += 2;
+ continue;
+ }
+ if (ch === "\n") {
+ flush();
+ out.push({ type: "br" });
+ i += 1;
+ continue;
+ }
+ if (ch === "`") {
+ const close = text.indexOf("`", i + 1);
+ if (close > i + 1) {
+ flush();
+ out.push({ type: "code", text: text.slice(i + 1, close) });
+ i = close + 1;
+ continue;
+ }
+ }
+ if (
+ (ch === "h" || ch === "H") &&
+ /^https?:\/\/[^\s]/i.test(text.slice(i, i + 9)) &&
+ (i === 0 || /[\s(]/.test(text.charAt(i - 1)))
+ ) {
+ const end = linkEnd(text, i);
+ const href = text.slice(i, end);
+ if (/^https?:\/\/[^\s/]+/i.test(href)) {
+ flush();
+ out.push({ type: "link", href, text: href });
+ i = end;
+ continue;
+ }
+ }
+ if (ch === "@" && (i === 0 || !USERNAME_CHAR.test(text.charAt(i - 1)))) {
+ let end = i + 1;
+ while (end < text.length && USERNAME_CHAR.test(text.charAt(end))) end += 1;
+ // Ponto final não é do @ ("fala com @ana.").
+ while (end > i + 1 && text.charAt(end - 1) === ".") end -= 1;
+ const username = text.slice(i + 1, end);
+ if (username.length >= 3 && username.length <= 20) {
+ flush();
+ out.push({ type: "mention", username });
+ i = end;
+ continue;
+ }
+ }
+ if (depth < MAX_DEPTH) {
+ let matched = false;
+ for (const [mark, type] of DELIMITERS) {
+ if (!text.startsWith(mark, i)) continue;
+ const inner = i + mark.length;
+ // Não abre com espaço logo depois (ex.: "2 * 3").
+ if (inner >= text.length || /\s/.test(text.charAt(inner))) continue;
+ // `*` seguido de outro `*` é parte de um `**` sem par.
+ if (mark === "*" && text.charAt(inner) === "*") continue;
+ // `_` no meio de palavra não marca (nomes_de_variavel).
+ if (mark === "_" && i > 0 && /\w/.test(text.charAt(i - 1))) continue;
+ let close = text.indexOf(mark, inner);
+ // `*` sozinho não fecha num `**`.
+ while (close !== -1 && mark === "*" && text.startsWith("**", close)) {
+ close = text.indexOf(mark, close + 2);
+ }
+ if (close === -1 || close === inner) continue;
+ if (/\s/.test(text.charAt(close - 1))) continue;
+ if (mark === "_" && /\w/.test(text.charAt(close + mark.length))) continue;
+ flush();
+ out.push({
+ type,
+ children: parseInline(text.slice(inner, close), depth + 1),
+ });
+ i = close + mark.length;
+ matched = true;
+ break;
+ }
+ if (matched) continue;
+ }
+ buffer += ch;
+ i += 1;
+ }
+ flush();
+ return out;
+};
+
+/**
+ * @param {string} source
+ * @returns {Block[]}
+ */
+export const parseMarkdown = (source) => {
+ const lines = source.split("\n");
+ /** @type {Block[]} */
+ const blocks = [];
+ /** @type {string[]} */
+ let paragraph = [];
+ const flushParagraph = () => {
+ if (paragraph.length)
+ blocks.push({ type: "paragraph", children: parseInline(paragraph.join("\n")) });
+ paragraph = [];
+ };
+ for (let i = 0; i < lines.length; i += 1) {
+ const line = /** @type {string} */ (lines[i]);
+ const fence = /^```([\w+#.-]{0,20})\s*$/.exec(line);
+ if (fence) {
+ const end = lines.findIndex((other, j) => j > i && /^```\s*$/.test(other));
+ if (end !== -1) {
+ flushParagraph();
+ blocks.push({
+ type: "codeblock",
+ lang: fence[1] ?? "",
+ text: lines.slice(i + 1, end).join("\n"),
+ });
+ i = end;
+ continue;
+ }
+ }
+ // Bloco de uma linha só: ```código```
+ const inline = /^```(.+)```$/.exec(line);
+ if (inline && inline[1] && !inline[1].includes("```")) {
+ flushParagraph();
+ blocks.push({ type: "codeblock", lang: "", text: inline[1] });
+ continue;
+ }
+ if (line.startsWith("> ") || line === ">") {
+ flushParagraph();
+ const quoted = [line.slice(2)];
+ while (
+ i + 1 < lines.length &&
+ (lines[i + 1]?.startsWith("> ") || lines[i + 1] === ">")
+ ) {
+ i += 1;
+ quoted.push((lines[i] ?? "").slice(2));
+ }
+ blocks.push({ type: "quote", children: parseInline(quoted.join("\n")) });
+ continue;
+ }
+ paragraph.push(line);
+ }
+ flushParagraph();
+ return blocks;
+};
+
+/**
+ * Texto puro da mensagem, sem marcação (para o leitor de tela e para copiar).
+ * @param {Inline[]} nodes
+ * @returns {string}
+ */
+export const plainInline = (nodes) =>
+ nodes
+ .map((node) => {
+ switch (node.type) {
+ case "text":
+ case "code":
+ case "link":
+ return node.text;
+ case "mention":
+ return `@${node.username}`;
+ case "br":
+ return "\n";
+ default:
+ return plainInline(node.children);
+ }
+ })
+ .join("");
+
+/**
+ * As menções de uma mensagem.
+ * @param {Block[]} blocks
+ * @returns {string[]}
+ */
+export const mentionsOf = (blocks) => {
+ /** @type {string[]} */
+ const found = [];
+ /** @param {Inline[]} nodes */
+ const walk = (nodes) => {
+ for (const node of nodes) {
+ if (node.type === "mention") found.push(node.username);
+ else if ("children" in node) walk(node.children);
+ }
+ };
+ for (const block of blocks) if (block.type !== "codeblock") walk(block.children);
+ return found;
+};
diff --git a/frontend/src/markdown/render.js b/frontend/src/markdown/render.js
new file mode 100644
index 0000000..fe69a21
--- /dev/null
+++ b/frontend/src/markdown/render.js
@@ -0,0 +1,114 @@
+// @ts-check
+
+import { strings } from "../i18n/strings.js";
+import { el } from "../ui/dom.js";
+import { parseMarkdown } from "./parse.js";
+
+/**
+ * Desenha o Markdown de uma mensagem só com elementos e nós de texto —
+ * nunca `innerHTML`. Links só com http(s), abertos em nova aba, sem
+ * `Referer` nem acesso à página que abriu (`noopener noreferrer`).
+ *
+ * @typedef {import("./parse.js").Inline} Inline
+ * @typedef {import("./parse.js").Block} Block
+ */
+
+/**
+ * Spoiler: o texto fica escondido até a pessoa pedir (botão, com estado).
+ * @param {Node[]} content
+ */
+export const spoilerNode = (content) => {
+ const button = el("button", {
+ class: "c-spoiler",
+ attrs: {
+ type: "button",
+ "aria-expanded": "false",
+ "aria-label": strings.message.spoilerShow,
+ },
+ });
+ const hidden = el("span", { class: "c-spoiler__text", attrs: { "aria-hidden": "true" } });
+ hidden.append(...content);
+ button.appendChild(hidden);
+ button.addEventListener("click", () => {
+ const open = button.getAttribute("aria-expanded") !== "true";
+ button.setAttribute("aria-expanded", String(open));
+ hidden.setAttribute("aria-hidden", String(!open));
+ if (open) button.removeAttribute("aria-label");
+ else button.setAttribute("aria-label", strings.message.spoilerShow);
+ });
+ return button;
+};
+
+/**
+ * @param {Inline[]} nodes
+ * @param {{me: string | null}} context
+ * @returns {Node[]}
+ */
+const inline = (nodes, context) =>
+ nodes.map((node) => {
+ switch (node.type) {
+ case "text":
+ return document.createTextNode(node.text);
+ case "br":
+ return document.createElement("br");
+ case "code":
+ return el("code", { class: "c-message__code", text: node.text });
+ case "link": {
+ const link = el("a", {
+ class: "c-message__link",
+ text: node.text,
+ attrs: {
+ href: node.href,
+ target: "_blank",
+ rel: "noopener noreferrer nofollow",
+ },
+ });
+ return link;
+ }
+ case "mention": {
+ const self = context.me !== null && node.username === context.me;
+ return el("span", {
+ class: self ? "c-mention c-mention--self" : "c-mention",
+ text: `@${node.username}`,
+ });
+ }
+ case "spoiler":
+ return spoilerNode(inline(node.children, context));
+ default: {
+ const tag = node.type === "strong" ? "strong" : node.type === "em" ? "em" : "del";
+ const element = el(tag);
+ element.append(...inline(node.children, context));
+ return element;
+ }
+ }
+ });
+
+/**
+ * O conteúdo de uma mensagem como elementos.
+ * @param {string} source
+ * @param {{me: string | null}} context
+ * @returns {HTMLElement}
+ */
+export const renderMarkdown = (source, context) => {
+ const blocks = parseMarkdown(source);
+ const root = el("div", { class: "c-message__content" });
+ for (const block of blocks) {
+ if (block.type === "codeblock") {
+ const pre = el("pre", { class: "c-message__pre" });
+ const code = el("code", { text: block.text });
+ if (block.lang) code.dataset.lang = block.lang;
+ pre.appendChild(code);
+ root.appendChild(pre);
+ } else if (block.type === "quote") {
+ const quote = el("blockquote", { class: "c-message__quote" });
+ quote.append(...inline(block.children, context));
+ root.appendChild(quote);
+ } else {
+ const paragraph = el("p", { class: "c-message__text" });
+ paragraph.append(...inline(block.children, context));
+ root.appendChild(paragraph);
+ }
+ }
+ if (!root.firstChild) root.appendChild(el("p", { class: "c-message__text" }));
+ return root;
+};
diff --git a/frontend/src/state/store.js b/frontend/src/state/store.js
index 8a36605..13a1c81 100644
--- a/frontend/src/state/store.js
+++ b/frontend/src/state/store.js
@@ -757,6 +757,18 @@ export const createStore = () => {
);
},
+ /**
+ * Tira da tela uma entrada que só existe aqui (resposta de
+ * comando "Dispensar"). Não mexe em nada do servidor.
+ * @param {string} id
+ */
+ removeLocal(id) {
+ const messages = state.messages.filter(
+ (m) => !(m.id === id && m.kind === "notice"),
+ );
+ if (messages.length !== state.messages.length) patch({ messages });
+ },
+
/**
* Tira da tela uma mensagem SUA que o servidor recusou de vez (o
* texto volta para o rascunho). Só falhas: uma confirmada nunca
diff --git a/frontend/src/ui/commandSuggestions.js b/frontend/src/ui/commandSuggestions.js
index c95e2e3..da541b6 100644
--- a/frontend/src/ui/commandSuggestions.js
+++ b/frontend/src/ui/commandSuggestions.js
@@ -12,17 +12,69 @@ import { el, must } from "./dom.js";
* fecha, clique/toque escolhe. Depois do nome, mostra só a sintaxe — sem
* tomar nenhuma tecla. Mensagens comuns não abrem nada.
*
+ * Também sugere pessoas ao digitar "@" (decisão C3): só quem está na
+ * conversa aberta, com os dados que o navegador já tem (lista de pessoas).
+ * Escolher troca o trecho "@parcial" por "@username ".
+ *
* @typedef {import("../state/store.js").CommandInfo} CommandInfo
+ * @typedef {import("../state/store.js").Person} Person
+ */
+
+/**
+ * "@parcial" logo antes do cursor (início de palavra), ou null.
+ * @param {string} text
+ * @param {number} cursor
+ * @returns {{start: number, query: string} | null}
+ */
+export const mentionQuery = (text, cursor) => {
+ const before = text.slice(0, cursor);
+ const match = /(^|\s)@([a-z0-9._]{0,20})$/.exec(before);
+ if (!match) return null;
+ return { start: before.length - (match[2] ?? "").length - 1, query: match[2] ?? "" };
+};
+
+/** Sem acento e em minúsculas. @param {string} text */
+const fold = (text) => text.normalize("NFD").replace(/\p{M}/gu, "").toLocaleLowerCase("pt-BR");
+
+/**
+ * Pessoas que combinam com o "@parcial" (no máximo 8, sem você).
+ * @param {Person[]} people
+ * @param {string} query
+ * @param {string | null} me
*/
+export const matchPeople = (people, query, me) => {
+ const q = fold(query);
+ return people
+ .filter((person) => person.username && person.username !== me)
+ .filter(
+ (person) =>
+ !q ||
+ (person.username ?? "").startsWith(q) ||
+ fold(person.name)
+ .split(/\s+/)
+ .some((word) => word.startsWith(q)),
+ )
+ .slice(0, 8);
+};
/**
* @param {{
* input: HTMLInputElement | HTMLTextAreaElement,
* getCatalog: () => CommandInfo[],
* onChoose: (text: string) => void,
+ * getPeople?: () => Person[],
+ * getMe?: () => string | null,
+ * onMention?: (start: number, end: number, text: string) => void,
* }} options
*/
-export const createCommandSuggestions = ({ input, getCatalog, onChoose }) => {
+export const createCommandSuggestions = ({
+ input,
+ getCatalog,
+ onChoose,
+ getPeople = () => [],
+ getMe = () => null,
+ onMention = () => {},
+}) => {
const root = /** @type {HTMLElement} */ (must(".c-command-suggestions"));
const list = /** @type {HTMLUListElement} */ (must(".c-command-suggestions__list", root));
const hint = /** @type {HTMLElement} */ (must(".c-command-suggestions__hint", root));
@@ -44,6 +96,11 @@ export const createCommandSuggestions = ({ input, getCatalog, onChoose }) => {
/** @type {{command: CommandInfo, matched: string}[]} */
let items = [];
+ /** Modo pessoas ("@"): as pessoas e onde o "@" começa. */
+ /** @type {Person[]} */
+ let people = [];
+ let mentionStart = -1;
+ const heading = root.querySelector(".c-command-suggestions__heading");
let active = 0;
let query = "";
/** Escape fecha até o texto mudar. */
@@ -55,6 +112,8 @@ export const createCommandSuggestions = ({ input, getCatalog, onChoose }) => {
const close = () => {
items = [];
+ people = [];
+ mentionStart = -1;
root.hidden = true;
list.hidden = true;
hint.hidden = true;
@@ -73,6 +132,14 @@ export const createCommandSuggestions = ({ input, getCatalog, onChoose }) => {
/** @param {number} index */
const choose = (index) => {
+ if (people.length) {
+ const person = people[index];
+ const start = mentionStart;
+ const end = input.selectionStart ?? input.value.length;
+ close();
+ if (person?.username) onMention(start, end, `@${person.username} `);
+ return;
+ }
const item = items[index];
if (!item) return;
close();
@@ -121,7 +188,52 @@ export const createCommandSuggestions = ({ input, getCatalog, onChoose }) => {
update(text, cursor) {
if (dismissedFor !== null && dismissedFor !== text) dismissedFor = null;
const result = dismissedFor === null ? suggest(text, cursor, getCatalog()) : null;
- if (!result) return close();
+ if (!result) {
+ const mention = dismissedFor === null ? mentionQuery(text, cursor) : null;
+ const found = mention ? matchPeople(getPeople(), mention.query, getMe()) : [];
+ if (!mention || found.length === 0) return close();
+ const same =
+ people.length === found.length &&
+ people.every((person, index) => person.username === found[index]?.username);
+ items = [];
+ people = found;
+ mentionStart = mention.start;
+ if (!same) active = 0;
+ root.hidden = false;
+ hint.hidden = true;
+ list.hidden = false;
+ if (heading) heading.textContent = strings.commands.peopleHeading;
+ list.replaceChildren(
+ ...people.map((person, index) => {
+ const option = el("li", {
+ class: "c-command-suggestions__option",
+ attrs: {
+ role: "option",
+ id: optionId(index),
+ "aria-selected": "false",
+ },
+ });
+ option.appendChild(
+ el("span", { class: "c-command-suggestions__name", text: person.name }),
+ );
+ option.appendChild(
+ el("span", {
+ class: "c-command-suggestions__desc",
+ text: `@${person.username}`,
+ }),
+ );
+ option.addEventListener("mousedown", (event) => {
+ event.preventDefault();
+ choose(index);
+ });
+ return option;
+ }),
+ );
+ setExpanded(true);
+ highlight();
+ return;
+ }
+ if (heading) heading.textContent = strings.commands.helpTitle;
root.hidden = false;
if (result.mode === "syntax") {
@@ -155,14 +267,15 @@ export const createCommandSuggestions = ({ input, getCatalog, onChoose }) => {
* @param {KeyboardEvent} event
*/
handleKey(event) {
- if (items.length === 0) return false;
+ const total = people.length || items.length;
+ if (total === 0) return false;
switch (event.key) {
case "ArrowDown":
- active = (active + 1) % items.length;
+ active = (active + 1) % total;
highlight();
return true;
case "ArrowUp":
- active = (active - 1 + items.length) % items.length;
+ active = (active - 1 + total) % total;
highlight();
return true;
case "Tab":
@@ -170,6 +283,10 @@ export const createCommandSuggestions = ({ input, getCatalog, onChoose }) => {
choose(active);
return true;
case "Enter": {
+ if (people.length) {
+ choose(active);
+ return true;
+ }
// Nome já completo (ex.: "/help"): Enter envia. Senão, completa.
const item = items[active];
if (!item || item.matched === query) return false;
diff --git a/frontend/src/ui/composer.js b/frontend/src/ui/composer.js
index a4a8029..9738868 100644
--- a/frontend/src/ui/composer.js
+++ b/frontend/src/ui/composer.js
@@ -293,6 +293,20 @@ export const createComposer = ({
reportInput();
},
+ /**
+ * Troca um trecho do texto (ex.: "@par" → "@pessoa ") e põe o
+ * cursor no fim do trecho novo.
+ * @param {number} start
+ * @param {number} end
+ * @param {string} text
+ */
+ replaceRange(start, end, text) {
+ input.setRangeText(text, start, end, "end");
+ input.focus();
+ afterChange();
+ reportInput();
+ },
+
/** O campo, para o autocomplete apontar atributos ARIA. */
input,
diff --git a/frontend/src/ui/message.js b/frontend/src/ui/message.js
index 584452b..70c5e53 100644
--- a/frontend/src/ui/message.js
+++ b/frontend/src/ui/message.js
@@ -5,13 +5,20 @@ import { el } from "./dom.js";
import { icon } from "./icons.js";
import { badge, renderIdentity } from "./identity.js";
import { authorKey } from "../state/store.js";
+import { renderMarkdown, spoilerNode } from "../markdown/render.js";
+import { mentionsOf, parseMarkdown } from "../markdown/parse.js";
/**
* Renderização de uma entrada da transcrição. Só `textContent` e
* `createElement`: nenhum conteúdo vindo da rede vira HTML.
*
* @typedef {import("../state/store.js").Message} Message
- * @typedef {{onRetry?: (message: Message) => void}} MessageHandlers
+ * @typedef {{
+ * onRetry?: (message: Message) => void,
+ * onDiscard?: (message: Message) => void,
+ * onDismiss?: (message: Message) => void,
+ * }} MessageHandlers
+ * @typedef {{compact?: boolean, me?: string | null}} RenderOptions
*/
/**
@@ -38,46 +45,16 @@ const timeElement = (timestamp) => {
};
/**
- * Spoiler: o texto fica escondido até a pessoa pedir. É um botão — chega
- * por teclado e anuncia o estado com `aria-expanded`.
- * @param {string} content
- */
-const spoiler = (content) => {
- const button = el("button", {
- class: "c-spoiler",
- attrs: {
- type: "button",
- "aria-expanded": "false",
- "aria-label": strings.message.spoilerShow,
- },
- });
- // Escondido também para leitores de tela até a pessoa pedir.
- const hidden = el("span", {
- class: "c-spoiler__text",
- text: content,
- attrs: { "aria-hidden": "true" },
- });
- button.appendChild(hidden);
- button.addEventListener("click", () => {
- const open = button.getAttribute("aria-expanded") !== "true";
- button.setAttribute("aria-expanded", String(open));
- button.setAttribute(
- "aria-label",
- open ? strings.message.spoilerHide : strings.message.spoilerShow,
- );
- hidden.setAttribute("aria-hidden", String(!open));
- // Aberto, o rótulo do botão não pode esconder o texto revelado.
- if (open) button.removeAttribute("aria-label");
- });
- return button;
-};
-
-/**
- * Conteúdo com a formatação aplicada pelo servidor (comandos /bold etc.).
+ * Conteúdo da mensagem. Formatação aplicada pelo servidor (comandos /bold,
+ * /italic, /code, /spoiler) vale para a mensagem inteira; texto comum passa
+ * pelo Markdown (decisão C2), desenhado sem HTML.
* @param {Message} message
+ * @param {string | null} me
* @returns {HTMLElement}
*/
-const renderContent = (message) => {
+const renderContent = (message, me) => {
+ if (!message.format) return renderMarkdown(message.content, { me });
+ const root = el("div", { class: "c-message__content" });
const paragraph = el("p", { class: "c-message__text" });
switch (message.format) {
case "bold":
@@ -89,13 +66,11 @@ const renderContent = (message) => {
case "code":
paragraph.appendChild(el("code", { class: "c-message__code", text: message.content }));
break;
- case "spoiler":
- paragraph.appendChild(spoiler(message.content));
- break;
default:
- paragraph.textContent = message.content;
+ paragraph.appendChild(spoilerNode([document.createTextNode(message.content)]));
}
- return paragraph;
+ root.appendChild(paragraph);
+ return root;
};
/**
@@ -135,17 +110,35 @@ const fillStatus = (slot, message, handlers) => {
});
retry.addEventListener("click", () => handlers.onRetry?.(message));
slot.appendChild(retry);
+ // "Apagar" (decisão C4): descarta a tentativa, só na sua tela.
+ if (handlers.onDiscard && message.clientMsgId) {
+ const discard = el("button", {
+ class: "c-button c-button--ghost c-button--sm c-message__retry",
+ text: strings.delivery.discard,
+ attrs: { type: "button" },
+ });
+ discard.addEventListener("click", () => handlers.onDiscard?.(message));
+ slot.appendChild(discard);
+ }
}
- // Enviada: sua mensagem confirmada pelo servidor ganha um ✓ discreto,
- // com o estado em texto para leitor de tela.
+ slot.hidden = message.delivery === "confirmed";
+ slot.dataset.state = message.delivery;
+};
+
+/**
+ * Enviada: a sua mensagem confirmada pelo servidor ganha um ✓ discreto
+ * logo depois do texto, com o estado em texto para o leitor de tela.
+ * @param {HTMLElement} slot
+ * @param {Message} message
+ */
+const fillSent = (slot, message) => {
+ slot.replaceChildren();
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;
};
/**
@@ -160,11 +153,12 @@ const iconAside = (name) => {
/**
* Resposta de comando (visível só para você): cartão com o selo
- * "Só você vê isto", em texto.
+ * "Só você vê isto", em texto, e o botão "Dispensar".
* @param {HTMLLIElement} item
* @param {Message} message
+ * @param {MessageHandlers} handlers
*/
-const renderNotice = (item, message) => {
+const renderNotice = (item, message, handlers) => {
item.classList.add("c-message--notice");
item.dataset.tone = message.tone ?? "info";
item.appendChild(iconAside(message.tone === "error" ? "alert" : "terminal"));
@@ -179,6 +173,15 @@ const renderNotice = (item, message) => {
for (const line of message.lines) list.appendChild(el("li", { text: line }));
card.appendChild(list);
}
+ if (handlers.onDismiss) {
+ const dismiss = el("button", {
+ class: "c-button c-button--ghost c-button--sm c-message__dismiss",
+ text: strings.message.dismiss,
+ attrs: { type: "button" },
+ });
+ dismiss.addEventListener("click", () => handlers.onDismiss?.(message));
+ card.appendChild(dismiss);
+ }
body.appendChild(card);
item.appendChild(body);
return item;
@@ -220,18 +223,29 @@ const renderSystem = (item, message) => {
*
* @param {Message} message
* @param {MessageHandlers} [handlers]
- * @param {{compact?: boolean}} [options]
+ * @param {RenderOptions} [options]
* @returns {HTMLLIElement}
*/
-export const renderMessage = (message, handlers = {}, { compact = false } = {}) => {
+export const renderMessage = (message, handlers = {}, { compact = false, me = null } = {}) => {
const item = el("li", { class: "c-message" });
item.dataset.messageId = message.id;
+ item.dataset.kind = message.kind;
- if (message.kind === "notice") return renderNotice(item, message);
+ if (message.kind === "notice") return renderNotice(item, message, handlers);
if (message.kind === "system") return renderSystem(item, message);
if (message.own) item.classList.add("c-message--self");
item.dataset.delivery = message.delivery;
+ // Alcançável pelas setas dentro da lista (foco itinerante da lista).
+ item.tabIndex = -1;
+ if (message.username) item.dataset.username = message.username;
+ // Menção a você: destaque (forma e cor) e aviso em texto para o leitor.
+ const mentionsMe =
+ !message.own &&
+ me !== null &&
+ !message.format &&
+ mentionsOf(parseMarkdown(message.content)).includes(me);
+ if (mentionsMe) item.classList.add("c-message--mention");
// 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;
@@ -267,10 +281,17 @@ export const renderMessage = (message, handlers = {}, { compact = false } = {})
line.appendChild(document.createTextNode(` ${message.content} `));
const time = timeElement(message.timestamp);
if (time) line.appendChild(time);
- body.appendChild(line);
+ const content = el("div", { class: "c-message__content" });
+ content.appendChild(line);
+ body.appendChild(content);
} else if (isCompact) {
- body.appendChild(el("span", { class: "sr-only", text: `${message.userName}:` }));
- body.appendChild(renderContent(message));
+ body.appendChild(
+ el("span", {
+ class: "sr-only",
+ text: `${message.userName}${message.own ? ` (${strings.room.youBadge})` : ""}:`,
+ }),
+ );
+ body.appendChild(renderContent(message, me));
} else {
if (variant === "announcement") {
item.classList.add("c-message--announcement");
@@ -294,7 +315,10 @@ export const renderMessage = (message, handlers = {}, { compact = false } = {})
el("span", { class: "c-message__handle", text: `@${message.username}` }),
);
}
- if (message.own) head.appendChild(badge(strings.room.youBadge));
+ // "você" não aparece em toda mensagem própria (decisão Q5): o nome
+ // já diz, e o leitor de tela continua ouvindo.
+ if (message.own)
+ head.appendChild(el("span", { class: "sr-only", text: `(${strings.room.youBadge})` }));
if (key) {
// Escondido até a pessoa sair; em texto, não só no tom.
const departed = badge(strings.message.departed, "departed");
@@ -304,8 +328,18 @@ export const renderMessage = (message, handlers = {}, { compact = false } = {})
const time = timeElement(message.timestamp);
if (time) head.appendChild(time);
body.appendChild(head);
- body.appendChild(renderContent(message));
+ body.appendChild(renderContent(message, me));
}
+ if (mentionsMe)
+ body.appendChild(el("span", { class: "sr-only", text: strings.message.mentionsYou }));
+
+ // ✓ logo depois do texto (no último parágrafo), não na ponta da linha.
+ const sent = el("span", { class: "c-message__sent-slot" });
+ fillSent(sent, message);
+ const blocks = body.querySelectorAll(".c-message__content > *");
+ const last = blocks[blocks.length - 1];
+ if (last && last.tagName === "P") last.appendChild(sent);
+ else body.querySelector(".c-message__content")?.appendChild(sent);
const status = el("p", { class: "c-message__status" });
fillStatus(status, message, handlers);
@@ -326,4 +360,6 @@ export const patchDelivery = (item, message, handlers = {}) => {
item.dataset.delivery = message.delivery;
const status = item.querySelector(".c-message__status");
if (status instanceof HTMLElement) fillStatus(status, message, handlers);
+ const sent = item.querySelector(".c-message__sent-slot");
+ if (sent instanceof HTMLElement) fillSent(sent, message);
};
diff --git a/frontend/src/ui/messageList.js b/frontend/src/ui/messageList.js
index 0e41c1f..5ae3101 100644
--- a/frontend/src/ui/messageList.js
+++ b/frontend/src/ui/messageList.js
@@ -1,18 +1,55 @@
// @ts-check
-import { clear, must } from "./dom.js";
+import { format, strings } from "../i18n/strings.js";
+import { clear, el, must } from "./dom.js";
+import { icon } from "./icons.js";
import { patchDelivery, renderMessage } from "./message.js";
+import { bindContextMenu } from "./primitives/contextMenu.js";
+import { showMenu } from "./primitives/menu.js";
/**
* @typedef {import("../state/store.js").Message} Message
+ * @typedef {import("./primitives/menuModel.js").MenuItem} MenuItem
*/
-/** Mensagens da mesma pessoa dentro desta janela viram um grupo. */
-const GROUP_WINDOW_MS = 5 * 60 * 1000;
+/**
+ * Janela de agrupamento: mensagens seguidas da mesma pessoa, no mesmo dia e
+ * a menos de 7 minutos uma da outra viram um grupo (a regra do
+ * `MessageGroupingUtils` do Fluxer, reimplementada aqui).
+ */
+const GROUP_WINDOW_MS = 7 * 60 * 1000;
+
+/** Dia local de um carimbo ISO ("" se ilegível). @param {string} timestamp */
+export const dayKey = (timestamp) => {
+ const date = new Date(timestamp);
+ if (Number.isNaN(date.getTime())) return "";
+ return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
+};
+
+/**
+ * Rótulo do separador de dia: "Hoje", "Ontem" ou a data.
+ * @param {string} timestamp
+ * @param {Date} [now]
+ */
+export const dayLabel = (timestamp, now = new Date()) => {
+ const date = new Date(timestamp);
+ if (Number.isNaN(date.getTime())) return "";
+ const today = dayKey(now.toISOString());
+ const yesterday = new Date(now);
+ yesterday.setDate(now.getDate() - 1);
+ const key = dayKey(timestamp);
+ if (key === today) return strings.message.today;
+ if (key === dayKey(yesterday.toISOString())) return strings.message.yesterday;
+ return date.toLocaleDateString("pt-BR", {
+ day: "numeric",
+ month: "long",
+ ...(date.getFullYear() === now.getFullYear() ? {} : { year: "numeric" }),
+ });
+};
/**
* Continuação de quem acabou de falar? Só conversa comum, mesma pessoa,
- * em sequência e dentro da janela.
+ * mesmo dia, em sequência e dentro da janela.
* @param {Message | undefined} previous
* @param {Message} message
* @returns {boolean}
@@ -26,6 +63,7 @@ export const continuesGroup = (previous, message) => {
}
const plain = (/** @type {Message} */ m) => (m.variant ?? "text") === "text";
if (!plain(previous) || !plain(message)) return false;
+ if (dayKey(previous.timestamp) !== dayKey(message.timestamp)) return false;
const gap = Date.parse(message.timestamp) - Date.parse(previous.timestamp);
return Number.isFinite(gap) && gap >= 0 && gap < GROUP_WINDOW_MS;
};
@@ -36,28 +74,89 @@ export const continuesGroup = (previous, message) => {
* projeto: por isso ela adiciona itens em vez de redesenhar a lista
* inteira, e atualiza no lugar o que muda (entrega confirmada ou falha).
*
- * @param {{onRetry?: (message: Message) => void, onFailed?: (message: Message) => void}} [handlers]
+ * Rolagem (comportamento do Fluxer e do Discord):
+ * - no fim, a lista acompanha as novas;
+ * - rolou para cima, as novas NÃO puxam a tela: aparece "N mensagens
+ * novas", que leva ao fim (Esc no campo faz o mesmo);
+ * - ao abrir uma conversa com não lidas, uma linha "Novas mensagens" marca
+ * onde você parou;
+ * - ao voltar a uma conversa, você volta para onde estava (em memória).
+ *
+ * Teclado: a lista é uma parada de Tab; ↑/↓ andam entre as mensagens, Home
+ * e End vão às pontas, Shift+F10 abre o menu da mensagem focada.
+ *
+ * @param {{
+ * onRetry?: (message: Message) => void,
+ * onFailed?: (message: Message) => void,
+ * onDiscard?: (message: Message) => void,
+ * onDismiss?: (message: Message) => void,
+ * getMe?: () => string | null,
+ * actionsFor?: (message: Message) => {items: MenuItem[], quick: {icon: string, label: string, run: () => void}[]} | null,
+ * }} [handlers]
*/
export const createMessageList = (handlers = {}) => {
// A região `role="log"` é o contêiner rolável; os itens moram numa
// lista de verdade dentro dela (role="log" não é permitido em ).
const root = /** @type {HTMLElement} */ (must(".c-message-list"));
const items = /** @type {HTMLOListElement} */ (must(".c-message-list__items", root));
+ const jump = /** @type {HTMLButtonElement} */ (must(".c-jump-bar"));
+ const getMe = handlers.getMe ?? (() => null);
/** key → elemento e última versão pintada. */
+ /** @type {Map} */
const painted = new Map();
+ /** Separadores de dia na tela: dia → elemento. */
+ /** @type {Map} */
+ const dividers = new Map();
+ /** Linha "Novas mensagens" (antes desta chave). */
+ let newMarkerKey = /** @type {string | null} */ (null);
+ /** Mensagens novas que chegaram com a lista rolada para cima. */
+ let unseen = 0;
- /** Rola só quando o usuário já estava no fim. */
+ /** No fim (ou quase)? */
const isAtBottom = () => root.scrollHeight - root.scrollTop - root.clientHeight < 80;
+ const paintJump = () => {
+ jump.hidden = unseen === 0;
+ const label =
+ unseen === 1
+ ? strings.message.jumpNewOne
+ : format(strings.message.jumpNew, { n: unseen });
+ jump.replaceChildren(
+ icon("arrow-down"),
+ el("span", { text: label }),
+ el("kbd", {
+ class: "c-jump-bar__kbd",
+ text: strings.message.jumpHint,
+ attrs: { "aria-hidden": "true" },
+ }),
+ );
+ jump.setAttribute("aria-label", `${label}. ${strings.message.jumpLatest}`);
+ };
+
const scrollToEnd = () => {
root.scrollTop = root.scrollHeight;
+ unseen = 0;
+ paintJump();
};
+ root.addEventListener(
+ "scroll",
+ () => {
+ if (unseen && isAtBottom()) {
+ unseen = 0;
+ paintJump();
+ }
+ },
+ { passive: true },
+ );
+ jump.addEventListener("click", () => {
+ scrollToEnd();
+ });
+
/**
* 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á.
+ * ganham a marca "saiu".
* @type {Set}
*/
let departed = new Set();
@@ -72,6 +171,156 @@ export const createMessageList = (handlers = {}) => {
if (mark instanceof HTMLElement) mark.hidden = !gone;
};
+ /** @param {string} timestamp */
+ const divider = (timestamp) => {
+ // O - continua item de lista (o ARIA não deixa trocar o papel de
+ // filho de
); o texto do dia é lido normalmente.
+ const node = el("li", { class: "c-day-divider" });
+ node.appendChild(el("span", { class: "c-day-divider__label", text: dayLabel(timestamp) }));
+ return node;
+ };
+
+ const newMarker = () => {
+ const node = el("li", { class: "c-new-divider" });
+ node.dataset.newMarker = "";
+ node.appendChild(
+ el("span", { class: "c-new-divider__label", text: strings.message.newMessages }),
+ );
+ return node;
+ };
+
+ /** Separador de dia que ficou sem mensagens depois dele (as antigas saíram). */
+ const pruneDividers = () => {
+ for (const [day, node] of dividers) {
+ let next = node.nextElementSibling;
+ while (next && next.classList.contains("c-new-divider")) next = next.nextElementSibling;
+ if (!next || next.classList.contains("c-day-divider")) {
+ node.remove();
+ dividers.delete(day);
+ }
+ }
+ };
+
+ // ─── Barra de ações (uma só, levada até a mensagem sob o ponteiro) ──
+ const toolbar = el("div", {
+ class: "c-message-actions",
+ attrs: { role: "toolbar", "aria-label": strings.message.more },
+ });
+ /** Mensagem dona da barra agora. @type {HTMLElement | null} */
+ let toolbarOwner = null;
+
+ /** @param {HTMLElement} element */
+ const messageOf = (element) => {
+ for (const entry of painted.values()) if (entry.element === element) return entry.message;
+ return null;
+ };
+
+ /** @param {HTMLElement | null} element */
+ const attachToolbar = (element) => {
+ if (element === toolbarOwner) return;
+ toolbarOwner = element;
+ if (!element || !handlers.actionsFor) {
+ toolbar.remove();
+ return;
+ }
+ const message = messageOf(element);
+ const actions = message ? handlers.actionsFor(message) : null;
+ if (!actions) {
+ toolbar.remove();
+ return;
+ }
+ toolbar.replaceChildren();
+ for (const action of actions.quick) {
+ const button = el("button", {
+ class: "c-icon-button c-icon-button--sm",
+ attrs: {
+ type: "button",
+ tabindex: "-1",
+ "aria-label": action.label,
+ "data-tooltip": action.label,
+ },
+ });
+ button.appendChild(icon(action.icon));
+ button.addEventListener("click", action.run);
+ toolbar.appendChild(button);
+ }
+ const more = el("button", {
+ class: "c-icon-button c-icon-button--sm",
+ attrs: {
+ type: "button",
+ tabindex: "-1",
+ "aria-haspopup": "menu",
+ "aria-expanded": "false",
+ "aria-label": strings.message.more,
+ "data-tooltip": strings.message.more,
+ },
+ });
+ more.appendChild(icon("dots"));
+ more.addEventListener("click", () => {
+ const latest = messageOf(element);
+ const menu = latest ? handlers.actionsFor?.(latest) : null;
+ if (!menu || !latest) return;
+ showMenu({
+ label: format(strings.message.actionsFor, { name: latest.userName }),
+ anchor: more,
+ placement: "bottom-end",
+ returnFocus: element,
+ items: menu.items,
+ });
+ });
+ toolbar.appendChild(more);
+ element.appendChild(toolbar);
+ };
+
+ items.addEventListener("pointerover", (event) => {
+ if (/** @type {PointerEvent} */ (event).pointerType === "touch") return;
+ const target = /** @type {Element} */ (event.target).closest(
+ '.c-message[data-kind="chat"]',
+ );
+ if (target instanceof HTMLElement) attachToolbar(target);
+ });
+ root.addEventListener("pointerleave", () => {
+ if (!toolbar.contains(document.activeElement)) attachToolbar(null);
+ });
+
+ bindContextMenu(items, {
+ selector: '.c-message[data-kind="chat"]',
+ resolve: (target) => {
+ const message = messageOf(target);
+ const menu = message ? handlers.actionsFor?.(message) : null;
+ return menu && message
+ ? {
+ label: format(strings.message.actionsFor, { name: message.userName }),
+ items: menu.items,
+ }
+ : null;
+ },
+ });
+
+ // ─── Teclado: a lista como uma parada de Tab ────────────────────────
+ root.tabIndex = 0;
+ const focusables = () =>
+ /** @type {HTMLElement[]} */ ([...items.querySelectorAll('.c-message[data-kind="chat"]')]);
+ root.addEventListener("keydown", (event) => {
+ if (event.altKey || event.ctrlKey || event.metaKey) return;
+ const list = focusables();
+ if (list.length === 0) return;
+ const active = document.activeElement;
+ const at = active instanceof HTMLElement ? list.indexOf(active) : -1;
+ /** @param {HTMLElement | undefined} next */
+ const go = (next) => {
+ if (!next) return;
+ event.preventDefault();
+ next.focus();
+ attachToolbar(next);
+ };
+ if (event.key === "ArrowUp") go(at === -1 ? list.at(-1) : list[Math.max(0, at - 1)]);
+ else if (event.key === "ArrowDown")
+ go(at === -1 ? list.at(-1) : list[Math.min(list.length - 1, at + 1)]);
+ else if (event.key === "Home" && at !== -1) go(list[0]);
+ else if (event.key === "End" && at !== -1) go(list.at(-1));
+ });
+
return {
/**
* @param {Message[]} messages
@@ -93,14 +342,21 @@ export const createMessageList = (handlers = {}) => {
painted.get(key)?.element.remove();
painted.delete(key);
}
+ pruneDividers();
} else if (gone.length > 0) {
// Conversa substituída ou limpa: única situação em que a
// lista é reconstruída. Fora dela, adição e atualização no lugar.
clear(items);
painted.clear();
+ dividers.clear();
+ toolbarOwner = null;
+ unseen = 0;
+ paintJump();
}
- let added = false;
+ let added = 0;
+ let ownAdded = false;
+ const me = getMe();
for (const [index, message] of messages.entries()) {
const entry = painted.get(message.key);
if (entry) {
@@ -113,16 +369,39 @@ export const createMessageList = (handlers = {}) => {
}
continue;
}
+ const previous = messages[index - 1];
+ const day = dayKey(message.timestamp);
+ if (
+ day &&
+ !dividers.has(day) &&
+ (!previous || dayKey(previous.timestamp) !== day)
+ ) {
+ const node = divider(message.timestamp);
+ dividers.set(day, node);
+ items.appendChild(node);
+ }
+ if (newMarkerKey === message.key) items.appendChild(newMarker());
const element = renderMessage(message, handlers, {
- compact: continuesGroup(messages[index - 1], message),
+ // A linha "Novas mensagens" começa um grupo novo.
+ compact: newMarkerKey !== message.key && continuesGroup(previous, message),
+ me,
});
markDeparted(element);
items.appendChild(element);
painted.set(message.key, { element, message });
- added = true;
+ if (message.kind === "chat" && !message.own) added += 1;
+ else if (message.own && message.kind === "chat") ownAdded = true;
}
- if (added && stick) scrollToEnd();
+ // A sua própria mensagem sempre leva ao fim; as dos outros só
+ // quando você já estava lá (senão, contam no "N novas").
+ if (stick || ownAdded) {
+ root.scrollTop = root.scrollHeight;
+ unseen = 0;
+ } else if (added) {
+ unseen += added;
+ }
+ paintJump();
},
/**
@@ -137,6 +416,37 @@ export const createMessageList = (handlers = {}) => {
}
},
+ /**
+ * Onde começam as não lidas ao abrir uma conversa (a linha "Novas
+ * mensagens" entra antes desta mensagem no próximo desenho).
+ * @param {string | null} key
+ */
+ setNewMarker(key) {
+ newMarkerKey = key;
+ for (const node of items.querySelectorAll("[data-new-marker]")) node.remove();
+ if (!key) return;
+ const target = painted.get(key)?.element;
+ if (target) items.insertBefore(newMarker(), target);
+ },
+
+ /** Põe a linha "Novas mensagens" na tela (se houver). */
+ revealNewMarker() {
+ const marker = items.querySelector("[data-new-marker]");
+ if (marker instanceof HTMLElement) marker.scrollIntoView({ block: "center" });
+ },
+
+ /** Posição de leitura (para voltar a ela depois). */
+ position: () => ({ top: root.scrollTop, atBottom: isAtBottom() }),
+
+ /** @param {{top: number, atBottom: boolean}} position */
+ restore(position) {
+ if (position.atBottom) scrollToEnd();
+ else root.scrollTop = position.top;
+ },
+
+ /** Há mensagens novas fora da vista? */
+ hasUnseen: () => unseen > 0,
+
scrollToEnd,
};
};
diff --git a/frontend/src/ui/roomHeader.js b/frontend/src/ui/roomHeader.js
index d4b4e3b..6066052 100644
--- a/frontend/src/ui/roomHeader.js
+++ b/frontend/src/ui/roomHeader.js
@@ -2,6 +2,7 @@
import { format, strings } from "../i18n/strings.js";
import { setIcon } from "./icons.js";
+import { conversationGlyph } from "./nav/sidebarNav.js";
/**
* Nome e descrição da conversa aberta nos lugares que dependem dela:
@@ -38,6 +39,10 @@ export const createRoomHeader = () => {
if (!button.classList.contains("c-action")) button.dataset.tooltip = label;
};
+ const introGlyph = document.querySelector("[data-intro-glyph]");
+ const introTitle = document.querySelector("[data-intro-title]");
+ const introBody = document.querySelector("[data-intro-body]");
+
let lastKind = "";
return {
@@ -73,6 +78,20 @@ export const createRoomHeader = () => {
? format(strings.conversations.dmPlaceholder, { name })
: format(strings.room.placeholder, { name });
}
+ // Começo da conversa, no topo da lista (como o "começo do canal"
+ // do Fluxer e do Discord).
+ if (room && introGlyph)
+ introGlyph.replaceChildren(conversationGlyph({ ...room, unread: 0 }));
+ if (introTitle) {
+ introTitle.textContent = dm
+ ? format(strings.message.introDm, { name })
+ : format(strings.message.introRoom, { name });
+ }
+ if (introBody) {
+ introBody.textContent = dm
+ ? strings.message.introDmBody
+ : strings.message.introRoomBody;
+ }
for (const invite of invites) invite.hidden = dm || !room?.code;
const blockLabel = format(strings.conversations.block, { name });
const leaveLabel = dm ? strings.conversations.closeDm : strings.conversations.leaveRoom;
diff --git a/frontend/test/grouping.test.js b/frontend/test/grouping.test.js
index d846d65..c3fbe09 100644
--- a/frontend/test/grouping.test.js
+++ b/frontend/test/grouping.test.js
@@ -18,12 +18,19 @@ const chat = (over = {}) => ({
});
describe("agrupamento de mensagens", () => {
- test("mesma pessoa, em sequência e dentro de 5 min: agrupa", () => {
- assert.equal(continuesGroup(chat(), chat({ timestamp: "2026-11-07T10:04:59Z" })), true);
+ // Janela de 7 minutos, como no Fluxer (MessageGroupingUtils).
+ test("mesma pessoa, em sequência e dentro de 7 min: agrupa", () => {
+ assert.equal(continuesGroup(chat(), chat({ timestamp: "2026-11-07T10:06:59Z" })), true);
});
- test("depois de 5 minutos: novo grupo", () => {
- assert.equal(continuesGroup(chat(), chat({ timestamp: "2026-11-07T10:05:00Z" })), false);
+ test("depois de 7 minutos: novo grupo", () => {
+ assert.equal(continuesGroup(chat(), chat({ timestamp: "2026-11-07T10:07:00Z" })), false);
+ });
+
+ test("virou o dia: novo grupo, mesmo dentro da janela", () => {
+ const late = new Date(2026, 10, 7, 23, 58).toISOString();
+ const early = new Date(2026, 10, 8, 0, 1).toISOString();
+ assert.equal(continuesGroup(chat({ timestamp: late }), chat({ timestamp: early })), false);
});
test("outra pessoa: novo grupo", () => {
@@ -58,3 +65,15 @@ describe("mesmo @, autores diferentes", () => {
assert.equal(continuesGroup(chat(), chat({ author: 3, id: "b" })), true);
});
});
+
+describe("separadores de dia", () => {
+ const now = new Date(2026, 10, 14, 15, 0);
+ test("hoje, ontem e a data", async () => {
+ const { dayLabel } = await import("../src/ui/messageList.js");
+ assert.equal(dayLabel(new Date(2026, 10, 14, 9, 0).toISOString(), now), "Hoje");
+ assert.equal(dayLabel(new Date(2026, 10, 13, 23, 0).toISOString(), now), "Ontem");
+ assert.equal(dayLabel(new Date(2026, 10, 2, 8, 0).toISOString(), now), "2 de novembro");
+ assert.equal(dayLabel(new Date(2025, 0, 5).toISOString(), now), "5 de janeiro de 2025");
+ assert.equal(dayLabel("não é data", now), "");
+ });
+});
diff --git a/frontend/test/markdown.test.js b/frontend/test/markdown.test.js
new file mode 100644
index 0000000..439dafb
--- /dev/null
+++ b/frontend/test/markdown.test.js
@@ -0,0 +1,160 @@
+// Markdown das mensagens: subconjunto, casos de borda e entradas hostis.
+// O interpretador é puro (sem DOM) e de custo linear.
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { mentionsOf, parseInline, parseMarkdown, plainInline } from "../src/markdown/parse.js";
+
+/** Árvore compacta para comparar: [tipo, conteúdo]. */
+const compact = (nodes) =>
+ nodes.map((n) =>
+ n.type === "text"
+ ? n.text
+ : n.type === "br"
+ ? "\n"
+ : n.type === "code"
+ ? ["code", n.text]
+ : n.type === "link"
+ ? ["link", n.href]
+ : n.type === "mention"
+ ? ["@", n.username]
+ : [n.type, compact(n.children)],
+ );
+
+describe("em linha", () => {
+ const cases = [
+ ["**negrito**", [["strong", ["negrito"]]]],
+ ["*itálico*", [["em", ["itálico"]]]],
+ ["_itálico_", [["em", ["itálico"]]]],
+ ["~~riscado~~", [["del", ["riscado"]]]],
+ ["||spoiler||", [["spoiler", ["spoiler"]]]],
+ ["`a * b`", [["code", "a * b"]]],
+ [
+ "**negrito com *itálico* dentro**",
+ [["strong", ["negrito com ", ["em", ["itálico"]], " dentro"]]],
+ ],
+ ["a **b** c", ["a ", ["strong", ["b"]], " c"]],
+ ["2 * 3 * 4", ["2 * 3 * 4"]],
+ ["nome_de_variavel_aqui", ["nome_de_variavel_aqui"]],
+ ["**sem fim", ["**sem fim"]],
+ ["****", ["****"]],
+ ["\\*literal\\*", ["*literal*"]],
+ ["`sem fim", ["`sem fim"]],
+ ["linha1\nlinha2", ["linha1", "\n", "linha2"]],
+ ["**x** e **y**", [["strong", ["x"]], " e ", ["strong", ["y"]]]],
+ ];
+ for (const [input, expected] of cases) {
+ test(JSON.stringify(input), () => assert.deepEqual(compact(parseInline(input)), expected));
+ }
+});
+
+describe("links", () => {
+ test("http e https viram link; pontuação do fim fica de fora", () => {
+ assert.deepEqual(compact(parseInline("veja https://exemplo.com/a?b=1.")), [
+ "veja ",
+ ["link", "https://exemplo.com/a?b=1"],
+ ".",
+ ]);
+ assert.deepEqual(compact(parseInline("(http://x.org)")), [
+ "(",
+ ["link", "http://x.org"],
+ ")",
+ ]);
+ });
+
+ test("outros esquemas não viram link (javascript:, data:, ftp:)", () => {
+ for (const input of [
+ "javascript:alert(1)",
+ "data:text/html,oi",
+ "ftp://x.org",
+ "httpx://a",
+ ]) {
+ assert.ok(
+ parseInline(input).every((n) => n.type !== "link"),
+ `${input} não pode virar link`,
+ );
+ }
+ });
+
+ test("link no meio de palavra não é reconhecido", () => {
+ assert.ok(parseInline("xhttps://a.com").every((n) => n.type !== "link"));
+ });
+});
+
+describe("menções", () => {
+ test("@username no formato do servidor", () => {
+ assert.deepEqual(compact(parseInline("oi @ana.souza, tudo bem?")), [
+ "oi ",
+ ["@", "ana.souza"],
+ ", tudo bem?",
+ ]);
+ assert.deepEqual(compact(parseInline("fala com @bia.")), ["fala com ", ["@", "bia"], "."]);
+ });
+
+ test("e-mail e @ curto demais não são menção", () => {
+ assert.ok(parseInline("a@b.com").every((n) => n.type !== "mention"));
+ assert.ok(parseInline("@ab").every((n) => n.type !== "mention"));
+ });
+
+ test("menções de uma mensagem (fora de código)", () => {
+ assert.deepEqual(mentionsOf(parseMarkdown("@ana e `@bia`\n```\n@caio\n```")), ["ana"]);
+ });
+});
+
+describe("blocos", () => {
+ test("bloco de código: o texto vai cru, com as quebras", () => {
+ const blocks = parseMarkdown("antes\n```js\nconst a = **b**;\n if (x) {}\n```\ndepois");
+ assert.equal(blocks.length, 3);
+ assert.deepEqual(blocks[1], {
+ type: "codeblock",
+ lang: "js",
+ text: "const a = **b**;\n if (x) {}",
+ });
+ });
+
+ test("bloco de uma linha e bloco sem fim", () => {
+ assert.deepEqual(parseMarkdown("```x = 1```"), [
+ { type: "codeblock", lang: "", text: "x = 1" },
+ ]);
+ const open = parseMarkdown("```\nsem fim");
+ assert.equal(open[0]?.type, "paragraph", "sem a cerca de fechamento, vira texto");
+ });
+
+ test("citação de várias linhas", () => {
+ const blocks = parseMarkdown("> um\n> **dois**\nfora");
+ assert.equal(blocks[0]?.type, "quote");
+ assert.deepEqual(compact(/** @type {any} */ (blocks[0]).children), [
+ "um",
+ "\n",
+ ["strong", ["dois"]],
+ ]);
+ assert.equal(blocks[1]?.type, "paragraph");
+ });
+});
+
+describe("entradas hostis", () => {
+ test("tags e entidades ficam como texto (nada vira elemento)", () => {
+ const text = '
<b> ';
+ assert.deepEqual(compact(parseInline(text)), [text]);
+ });
+
+ test("aninhamento profundo é limitado e não estoura a pilha", () => {
+ const deep = "**".repeat(400) + "x" + "**".repeat(400);
+ assert.doesNotThrow(() => parseInline(deep));
+ const nested = "*_".repeat(300) + "x" + "_*".repeat(300);
+ assert.doesNotThrow(() => parseInline(nested));
+ });
+
+ test("1000 marcadores sem par: termina rápido", () => {
+ const start = performance.now();
+ parseMarkdown(`${"*".repeat(500)}${"_".repeat(250)}${"~".repeat(250)}`);
+ parseMarkdown("`".repeat(1000));
+ parseMarkdown("> ".repeat(500));
+ parseMarkdown("```\n".repeat(250));
+ assert.ok(performance.now() - start < 200, "sem explosão de tempo");
+ });
+
+ test("o texto puro devolve o que foi escrito, sem a marcação", () => {
+ assert.equal(plainInline(parseInline("**oi** _você_ @ana `x`")), "oi você @ana x");
+ });
+});
diff --git a/frontend/test/mentions.test.js b/frontend/test/mentions.test.js
new file mode 100644
index 0000000..dfeb44b
--- /dev/null
+++ b/frontend/test/mentions.test.js
@@ -0,0 +1,36 @@
+// Sugestões de "@pessoa" no campo de mensagem (decisão C3).
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { matchPeople, mentionQuery } from "../src/ui/commandSuggestions.js";
+
+const people = [
+ { id: "ana", name: "Ana Souza", username: "ana" },
+ { id: "bia", name: "Beatriz Lima", username: "bia.lima" },
+ { id: "caio", name: "Caio Ávila", username: "caio" },
+];
+
+describe("menções no campo", () => {
+ test("@ no começo de palavra, antes do cursor", () => {
+ assert.deepEqual(mentionQuery("oi @bi", 6), { start: 3, query: "bi" });
+ assert.deepEqual(mentionQuery("@", 1), { start: 0, query: "" });
+ assert.equal(mentionQuery("email@bi", 8), null, "e-mail não é menção");
+ assert.equal(mentionQuery("oi @bi agora", 12), null, "o cursor já saiu do @");
+ });
+
+ test("combina por @ ou por palavra do nome, sem acento; você fica de fora", () => {
+ assert.deepEqual(
+ matchPeople(people, "b", "ana").map((p) => p.username),
+ ["bia.lima"],
+ );
+ assert.deepEqual(
+ matchPeople(people, "avi", "ana").map((p) => p.username),
+ ["caio"],
+ "Ávila combina com avi",
+ );
+ assert.deepEqual(
+ matchPeople(people, "", "ana").map((p) => p.username),
+ ["bia.lima", "caio"],
+ );
+ });
+});