From fa070318d19848471e8e650c0c5228a0d4692ec3 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 18:31:12 +0000 Subject: [PATCH] =?UTF-8?q?feat(colecao):=20cabe=C3=A7alho=20editorial,=20?= =?UTF-8?q?sequ=C3=AAncia=20da=20franquia=20e=20erros=20claros?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - cabeçalho sem painel: no celular o texto fica abaixo da imagem; no desktop, véu forte atrás do texto (pior contraste 9,19:1, antes 1,07:1) - cabeçalho compacto sem imagem de fundo e escala menor para nomes longos - período e quantidade da franquia, filmes numerados na ordem de lançamento e "Em breve" para os sem data - erro com h1: inexistente, falha temporária com nova tentativa e falha técnica sem detalhes do servidor - botão Compartilhar - regras da coleção em lib/collection.ts, com testes unitários - PosterCard ganha o parâmetro opcional meta (sem efeito nas outras páginas) - testes E2E de regressão, conferidos com seis defeitos reintroduzidos Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HKQbFf5xJKvmX4LHXBRHDZ --- docs/DECISIONS.md | 18 ++ e2e/tests/collection.spec.ts | 295 ++++++++++++++++++++++++++++ e2e/tests/encyclopedia.spec.ts | 3 +- src/components/movie/PosterCard.tsx | 6 +- src/i18n/pt-BR.ts | 9 + src/lib/collection.test.ts | 76 +++++++ src/lib/collection.ts | 52 +++++ src/pages/Collection.css | 146 ++++++++++++-- src/pages/Collection.tsx | 198 ++++++++++++++----- 9 files changed, 728 insertions(+), 75 deletions(-) create mode 100644 e2e/tests/collection.spec.ts create mode 100644 src/lib/collection.test.ts create mode 100644 src/lib/collection.ts diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 7ea2436..5011fda 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -576,3 +576,21 @@ Cada decisão tem: contexto, decisão e consequência. As decisões D-01 a D-11 - **"Desfazer" de um título só:** restaurar uma cópia da lista inteira desfaria também remoções feitas depois. `reinsertWatchlistItem` devolve só aquele título, no lugar pela data de inclusão (`addedAt`). A primeira versão usava a posição numérica de origem, que muda com remoções seguidas; o E2E pegou (a tela parecia certa porque ordena por data, mas o armazenamento ficava fora de ordem) e um teste unitário reproduz o caso. A posição numérica só vale para itens antigos sem data de inclusão. - **Foco:** depois de remover, o foco vai para o título vizinho; se a lista esvaziar, para "Descobrir filmes". - **Armazenamento inalterado:** mesmo formato e chave (`cinelux:minha-lista:v1`); a ordenação nunca grava nada. + +## D-68. Redesign: coleções (`/colecao/:id`) + +- **Diagnóstico** (produção, dados reais: James Bond com 27 filmes, Matrix com descrição longa, Encanto, Os Fantasmas se Divertem sem pôster/data/descrição, Jujutsu Kaisen sem imagem de fundo, Star Trek com nome longo, coleção inexistente e identificador inválido; 8 larguras, 64 combinações): sem rolagem horizontal, cortes ou saltos de título. Os problemas: texto do cabeçalho com contraste abaixo de 4,5:1 sobre a imagem (medido pixel a pixel: 1,07 a 3,13 nos piores trechos no celular; o Lighthouse não mede contraste sobre imagem); cabeçalho em painel de vidro, com até 764 px no celular; painel vazio quando não há imagem; nome longo em 4 linhas; sem período, numeração ou compartilhar; filme anunciado como "Sem data"; e o estado de erro sem `h1`, mostrando a mensagem técnica do serviço (por exemplo, sobre a chave do TMDB). +- **Aprovado e feito (A1–A5, B1):** + - cabeçalho editorial sem painel: no celular a imagem é uma faixa no topo e o texto fica abaixo dela, sobre o fundo sólido; a partir de 900 px o texto fica sobre a imagem, com um véu escuro forte atrás da coluna de texto. Pior contraste medido depois: 9,19:1 (antes 1,07:1); + - sem imagem: cabeçalho compacto com a luz dourada das pessoas (D-66); + - nomes acima de 28 caracteres usam escala menor (no máximo três linhas a 320 px, sem cortar); + - período e quantidade ("1962–2021 · 27 filmes"), lista ordenada com o número de cada filme na sequência (visual; a posição é anunciada pela própria lista) e "Em breve" para filmes sem data; + - erro com `h1` em todos os estados: inexistente ("Coleção não encontrada", sem nova tentativa, com caminho para descobrir), falha temporária (mensagem do serviço e "Tentar novamente") e falha técnica (mensagem genérica, sem detalhes do servidor); identificador inválido continua na 404 do site; + - botão Compartilhar, o mesmo de filme, série e pessoa; + - descrição sempre abaixo do cabeçalho, como abertura. +- **Regras em `lib/collection.ts`** (antes dentro do componente): ordem de lançamento (sem data por último; empate pelo título e pela ordem do TMDB), período, numeração e nome longo, com testes unitários. +- **Componente compartilhado:** `PosterCard` ganhou o parâmetro opcional `meta` (texto abaixo do título no lugar do ano). Sem ele, nada muda; o teste visual confirmou que só as telas de coleção mudaram. +- **Desempenho:** o primeiro pôster só recebe prioridade alta quando não há imagem de fundo; com ela, a imagem é o maior elemento e o pôster não disputa a banda. +- **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. diff --git a/e2e/tests/collection.spec.ts b/e2e/tests/collection.spec.ts new file mode 100644 index 0000000..6f0a3c0 --- /dev/null +++ b/e2e/tests/collection.spec.ts @@ -0,0 +1,295 @@ +import type { Page } from "@playwright/test"; +import { collection2344 } from "../fixtures/index.ts"; +import { deferred, expect, test } from "../helpers/test.ts"; +import type { CollectionDetails, MovieSummary } from "../../src/types/tmdb.ts"; + +/** Página de coleção: cabeçalho, sequência, casos especiais, erros e compartilhar (D-68). */ + +const PATH = "/colecao/2344"; +const ENDPOINT = "collection/2344"; + +/** PNG branco: a imagem de fundo mais clara possível, o pior caso para o contraste. */ +const WHITE_PNG = Buffer.from( + "iVBORw0KGgoAAAANSUhEUgAAABAAAAAJCAIAAAC0SDtlAAAAF0lEQVR4nGP8//8/AymAiSTVoxpopQEAMWADD3qy2BsAAAAASUVORK5CYII=", + "base64", +); + +const part = ( + id: number, + title: string, + release_date?: string, + poster: string | null = "/p.jpg", +): MovieSummary => ({ + id, + title, + poster_path: poster, + ...(release_date === undefined ? {} : { release_date }), +}); + +const withCollection = (overrides: Partial): { body: CollectionDetails } => ({ + body: { ...collection2344, ...overrides }, +}); + +const parts = (page: Page) => + page.getByRole("list", { name: "Filmes da coleção" }).getByRole("listitem"); + +test.describe("Coleção: conteúdo", () => { + test("cabeçalho com período e quantidade, filmes numerados na ordem de lançamento", async ({ + page, + }) => { + await page.goto(PATH); + await expect(page.getByRole("heading", { level: 1 })).toHaveText(collection2344.name); + await expect(page.locator(".collection-hero__facts")).toHaveText("1999–2003 · 3 filmes"); + + // A numeração acompanha a ordem de lançamento, não a ordem que veio do TMDB. + await expect(parts(page).locator(".collection-part__number")).toHaveText(["01", "02", "03"]); + await expect(parts(page).getByRole("heading", { level: 3 })).toHaveText([ + "Matrix", + "Matrix Reloaded", + "Matrix Revolutions", + ]); + // O número é só visual: a lista ordenada já anuncia a posição. + await expect(parts(page).first().locator(".collection-part__number")).toHaveAttribute( + "aria-hidden", + "true", + ); + + // Um único h1, e o card leva ao detalhe. + await expect(page.locator("h1")).toHaveCount(1); + await parts(page).first().getByRole("link").click(); + await expect(page).toHaveURL("/movie/603"); + await expect(page.getByRole("heading", { level: 1 })).toHaveText("Matrix"); + }); + + test("sem imagem, sem descrição, sem pôster e sem data: cabeçalho compacto e 'Em breve'", async ({ + page, + tmdb, + }) => { + tmdb.on( + ENDPOINT, + withCollection({ + backdrop_path: null, + overview: "", + parts: [ + part(2, "Sequência", "2003-05-15"), + part(3, "Anunciado", undefined, null), + part(1, "Original", "1999-03-31"), + ], + }), + ); + await page.goto(PATH); + + await expect(page.locator(".collection-hero")).toHaveClass(/collection-hero--plain/); + await expect(page.locator(".collection-hero img")).toHaveCount(0); + await expect( + page.getByText("Esta coleção ainda não tem descrição em português."), + ).toBeVisible(); + + const last = parts(page).last(); + await expect(last.locator(".collection-part__number")).toHaveText("03"); + await expect(last.locator(".poster-card__meta")).toHaveText("Em breve"); + await expect(last.locator(".collection-part__badge")).toHaveText("Em breve"); + await expect(last).not.toContainText("Sem data"); + // O período considera só os filmes com data. + await expect(page.locator(".collection-hero__facts")).toHaveText("1999–2003 · 3 filmes"); + }); + + test("um filme só: ano único e singular", async ({ page, tmdb }) => { + tmdb.on(ENDPOINT, withCollection({ parts: [part(1, "Único", "2021-09-30")] })); + await page.goto(PATH); + await expect(page.locator(".collection-hero__facts")).toHaveText("2021 · 1 filme"); + await expect(parts(page)).toHaveCount(1); + }); + + test("coleção vazia: aviso com caminho para descobrir, sem período", async ({ page, tmdb }) => { + tmdb.on(ENDPOINT, withCollection({ parts: [] })); + await page.goto(PATH); + await expect(page.getByRole("heading", { level: 1 })).toHaveText(collection2344.name); + await expect(page.getByText("Esta coleção ainda não tem filmes")).toBeVisible(); + await expect( + page.getByRole("main").getByRole("link", { name: "Descobrir filmes" }), + ).toHaveAttribute("href", "/discover"); + await expect(page.locator(".collection-hero__facts")).toHaveCount(0); + }); + + test("nome longo cabe em até três linhas, sem cortar", async ({ page, tmdb }) => { + const name = "Star Trek: Realidade Alternativa - Coleção"; + tmdb.on(ENDPOINT, withCollection({ name })); + await page.goto(PATH); + const title = page.getByRole("heading", { level: 1 }); + await expect(title).toHaveText(name); + const [lines, overflow] = await title.evaluate((element) => [ + Math.round( + element.getBoundingClientRect().height / parseFloat(getComputedStyle(element).lineHeight), + ), + element.scrollWidth - element.clientWidth, + ]); + expect(lines).toBeLessThanOrEqual(3); + expect(overflow).toBeLessThanOrEqual(0); + }); + + test("mostra o esqueleto enquanto carrega, sem salto para o conteúdo", async ({ page, tmdb }) => { + const gate = deferred(); + tmdb.on(ENDPOINT, { body: collection2344, waitFor: gate.promise }); + await page.goto(PATH); + await expect(page.locator("main[aria-busy='true']")).toBeVisible(); + gate.resolve(); + await expect(page.getByRole("heading", { level: 1 })).toHaveText(collection2344.name); + await expect(page.locator("main[aria-busy='true']")).toHaveCount(0); + }); +}); + +test.describe("Coleção: erros", () => { + test("inexistente: título próprio e caminhos, sem 'Tentar novamente'", async ({ + page, + tmdb, + consoleErrors, + }) => { + consoleErrors.allow(/404/); + tmdb.on(ENDPOINT, { status: 404, body: { status_code: 34 } }); + await page.goto(PATH); + await expect(page.getByRole("heading", { level: 1 })).toHaveText("Coleção não encontrada"); + await expect(page).toHaveTitle("Coleção não encontrada · Cinelux"); + await expect(page.getByRole("button", { name: "Tentar novamente" })).toHaveCount(0); + await expect( + page.getByRole("main").getByRole("link", { name: "Descobrir filmes" }), + ).toBeVisible(); + }); + + test("falha temporária: mensagem clara e nova tentativa que funciona", async ({ + page, + tmdb, + consoleErrors, + }) => { + consoleErrors.allow(/503/); + // O erro do carregamento antecipado fica guardado para a página: uma consulta só. + tmdb.on(ENDPOINT, { status: 503, body: { status_code: 9 } }, { times: 1 }); + await page.goto(PATH); + await expect(page.getByRole("heading", { level: 1 })).toHaveText( + "Não foi possível abrir esta coleção", + ); + await expect(page.getByRole("alert")).toContainText("indisponível"); + await page.getByRole("button", { name: "Tentar novamente" }).click(); + await expect(page.getByRole("heading", { level: 1 })).toHaveText(collection2344.name); + }); + + test("falha técnica não mostra detalhes do servidor", async ({ page, tmdb, consoleErrors }) => { + consoleErrors.allow(/401/); + tmdb.on(ENDPOINT, { status: 401, body: { status_code: 7 } }); + await page.goto(PATH); + await expect(page.getByRole("heading", { level: 1 })).toHaveText( + "Não foi possível abrir esta coleção", + ); + await expect(page.getByRole("alert")).not.toContainText(/chave|TMDB é inválida/i); + await expect(page.getByRole("alert")).toContainText("não respondeu como esperado"); + }); + + test("identificador inválido vai para a 404 do site sem consultar a API", async ({ + page, + tmdb, + }) => { + await page.goto("/colecao/abc"); + await expect(page.getByRole("heading", { level: 1 })).toHaveText("Esta cena foi cortada"); + expect(tmdb.calls.filter((url) => url.pathname.includes("collection"))).toEqual([]); + }); +}); + +test.describe("Coleção: compartilhar", () => { + test("usa a folha do sistema com o nome da coleção", async ({ page }) => { + await page.addInitScript(() => { + const shared: unknown[] = []; + Object.assign(window, { __shared: shared }); + Object.defineProperty(navigator, "share", { + configurable: true, + value: (data: unknown) => { + shared.push(data); + return Promise.resolve(); + }, + }); + }); + await page.goto(PATH); + await page.getByRole("button", { name: "Compartilhar" }).click(); + const shared = await page.evaluate( + () => (window as unknown as { __shared: unknown[] }).__shared, + ); + expect(shared).toEqual([{ title: collection2344.name, url: page.url() }]); + }); + + test("sem a folha do sistema, copia o link pelo teclado e avisa", async ({ page, context }) => { + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + await page.goto(PATH); + await page.getByRole("button", { name: "Compartilhar" }).focus(); + await page.keyboard.press("Enter"); + await expect(page.getByRole("button", { name: "Link copiado" })).toBeVisible(); + await expect(page.getByRole("region", { name: "Avisos" })).toContainText("Link copiado"); + expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(page.url()); + }); +}); + +test.describe("Coleção: contraste do cabeçalho", () => { + test("texto com pelo menos 4,5:1 mesmo sobre uma imagem de fundo branca", async ({ page }) => { + await page.route("https://image.tmdb.org/**", (route) => + route.fulfill({ status: 200, contentType: "image/png", body: WHITE_PNG }), + ); + await page.goto(PATH); + await expect(page.locator(".collection-hero__media img")).toBeVisible(); + await page.waitForFunction( + () => document.querySelector(".collection-hero__media img")?.complete, + ); + + const texts = page.locator(".collection-hero__content > :is(p, h1)"); + const targets = await texts.evaluateAll((elements) => + elements.map((element) => { + const box = element.getBoundingClientRect(); + return { + color: getComputedStyle(element).color, + box: [box.x, box.y, box.width, box.height], + }; + }), + ); + // Esconde só o texto (pelo próprio elemento: a CSP proíbe estilos injetados) e mede o + // fundo que fica sob ele. + await texts.evaluateAll((elements) => { + for (const element of elements) (element as HTMLElement).style.visibility = "hidden"; + }); + const shot = (await page.screenshot()).toString("base64"); + + // A leitura dos pixels acontece numa página em branco, fora do site: a CSP do site + // (corretamente) não aceita imagens data:. + const tool = await page.context().newPage(); + const worst = await tool.evaluate( + async ({ shot, targets, viewport }) => { + const image = new Image(); + image.src = `data:image/png;base64,${shot}`; + await image.decode(); + const canvas = document.createElement("canvas"); + canvas.width = image.width; + canvas.height = image.height; + const context = canvas.getContext("2d"); + if (!context) return 0; + context.drawImage(image, 0, 0); + const scale = image.width / viewport; + const luminance = ([r, g, b]: number[]) => { + const f = (c: number) => + (c /= 255) <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; + return 0.2126 * f(r ?? 0) + 0.7152 * f(g ?? 0) + 0.0722 * f(b ?? 0); + }; + let min = 21; + for (const { color, box } of targets) { + const text = (color.match(/\d+/g) ?? []).slice(0, 3).map(Number); + const [x = 0, y = 0, w = 0, h = 0] = box.map((v) => Math.round(v * scale)); + const data = context.getImageData(x, y, Math.max(1, w), Math.max(1, h)).data; + for (let i = 0; i < data.length; i += 4 * 7) { + const a = luminance(text); + const b = luminance([data[i] ?? 0, data[i + 1] ?? 0, data[i + 2] ?? 0]); + min = Math.min(min, (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05)); + } + } + return min; + }, + { shot, targets, viewport: page.viewportSize()?.width ?? 1 }, + ); + await tool.close(); + expect(worst).toBeGreaterThanOrEqual(4.5); + }); +}); diff --git a/e2e/tests/encyclopedia.spec.ts b/e2e/tests/encyclopedia.spec.ts index cefe5e9..54dda6f 100644 --- a/e2e/tests/encyclopedia.spec.ts +++ b/e2e/tests/encyclopedia.spec.ts @@ -227,7 +227,8 @@ test.describe("Navegação entre conteúdos", () => { await page.getByRole("link", { name: /Parte da coleção.*Matrix: Coleção/ }).click(); await expect(page).toHaveURL("/colecao/2344"); await expect(page.getByRole("heading", { level: 1 })).toHaveText(collection2344.name); - await expect(page.getByText("Coleção · 3 filmes")).toBeVisible(); + // Período e quantidade da franquia (D-68). + await expect(page.getByText("1999–2003 · 3 filmes")).toBeVisible(); const parts = page.getByRole("list", { name: "Filmes da coleção" }).getByRole("listitem"); await expect(parts).toHaveText([/Matrix\s*1999/, /Matrix Reloaded/, /Matrix Revolutions/]); diff --git a/src/components/movie/PosterCard.tsx b/src/components/movie/PosterCard.tsx index 58a0705..02f0866 100644 --- a/src/components/movie/PosterCard.tsx +++ b/src/components/movie/PosterCard.tsx @@ -63,10 +63,12 @@ interface PosterCardProps { movie: MovieSummary; eager?: boolean | undefined; priority?: boolean | undefined; + /** Texto abaixo do título no lugar do ano (ex.: "Em breve" na coleção, D-68). */ + meta?: string | undefined; } /** Card de filme: o pôster é o protagonista; o card inteiro é um link. */ -const PosterCard = ({ movie, eager = false, priority = false }: PosterCardProps) => { +const PosterCard = ({ movie, eager = false, priority = false, meta }: PosterCardProps) => { const title = getMovieTitle(movie); const year = getReleaseYear(movie.release_date); @@ -82,7 +84,7 @@ const PosterCard = ({ movie, eager = false, priority = false }: PosterCardProps)

{title}

-

{year ?? messages.common.noDate}

+

{meta ?? year ?? messages.common.noDate}

); }; diff --git a/src/i18n/pt-BR.ts b/src/i18n/pt-BR.ts index 8e0746f..1cb1f22 100644 --- a/src/i18n/pt-BR.ts +++ b/src/i18n/pt-BR.ts @@ -516,6 +516,15 @@ export const ptBR = { partsSubtitle: "Em ordem de lançamento.", partsLabel: "Filmes da coleção", noOverview: "Esta coleção ainda não tem descrição em português.", + upcoming: "Em breve", + emptyTitle: "Esta coleção ainda não tem filmes", + emptyMessage: "O TMDB ainda não lista filmes para esta franquia.", + notFoundTitle: "Coleção não encontrada", + 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", }, people: { diff --git a/src/lib/collection.test.ts b/src/lib/collection.test.ts new file mode 100644 index 0000000..166e43c --- /dev/null +++ b/src/lib/collection.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from "vitest"; +import type { MovieSummary } from "../types/tmdb"; +import { + collectionPeriod, + isLongCollectionName, + sequenceNumber, + sortCollectionParts, +} from "./collection"; + +const movie = (id: number, title: string, release_date?: string): MovieSummary => ({ + id, + title, + poster_path: null, + ...(release_date === undefined ? {} : { release_date }), +}); + +describe("sortCollectionParts", () => { + it("ordena por lançamento, com os sem data por último", () => { + const parts = [ + movie(1, "Matrix Revolutions", "2003-11-05"), + movie(2, "Matrix 5"), + movie(3, "Matrix", "1999-03-31"), + movie(4, "Matrix Reloaded", "2003-05-15"), + movie(5, "Matrix Antigo", ""), + ]; + expect(sortCollectionParts(parts).map((part) => part.id)).toEqual([3, 4, 1, 2, 5]); + }); + + it("desempata pelo título e mantém a ordem do TMDB quando tudo é igual", () => { + const parts = [ + movie(1, "Beta", "2010-01-01"), + movie(2, "alfa", "2010-01-01"), + movie(3, "Gama"), + movie(4, "Gama"), + ]; + expect(sortCollectionParts(parts).map((part) => part.id)).toEqual([2, 1, 3, 4]); + }); + + it("não altera a lista original e aceita lista vazia", () => { + const parts = [movie(1, "B", "2001-01-01"), movie(2, "A", "2000-01-01")]; + sortCollectionParts(parts); + expect(parts.map((part) => part.id)).toEqual([1, 2]); + expect(sortCollectionParts([])).toEqual([]); + }); +}); + +describe("collectionPeriod", () => { + it("vai do primeiro ao último ano, ignorando quem não tem data", () => { + expect( + collectionPeriod([movie(1, "a", "2021-09-30"), movie(2, "b", "1962-10-05"), movie(3, "c")]), + ).toBe("1962–2021"); + }); + + it("mostra um ano só quando todos são do mesmo ano", () => { + expect(collectionPeriod([movie(1, "a", "2021-01-01"), movie(2, "b", "2021-12-01")])).toBe( + "2021", + ); + }); + + it("é null sem nenhuma data (coleção vazia ou só com filmes anunciados)", () => { + expect(collectionPeriod([])).toBeNull(); + expect(collectionPeriod([movie(1, "a"), movie(2, "b", "")])).toBeNull(); + }); +}); + +describe("sequenceNumber e nomes longos", () => { + it("numera a partir de 01, com dois dígitos", () => { + expect([0, 8, 26].map(sequenceNumber)).toEqual(["01", "09", "27"]); + }); + + it("marca como longo o nome do Star Trek, não o da Matrix", () => { + expect(isLongCollectionName("Star Trek: Realidade Alternativa - Coleção")).toBe(true); + expect(isLongCollectionName("Matrix: Coleção")).toBe(false); + expect(isLongCollectionName("Os Fantasmas se Divertem: Coleção")).toBe(true); + }); +}); diff --git a/src/lib/collection.ts b/src/lib/collection.ts new file mode 100644 index 0000000..bad4a3c --- /dev/null +++ b/src/lib/collection.ts @@ -0,0 +1,52 @@ +import type { MovieSummary } from "../types/tmdb"; +import { getReleaseYear } from "./format"; + +/** + * Regras da página de coleção (D-68), fora do componente para serem testadas. + */ + +/** + * Ordem de lançamento: filmes com data primeiro, do mais antigo ao mais recente; os sem + * data (anunciados) por último. Empates (mesma data ou nenhuma) ficam pelo título e, por + * fim, pela ordem que veio do TMDB, para o resultado ser sempre o mesmo. + */ +export function sortCollectionParts(parts: readonly MovieSummary[]): MovieSummary[] { + const byTitle = new Intl.Collator("pt-BR", { sensitivity: "base", numeric: true }); + return parts + .map((part, index) => ({ part, index })) + .sort((a, b) => { + const da = a.part.release_date ?? ""; + const db = b.part.release_date ?? ""; + if (da !== db) { + if (!da) return 1; + if (!db) return -1; + return da.localeCompare(db); + } + return byTitle.compare(a.part.title, b.part.title) || a.index - b.index; + }) + .map(({ part }) => part); +} + +/** Período da franquia pelos filmes com data: "1962–2021", "2021" ou null. */ +export function collectionPeriod(parts: readonly MovieSummary[]): string | null { + const years = parts + .map((part) => getReleaseYear(part.release_date)) + .filter((year): year is string => year !== null) + .map(Number); + if (!years.length) return null; + const first = Math.min(...years); + const last = Math.max(...years); + return first === last ? String(first) : `${String(first)}–${String(last)}`; +} + +/** Posição do filme na sequência, com dois dígitos: "01", "02"... "27". */ +export const sequenceNumber = (index: number): string => String(index + 1).padStart(2, "0"); + +/** + * Nomes acima disto usam uma escala menor no cabeçalho, para não ocupar quatro linhas no + * celular ("Star Trek: Realidade Alternativa - Coleção" tem 42 caracteres). + */ +export const LONG_COLLECTION_NAME = 28; + +export const isLongCollectionName = (name: string): boolean => + name.trim().length > LONG_COLLECTION_NAME; diff --git a/src/pages/Collection.css b/src/pages/Collection.css index 8c3f154..485e946 100644 --- a/src/pages/Collection.css +++ b/src/pages/Collection.css @@ -1,25 +1,22 @@ @layer pages { - /* Cabeçalho da coleção: painel com a imagem de fundo e o texto por cima. */ + /* + * Cabeçalho editorial da coleção (D-68): sem painel. A imagem de fundo ocupa a largura + * e esmaece na página. + * celular: a imagem é uma faixa no topo e o texto fica abaixo dela, sobre o fundo + * sólido; o contraste não depende da imagem + * 900 px+: o texto fica sobre a imagem, com um véu escuro forte atrás da coluna de texto + */ .collection-hero { position: relative; display: grid; - width: min(100% - 2 * var(--gutter), var(--container-max)); - min-height: min(56svh, 460px); - margin: var(--space-5) auto 0; - align-items: end; - overflow: hidden; isolation: isolate; - border: var(--border-width) solid var(--glass-border-strong); - border-radius: var(--radius-lg); - background: var(--gradient-panel); - box-shadow: var(--glass-highlight), var(--glass-shadow); } .collection-hero__media { - position: absolute; - inset: 0; - z-index: var(--layer-behind); - border-radius: 0; + position: relative; + aspect-ratio: 16 / 9; + max-height: 46svh; + overflow: hidden; } .collection-hero__media img { @@ -29,39 +26,150 @@ object-position: center 25%; } + /* A imagem esmaece no fundo da página, sem linha de corte. */ .collection-hero__media::after { position: absolute; inset: 0; - background: var(--gradient-hero-scrim); + background: var(--gradient-backdrop-scrim); content: ""; } .collection-hero__content { display: grid; justify-items: start; - gap: var(--space-3); - padding: var(--space-7) var(--space-5) var(--space-5); + gap: var(--space-2); + padding-block: var(--space-4) var(--space-2); } .collection-hero__title { font-size: var(--text-3xl); + overflow-wrap: anywhere; text-wrap: balance; } + /* Nomes longos usam uma escala menor: no máximo três linhas a 320 px, sem cortar. */ + .collection-hero__title--long { + font-size: clamp(1.75rem, 1.2rem + 2.6vw, 3.25rem); + } + .collection-hero__title-skeleton { width: min(24rem, 85%); height: clamp(2.2rem, 5vw, 3.5rem); } - .collection-hero__overview { + .collection-hero__facts { + color: var(--color-text-secondary); + } + + .collection-hero__actions { + margin-top: var(--space-2); + } + + /* Sem imagem de fundo: cabeçalho compacto com a luz dourada sutil das pessoas (D-66). */ + .collection-hero--plain::before { + position: absolute; + inset: -4rem 0 0; + z-index: var(--layer-behind); + background: var(--gradient-spotlight); + content: ""; + pointer-events: none; + } + + .collection-hero--plain .collection-hero__content { + padding-top: var(--space-6); + } + + /* Descrição como abertura editorial, abaixo do cabeçalho em todas as larguras. */ + .collection-overview { max-width: var(--measure-prose); + margin-top: var(--space-5); color: var(--color-text-secondary); font-size: var(--text-lg); + line-height: var(--leading-relaxed); + } + + /* No celular, a descrição longa em corpo normal: menos altura antes dos filmes. */ + @media (max-width: 599px) { + .collection-overview { + margin-top: var(--space-4); + font-size: var(--text-md); + line-height: var(--leading-body); + } + } + + .collection-overview--empty { + color: var(--color-text-tertiary); + font-size: var(--text-md); + } + + /* Filmes em sequência: número de ordem acima de cada card. */ + .collection-parts { + margin: 0; + padding: 0; + list-style: none; + } + + .collection-part { + position: relative; + display: grid; + align-content: start; + gap: var(--space-2); + } + + .collection-part__number { + color: var(--color-text-tertiary); + font-size: var(--text-lg); + font-variant-numeric: lining-nums tabular-nums; + line-height: var(--leading-none); + } + + .collection-part__badge { + position: absolute; + top: calc(var(--text-lg) + var(--space-2) + var(--space-4)); + left: var(--space-4); + z-index: 1; + pointer-events: none; } @media (min-width: 900px) { + .collection-hero { + min-height: min(62svh, 520px); + align-items: end; + } + + .collection-hero__media { + position: absolute; + inset: 0; + z-index: var(--layer-behind); + max-height: none; + aspect-ratio: auto; + } + + /* Véu forte atrás da coluna de texto (à esquerda e embaixo): contraste AA sobre + qualquer imagem, inclusive as claras. */ + .collection-hero__media::after { + background: + linear-gradient( + 90deg, + rgb(var(--rgb-ink) / 94%) 0%, + rgb(var(--rgb-ink) / 86%) 38%, + rgb(var(--rgb-ink) / 20%) 72%, + rgb(var(--rgb-ink) / 0%) 100% + ), + var(--gradient-backdrop-scrim); + } + .collection-hero__content { - padding: var(--space-8) var(--space-7) var(--space-7); + max-width: min(var(--container-max), 100% - 2 * var(--gutter)); + padding-block: var(--space-8) var(--space-6); + } + + .collection-hero__content > * { + max-width: 38rem; + } + + .collection-hero--plain { + min-height: 0; } } } diff --git a/src/pages/Collection.tsx b/src/pages/Collection.tsx index 95707b7..be3f8ed 100644 --- a/src/pages/Collection.tsx +++ b/src/pages/Collection.tsx @@ -1,67 +1,124 @@ import { Link, useParams } from "react-router"; import { messages, plural } from "../i18n"; +import { + collectionPeriod, + isLongCollectionName, + sequenceNumber, + sortCollectionParts, +} from "../lib/collection"; import { textOr } from "../lib/format"; import { backdropSrcSet, getBackdropUrl } from "../lib/images"; import { useCollection } from "../hooks/useCollection"; import { useDocumentTitle } from "../hooks/useDocumentTitle"; -import PosterGrid from "../components/movie/PosterGrid"; +import type { TmdbErrorCode } from "../services/tmdb"; +import PosterCard from "../components/movie/PosterCard"; import SectionHeader from "../components/ui/SectionHeader"; +import ShareButton from "../components/ui/ShareButton"; import StateMessage from "../components/ui/StateMessage"; import NotFound from "./NotFound"; 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", +]; + +/** Mesma grade do cabeçalho final: a página não salta quando os dados chegam (D-68). */ 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, reload } = useCollection(id); - useDocumentTitle(textOr(collection?.name, isLoading ? text.loadingTitle : text.fallbackTitle)); + 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, + ), + ); if (isLoading) return ; if (error || !collection) { - return ( -
-
- - {messages.common.backHome} - - } - /> -
-
- ); + return ; } - // Ordem de lançamento; filmes ainda sem data ficam por último. - const parts = [...collection.parts].sort((a, b) => { - if (!a.release_date || !b.release_date) return a.release_date ? -1 : b.release_date ? 1 : 0; - return a.release_date.localeCompare(b.release_date); - }); + const parts = sortCollectionParts(collection.parts); + const period = collectionPeriod(parts); const backdrop = getBackdropUrl(collection.backdrop_path); + const facts = [period, parts.length ? plural(text.count, parts.length) : null].filter(Boolean); return (
-
-
- {backdrop && ( +
+ {backdrop && ( +
{ alt="" fetchPriority="high" /> - )} -
-
-

- {[text.kicker, plural(text.count, parts.length)].join(" · ")} -

-

+

+ )} +
+

{text.kicker}

+

{collection.name}

-

- {textOr(collection.overview, text.noOverview)} -

+ {facts.length > 0 &&

{facts.join(" · ")}

} +
+ +
+

+ {textOr(collection.overview, text.noOverview)} +

+
- - + + {parts.length ? ( +
    + {parts.map((part, index) => { + const upcoming = !part.release_date; + return ( +
  1. + {/* A posição já é anunciada pela lista ordenada ("1 de 27"). */} + + + {upcoming && ( + + )} +
  2. + ); + })} +
+ ) : ( + + {text.discover} + + } + /> + )}