diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 5011fda..6212b34 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -594,3 +594,18 @@ Cada decisão tem: contexto, decisão e consequência. As decisões D-01 a D-11 - **Efeito colateral aceito:** no celular, o primeiro filme desceu em coleções com descrição longa (Matrix: de y ≈ 922 para 966 px), porque a descrição saiu de cima da imagem, onde era ilegível, e o Compartilhar ocupa uma linha. A descrição usa corpo normal no celular para atenuar. - **Não feito, por decisão do proprietário:** alternar a ordem (B2) e tirar o CSS da coleção do arquivo global (C1, para uma etapa de desempenho). - **Testes:** 8 unitários e 19 E2E novos (nas 7 larguras), incluindo um teste de contraste que serve uma imagem de fundo branca (o pior caso) e mede os pixels sob o texto. Contraprovas: contraste, nome longo, numeração, filme sem data, erro sem `h1` e compartilhar, cada uma fazendo pelo menos um teste falhar. + +## D-69. Sobre, Privacidade, 404 e erros de página + +- **Diagnóstico** (produção, 8 páginas e estados em 8 larguras): sem rolagem horizontal, cortes ou saltos de título; Sobre, Privacidade e 404 com `h1`. Os problemas: os erros de filme, série, pessoa e temporada não tinham `h1`, ofereciam "Tentar novamente" mesmo para conteúdo inexistente (o que não resolve nada), mantinham um título de aba genérico ("Filme · Cinelux") e mostravam a mensagem crua do serviço, que numa falha de configuração seria técnica ("A chave do TMDB é inválida…"); a 404 e o conteúdo inexistente respondiam HTTP 200 sem `noindex`; e Sobre e Privacidade ainda usavam a linha sólida anterior à D-64. +- **Aprovado e feito:** + - **A1.** Sobre e Privacidade com o filete esmaecido (`--rule-fade`); o aviso do TMDB como citação (filete dourado, sem caixa), com o texto obrigatório preservado. `src/config/legal.ts` intocado. + - **A2.** Código da 404 e do erro inesperado ("Ops") no gradiente da marca, com cor sólida no alto contraste do sistema. + - **B1.** `components/ui/PageError.tsx`, usado por filme, série, pessoa, temporada e coleção (que tinha a primeira versão desta lógica, D-68, agora removida). `h1`, título da aba por `pageErrorTitle` (a página o usa no próprio `useDocumentTitle`, porque o efeito do filho roda antes do da página e seria sobrescrito) e mensagem amigável: a do serviço só para falhas que a pessoa entende (rede, limite, serviço fora); as técnicas viram uma mensagem genérica. + - **B2.** Conteúdo inexistente sem "Tentar novamente", com "Descobrir filmes" e "Voltar ao início"; a temporada mantém "Voltar para a série", que já existia. Falhas temporárias continuam com "Tentar novamente". Os dois testes que exigiam o botão no 404 (filme e série) e o da temporada inexistente foram reescritos para verificar o novo comportamento, com mais asserções que antes (título da aba, ausência do botão, caminhos e `noindex`). + - **B3.** `hooks/useNoIndex.ts` cria `` na 404 (inclusive a do roteador) e no conteúdo inexistente, e o remove ao sair; uma contagem de uso impede que um componente remova a tag de outro, e uma tag `robots` de outra origem nunca é tocada. O erro inesperado não recebe `noindex`: é uma falha passageira de uma página que existe. +- **Não feito:** índice na Privacidade (B4), por decisão do proprietário. +- **Limitação que continua:** a SPA responde HTTP 200 para qualquer rota (a Vercel serve o `index.html`). O `noindex` só vale depois que o JavaScript roda; buscadores que executam JavaScript o respeitam, mas a resposta continua sendo 200, não 404. Resolver isso exige mudar a infraestrutura (por exemplo, uma função que responda 404 para rotas conhecidas como inexistentes), o que não foi autorizado. +- **Custo:** o `PageError` vira um pacote de 1 KB, baixado só quando uma página de erro aparece; CSS global de 13,03 para 13,04 KB (gzip). +- **Testes:** 7 unitários (`useNoIndex` e `RouteError`, inclusive erro de renderização) e 25 E2E novos por largura (175 nas 7 larguras): os cinco tipos de inexistente, falha temporária com recuperação, falha técnica, `noindex` ao abrir direto, recarregar, voltar pelo histórico e sair para uma página válida, ausência de `noindex` em 12 páginas válidas, teclado e foco, alto contraste e as páginas de texto. Contraprova com oito defeitos reintroduzidos (tag que não sai, nova tentativa no inexistente, 404 sem `noindex`, erro sem `h1`, mensagem técnica, alto contraste, linha sólida e `noindex` no erro inesperado), cada um fazendo testes falharem. +- **Lighthouse** (build da `main` e desta versão, servidos igualmente, com a API de produção): desempenho igual dentro de ±1 ponto e acessibilidade 100 em todas. O SEO da 404 e do erro de filme cai para 63 porque a auditoria "a página pode ser indexada" reprova páginas com `noindex`, que é o efeito pretendido; Sobre e Privacidade seguem com 100. diff --git a/e2e/tests/encyclopedia.spec.ts b/e2e/tests/encyclopedia.spec.ts index 54dda6f..0bb9b02 100644 --- a/e2e/tests/encyclopedia.spec.ts +++ b/e2e/tests/encyclopedia.spec.ts @@ -63,15 +63,22 @@ test.describe("Série", () => { ); }); - test("mostra erro com nova tentativa quando a série não existe", async ({ + test("série inexistente: título próprio, caminhos de volta e sem nova tentativa", async ({ page, consoleErrors, }) => { consoleErrors.allow(/404/); await page.goto("/serie/999999"); - await expect(page.getByRole("alert")).toContainText("Não foi possível abrir esta série"); - await expect(page.getByRole("button", { name: "Tentar novamente" })).toBeVisible(); + // Tentar de novo não resolve um conteúdo que não existe (D-69). + await expect(page.getByRole("heading", { level: 1 })).toHaveText("Série não encontrada"); + await expect(page).toHaveTitle("Série não encontrada · Cinelux"); + await expect(page.getByRole("alert")).toContainText("nenhuma série do TMDB"); + await expect(page.getByRole("button", { name: "Tentar novamente" })).toHaveCount(0); + await expect( + page.getByRole("alert").getByRole("link", { name: "Descobrir filmes" }), + ).toBeVisible(); + await expect(page.locator('meta[name="robots"]')).toHaveAttribute("content", "noindex"); }); }); diff --git a/e2e/tests/movie.spec.ts b/e2e/tests/movie.spec.ts index fed50b0..ad71c0f 100644 --- a/e2e/tests/movie.spec.ts +++ b/e2e/tests/movie.spec.ts @@ -105,18 +105,26 @@ test.describe("Filme", () => { ).toContainText("Não informada"); }); - test("mostra erro com nova tentativa quando o filme não existe no TMDB", async ({ + test("filme inexistente no TMDB: título próprio, caminhos de volta e sem nova tentativa", async ({ page, consoleErrors, }) => { consoleErrors.allow(/status of 404/); await page.goto("/movie/999999"); + // Tentar de novo não resolve um conteúdo que não existe (D-69). + await expect(page.getByRole("heading", { level: 1 })).toHaveText("Filme não encontrado"); + await expect(page).toHaveTitle("Filme não encontrado · Cinelux"); const alert = page.getByRole("alert"); - await expect(alert).toContainText("Não foi possível abrir este filme"); - await expect(alert).toContainText("Não encontramos este conteúdo."); - await expect(alert.getByRole("button", { name: "Tentar novamente" })).toBeVisible(); + await expect(alert).toContainText("nenhum filme do TMDB"); + await expect(alert.getByRole("button", { name: "Tentar novamente" })).toHaveCount(0); + await expect(alert.getByRole("link", { name: "Descobrir filmes" })).toHaveAttribute( + "href", + "/discover", + ); await alert.getByRole("link", { name: "Voltar ao início" }).click(); await expect(page).toHaveURL("/"); + // A página inicial é válida: o noindex do erro não fica para trás. + await expect(page.locator('meta[name="robots"]')).toHaveCount(0); }); }); diff --git a/e2e/tests/page-errors.spec.ts b/e2e/tests/page-errors.spec.ts new file mode 100644 index 0000000..c88bf0f --- /dev/null +++ b/e2e/tests/page-errors.spec.ts @@ -0,0 +1,187 @@ +import { expect, expectNoHorizontalScroll, test } from "../helpers/test.ts"; + +/** Erros de página, 404 e noindex (D-69). */ + +const robots = '[name="robots"]'; + +const NOT_FOUND = [ + { kind: "filme", path: "/movie/999999", title: "Filme não encontrado" }, + { kind: "série", path: "/serie/999999", title: "Série não encontrada" }, + { kind: "pessoa", path: "/pessoa/999999", title: "Pessoa não encontrada" }, + { kind: "temporada", path: "/serie/1396/temporada/9", title: "Temporada não encontrada" }, + { kind: "coleção", path: "/colecao/999999", title: "Coleção não encontrada" }, +] as const; + +test.describe("Conteúdo inexistente", () => { + for (const { kind, path, title } of NOT_FOUND) { + test(`${kind}: h1, título da aba, caminhos de volta, sem nova tentativa e noindex`, async ({ + page, + consoleErrors, + }) => { + consoleErrors.allow(/404/); + await page.goto(path); + + await expect(page.getByRole("heading", { level: 1 })).toHaveText(title); + await expect(page.locator("h1")).toHaveCount(1); + await expect(page).toHaveTitle(`${title} · Cinelux`); + const alert = page.getByRole("alert"); + await expect(alert).not.toContainText(/não encontramos este conteúdo|chave/i); + await expect(alert.getByRole("button", { name: "Tentar novamente" })).toHaveCount(0); + await expect(alert.getByRole("link", { name: "Descobrir filmes" })).toHaveAttribute( + "href", + "/discover", + ); + await expect(alert.getByRole("link", { name: "Voltar ao início" })).toHaveAttribute( + "href", + "/", + ); + await expect(page.locator(`meta${robots}`)).toHaveAttribute("content", "noindex"); + await expectNoHorizontalScroll(page); + }); + } + + test("os cinco erros usam a mesma estrutura", async ({ page, consoleErrors }) => { + consoleErrors.allow(/404/); + for (const { path } of NOT_FOUND) { + await page.goto(path); + await expect(page.locator("main.page-error .page-head h1")).toHaveCount(1); + await expect(page.locator("main.page-error [role='alert']")).toHaveCount(1); + } + }); + + test("pelo teclado, o foco chega aos caminhos de volta", async ({ page, consoleErrors }) => { + consoleErrors.allow(/404/); + await page.goto("/movie/999999"); + const discover = page.getByRole("alert").getByRole("link", { name: "Descobrir filmes" }); + await expect(discover).toBeVisible(); + for (let step = 0; step < 40; step++) { + await page.keyboard.press("Tab"); + if (await discover.evaluate((element) => element === document.activeElement)) break; + } + await expect(discover).toBeFocused(); + const outline = await discover.evaluate((element) => getComputedStyle(element).outlineStyle); + expect(outline).not.toBe("none"); + }); +}); + +test.describe("Falhas que não são de conteúdo inexistente", () => { + test("falha temporária: mensagem clara, nova tentativa que funciona e sem noindex", async ({ + page, + tmdb, + consoleErrors, + }) => { + consoleErrors.allow(/503/); + tmdb.on("movie/550", { status: 503, body: { status_code: 9 } }, { times: 1 }); + await page.goto("/movie/550"); + + await expect(page.getByRole("heading", { level: 1 })).toHaveText( + "Não foi possível abrir este filme", + ); + await expect(page).toHaveTitle("Não foi possível abrir este filme · Cinelux"); + await expect(page.getByRole("alert")).toContainText("indisponível"); + await expect(page.locator(`meta${robots}`)).toHaveCount(0); + await page.getByRole("button", { name: "Tentar novamente" }).click(); + await expect(page.getByRole("heading", { level: 1 })).toHaveText("Clube da Luta"); + }); + + test("falha técnica: mensagem genérica, sem detalhes do servidor", async ({ + page, + tmdb, + consoleErrors, + }) => { + consoleErrors.allow(/401/); + tmdb.on("person/287", { status: 401, body: { status_code: 7 } }); + await page.goto("/pessoa/287"); + await expect(page.getByRole("heading", { level: 1 })).toHaveText( + "Não foi possível abrir este perfil", + ); + const alert = page.getByRole("alert"); + await expect(alert).not.toContainText(/chave|TMDB é inválida/i); + await expect(alert).toContainText("não respondeu como esperado"); + await expect(alert.getByRole("button", { name: "Tentar novamente" })).toBeVisible(); + }); +}); + +test.describe("noindex na navegação da SPA", () => { + test("rota inexistente aberta direto e recarregada: noindex, sem duplicar", async ({ page }) => { + await page.goto("/rota-que-nao-existe"); + await expect(page.getByRole("heading", { level: 1 })).toHaveText("Esta cena foi cortada"); + await expect(page.locator(`meta${robots}`)).toHaveAttribute("content", "noindex"); + await page.reload(); + await expect(page.locator(`meta${robots}`)).toHaveCount(1); + }); + + test("ao sair da 404 para uma página válida, o noindex não fica para trás", async ({ page }) => { + await page.goto("/rota-que-nao-existe"); + await expect(page.locator(`meta${robots}`)).toHaveCount(1); + await page.getByRole("main").getByRole("link", { name: "Voltar ao início" }).click(); + await expect(page).toHaveURL("/"); + await expect(page.locator(`meta${robots}`)).toHaveCount(0); + // E de volta pelo histórico: a 404 recoloca a tag. + await page.goBack(); + await expect(page.locator(`meta${robots}`)).toHaveCount(1); + }); + + for (const path of [ + "/", + "/discover", + "/search?q=duna", + "/movie/550", + "/serie/1396", + "/serie/1396/temporada/1", + "/pessoa/287", + "/pessoas", + "/colecao/2344", + "/minha-lista", + "/sobre", + "/privacidade", + ]) { + test(`página válida sem noindex: ${path}`, async ({ page }) => { + await page.goto(path); + await expect(page.locator("h1").first()).toBeVisible(); + await expect(page.locator(`meta${robots}`)).toHaveCount(0); + }); + } +}); + +test.describe("Telas de estado", () => { + test("código da 404 no gradiente da marca e sólido no alto contraste", async ({ page }) => { + await page.goto("/rota-que-nao-existe"); + const code = page.locator(".status-screen__code"); + await expect(code).toHaveText("404"); + expect(await code.evaluate((element) => getComputedStyle(element).backgroundClip)).toBe("text"); + + await page.emulateMedia({ forcedColors: "active" }); + await expect(code).toBeVisible(); + expect(await code.evaluate((element) => getComputedStyle(element).backgroundClip)).not.toBe( + "text", + ); + }); + + test("Sobre e Privacidade: um h1, seções com filete e o aviso do TMDB como citação", async ({ + page, + }) => { + for (const path of ["/sobre", "/privacidade"]) { + await page.goto(path); + await expect(page.locator("h1")).toHaveCount(1); + const section = page.locator(".legal__section").first(); + expect(await section.evaluate((element) => getComputedStyle(element).borderTopStyle)).toBe( + "none", + ); + expect( + await section.evaluate((element) => getComputedStyle(element).backgroundImage), + ).toContain("linear-gradient"); + await expectNoHorizontalScroll(page); + } + await page.goto("/sobre"); + const notice = page.locator(".legal__notice"); + // Texto obrigatório do TMDB preservado, agora sem caixa: só o filete dourado. + await expect(notice).toContainText("This product uses TMDB and the TMDB APIs"); + expect(await notice.evaluate((element) => getComputedStyle(element).backgroundColor)).toBe( + "rgba(0, 0, 0, 0)", + ); + expect(await notice.evaluate((element) => getComputedStyle(element).borderLeftStyle)).toBe( + "solid", + ); + }); +}); diff --git a/e2e/tests/season.spec.ts b/e2e/tests/season.spec.ts index 6005c94..01e64bb 100644 --- a/e2e/tests/season.spec.ts +++ b/e2e/tests/season.spec.ts @@ -100,11 +100,16 @@ test.describe("Temporada", () => { }) => { consoleErrors.allow(/404/); await page.goto("/serie/1396/temporada/9"); - await expect(page.getByRole("alert")).toContainText("Não foi possível abrir esta temporada"); + await expect(page.getByRole("heading", { level: 1 })).toHaveText("Temporada não encontrada"); + await expect(page.getByRole("alert")).toContainText("não tem uma temporada com este número"); await expect(page.getByRole("link", { name: "Voltar para a série" })).toHaveAttribute( "href", "/serie/1396", ); + // Inexistente: sem nova tentativa, com os caminhos padrão e noindex (D-69). + await expect(page.getByRole("button", { name: "Tentar novamente" })).toHaveCount(0); + await expect(page.getByRole("link", { name: "Descobrir filmes" }).first()).toBeVisible(); + await expect(page.locator('meta[name="robots"]')).toHaveAttribute("content", "noindex"); }); test("número de temporada inválido mostra a página 404 sem chamar o TMDB", async ({ diff --git a/src/components/ui/PageError.tsx b/src/components/ui/PageError.tsx new file mode 100644 index 0000000..4d42525 --- /dev/null +++ b/src/components/ui/PageError.tsx @@ -0,0 +1,86 @@ +import type { ReactNode } from "react"; +import { Link } from "react-router"; +import { messages } from "../../i18n"; +import { useNoIndex } from "../../hooks/useNoIndex"; +import type { TmdbErrorCode } from "../../services/tmdb"; +import StateMessage from "./StateMessage"; + +/** Textos de erro de cada página de detalhe (filme, série, pessoa, temporada, coleção). */ +export interface PageErrorTexts { + kicker: string; + notFoundTitle: string; + notFoundMessage: string; + errorTitle: string; +} + +/** + * Falhas que a pessoa entende e que uma nova tentativa pode resolver. As demais (chave do + * servidor, resposta inesperada...) são detalhes técnicos: no lugar, uma mensagem genérica. + */ +const FRIENDLY_ERRORS: readonly TmdbErrorCode[] = [ + "network", + "rateLimited", + "upstream", + "unavailable", +]; + +/** Título da aba no erro; a página o usa no próprio `useDocumentTitle` (D-69). */ +export function pageErrorTitle(code: TmdbErrorCode | null, texts: PageErrorTexts): string { + return code === "notFound" ? texts.notFoundTitle : texts.errorTitle; +} + +interface PageErrorProps { + texts: PageErrorTexts; + code: TmdbErrorCode | null; + /** Mensagem do serviço; só aparece quando é uma falha que a pessoa entende. */ + message: string; + onRetry: () => void; + /** Caminho a mais, antes dos padrões (ex.: "Voltar para a série" na temporada). */ + extraAction?: ReactNode | undefined; +} + +/** + * Erro de página de detalhe (D-69), com título de página (`h1`): + * - inexistente: sem "Tentar novamente" (não resolveria), com caminhos para descobrir e + * para o início, e `noindex` (a SPA responde 200 também para conteúdo inexistente); + * - falha temporária: a mensagem do serviço e "Tentar novamente"; + * - falha técnica: mensagem genérica, sem detalhes do servidor. + */ +const PageError = ({ texts, code, message, onRetry, extraAction }: PageErrorProps) => { + const notFound = code === "notFound"; + const friendly = code !== null && FRIENDLY_ERRORS.includes(code); + useNoIndex(notFound); + + return ( +
+
+
+

{texts.kicker}

+

{pageErrorTitle(code, texts)}

+
+ + {extraAction} + {notFound && ( + + {messages.common.discoverMovies} + + )} + + {messages.common.backHome} + + + } + /> +
+
+ ); +}; + +export default PageError; diff --git a/src/components/ui/StatusScreen.css b/src/components/ui/StatusScreen.css index de26dd4..2244357 100644 --- a/src/components/ui/StatusScreen.css +++ b/src/components/ui/StatusScreen.css @@ -12,12 +12,21 @@ gap: var(--space-4); } + /* Código ("404", "Ops") no gradiente da marca, como os algarismos do ranking (D-69). */ .status-screen__code { color: var(--color-accent-default); font-size: clamp(5rem, 3rem + 14vw, 12rem); line-height: var(--leading-numeral); } + @supports (background-clip: text) { + .status-screen__code { + background: var(--gradient-accent-text); + background-clip: text; + color: transparent; + } + } + .status-screen__title { max-width: 18ch; font-size: var(--text-3xl); diff --git a/src/hooks/useNoIndex.test.tsx b/src/hooks/useNoIndex.test.tsx new file mode 100644 index 0000000..a6601d4 --- /dev/null +++ b/src/hooks/useNoIndex.test.tsx @@ -0,0 +1,55 @@ +import { render } from "@testing-library/react"; +import { describe, expect, it } from "vitest"; +import { useNoIndex } from "./useNoIndex"; + +const Probe = ({ active }: { active?: boolean }) => { + useNoIndex(active); + return null; +}; + +const tags = () => document.head.querySelectorAll('meta[name="robots"]'); + +describe("useNoIndex", () => { + it("adiciona noindex ao montar e remove ao desmontar", () => { + const { unmount } = render(); + expect(tags()).toHaveLength(1); + expect(tags()[0]?.getAttribute("content")).toBe("noindex"); + unmount(); + expect(tags()).toHaveLength(0); + }); + + it("não age quando inativo", () => { + render(); + expect(tags()).toHaveLength(0); + }); + + it("vários usuários dividem uma tag; só o último a sair a remove", () => { + const first = render(); + const second = render(); + expect(tags()).toHaveLength(1); + first.unmount(); + expect(tags()).toHaveLength(1); + second.unmount(); + expect(tags()).toHaveLength(0); + }); + + it("deixar de estar ativo (o conteúdo carregou) remove a tag", () => { + const { rerender, unmount } = render(); + expect(tags()).toHaveLength(1); + rerender(); + expect(tags()).toHaveLength(0); + unmount(); + }); + + it("não remove uma tag robots que não é dela", () => { + const external = document.createElement("meta"); + external.name = "robots"; + external.content = "max-image-preview:large"; + document.head.append(external); + const { unmount } = render(); + unmount(); + expect(tags()).toHaveLength(1); + expect(tags()[0]).toBe(external); + external.remove(); + }); +}); diff --git a/src/hooks/useNoIndex.ts b/src/hooks/useNoIndex.ts new file mode 100644 index 0000000..7291249 --- /dev/null +++ b/src/hooks/useNoIndex.ts @@ -0,0 +1,37 @@ +import { useEffect } from "react"; + +/** + * Pede aos buscadores que não indexem a página atual (D-69): 404 e conteúdo inexistente. + * + * A SPA responde HTTP 200 para qualquer rota (o `index.html`), então a meta tag é o único + * sinal disponível sem mudar a infraestrutura. Ela é criada ao montar e removida ao + * desmontar; uma contagem de uso evita que um componente remova a tag de outro, e que a + * navegação para uma página válida carregue o `noindex` da anterior. + */ +const SELECTOR = 'meta[name="robots"][data-cinelux-noindex]'; +let users = 0; + +function addTag(): void { + if (document.head.querySelector(SELECTOR)) return; + const meta = document.createElement("meta"); + meta.name = "robots"; + meta.content = "noindex"; + meta.setAttribute("data-cinelux-noindex", ""); + document.head.append(meta); +} + +function removeTag(): void { + document.head.querySelector(SELECTOR)?.remove(); +} + +export function useNoIndex(active = true): void { + useEffect(() => { + if (!active) return undefined; + users += 1; + addTag(); + return () => { + users -= 1; + if (users === 0) removeTag(); + }; + }, [active]); +} diff --git a/src/i18n/pt-BR.ts b/src/i18n/pt-BR.ts index 1cb1f22..39e910a 100644 --- a/src/i18n/pt-BR.ts +++ b/src/i18n/pt-BR.ts @@ -206,6 +206,10 @@ export const ptBR = { position: "{position}º lugar", }, + pageError: { + generic: "O serviço de filmes não respondeu como esperado. Tente de novo em instantes.", + }, + status: { notFoundTitle: "Página não encontrada", notFoundCode: "404", @@ -321,6 +325,9 @@ export const ptBR = { loading: "Carregando filme", error: "Não foi possível abrir este filme", notFound: "Filme não encontrado.", + notFoundTitle: "Filme não encontrado", + notFoundMessage: + "Este endereço não corresponde a nenhum filme do TMDB. Ele pode ter sido removido ou o endereço está incorreto.", genresLabel: "Gêneros", originalTitle: "Título original: {title}", votes: "{count} votos no TMDB", @@ -412,6 +419,9 @@ export const ptBR = { fallbackTitle: "Série", error: "Não foi possível abrir esta série", notFound: "Série não encontrada.", + notFoundTitle: "Série não encontrada", + notFoundMessage: + "Este endereço não corresponde a nenhuma série do TMDB. Ela pode ter sido removida ou o endereço está incorreto.", seasonsCount: { one: "{count} temporada", other: "{count} temporadas" }, episodesCount: { one: "{count} episódio", other: "{count} episódios" }, createdBy: "Criação", @@ -447,6 +457,9 @@ export const ptBR = { documentTitle: "{season} · {show}", error: "Não foi possível abrir esta temporada", notFound: "Temporada não encontrada.", + notFoundTitle: "Temporada não encontrada", + notFoundMessage: + "Esta série não tem uma temporada com este número no TMDB. Veja as temporadas disponíveis na página da série.", backToShow: "Voltar para {show}", backToSeries: "Voltar para a série", breadcrumbLabel: "Você está em", @@ -470,6 +483,9 @@ export const ptBR = { fallbackTitle: "Pessoa", error: "Não foi possível abrir este perfil", notFound: "Pessoa não encontrada.", + notFoundTitle: "Pessoa não encontrada", + notFoundMessage: + "Este endereço não corresponde a nenhum perfil do TMDB. Ele pode ter sido removido ou o endereço está incorreto.", kicker: "Perfil", born: "Nascimento", died: "Falecimento", @@ -523,7 +539,6 @@ export const ptBR = { notFoundMessage: "Este endereço não corresponde a nenhuma coleção do TMDB. Ela pode ter sido removida ou unida a outra.", errorTitle: "Não foi possível abrir esta coleção", - errorGeneric: "O serviço de filmes não respondeu como esperado. Tente de novo em instantes.", discover: "Descobrir filmes", }, diff --git a/src/pages/Collection.tsx b/src/pages/Collection.tsx index be3f8ed..2e7efc0 100644 --- a/src/pages/Collection.tsx +++ b/src/pages/Collection.tsx @@ -10,9 +10,9 @@ import { textOr } from "../lib/format"; import { backdropSrcSet, getBackdropUrl } from "../lib/images"; import { useCollection } from "../hooks/useCollection"; import { useDocumentTitle } from "../hooks/useDocumentTitle"; -import type { TmdbErrorCode } from "../services/tmdb"; import PosterCard from "../components/movie/PosterCard"; import SectionHeader from "../components/ui/SectionHeader"; +import PageError, { pageErrorTitle } from "../components/ui/PageError"; import ShareButton from "../components/ui/ShareButton"; import StateMessage from "../components/ui/StateMessage"; import NotFound from "./NotFound"; @@ -20,17 +20,13 @@ import "./Collection.css"; const text = messages.collection; -/** - * Falhas que a pessoa entende e que uma nova tentativa pode resolver. As demais (chave do - * servidor, resposta inesperada...) são detalhes técnicos: a página mostra uma mensagem - * genérica no lugar (D-68). - */ -const FRIENDLY_ERRORS: readonly TmdbErrorCode[] = [ - "network", - "rateLimited", - "upstream", - "unavailable", -]; +/** Textos do erro de página (D-68, D-69). */ +const errorTexts = { + kicker: text.kicker, + notFoundTitle: text.notFoundTitle, + notFoundMessage: text.notFoundMessage, + errorTitle: text.errorTitle, +}; /** Mesma grade do cabeçalho final: a página não salta quando os dados chegam (D-68). */ const CollectionSkeleton = () => ( @@ -46,64 +42,16 @@ const CollectionSkeleton = () => ( ); -/** Erro com título de página: inexistente não oferece nova tentativa (D-68). */ -const CollectionError = ({ - code, - message, - onRetry, -}: { - code: TmdbErrorCode | null; - message: string; - onRetry: () => void; -}) => { - const notFound = code === "notFound"; - const friendly = code !== null && FRIENDLY_ERRORS.includes(code); - - return ( -
-
-
-

{text.kicker}

-

- {notFound ? text.notFoundTitle : text.errorTitle} -

-
- - {notFound && ( - - {text.discover} - - )} - - {messages.common.backHome} - - - } - /> -
-
- ); -}; - const CollectionDetails = ({ id }: { id: string }) => { const { data: collection, isLoading, error, errorCode, reload } = useCollection(id); - const notFound = errorCode === "notFound"; useDocumentTitle( - textOr( - collection?.name, - isLoading ? text.loadingTitle : notFound ? text.notFoundTitle : text.fallbackTitle, - ), + textOr(collection?.name, isLoading ? text.loadingTitle : pageErrorTitle(errorCode, errorTexts)), ); if (isLoading) return ; if (error || !collection) { - return ; + return ; } const parts = sortCollectionParts(collection.parts); diff --git a/src/pages/Legal.css b/src/pages/Legal.css index ff96cbc..bea27b3 100644 --- a/src/pages/Legal.css +++ b/src/pages/Legal.css @@ -9,7 +9,7 @@ justify-items: start; gap: var(--space-3); padding-block: var(--space-6); - border-top: 1px solid var(--color-border); + background: var(--rule-fade) top left / 100% var(--border-width) no-repeat; } .legal__title { @@ -34,13 +34,14 @@ height: 18px; } + /* Aviso do TMDB como citação editorial, no padrão da frase de efeito (D-64, D-69): + filete dourado, sem caixa. */ .legal__notice { display: grid; gap: var(--space-2); margin: var(--space-2) 0; - padding: var(--space-4); - border-left: 2px solid var(--color-accent-default); - background: var(--surface-card); + padding-left: var(--space-4); + border-left: var(--border-width-strong) solid var(--color-accent-default); } .legal__notice figcaption { @@ -53,13 +54,17 @@ } .legal__notice blockquote p { - color: var(--color-text-primary); + color: var(--color-text-heading); + font-family: var(--font-display); + font-size: var(--text-lg); font-weight: var(--weight-semibold); + letter-spacing: var(--tracking-tight); + line-height: var(--leading-title); } .legal__footer { padding-top: var(--space-5); - border-top: 1px solid var(--color-border); + background: var(--rule-fade) top left / 100% var(--border-width) no-repeat; color: var(--color-text-tertiary); } } diff --git a/src/pages/Movie.tsx b/src/pages/Movie.tsx index 012ad4e..d7b5486 100644 --- a/src/pages/Movie.tsx +++ b/src/pages/Movie.tsx @@ -1,5 +1,5 @@ import { useState } from "react"; -import { Link, useParams } from "react-router"; +import { useParams } from "react-router"; import { PiArrowDown, PiCalendarBlank, @@ -54,38 +54,32 @@ import TitleHero, { TitleHeroSkeleton } from "../components/title/TitleHero"; import VideoGallery from "../components/title/VideoGallery"; import SectionHeader from "../components/ui/SectionHeader"; import ShareButton from "../components/ui/ShareButton"; -import StateMessage from "../components/ui/StateMessage"; +import PageError, { pageErrorTitle } from "../components/ui/PageError"; import NotFound from "./NotFound"; import "./Movie.css"; const text = messages.movie; + +/** Textos do erro de página (D-69). */ +const errorTexts = { + kicker: text.fallbackTitle, + notFoundTitle: text.notFoundTitle, + notFoundMessage: text.notFoundMessage, + errorTitle: text.error, +}; const titleText = messages.title; const MovieDetails = ({ id }: { id: string }) => { const [trailerOpen, setTrailerOpen] = useState(false); - const { data: movie, isLoading, error, reload } = useMovie(id); - useDocumentTitle(textOr(movie?.title, isLoading ? text.loadingTitle : text.fallbackTitle)); + const { data: movie, isLoading, error, errorCode, reload } = useMovie(id); + useDocumentTitle( + textOr(movie?.title, isLoading ? text.loadingTitle : pageErrorTitle(errorCode, errorTexts)), + ); if (isLoading) return ; if (error || !movie) { - return ( -
-
- - {messages.common.backHome} - - } - /> -
-
- ); + return ; } const title = textOr(movie.title, messages.common.untitled); diff --git a/src/pages/NotFound.tsx b/src/pages/NotFound.tsx index fcadba8..38d5ca4 100644 --- a/src/pages/NotFound.tsx +++ b/src/pages/NotFound.tsx @@ -1,11 +1,14 @@ import { messages } from "../i18n"; import { useDocumentTitle } from "../hooks/useDocumentTitle"; +import { useNoIndex } from "../hooks/useNoIndex"; import StatusScreen from "../components/ui/StatusScreen"; const text = messages.status; const NotFound = () => { useDocumentTitle(text.notFoundTitle); + // A SPA responde 200 também aqui: o noindex evita que a 404 seja indexada (D-69). + useNoIndex(); return ( { }; const PersonProfile = ({ id }: { id: string }) => { - const { data: person, isLoading, error, reload } = usePerson(id); - useDocumentTitle(textOr(person?.name, isLoading ? text.loadingTitle : text.fallbackTitle)); + const { data: person, isLoading, error, errorCode, reload } = usePerson(id); + useDocumentTitle( + textOr(person?.name, isLoading ? text.loadingTitle : pageErrorTitle(errorCode, errorTexts)), + ); if (isLoading) return ; if (error || !person) { - return ( -
-
- - {messages.common.backHome} - - } - /> -
-
- ); + return ; } const photo = getProfileUrl(person.profile_path, "h632"); diff --git a/src/pages/RouteError.test.tsx b/src/pages/RouteError.test.tsx new file mode 100644 index 0000000..d198291 --- /dev/null +++ b/src/pages/RouteError.test.tsx @@ -0,0 +1,55 @@ +import { render, screen } from "@testing-library/react"; +import { createMemoryRouter, RouterProvider } from "react-router"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import RouteError from "./RouteError"; + +const robots = () => document.head.querySelector('meta[name="robots"]'); + +function renderRoute(route: { element?: React.ReactNode; loader?: () => never }) { + const router = createMemoryRouter([{ path: "/", errorElement: , ...route }]); + return render(); +} + +const Broken = () => { + throw new Error("falha de renderização simulada"); +}; + +describe("RouteError", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("erro inesperado: título próprio, caminhos de volta e sem noindex", async () => { + // O React registra o erro no console; aqui ele é esperado. + vi.spyOn(console, "error").mockImplementation(() => undefined); + renderRoute({ element: }); + + expect( + await screen.findByRole("heading", { level: 1, name: "O projetor falhou" }), + ).toBeVisible(); + expect(document.title).toBe("Algo deu errado · Cinelux"); + expect(screen.getByRole("link", { name: "Voltar ao início" })).toHaveAttribute("href", "/"); + expect(screen.getByRole("link", { name: "Descobrir filmes" })).toHaveAttribute( + "href", + "/discover", + ); + // Uma falha passageira de uma página que existe não deve sair dos buscadores. + expect(robots()).toBeNull(); + }); + + it("404 vinda do roteador: tela de página inexistente com noindex", async () => { + renderRoute({ + loader: () => { + // eslint-disable-next-line @typescript-eslint/only-throw-error -- é assim que o React Router sinaliza 404 + throw new Response("", { status: 404 }); + }, + element:

nunca exibido

, + }); + + expect( + await screen.findByRole("heading", { level: 1, name: "Esta cena foi cortada" }), + ).toBeVisible(); + expect(document.title).toBe("Página não encontrada · Cinelux"); + expect(robots()?.getAttribute("content")).toBe("noindex"); + }); +}); diff --git a/src/pages/RouteError.tsx b/src/pages/RouteError.tsx index 71cdcad..02b60c4 100644 --- a/src/pages/RouteError.tsx +++ b/src/pages/RouteError.tsx @@ -1,6 +1,7 @@ import { isRouteErrorResponse, useRouteError } from "react-router"; import { messages } from "../i18n"; import { useDocumentTitle } from "../hooks/useDocumentTitle"; +import { useNoIndex } from "../hooks/useNoIndex"; import StatusScreen from "../components/ui/StatusScreen"; const text = messages.status; @@ -10,6 +11,8 @@ const RouteError = () => { const isNotFound = isRouteErrorResponse(error) && error.status === 404; useDocumentTitle(isNotFound ? text.notFoundTitle : text.errorTitle); + // Só a 404: um erro inesperado é uma falha passageira de uma página que existe (D-69). + useNoIndex(isNotFound); if (import.meta.env.DEV && !isNotFound) { console.error(error); diff --git a/src/pages/Season.tsx b/src/pages/Season.tsx index 8a0edef..7be64c1 100644 --- a/src/pages/Season.tsx +++ b/src/pages/Season.tsx @@ -17,6 +17,7 @@ import { isSeasonNumber } from "../services/prefetch"; import Breadcrumbs from "../components/layout/Breadcrumbs"; import { Poster } from "../components/movie/PosterCard"; import SectionHeader from "../components/ui/SectionHeader"; +import PageError, { pageErrorTitle } from "../components/ui/PageError"; import StateMessage from "../components/ui/StateMessage"; import type { Episode } from "../types/tmdb"; import NotFound from "./NotFound"; @@ -25,6 +26,14 @@ import { loadStylesheet } from "../lib/stylesheet"; const text = messages.season; +/** Textos do erro de página (D-69). */ +const errorTexts = { + kicker: text.fallbackTitle, + notFoundTitle: text.notFoundTitle, + notFoundMessage: text.notFoundMessage, + errorTitle: text.error, +}; + /** Hoje no formato do TMDB (AAAA-MM-DD), no fuso de quem está vendo. */ function today(): string { const now = new Date(); @@ -120,7 +129,7 @@ const EpisodeCard = ({ episode, upcoming }: { episode: Episode; upcoming: boolea }; const SeasonDetailsPage = ({ id, number }: { id: string; number: string }) => { - const { data, isLoading, error, reload } = useSeason(id, number); + const { data, isLoading, error, errorCode, reload } = useSeason(id, number); const showName = textOr(data?.show.name, messages.tv.fallbackTitle); const seasonName = textOr(data?.season.name, text.fallbackTitle); useDocumentTitle( @@ -128,28 +137,24 @@ const SeasonDetailsPage = ({ id, number }: { id: string; number: string }) => { ? interpolate(text.documentTitle, { season: seasonName, show: showName }) : isLoading ? text.loadingTitle - : text.fallbackTitle, + : pageErrorTitle(errorCode, errorTexts), ); if (isLoading) return ; if (error || !data) { return ( -
-
- - {text.backToSeries} - - } - /> -
-
+ + {text.backToSeries} + + } + /> ); } diff --git a/src/pages/Tv.tsx b/src/pages/Tv.tsx index 0a49eef..c763184 100644 --- a/src/pages/Tv.tsx +++ b/src/pages/Tv.tsx @@ -1,5 +1,5 @@ import { useState } from "react"; -import { Link, useParams } from "react-router"; +import { useParams } from "react-router"; import { PiArrowDown, PiBroadcast, @@ -45,11 +45,19 @@ import TitleHero, { TitleHeroSkeleton } from "../components/title/TitleHero"; import VideoGallery from "../components/title/VideoGallery"; import SectionHeader from "../components/ui/SectionHeader"; import ShareButton from "../components/ui/ShareButton"; -import StateMessage from "../components/ui/StateMessage"; +import PageError, { pageErrorTitle } from "../components/ui/PageError"; import NotFound from "./NotFound"; import "./Movie.css"; const text = messages.tv; + +/** Textos do erro de página (D-69). */ +const errorTexts = { + kicker: text.fallbackTitle, + notFoundTitle: text.notFoundTitle, + notFoundMessage: text.notFoundMessage, + errorTitle: text.error, +}; const movieText = messages.movie; const titleText = messages.title; @@ -58,29 +66,15 @@ const MAX_RELATED = 6; const TvDetailsPage = ({ id }: { id: string }) => { const [trailerOpen, setTrailerOpen] = useState(false); - const { data: show, isLoading, error, reload } = useTv(id); - useDocumentTitle(textOr(show?.name, isLoading ? text.loadingTitle : text.fallbackTitle)); + const { data: show, isLoading, error, errorCode, reload } = useTv(id); + useDocumentTitle( + textOr(show?.name, isLoading ? text.loadingTitle : pageErrorTitle(errorCode, errorTexts)), + ); if (isLoading) return ; if (error || !show) { - return ( -
-
- - {messages.common.backHome} - - } - /> -
-
- ); + return ; } const title = textOr(show.name, messages.common.untitled); diff --git a/src/styles/base.css b/src/styles/base.css index 8cd931b..864acdb 100644 --- a/src/styles/base.css +++ b/src/styles/base.css @@ -158,7 +158,7 @@ } /* Texto recortado no gradiente da marca: volta à cor sólida do sistema (D-64, D-66). */ - :is(.ranked__number, .person-head__monogram, .watchlist__total-number) { + :is(.ranked__number, .person-head__monogram, .watchlist__total-number, .status-screen__code) { background: none; color: CanvasText; }