From f53013acde214bb926da4a0c54ffaed24d8a96c9 Mon Sep 17 00:00:00 2001 From: Guilherme Cruz <100307080+https-shini@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:15:47 +0000 Subject: [PATCH 1/3] =?UTF-8?q?feat(estado):=20organiza=C3=A7=C3=A3o=20da?= =?UTF-8?q?=20lista=20de=20conversas=20(fixadas,=20ordem,=20se=C3=A7=C3=B5?= =?UTF-8?q?es)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Módulo puro com as regras: fixar tira da lista de origem e desafixar devolve ao lugar; conversa nova entra no topo; mensagem nova não reordena; conversa que acaba sai das fixadas e da ordem; lista mista; filtro de não lidas; vizinha para Alt+↑/↓. Tudo em memória, pela vida da identidade (sem conta, não há como guardar entre sessões sem deixar rastro). O estado ganha a página do centro (início, comandos, perfil). --- frontend/src/state/navigation.js | 277 +++++++++++++++++++++++++++++++ frontend/src/state/store.js | 49 +++++- frontend/test/navigation.test.js | 139 ++++++++++++++++ 3 files changed, 462 insertions(+), 3 deletions(-) create mode 100644 frontend/src/state/navigation.js create mode 100644 frontend/test/navigation.test.js diff --git a/frontend/src/state/navigation.js b/frontend/src/state/navigation.js new file mode 100644 index 0000000..cbaf77c --- /dev/null +++ b/frontend/src/state/navigation.js @@ -0,0 +1,277 @@ +// @ts-check + +/** + * Organização da lista de conversas: fixadas, ordem escolhida pela pessoa, + * seções recolhidas, lista mista e filtro de não lidas. Funções puras. + * + * Regras (decisões D1 e D4 do plano): + * - Tudo vive em memória, pela vida da identidade. Não há conta para guardar + * entre sessões, e gravar ids de conversas no navegador deixaria rastro. + * - Fixar leva a conversa para "Fixadas" e a tira da lista de origem (sem + * aparecer duas vezes); desafixar a devolve ao lugar em que estava. + * - Conversa nova entra no topo da sua lista. Mensagem nova NÃO reordena: a + * ordem é da pessoa. + * - Conversa que deixa de existir some das fixadas e da ordem. + * + * O padrão de seções e de reordenar pelo teclado (pegar, mover, soltar) + * segue o que o Fluxer faz na lista de privadas e favoritos — implementação + * própria, sem código dele. + * + * @typedef {import("./store.js").ConversationEntry} ConversationEntry + * @typedef {"pinned" | "rooms" | "dms" | "all"} SectionId + * @typedef {{ + * pinned: string[], + * order: string[], + * collapsed: Record, + * mixed: boolean, + * unreadOnly: boolean, + * }} NavPrefs + * @typedef {{id: SectionId, items: ConversationEntry[], unread: number, total: number, collapsed: boolean}} Section + */ + +/** @returns {NavPrefs} */ +export const initialNav = () => ({ + pinned: [], + order: [], + collapsed: { pinned: false, rooms: false, dms: false, all: false }, + mixed: false, + unreadOnly: false, +}); + +/** @param {ConversationEntry} entry */ +const isDm = (entry) => entry.kind === "dm"; + +/** + * Garante que toda conversa existente está na ordem (as novas no topo) e + * que nada aponta para conversa que acabou. + * @param {NavPrefs} nav + * @param {ConversationEntry[]} conversations + * @returns {NavPrefs} + */ +export const reconcile = (nav, conversations) => { + const ids = new Set(conversations.map((entry) => entry.conversationId)); + const known = nav.order.filter((id) => ids.has(id)); + const knownSet = new Set(known); + // As que ainda não estão na ordem: a mais recente primeiro. + const fresh = conversations + .map((entry) => entry.conversationId) + .filter((id) => !knownSet.has(id)) + .reverse(); + const order = [...fresh, ...known]; + const pinned = nav.pinned.filter((id) => ids.has(id)); + const same = + order.length === nav.order.length && + order.every((id, i) => id === nav.order[i]) && + pinned.length === nav.pinned.length; + return same ? nav : { ...nav, order, pinned }; +}; + +/** + * As conversas na ordem da pessoa. + * @param {NavPrefs} nav + * @param {ConversationEntry[]} conversations + */ +const ordered = (nav, conversations) => { + const byId = new Map(conversations.map((entry) => [entry.conversationId, entry])); + return reconcile(nav, conversations) + .order.map((id) => byId.get(id)) + .filter(/** @returns {entry is ConversationEntry} */ (entry) => entry !== undefined); +}; + +/** + * Seções na ordem obrigatória: Fixadas, Salas, Privadas (ou, com a lista + * mista, Fixadas e Conversas). Fixadas vazia não aparece. Com o filtro de + * não lidas, só ficam as que têm não lidas — e a aberta, para a pessoa não + * perder onde está. + * @param {NavPrefs} nav + * @param {ConversationEntry[]} conversations + * @param {string | null} currentId + * @returns {Section[]} + */ +export const sectionsOf = (nav, conversations, currentId = null) => { + const byId = new Map(conversations.map((entry) => [entry.conversationId, entry])); + const pinnedSet = new Set(nav.pinned); + /** @param {ConversationEntry[]} list */ + const visible = (list) => + nav.unreadOnly + ? list.filter((entry) => entry.unread > 0 || entry.conversationId === currentId) + : list; + /** @param {SectionId} id @param {ConversationEntry[]} list @returns {Section} */ + const section = (id, list) => ({ + id, + items: visible(list), + unread: list.reduce((sum, entry) => sum + entry.unread, 0), + total: list.length, + collapsed: nav.collapsed[id], + }); + const pinned = nav.pinned + .map((id) => byId.get(id)) + .filter(/** @returns {entry is ConversationEntry} */ (entry) => entry !== undefined); + const rest = ordered(nav, conversations).filter( + (entry) => !pinnedSet.has(entry.conversationId), + ); + /** @type {Section[]} */ + const sections = []; + if (pinned.length) sections.push(section("pinned", pinned)); + if (nav.mixed) { + sections.push(section("all", rest)); + } else { + sections.push( + section( + "rooms", + rest.filter((entry) => !isDm(entry)), + ), + ); + sections.push(section("dms", rest.filter(isDm))); + } + return sections; +}; + +/** + * Conversas na ordem em que aparecem na tela (para Alt+↑/↓), sem as de + * seções recolhidas — exceto a aberta. + * @param {NavPrefs} nav + * @param {ConversationEntry[]} conversations + * @param {string | null} currentId + */ +export const visualOrder = (nav, conversations, currentId = null) => + sectionsOf({ ...nav, unreadOnly: false }, conversations, currentId).flatMap((section) => + section.collapsed + ? section.items.filter((entry) => entry.conversationId === currentId) + : section.items, + ); + +/** + * Seção em que a conversa está agora. + * @param {NavPrefs} nav + * @param {ConversationEntry | undefined} entry + * @returns {SectionId} + */ +export const sectionOf = (nav, entry) => { + if (!entry) return "rooms"; + if (nav.pinned.includes(entry.conversationId)) return "pinned"; + if (nav.mixed) return "all"; + return isDm(entry) ? "dms" : "rooms"; +}; + +/** + * Fixa ou desafixa. + * @param {NavPrefs} nav + * @param {string} id + * @param {boolean} [value] padrão: inverte + * @param {number} [at] posição em Fixadas (padrão: no fim) + * @returns {NavPrefs} + */ +export const setPinned = (nav, id, value = !nav.pinned.includes(id), at = -1) => { + const without = nav.pinned.filter((item) => item !== id); + if (!value) return { ...nav, pinned: without }; + const index = at < 0 || at > without.length ? without.length : at; + return { ...nav, pinned: [...without.slice(0, index), id, ...without.slice(index)] }; +}; + +/** + * Coloca `ids` (na nova ordem relativa) nos mesmos lugares que ocupavam em + * `order`, sem mexer nos outros. + * @param {string[]} order + * @param {string[]} ids + */ +const reslot = (order, ids) => { + const set = new Set(ids); + let next = 0; + return order.map((id) => (set.has(id) ? /** @type {string} */ (ids[next++]) : id)); +}; + +/** + * Move uma conversa para `to` (índice dentro da própria seção). + * @param {NavPrefs} nav + * @param {ConversationEntry[]} conversations + * @param {string} id + * @param {number} to + * @returns {{nav: NavPrefs, position: number, total: number, section: SectionId} | null} + */ +export const moveTo = (nav, conversations, id, to) => { + const synced = reconcile(nav, conversations); + const entry = conversations.find((item) => item.conversationId === id); + if (!entry) return null; + const section = sectionOf(synced, entry); + const list = + sectionsOf({ ...synced, unreadOnly: false }, conversations) + .find((item) => item.id === section) + ?.items.map((item) => item.conversationId) ?? []; + const from = list.indexOf(id); + if (from < 0) return null; + const target = Math.max(0, Math.min(list.length - 1, to)); + const moved = list.filter((item) => item !== id); + moved.splice(target, 0, id); + const next = + section === "pinned" + ? { ...synced, pinned: moved } + : { ...synced, order: reslot(synced.order, moved) }; + return { nav: next, position: target + 1, total: list.length, section }; +}; + +/** + * Move uma posição para cima (-1) ou para baixo (+1). + * @param {NavPrefs} nav + * @param {ConversationEntry[]} conversations + * @param {string} id + * @param {-1 | 1} delta + */ +export const moveBy = (nav, conversations, id, delta) => { + const synced = reconcile(nav, conversations); + const entry = conversations.find((item) => item.conversationId === id); + if (!entry) return null; + const section = sectionOf(synced, entry); + const list = + sectionsOf({ ...synced, unreadOnly: false }, conversations) + .find((item) => item.id === section) + ?.items.map((item) => item.conversationId) ?? []; + const from = list.indexOf(id); + if (from < 0) return null; + const to = from + delta; + if (to < 0 || to >= list.length) return null; + return moveTo(synced, conversations, id, to); +}; + +/** + * Posição da conversa dentro da seção (para habilitar "Mover para cima/baixo"). + * @param {NavPrefs} nav + * @param {ConversationEntry[]} conversations + * @param {string} id + * @returns {{index: number, total: number, section: SectionId}} + */ +export const positionOf = (nav, conversations, id) => { + const entry = conversations.find((item) => item.conversationId === id); + const section = sectionOf(nav, entry); + const list = + sectionsOf({ ...nav, unreadOnly: false }, conversations) + .find((item) => item.id === section) + ?.items.map((item) => item.conversationId) ?? []; + return { index: list.indexOf(id), total: list.length, section }; +}; + +/** + * Próxima conversa (com volta) a partir da aberta, na ordem da tela. + * @param {NavPrefs} nav + * @param {ConversationEntry[]} conversations + * @param {string | null} currentId + * @param {1 | -1} delta + * @param {{unreadOnly?: boolean}} [options] + * @returns {string | null} + */ +export const neighbor = (nav, conversations, currentId, delta, { unreadOnly = false } = {}) => { + const list = visualOrder(nav, conversations, currentId); + if (list.length === 0) return null; + const start = list.findIndex((entry) => entry.conversationId === currentId); + for (let i = 1; i <= list.length; i += 1) { + const index = + ((((start === -1 ? (delta > 0 ? -1 : 0) : start) + delta * i) % list.length) + + list.length) % + list.length; + const entry = list[index]; + if (!entry || entry.conversationId === currentId) continue; + if (unreadOnly && entry.unread === 0) continue; + return entry.conversationId; + } + return null; +}; diff --git a/frontend/src/state/store.js b/frontend/src/state/store.js index cfeb1a5..8a36605 100644 --- a/frontend/src/state/store.js +++ b/frontend/src/state/store.js @@ -1,5 +1,7 @@ // @ts-check +import { initialNav, reconcile } from "./navigation.js"; + /** * Estado observável da aplicação. Não conhece transporte nem DOM: recebe * fatos já traduzidos e avisa quem estiver ouvindo. @@ -112,6 +114,7 @@ export const authorKey = (username, author) => /** * @typedef {object} State * @property {"entry" | "home" | "room"} screen entrada, início (sem conversa aberta) ou conversa + * @property {"home" | "commands" | "profile"} page com `screen: "home"`, qual página ocupa o centro * @property {boolean} joining pediu para entrar e espera o servidor confirmar (na tela de entrada) * @property {Person | null} me * @property {"member" | "admin"} role @@ -130,6 +133,7 @@ export const authorKey = (username, author) => * @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 + * @property {import("./navigation.js").NavPrefs} nav organização da lista (fixadas, ordem, seções) — só em memória */ /** @typedef {(state: State) => void} Listener */ @@ -154,6 +158,7 @@ const HIDDEN_LIMIT = 2000; /** @returns {State} */ const initialState = () => ({ screen: "entry", + page: "home", joining: false, me: null, role: "member", @@ -172,6 +177,7 @@ const initialState = () => ({ pageVisible: true, room: null, conversations: [], + nav: initialNav(), }); /** @@ -248,7 +254,13 @@ export const createStore = () => { * @param {Partial} partial */ const patch = (partial) => { - state = { ...state, ...partial }; + const next = { ...state, ...partial }; + // A organização da lista acompanha as conversas: nova entra no topo, + // a que acabou sai das fixadas e da ordem. + if (partial.conversations && partial.conversations !== state.conversations) { + next.nav = reconcile(next.nav, next.conversations); + } + state = next; notify(); }; @@ -474,7 +486,37 @@ export const createStore = () => { goHome() { if (state.screen === "entry") return; stashActive(); - patch({ screen: "home", room: null, ...CLEAR_VIEW }); + patch({ screen: "home", page: "home", room: null, ...CLEAR_VIEW }); + }, + + /** + * Página no centro sem conversa aberta: Comandos ou Perfil. As + * conversas continuam na lista, recebendo mensagens. + * @param {"home" | "commands" | "profile"} page + */ + showPage(page) { + if (state.screen === "entry") return; + stashActive(); + patch({ screen: "home", page, room: null, ...CLEAR_VIEW }); + }, + + /** + * Muda a organização da lista (fixar, mover, recolher, misturar, + * filtrar). Só em memória. + * @param {(nav: import("./navigation.js").NavPrefs) => import("./navigation.js").NavPrefs} change + */ + updateNav(change) { + const nav = reconcile(change(state.nav), state.conversations); + if (nav !== state.nav) patch({ nav }); + }, + + /** + * Zera as não lidas de uma conversa sem abri-la ("Marcar como lida"). + * @param {string} id + */ + markRead(id) { + if (!state.conversations.some((e) => e.conversationId === id && e.unread)) return; + bumpUnread(id, 0); }, /** @@ -513,6 +555,7 @@ export const createStore = () => { patch({ conversations, screen: state.screen === "entry" ? "entry" : "home", + page: "home", room: null, ...CLEAR_VIEW, }); @@ -542,7 +585,7 @@ export const createStore = () => { */ completeLogin() { if (!state.joining) return; - patch({ screen: "home", joining: false }); + patch({ screen: "home", page: "home", joining: false }); }, /** diff --git a/frontend/test/navigation.test.js b/frontend/test/navigation.test.js new file mode 100644 index 0000000..e1a9668 --- /dev/null +++ b/frontend/test/navigation.test.js @@ -0,0 +1,139 @@ +// Organização da lista de conversas: seções, fixadas, ordem, filtro e +// navegação por teclado entre conversas. + +import { test, describe } from "node:test"; +import assert from "node:assert/strict"; +import { + initialNav, + moveBy, + moveTo, + neighbor, + positionOf, + reconcile, + sectionsOf, + setPinned, + visualOrder, +} from "../src/state/navigation.js"; + +/** @param {string} id @param {"room" | "dm"} kind @param {number} [unread] */ +const conv = (id, kind = "room", unread = 0) => ({ + conversationId: id, + kind, + name: id, + role: /** @type {"member"} */ ("member"), + unread, +}); + +// Na ordem em que chegaram do servidor: r1, d1, r2, d2, r3. +const list = [conv("r1"), conv("d1", "dm"), conv("r2", "room", 2), conv("d2", "dm", 1), conv("r3")]; +/** @param {import("../src/state/navigation.js").Section[]} sections */ +const ids = (sections) => + Object.fromEntries(sections.map((s) => [s.id, s.items.map((e) => e.conversationId)])); + +describe("seções", () => { + test("Salas e Privadas, a conversa mais nova no topo; Fixadas vazia não aparece", () => { + assert.deepEqual(ids(sectionsOf(initialNav(), list)), { + rooms: ["r3", "r2", "r1"], + dms: ["d2", "d1"], + }); + }); + + test("fixar leva para Fixadas e tira da lista de origem; desafixar devolve", () => { + let nav = reconcile(initialNav(), list); + nav = setPinned(nav, "r2"); + nav = setPinned(nav, "d1"); + assert.deepEqual(ids(sectionsOf(nav, list)), { + pinned: ["r2", "d1"], + rooms: ["r3", "r1"], + dms: ["d2"], + }); + nav = setPinned(nav, "r2", false); + assert.deepEqual(ids(sectionsOf(nav, list)).rooms, ["r3", "r2", "r1"], "volta ao lugar"); + }); + + test("lista mista junta salas e privadas, na ordem da pessoa", () => { + const nav = { ...reconcile(initialNav(), list), mixed: true }; + assert.deepEqual(ids(sectionsOf(nav, list)), { all: ["r3", "d2", "r2", "d1", "r1"] }); + }); + + test("não lidas por seção, inclusive recolhida; filtro mantém a aberta", () => { + const nav = { ...reconcile(initialNav(), list), unreadOnly: true }; + const sections = sectionsOf(nav, list, "r1"); + assert.deepEqual(ids(sections), { rooms: ["r2", "r1"], dms: ["d2"] }); + assert.equal(sections.find((s) => s.id === "rooms")?.unread, 2); + assert.equal(sections.find((s) => s.id === "rooms")?.total, 3); + }); + + test("conversa que acabou some das fixadas e da ordem; nova entra no topo", () => { + let nav = setPinned(reconcile(initialNav(), list), "r1"); + const after = [...list.filter((e) => e.conversationId !== "r1"), conv("r4")]; + nav = reconcile(nav, after); + assert.deepEqual(nav.pinned, []); + assert.ok(!nav.order.includes("r1")); + assert.equal(nav.order[0], "r4"); + }); +}); + +describe("reordenar", () => { + test("mover dentro da seção não mexe nas outras", () => { + const nav = reconcile(initialNav(), list); + const result = moveBy(nav, list, "r1", -1); + assert.ok(result); + assert.equal(result.position, 2); + assert.equal(result.total, 3); + assert.deepEqual(ids(sectionsOf(result.nav, list)), { + rooms: ["r3", "r1", "r2"], + dms: ["d2", "d1"], + }); + }); + + test("nas pontas não há para onde mover", () => { + const nav = reconcile(initialNav(), list); + assert.equal(moveBy(nav, list, "r3", -1), null); + assert.equal(moveBy(nav, list, "r1", 1), null); + }); + + test("mover em Fixadas reordena só as fixadas", () => { + let nav = setPinned(setPinned(reconcile(initialNav(), list), "r1"), "d2"); + const result = moveTo(nav, list, "d2", 0); + assert.ok(result); + nav = result.nav; + assert.deepEqual(nav.pinned, ["d2", "r1"]); + assert.equal(result.section, "pinned"); + }); + + test("posição dentro da seção", () => { + const nav = reconcile(initialNav(), list); + assert.deepEqual(positionOf(nav, list, "r2"), { index: 1, total: 3, section: "rooms" }); + }); +}); + +describe("Alt+↑/↓ entre conversas", () => { + const nav = setPinned(reconcile(initialNav(), list), "r1"); + test("ordem da tela: Fixadas, Salas, Privadas", () => { + assert.deepEqual( + visualOrder(nav, list).map((e) => e.conversationId), + ["r1", "r3", "r2", "d2", "d1"], + ); + }); + + test("anterior e seguinte, com volta", () => { + assert.equal(neighbor(nav, list, "r3", 1), "r2"); + assert.equal(neighbor(nav, list, "r1", -1), "d1"); + assert.equal(neighbor(nav, list, null, 1), "r1", "sem conversa aberta: a primeira"); + }); + + test("só não lidas (Alt+Shift)", () => { + assert.equal(neighbor(nav, list, "r1", 1, { unreadOnly: true }), "r2"); + assert.equal(neighbor(nav, list, "r2", 1, { unreadOnly: true }), "d2"); + assert.equal(neighbor(nav, list, "d2", 1, { unreadOnly: true }), "r2"); + }); + + test("seção recolhida fica de fora (menos a aberta)", () => { + const collapsed = { ...nav, collapsed: { ...nav.collapsed, dms: true } }; + assert.deepEqual( + visualOrder(collapsed, list, "d1").map((e) => e.conversationId), + ["r1", "r3", "r2", "d1"], + ); + }); +}); From 707f793ff33da838232d0a48a853740c7102dae5 Mon Sep 17 00:00:00 2001 From: Guilherme Cruz <100307080+https-shini@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:15:47 +0000 Subject: [PATCH 2/3] =?UTF-8?q?feat(navega=C3=A7=C3=A3o):=20menu=20lateral?= =?UTF-8?q?=20em=20se=C3=A7=C3=B5es,=20perfil=20no=20p=C3=A9=20e=20p=C3=A1?= =?UTF-8?q?ginas=20Comandos=20e=20Perfil?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Ordem: Início e Comandos no topo; Fixadas, Salas e Privadas no meio (única parte que rola); o perfil fixo embaixo, com nome e @ inteiros. - Seções recolhíveis com o total de não lidas; item compacto de uma linha; fixar e "⋯" ao passar o ponteiro; menu da conversa por clique direito, Shift+F10, tecla de menu e toque longo. - Reordenar arrastando (mouse) ou com Ctrl/⌘+Shift+↑/↓, com a posição anunciada; soltar em Fixadas fixa. - A lista é uma única parada de Tab (foco itinerante com setas). - "+" com nova sala, código e privada sem sair da conversa; Ir para conversa (Ctrl/⌘ K) só nas suas conversas e no @ exato; Alt+↑/↓ e Alt+Shift+↑/↓ entre conversas. - Filtro Tudo/Não lidas; aviso de não lidas fora da vista; trilho de 72 px entre 768 e 1279 px (ou quando a pessoa recolhe). - Página Comandos com o catálogo do servidor (busca, categorias, Usar) e página Perfil (nome por /nick, ausente por /afk, tema, notificações, sair). Menu rápido do perfil e menu "⋯" do cabeçalho (fixar, convite, limpar a tela, apagar para todos, sair, encerrar, bloquear). - Escape com dica aberta dentro da gaveta fecha a gaveta. - E2E 08-navegacao com 21 verificações novas. --- e2e/08-navegacao.mjs | 203 +++++++ frontend/index.html | 242 +++++--- frontend/src/css/components/avatar.css | 18 + frontend/src/css/components/nav.css | 522 +++++++++++++++++ frontend/src/css/components/pages.css | 552 ++++++++++++++++++ frontend/src/css/index.css | 2 + frontend/src/i18n/strings.js | 138 +++++ frontend/src/main.js | 739 +++++++++++++++++++++++-- frontend/src/ui/identity.js | 4 +- frontend/src/ui/nav/newConversation.js | 242 ++++++++ frontend/src/ui/nav/quickSwitcher.js | 291 ++++++++++ frontend/src/ui/nav/sidebarNav.js | 644 +++++++++++++++++++++ frontend/src/ui/pages/commandsPage.js | 183 ++++++ frontend/src/ui/pages/profilePage.js | 315 +++++++++++ frontend/src/ui/themeToggle.js | 10 +- frontend/src/ui/tooltip.js | 6 +- frontend/src/ui/userPanel.js | 40 +- 17 files changed, 3989 insertions(+), 162 deletions(-) create mode 100644 e2e/08-navegacao.mjs create mode 100644 frontend/src/css/components/nav.css create mode 100644 frontend/src/css/components/pages.css create mode 100644 frontend/src/ui/nav/newConversation.js create mode 100644 frontend/src/ui/nav/quickSwitcher.js create mode 100644 frontend/src/ui/nav/sidebarNav.js create mode 100644 frontend/src/ui/pages/commandsPage.js create mode 100644 frontend/src/ui/pages/profilePage.js diff --git a/e2e/08-navegacao.mjs b/e2e/08-navegacao.mjs new file mode 100644 index 0000000..1bcad8c --- /dev/null +++ b/e2e/08-navegacao.mjs @@ -0,0 +1,203 @@ +// Navegação nova (esquerda): ordem Início/Comandos/conversas/perfil, fixar, +// reordenar pelo teclado, seções recolhíveis com não lidas, filtro, menu da +// conversa, "+", Ctrl K, Alt+setas, páginas Comandos e Perfil, menu "⋯" do +// cabeçalho e a lista como uma única parada de Tab. +export default async ({ open, enter, createRoom, say, user, ok, axe, RUN }) => { + const ana = await open(); + await enter(ana, "Ana Souza", user("ana")); + const hashAlfa = await createRoom(ana, "Alfa"); + await createRoom(ana, "Beta"); + await createRoom(ana, "Gama"); + + const bia = await open({ hash: hashAlfa }); + await enter(bia, "Bia Lima", user("bia")); + + /** Rótulos visíveis de uma seção, na ordem da tela. */ + const sectionNames = (id) => + ana.$$eval(`.c-nav-group__list[data-section="${id}"] .c-conv__name`, (xs) => + xs.map((x) => x.textContent?.trim() ?? ""), + ); + + // Ordem da navegação: Início e Comandos antes das conversas; perfil no pé. + const order = await ana.evaluate(() => { + const nav = document.querySelector(".c-sidebar"); + const pos = (sel) => nav?.querySelector(sel)?.getBoundingClientRect().top ?? Number.NaN; + return { + home: pos("[data-go-home]"), + commands: pos("[data-go-commands]"), + list: pos("[data-conversation-tree]"), + profile: pos(".c-user-panel"), + }; + }); + ok( + order.home < order.commands && order.commands < order.list && order.list < order.profile, + "ordem: Início, Comandos, conversas e o perfil embaixo", + ); + ok( + (await sectionNames("rooms")).join(",") === "Gama,Beta,Alfa", + "conversa nova entra no topo da sua seção", + ); + + // Fixar pelo menu da conversa, só com teclado (Shift+F10). + await ana.focus('.c-conv:has-text("Beta")'); + await ana.keyboard.press("Shift+F10"); + await ana.waitForSelector('.c-menu[role="menu"]'); + ok( + await ana.evaluate(() => document.activeElement?.getAttribute("role") === "menuitem"), + "o menu abre com o foco no primeiro item", + ); + await ana.keyboard.type("Fix"); + await ana.keyboard.press("Enter"); + await ana.waitForSelector('.c-nav-group__list[data-section="pinned"] .c-conv:has-text("Beta")'); + ok( + !(await sectionNames("rooms")).includes("Beta"), + "fixada sai da lista de origem (sem aparecer duas vezes)", + ); + ok( + await ana.evaluate(() => + ( + document + .querySelector('[data-section="pinned"] .c-conv') + ?.getAttribute("aria-label") ?? "" + ).includes("fixada"), + ), + "o rótulo acessível diz que está fixada", + ); + + // Reordenar pelo teclado, com a posição anunciada. + await ana.focus('.c-conv:has-text("Gama")'); + await ana.keyboard.press("Control+Shift+ArrowDown"); + await ana.waitForFunction(() => + (document.querySelector("[data-announcer]")?.textContent ?? "").includes("posição 2 de 2"), + ); + ok((await sectionNames("rooms")).join(",") === "Alfa,Gama", "Ctrl+Shift+↓ move a conversa"); + + // Seção recolhida mostra o total de não lidas. + await ana.focus('[data-section-toggle="rooms"]'); + await ana.keyboard.press("ArrowLeft"); + await ana.waitForSelector('.c-nav-group__list[data-section="rooms"]', { state: "hidden" }); + await say(bia, `oi alfa ${RUN}`); + await ana.waitForSelector('[data-section-toggle="rooms"] .c-nav-group__badge'); + ok( + (await ana.textContent('[data-section-toggle="rooms"] .c-nav-group__badge'))?.trim() === + "1", + "seção recolhida mostra 1 não lida", + ); + await ana.keyboard.press("ArrowRight"); + await ana.waitForSelector('.c-nav-group__list[data-section="rooms"]'); + + // Filtro "Não lidas". + await ana.click('[data-nav-filter="unread"]'); + await ana + .waitForFunction( + () => !document.querySelector('.c-sidebar .c-conv[aria-label^="Beta"]'), + null, + { timeout: 3000 }, + ) + .catch(() => {}); + const unreadOnly = await ana.$$eval(".c-sidebar .c-conv__name", (xs) => + xs.map((x) => x.textContent?.trim()), + ); + ok( + unreadOnly.includes("Alfa") && !unreadOnly.includes("Beta"), + `filtro mostra só as não lidas (e a aberta): ${unreadOnly.join(", ")}`, + ); + await ana.click('[data-nav-filter="all"]'); + + // A lista é uma parada de Tab: entra uma vez, sai na próxima. + await ana.focus("[data-go-commands]"); + await ana.keyboard.press("Tab"); + await ana.keyboard.press("Tab"); + await ana.keyboard.press("Tab"); + const inTree = await ana.evaluate( + () => + document.querySelector("[data-conversation-tree]")?.contains(document.activeElement) ?? + false, + ); + await ana.keyboard.press("Tab"); + const leftTree = await ana.evaluate( + () => + !( + document + .querySelector("[data-conversation-tree]") + ?.contains(document.activeElement) ?? true + ), + ); + ok(inTree && leftTree, "a lista de conversas é uma única parada de Tab"); + + // Ctrl K: ir para conversa pelo nome. + await ana.focus("#campo-mensagem"); + await ana.keyboard.press("Control+k"); + await ana.waitForSelector(".c-quick[open]"); + ok((await axe(ana)).length === 0, "Ir para conversa sem violações sérias"); + await ana.keyboard.type("alf"); + await ana.keyboard.press("Enter"); + await ana.waitForFunction( + () => document.querySelector(".c-header__title")?.textContent?.trim() === "Alfa", + ); + ok(true, "Ctrl K abre a conversa escolhida"); + + // Alt+↓: próxima conversa na ordem da tela (Fixadas → Salas → Privadas). + await ana.keyboard.press("Alt+ArrowDown"); + await ana.waitForFunction( + () => document.querySelector(".c-header__title")?.textContent?.trim() === "Gama", + ); + ok(true, "Alt+↓ vai para a conversa seguinte"); + + // "+": nova sala sem ir ao início. + await ana.click("[data-nav-new]"); + await ana.fill("#nova-sala-nome", "Delta"); + await ana.keyboard.press("Enter"); + await ana.waitForFunction( + () => document.querySelector(".c-header__title")?.textContent?.trim() === "Delta", + ); + ok(true, "o + cria e abre uma sala sem passar pelo início"); + + // Menu "⋯" do cabeçalho: limpar a minha tela. + await say(ana, `para limpar ${RUN}`); + await ana.waitForSelector(`.c-message:has-text("para limpar ${RUN}")`); + await ana.click("[data-conversation-menu]"); + await ana.click('.c-menu__item:has-text("Limpar minha tela")'); + await ana.waitForSelector(`.c-message:has-text("para limpar ${RUN}")`, { state: "detached" }); + ok(true, "menu do cabeçalho: limpar minha tela"); + + // Página Comandos: catálogo do servidor e "Usar". + await ana.click("[data-go-commands]"); + await ana.waitForSelector('[data-page="commands"]:not([hidden]) .c-command-card'); + ok( + (await ana.$$('[data-page="commands"] .c-command-card')).length > 10, + "página Comandos mostra o catálogo", + ); + ok((await axe(ana)).length === 0, "página Comandos sem violações sérias"); + await ana.fill("#comandos-busca", "dado"); + await ana.click('.c-command-card:has-text("/roll") button:has-text("Usar")'); + await ana.waitForSelector('.c-app[data-screen="room"]'); + ok((await ana.inputValue("#campo-mensagem")) === "/roll ", "Usar põe o comando no campo"); + + // Menu do perfil: ficar ausente (comando real /afk). + await ana.click("[data-profile-menu]"); + await ana.click('.c-menu__item:has-text("Ausente") >> nth=0'); + await ana.waitForFunction(() => + (document.querySelector(".c-user-panel__status")?.textContent ?? "").includes("Ausente"), + ); + ok(true, "menu do perfil: ausente"); + + // Página Perfil. + await ana.click("[data-go-profile]"); + await ana.waitForSelector('[data-page="profile"]:not([hidden])'); + ok( + (await ana.getAttribute( + '[data-page="profile"] [role="switch"] >> nth=0', + "aria-checked", + )) === "true", + "a página Perfil mostra o status ausente", + ); + ok((await axe(ana)).length === 0, "página Perfil sem violações sérias"); + + // Sair de uma sala pelo menu da conversa. + await ana.click('.c-conv:has-text("Gama")', { button: "right" }); + await ana.click('.c-menu__item:has-text("Sair da sala")'); + await ana.click(".c-dialog__confirm"); + await ana.waitForSelector('.c-sidebar .c-conv:has-text("Gama")', { state: "detached" }); + ok(true, "sair da sala pelo menu da conversa"); +}; diff --git a/frontend/index.html b/frontend/index.html index 4779c1b..9ad9726 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -77,13 +77,38 @@ ui/icons.js (uma fonte só para HTML e JS). -->
- -