diff --git a/.agents/skills/backend-domain/SKILL.md b/.agents/skills/backend-domain/SKILL.md index 77de3c4..bfc1cfd 100644 --- a/.agents/skills/backend-domain/SKILL.md +++ b/.agents/skills/backend-domain/SKILL.md @@ -16,7 +16,10 @@ Procedimento operacional. O racional completo está em `docs/PATTERNS/BACKEND-AR Sem `try/catch` no handler. - **Path em camelCase, substantivo no plural, sem verbo.** Ação é o método HTTP. Filtro, busca, ordenação e paginação na query string. -- Toda rota de lista aceita `search` na query (busca no servidor), além de paginação e ordenação. +- Toda rota de lista aceita `search` na query (busca no servidor), além de paginação e ordenação. O + `search` é `searchSchema([...chaves])` de `server/schemas/common.ts`, e o service passa o termo por + `parseSearch` (`server/lib/search.ts`) com as chaves da lista: texto livre, `campo:valor` e o + período `de:`/`ate:`. Comparação com `matchesTerm`/`normalizeTerm` (sem acento e sem caixa). - Sucesso sem envelope: recurso direto, ou `{ data, meta }` para lista (`listSchema` de `server/schemas/common.ts`). diff --git a/.agents/skills/new-screen/SKILL.md b/.agents/skills/new-screen/SKILL.md index 8c68cd6..71c6e1a 100644 --- a/.agents/skills/new-screen/SKILL.md +++ b/.agents/skills/new-screen/SKILL.md @@ -25,7 +25,9 @@ Procedimento operacional. O racional está em `docs/PATTERNS/FRONTEND-ARCH.md` e 3. **Queries** em `_hooks/.queries.ts` com `queryOptions`. O `clientLoader` faz `void queryClient.prefetchQuery(...)` e a tela usa `useQuery` com a mesma função. 4. **Mutations** com `useMutation`, invalidando as chaves afetadas no `onSuccess` e `toast.success`. -5. **Tela:** `PageHeader` no topo. Lista com `DataTable`, sempre com busca (`search`, obrigatório) e +5. **Tela:** `PageHeader` no topo. Lista com `DataTable`, sempre com busca (`search`, obrigatório, com + o estado do `useListSearch` e as `keys` de `campo:valor` iguais às do service; `periodLabel` liga o + período) e os filtros em `filters` como um `FilterButton` (`keys` com as chaves da URL que são filtro, cada filtro num `FilterField`); estado na URL (`useListParams`), com o valor padrão fora dela. Detalhe em `EntityDrawer` com o id na URL. Criação em `FormDialog`. Confirmação com `useConfirm()`. @@ -39,4 +41,5 @@ Procedimento operacional. O racional está em `docs/PATTERNS/FRONTEND-ARCH.md` e ## Antes de concluir `bun run lint`, `bun run typecheck`, `bun run test:e2e`, e a tela conferida nos dois temas e em -viewport de celular. +viewport de celular (390px, sem rolagem horizontal; o `DataTable` vira cards e coluna secundária leva +`hideOnMobile`). Ver "Celular" em `docs/DESIGN-SYSTEM.md`. diff --git a/.env.example b/.env.example index 833eea6..e417e72 100644 --- a/.env.example +++ b/.env.example @@ -9,3 +9,12 @@ SESSION_SECRET= # Obrigatória. Senha de admin@local.test e user@local.test, recriados a cada start. SEED_PASSWORD= + +# @modulo:notificacoes +# Par VAPID do Web Push, próprio de cada deploy: bunx web-push generate-vapid-keys. Obrigatório em +# produção; em dev, sem ele, um par novo é gerado a cada start e as inscrições se refazem. +VAPID_PUBLIC_KEY= +VAPID_PRIVATE_KEY= +# mailto: ou a URL https:// do sistema. +VAPID_SUBJECT=mailto:notificacoes@localhost +# @modulo:fim diff --git a/CLAUDE.md b/CLAUDE.md index 3d51373..0a7395b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -14,6 +14,9 @@ perfil e dashboard como domínio de referência: ao criar algo novo, copie o for - `docs/PATTERNS/API-DESIGN.md`: desenho da API e a matriz de rotas. - `docs/PATTERNS/FRONTEND-ARCH.md`: colocation, dados, sessão, formulários. - `docs/DESIGN-SYSTEM.md`: tokens, tipografia, componentes. +- `docs/MODULOS.md`: core e módulos opcionais (`notificacoes`, `chat`), o `modulos.json` e os + marcadores `@modulo:` nos arquivos do core. Mexeu num ponto de ligação de módulo: marque o + trecho e gere um projeto sem o módulo para rodar os gates. - Skills em `.agents/skills/` (`.claude/skills` aponta para lá): `backend-domain` para endpoint ou recurso novo, `new-screen` para tela nova, `react-router` para dúvida do framework. @@ -32,6 +35,7 @@ bun run format:check # prettier --check (roda no CI) bun run test # vitest em watch bun run test:run # vitest uma vez (roda no CI) bun run test:e2e # playwright contra o build de produção, porta 4173 (roda no CI) +bun run modulos # cria projeto com os módulos escolhidos e atualiza por módulo (docs/MODULOS.md) ``` Gates antes de dar uma tarefa por concluída: `lint`, `lint:api`, `format:check`, `typecheck`, @@ -67,17 +71,69 @@ Gates antes de dar uma tarefa por concluída: `lint`, `lint:api`, `format:check` - Sem banco nesta etapa: `server/lib/memoryStore.ts` guarda os dados em memória, e o start recria os usuários do seed (`SEED_PASSWORD`). Só `server/services/` importa o store. Quando o banco entrar, a troca fica nos services. -- Sessão: cookie `session` HttpOnly com `{ sub, ver, exp }` assinado por HMAC (`SESSION_SECRET`). O +- Sessão: cookie `session` HttpOnly com `{ sub, sid, ver, exp }` assinado por HMAC (`SESSION_SECRET`). O `requireAuth` (`server/middleware/auth.ts`) relê o usuário a cada request, então role e status valem na hora. Rotas de admin usam `requireAuth()` seguido de `requireRole("admin")`. -- `ver` é o `sessionVersion` do usuário. Reset de senha e troca da própria senha incrementam, o que - derruba as sessões abertas; na troca própria, o handler reemite o cookie para quem trocou. +- `ver` é o `sessionVersion` do usuário. Reset de senha, troca da própria senha e desativação + incrementam, o que derruba as sessões abertas; na troca própria, o handler reemite o cookie da mesma + sessão para quem trocou. `sid` identifica o login: o que fica preso a ele (a inscrição de Web Push) é + apagado no logout. Cookie sem `sid`, emitido antes dele existir, continua valendo, com o id da sessão + tirado do hash do token. - Usuário nunca é apagado, só desativado (`active: false`): o audit precisa do autor. - Toda mudança que um admin precise rastrear grava `recordAudit()` no service. - Usuário com `mustChangePassword` só acessa `GET /me` e `PUT /me/password`; o resto responde `403` `PASSWORD_CHANGE_REQUIRED`. - Erros de contrato de uma rota são declarados com `...problemResponses(401, 422)`. +### Notificações + +- Outro módulo avisa alguém com `notifyUser(userId, { title, body, url, senderName, important })` + (`server/services/notifications/notifications.service.ts`). O exemplo do template está no + `updateUser`: cargo mudado e conta reativada por um admin. `senderName` é o que a notificação mostra + com a prévia desligada; `important` avisa mesmo com os avisos silenciados. +- O aviso fica no store (tela `/notifications`, contador na sidebar e `(N)` na aba) e chega por dois + caminhos: as abas abertas pelo stream SSE de `GET /events`, e os navegadores sem o app + aberto por Web Push (`public/sw.js`). O par VAPID vem do `.env` (`VAPID_PUBLIC_KEY`, + `VAPID_PRIVATE_KEY`, `VAPID_SUBJECT`), obrigatório em produção; em dev, sem ele, um par é gerado a + cada start e os navegadores se inscrevem de novo ao abrir o app. +- Cada usuário arquiva avisos (saem da lista e do contador) e silencia os avisos por 8 horas, 1 semana + ou sempre (`PUT /noticeMute`): silenciados chegam na lista, sem notificação nem som, e o contador + fica cinza. O menu de cada aviso abre pela seta ou pelo clique direito. +- Avisos em sequência e grupo agitado: depois de avisar, 15 s sem notificação nem som daquele tipo + (`SQUELCH_MS`, igual na página e no push). Conversa de duas pessoas avisa toda mensagem. +- Texto e preferências da notificação ficam em `shared/` (`notificationText.ts`, + `notificationPreferences.ts`), importados pela página (`~shared/...`) e pelo servidor. `shared/` não + importa `app/` nem `server/` (regra do ESLint). As regras: "Fulano: texto" em grupo, "Mencionou você:", + "Respondeu a você:", "Fulano reagiu ❤️ a: …" e, sem prévia, "N novas mensagens", "Mensagem de + Fulano" ou "Notificação de Fulano". +- As abas abertas ficam na memória do processo (`stream.service.ts`). Com mais de um processo, o + evento precisa de um canal entre eles (Redis, LISTEN/NOTIFY) antes de escalar. +- No front, `NotificationConnection` (montado pelo layout) cuida do stream, da notificação do sistema + (só com a janela sem foco), do som, da inscrição de push, do cache do chat e do `(N)`, que soma os + avisos não silenciados e as conversas não lidas. As configurações ficam no `localStorage` de cada + usuário, separadas para mensagens, grupos e avisos, e vão junto com a inscrição de push. +- `SINGLE_TAB` (`app/config/app.ts`) deixa uma aba do app por navegador, com "Usar aqui" na segunda. + +### Conversas + +- Chat entre os usuários do app, de duas pessoas ou em grupo (`server/services/chat/chat.service.ts`, + rotas `/conversations` e `/contacts`, tela `app/routes/chat/`). Conversa de duas pessoas é uma só: + pedir de novo devolve a que existe. +- Não lidas, "marcar como não lida" (só a bolinha), silenciar e arquivar são de cada pessoa + (`MemberStateRecord`) e valem só para ela. Responder lê a conversa só para quem respondeu. Arquivada + só volta ao desarquivar. +- Silenciada ou arquivada só avisa a mensagem dirigida à pessoa: menção a ela, `@todos` ou resposta a + uma mensagem dela. Reação de outra pessoa a uma mensagem sua avisa e vira a prévia, mas não fura + silêncio nem arquivo. O `(N)` conta conversas com mensagem não lida, fora as arquivadas e as + silenciadas sem menção. +- A conversa aberta (`ConversationView`) só é lida com a janela em foco há 2,5 s e a rolagem no fim, e + só até a última mensagem que estava na tela (`readUntil`, que nunca volta atrás); aberta sem foco, + espera o primeiro clique ou tecla. Abre na faixa "N mensagens não lidas", buscando páginas + antigas se preciso, e a faixa fica até sair ou mandar mensagem. Só a própria mensagem rola até o fim. + Esc cancela a citação e depois fecha a conversa. +- As mensagens ficam no cache do TanStack Query por conversa (`app/lib/chat/chat.queries.ts`); o + stream acrescenta as novas, e voltar à conversa mantém as páginas antigas já carregadas. + ### Frontend: sessão e dados - `app/lib/api.ts` é a única camada de fetch. Ela lança `ApiError` com o Problem Details, e diff --git a/README.md b/README.md index f3c96ee..73148ca 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ Requisitos: Node.js 22.22 ou superior e bun 1.4.2 (fixado em `packageManager`). ```bash bun install -cp .env.example .env # preencha SESSION_SECRET (openssl rand -base64 48) e SEED_PASSWORD +cp .env.example .env # SESSION_SECRET (openssl rand -base64 48), SEED_PASSWORD e o par VAPID bun run dev # front em http://localhost:3000, API em :3001 ``` @@ -82,6 +82,7 @@ server/ # backend ├── services/ # regra de negócio e todo acesso a dados ├── middleware/ # sessão e role └── lib/ # store em memória, Problem Details, router +shared/ # usado pelos dois lados: texto e preferências das notificações e2e/ # testes do caminho do usuário docs/ # patterns e design system ``` @@ -105,6 +106,7 @@ A arquitetura em uma frase de cada lado: no servidor, **só `services/` acessa d - [docs/PATTERNS/API-DESIGN.md](docs/PATTERNS/API-DESIGN.md): regras da API e matriz de rotas - [docs/PATTERNS/FRONTEND-ARCH.md](docs/PATTERNS/FRONTEND-ARCH.md): colocation, dados, sessão, formulários - [docs/DESIGN-SYSTEM.md](docs/DESIGN-SYSTEM.md): tokens, tipografia, componentes +- [docs/MODULOS.md](docs/MODULOS.md): criar projeto com os módulos escolhidos e atualizar por módulo - `CLAUDE.md` (e o symlink `AGENTS.md`): guia para agentes de código - `.agents/skills/`: `backend-domain`, `new-screen` e a skill oficial `react-router` @@ -112,18 +114,34 @@ A arquitetura em uma frase de cada lado: no servidor, **só `services/` acessa d `Dockerfile` multi-stage: build com bun e Node, runtime `node:24-alpine` como usuário `node`, com `HEALTHCHECK` em `/api/health`. O `docker-compose.yml` é o do Dokploy: sem `ports:` publicadas, o -domínio é cadastrado na aba Domains. Variáveis obrigatórias: `SESSION_SECRET` e `SEED_PASSWORD`. +domínio é cadastrado na aba Domains. Variáveis obrigatórias: `SESSION_SECRET`, `SEED_PASSWORD`, `VAPID_PUBLIC_KEY` e `VAPID_PRIVATE_KEY` (`bunx web-push generate-vapid-keys`). Versão e CHANGELOG saem do release-please, a partir das mensagens de commit em Conventional Commits. ## Criar um projeto a partir do template -1. "Use this template" no GitHub, ou copie o repositório. -2. Troque o nome em `package.json`, `app/config/app.ts` e no título do contrato em `server/app.ts`. -3. Gere um `SESSION_SECRET` novo por ambiente. +1. Do Default, escolha os módulos e gere o projeto: + `bun run modulos novo ../MeuProjeto --com chat --nome meu-projeto`. Sem `--com`, vem só o core. + Notificações e chat são opcionais (guia em [docs/MODULOS.md](docs/MODULOS.md)). +2. Troque o nome em `app/config/app.ts` e no título do contrato em `server/app.ts`. +3. O `.env` de dev já sai pronto (admin@local.test, senha 12345678). Em staging e produção, gere um + `SESSION_SECRET` novo por ambiente. 4. Crie o secret `RELEASE_PLEASE_TOKEN` no repositório, para o PR de release rodar o CI. -5. Apague ou adapte o que o projeto não usa. O domínio de usuários e a sessão ficam: o resto depende - deles. +5. Para trazer correções do Default depois: `bun run modulos atualizar ../MeuProjeto [módulo]`, que + mostra o que muda antes de gravar. + +## Notificações e conversas + +Qualquer módulo avisa um usuário com `notifyUser(userId, { title, body, url })`. O aviso aparece na +tela Notificações e no contador da sidebar, põe `(N)` no título e no ícone da aba, e vira notificação +do sistema: pela página aberta (só com a janela sem foco) ou por Web Push com o app fechado. O par +VAPID do push vem do `.env` (`bunx web-push generate-vapid-keys`), obrigatório em produção. Avisos podem ser arquivados e silenciados por 8 +horas, 1 semana ou sempre. + +A tela Conversas é um chat entre os usuários, de duas pessoas ou em grupo, com não lidas, menção, +resposta citada e reações. Cada pessoa marca como não lida, silencia e arquiva as próprias conversas, +e configura no menu do perfil, separado para mensagens, grupos e avisos, se quer notificação, som e +prévia. Detalhes em `CLAUDE.md`, seções Notificações e Conversas. ## Próxima etapa diff --git a/app/app.css b/app/app.css index 2cefee7..05a36bc 100644 --- a/app/app.css +++ b/app/app.css @@ -73,54 +73,63 @@ } .dark { - --background: #090b0e; + /* Grafite em vez de quase preto. Três camadas de superfície, cada uma mais clara: página, sidebar e + card, e por cima menu e modal. No escuro a sombra quase não aparece, então a separação vem do tom. */ + --background: #13171e; --foreground: #f3f5f8; - --card: #0f1217; + --card: #1c222c; --card-foreground: #f3f5f8; - --popover: #0f1217; + --popover: #242b37; --popover-foreground: #f3f5f8; - --primary: #0066ff; - --primary-foreground: #ffffff; - --primary-glow: rgba(0, 102, 255, 0.12); + /* #0066ff fica abaixo de 4:1 sobre o card escuro. Este azul passa de 4,5:1 como texto em todas as + superfícies, e por ser claro o texto do botão preenchido é escuro (6,4:1), não branco. */ + --primary: #4d94ff; + --primary-foreground: #0b0e13; + --primary-glow: rgba(77, 148, 255, 0.16); - --secondary: rgba(255, 255, 255, 0.06); + --secondary: rgba(255, 255, 255, 0.08); --secondary-foreground: #f3f5f8; - --muted: rgba(255, 255, 255, 0.03); - --muted-foreground: #8e99a7; - --accent: rgba(255, 255, 255, 0.06); + --muted: rgba(255, 255, 255, 0.045); + --muted-foreground: #a7b1be; + --accent: rgba(255, 255, 255, 0.08); --accent-foreground: #f3f5f8; - --destructive: #ff4a5a; - --border: rgba(255, 255, 255, 0.2); + --destructive: #ff5f6d; + --border: rgba(255, 255, 255, 0.1); --input: rgba(255, 255, 255, 0.2); - --ring: rgba(0, 102, 255, 0.4); + --ring: rgba(77, 148, 255, 0.5); - --sidebar: #090b0e; + --sidebar: #171c24; --sidebar-foreground: #f3f5f8; - --sidebar-primary: #0066ff; - --sidebar-primary-foreground: #ffffff; - --sidebar-accent: rgba(255, 255, 255, 0.06); + --sidebar-primary: #4d94ff; + --sidebar-primary-foreground: #0b0e13; + --sidebar-accent: rgba(255, 255, 255, 0.08); --sidebar-accent-foreground: #f3f5f8; - --sidebar-border: rgba(255, 255, 255, 0.2); - --sidebar-ring: rgba(0, 102, 255, 0.4); + --sidebar-border: rgba(255, 255, 255, 0.1); + --sidebar-ring: rgba(77, 148, 255, 0.5); - --dim: #556070; - --success: #0066ff; + --dim: #8590a0; /* 4:1 sobre o card e o menu, para ícone e dica continuarem visíveis */ + --success: #4d94ff; --warning: #ffb700; - --skeleton: #1b2532; - --badge-primary-fg: #4d94ff; - --badge-primary-bg: rgba(0, 102, 255, 0.12); + --skeleton: #2a323e; + --badge-primary-fg: #7ab0ff; + --badge-primary-bg: rgba(77, 148, 255, 0.16); --badge-destructive-fg: #ff4a5a; --badge-destructive-bg: rgba(255, 74, 90, 0.12); --badge-warning-fg: #ffb700; --badge-warning-bg: rgba(255, 183, 0, 0.12); - --elevation-card: 0 4px 12px rgba(0, 0, 0, 0.1); - --elevation-card-elevated: 0 10px 40px rgba(0, 0, 0, 0.1), 0 20px 50px rgba(0, 0, 0, 0.45); - --elevation-modal: 0 10px 40px rgba(0, 0, 0, 0.1), 0 20px 50px rgba(0, 0, 0, 0.45); + /* Fio claro no topo marca a borda de cima da superfície, e a sombra escura a de baixo. */ + --elevation-card: inset 0 1px 0 rgba(255, 255, 255, 0.04), 0 4px 12px rgba(0, 0, 0, 0.35); + --elevation-card-elevated: + inset 0 1px 0 rgba(255, 255, 255, 0.05), 0 10px 40px rgba(0, 0, 0, 0.4), + 0 20px 50px rgba(0, 0, 0, 0.5); + --elevation-modal: + inset 0 1px 0 rgba(255, 255, 255, 0.06), 0 10px 40px rgba(0, 0, 0, 0.5), + 0 24px 60px rgba(0, 0, 0, 0.6); --elevation-primary-glow: 0 0 16px var(--primary-glow); - --scrollbar-thumb: rgba(255, 255, 255, 0.1); + --scrollbar-thumb: rgba(255, 255, 255, 0.18); } @theme inline { diff --git a/app/components/layout/AuthCard.tsx b/app/components/layout/AuthCard.tsx index d23afbe..61a1e6d 100644 --- a/app/components/layout/AuthCard.tsx +++ b/app/components/layout/AuthCard.tsx @@ -4,7 +4,7 @@ import { APP_NAME } from "~/config/app"; // Moldura das telas fora do app (login, troca obrigatória de senha). export function AuthCard({ subtitle, children }: { subtitle: string; children: React.ReactNode }) { return ( -
+
diff --git a/app/components/layout/MobileNav.tsx b/app/components/layout/MobileNav.tsx index 22f09f6..3259c18 100644 --- a/app/components/layout/MobileNav.tsx +++ b/app/components/layout/MobileNav.tsx @@ -1,6 +1,7 @@ import { User as UserIcon } from "lucide-react"; import { NavLink, useLocation } from "react-router"; -import { visibleNavigation } from "~/config/navigation"; +import { visibleNavigation, type NavItem } from "~/config/navigation"; +import { formatCounter, useNavCounter } from "~/hooks/useNavCounter"; import { cn } from "~/lib/utils"; import type { User } from "~/types/user"; import { ProfileMenu } from "./ProfileMenu"; @@ -13,6 +14,30 @@ const itemClass = (isActive: boolean) => : "text-muted-foreground hover:text-foreground", ); +function MobileNavLink({ item }: { item: NavItem }) { + const { count, muted } = useNavCounter(item.counter); + return ( + 0 ? `${item.label} (${formatCounter(count)})` : item.label} + className={({ isActive }) => itemClass(isActive)} + > + + {count > 0 && ( + + {formatCounter(count)} + + )} + + ); +} + // Abaixo de md a sidebar some e a navegação vira uma barra inferior (design system, seção responsivo). // O ícone de perfil abre o mesmo menu da sidebar: tema, meu perfil e sair. export function MobileNav({ user, onLogout }: { user: User; onLogout: () => void }) { @@ -25,15 +50,7 @@ export function MobileNav({ user, onLogout }: { user: User; onLogout: () => void className="fixed inset-x-0 bottom-0 z-30 flex items-center justify-around border-t bg-card px-4 pt-2.5 pb-[calc(10px+env(safe-area-inset-bottom))] md:hidden" > {items.map((item) => ( - itemClass(isActive)} - > - - + ))} + )} +
+
+ ); +} diff --git a/app/components/layout/NotificationBell.tsx b/app/components/layout/NotificationBell.tsx new file mode 100644 index 0000000..8dc3d98 --- /dev/null +++ b/app/components/layout/NotificationBell.tsx @@ -0,0 +1,213 @@ +import { useInfiniteQuery, useQuery } from "@tanstack/react-query"; +import { Bell, BellOff, CheckCheck, Search, Settings } from "lucide-react"; +import { useState } from "react"; +import { useNavigate } from "react-router"; +import { ErrorState } from "~/components/patterns/EmptyState"; +import { mutedUntilLabel } from "~/components/patterns/MuteMenuItems"; +import { Button } from "~/components/ui/button"; +import { Popover, PopoverContent, PopoverTrigger } from "~/components/ui/popover"; +import { Tooltip, TooltipContent, TooltipTrigger } from "~/components/ui/tooltip"; +import { formatCounter } from "~/hooks/useNavCounter"; +import { + isMutedNow, + noticeMuteQuery, + unreadNotificationsQuery, + useMarkAllNotificationsRead, + useUpdateNotification, +} from "~/lib/notifier/notifications.queries"; +import { cn } from "~/lib/utils"; +import type { AppNotification } from "~/types/notification"; +import { loadMoreOnScroll, NotificationItem, notificationPagesQuery } from "./NotificationItem"; +import { NotificationSearchDialog } from "./NotificationSearchDialog"; +import { NotificationSettingsDialog } from "./NotificationSettingsDialog"; + +// Recebidas, sem filtro. +const panelQuery = notificationPagesQuery({}); + +function Section({ + title, + items, + onOpen, +}: { + title: string; + items: AppNotification[]; + onOpen: (notification: AppNotification) => void; +}) { + if (items.length === 0) return null; + return ( +
+

{title}

+
    + {items.map((n) => ( + + ))} +
+
+ ); +} + +// Sininho ao lado dos botões do topo de cada tela. Abre o painel com as notificações; a lupa abre a +// busca e a engrenagem, as mesmas configurações do menu do perfil. +// `size`: "icon-sm" ao lado de botões pequenos, como no topo da lista de conversas. +export function NotificationBell({ size = "icon" }: { size?: "icon" | "icon-sm" }) { + const [open, setOpen] = useState(false); + const [settingsOpen, setSettingsOpen] = useState(false); + const [searchOpen, setSearchOpen] = useState(false); + const unread = useQuery(unreadNotificationsQuery).data ?? 0; + const mute = useQuery(noticeMuteQuery); + const muted = isMutedNow(mute.data); + const list = useInfiniteQuery({ ...panelQuery, enabled: open }); + const update = useUpdateNotification(); + const markAll = useMarkAllNotificationsRead(); + const navigate = useNavigate(); + + const items = list.data?.pages.flatMap((page) => page.data) ?? []; + const important = items.filter((n) => n.important); + const others = items.filter((n) => !n.important); + const label = unread > 0 ? `Notificações (${formatCounter(unread)})` : "Notificações"; + + function openNotification(notification: AppNotification) { + if (!notification.read) update.mutate({ id: notification.id, read: true }); + setOpen(false); + if (notification.url) navigate(notification.url); + } + + return ( + <> + + + + + + + + Notificações + + { + event.preventDefault(); + (event.currentTarget as HTMLElement).focus(); + }} + className="w-[min(480px,calc(100vw-32px))] gap-0 overflow-hidden p-0" + > +
+

Notificações

+ + + + + Buscar + + + + + + Marcar todas como lidas + + + + + + Configurações + +
+ {muted && ( +

+ Avisos silenciados {mutedUntilLabel(mute.data?.mutedUntil ?? null)}: chegam aqui, sem + notificação nem som. +

+ )} +
+ {list.isLoading ? ( +

+ Carregando... +

+ ) : list.error ? ( + list.refetch()} /> + ) : items.length === 0 ? ( +
+ +

Nenhuma notificação

+

+ Quando algo mudar na sua conta, o aviso aparece aqui. +

+
+ ) : ( + <> +
+
0 ? "Mais notificações" : "Recentes"} + items={others} + onOpen={openNotification} + /> + {list.isFetchingNextPage && ( +

+ Carregando mais... +

+ )} + + )} +
+
+
+ + + + ); +} diff --git a/app/components/layout/NotificationConnection.tsx b/app/components/layout/NotificationConnection.tsx new file mode 100644 index 0000000..c9e2ed6 --- /dev/null +++ b/app/components/layout/NotificationConnection.tsx @@ -0,0 +1,363 @@ +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { useEffect, useRef, useState } from "react"; +import { useNavigate } from "react-router"; +import { api } from "~/lib/api"; +import { renderDocumentBadge } from "~/lib/notifier/documentBadge"; +import { forgetSquelches, squelched } from "~/lib/notifier/squelch"; +import { + isMutedNow, + noticeMuteQuery, + unreadNotificationIds, + unreadNotificationsQuery, +} from "~/lib/notifier/notifications.queries"; +import { + getNotifierState, + loadPreferences, + refreshPermission, + resetPreferences, + useNotifierState, +} from "~/lib/notifier/preferences"; +import { + dropLocalPushSubscription, + registerServiceWorker, + syncPushSubscription, +} from "~/lib/notifier/push"; +import { connectRealtime, type RealtimeEvent } from "~/lib/notifier/realtime"; +import { canPlaySound, installAudioUnlock, playIncoming } from "~/lib/notifier/sounds"; +import { + closePageNotifications, + closeSystemNotifications, + closeSystemNotificationsExcept, + showSystemNotification, +} from "~/lib/notifier/systemNotifications"; +import { soundOn, type AppNotification, type NotificationKind } from "~/types/notification"; +import type { User } from "~/types/user"; +import { noticeNotification } from "~shared/notificationText"; +// @modulo:chat +import { + applyConversation, + applyMessage, + unreadConversationIds, + unreadConversationsQuery, +} from "~/lib/chat/chat.queries"; +import { requestComposerFocus } from "~/lib/chat/composerFocus"; +import type { Conversation, Message } from "~/types/chat"; +import { messageNotification, reactionNotification } from "~shared/notificationText"; +// @modulo:fim + +// Parâmetro com que o service worker abre o app pelo clique numa notificação de push. +const OPENED_PARAM = "notificacao"; + +// O usuário está usando o app: janela em foco e aba visível. Aí não há notificação nem som, como no +// WhatsApp Web; o contador da aba e da sidebar continua. +const inUse = () => document.hasFocus() && document.visibilityState === "visible"; + +// @modulo:chat +const isUnread = (conversation: Conversation) => + conversation.unreadCount > 0 || conversation.markedUnread; +// @modulo:fim + +// Notificação e som de um aviso, conforme as configurações do tipo dele. O som é o do app; depois de +// um F5 sem clique o navegador não deixa a página tocar, e aí vai o som do sistema. +function alert( + kind: NotificationKind, + title: string, + options: { body: string; tag: string; url: string | null; onClick: () => void }, +) { + const { prefs, permission } = getNotifierState(); + const sound = soundOn(prefs, kind); + const ownSound = sound && canPlaySound(); + if (prefs[kind].show && permission === "granted") { + showSystemNotification(title, { ...options, systemSound: sound && !ownSound }); + } + if (ownSound) playIncoming(prefs.sound, prefs.volume); +} + +// Stream de eventos, notificações do sistema, som, Web Push e o "(N)" da aba, enquanto há sessão e +// em qualquer tela. Montado uma vez pelo layout autenticado. +export function NotificationConnection({ user }: { user: User }) { + const queryClient = useQueryClient(); + const navigate = useNavigate(); + const navigateRef = useRef(navigate); + useEffect(() => { + navigateRef.current = navigate; + }, [navigate]); + + const { prefs, permission, userId: prefsUserId } = useNotifierState(); + const [pushEndpoint, setPushEndpoint] = useState(null); + const [offline, setOffline] = useState(false); + const notices = useQuery(unreadNotificationsQuery); + // @modulo:chat + const conversations = useQuery(unreadConversationsQuery); + // @modulo:fim + const noticeMute = useQuery(noticeMuteQuery); + const noticeMuteRef = useRef(noticeMute.data); + useEffect(() => { + noticeMuteRef.current = noticeMute.data; + }, [noticeMute.data]); + + // Abre o caminho da notificação e marca como lida. Do clique na notificação do sistema (página ou + // push) para qualquer tela. + const openNoticeRef = useRef((id: string, url: string | null) => { + window.focus(); + // Sem caminho, fica na tela atual: a notificação está no sininho do topo. + if (url) navigateRef.current(url); + void api.patch(`/notifications/${id}`, { read: true }).catch(() => {}); + }); + // @modulo:chat + // Abre a conversa com o cursor no campo, de qualquer tela. + const openConversationRef = useRef((id: string) => { + window.focus(); + requestComposerFocus(id); + navigateRef.current(`/chat?c=${id}`); + }); + // @modulo:fim + + // Configurações de quem entrou, guardadas neste navegador. + useEffect(() => { + loadPreferences(user.id); + }, [user.id]); + + // Aviso com o app fechado: vale sempre que o navegador tiver a permissão. As configurações vão + // junto, porque é o servidor que manda o push. + useEffect(() => { + if (prefsUserId !== user.id) return; + let current = true; + void syncPushSubscription(permission === "granted", prefs).then((endpoint) => { + if (current) setPushEndpoint(endpoint); + }); + return () => { + current = false; + }; + }, [prefsUserId, user.id, permission, prefs]); + + // Stream de eventos. Reabre quando a inscrição de push muda, para o servidor saber que este + // navegador está com o app aberto. + useEffect(() => { + // Silenciados não avisam, a não ser o importante. Vários seguidos: um aviso a cada 15 s. + const onNotice = (notification: AppNotification, count: number) => { + if (inUse()) return; + if (!notification.important && isMutedNow(noticeMuteRef.current)) return; + if (squelched("notices")) return; + const text = noticeNotification(notification, getNotifierState().prefs.previews, count); + alert("notices", text.title, { + body: text.body, + tag: notification.id, + url: notification.url, + onClick: () => openNoticeRef.current(notification.id, notification.url), + }); + }; + + // @modulo:chat + // Mensagem de outra pessoa. Silenciada ou arquivada só avisa a dirigida a você; grupo agitado + // fica 15 s sem avisar. + const onMessage = (message: Message, conversation: Conversation) => { + if (message.authorId === user.id || inUse()) return; + const isGroup = conversation.kind === "group"; + const mentionsMe = message.mentionsAll || message.mentionIds.includes(user.id); + const repliesToMe = message.replyTo?.authorId === user.id; + if ((conversation.muted || conversation.archived) && !mentionsMe && !repliesToMe) return; + if (isGroup && squelched(conversation.id)) return; + const { prefs: current } = getNotifierState(); + const text = messageNotification({ + conversationName: conversation.name, + isGroup, + senderName: message.authorName, + text: message.text, + previews: current.previews, + unreadCount: conversation.unreadCount, + mentionsMe: isGroup && mentionsMe, + repliesToMe: isGroup && repliesToMe, + }); + alert(isGroup ? "groups" : "messages", text.title, { + body: text.body, + tag: conversation.id, + url: `/chat?c=${conversation.id}`, + onClick: () => openConversationRef.current(conversation.id), + }); + }; + + // Reação de outra pessoa a uma mensagem sua: avisa como mensagem, mas não fura silêncio nem + // arquivo. + const onReaction = ( + conversation: Conversation, + reaction: { authorName: string; emoji: string; text: string }, + ) => { + if (inUse() || conversation.muted || conversation.archived) return; + const isGroup = conversation.kind === "group"; + if (isGroup && squelched(conversation.id)) return; + const text = reactionNotification( + { conversationName: conversation.name, isGroup, ...reaction }, + getNotifierState().prefs.previews, + ); + alert(isGroup ? "groups" : "messages", text.title, { + body: text.body, + tag: conversation.id, + url: `/chat?c=${conversation.id}`, + onClick: () => openConversationRef.current(conversation.id), + }); + }; + // @modulo:fim + + const onEvent = (event: RealtimeEvent) => { + switch (event.type) { + case "notification": + case "read": + case "unread": + queryClient.setQueryData(unreadNotificationsQuery.queryKey, event.unread); + void queryClient.invalidateQueries({ queryKey: ["notifications", "list"] }); + if (event.type === "notification") onNotice(event.notification, event.unread); + if (event.type === "read") closeSystemNotifications(event.ids); + break; + case "noticeMute": + queryClient.setQueryData(noticeMuteQuery.queryKey, { + muted: event.muted, + mutedUntil: event.mutedUntil, + }); + break; + // @modulo:chat + case "conversation": + applyConversation(queryClient, event.conversation); + // Lida aqui, em outra aba ou em outro computador: a notificação dela some. + if (!isUnread(event.conversation)) closeSystemNotifications([event.conversation.id]); + break; + case "message": + applyMessage(queryClient, event.message); + applyConversation(queryClient, event.conversation); + if (event.message.authorId === user.id) { + closeSystemNotifications([event.conversation.id]); + } else { + onMessage(event.message, event.conversation); + } + break; + case "reaction": + applyMessage(queryClient, event.message); + applyConversation(queryClient, event.conversation); + if (event.reaction) onReaction(event.conversation, event.reaction); + break; + // @modulo:fim + } + }; + + return connectRealtime({ + pushEndpoint, + onEvent, + onOpen: () => { + setOffline(false); + // O que chegou com a conexão caída. + void queryClient.invalidateQueries({ queryKey: ["notifications"] }); + const unreadIds = [unreadNotificationIds()]; + // @modulo:chat + void queryClient.invalidateQueries({ queryKey: ["chat"] }); + unreadIds.push(unreadConversationIds()); + // @modulo:fim + void Promise.all(unreadIds) + .then((lists) => closeSystemNotificationsExcept(lists.flat())) + .catch(() => {}); + }, + onOffline: () => setOffline(true), + }); + }, [pushEndpoint, queryClient, user.id]); + + // Contador da aba: avisos (fora os silenciados) e conversas com mensagem não lida. + const counts = [isMutedNow(noticeMute.data) ? 0 : (notices.data ?? 0)]; + // @modulo:chat + counts.push(conversations.data ?? 0); + // @modulo:fim + const unread = counts.reduce((sum, count) => sum + count, 0); + + // A troca de tela troca o título (meta da rota): o "(N)" volta na frente dele. + useEffect(() => { + renderDocumentBadge(unread, offline); + const observer = new MutationObserver(() => renderDocumentBadge(unread, offline)); + const title = document.querySelector("title"); + if (title) observer.observe(title, { childList: true }); + return () => observer.disconnect(); + }, [unread, offline]); + + useEffect(() => () => renderDocumentBadge(0, false), []); + + // Permissão trocada pelo cadeado do navegador, áudio liberado no primeiro clique, notificações da + // página fechadas ao sair dela, clique no push com a aba aberta (pelo service worker). + useEffect(() => { + void registerServiceWorker(); + const removeAudioUnlock = installAudioUnlock(); + let permissionStatus: PermissionStatus | null = null; + let detached = false; + navigator.permissions + ?.query({ name: "notifications" as PermissionName }) + .then((status) => { + if (detached) return; + permissionStatus = status; + status.addEventListener("change", refreshPermission); + }) + .catch(() => {}); + window.addEventListener("focus", refreshPermission); + window.addEventListener("pagehide", closePageNotifications); + + const onWorkerMessage = (event: MessageEvent) => { + const data = event.data as { + type?: string; + id?: string; + url?: string | null; + kind?: string; + } | null; + if (data?.type !== "abrir-notificacao" || typeof data.id !== "string") return; + // @modulo:chat + if (data.kind === "conversation") { + openConversationRef.current(data.id); + return; + } + // @modulo:fim + openNoticeRef.current(data.id, data.url ?? null); + }; + navigator.serviceWorker?.addEventListener("message", onWorkerMessage); + + // Aberto pelo clique num push com o app fechado: o service worker abriu a URL com o id. + const params = new URLSearchParams(window.location.search); + const openedId = params.get(OPENED_PARAM); + if (openedId) { + params.delete(OPENED_PARAM); + const query = params.toString(); + window.history.replaceState( + null, + "", + `${window.location.pathname}${query ? `?${query}` : ""}`, + ); + openedFromPush(openedId); + } + + return () => { + detached = true; + permissionStatus?.removeEventListener("change", refreshPermission); + window.removeEventListener("focus", refreshPermission); + window.removeEventListener("pagehide", closePageNotifications); + navigator.serviceWorker?.removeEventListener("message", onWorkerMessage); + removeAudioUnlock(); + closePageNotifications(); + forgetSquelches(); + }; + }, []); + + return null; +} + +// Aberto pelo clique num push: na conversa, o cursor vai para o campo; no aviso, ele é marcado como +// lido. +function openedFromPush(id: string) { + // @modulo:chat + if (window.location.pathname.startsWith("/chat")) { + requestComposerFocus(id); + return; + } + // @modulo:fim + void api.patch(`/notifications/${id}`, { read: true }).catch(() => {}); +} + +// Logout: as configurações e a inscrição deste navegador não passam para o próximo usuário. Chamado +// pelo layout no "Sair", e não no unmount: em dev o StrictMode desmonta e monta de novo, e o cancelamento +// atrasado derrubaria a inscrição recém-criada. +export function leaveNotifications() { + resetPreferences(); + dropLocalPushSubscription(); +} diff --git a/app/components/layout/NotificationItem.tsx b/app/components/layout/NotificationItem.tsx new file mode 100644 index 0000000..4123650 --- /dev/null +++ b/app/components/layout/NotificationItem.tsx @@ -0,0 +1,191 @@ +import { infiniteQueryOptions, useQuery } from "@tanstack/react-query"; +import { Archive, ArchiveRestore, Bell, Mail, MailOpen, MoreVertical } from "lucide-react"; +import { MuteMenuItems } from "~/components/patterns/MuteMenuItems"; +import { Button } from "~/components/ui/button"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from "~/components/ui/dropdown-menu"; +import { api } from "~/lib/api"; +import { formatDateTime } from "~/lib/format"; +import { + isMutedNow, + noticeMuteQuery, + useSetNoticeMute, + useUpdateNotification, +} from "~/lib/notifier/notifications.queries"; +import { cn } from "~/lib/utils"; +import type { AppNotification, NotificationPage } from "~/types/notification"; + +// Item de notificação e a lista paginada, usados no painel do sininho e na busca. + +const PAGE_SIZE = 20; + +export type NotificationFilters = { + search?: string; + read?: "true" | "false"; + archived?: boolean; +}; + +// Página a página conforme rola. Fica sob ["notifications", "list"]: o stream invalida quando chega +// ou muda uma notificação. +export const notificationPagesQuery = (filters: NotificationFilters) => + infiniteQueryOptions({ + queryKey: ["notifications", "list", "pages", filters], + queryFn: ({ pageParam, signal }) => { + const query = new URLSearchParams({ page: String(pageParam), pageSize: String(PAGE_SIZE) }); + if (filters.search) query.set("search", filters.search); + if (filters.read) query.set("read", filters.read); + if (filters.archived) query.set("archived", "true"); + return api.get(`/notifications?${query.toString()}`, { signal }); + }, + initialPageParam: 1, + getNextPageParam: (last) => + last.meta.page * last.meta.pageSize < last.meta.total ? last.meta.page + 1 : undefined, + }); + +// Perto do fim da lista rolável, busca a próxima página. +export function loadMoreOnScroll(list: { + hasNextPage: boolean; + isFetchingNextPage: boolean; + fetchNextPage: () => unknown; +}) { + return (event: React.UIEvent) => { + const el = event.currentTarget; + if ( + el.scrollHeight - el.scrollTop - el.clientHeight < 200 && + list.hasNextPage && + !list.isFetchingNextPage + ) { + void list.fetchNextPage(); + } + }; +} + +const relative = new Intl.RelativeTimeFormat("pt-BR", { numeric: "auto" }); +const UNITS: [Intl.RelativeTimeFormatUnit, number][] = [ + ["year", 365 * 24 * 3600], + ["month", 30 * 24 * 3600], + ["week", 7 * 24 * 3600], + ["day", 24 * 3600], + ["hour", 3600], + ["minute", 60], +]; + +// "há 18 horas", "há 2 dias", "agora". +function timeAgo(iso: string) { + const seconds = Math.round((new Date(iso).getTime() - Date.now()) / 1000); + for (const [unit, size] of UNITS) { + if (Math.abs(seconds) >= size) return relative.format(Math.trunc(seconds / size), unit); + } + return "agora"; +} + +function initials(name: string) { + const parts = name.trim().split(/\s+/); + return ( + (parts[0]?.[0] ?? "") + (parts.length > 1 ? (parts.at(-1)?.[0] ?? "") : "") + ).toUpperCase(); +} + +// Ações de uma notificação: lida ou não lida, arquivar ou desarquivar e silenciar os avisos. +function ItemMenu({ notification }: { notification: AppNotification }) { + const update = useUpdateNotification(); + const mute = useQuery(noticeMuteQuery); + const setMute = useSetNoticeMute(); + return ( + + + + + + update.mutate({ id: notification.id, read: !notification.read })} + > + {notification.read ? : } + {notification.read ? "Marcar como não lida" : "Marcar como lida"} + + update.mutate({ id: notification.id, archived: !notification.archived })} + > + {notification.archived ? : } + {notification.archived ? "Desarquivar" : "Arquivar"} + + + setMute.mutate(option)} + /> + + + ); +} + +export function NotificationItem({ + notification, + onOpen, +}: { + notification: AppNotification; + onOpen: (notification: AppNotification) => void; +}) { + const n = notification; + return ( +
  • + {/* Bolinha à esquerda: não lida. */} + + + {/* Acima do botão que cobre a linha, para o menu abrir sem abrir a notificação. */} +
    + +
    +
  • + ); +} diff --git a/app/components/layout/NotificationSearchDialog.tsx b/app/components/layout/NotificationSearchDialog.tsx new file mode 100644 index 0000000..b3f0651 --- /dev/null +++ b/app/components/layout/NotificationSearchDialog.tsx @@ -0,0 +1,166 @@ +import { useInfiniteQuery } from "@tanstack/react-query"; +import { Archive, Search, SearchX } from "lucide-react"; +import { useState } from "react"; +import { useNavigate } from "react-router"; +import { ErrorState } from "~/components/patterns/EmptyState"; +import { Dialog, DialogContent, DialogDescription, DialogTitle } from "~/components/ui/dialog"; +import { Input } from "~/components/ui/input"; +import { useDebouncedValue } from "~/hooks/useDebouncedValue"; +import { useUpdateNotification } from "~/lib/notifier/notifications.queries"; +import { cn } from "~/lib/utils"; +import type { AppNotification } from "~/types/notification"; +import { loadMoreOnScroll, NotificationItem, notificationPagesQuery } from "./NotificationItem"; + +type Status = "all" | "false" | "true"; +type Folder = "inbox" | "archived"; + +const STATUS_LABELS: Record = { all: "Todas", false: "Não lidas", true: "Lidas" }; +const FOLDER_LABELS: Record = { inbox: "Recebidas", archived: "Arquivadas" }; + +function Chips({ + label, + labels, + value, + onChange, +}: { + label: string; + labels: Record; + value: T; + onChange: (value: T) => void; +}) { + return ( +
    + {(Object.keys(labels) as T[]).map((key) => ( + + ))} +
    + ); +} + +// Busca nas notificações, aberta pela lupa do painel do sininho. Procura no título e no texto, com +// filtro de lidas e a pasta das arquivadas. +export function NotificationSearchDialog({ + open, + onOpenChange, +}: { + open: boolean; + onOpenChange: (open: boolean) => void; +}) { + const [text, setText] = useState(""); + const [status, setStatus] = useState("all"); + const [folder, setFolder] = useState("inbox"); + const search = useDebouncedValue(text.trim()); + const list = useInfiniteQuery({ + ...notificationPagesQuery({ + search: search || undefined, + read: status === "all" ? undefined : status, + archived: folder === "archived", + }), + enabled: open, + }); + const update = useUpdateNotification(); + const navigate = useNavigate(); + + const items = list.data?.pages.flatMap((page) => page.data) ?? []; + const total = list.data?.pages[0]?.meta.total ?? 0; + const filtered = Boolean(search) || status !== "all"; + + function openNotification(notification: AppNotification) { + if (!notification.read) update.mutate({ id: notification.id, read: true }); + onOpenChange(false); + if (notification.url) navigate(notification.url); + } + + return ( + + +
    +
    + Buscar notificações + + Procura no título e no texto. Aceita titulo:valor e texto:valor. + +
    +
    + + setText(event.target.value)} + /> +
    +
    + + +
    +
    +
    + {list.isLoading ? ( +

    + Carregando... +

    + ) : list.error ? ( + list.refetch()} /> + ) : items.length === 0 ? ( +
    + {filtered ? ( + + ) : ( + + )} +

    + {filtered + ? "Nenhuma notificação encontrada" + : folder === "archived" + ? "Nenhuma notificação arquivada" + : "Nenhuma notificação"} +

    + {filtered && ( +

    + Ajuste a busca ou os filtros. +

    + )} +
    + ) : ( + <> +

    + {total === 1 ? "1 notificação" : `${total} notificações`} +

    +
      + {items.map((n) => ( + + ))} +
    + {list.isFetchingNextPage && ( +

    + Carregando mais... +

    + )} + + )} +
    +
    +
    + ); +} diff --git a/app/components/layout/NotificationSettingsDialog.tsx b/app/components/layout/NotificationSettingsDialog.tsx new file mode 100644 index 0000000..d94ca60 --- /dev/null +++ b/app/components/layout/NotificationSettingsDialog.tsx @@ -0,0 +1,242 @@ +import { BellRing, Volume2, VolumeX } from "lucide-react"; +import { useId, useState } from "react"; +import { SearchableSelect } from "~/components/patterns/SearchableSelect"; +import { Button } from "~/components/ui/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from "~/components/ui/dialog"; +import { Label } from "~/components/ui/label"; +import { Slider } from "~/components/ui/slider"; +import { Switch } from "~/components/ui/switch"; +import { requestPermission, updatePreferences, useNotifierState } from "~/lib/notifier/preferences"; +import { previewSound, SOUND_LABELS } from "~/lib/notifier/sounds"; +import { + isMuted, + NOTIFICATION_SOUNDS, + type NotificationKind, + type NotificationSound, +} from "~/types/notification"; + +const KINDS: { kind: NotificationKind; title: string; description: string }[] = [ + // @modulo:chat + { kind: "messages", title: "Mensagens", description: "Conversas de duas pessoas" }, + { kind: "groups", title: "Grupos", description: "Conversas em grupo" }, + // @modulo:fim + { kind: "notices", title: "Avisos", description: "Avisos do sistema, na tela Notificações" }, +]; + +function ToggleRow({ + label, + description, + checked, + onChange, +}: { + label: string; + description?: string; + checked: boolean; + onChange: (value: boolean) => void; +}) { + const id = useId(); + return ( +
    +
    + + {description && ( +

    {description}

    + )} +
    + +
    + ); +} + +// Silêncio temporário, em minutos. "0" desliga o silêncio. +const MUTE_DURATIONS = [ + { value: "0", label: "Não silenciar" }, + { value: "30", label: "30 minutos" }, + { value: "60", label: "1 hora" }, + { value: "480", label: "8 horas" }, + { value: "1440", label: "24 horas" }, +]; + +const SOUND_OPTIONS = NOTIFICATION_SOUNDS.map((sound) => ({ + value: sound, + label: SOUND_LABELS[sound], +})); + +const timeFormat = new Intl.DateTimeFormat("pt-BR", { + weekday: "short", + hour: "2-digit", + minute: "2-digit", +}); + +// Configurações de notificação (menu do perfil). Cada mudança vale na hora e fica neste navegador. +export function NotificationSettingsDialog({ + open, + onOpenChange, +}: { + open: boolean; + onOpenChange: (open: boolean) => void; +}) { + const { prefs, permission } = useNotifierState(); + const setKind = (kind: NotificationKind, field: "show" | "sound", value: boolean) => + updatePreferences({ ...prefs, [kind]: { ...prefs[kind], [field]: value } }); + + // O volume muda na tela enquanto arrasta e só grava ao soltar: cada gravação reenvia a inscrição + // de push ao servidor. + const [dragVolume, setDragVolume] = useState(null); + const volume = dragVolume ?? prefs.volume; + + const muted = isMuted(prefs); + const mutedHint = !muted + ? "Desliga o som de todos os avisos. As notificações continuam aparecendo." + : prefs.mutedUntil === null + ? "Silenciado até você desligar." + : `Silenciado até ${timeFormat.format(prefs.mutedUntil)}.`; + + const setMuteDuration = (value: string) => { + const minutes = Number(value); + updatePreferences({ + ...prefs, + muted: minutes > 0, + mutedUntil: minutes > 0 ? Date.now() + minutes * 60_000 : null, + }); + }; + + const setSound = (sound: NotificationSound) => { + updatePreferences({ ...prefs, sound }); + previewSound(sound, volume); + }; + + const permissionHint = + permission === "unsupported" + ? "Este navegador não mostra notificações, ou o site não está em HTTPS. O contador continua." + : permission === "denied" + ? "Bloqueadas neste navegador: clique no cadeado ao lado do endereço do site, em Notificações escolha Permitir e recarregue a página." + : null; + + return ( + + + + Notificações + + Só com a janela sem foco, como no WhatsApp Web. Valem só neste navegador. + + +
    + {permission === "default" && ( + + )} + {permissionHint && ( +

    + {permissionHint} +

    + )} +
    + updatePreferences({ ...prefs, muted: value, mutedUntil: null })} + /> +
    +
    + + +
    +
    + + setSound(value as NotificationSound)} + /> +
    +
    +
    +
    + + + {Math.round(volume * 100)}% + +
    +
    + {volume === 0 ? ( + + ) : ( + + )} + setDragVolume(value)} + onValueCommit={([value]) => { + setDragVolume(null); + updatePreferences({ ...prefs, volume: value }); + previewSound(prefs.sound, value); + }} + /> +
    +
    + +
    + {KINDS.map(({ kind, title, description }) => ( +
    +

    {title}

    +

    {description}

    + setKind(kind, "show", value)} + /> + setKind(kind, "sound", value)} + /> +
    + ))} +
    + updatePreferences({ ...prefs, previews: value })} + /> +
    +
    +
    +
    + ); +} diff --git a/app/components/layout/PageHeader.tsx b/app/components/layout/PageHeader.tsx index 8f1114b..cd032de 100644 --- a/app/components/layout/PageHeader.tsx +++ b/app/components/layout/PageHeader.tsx @@ -1,7 +1,11 @@ +// @modulo:notificacoes +import { NotificationBell } from "./NotificationBell"; +// @modulo:fim + type PageHeaderProps = { title: string; description?: string; - // Botões da tela (criar, exportar), alinhados à direita. + // Botões da tela (criar, exportar), alinhados à direita, antes do sininho. actions?: React.ReactNode; }; @@ -14,7 +18,13 @@ export function PageHeader({ title, description, actions }: PageHeaderProps) {

    {description}

    )}
    - {actions &&
    {actions}
    } + {/* Botões da tela e, com as notificações, o sininho depois deles, em todas as telas. */} +
    + {actions} + {/* @modulo:notificacoes */} + + {/* @modulo:fim */} +
    ); } diff --git a/app/components/layout/ProfileMenu.tsx b/app/components/layout/ProfileMenu.tsx index 620f04e..8a952b9 100644 --- a/app/components/layout/ProfileMenu.tsx +++ b/app/components/layout/ProfileMenu.tsx @@ -12,6 +12,11 @@ import { ROLE_LABELS } from "~/lib/labels"; import { useTheme } from "~/lib/theme"; import { cn } from "~/lib/utils"; import type { User } from "~/types/user"; +// @modulo:notificacoes +import { Bell } from "lucide-react"; +import { useState } from "react"; +import { NotificationSettingsDialog } from "./NotificationSettingsDialog"; +// @modulo:fim type ProfileMenuProps = { user: User; @@ -53,46 +58,72 @@ export function ProfileMenu({ }: ProfileMenuProps) { const { theme, toggleTheme } = useTheme(); const dark = theme === "dark"; + // @modulo:notificacoes + const [notificationsOpen, setNotificationsOpen] = useState(false); + // @modulo:fim return ( - - {children} - - -

    {user.fullName}

    -

    {ROLE_LABELS[user.role]}

    -

    {user.email}

    -
    - - {/* Trocar o tema não fecha o menu: dá para ver o resultado e voltar. */} - { - event.preventDefault(); - toggleTheme(); - }} - className="gap-2.5 px-3 py-2" + <> + + {children} + notificationsOpen && event.preventDefault()} + // @modulo:fim > - - Tema escuro - - + +

    {user.fullName}

    +

    {ROLE_LABELS[user.role]}

    +

    {user.email}

    +
    + + {/* Trocar o tema não fecha o menu: dá para ver o resultado e voltar. */} + { + event.preventDefault(); + toggleTheme(); + }} + className="gap-2.5 px-3 py-2" + > + + Tema escuro + + + + + + + Meu perfil + + - - - - Meu perfil - - + {/* @modulo:notificacoes */} + setNotificationsOpen(true)} + className="gap-2.5 px-3 py-2" + > + + Notificações + + {/* @modulo:fim */} - + - - - Sair - -
    -
    + + + Sair + + + + {/* @modulo:notificacoes */} + + {/* @modulo:fim */} + ); } diff --git a/app/components/layout/Sidebar.tsx b/app/components/layout/Sidebar.tsx index 1ccf556..45bf6d9 100644 --- a/app/components/layout/Sidebar.tsx +++ b/app/components/layout/Sidebar.tsx @@ -13,6 +13,7 @@ import { import { Tooltip, TooltipContent, TooltipTrigger } from "~/components/ui/tooltip"; import { APP_NAME } from "~/config/app"; import { visibleNavigation, type NavItem, type NavSection } from "~/config/navigation"; +import { formatCounter, useNavCounter } from "~/hooks/useNavCounter"; import { cn } from "~/lib/utils"; import type { User } from "~/types/user"; import { ProfileMenu } from "./ProfileMenu"; @@ -79,12 +80,14 @@ function SidebarLink({ item, collapsed }: { item: NavItem; collapsed: boolean }) // dentro do TooltipTrigger (Slot do Radix), que mescla className como texto e quebraria a função. const active = isItemActive(item, pathname); const Icon = item.icon; + const { count, muted } = useNavCounter(item.counter); + const label = count > 0 ? `${item.label} (${formatCounter(count)})` : item.label; return ( - + 0 ? label : undefined} className={cn( "group/item relative flex items-center gap-2.5 rounded-lg px-2 py-1.5 text-xs font-bold transition-all duration-200 ease-ui", collapsed && "justify-center px-0", @@ -93,10 +96,30 @@ function SidebarLink({ item, collapsed }: { item: NavItem; collapsed: boolean }) : "text-muted-foreground hover:bg-accent hover:text-foreground", )} > - - - - {!collapsed && {item.label}} + + + + + {collapsed && count > 0 && ( + + )} + + {!collapsed && {item.label}} + {!collapsed && count > 0 && ( + + {formatCounter(count)} + + )} ); diff --git a/app/components/layout/SingleTabGate.tsx b/app/components/layout/SingleTabGate.tsx new file mode 100644 index 0000000..384cd55 --- /dev/null +++ b/app/components/layout/SingleTabGate.tsx @@ -0,0 +1,80 @@ +import { AppWindow } from "lucide-react"; +import { useEffect, useSyncExternalStore } from "react"; +import { Button } from "~/components/ui/button"; +import { APP_NAME, SINGLE_TAB } from "~/config/app"; + +const TAB_LOCK = "app-aba"; +// A trava não respondeu: abre o app em vez de deixar a tela em branco. +const CHECK_TIMEOUT_MS = 2_000; + +type TabState = "checking" | "active" | "blocked"; + +const supported = SINGLE_TAB && typeof navigator !== "undefined" && !!navigator.locks; +let state: TabState = supported ? "checking" : "active"; +let started = false; +const listeners = new Set<() => void>(); + +function setState(next: TabState) { + if (state === next) return; + state = next; + listeners.forEach((listener) => listener()); +} + +// Uma trava por página, fora do ciclo do React (em dev o StrictMode monta tudo duas vezes, e a trava +// pedida pelo componente ficaria presa na primeira). Segurada até a página fechar. `steal` ("Usar +// aqui") toma a da outra aba, que cai no catch e passa a mostrar o aviso. +function requestTab(steal: boolean) { + navigator.locks + .request(TAB_LOCK, steal ? { steal: true } : { ifAvailable: true }, (lock) => { + if (!lock) { + setState("blocked"); + return; + } + setState("active"); + return new Promise(() => {}); + }) + .catch(() => setState("blocked")); +} + +function start() { + if (!supported || started) return; + started = true; + requestTab(false); + setTimeout(() => { + if (state === "checking") setState("active"); + }, CHECK_TIMEOUT_MS); +} + +function subscribe(listener: () => void) { + listeners.add(listener); + return () => listeners.delete(listener); +} + +// Uma aba do app por navegador (SINGLE_TAB em config/app.ts). A trava é do endereço do site: apps +// em endereços diferentes abrem juntos sem se enxergar. Navegador sem Web Locks não bloqueia. +export function SingleTabGate({ children }: { children: React.ReactNode }) { + const tab = useSyncExternalStore( + subscribe, + () => state, + () => "active" as TabState, + ); + useEffect(start, []); + + if (tab === "checking") return null; + if (tab === "active") return children; + + return ( +
    +
    + +

    O {APP_NAME} está aberto em outra aba

    +

    + Clique em "Usar aqui" para usar o {APP_NAME} nesta aba. A outra para de funcionar. +

    + +
    +
    + ); +} diff --git a/app/components/layout/Splash.tsx b/app/components/layout/Splash.tsx index 9807989..fd045fe 100644 --- a/app/components/layout/Splash.tsx +++ b/app/components/layout/Splash.tsx @@ -3,7 +3,7 @@ import { Layers } from "lucide-react"; // Tela de carregamento: vai dentro do index.html (HydrateFallback) e aparece enquanto o JS carrega. export function Splash() { return ( -
    +
    diff --git a/app/components/patterns/DataTable.tsx b/app/components/patterns/DataTable.tsx index 12379cc..cbd948e 100644 --- a/app/components/patterns/DataTable.tsx +++ b/app/components/patterns/DataTable.tsx @@ -1,5 +1,7 @@ import { ArrowDown, ArrowUp, ArrowUpDown, ChevronLeft, ChevronRight } from "lucide-react"; +import { createContext, Fragment, useContext, useId } from "react"; import { Button } from "~/components/ui/button"; +import { Label } from "~/components/ui/label"; import { Skeleton } from "~/components/ui/skeleton"; import { Table, @@ -13,6 +15,7 @@ import { formatNumber } from "~/lib/format"; import { cn } from "~/lib/utils"; import { EmptyState, ErrorState } from "./EmptyState"; import { ListToolbar, type ListSearch } from "./ListToolbar"; +import { SearchableSelect } from "./SearchableSelect"; export type Column = { key: string; @@ -21,6 +24,9 @@ export type Column = { // Campo de ordenação na API. Sem ele, a coluna não ordena. sortField?: string; className?: string; + // No celular a tabela vira lista de cards: a primeira coluna é o título do card e as outras viram + // pares rótulo e valor. Coluna secundária pode sair do card. + hideOnMobile?: boolean; }; type DataTableProps = { @@ -44,6 +50,8 @@ type DataTableProps = { }; onRowClick?: (row: T) => void; rowLabel?: (row: T) => string; + // Clique direito na linha (menu de ações dela). + onRowContextMenu?: (row: T) => void; empty: React.ComponentProps; }; @@ -76,6 +84,49 @@ function SortButton({ ); } +// Ordenação no celular, onde não há cabeçalho de coluna para clicar: cada coluna ordenável vira duas +// opções, crescente e decrescente. +function MobileSort({ + columns, + sort, + onSortChange, +}: { + columns: Column[]; + sort?: string; + onSortChange: (sort: string) => void; +}) { + const id = useId(); + const options = columns.flatMap((column) => + column.sortField + ? [ + { value: column.sortField, label: `${column.header} (crescente)` }, + { value: `-${column.sortField}`, label: `${column.header} (decrescente)` }, + ] + : [], + ); + if (options.length === 0) return null; + return ( +
    + + +
    + ); +} + +// Onde a célula está: nos cards (celular) ou na tabela (desktop). As duas são montadas e só uma +// aparece; um menu controlado pela página abre só na que está na tela. +const VariantContext = createContext<"cards" | "table">("table"); +export const useDataTableVariant = () => useContext(VariantContext); + // Padding das células: mais folga na primeira e na última coluna, alinhado com a barra de busca. const cellPadding = "px-4 first:pl-6 last:pr-6"; @@ -93,9 +144,40 @@ export function DataTable({ pagination, onRowClick, rowLabel, + onRowContextMenu, empty, }: DataTableProps) { const showSkeleton = isLoading && !rows; + const [titleColumn, ...detailColumns] = columns; + const mobileColumns = detailColumns.filter((column) => !column.hideOnMobile); + + const contextMenuProps = (row: T) => + onRowContextMenu + ? { + onContextMenu: (event: React.MouseEvent) => { + event.preventDefault(); + onRowContextMenu(row); + }, + } + : {}; + + // Linha e card abrem o item do mesmo jeito: clique, Enter ou espaço. + const rowProps = (row: T) => ({ + ...contextMenuProps(row), + ...(onRowClick + ? { + onClick: () => onRowClick(row), + onKeyDown: (event: React.KeyboardEvent) => { + if (event.key === "Enter" || event.key === " ") { + event.preventDefault(); + onRowClick(row); + } + }, + tabIndex: 0, + "aria-label": rowLabel?.(row), + } + : {}), + }); const totalPages = pagination ? Math.max(1, Math.ceil(pagination.total / pagination.pageSize)) : 1; @@ -109,85 +191,118 @@ export function DataTable({ ) : !showSkeleton && rows?.length === 0 ? ( ) : ( - - - - {columns.map((column) => { - const direction = - column.sortField && sort === column.sortField - ? "ascending" - : column.sortField && sort === `-${column.sortField}` - ? "descending" - : undefined; - return ( - - {column.sortField && onSortChange ? ( - - ) : ( - column.header - )} - - ); - })} - - - - {showSkeleton - ? Array.from({ length: 5 }, (_, index) => ( - - {columns.map((column) => ( - - - - ))} - - )) - : rows?.map((row) => ( - onRowClick(row) : undefined} - onKeyDown={ - onRowClick - ? (event) => { - if (event.key === "Enter" || event.key === " ") { - event.preventDefault(); - onRowClick(row); - } - } - : undefined - } - tabIndex={onRowClick ? 0 : undefined} - aria-label={onRowClick && rowLabel ? rowLabel(row) : undefined} - className={cn( - onRowClick && - "cursor-pointer focus-visible:bg-accent focus-visible:outline-none", - )} - > - {columns.map((column) => ( - + {sort !== undefined && onSortChange && ( + + )} + +
      + {showSkeleton + ? Array.from({ length: 3 }, (_, index) => ( +
    • + + +
    • + )) + : rows?.map((row) => ( +
    • +
      +
      {titleColumn.cell(row)}
      + {mobileColumns.length > 0 && ( +
      + {mobileColumns.map((column) => ( + +
      + {column.header} +
      +
      {column.cell(row)}
      +
      + ))} +
      + )} +
      +
    • + ))} +
    +
    +
    +
    + + + {columns.map((column) => { + const direction = + column.sortField && sort === column.sortField + ? "ascending" + : column.sortField && sort === `-${column.sortField}` + ? "descending" + : undefined; + return ( + - {column.cell(row)} - + {column.sortField && onSortChange ? ( + + ) : ( + column.header + )} + + ); + })} + + + + {showSkeleton + ? Array.from({ length: 5 }, (_, index) => ( + + {columns.map((column) => ( + + + + ))} + + )) + : rows?.map((row) => ( + + {columns.map((column) => ( + + {column.cell(row)} + + ))} + ))} - - ))} - -
    + + +
    + )} {pagination && pagination.total > 0 && ( diff --git a/app/components/patterns/EntityDrawer.tsx b/app/components/patterns/EntityDrawer.tsx index 401adce..60589ce 100644 --- a/app/components/patterns/EntityDrawer.tsx +++ b/app/components/patterns/EntityDrawer.tsx @@ -28,7 +28,7 @@ export function EntityDrawer({ }: EntityDrawerProps) { return ( - + {title} {description && {description}} diff --git a/app/components/patterns/ListToolbar.tsx b/app/components/patterns/ListToolbar.tsx index aaba57f..388f8ce 100644 --- a/app/components/patterns/ListToolbar.tsx +++ b/app/components/patterns/ListToolbar.tsx @@ -1,8 +1,30 @@ -import { Search } from "lucide-react"; +import { CalendarDays, ListFilter, Search, X } from "lucide-react"; +import { useId, useMemo, useRef } from "react"; +import { Button } from "~/components/ui/button"; import { Input } from "~/components/ui/input"; +import { Label } from "~/components/ui/label"; +import { Popover, PopoverContent, PopoverTrigger } from "~/components/ui/popover"; +import { + MAX_SEARCH_LENGTH, + MIN_SEARCH_LENGTH, + periodFromTerm, + shortValueKeys, + withPeriod, + type SearchKey, +} from "~/lib/search"; // Toda lista é pesquisável: a busca é obrigatória e vai para a API (?search=), não filtra no navegador. -export type ListSearch = { value: string; onChange: (value: string) => void; placeholder: string }; +// A caixa aceita texto livre e `campo:valor` (server/lib/search.ts). `keys` são as chaves da lista e +// `periodLabel` liga o período (`de:` e `ate:`); sem eles, a caixa é só texto livre. +export type ListSearch = { + value: string; + onChange: (value: string) => void; + placeholder: string; + // Tem texto e não alcança o mínimo. Vem do useListSearch. + tooShort?: boolean; + keys?: readonly SearchKey[]; + periodLabel?: string; +}; // Barra de uma lista: busca e, ao lado, o FilterButton. O DataTable já a inclui; uma lista que não é // tabela (kanban, cards) usa esta barra direto, no topo do próprio card. @@ -14,19 +36,173 @@ export function ListToolbar({ filters?: React.ReactNode; }) { return ( -
    -
    +
    + + {filters} +
    + ); +} + +function SearchBox({ search }: { search: ListSearch }) { + const { value, onChange, placeholder, tooShort = false, keys = [], periodLabel } = search; + const inputRef = useRef(null); + const hintId = useId(); + const fromId = useId(); + const toId = useId(); + + const shortKeys = useMemo(() => shortValueKeys(value, keys), [value, keys]); + const period = useMemo(() => periodFromTerm(value), [value]); + const hasPanel = keys.length > 0 || Boolean(periodLabel); + + // O que o servidor descartaria em silêncio, dito antes. + const hint = tooShort + ? `Digite ao menos ${MIN_SEARCH_LENGTH} caracteres para buscar.` + : shortKeys.length > 0 + ? `O valor de ${shortKeys.map((k) => `${k}:`).join(", ")} é curto demais: esse filtro foi ignorado.` + : null; + + // Põe `chave:` no fim do que já está digitado e devolve o cursor para a caixa. + function insertKey(key: string) { + const base = value.trimEnd(); + onChange(base ? `${base} ${key}:` : `${key}:`); + inputRef.current?.focus(); + } + + return ( +
    +
    search.onChange(event.target.value)} - className="pl-9" + aria-label={placeholder} + aria-describedby={hint ? hintId : undefined} + placeholder={placeholder} + value={value} + onChange={(event) => onChange(event.target.value)} + // Impede a digitação em vez de o servidor recusar depois. + maxLength={MAX_SEARCH_LENGTH} + className="pr-16 pl-9 [&::-webkit-search-cancel-button]:hidden" /> + +
    + {value && ( + + )} + + {hasPanel && ( + + + + + + {keys.length > 0 && ( +
    +

    Filtrar por campo

    +

    + Digitar o valor direto já encontra. Use o campo quando o termo for ambíguo. +

    +
    + {keys.map(({ key, label }) => ( + + ))} +
    +
    + )} + + {periodLabel && ( +
    +
    +

    + + {periodLabel} +

    + +
    +
    +
    + + + onChange(withPeriod(value, { ...period, from: event.target.value })) + } + /> +
    +
    + + + onChange(withPeriod(value, { ...period, to: event.target.value })) + } + /> +
    +
    +
    + )} +
    +
    + )} +
    - {filters} + + {hint && ( +

    + {hint} +

    + )}
    ); } diff --git a/app/components/patterns/MuteMenuItems.tsx b/app/components/patterns/MuteMenuItems.tsx new file mode 100644 index 0000000..28bb516 --- /dev/null +++ b/app/components/patterns/MuteMenuItems.tsx @@ -0,0 +1,53 @@ +import { BellOff, BellRing } from "lucide-react"; +import { + DropdownMenuItem, + DropdownMenuSub, + DropdownMenuSubContent, + DropdownMenuSubTrigger, +} from "~/components/ui/dropdown-menu"; +import { MUTE_LABELS, type MuteOption } from "~/types/notification"; + +const OPTIONS = Object.entries(MUTE_LABELS) as [MuteOption, string][]; + +// "Silenciar" com 8 horas, 1 semana e Sempre, ou "Voltar a avisar" quando já está silenciado. Usado +// no menu das conversas e no dos avisos. +export function MuteMenuItems({ + muted, + label = "Silenciar", + onChange, +}: { + muted: boolean; + label?: string; + onChange: (option: MuteOption | null) => void; +}) { + if (muted) { + return ( + onChange(null)}> + + Voltar a avisar + + ); + } + return ( + + + + {label} + + + {OPTIONS.map(([option, text]) => ( + onChange(option)}> + {text} + + ))} + + + ); +} + +// "até 14:30 de 28/10" ou "sempre", para dizer até quando está silenciado. +export function mutedUntilLabel(mutedUntil: string | null) { + if (!mutedUntil) return "para sempre"; + const date = new Date(mutedUntil); + return `até ${date.toLocaleString("pt-BR", { dateStyle: "short", timeStyle: "short" })}`; +} diff --git a/app/components/ui/alert-dialog.tsx b/app/components/ui/alert-dialog.tsx index 1e53611..24c81bd 100644 --- a/app/components/ui/alert-dialog.tsx +++ b/app/components/ui/alert-dialog.tsx @@ -26,7 +26,7 @@ function AlertDialogOverlay({ ) { + const values = props.value ?? props.defaultValue ?? [props.min ?? 0]; + return ( + + + + + {values.map((_, index) => ( + + ))} + + ); +} + +export { Slider }; diff --git a/app/components/ui/switch.tsx b/app/components/ui/switch.tsx new file mode 100644 index 0000000..7629289 --- /dev/null +++ b/app/components/ui/switch.tsx @@ -0,0 +1,30 @@ +import * as React from "react"; +import { cn } from "~/lib/utils"; +import { Switch as SwitchPrimitive } from "radix-ui"; + +function Switch({ + className, + size = "default", + ...props +}: React.ComponentProps & { + size?: "sm" | "default"; +}) { + return ( + + + + ); +} + +export { Switch }; diff --git a/app/config/app.ts b/app/config/app.ts index b3df02a..5bd8d79 100644 --- a/app/config/app.ts +++ b/app/config/app.ts @@ -1,3 +1,7 @@ // Identidade do app. Troque aqui ao criar um projeto a partir do template. export const APP_NAME = "Default"; export const APP_TAGLINE = "Acesse a plataforma"; + +// Uma aba do app por navegador, como o WhatsApp Web: a segunda mostra "Usar aqui" e a primeira para +// (sem stream nem notificação em dobro). Desligue se o projeto precisa de várias abas abertas. +export const SINGLE_TAB = true; diff --git a/app/config/navigation.ts b/app/config/navigation.ts index dbeb6b1..15e5481 100644 --- a/app/config/navigation.ts +++ b/app/config/navigation.ts @@ -1,4 +1,7 @@ import { LayoutDashboard, Users, type LucideIcon } from "lucide-react"; +// @modulo:chat +import { MessageCircle } from "lucide-react"; +// @modulo:fim import type { Role } from "~/types/user"; export type NavItem = { @@ -9,6 +12,8 @@ export type NavItem = { end?: boolean; // Sem roles, todo usuário vê. Esconder o item é só conforto: o backend é quem barra. roles?: Role[]; + // Contador ao lado do item, pelo nome registrado em useNavCounter (o "unreadConversations" do chat). + counter?: string; }; export type NavSection = { title: string; items: NavItem[] }; @@ -17,7 +22,12 @@ export type NavSection = { title: string; items: NavItem[] }; export const NAVIGATION: NavSection[] = [ { title: "Principal", - items: [{ to: "/", label: "Dashboard", icon: LayoutDashboard, end: true }], + items: [ + { to: "/", label: "Dashboard", icon: LayoutDashboard, end: true }, + // @modulo:chat + { to: "/chat", label: "Conversas", icon: MessageCircle, counter: "unreadConversations" }, + // @modulo:fim + ], }, { title: "Administração", diff --git a/app/hooks/useListSearch.ts b/app/hooks/useListSearch.ts new file mode 100644 index 0000000..06289bd --- /dev/null +++ b/app/hooks/useListSearch.ts @@ -0,0 +1,23 @@ +import { useEffect, useState } from "react"; +import { useDebouncedValue } from "~/hooks/useDebouncedValue"; +import { useListParams } from "~/hooks/useListParams"; +import { MIN_SEARCH_LENGTH } from "~/lib/search"; + +// Termo da caixa de busca de uma lista. O digitado vai para a URL (?search=) depois de uma pausa e +// só a partir do mínimo, que o servidor recusa abaixo dele. Apagar tudo limpa a busca na hora. +export function useListSearch(current: string | undefined) { + const { set } = useListParams(); + const [value, setValue] = useState(current ?? ""); + const debounced = useDebouncedValue(value.trim()); + + const next = debounced.length >= MIN_SEARCH_LENGTH ? debounced : ""; + useEffect(() => { + if (next !== (current ?? "")) set({ search: next }); + }, [next, current, set]); + + // O aviso olha o digitado, e não o debounced: aparece enquanto a pessoa digita. + const typed = value.trim(); + const tooShort = typed.length > 0 && typed.length < MIN_SEARCH_LENGTH; + + return { value, onChange: setValue, tooShort }; +} diff --git a/app/hooks/useMediaQuery.ts b/app/hooks/useMediaQuery.ts new file mode 100644 index 0000000..8d27d80 --- /dev/null +++ b/app/hooks/useMediaQuery.ts @@ -0,0 +1,14 @@ +import { useSyncExternalStore } from "react"; + +// A media query casa agora, e acompanha a mudança (girar o celular, redimensionar a janela). +export function useMediaQuery(query: string) { + return useSyncExternalStore( + (onChange) => { + const list = window.matchMedia(query); + list.addEventListener("change", onChange); + return () => list.removeEventListener("change", onChange); + }, + () => window.matchMedia(query).matches, + () => false, + ); +} diff --git a/app/hooks/useNavCounter.ts b/app/hooks/useNavCounter.ts new file mode 100644 index 0000000..17a41ff --- /dev/null +++ b/app/hooks/useNavCounter.ts @@ -0,0 +1,23 @@ +// @modulo:chat +import { useQuery } from "@tanstack/react-query"; +import { unreadConversationsQuery } from "~/lib/chat/chat.queries"; +// @modulo:fim +import type { NavItem } from "~/config/navigation"; + +type Counter = { count: number; muted: boolean }; + +const NO_COUNT: Counter = { count: 0, muted: false }; + +// Número ao lado de um item da navegação, pelo nome do contador do item. O cache é o mesmo do "(N)" da +// aba, atualizado pelo stream. `muted` fica para um contador que respeite silêncio; as conversas não +// usam. Um módulo com contador acrescenta o dele aqui. +export function useNavCounter(counter: NavItem["counter"]): Counter { + const counts: Record = {}; + // @modulo:chat + const conversations = useQuery(unreadConversationsQuery); + counts.unreadConversations = { count: conversations.data ?? 0, muted: false }; + // @modulo:fim + return (counter && counts[counter]) || NO_COUNT; +} + +export const formatCounter = (count: number) => (count > 999 ? "999+" : String(count)); diff --git a/app/hooks/usePageAttention.ts b/app/hooks/usePageAttention.ts new file mode 100644 index 0000000..c1024fb --- /dev/null +++ b/app/hooks/usePageAttention.ts @@ -0,0 +1,21 @@ +import { useEffect, useState } from "react"; + +// O usuário está olhando o app: janela em foco e aba visível. +const attentive = () => + typeof document !== "undefined" && document.hasFocus() && document.visibilityState === "visible"; + +export function usePageAttention() { + const [value, setValue] = useState(attentive); + useEffect(() => { + const update = () => setValue(attentive()); + window.addEventListener("focus", update); + window.addEventListener("blur", update); + document.addEventListener("visibilitychange", update); + return () => { + window.removeEventListener("focus", update); + window.removeEventListener("blur", update); + document.removeEventListener("visibilitychange", update); + }; + }, []); + return value; +} diff --git a/app/lib/chat/chat.queries.ts b/app/lib/chat/chat.queries.ts new file mode 100644 index 0000000..d16d688 --- /dev/null +++ b/app/lib/chat/chat.queries.ts @@ -0,0 +1,183 @@ +import { + infiniteQueryOptions, + keepPreviousData, + queryOptions, + useMutation, + useQueryClient, + type InfiniteData, + type QueryClient, +} from "@tanstack/react-query"; +import type { + Contact, + Conversation, + ConversationFilter, + ConversationPage, + Message, + MessagePage, +} from "~/types/chat"; +import type { MuteOption } from "~/types/notification"; +import { api } from "../api"; + +// Queries do chat usadas fora da tela de Conversas também: o contador da sidebar e da aba, e o stream +// de eventos, que atualiza o cache sem buscar de novo. + +const LIST_PAGE_SIZE = 100; +const MESSAGES_PAGE_SIZE = 50; + +export const conversationsQuery = (filter: ConversationFilter, search?: string) => + queryOptions({ + queryKey: ["chat", "conversations", { filter, search: search ?? "" }], + queryFn: ({ signal }) => { + const query = new URLSearchParams({ filter, pageSize: String(LIST_PAGE_SIZE) }); + if (search) query.set("search", search); + return api.get(`/conversations?${query}`, { signal }); + }, + placeholderData: keepPreviousData, + }); + +// Conversas que contam no "(N)" da aba e na sidebar. +export const unreadConversationsQuery = queryOptions({ + queryKey: ["chat", "unread"], + queryFn: async ({ signal }) => + (await api.get("/conversations?pageSize=1", { signal })).meta + .unreadConversations, +}); + +// Ids das conversas não lidas, para fechar as notificações do push das que já foram lidas. +export const unreadConversationIds = async () => + (await api.get(`/conversations?filter=unread&pageSize=${LIST_PAGE_SIZE}`)).data + .filter((c) => c.unreadCount > 0 || c.markedUnread) + .map((c) => c.id); + +export const conversationQuery = (id: string) => + queryOptions({ + queryKey: ["chat", "conversation", id], + queryFn: ({ signal }) => api.get(`/conversations/${id}`, { signal }), + }); + +// Páginas da mais nova (pages[0]) para as mais antigas. O stream acrescenta as novas, e voltar à +// conversa mantém as páginas antigas já carregadas. +export const messagesQuery = (id: string) => + infiniteQueryOptions({ + queryKey: ["chat", "messages", id], + queryFn: ({ pageParam, signal }) => + api.get( + `/conversations/${id}/messages?limit=${MESSAGES_PAGE_SIZE}${pageParam ? `&before=${pageParam}` : ""}`, + { signal }, + ), + initialPageParam: undefined as number | undefined, + getNextPageParam: (last) => (last.meta.hasMore ? last.data[0]?.seq : undefined), + staleTime: Infinity, + gcTime: 30 * 60 * 1000, + }); + +export const contactsQuery = (search: string) => + queryOptions({ + queryKey: ["chat", "contacts", search], + queryFn: ({ signal }) => + api.get<{ data: Contact[] }>( + `/contacts?pageSize=100${search.length >= 3 ? `&search=${encodeURIComponent(search)}` : ""}`, + { signal }, + ), + placeholderData: keepPreviousData, + }); + +// Mensagens carregadas, da mais antiga para a mais nova, sem repetição. +export function flattenMessages(data: InfiniteData | undefined): Message[] { + if (!data) return []; + const byId = new Map(); + for (const page of data.pages) for (const message of page.data) byId.set(message.id, message); + return [...byId.values()].sort((a, b) => a.seq - b.seq); +} + +// Conversa mudou (stream ou resposta): a conversa e as listas que a mostram. As listas são refeitas +// em segundo plano, para a ordem e os filtros virem do servidor. +export function applyConversation(queryClient: QueryClient, conversation: Conversation) { + queryClient.setQueryData(conversationQuery(conversation.id).queryKey, conversation); + queryClient.setQueriesData( + { queryKey: ["chat", "conversations"] }, + (page) => + page && { + ...page, + data: page.data.map((c) => (c.id === conversation.id ? conversation : c)), + }, + ); + void queryClient.invalidateQueries({ queryKey: ["chat", "conversations"] }); + void queryClient.invalidateQueries({ queryKey: unreadConversationsQuery.queryKey }); +} + +// Mensagem nova ou alterada (reação) na conversa já carregada. +export function applyMessage(queryClient: QueryClient, message: Message) { + queryClient.setQueryData>( + messagesQuery(message.conversationId).queryKey, + (data) => { + if (!data) return data; + const exists = data.pages.some((page) => page.data.some((m) => m.id === message.id)); + const pages = exists + ? data.pages.map((page) => ({ + ...page, + data: page.data.map((m) => (m.id === message.id ? message : m)), + })) + : data.pages.map((page, i) => + i === 0 ? { ...page, data: [...page.data, message] } : page, + ); + return { ...data, pages }; + }, + ); +} + +export function useUpdateConversation() { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: ({ + id, + ...patch + }: { + id: string; + read?: boolean; + readUntil?: number; + mute?: MuteOption | null; + archived?: boolean; + }) => api.patch(`/conversations/${id}`, patch), + onSuccess: (conversation) => applyConversation(queryClient, conversation), + }); +} + +export function useCreateConversation() { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: ( + input: + { kind: "direct"; memberId: string } | { kind: "group"; name: string; memberIds: string[] }, + ) => api.post("/conversations", input), + onSuccess: (conversation) => applyConversation(queryClient, conversation), + }); +} + +export function useSendMessage(conversationId: string) { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: (input: { + text: string; + replyToId?: string | null; + mentionIds?: string[]; + mentionsAll?: boolean; + }) => api.post(`/conversations/${conversationId}/messages`, input), + onSuccess: (message) => applyMessage(queryClient, message), + }); +} + +export function useReact(conversationId: string) { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: async ({ messageId, emoji }: { messageId: string; emoji: string | null }) => { + const path = `/conversations/${conversationId}/messages/${messageId}/myReaction`; + if (emoji) return api.put(path, { emoji }); + await api.delete(path); + return null; + }, + onSuccess: (message) => { + if (message) applyMessage(queryClient, message); + }, + }); +} diff --git a/app/lib/chat/composerFocus.ts b/app/lib/chat/composerFocus.ts new file mode 100644 index 0000000..c9c90e0 --- /dev/null +++ b/app/lib/chat/composerFocus.ts @@ -0,0 +1,17 @@ +// Conversa aberta pelo clique numa notificação: o cursor vai para o campo de mensagem. O campo pode +// ainda não estar na tela (app aberto pelo clique no push), então ele pega quando aparecer. +export const COMPOSER_FOCUS_EVENT = "chat:foco-no-campo"; + +let pending: string | null = null; + +export function requestComposerFocus(conversationId: string) { + pending = conversationId; + window.dispatchEvent(new CustomEvent(COMPOSER_FOCUS_EVENT, { detail: conversationId })); +} + +// true uma vez para a conversa que pediu o cursor. +export function takeComposerFocus(conversationId: string) { + if (pending !== conversationId) return false; + pending = null; + return true; +} diff --git a/app/lib/notifier/documentBadge.ts b/app/lib/notifier/documentBadge.ts new file mode 100644 index 0000000..eff9677 --- /dev/null +++ b/app/lib/notifier/documentBadge.ts @@ -0,0 +1,97 @@ +import { APP_NAME } from "~/config/app"; + +// Título e ícone da aba: "(N) App" e o ícone com o número de não lidas, ou com "!" sem conexão. +const BASE_ICON = "/favicon.ico"; + +let baseImage: Promise | null = null; + +function loadBaseIcon() { + baseImage ??= new Promise((resolve, reject) => { + const img = new Image(); + img.onload = () => resolve(img); + img.onerror = reject; + img.src = BASE_ICON; + }); + return baseImage; +} + +// Cores fixas: o ícone da aba fica fora do tema do app, e o canvas não lê variável CSS. +const BADGE_COLOR = "#ef4444"; +const OFFLINE_COLOR = "#9ca3af"; + +// Ícone com o número (1 a 99, depois "99+") ou com o "!" de conexão caída. +async function drawIcon(count: number, offline: boolean) { + const img = await loadBaseIcon(); + const size = 64; + const canvas = document.createElement("canvas"); + canvas.width = size; + canvas.height = size; + const ctx = canvas.getContext("2d")!; + const scale = Math.min(size / img.width, size / img.height); + ctx.drawImage( + img, + (size - img.width * scale) / 2, + (size - img.height * scale) / 2, + img.width * scale, + img.height * scale, + ); + + const label = offline ? "!" : count > 99 ? "99+" : String(count); + ctx.font = `bold ${label.length > 2 ? 24 : 34}px sans-serif`; + const width = Math.max(40, ctx.measureText(label).width + 16); + const height = 40; + const x = size - width; + ctx.fillStyle = offline ? OFFLINE_COLOR : BADGE_COLOR; + ctx.beginPath(); + ctx.roundRect(x, 0, width, height, height / 2); + ctx.fill(); + ctx.fillStyle = "#ffffff"; + ctx.textAlign = "center"; + ctx.textBaseline = "middle"; + ctx.fillText(label, x + width / 2, height / 2 + 2); + return canvas.toDataURL("image/png"); +} + +function setFavicon(href: string) { + let link = document.querySelector("link[rel~='icon']"); + if (!link) { + link = document.createElement("link"); + link.rel = "icon"; + document.head.appendChild(link); + } + link.href = href; +} + +let shown = { count: 0, offline: false }; +let drawSeq = 0; + +// O título base é o da tela (meta da rota): "(N) " vai na frente dele e sai quando zera. +const COUNT_PREFIX = /^\(\d+\+?\) /; + +export function renderDocumentBadge(count: number, offline: boolean) { + const base = document.title.replace(COUNT_PREFIX, "") || APP_NAME; + const title = count > 0 ? `(${count > 999 ? "999+" : count}) ${base}` : base; + // Gravar o mesmo título ainda conta como mudança para o MutationObserver de quem chama. + if (document.title !== title) document.title = title; + if (shown.count === count && shown.offline === offline) return; + shown = { count, offline }; + + // Instalado como app: o número vai para o ícone do app (só lá a API existe). + const nav = navigator as Navigator & { + setAppBadge?: (n?: number) => Promise; + clearAppBadge?: () => Promise; + }; + if (count > 0) nav.setAppBadge?.(count).catch(() => {}); + else nav.clearAppBadge?.().catch(() => {}); + + const seq = ++drawSeq; + if (count === 0 && !offline) { + setFavicon(BASE_ICON); + return; + } + drawIcon(count, offline) + .then((href) => { + if (seq === drawSeq) setFavicon(href); + }) + .catch(() => {}); +} diff --git a/app/lib/notifier/notifications.queries.ts b/app/lib/notifier/notifications.queries.ts new file mode 100644 index 0000000..af7ce62 --- /dev/null +++ b/app/lib/notifier/notifications.queries.ts @@ -0,0 +1,61 @@ +import { queryOptions, useMutation, useQueryClient } from "@tanstack/react-query"; +import type { + AppNotification, + MuteOption, + NoticeMute, + NotificationPage, +} from "~/types/notification"; +import { api } from "../api"; + +// Queries de notificação usadas fora da tela de Notificações: o contador da sidebar e da aba, e o +// silêncio dos avisos. + +export const unreadNotificationsQuery = queryOptions({ + queryKey: ["notifications", "unread"], + queryFn: async ({ signal }) => + (await api.get("/notifications?read=false&pageSize=1", { signal })).meta + .unread, +}); + +// Ids das não lidas (até 100), para fechar as notificações do push que já foram lidas. +export const unreadNotificationIds = async () => + (await api.get("/notifications?read=false&pageSize=100")).data.map( + (notification) => notification.id, + ); + +export const noticeMuteQuery = queryOptions({ + queryKey: ["notifications", "mute"], + queryFn: ({ signal }) => api.get("/noticeMute", { signal }), +}); + +// Silenciado agora: o prazo vence sozinho, sem aviso do servidor. +export function isMutedNow(mute: { muted: boolean; mutedUntil: string | null } | undefined) { + if (!mute?.muted) return false; + return mute.mutedUntil === null || new Date(mute.mutedUntil).getTime() > Date.now(); +} + +export function useUpdateNotification() { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: ({ id, ...patch }: { id: string; read?: boolean; archived?: boolean }) => + api.patch(`/notifications/${id}`, patch), + // O contador chega pelo stream; a lista é refeita aqui para a tela não esperar por ele. + onSuccess: () => void queryClient.invalidateQueries({ queryKey: ["notifications"] }), + }); +} + +export function useMarkAllNotificationsRead() { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: () => api.patch("/notifications", { read: true }), + onSuccess: () => void queryClient.invalidateQueries({ queryKey: ["notifications"] }), + }); +} + +export function useSetNoticeMute() { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: (mute: MuteOption | null) => api.put("/noticeMute", { mute }), + onSuccess: (mute) => queryClient.setQueryData(noticeMuteQuery.queryKey, mute), + }); +} diff --git a/app/lib/notifier/preferences.ts b/app/lib/notifier/preferences.ts new file mode 100644 index 0000000..a120420 --- /dev/null +++ b/app/lib/notifier/preferences.ts @@ -0,0 +1,100 @@ +import { useSyncExternalStore } from "react"; +import { + DEFAULT_NOTIFICATION_PREFERENCES, + normalizeNotificationPreferences, + type NotificationPreferences, +} from "~shared/notificationPreferences"; + +// Configurações de notificação de cada usuário neste navegador (computador dividido: cada um com as +// suas). Ficam no localStorage, não no servidor: em outro computador valem as padrão até a pessoa mudar. +// Também guarda a permissão do navegador, que muda pelo cadeado da barra de endereço. + +// "unsupported": navegador sem notificação, ou site fora de HTTPS (exceto localhost). +export type PermissionState = NotificationPermission | "unsupported"; + +export function readPermission(): PermissionState { + if (typeof window === "undefined" || !("Notification" in window) || !window.isSecureContext) { + return "unsupported"; + } + return Notification.permission; +} + +type NotifierState = { + prefs: NotificationPreferences; + // De quem são as preferências na tela (onde gravar). Null antes de carregar: valem as padrão. + userId: string | null; + permission: PermissionState; +}; + +const INITIAL: NotifierState = { + prefs: DEFAULT_NOTIFICATION_PREFERENCES, + userId: null, + permission: "unsupported", +}; + +let state: NotifierState = { ...INITIAL, permission: readPermission() }; +const listeners = new Set<() => void>(); + +function setState(patch: Partial) { + state = { ...state, ...patch }; + listeners.forEach((listener) => listener()); +} + +const prefsKey = (userId: string) => `notificacoes:${userId}`; + +const normalize = normalizeNotificationPreferences; + +export function loadPreferences(userId: string) { + let stored: unknown = null; + try { + stored = JSON.parse(localStorage.getItem(prefsKey(userId)) ?? "null"); + } catch { + // Storage bloqueado ou valor estragado: valem as padrão. + } + setState({ prefs: normalize(stored), userId }); +} + +export function updatePreferences(prefs: NotificationPreferences) { + setState({ prefs }); + if (!state.userId) return; + try { + localStorage.setItem(prefsKey(state.userId), JSON.stringify(prefs)); + } catch { + // Storage bloqueado: valem só até recarregar. + } +} + +// Saiu da conta: as preferências não passam para o próximo usuário da mesma aba. +export function resetPreferences() { + setState({ prefs: DEFAULT_NOTIFICATION_PREFERENCES, userId: null }); +} + +export function refreshPermission() { + const permission = readPermission(); + if (permission !== state.permission) setState({ permission }); +} + +// Precisa vir de um clique: o navegador ignora o pedido feito sozinho. +export async function requestPermission() { + if (readPermission() === "unsupported") return "unsupported"; + const permission = await Notification.requestPermission(); + setState({ permission }); + return permission; +} + +export function getNotifierState() { + return state; +} + +function subscribe(listener: () => void) { + listeners.add(listener); + return () => listeners.delete(listener); +} + +export function useNotifierState() { + return useSyncExternalStore( + subscribe, + () => state, + () => INITIAL, + ); +} diff --git a/app/lib/notifier/push.ts b/app/lib/notifier/push.ts new file mode 100644 index 0000000..4938b1e --- /dev/null +++ b/app/lib/notifier/push.ts @@ -0,0 +1,82 @@ +import type { NotificationPreferences } from "~/types/notification"; +import { api } from "../api"; + +// Web Push: com o app fechado, o servidor avisa o navegador pela chave VAPID dele, e o service worker +// (public/sw.js) mostra a notificação. A inscrição fica presa à sessão de login no servidor. + +export const pushSupported = () => + typeof window !== "undefined" && + window.isSecureContext && + "serviceWorker" in navigator && + "PushManager" in window; + +function base64UrlToBytes(base64Url: string) { + const base64 = (base64Url + "=".repeat((4 - (base64Url.length % 4)) % 4)) + .replace(/-/g, "+") + .replace(/_/g, "/"); + const raw = atob(base64); + const bytes = new Uint8Array(new ArrayBuffer(raw.length)); + for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i); + return bytes; +} + +function sameKey(a: ArrayBuffer | null | undefined, b: Uint8Array) { + if (!a) return false; + const bytes = new Uint8Array(a); + return bytes.length === b.length && bytes.every((value, i) => value === b[i]); +} + +export function registerServiceWorker(): Promise { + if (!pushSupported()) return Promise.resolve(null); + return navigator.serviceWorker.register("/sw.js").catch((error: unknown) => { + console.error("Erro ao registrar o service worker", error); + return null; + }); +} + +// Liga (permissão concedida) ou desliga o push deste navegador. As configurações vão junto: o +// servidor segue as mesmas regras da página. Devolve o endpoint que ficou (null: sem push aqui), que +// o stream de eventos manda ao servidor para ele não avisar por push quem está com o app aberto. +export async function syncPushSubscription( + enabled: boolean, + preferences: NotificationPreferences, +): Promise { + const registration = await registerServiceWorker(); + if (!registration) return null; + try { + const current = await registration.pushManager.getSubscription(); + if (!enabled || Notification.permission !== "granted") { + // Sem a permissão, o navegador já não entrega; o servidor apaga a inscrição no próximo envio. + await current?.unsubscribe(); + return null; + } + const { publicKey } = await api.get<{ publicKey: string }>("/pushKey"); + const key = base64UrlToBytes(publicKey); + let subscription = current; + // A chave do servidor trocou (restart): a inscrição antiga não serve. + if (subscription && !sameKey(subscription.options.applicationServerKey, key)) { + await subscription.unsubscribe(); + subscription = null; + } + subscription ??= await registration.pushManager.subscribe({ + userVisibleOnly: true, + applicationServerKey: key, + }); + await api.post("/pushSubscriptions", { ...subscription.toJSON(), preferences }); + return subscription.endpoint; + } catch (error) { + console.error("Erro ao configurar o aviso com o app fechado", error); + return null; + } +} + +// Logout: o servidor já apagou a inscrição desta sessão. Cancelar aqui também evita que o próximo +// usuário deste navegador herde o mesmo endpoint antes de se inscrever. +export function dropLocalPushSubscription() { + if (!pushSupported()) return; + navigator.serviceWorker + .getRegistration() + .then((registration) => registration?.pushManager.getSubscription()) + .then((subscription) => subscription?.unsubscribe()) + .catch(() => {}); +} diff --git a/app/lib/notifier/realtime.ts b/app/lib/notifier/realtime.ts new file mode 100644 index 0000000..e82bdab --- /dev/null +++ b/app/lib/notifier/realtime.ts @@ -0,0 +1,118 @@ +import type { AppNotification, NoticeMute } from "~/types/notification"; +// @modulo:chat +import type { Conversation, Message } from "~/types/chat"; +// @modulo:fim + +// Stream SSE de GET /api/v1/events, aberto enquanto há sessão, em qualquer tela. +// O EventSource reconecta sozinho em queda de rede, mas desiste em resposta de erro (502 no deploy, +// 401) e não percebe conexão que morre calada. Aqui ele é recriado com espera crescente de 1 s a 30 s, +// e a conexão sem nenhum evento por 45 s (o servidor manda `ping` a cada 20 s) é descartada. + +export type RealtimeEvent = + | { type: "notification"; notification: AppNotification; unread: number } + // @modulo:chat + | { type: "conversation"; conversation: Conversation } + | { type: "message"; message: Message; conversation: Conversation } + | { + type: "reaction"; + message: Message; + conversation: Conversation; + // Só quando é de outra pessoa a uma mensagem sua. + reaction: { authorName: string; emoji: string; text: string } | null; + } + // @modulo:fim + | { type: "read"; ids: string[] | null; unread: number } + | { type: "unread"; unread: number } + | ({ type: "noticeMute" } & NoticeMute); + +const EVENT_TYPES = [ + "notification", + "read", + "unread", + "noticeMute", + // @modulo:chat + "conversation", + "message", + "reaction", + // @modulo:fim +] as const; + +type Options = { + // Inscrição de push deste navegador: com a aba aberta, o servidor não manda push para ele. + pushEndpoint: string | null; + onEvent: (event: RealtimeEvent) => void; + // Conectou (também depois de cair): a tela refaz o que pode ter perdido. + onOpen: () => void; + onOffline: () => void; +}; + +const MIN_RETRY_MS = 1_000; +const MAX_RETRY_MS = 30_000; +const SILENCE_MS = 45_000; + +export function connectRealtime({ pushEndpoint, onEvent, onOpen, onOffline }: Options) { + let source: EventSource | null = null; + let retryMs = MIN_RETRY_MS; + let retryTimer: ReturnType | undefined; + let silenceTimer: ReturnType | undefined; + let stopped = false; + + const url = `/api/v1/events${ + pushEndpoint ? `?pushEndpoint=${encodeURIComponent(pushEndpoint)}` : "" + }`; + + function heard() { + clearTimeout(silenceTimer); + silenceTimer = setTimeout(() => drop(), SILENCE_MS); + } + + function drop() { + source?.close(); + source = null; + clearTimeout(silenceTimer); + if (stopped) return; + onOffline(); + retryTimer = setTimeout(open, retryMs); + retryMs = Math.min(retryMs * 2, MAX_RETRY_MS); + } + + function parse(event: MessageEvent) { + heard(); + try { + return JSON.parse(event.data) as Record; + } catch { + return null; + } + } + + function open() { + if (stopped) return; + source = new EventSource(url); + heard(); + source.addEventListener("ready", (event) => { + parse(event); + retryMs = MIN_RETRY_MS; + onOpen(); + }); + source.addEventListener("ping", (event) => parse(event)); + for (const type of EVENT_TYPES) { + source.addEventListener(type, (event) => { + const data = parse(event); + if (data) onEvent({ type, ...data } as RealtimeEvent); + }); + } + // Queda de rede o EventSource tenta sozinho (CONNECTING); resposta de erro fecha (CLOSED). + source.addEventListener("error", () => { + if (source?.readyState === EventSource.CLOSED) drop(); + else onOffline(); + }); + } + + open(); + return () => { + stopped = true; + clearTimeout(retryTimer); + clearTimeout(silenceTimer); + source?.close(); + }; +} diff --git a/app/lib/notifier/sounds.ts b/app/lib/notifier/sounds.ts new file mode 100644 index 0000000..4301367 --- /dev/null +++ b/app/lib/notifier/sounds.ts @@ -0,0 +1,96 @@ +// Som de notificação gerado aqui (Web Audio), sem arquivo. O navegador só deixa tocar depois de um +// clique ou tecla na página; antes disso, a notificação sai com o som do sistema (notifier.ts). +import type { NotificationSound } from "~/types/notification"; + +let context: AudioContext | null = null; + +function audio(): AudioContext | null { + if (typeof window === "undefined" || !("AudioContext" in window)) return null; + context ??= new AudioContext(); + return context; +} + +// Já houve clique ou tecla nesta página. Sem a API (navegador antigo), tenta e o navegador decide. +const pageActivated = () => + (navigator.userActivation as UserActivation | undefined)?.hasBeenActive ?? true; + +export function canPlaySound() { + return !!audio() && pageActivated(); +} + +// Primeira interação: libera o áudio. +export function installAudioUnlock() { + const unlock = () => { + const ctx = audio(); + if (ctx?.state === "suspended") void ctx.resume(); + }; + window.addEventListener("pointerdown", unlock, true); + window.addEventListener("keydown", unlock, true); + return () => { + window.removeEventListener("pointerdown", unlock, true); + window.removeEventListener("keydown", unlock, true); + }; +} + +// Uma nota curta, com ataque rápido e queda suave. +function note(ctx: AudioContext, freq: number, start: number, duration: number, volume: number) { + const osc = ctx.createOscillator(); + const gain = ctx.createGain(); + osc.type = "sine"; + osc.frequency.setValueAtTime(freq, start); + gain.gain.setValueAtTime(0.0001, start); + gain.gain.exponentialRampToValueAtTime(volume, start + 0.01); + gain.gain.exponentialRampToValueAtTime(0.0001, start + duration); + osc.connect(gain).connect(ctx.destination); + osc.start(start); + osc.stop(start + duration + 0.02); +} + +type Note = { freq: number; at: number; duration: number; level: number }; + +// Cada som é uma sequência de notas. `level` é relativo: o volume da configuração multiplica. +const PATTERNS: Record = { + // Duas notas subindo. + padrao: [ + { freq: 880, at: 0, duration: 0.12, level: 0.36 }, + { freq: 1318.5, at: 0.1, duration: 0.22, level: 0.32 }, + ], + // Uma nota longa, com a oitava por cima. + sino: [ + { freq: 1046.5, at: 0, duration: 0.9, level: 0.34 }, + { freq: 2093, at: 0, duration: 0.6, level: 0.12 }, + ], + // Três notas subindo. + chime: [ + { freq: 784, at: 0, duration: 0.18, level: 0.3 }, + { freq: 987.8, at: 0.12, duration: 0.18, level: 0.3 }, + { freq: 1318.5, at: 0.24, duration: 0.3, level: 0.3 }, + ], + // Uma nota curta. + pop: [{ freq: 660, at: 0, duration: 0.07, level: 0.4 }], +}; + +export const SOUND_LABELS: Record = { + padrao: "Padrão", + sino: "Sino", + chime: "Chime", + pop: "Pop", +}; + +function play(sound: NotificationSound, volume: number) { + const ctx = audio(); + if (!ctx || volume <= 0) return; + if (ctx.state === "suspended") void ctx.resume(); + const t = ctx.currentTime; + for (const n of PATTERNS[sound]) note(ctx, n.freq, t + n.at, n.duration, n.level * volume); +} + +// Aviso chegando. Sem clique ou tecla na página o navegador não deixa tocar. +export function playIncoming(sound: NotificationSound, volume: number) { + if (pageActivated()) play(sound, volume); +} + +// Botão "Testar som" e troca de som ou volume na configuração: já vem de um clique. +export function previewSound(sound: NotificationSound, volume: number) { + play(sound, volume); +} diff --git a/app/lib/notifier/squelch.ts b/app/lib/notifier/squelch.ts new file mode 100644 index 0000000..5e69e75 --- /dev/null +++ b/app/lib/notifier/squelch.ts @@ -0,0 +1,15 @@ +import { SQUELCH_MS } from "~shared/notificationText"; + +// Pausa de um aviso (grupo agitado, avisos em sequência): true = ainda dentro dela, sem notificação +// nem som. O servidor faz o mesmo para o push. +const lastAlert = new Map(); + +export function squelched(key: string, now = Date.now()) { + if (now - (lastAlert.get(key) ?? 0) < SQUELCH_MS) return true; + lastAlert.set(key, now); + return false; +} + +export function forgetSquelches() { + lastAlert.clear(); +} diff --git a/app/lib/notifier/systemNotifications.ts b/app/lib/notifier/systemNotifications.ts new file mode 100644 index 0000000..be54bcf --- /dev/null +++ b/app/lib/notifier/systemNotifications.ts @@ -0,0 +1,72 @@ +// Notificações do sistema operacional. Uma por notificação do app (tag = id), fechadas quando ela é +// lida aqui, em outra aba ou em outro computador. + +type ShowOptions = { + body: string; + tag: string; + url: string | null; + // Toca o som do sistema (quando o app não pode tocar o seu). + systemSound: boolean; + onClick: () => void; +}; + +const ICON = "/icons/icon-192.png"; +const pageNotifications = new Map(); + +export function showSystemNotification(title: string, options: ShowOptions) { + const { body, tag, url, systemSound, onClick } = options; + const init: NotificationOptions & { renotify?: boolean } = { + body, + tag, + icon: ICON, + renotify: true, + silent: !systemSound, + data: { url }, + }; + try { + const notification = new Notification(title, init); + notification.onclick = () => { + notification.close(); + onClick(); + }; + notification.onclose = () => { + if (pageNotifications.get(tag) === notification) pageNotifications.delete(tag); + }; + pageNotifications.set(tag, notification); + } catch { + // Celular (Chrome Android): só pelo service worker. O clique volta pelo sw.js. + navigator.serviceWorker?.ready + .then((registration) => registration.showNotification(title, init)) + .catch(() => {}); + } +} + +// `tags` null fecha todas: as da página e as que vieram por push ou pelo service worker. +export function closeSystemNotifications(tags: string[] | null) { + for (const [tag, notification] of pageNotifications) { + if (tags && !tags.includes(tag)) continue; + notification.close(); + pageNotifications.delete(tag); + } + navigator.serviceWorker + ?.getRegistration() + .then((registration) => registration?.getNotifications()) + .then((list) => list?.forEach((n) => (!tags || tags.includes(n.tag)) && n.close())) + .catch(() => {}); +} + +// Abertura do app e reconexão: somem as notificações do push que já não estão entre as não lidas +// (lidas em outro computador, ou antes de esta aba abrir). +export function closeSystemNotificationsExcept(unreadIds: string[]) { + navigator.serviceWorker + ?.getRegistration() + .then((registration) => registration?.getNotifications()) + .then((list) => list?.forEach((n) => !unreadIds.includes(n.tag) && n.close())) + .catch(() => {}); +} + +// Saindo da página: as notificações dela não ficam para trás. +export function closePageNotifications() { + for (const notification of pageNotifications.values()) notification.close(); + pageNotifications.clear(); +} diff --git a/app/lib/search.ts b/app/lib/search.ts new file mode 100644 index 0000000..252a81a --- /dev/null +++ b/app/lib/search.ts @@ -0,0 +1,64 @@ +// Apoio da caixa de busca das listas. A gramática (texto livre mais `campo:valor`) vive no servidor, +// em server/lib/search.ts; aqui só se reconhece o que foi digitado para avisar e para o calendário. + +// Os mesmos limites do servidor: mínimo por parte e máximo do termo. +export const MIN_SEARCH_LENGTH = 3; +export const MAX_SEARCH_LENGTH = 100; + +// Uma chave de `campo:valor` aceita pela lista, com o nome que aparece no painel. +export type SearchKey = { key: string; label: string }; + +// As duas formas com chave do tokenizador do servidor, sem as de texto livre. +const KEYED_TOKEN = /([^\s:"]+):"([^"]*)"|([^\s:"]+):(\S+)/g; + +// Chaves com valor curto demais: o servidor descarta só esse filtro e devolve a lista sem ele, sem +// erro. A caixa avisa antes. +export function shortValueKeys(term: string, keys: readonly SearchKey[]) { + const known = new Set(keys.map((k) => k.key.toLowerCase())); + const short = new Set(); + for (const m of term.matchAll(KEYED_TOKEN)) { + const key = (m[1] ?? m[3] ?? "").toLowerCase(); + const value = m[2] ?? m[4] ?? ""; + // Valor vazio (`cargo:`) é filtro sendo digitado, não filtro errado. + if (known.has(key) && value.length > 0 && value.length < MIN_SEARCH_LENGTH) short.add(key); + } + return [...short]; +} + +// `de:` e `ate:` como tokens inteiros: `grande:x` e `14:30` ficam de fora. +const PERIOD_TOKEN = /(^|\s)(de|ate):(\S+)/gi; + +// Período em `AAAA-MM-DD`, o formato do . +export type SearchPeriod = { from: string; to: string }; + +const brToIso = (value: string) => { + const m = /^(\d{2})\/(\d{2})\/(\d{4})$/.exec(value); + if (m) return `${m[3]}-${m[2]}-${m[1]}`; + return /^\d{4}-\d{2}-\d{2}$/.test(value) ? value : ""; +}; + +const isoToBr = (value: string) => { + const [year, month, day] = value.split("-"); + return `${day}/${month}/${year}`; +}; + +// O período já escrito na caixa, para o painel abrir mostrando o que está valendo. +export function periodFromTerm(term: string): SearchPeriod { + const period = { from: "", to: "" }; + for (const m of term.matchAll(PERIOD_TOKEN)) { + const iso = brToIso(m[3]); + if (!iso) continue; + if (m[2].toLowerCase() === "de") period.from = iso; + else period.to = iso; + } + return period; +} + +// Reescreve o termo com o período escolhido. Substitui os `de:`/`ate:` que já estavam, em vez de +// acrescentar: dois `de:` na caixa e o servidor obedeceria ao último sem ninguém entender por quê. +export function withPeriod(term: string, period: SearchPeriod) { + const parts = [term.replace(PERIOD_TOKEN, " ").replace(/\s+/g, " ").trim()]; + if (period.from) parts.push(`de:${isoToBr(period.from)}`); + if (period.to) parts.push(`ate:${isoToBr(period.to)}`); + return parts.filter(Boolean).join(" "); +} diff --git a/app/root.tsx b/app/root.tsx index b59744c..f46d48c 100644 --- a/app/root.tsx +++ b/app/root.tsx @@ -20,6 +20,13 @@ import "./app.css"; export const meta: Route.MetaFunction = () => [{ title: APP_NAME }]; +// Manifest do app instalado: o iOS só entrega Web Push com o site na tela inicial (16.4 ou mais novo). +// Troque nome, cor e ícones (public/manifest.webmanifest e public/icons/) ao criar o projeto. +export const links: Route.LinksFunction = () => [ + { rel: "manifest", href: "/manifest.webmanifest" }, + { rel: "apple-touch-icon", href: "/icons/icon-192.png" }, +]; + export function Layout({ children }: { children: React.ReactNode }) { return ( // suppressHydrationWarning: o script do tema pode pôr .dark no antes do React hidratar. @@ -72,7 +79,7 @@ export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) { } return ( -
    +

    {title}

    {details}

    diff --git a/app/routes.ts b/app/routes.ts index 84edb4d..385268e 100644 --- a/app/routes.ts +++ b/app/routes.ts @@ -8,6 +8,9 @@ export default [ layout("routes/app-layout.tsx", [ index("routes/dashboard/route.tsx"), route("users", "routes/users/route.tsx"), + // @modulo:chat + route("chat", "routes/chat/route.tsx"), + // @modulo:fim route("profile", "routes/profile.tsx"), route("*", "routes/not-found.tsx"), ]), diff --git a/app/routes/app-layout.tsx b/app/routes/app-layout.tsx index ff7b727..1364cd6 100644 --- a/app/routes/app-layout.tsx +++ b/app/routes/app-layout.tsx @@ -1,9 +1,17 @@ import { useQuery, useQueryClient } from "@tanstack/react-query"; import { useEffect, useRef, useState } from "react"; -import { Outlet, redirect, useLocation, useNavigate } from "react-router"; +import { Outlet, redirect, useLocation, useMatches, useNavigate } from "react-router"; import { MobileNav } from "~/components/layout/MobileNav"; import { Sidebar, SIDEBAR_MODES, type SidebarMode } from "~/components/layout/Sidebar"; +import { SingleTabGate } from "~/components/layout/SingleTabGate"; import { TopProgress } from "~/components/layout/TopProgress"; +// @modulo:notificacoes +import { NotificationBanner } from "~/components/layout/NotificationBanner"; +import { + leaveNotifications, + NotificationConnection, +} from "~/components/layout/NotificationConnection"; +// @modulo:fim import { isUnauthorized } from "~/lib/api"; import { loginPath, logout, markSignedOut, meQuery, requireSessionUser } from "~/lib/auth"; import type { Route } from "./+types/app-layout"; @@ -83,6 +91,10 @@ export default function AppLayout({ loaderData }: Route.ComponentProps) { const navigate = useNavigate(); const location = useLocation(); const loggingOut = useRef(false); + // Tela que ocupa toda a área (Conversas): sem o padding e a largura máxima das outras. + const fullBleed = useMatches().some( + (match) => (match.handle as { fullBleed?: boolean } | undefined)?.fullBleed, + ); // A revalidação em segundo plano do /me devolveu "sem sessão": sai para o login guardando a volta. // No logout explícito, quem navega é o handleLogout, sem a volta. @@ -92,14 +104,20 @@ export default function AppLayout({ loaderData }: Route.ComponentProps) { async function handleLogout() { loggingOut.current = true; + // @modulo:notificacoes + leaveNotifications(); + // @modulo:fim await logout(); navigate("/login", { replace: true }); } return ( - <> + -
    + {/* @modulo:notificacoes */} + {user && } + {/* @modulo:fim */} +
    {user && (
    )}
    - {/* pb-24 no mobile: espaço para a barra de navegação inferior. */} -
    - -
    + {fullBleed ? ( + // pb-[...] no mobile: espaço para a barra de navegação inferior. +
    + {/* @modulo:notificacoes */} + + {/* @modulo:fim */} +
    + +
    +
    + ) : ( + // pb-24 no mobile: espaço para a barra de navegação inferior. +
    + {/* @modulo:notificacoes */} + + {/* @modulo:fim */} + +
    + )}
    {user && }
    - + ); } diff --git a/app/routes/chat/_components/Avatar.tsx b/app/routes/chat/_components/Avatar.tsx new file mode 100644 index 0000000..7a2023b --- /dev/null +++ b/app/routes/chat/_components/Avatar.tsx @@ -0,0 +1,25 @@ +import { Users } from "lucide-react"; +import { cn } from "~/lib/utils"; +import { initials } from "../_lib/unread"; + +export function Avatar({ + name, + group, + className, +}: { + name: string; + group?: boolean; + className?: string; +}) { + return ( + + {group ? : initials(name)} + + ); +} diff --git a/app/routes/chat/_components/Composer.tsx b/app/routes/chat/_components/Composer.tsx new file mode 100644 index 0000000..dee8f3a --- /dev/null +++ b/app/routes/chat/_components/Composer.tsx @@ -0,0 +1,197 @@ +import { SendHorizontal, X } from "lucide-react"; +import { useEffect, useRef, useState } from "react"; +import { Button } from "~/components/ui/button"; +import { COMPOSER_FOCUS_EVENT, takeComposerFocus } from "~/lib/chat/composerFocus"; +import { cn } from "~/lib/utils"; +import type { ChatMember, Message } from "~/types/chat"; +import { ALL_MENTION, mentionQuery, mentionsIn } from "../_lib/mentions"; +import { Avatar } from "./Avatar"; + +type Suggestion = { id: string | null; name: string }; + +const normalize = (text: string) => + text + .normalize("NFD") + .replace(/\p{Diacritic}/gu, "") + .toLowerCase(); + +// Campo de mensagem: Enter envia, Shift+Enter quebra a linha, "@" sugere as pessoas do grupo (e +// "@todos") e Esc fecha as sugestões. A citação aparece em cima, e o X ou o Esc a cancela. +export function Composer({ + conversationId, + isGroup, + members, + myId, + replyTo, + onCancelReply, + onSend, + sending, +}: { + conversationId: string; + isGroup: boolean; + members: ChatMember[]; + myId: string; + replyTo: Message | null; + onCancelReply: () => void; + onSend: (input: { text: string; mentionIds: string[]; mentionsAll: boolean }) => void; + sending: boolean; +}) { + const [text, setText] = useState(""); + const [cursor, setCursor] = useState(0); + const [highlight, setHighlight] = useState(0); + const [dismissed, setDismissed] = useState(false); + const ref = useRef(null); + + // Aberta pela notificação: o cursor vem para o campo, agora ou quando o pedido chegar. + useEffect(() => { + if (takeComposerFocus(conversationId)) ref.current?.focus(); + const onFocusRequest = (event: Event) => { + if ( + (event as CustomEvent).detail === conversationId && + takeComposerFocus(conversationId) + ) + ref.current?.focus(); + }; + window.addEventListener(COMPOSER_FOCUS_EVENT, onFocusRequest); + return () => window.removeEventListener(COMPOSER_FOCUS_EVENT, onFocusRequest); + }, [conversationId]); + + // Citar põe o cursor no campo. + useEffect(() => { + if (replyTo) ref.current?.focus(); + }, [replyTo]); + + // Cresce com o texto até umas 6 linhas. + useEffect(() => { + const el = ref.current; + if (!el) return; + el.style.height = "auto"; + el.style.height = `${Math.min(el.scrollHeight, 160)}px`; + }, [text]); + + const query = isGroup && !dismissed ? mentionQuery(text, cursor) : null; + const others = members.filter((m) => m.id !== myId); + const suggestions: Suggestion[] = + query === null + ? [] + : [ + ...others.map((m) => ({ id: m.id, name: m.fullName })), + { id: null, name: ALL_MENTION }, + ].filter((s) => normalize(s.name).includes(normalize(query))); + const active = Math.min(highlight, Math.max(0, suggestions.length - 1)); + + function pick(suggestion: Suggestion) { + const before = text.slice(0, cursor).replace(/@([^\s@]*)$/, `@${suggestion.name} `); + const next = before + text.slice(cursor); + setText(next); + setHighlight(0); + requestAnimationFrame(() => { + ref.current?.focus(); + ref.current?.setSelectionRange(before.length, before.length); + setCursor(before.length); + }); + } + + function send() { + const trimmed = text.trim(); + if (!trimmed || sending) return; + onSend({ text: trimmed, ...mentionsIn(trimmed, others) }); + setText(""); + setCursor(0); + } + + function onKeyDown(event: React.KeyboardEvent) { + if (suggestions.length > 0) { + if (event.key === "ArrowDown" || event.key === "ArrowUp") { + event.preventDefault(); + const step = event.key === "ArrowDown" ? 1 : -1; + setHighlight((active + step + suggestions.length) % suggestions.length); + return; + } + if (event.key === "Enter" || event.key === "Tab") { + event.preventDefault(); + pick(suggestions[active]); + return; + } + if (event.key === "Escape") { + event.preventDefault(); + setDismissed(true); + return; + } + } + if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) { + event.preventDefault(); + send(); + } + } + + return ( +
    + {suggestions.length > 0 && ( +
      + {suggestions.map((s, i) => ( +
    • { + event.preventDefault(); + pick(s); + }} + className={cn( + "flex cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-sm", + i === active && "bg-accent", + )} + > + + {s.id === null ? "todos (avisa todo o grupo)" : s.name} +
    • + ))} +
    + )} + {replyTo && ( +
    +
    +

    + Respondendo a {replyTo.authorId === myId ? "você" : replyTo.authorName} +

    +

    {replyTo.text}

    +
    + +
    + )} +
    +