diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 25d5655..e181557 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -55,8 +55,8 @@ jobs: - name: Testes run: npm test - # Bloqueante: dependências que vão para produção (o backend; o - # frontend não tem dependência de runtime). + # Bloqueante: dependências que vão para produção (o backend e a + # única dependência de runtime do frontend, @floating-ui/dom). - name: Auditoria de dependências de produção run: | npm audit --omit=dev --audit-level=high diff --git a/README.md b/README.md index 451b268..f55ab9a 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,9 @@ sessão acaba. O objetivo técnico é mostrar comunicação em tempo real, um design system com acessibilidade verificada e dois temas usando apenas HTML, CSS e JavaScript -nativos no navegador — **nenhuma dependência de runtime no frontend**. +nativos no navegador — **uma única dependência de runtime no frontend**: +[`@floating-ui/dom`](https://floating-ui.com/) (MIT, versão fixa), que posiciona +menus e cartões junto de quem os abriu. ## Funcionalidades @@ -109,8 +111,8 @@ Nenhum destes itens está implementado. | Camada | Tecnologia | | -------------- | -------------------------------------------------------------------------------------------------- | -| Frontend | HTML, CSS (custom properties, BEM), JavaScript ES2022 com JSDoc | -| Build / dev | [Vite](https://vitejs.dev/) 5 | +| Frontend | HTML, CSS (custom properties, BEM), JavaScript ES2022 com JSDoc; `@floating-ui/dom` 1.6.13 (MIT) | +| Build / dev | [Vite](https://vitejs.dev/) 6 | | Backend | Node.js, [`ws`](https://github.com/websockets/ws) 8, `dotenv` | | Qualidade | ESLint 9, Stylelint 16, TypeScript (só checagem de tipos), Prettier 3, script próprio de contraste | | CI / segurança | GitHub Actions, CodeQL | diff --git a/frontend/index.html b/frontend/index.html index dec5260..4779c1b 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -24,7 +24,7 @@ @@ -65,7 +65,7 @@ --> - web-chat · sala aberta + web-chat Ir para a conversa @@ -213,7 +213,7 @@

Conexão

-

Sala aberta · tempo real

+

Tempo real · sem cadastro

Converse agora. Sem cadastro, sem rastro.

@@ -280,7 +280,7 @@

-

Entrar na sala

+

Entrar

Como as pessoas vão ver você.

Entrar na sala

class="c-field__hint c-entry__username-hint" id="campo-username-ajuda" > - Único na sala. Letras minúsculas, números, ponto ou _. + Único entre quem está conectado. Letras minúsculas, números, + ponto ou _.

Entrar na sala class="c-button c-button--primary c-button--block c-button--large c-entry__submit" > - Entrar na sala + Entrar diff --git a/frontend/src/css/components/composer.css b/frontend/src/css/components/composer.css index d022445..640443a 100644 --- a/frontend/src/css/components/composer.css +++ b/frontend/src/css/components/composer.css @@ -21,10 +21,13 @@ box-shadow var(--duration-fast) var(--ease-standard); } -/* O campo em si não desenha anel: o composer inteiro mostra o foco. */ +/* O campo em si não desenha anel: o composer inteiro mostra o foco, com + borda neutra e halo carmim suave (antes era uma borda vermelha forte, que + competia com a conversa durante a digitação contínua). O contraste da + borda de controle continua acima de 3:1 (1.4.11). */ .c-composer:focus-within { - border-color: var(--color-focus-ring); - box-shadow: 0 0 0 var(--halo-width) var(--color-brand-soft); + border-color: var(--color-outline-control); + box-shadow: 0 0 0 var(--halo-width) color-mix(in srgb, var(--color-focus-ring) 35%, transparent); } .c-composer__input { diff --git a/frontend/src/css/components/menu.css b/frontend/src/css/components/menu.css new file mode 100644 index 0000000..a1c9c96 --- /dev/null +++ b/frontend/src/css/components/menu.css @@ -0,0 +1,175 @@ +/* Menu de ações (padrão "menu" do APG): flutuante no desktop, folha + inferior no celular. Posição pelo @floating-ui/dom (left/top via CSSOM). */ + +.c-menu { + position: fixed; + z-index: var(--z-menu); + top: 0; + left: 0; + display: flex; + flex-direction: column; + min-width: var(--menu-min-width); + max-width: min(20rem, calc(100vw - var(--space-4))); + overflow: auto; + padding: var(--space-1-5); + border: var(--rule-1) solid var(--color-border-subtle); + border-radius: var(--radius-lg); + background-color: var(--color-bg-elevated); + color: var(--color-text-2); + box-shadow: var(--shadow-3); + animation: pop-in var(--duration-base) var(--ease-out); +} + +.c-menu__list { + display: flex; + flex-direction: column; +} + +.c-menu__item { + display: flex; + gap: var(--space-3); + align-items: center; + width: 100%; + min-height: var(--menu-item-height); + padding: var(--space-1-5) var(--space-2); + border: 0; + border-radius: var(--radius-sm); + background: transparent; + color: inherit; + font: inherit; + font-size: var(--text-sm); + text-align: start; + cursor: pointer; +} + +.c-menu__item:hover, +.c-menu__item:focus-visible, +.c-menu__item:focus { + outline: none; + background-color: var(--color-bg-selected); + color: var(--color-text-1); +} + +.c-menu__item:focus-visible { + box-shadow: inset 0 0 0 var(--rule-2) var(--color-focus-ring); +} + +.c-menu__item[aria-disabled="true"] { + color: var(--color-text-disabled); + cursor: default; +} + +.c-menu__item[aria-disabled="true"]:hover, +.c-menu__item[aria-disabled="true"]:focus { + background-color: transparent; +} + +.c-menu__item--danger { + color: var(--color-danger-text); +} + +.c-menu__item--danger:hover, +.c-menu__item--danger:focus { + color: var(--color-danger-text); +} + +.c-menu__icon { + display: inline-flex; + flex: none; + width: var(--text-lg); + font-size: var(--text-lg); +} + +.c-menu__text { + flex: 1 1 auto; + min-width: 0; +} + +.c-menu__hint { + flex: none; + color: var(--color-text-3); + font-size: var(--text-xs); +} + +.c-menu__chevron { + display: inline-flex; + flex: none; + color: var(--color-text-3); +} + +.c-menu__separator { + height: var(--rule-1); + margin: var(--space-1-5) var(--space-1); + background-color: var(--color-border-subtle); +} + +.c-menu__label { + padding: var(--space-1-5) var(--space-2) var(--space-0-5); + color: var(--color-text-3); + font-size: var(--text-2xs); + font-weight: var(--weight-semibold); + letter-spacing: var(--tracking-caps); + text-transform: uppercase; +} + +.c-menu__title, +.c-menu__grabber { + display: none; +} + +/* ─── Folha inferior (celular) ─────────────────────────────────────── */ +.c-menu-sheet { + position: fixed; + inset: 0; + z-index: var(--z-menu); +} + +.c-menu-sheet__scrim { + position: absolute; + inset: 0; + background-color: var(--color-scrim); + opacity: var(--opacity-scrim); +} + +.c-menu--sheet { + position: absolute; + inset: auto 0 0; + max-width: none; + max-height: 80dvh; + padding: var(--space-2) var(--space-2) calc(var(--space-3) + env(safe-area-inset-bottom)); + border-radius: var(--radius-lg) var(--radius-lg) 0 0; + animation: sheet-up var(--duration-slow) var(--ease-out); +} + +.c-menu--sheet .c-menu__item { + min-height: var(--tap-comfort); + font-size: var(--text-md); +} + +.c-menu--sheet .c-menu__grabber { + display: block; + width: var(--space-10); + height: var(--space-1); + margin: var(--space-0) auto var(--space-2); + border-radius: var(--radius-full); + background-color: var(--color-border-subtle); +} + +.c-menu--sheet .c-menu__title { + display: block; + padding: var(--space-1) var(--space-2) var(--space-2); + color: var(--color-text-3); + font-size: var(--text-xs); + font-weight: var(--weight-semibold); +} + +/* Submenu no celular: substitui a folha, por cima. */ +.c-menu--sheet.c-menu--sub { + z-index: 1; +} + +@keyframes sheet-up { + from { + transform: translateY(100%); + } +} diff --git a/frontend/src/css/components/toast.css b/frontend/src/css/components/toast.css index 297487c..b77ebed 100644 --- a/frontend/src/css/components/toast.css +++ b/frontend/src/css/components/toast.css @@ -1,9 +1,11 @@ -/* Avisos temporários, no canto inferior direito (centro em telas estreitas). */ +/* Avisos temporários, no alto à direita, logo abaixo do cabeçalho: nunca + em cima do campo de mensagem nem do botão de enviar (antes ficavam no + canto inferior e cobriam o botão). Em telas estreitas, no alto, centrados. */ .c-toasts { position: fixed; + top: calc(var(--header-height) + var(--space-3)); right: var(--space-4); - bottom: var(--space-4); z-index: var(--z-toast); display: flex; flex-direction: column; @@ -46,8 +48,8 @@ @media (max-width: 30rem) { .c-toasts { + top: calc(var(--header-height) + var(--space-2)); right: var(--space-2); - bottom: var(--space-16); left: var(--space-2); align-items: stretch; } diff --git a/frontend/src/css/index.css b/frontend/src/css/index.css index 754a923..f4dcc5f 100644 --- a/frontend/src/css/index.css +++ b/frontend/src/css/index.css @@ -54,6 +54,7 @@ /* camadas flutuantes */ @import url("./components/member-card.css"); +@import url("./components/menu.css"); @import url("./components/dialog.css"); @import url("./components/tooltip.css"); @import url("./components/toast.css"); diff --git a/frontend/src/css/tokens.css b/frontend/src/css/tokens.css index 20cb909..657e12d 100644 --- a/frontend/src/css/tokens.css +++ b/frontend/src/css/tokens.css @@ -260,6 +260,7 @@ --z-drawer: 50; --z-overlay: 100; --z-popover: 200; + --z-menu: 300; /* menus de contexto: acima de cartões e gavetas */ --z-toast: 1000; /* Alvos de toque (2.5.8) */ @@ -312,6 +313,14 @@ --avatar-lg: 2.5rem; /* 40px */ --avatar-xl: 5rem; /* 80px */ --measure-message: 70ch; + /* Arquitetura em três áreas (navegação | conversa | contexto). */ + --layout-nav-width: 17rem; /* 272px */ + --layout-rail-width: 4.5rem; /* 72px — navegação recolhida */ + --layout-panel-width: 21.25rem; /* 340px — painel de contexto */ + --layout-main-min: 30rem; /* abaixo disso o painel vira folha */ + --nav-item-height: 2.25rem; /* 36px — item de conversa de uma linha */ + --menu-min-width: 13.75rem; /* 220px */ + --menu-item-height: 2.25rem; --gutter-message: 4.5rem; /* coluna do avatar nas mensagens */ } diff --git a/frontend/src/i18n/strings.js b/frontend/src/i18n/strings.js index e4d61ba..c9a0d2d 100644 --- a/frontend/src/i18n/strings.js +++ b/frontend/src/i18n/strings.js @@ -6,11 +6,11 @@ */ export const strings = { entry: { - submit: "Entrar na sala", + submit: "Entrar", submitting: "Entrando…", nameRequired: "Escreva seu nome completo para entrar.", usernameRequired: "Escolha um nome de usuário para entrar.", - usernameHint: "Único na sala. Letras minúsculas, números, ponto ou _.", + usernameHint: "Único entre quem está conectado. Letras minúsculas, números, ponto ou _.", usernameSuggested: "Sugerido a partir do seu nome. Você pode trocar.", usernameValid: "Formato válido. A disponibilidade é conferida ao entrar.", usernameChars: "Use só letras minúsculas sem acento, números, ponto ou _.", diff --git a/frontend/src/ui/icons.js b/frontend/src/ui/icons.js index 96161d3..aa186f4 100644 --- a/frontend/src/ui/icons.js +++ b/frontend/src/ui/icons.js @@ -71,6 +71,47 @@ const SHAPES = { megaphone: [p("m3 11 18-5v12L3 14v-3z"), p("M11.6 16.8a3 3 0 1 1-5.8-1.6")], shield: [p("M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z")], pencil: [p("M17 3a2.85 2.85 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5z")], + pin: [p("M9 4h6l-1 6 3 3H7l3-3z"), p("M12 13v8")], + dots: [c(5, 12, 1), c(12, 12, 1), c(19, 12, 1)], + "chevron-right": [p("m9 6 6 6-6 6")], + "chevron-down": [p("m6 9 6 6 6-6")], + "chevron-left": [p("m15 6-6 6 6 6")], + "arrow-up": [p("M12 19V5"), p("m6 11 6-6 6 6")], + "arrow-down": [p("M12 5v14"), p("m6 13 6 6 6-6")], + search: [c(11, 11, 7), p("m20 20-4.35-4.35")], + reply: [p("M9 14 4 9l5-5"), p("M4 9h10a6 6 0 0 1 6 6v3")], + smile: [c(12, 12, 9), p("M8 14a5 5 0 0 0 8 0"), p("M9 9h.01"), p("M15 9h.01")], + settings: [ + c(12, 12, 3), + p( + "M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z", + ), + ], + link: [ + p("M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"), + p("M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"), + ], + bold: [p("M7 5h6a3.5 3.5 0 0 1 0 7H7z"), p("M7 12h7a3.5 3.5 0 0 1 0 7H7z")], + italic: [p("M19 4h-9"), p("M14 20H5"), p("M15 4 9 20")], + code: [p("m8 8-4 4 4 4"), p("m16 8 4 4-4 4")], + "eye-off": [ + p("M9.88 9.88a3 3 0 1 0 4.24 4.24"), + p("M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"), + p("M6.61 6.61A13.53 13.53 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"), + p("M2 2l20 20"), + ], + "panel-right": [ + ["rect", { x: "3", y: "4", width: "18", height: "16", rx: "2" }], + p("M15 4v16"), + ], + sidebar: [["rect", { x: "3", y: "4", width: "18", height: "16", rx: "2" }], p("M9 4v16")], + "bell-off": [ + p("M8.7 3A6 6 0 0 1 18 8a21.3 21.3 0 0 0 .6 5"), + p("M17 17H3s3-2 3-9a4.67 4.67 0 0 1 .3-1.7"), + p("M10.3 21a1.94 1.94 0 0 0 3.4 0"), + p("m2 2 20 20"), + ], + "corner-down-left": [p("M20 4v7a4 4 0 0 1-4 4H4"), p("m9 10-5 5 5 5")], }; /** O logotipo é preenchido, não traçado: uma bolha de conversa. */ diff --git a/frontend/src/ui/memberCard.js b/frontend/src/ui/memberCard.js index e7f7fc6..bbe45e0 100644 --- a/frontend/src/ui/memberCard.js +++ b/frontend/src/ui/memberCard.js @@ -4,6 +4,7 @@ import { format, strings } from "../i18n/strings.js"; import { el, must } from "./dom.js"; import { badge, hueFor, renderIdentity } from "./identity.js"; import { icon } from "./icons.js"; +import { anchorTo } from "./primitives/position.js"; /** * Cartão de pessoa: popover não modal aberto a partir do painel de pessoas. @@ -49,10 +50,14 @@ export const createMemberCard = ({ /** @type {HTMLButtonElement | null} */ let trigger = null; + /** Para de acompanhar a posição (cartão fechado). */ + let unanchor = () => {}; /** @param {{restoreFocus?: boolean}} [options] */ const close = ({ restoreFocus = true } = {}) => { if (card.hidden) return; + unanchor(); + unanchor = () => {}; card.hidden = true; trigger?.setAttribute("aria-expanded", "false"); if (restoreFocus && trigger?.isConnected) trigger.focus(); @@ -180,21 +185,21 @@ export const createMemberCard = ({ return list; }; - /** Posiciona ao lado do botão; em tela estreita o CSS vira folha. */ + /** + * Posiciona ao lado do botão com o @floating-ui/dom (vira para o outro + * lado e desliza na tela quando falta espaço, e acompanha a rolagem). + * Em tela estreita o CSS faz do cartão uma folha presa à base. + */ const place = () => { + unanchor(); + unanchor = () => {}; if (!trigger || window.matchMedia("(max-width: 47.99rem)").matches) { card.style.removeProperty("top"); card.style.removeProperty("left"); + card.style.removeProperty("max-height"); return; } - const box = trigger.getBoundingClientRect(); - const size = card.getBoundingClientRect(); - const gap = 12; - let left = box.left - size.width - gap; - if (left < gap) left = Math.min(box.right + gap, window.innerWidth - size.width - gap); - const top = Math.min(Math.max(gap, box.top), window.innerHeight - size.height - gap); - card.style.left = `${Math.round(left)}px`; - card.style.top = `${Math.round(top)}px`; + unanchor = anchorTo(trigger, card, { placement: "left-start", gap: 12, minHeight: 200 }); }; // Captura: o Escape fecha o cartão antes de chegar à gaveta embaixo dele. @@ -213,7 +218,8 @@ export const createMemberCard = ({ if (card.contains(event.target) || trigger?.contains(event.target)) return; close({ restoreFocus: false }); }); - window.addEventListener("resize", () => close({ restoreFocus: false })); + // Mudança de tamanho (inclusive o teclado virtual abrindo) só + // reposiciona: o cartão não fecha mais sozinho. return { /** diff --git a/frontend/src/ui/primitives/contextMenu.js b/frontend/src/ui/primitives/contextMenu.js new file mode 100644 index 0000000..6f2da86 --- /dev/null +++ b/frontend/src/ui/primitives/contextMenu.js @@ -0,0 +1,95 @@ +// @ts-check + +import { showMenu } from "./menu.js"; + +/** + * Liga o menu de contexto a uma área: clique direito, Shift+F10, a tecla de + * menu do teclado e o toque longo (celular) abrem o MESMO menu que o botão + * "⋯" de cada item — como no Fluxer, um menu por entidade. + * + * `resolve` recebe o elemento-alvo e diz qual menu abrir (ou `null`, e o + * menu do navegador continua valendo, por exemplo dentro de um campo). + * + * @param {HTMLElement} container + * @param {{ + * selector: string, + * resolve: (target: HTMLElement) => {items: import("./menuModel.js").MenuItem[], label: string} | null, + * }} options + */ +export const bindContextMenu = (container, { selector, resolve }) => { + /** @param {HTMLElement} target @param {{x: number, y: number} | null} point */ + const open = (target, point) => { + const menu = resolve(target); + if (!menu || menu.items.length === 0) return false; + showMenu({ + ...menu, + point, + anchor: point ? null : target, + placement: "bottom-start", + returnFocus: target, + }); + return true; + }; + + container.addEventListener("contextmenu", (event) => { + const target = /** @type {Element | null} */ (event.target); + // Seleção de texto e campos mantêm o menu do navegador (copiar, colar). + if (target?.closest("input, textarea, [contenteditable='true'], a[href]")) return; + if (window.getSelection()?.toString()) return; + const host = target?.closest(selector); + if (!(host instanceof HTMLElement) || !container.contains(host)) return; + if (open(host, { x: event.clientX, y: event.clientY })) event.preventDefault(); + }); + + container.addEventListener("keydown", (event) => { + const isMenuKey = event.key === "ContextMenu" || (event.key === "F10" && event.shiftKey); + if (!isMenuKey) return; + const target = /** @type {Element | null} */ (event.target); + const host = target?.closest(selector); + if (!(host instanceof HTMLElement)) return; + if (open(host, null)) event.preventDefault(); + }); + + // Toque longo: 500 ms parado (até 8 px). O clique que vem depois é + // engolido, para não abrir a conversa ou a pessoa por baixo do menu. + /** @type {ReturnType | null} */ + let timer = null; + let startX = 0; + let startY = 0; + let fired = false; + const cancel = () => { + if (timer) clearTimeout(timer); + timer = null; + }; + container.addEventListener("pointerdown", (event) => { + if (event.pointerType !== "touch") return; + const target = /** @type {Element | null} */ (event.target); + if (target?.closest("input, textarea, [contenteditable='true']")) return; + const host = target?.closest(selector); + if (!(host instanceof HTMLElement)) return; + fired = false; + startX = event.clientX; + startY = event.clientY; + cancel(); + timer = setTimeout(() => { + timer = null; + fired = open(host, { x: startX, y: startY }); + if (fired) navigator.vibrate?.(10); + }, 500); + }); + container.addEventListener("pointermove", (event) => { + if (timer && Math.hypot(event.clientX - startX, event.clientY - startY) > 8) cancel(); + }); + container.addEventListener("pointerup", cancel); + container.addEventListener("pointercancel", cancel); + container.addEventListener( + "click", + (event) => { + if (!fired) return; + fired = false; + event.preventDefault(); + event.stopPropagation(); + }, + true, + ); +}; diff --git a/frontend/src/ui/primitives/menu.js b/frontend/src/ui/primitives/menu.js new file mode 100644 index 0000000..923d07a --- /dev/null +++ b/frontend/src/ui/primitives/menu.js @@ -0,0 +1,375 @@ +// @ts-check + +import { el } from "../dom.js"; +import { icon } from "../icons.js"; +import { first, isFocusable, move, tidy, typeahead } from "./menuModel.js"; +import { anchorTo, pointAnchor } from "./position.js"; + +/** + * Menu (padrão "menu" do APG) para ações de mensagens, pessoas e conversas. + * + * - Desktop: menu flutuante preso à âncora (botão "⋯") ou ao ponto do + * clique direito, posicionado pelo `@floating-ui/dom`. + * - Celular (até 767 px): o mesmo menu vira uma folha inferior, como no + * Fluxer (`menu_bottom_sheet`), com fundo escurecido e área de toque maior. + * + * Teclado: setas, Home/End, letras (busca), Enter/Espaço, → abre submenu, + * ← ou Escape fecha o submenu, Escape fecha o menu e devolve o foco a quem + * abriu, Tab fecha e segue o fluxo normal. + * + * Só um menu fica aberto por vez. Nada de HTML: rótulos entram como texto. + * + * @typedef {import("./menuModel.js").MenuItem} MenuItem + * @typedef {{ + * items: MenuItem[], + * label: string, + * anchor?: Element | null, + * point?: {x: number, y: number} | null, + * placement?: import("@floating-ui/dom").Placement, + * returnFocus?: HTMLElement | null, + * onClose?: () => void, + * }} MenuOptions + */ + +/** Largura em que o menu vira folha inferior. */ +const SHEET_QUERY = "(max-width: 47.99rem)"; + +/** @type {{close: (options?: {restoreFocus?: boolean}) => void} | null} */ +let openMenu = null; + +/** Fecha o menu aberto (se houver). */ +export const closeMenus = () => openMenu?.close({ restoreFocus: false }); + +/** Há um menu aberto? */ +export const isMenuOpen = () => openMenu !== null; + +/** + * Desenha a lista de itens. Devolve os botões, alinhados aos itens. + * @param {HTMLElement} list + * @param {MenuItem[]} items + * @returns {(HTMLElement | null)[]} + */ +const paint = (list, items) => { + list.replaceChildren(); + return items.map((item) => { + const type = item.type ?? "item"; + if (type === "separator") { + list.appendChild( + el("div", { class: "c-menu__separator", attrs: { role: "separator" } }), + ); + return null; + } + if (type === "label") { + list.appendChild( + el("div", { + class: "c-menu__label", + text: item.label ?? "", + attrs: { role: "presentation" }, + }), + ); + return null; + } + const role = type === "check" ? "menuitemcheckbox" : "menuitem"; + const button = el("button", { + class: `c-menu__item${item.danger ? " c-menu__item--danger" : ""}`, + attrs: { type: "button", role, tabindex: "-1" }, + }); + if (type === "check") button.setAttribute("aria-checked", String(Boolean(item.checked))); + if (type === "submenu") { + button.setAttribute("aria-haspopup", "menu"); + button.setAttribute("aria-expanded", "false"); + } + if (item.disabled) button.setAttribute("aria-disabled", "true"); + const glyph = el("span", { class: "c-menu__icon" }); + if (type === "check") { + if (item.checked) glyph.appendChild(icon("check")); + } else if (item.icon) glyph.appendChild(icon(item.icon)); + glyph.setAttribute("aria-hidden", "true"); + button.appendChild(glyph); + button.appendChild(el("span", { class: "c-menu__text", text: item.label ?? "" })); + if (item.hint) { + button.appendChild( + el("span", { + class: "c-menu__hint", + text: item.hint, + attrs: { "aria-hidden": "true" }, + }), + ); + } + if (type === "submenu") { + const chevron = el("span", { class: "c-menu__chevron" }); + chevron.appendChild(icon("chevron-right")); + chevron.setAttribute("aria-hidden", "true"); + button.appendChild(chevron); + } + list.appendChild(button); + return button; + }); +}; + +/** + * Abre um menu. Fecha o anterior, se houver. + * @param {MenuOptions} options + * @returns {{close: (options?: {restoreFocus?: boolean}) => void}} + */ +export const showMenu = ({ + items: rawItems, + label, + anchor = null, + point = null, + placement = "bottom-start", + returnFocus = null, + onClose = () => {}, +}) => { + openMenu?.close({ restoreFocus: false }); + const items = tidy(rawItems); + const asSheet = window.matchMedia(SHEET_QUERY).matches; + const previousFocus = + returnFocus ?? + (document.activeElement instanceof HTMLElement ? document.activeElement : null); + + const host = el("div", { class: asSheet ? "c-menu-sheet" : "c-menu-layer" }); + const scrim = asSheet ? el("div", { class: "c-menu-sheet__scrim" }) : null; + const panel = el("div", { + class: asSheet ? "c-menu c-menu--sheet" : "c-menu", + attrs: { role: "menu", "aria-label": label }, + }); + if (asSheet) { + panel.appendChild( + el("div", { class: "c-menu__grabber", attrs: { "aria-hidden": "true" } }), + ); + panel.appendChild( + el("p", { class: "c-menu__title", text: label, attrs: { "aria-hidden": "true" } }), + ); + } + const list = el("div", { class: "c-menu__list" }); + panel.appendChild(list); + if (scrim) host.appendChild(scrim); + host.appendChild(panel); + document.body.appendChild(host); + + /** Submenu aberto: o painel, os itens e o botão que o abriu. */ + /** @type {{panel: HTMLElement, items: MenuItem[], buttons: (HTMLElement | null)[], index: number, owner: HTMLElement, stop: () => void} | null} */ + let sub = null; + + let buttons = paint(list, items); + let index = -1; + let buffer = ""; + /** @type {ReturnType | null} */ + let bufferTimer = null; + + /** @param {(HTMLElement | null)[]} list @param {number} i */ + const focusAt = (list, i) => { + const button = list[i]; + if (button) button.focus(); + }; + + const closeSub = (restore = true) => { + if (!sub) return; + sub.stop(); + sub.panel.remove(); + sub.owner.setAttribute("aria-expanded", "false"); + if (restore) sub.owner.focus(); + sub = null; + }; + + /** @param {number} i */ + const openSub = (i) => { + const item = items[i]; + const owner = buttons[i]; + if (!item || !owner || (item.type ?? "item") !== "submenu") return; + closeSub(false); + const subItems = tidy(item.items ?? []); + const subPanel = el("div", { + class: asSheet ? "c-menu c-menu--sheet c-menu--sub" : "c-menu c-menu--sub", + attrs: { role: "menu", "aria-label": item.label ?? "" }, + }); + const subList = el("div", { class: "c-menu__list" }); + subPanel.appendChild(subList); + host.appendChild(subPanel); + const subButtons = paint(subList, subItems); + owner.setAttribute("aria-expanded", "true"); + const stop = asSheet + ? () => {} + : anchorTo(owner, subPanel, { placement: "right-start", gap: 2 }); + sub = { + panel: subPanel, + items: subItems, + buttons: subButtons, + index: first(subItems), + owner, + stop, + }; + focusAt(subButtons, sub.index); + }; + + /** @param {MenuItem} item */ + const activate = (item) => { + if (!item || item.disabled) return; + const type = item.type ?? "item"; + if (type === "submenu") return; + close({ restoreFocus: true }); + item.run?.(); + }; + + /** @param {KeyboardEvent} event */ + const onKey = (event) => { + const inSub = sub !== null && sub.panel.contains(/** @type {Node} */ (event.target)); + const current = inSub && sub ? sub : { items, buttons, index }; + if (event.key === "Escape" || (inSub && event.key === "ArrowLeft")) { + event.preventDefault(); + event.stopPropagation(); + if (inSub) closeSub(true); + else close({ restoreFocus: true }); + return; + } + if (event.key === "Tab") { + close({ restoreFocus: false }); + return; + } + const next = move(event.key, current.items, current.index); + if (next !== null) { + event.preventDefault(); + if (next >= 0) { + if (inSub && sub) sub.index = next; + else index = next; + focusAt(current.buttons, next); + } + return; + } + const item = current.items[current.index]; + if (event.key === "ArrowRight" && !inSub && item && (item.type ?? "item") === "submenu") { + event.preventDefault(); + openSub(index); + return; + } + if (event.key === "Enter" || event.key === " ") { + event.preventDefault(); + if (!inSub && item && (item.type ?? "item") === "submenu") openSub(index); + else if (item) activate(item); + return; + } + if (event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) { + buffer += event.key; + if (bufferTimer) clearTimeout(bufferTimer); + bufferTimer = setTimeout(() => (buffer = ""), 500); + const found = typeahead(current.items, current.index, buffer); + if (found >= 0) { + if (inSub && sub) sub.index = found; + else index = found; + focusAt(current.buttons, found); + } + } + }; + + /** @param {MouseEvent} event */ + const onClick = (event) => { + const target = /** @type {Element | null} */ (event.target); + const button = target?.closest(".c-menu__item"); + if (!(button instanceof HTMLElement)) return; + const inSub = sub !== null && sub.panel.contains(button); + const list = inSub && sub ? sub.buttons : buttons; + const source = inSub && sub ? sub.items : items; + const i = list.indexOf(button); + const item = source[i]; + if (!item) return; + if (!inSub && (item.type ?? "item") === "submenu") { + index = i; + if (sub?.owner === button) closeSub(true); + else openSub(i); + return; + } + activate(item); + }; + + /** @param {PointerEvent} event */ + const onPointerDownOutside = (event) => { + const target = /** @type {Node} */ (event.target); + if (panel.contains(target) || sub?.panel.contains(target)) return; + // O clique fora fecha sem roubar o foco do que foi clicado. + close({ restoreFocus: false }); + // O toque no próprio botão que abriu não deve reabrir o menu. + if (anchor instanceof Node && anchor.contains(target)) { + event.preventDefault(); + } + }; + + /** @param {FocusEvent} event */ + const onFocusIn = (event) => { + const inSub = sub !== null && sub.panel.contains(/** @type {Node} */ (event.target)); + const list = inSub && sub ? sub.buttons : buttons; + const i = list.indexOf(/** @type {HTMLElement} */ (event.target)); + if (i < 0) return; + if (inSub && sub) sub.index = i; + else { + index = i; + // Voltar ao menu principal fecha o submenu aberto. + if (sub && buttons[i] !== sub.owner) closeSub(false); + } + }; + + /** @param {PointerEvent} event — passar o ponteiro sobre um item o foca (sem rolar). */ + const onPointerMove = (event) => { + if (event.pointerType !== "mouse") return; + const target = /** @type {Element | null} */ (event.target); + const button = target?.closest(".c-menu__item"); + if (button instanceof HTMLElement && document.activeElement !== button) { + button.focus({ preventScroll: true }); + } + }; + + host.addEventListener("keydown", onKey); + host.addEventListener("click", onClick); + host.addEventListener("focusin", onFocusIn); + host.addEventListener("pointermove", onPointerMove); + scrim?.addEventListener("click", () => close({ restoreFocus: true })); + document.addEventListener("pointerdown", onPointerDownOutside, true); + + const stop = asSheet + ? () => {} + : anchorTo(anchor ?? pointAnchor(point?.x ?? 0, point?.y ?? 0), panel, { + placement: anchor ? placement : "right-start", + gap: anchor ? 6 : 2, + }); + + index = first(items); + // O foco vai para o primeiro item depois do primeiro desenho (o + // posicionamento é assíncrono e o foco não pode rolar a página). + requestAnimationFrame(() => { + if (openMenu === handle) { + const button = buttons[index]; + button?.focus({ preventScroll: true }); + } + }); + anchor?.setAttribute("aria-expanded", "true"); + + let closed = false; + /** @param {{restoreFocus?: boolean}} [options] */ + const close = ({ restoreFocus = true } = {}) => { + if (closed) return; + closed = true; + closeSub(false); + stop(); + document.removeEventListener("pointerdown", onPointerDownOutside, true); + host.remove(); + anchor?.setAttribute("aria-expanded", "false"); + if (openMenu === handle) openMenu = null; + if (restoreFocus && previousFocus?.isConnected) + previousFocus.focus({ preventScroll: true }); + onClose(); + }; + + const handle = { + close, + /** Troca os itens sem fechar (ex.: um estado mudou). @param {MenuItem[]} next */ + refresh(next) { + items.splice(0, items.length, ...tidy(next)); + buttons = paint(list, items); + index = Math.min(Math.max(index, first(items)), items.length - 1); + if (!isFocusable(items[index] ?? {})) index = first(items); + focusAt(buttons, index); + }, + }; + openMenu = handle; + return handle; +}; diff --git a/frontend/src/ui/primitives/menuModel.js b/frontend/src/ui/primitives/menuModel.js new file mode 100644 index 0000000..0ddfbd6 --- /dev/null +++ b/frontend/src/ui/primitives/menuModel.js @@ -0,0 +1,125 @@ +// @ts-check + +/** + * Modelo de um menu (padrão "menu" do APG/WAI-ARIA), sem DOM: quais itens + * recebem foco, para onde as setas levam e a busca pela primeira letra. + * O desenho e os eventos ficam em `menu.js`. + * + * Inspirado na organização dos menus de contexto do Fluxer (um menu por + * entidade, montado a partir de grupos de itens) — implementação própria. + */ + +/** + * @typedef {object} MenuItem + * @property {"item" | "check" | "separator" | "label" | "submenu"} [type] padrão: "item" + * @property {string} [id] + * @property {string} [label] + * @property {string} [icon] nome em `icons.js` + * @property {string} [hint] texto à direita (atalho, valor atual) + * @property {boolean} [danger] + * @property {boolean} [disabled] + * @property {boolean} [checked] só `check` + * @property {() => void} [run] + * @property {MenuItem[]} [items] só `submenu` + */ + +/** @param {MenuItem} item */ +export const isFocusable = (item) => + (item.type ?? "item") !== "separator" && item.type !== "label" && !item.disabled; + +/** + * Tira separadores no começo, no fim e repetidos (sobram quando um grupo + * inteiro some por falta de permissão) e rótulos de grupo sem itens. + * @param {MenuItem[]} items + * @returns {MenuItem[]} + */ +export const tidy = (items) => { + /** @type {MenuItem[]} */ + const out = []; + for (const [index, item] of items.entries()) { + const type = item.type ?? "item"; + if (type === "separator") { + if (out.length === 0 || (out.at(-1)?.type ?? "item") === "separator") continue; + } + if (type === "label") { + const next = items[index + 1]; + if (!next || (next.type ?? "item") === "separator" || next.type === "label") continue; + } + out.push(item); + } + while (out.length && (out.at(-1)?.type ?? "item") === "separator") out.pop(); + return out; +}; + +/** + * Próximo índice focável a partir de `from`, andando `step` (com volta). + * @param {MenuItem[]} items + * @param {number} from -1 = antes do primeiro + * @param {1 | -1} step + * @returns {number} -1 se nenhum é focável + */ +export const step = (items, from, step) => { + const n = items.length; + if (n === 0) return -1; + let index = from; + for (let i = 0; i < n; i += 1) { + index = (index + step + n) % n; + const item = items[index]; + if (item && isFocusable(item)) return index; + } + return -1; +}; + +/** @param {MenuItem[]} items */ +export const first = (items) => step(items, -1, 1); +/** @param {MenuItem[]} items */ +export const last = (items) => step(items, 0, -1); + +/** + * Busca pela digitação (letras seguidas em até ~0,5 s formam um prefixo), + * começando depois do item atual, com volta. + * @param {MenuItem[]} items + * @param {number} from + * @param {string} prefix + * @returns {number} -1 se nenhum combina + */ +export const typeahead = (items, from, prefix) => { + const wanted = prefix.toLocaleLowerCase("pt-BR"); + const n = items.length; + for (let i = 1; i <= n; i += 1) { + const index = (from + i + n) % n; + const item = items[index]; + if ( + item && + isFocusable(item) && + (item.label ?? "").toLocaleLowerCase("pt-BR").startsWith(wanted) + ) { + return index; + } + } + return -1; +}; + +/** + * Tecla → movimento. `null` = a tecla não é do menu. + * @param {string} key + * @param {MenuItem[]} items + * @param {number} current + * @returns {number | null} + */ +export const move = (key, items, current) => { + switch (key) { + case "ArrowDown": + return step(items, current, 1); + case "ArrowUp": + return step(items, current === -1 ? 0 : current, -1); + case "Home": + case "PageUp": + return first(items); + case "End": + case "PageDown": + return last(items); + default: + return null; + } +}; diff --git a/frontend/src/ui/primitives/position.js b/frontend/src/ui/primitives/position.js new file mode 100644 index 0000000..9b7f32c --- /dev/null +++ b/frontend/src/ui/primitives/position.js @@ -0,0 +1,72 @@ +// @ts-check + +import { autoUpdate, computePosition, flip, offset, shift, size } from "@floating-ui/dom"; + +/** + * Posição de elementos flutuantes (menus, cartões, sugestões) com o + * `@floating-ui/dom` — a mesma biblioteca que o Fluxer usa por baixo dos + * menus dele (aqui, o núcleo sem React; licença MIT). + * + * O elemento flutuante usa `position: fixed` (classe do componente) e só + * recebe `left`, `top` e `max-height` pelo CSSOM — nada de estilo inline no + * HTML, então a CSP não precisa de `unsafe-inline`. + * + * Acompanha rolagem e mudança de tamanho sem fechar: abrir o teclado virtual + * do celular não derruba mais um menu aberto. + */ + +/** + * Âncora num ponto da tela (clique direito, toque longo). + * @param {number} x + * @param {number} y + */ +export const pointAnchor = (x, y) => ({ + getBoundingClientRect: () => ({ + x, + y, + top: y, + left: x, + right: x, + bottom: y, + width: 0, + height: 0, + }), +}); + +/** + * Prende `floating` a `reference` e o mantém no lugar até a limpeza. + * @param {Element | ReturnType} reference + * @param {HTMLElement} floating + * @param {{placement?: import("@floating-ui/dom").Placement, gap?: number, minHeight?: number}} [options] + * @returns {() => void} para de acompanhar + */ +export const anchorTo = ( + reference, + floating, + { placement = "bottom-start", gap = 6, minHeight = 120 } = {}, +) => { + const update = () => { + void computePosition(reference, floating, { + placement, + strategy: "fixed", + middleware: [ + offset(gap), + flip({ padding: 8 }), + shift({ padding: 8 }), + size({ + padding: 8, + apply({ availableHeight }) { + floating.style.maxHeight = `${Math.max(minHeight, Math.floor(availableHeight))}px`; + }, + }), + ], + }).then(({ x, y }) => { + floating.style.left = `${Math.round(x)}px`; + floating.style.top = `${Math.round(y)}px`; + }); + }; + if (reference instanceof Element) return autoUpdate(reference, floating, update); + update(); + window.addEventListener("resize", update); + return () => window.removeEventListener("resize", update); +}; diff --git a/frontend/test/menu.test.js b/frontend/test/menu.test.js new file mode 100644 index 0000000..c0590cf --- /dev/null +++ b/frontend/test/menu.test.js @@ -0,0 +1,73 @@ +// Modelo do menu (padrão APG): foco, setas, busca por letra e limpeza. + +import { test, describe } from "node:test"; +import assert from "node:assert/strict"; +import { first, last, move, step, tidy, typeahead } from "../src/ui/primitives/menuModel.js"; + +/** @type {import("../src/ui/primitives/menuModel.js").MenuItem[]} */ +const items = [ + { type: "label", label: "Conversa" }, + { label: "Fixar" }, + { label: "Mover para cima", disabled: true }, + { label: "Mover para baixo" }, + { type: "separator" }, + { label: "Marcar como lida" }, + { label: "Sair da sala", danger: true }, +]; + +describe("menu: foco e setas", () => { + test("o primeiro e o último focáveis pulam rótulo, separador e desabilitado", () => { + assert.equal(first(items), 1); + assert.equal(last(items), 6); + }); + + test("↓ e ↑ andam com volta, sem parar em itens que não recebem foco", () => { + assert.equal(step(items, 1, 1), 3, "pula o desabilitado"); + assert.equal(step(items, 3, 1), 5, "pula o separador"); + assert.equal(step(items, 6, 1), 1, "volta ao começo"); + assert.equal(step(items, 1, -1), 6, "volta ao fim"); + }); + + test("Home/End e PageUp/PageDown; tecla alheia não é do menu", () => { + assert.equal(move("Home", items, 5), 1); + assert.equal(move("End", items, 1), 6); + assert.equal(move("PageUp", items, 5), 1); + assert.equal(move("ArrowDown", items, -1), 1, "sem foco: ↓ vai ao primeiro"); + assert.equal(move("ArrowUp", items, -1), 6, "sem foco: ↑ vai ao último"); + assert.equal(move("a", items, 1), null); + }); + + test("menu sem item focável", () => { + assert.equal(first([{ type: "separator" }, { label: "x", disabled: true }]), -1); + assert.equal(step([], 0, 1), -1); + }); +}); + +describe("menu: busca pela digitação", () => { + test("acha pelo prefixo a partir do item atual, com volta e sem acento de caixa", () => { + assert.equal(typeahead(items, 1, "m"), 3, "o desabilitado não conta"); + assert.equal(typeahead(items, 3, "m"), 5); + assert.equal(typeahead(items, 5, "m"), 3, "volta ao começo"); + assert.equal(typeahead(items, 1, "SAIR"), 6); + assert.equal(typeahead(items, 1, "z"), -1); + }); +}); + +describe("menu: limpeza dos grupos", () => { + test("separadores no começo, no fim e repetidos somem; rótulo sem itens também", () => { + const result = tidy([ + { type: "separator" }, + { label: "A" }, + { type: "separator" }, + { type: "separator" }, + { type: "label", label: "Moderação" }, + { type: "separator" }, + { label: "B" }, + { type: "separator" }, + ]); + assert.deepEqual( + result.map((item) => item.type ?? item.label), + ["A", "separator", "B"], + ); + }); +}); diff --git a/package-lock.json b/package-lock.json index 03ffeaa..6c4f896 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,6 +8,9 @@ "name": "web-chat", "version": "1.0.0", "license": "MIT", + "dependencies": { + "@floating-ui/dom": "1.6.13" + }, "devDependencies": { "@eslint/js": "^9.13.0", "axe-core": "4.10.2", @@ -832,6 +835,31 @@ "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, + "node_modules/@floating-ui/core": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.8.0.tgz", + "integrity": "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==", + "license": "MIT", + "dependencies": { + "@floating-ui/utils": "^0.2.12" + } + }, + "node_modules/@floating-ui/dom": { + "version": "1.6.13", + "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.6.13.tgz", + "integrity": "sha512-umqzocjDgNRGTuO7Q8CU32dkHkECqI8ZdMZ5Swb6QAM0t5rnlrN3lGo1hdpscRd3WS8T6DKYK4ephgIH9iRh3w==", + "license": "MIT", + "dependencies": { + "@floating-ui/core": "^1.6.0", + "@floating-ui/utils": "^0.2.9" + } + }, + "node_modules/@floating-ui/utils": { + "version": "0.2.12", + "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.12.tgz", + "integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==", + "license": "MIT" + }, "node_modules/@humanfs/core": { "version": "0.19.2", "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", diff --git a/package.json b/package.json index d69c059..02b39b1 100644 --- a/package.json +++ b/package.json @@ -36,5 +36,8 @@ "stylelint-config-standard": "^36.0.1", "typescript": "^5.6.3", "vite": "^6.4.6" + }, + "dependencies": { + "@floating-ui/dom": "1.6.13" } } diff --git a/scripts/e2e.mjs b/scripts/e2e.mjs index deb4c2a..0d6b7c8 100644 --- a/scripts/e2e.mjs +++ b/scripts/e2e.mjs @@ -254,6 +254,18 @@ const ctx = { // A CSP da página bloqueia script inline (como deve). O código do axe // entra como expressão avaliada pelo protocolo de depuração, que não // passa pela CSP — o teste roda com a CSP real ligada. + // Espera as animações finitas terminarem (entrada de mensagem, + // menu, painel): o axe mede a cor computada, e no meio de um + // esmaecimento ela ainda não é a final. Animações infinitas + // (indicadores de carregamento) não entram na espera. + await page.evaluate(() => + Promise.all( + document + .getAnimations() + .filter((a) => a.effect?.getComputedTiming().iterations !== Infinity) + .map((a) => a.finished.catch(() => {})), + ), + ); await page.evaluate(source); const result = await page.evaluate(() => window.axe.run(document, {