Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions docs/DECISIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -565,3 +565,14 @@ Cada decisão tem: contexto, decisão e consequência. As decisões D-01 a D-11
- **Esqueleto** com a mesma grade do cabeçalho final.
- **Correção da D-64:** a regra de alto contraste do ranking nunca tinha sido aplicada (o script de edição procurava o bloco com outra indentação e não verificava a troca). Agora ela vale para o ranking e para o monograma, com teste E2E. No Chromium o texto continuava legível, porque o navegador força a cor do texto, mas a regra não dependia disso.
- **Não alterado:** o carregamento da foto do perfil (decisão do proprietário) e a página `/pessoas`, que já estava consistente.

## D-67. Redesign: Minha lista (e a ausência de Perfil)

- **Perfil de usuário não existe:** não há rota, login, conta, sessão nem banco de dados. Por decisão do proprietário, nenhuma página de Perfil foi criada; contas e autenticação continuam no roadmap (I-19). O único perfil do site é o de pessoas (D-66).
- **Diagnóstico de Minha lista** (produção, 60 títulos reais da API, 3 títulos e lista vazia; 320 a 1440 px): sem rolagem horizontal, cortes ou erros. Os pontos: com itens, os títulos pulavam do `h1` para o `h3` dos cards (acessibilidade 98 no Lighthouse); a barra de contagem tinha a linha sólida anterior à D-64; a lista vazia só oferecia "Descobrir filmes"; e não havia filtro, ordenação nem remoção na própria lista.
- **Medição da lista preenchida:** o Lighthouse padrão abre o navegador limpo (lista vazia). Para medir com títulos, o Chromium é aberto com depuração remota, a lista é gravada no armazenamento do domínio e o Lighthouse roda nesse navegador com `--disable-storage-reset`.
- **Aprovado e feito:** total em destaque no gradiente da marca, com "Limpar lista" na mesma linha; filete esmaecido; `h2` para leitores de tela; lista vazia sem caixa, com "Descobrir filmes" e "Descobrir séries"; filtro Tudo/Filmes/Séries no controle segmentado, com a contagem de cada tipo (sempre do total); ordenação por mais recentes, mais antigos, título A–Z, melhor avaliados e lançamento (sem nota ou sem data por último; empate pelo título); remoção de cada título com botão de 44 px e "Desfazer". Filtro e ordem ficam na URL (`?tipo=series&ordem=titulo`), como em Descobrir. A exibição progressiva (B4) ficou adiada.
- **Sem mexer nos componentes compartilhados:** o card é um link inteiro, e um botão não pode ficar dentro dele; a lista monta a própria grade, com o mesmo `PosterCard`, e o botão de remover fica ao lado do link, sobre o canto. A chave de cada item passa a ser tipo + id (filme e série podem ter o mesmo id).
- **"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.
254 changes: 254 additions & 0 deletions e2e/tests/watchlist-page.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,254 @@
import type { Page } from "@playwright/test";
import { expect, expectNoHorizontalScroll, test } from "../helpers/test.ts";
import type { WatchlistItem } from "../../src/lib/watchlist.ts";

/** Página Minha lista: filtro, ordenação, remoção com "Desfazer" e estados vazios (D-67). */

const STORAGE_KEY = "cinelux:minha-lista:v1";

/** Salvos do mais recente (topo) ao mais antigo; dois sem nota e dois sem data. */
const SAVED: WatchlistItem[] = [
{
id: 550,
mediaType: "movie",
title: "Clube da Luta",
posterPath: "/a.jpg",
date: "1999-10-15",
voteAverage: 8.4,
addedAt: 600,
},
{
id: 1396,
mediaType: "tv",
title: "Breaking Bad",
posterPath: "/b.jpg",
date: "2008-01-20",
voteAverage: 8.9,
addedAt: 500,
},
{
id: 603,
mediaType: "movie",
title: "Matrix",
posterPath: "/c.jpg",
date: "1999-03-31",
voteAverage: null,
addedAt: 400,
},
{
id: 157336,
mediaType: "movie",
title: "Interestelar",
posterPath: "/d.jpg",
date: "",
voteAverage: 8.4,
addedAt: 300,
},
{
id: 1399,
mediaType: "tv",
title: "Game of Thrones",
posterPath: "/e.jpg",
date: "",
voteAverage: null,
addedAt: 200,
},
{
id: 27205,
mediaType: "movie",
title: "A Origem",
posterPath: "/f.jpg",
date: "2010-07-15",
voteAverage: 8.4,
addedAt: 100,
},
];

async function seed(page: Page, items: readonly WatchlistItem[]): Promise<void> {
await page.addInitScript(
([key, value]) => {
// Só na primeira carga: recarregar a página precisa mostrar o que a página gravou.
if (window.sessionStorage.getItem("seeded")) return;
window.sessionStorage.setItem("seeded", "1");
window.localStorage.setItem(key, value);
},
[STORAGE_KEY, JSON.stringify(items)] as const,
);
}

const FIGHT_CLUB = SAVED.slice(0, 1);

const grid = (page: Page) => page.getByRole("list", { name: "Títulos salvos" });
const titles = (page: Page) => grid(page).getByRole("heading", { level: 3 }).allTextContents();
const stored = (page: Page) =>
page.evaluate(
(key) =>
(JSON.parse(window.localStorage.getItem(key) ?? "[]") as { title: string }[]).map(
(i) => i.title,
),
STORAGE_KEY,
);

test.describe("Minha lista: filtro e ordenação", () => {
test("conta cada tipo, filtra e mantém o filtro na URL", async ({ page }) => {
await seed(page, SAVED);
await page.goto("/minha-lista");

const filters = page.getByRole("list", { name: "Filtrar por tipo" });
await expect(filters.getByRole("button", { name: "Tudo: 6" })).toHaveAttribute(
"aria-pressed",
"true",
);
await expect(filters.getByRole("button", { name: "Filmes: 4" })).toBeVisible();
await filters.getByRole("button", { name: "Séries: 2" }).click();

await expect(page).toHaveURL("/minha-lista?tipo=series");
await expect.poll(() => titles(page)).toEqual(["Breaking Bad", "Game of Thrones"]);
await expect(page.locator(".watchlist__total")).toHaveText("2 títulos salvos");
// As contagens dos botões são do total, não do filtro.
await expect(filters.getByRole("button", { name: "Filmes: 4" })).toBeVisible();
});

test("ordena, trata quem não tem nota ou data e combina com o filtro", async ({ page }) => {
await seed(page, SAVED);
await page.goto("/minha-lista");
const sort = page.getByLabel("Ordenar por");

await expect.poll(() => titles(page)).toEqual(SAVED.map((item) => item.title));

await sort.selectOption({ label: "Mais antigos" });
await expect.poll(() => titles(page)).toEqual(SAVED.map((item) => item.title).reverse());

await sort.selectOption({ label: "Título (A–Z)" });
await expect
.poll(() => titles(page))
.toEqual([
"A Origem",
"Breaking Bad",
"Clube da Luta",
"Game of Thrones",
"Interestelar",
"Matrix",
]);

// Sem nota por último; empate na nota resolvido pelo título.
await sort.selectOption({ label: "Melhor avaliados" });
await expect
.poll(() => titles(page))
.toEqual([
"Breaking Bad",
"A Origem",
"Clube da Luta",
"Interestelar",
"Game of Thrones",
"Matrix",
]);

// Sem data por último.
await sort.selectOption({ label: "Lançamento" });
await expect(page).toHaveURL("/minha-lista?ordem=lancamento");
await expect
.poll(() => titles(page))
.toEqual([
"A Origem",
"Breaking Bad",
"Clube da Luta",
"Matrix",
"Game of Thrones",
"Interestelar",
]);

// Filtro e ordem juntos, e os dois sobrevivem ao recarregar.
await page.getByRole("button", { name: "Filmes: 4" }).click();
await expect(page).toHaveURL("/minha-lista?tipo=filmes&ordem=lancamento");
await page.reload();
await expect
.poll(() => titles(page))
.toEqual(["A Origem", "Clube da Luta", "Matrix", "Interestelar"]);
await expect(sort).toHaveValue("release");
// A ordenação nunca muda o que fica guardado.
await expect.poll(() => stored(page)).toEqual(SAVED.map((item) => item.title));
});

test("filtro sem títulos mostra aviso e volta para Tudo", async ({ page }) => {
await seed(
page,
SAVED.filter((item) => item.mediaType === "movie"),
);
await page.goto("/minha-lista?tipo=series");
await expect(page.getByText("Nenhuma série na sua lista")).toBeVisible();
await page.getByRole("button", { name: "Ver todos os títulos" }).click();
await expect(page).toHaveURL("/minha-lista");
await expect(grid(page).getByRole("listitem")).toHaveCount(4);
});
});

test.describe("Minha lista: remoção", () => {
test("remove um título, guarda a mudança e o Desfazer devolve só ele, no lugar", async ({
page,
}) => {
await seed(page, SAVED);
await page.goto("/minha-lista");
const toasts = page.getByRole("region", { name: "Avisos" });

const removeMatrix = page.getByRole("button", { name: "Remover Matrix da lista" });
const box = await removeMatrix.boundingBox();
expect(box && box.width >= 44 && box.height >= 44).toBe(true);

await removeMatrix.click();
await expect.poll(() => titles(page)).not.toContain("Matrix");
await expect.poll(() => stored(page)).not.toContain("Matrix");
// O foco vai para o título vizinho, não para o topo da página.
await expect(grid(page).getByRole("link", { name: /Interestelar/ })).toBeFocused();

// Uma segunda remoção, e depois o Desfazer da primeira.
await page.getByRole("button", { name: "Remover Breaking Bad da lista" }).click();
await toasts
.getByRole("listitem")
.filter({ hasText: "Matrix saiu da sua lista" })
.getByRole("button", { name: "Desfazer" })
.click();

const expected = SAVED.map((item) => item.title).filter((title) => title !== "Breaking Bad");
await expect.poll(() => titles(page)).toEqual(expected);
await expect.poll(() => stored(page)).toEqual(expected);
await page.reload();
await expect.poll(() => titles(page)).toEqual(expected);
});

test("remover o último título leva à lista vazia, com os dois caminhos", async ({ page }) => {
await seed(page, FIGHT_CLUB);
await page.goto("/minha-lista");
await page.getByRole("button", { name: "Remover Clube da Luta da lista" }).click();

await expect(page.getByRole("heading", { name: "Sua lista está vazia" })).toBeVisible();
await expect(page.getByRole("link", { name: "Descobrir filmes" })).toBeFocused();
await expect(page.getByRole("link", { name: "Descobrir séries" })).toBeVisible();
await expect.poll(() => stored(page)).toEqual([]);
});
});

test.describe("Minha lista: muitos títulos e navegação", () => {
test("60 títulos sem rolagem lateral, e o card leva ao detalhe", async ({ page }) => {
const many: WatchlistItem[] = Array.from({ length: 60 }, (_, index) => ({
id: 990000 + index,
mediaType: index % 3 ? "movie" : "tv",
title: `Título salvo com um nome bem comprido ${String(index + 1)}`,
posterPath: null,
date: "",
voteAverage: null,
addedAt: 1000 - index,
}));
await seed(page, [...FIGHT_CLUB, ...many]);
await page.goto("/minha-lista");

await expect(grid(page).getByRole("listitem")).toHaveCount(61);
await expect(page.getByRole("button", { name: "Séries: 20" })).toBeVisible();
await expectNoHorizontalScroll(page);

await grid(page)
.getByRole("link", { name: /Clube da Luta/ })
.click();
await expect(page).toHaveURL("/movie/550");
});
});
11 changes: 8 additions & 3 deletions e2e/tests/watchlist.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ test.describe("Minha lista", () => {
await page.getByRole("banner").getByRole("link", { name: "Minha lista" }).click();
await expect(page).toHaveURL("/minha-lista");
await expect(page).toHaveTitle("Minha lista · Cinelux");
await expect(page.getByText("1 título", { exact: true })).toBeVisible();
await expect(page.locator(".watchlist__total")).toHaveText("1 título salvo");
const list = page.getByRole("list", { name: "Títulos salvos" });
await expect(list.getByRole("link", { name: /Clube da Luta/ })).toHaveAttribute(
"href",
Expand All @@ -70,15 +70,15 @@ test.describe("Minha lista", () => {
await page.goto("/serie/1396");
await page.getByRole("button", { name: "Salvar na lista" }).click();
await page.goto("/minha-lista");
await expect(page.getByText("2 títulos", { exact: true })).toBeVisible();
await expect(page.locator(".watchlist__total")).toHaveText("2 títulos salvos");
await expect(list.getByRole("listitem").first()).toContainText("Breaking Bad");
await expect(list.getByRole("listitem").first()).toContainText("Série");

// Remover pelo mesmo botão da página do título.
await page.goto("/serie/1396");
await page.getByRole("button", { name: "Na sua lista" }).click();
await page.goto("/minha-lista");
await expect(page.getByText("1 título", { exact: true })).toBeVisible();
await expect(page.locator(".watchlist__total")).toHaveText("1 título salvo");

// Limpar pede confirmação; cancelar mantém a lista.
await page.getByRole("button", { name: "Limpar lista" }).click();
Expand All @@ -93,6 +93,11 @@ test.describe("Minha lista", () => {
"href",
"/discover",
);
// A lista também guarda séries: a lista vazia oferece os dois caminhos (D-67).
await expect(page.getByRole("link", { name: "Descobrir séries" })).toHaveAttribute(
"href",
"/discover?tipo=series",
);
expect(await page.evaluate((key) => window.localStorage.getItem(key), STORAGE_KEY)).toBeNull();
});

Expand Down
20 changes: 19 additions & 1 deletion src/hooks/useWatchlist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { useCallback, useSyncExternalStore } from "react";
import {
isInWatchlist,
parseWatchlist,
reinsertWatchlistItem,
removeWatchlistItem,
toggleWatchlistItem,
WATCHLIST_STORAGE_KEY,
type WatchlistItem,
Expand Down Expand Up @@ -71,6 +73,10 @@ export interface Watchlist {
clear: () => void;
/** Volta a lista a um estado anterior (o "Desfazer" do aviso). */
restore: (items: readonly WatchlistItem[]) => void;
/** Remove um título; devolve o item e a posição dele, para o "Desfazer" (D-67). */
remove: (mediaType: MediaType, id: number) => { item: WatchlistItem; index: number } | null;
/** Devolve só aquele título, na posição em que estava (D-67). */
reinsert: (item: WatchlistItem, index: number) => void;
}

export function useWatchlist(): Watchlist {
Expand All @@ -91,5 +97,17 @@ export function useWatchlist(): Watchlist {
write(previous);
}, []);

return { items, has, toggle, clear, restore };
const remove = useCallback((mediaType: MediaType, id: number) => {
const current = getSnapshot();
const { items: next, index } = removeWatchlistItem(current, mediaType, id);
const item = current[index];
if (!item) return null;
write(next);
return { item, index };
}, []);
const reinsert = useCallback((item: WatchlistItem, index: number) => {
write(reinsertWatchlistItem(getSnapshot(), item, index));
}, []);

return { items, has, toggle, clear, restore, remove, reinsert };
}
20 changes: 20 additions & 0 deletions src/i18n/pt-BR.ts
Original file line number Diff line number Diff line change
Expand Up @@ -545,6 +545,26 @@ export const ptBR = {
emptyTitle: "Sua lista está vazia",
emptyMessage: 'Abra um filme ou uma série e toque em "Salvar na lista".',
emptyAction: "Descobrir filmes",
emptyActionSeries: "Descobrir séries",
filterLabel: "Filtrar por tipo",
filterAll: "Tudo",
filterMovies: "Filmes",
filterSeries: "Séries",
filterCount: "{category}: {count}",
sortLabel: "Ordenar por",
sorts: {
recent: "Mais recentes",
oldest: "Mais antigos",
title: "Título (A–Z)",
rating: "Melhor avaliados",
release: "Lançamento",
},
savedLabel: { one: "título salvo", other: "títulos salvos" },
remove: "Remover {title} da lista",
emptyMovies: "Nenhum filme na sua lista",
emptySeries: "Nenhuma série na sua lista",
emptyFilterMessage: "Os outros títulos salvos continuam em Tudo.",
emptyFilterAction: "Ver todos os títulos",
clear: "Limpar lista",
clearTitle: "Limpar a lista?",
clearDescription: "Os títulos salvos neste navegador serão removidos. Não é possível desfazer.",
Expand Down
Loading
Loading