diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index cab5118..7ea2436 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -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. diff --git a/e2e/tests/watchlist-page.spec.ts b/e2e/tests/watchlist-page.spec.ts new file mode 100644 index 0000000..b0e9a4b --- /dev/null +++ b/e2e/tests/watchlist-page.spec.ts @@ -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 { + 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"); + }); +}); diff --git a/e2e/tests/watchlist.spec.ts b/e2e/tests/watchlist.spec.ts index 5b666eb..fc2bdb6 100644 --- a/e2e/tests/watchlist.spec.ts +++ b/e2e/tests/watchlist.spec.ts @@ -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", @@ -70,7 +70,7 @@ 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"); @@ -78,7 +78,7 @@ test.describe("Minha lista", () => { 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(); @@ -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(); }); diff --git a/src/hooks/useWatchlist.ts b/src/hooks/useWatchlist.ts index 8db5964..b10e73b 100644 --- a/src/hooks/useWatchlist.ts +++ b/src/hooks/useWatchlist.ts @@ -2,6 +2,8 @@ import { useCallback, useSyncExternalStore } from "react"; import { isInWatchlist, parseWatchlist, + reinsertWatchlistItem, + removeWatchlistItem, toggleWatchlistItem, WATCHLIST_STORAGE_KEY, type WatchlistItem, @@ -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 { @@ -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 }; } diff --git a/src/i18n/pt-BR.ts b/src/i18n/pt-BR.ts index 77c1052..8e0746f 100644 --- a/src/i18n/pt-BR.ts +++ b/src/i18n/pt-BR.ts @@ -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.", diff --git a/src/lib/watchlist.test.ts b/src/lib/watchlist.test.ts index 5d3349c..2d17ded 100644 --- a/src/lib/watchlist.test.ts +++ b/src/lib/watchlist.test.ts @@ -5,6 +5,12 @@ import { toggleWatchlistItem, WATCHLIST_MAX_ITEMS, type WatchlistItem, + countWatchlist, + filterWatchlist, + isWatchlistSort, + reinsertWatchlistItem, + removeWatchlistItem, + sortWatchlist, } from "./watchlist"; const item = (overrides: Partial = {}): WatchlistItem => ({ @@ -71,3 +77,107 @@ describe("toggleWatchlistItem", () => { expect(isInWatchlist(saved, "movie", 6)).toBe(false); }); }); + +describe("visão da lista (D-67)", () => { + const item = (overrides: Partial & Pick): WatchlistItem => ({ + mediaType: "movie", + title: `Título ${String(overrides.id)}`, + posterPath: null, + date: "", + voteAverage: null, + addedAt: 0, + ...overrides, + }); + const ids = (list: readonly WatchlistItem[]) => list.map((entry) => entry.id); + + const amelie = item({ + id: 2, + title: "amélie", + mediaType: "tv", + date: "", + voteAverage: 8.1, + addedAt: 400, + }); + const list = [ + item({ id: 1, title: "Zodíaco", date: "2007-03-02", voteAverage: 7.5, addedAt: 500 }), + amelie, + item({ id: 3, title: "Ágora", date: "2009-10-09", voteAverage: null, addedAt: 300 }), + item({ + id: 4, + title: "Brasil 2", + mediaType: "tv", + date: "2009-10-09", + voteAverage: 7.5, + addedAt: 200, + }), + item({ id: 5, title: "Brasil 10", date: "", voteAverage: null, addedAt: 100 }), + ]; + + it("filtra por tipo e conta cada um", () => { + expect(ids(filterWatchlist(list, "all"))).toEqual([1, 2, 3, 4, 5]); + expect(ids(filterWatchlist(list, "tv"))).toEqual([2, 4]); + expect(ids(filterWatchlist(list, "movie"))).toEqual([1, 3, 5]); + expect(countWatchlist(list)).toEqual({ all: 5, movie: 3, tv: 2 }); + expect(countWatchlist([])).toEqual({ all: 0, movie: 0, tv: 0 }); + }); + + it("ordena por mais recentes e mais antigos pelo momento em que foi salvo", () => { + expect(ids(sortWatchlist(list, "recent"))).toEqual([1, 2, 3, 4, 5]); + expect(ids(sortWatchlist(list, "oldest"))).toEqual([5, 4, 3, 2, 1]); + }); + + it("ordena por título sem diferenciar acentos e maiúsculas, com números naturais", () => { + expect(ids(sortWatchlist(list, "title"))).toEqual([3, 2, 4, 5, 1]); + }); + + it("melhor avaliados primeiro; sem nota por último; empate pelo título", () => { + expect(ids(sortWatchlist(list, "rating"))).toEqual([2, 4, 1, 3, 5]); + }); + + it("lançamento mais recente primeiro; sem data por último; empate pelo título", () => { + expect(ids(sortWatchlist(list, "release"))).toEqual([3, 4, 1, 2, 5]); + }); + + it("não altera a lista original e combina com o filtro", () => { + const before = ids(list); + expect(ids(sortWatchlist(filterWatchlist(list, "tv"), "title"))).toEqual([2, 4]); + expect(ids(list)).toEqual(before); + }); + + it("aceita só ordenações conhecidas", () => { + expect(isWatchlistSort("rating")).toBe(true); + expect(isWatchlistSort("popularity")).toBe(false); + expect(isWatchlistSort(null)).toBe(false); + }); + + it("remove e devolve o item na mesma posição, mesmo após outras remoções", () => { + const first = removeWatchlistItem(list, "tv", 2); + expect(first.index).toBe(1); + const second = removeWatchlistItem(first.items, "movie", 3); + // Desfazer a primeira remoção não traz de volta a segunda. + const undone = reinsertWatchlistItem(second.items, amelie, first.index); + expect(ids(undone)).toEqual([1, 2, 4, 5]); + // Desfazer duas vezes não duplica. + expect(ids(reinsertWatchlistItem(undone, amelie, first.index))).toEqual([1, 2, 4, 5]); + }); + + it("desfazer depois de remover um título anterior devolve a ordem original (E2E de D-67)", () => { + const first = removeWatchlistItem(list, "movie", 3); // posição 2 + const second = removeWatchlistItem(first.items, "tv", 2); // posição 1 + const undone = reinsertWatchlistItem(second.items, list[2] ?? amelie, first.index); + expect(ids(undone)).toEqual([1, 3, 4, 5]); + }); + + it("sem a data de inclusão (itens antigos), usa a posição de origem", () => { + const legacy = list.map((entry) => ({ ...entry, addedAt: 0 })); + const removed = removeWatchlistItem(legacy, "movie", 3); + const restoredItem = legacy[2] ?? amelie; + expect(ids(reinsertWatchlistItem(removed.items, restoredItem, removed.index))).toEqual([ + 1, 2, 3, 4, 5, + ]); + }); + + it("remover algo que não está na lista não muda nada", () => { + expect(removeWatchlistItem(list, "movie", 999)).toEqual({ items: list, index: -1 }); + }); +}); diff --git a/src/lib/watchlist.ts b/src/lib/watchlist.ts index f24334d..89fc28a 100644 --- a/src/lib/watchlist.ts +++ b/src/lib/watchlist.ts @@ -89,3 +89,104 @@ export function toggleWatchlistItem( } return [item, ...items].slice(0, WATCHLIST_MAX_ITEMS); } + +/** Recorte por tipo na página da lista (D-67). */ +export type WatchlistMedia = "all" | MediaType; + +/** Ordenações da página da lista (D-67). "recent" é a ordem em que os itens são guardados. */ +export const WATCHLIST_SORTS = ["recent", "oldest", "title", "rating", "release"] as const; +export type WatchlistSort = (typeof WATCHLIST_SORTS)[number]; + +export function isWatchlistSort(value: string | null | undefined): value is WatchlistSort { + return (WATCHLIST_SORTS as readonly string[]).includes(value ?? ""); +} + +export function filterWatchlist( + items: readonly WatchlistItem[], + media: WatchlistMedia, +): WatchlistItem[] { + return media === "all" ? [...items] : items.filter((item) => item.mediaType === media); +} + +export function countWatchlist(items: readonly WatchlistItem[]): Record { + const movie = items.filter((item) => item.mediaType === "movie").length; + return { all: items.length, movie, tv: items.length - movie }; +} + +const byTitle = new Intl.Collator("pt-BR", { sensitivity: "base", numeric: true }); + +/** + * Ordena sem alterar a lista guardada. Itens sem nota ou sem data ficam por último nas + * ordenações que dependem delas; empates caem no título e, por fim, na posição original, + * para a ordem ser sempre a mesma. + */ +export function sortWatchlist( + items: readonly WatchlistItem[], + sort: WatchlistSort, +): WatchlistItem[] { + const indexed = items.map((item, index) => ({ item, index })); + const tie = (a: (typeof indexed)[number], b: (typeof indexed)[number]) => + byTitle.compare(a.item.title, b.item.title) || a.index - b.index; + + indexed.sort((a, b) => { + switch (sort) { + case "recent": + return b.item.addedAt - a.item.addedAt || a.index - b.index; + case "oldest": + return a.item.addedAt - b.item.addedAt || b.index - a.index; + case "title": + return tie(a, b); + case "rating": { + const ra = a.item.voteAverage; + const rb = b.item.voteAverage; + if (ra === null || rb === null) return ra === rb ? tie(a, b) : ra === null ? 1 : -1; + return rb - ra || tie(a, b); + } + case "release": { + const da = a.item.date; + const db = b.item.date; + if (!da || !db) return da === db ? tie(a, b) : da ? -1 : 1; + return db.localeCompare(da) || tie(a, b); + } + } + }); + return indexed.map(({ item }) => item); +} + +/** Remove um item, devolvendo também a posição dele, para o "Desfazer" (D-67). */ +export function removeWatchlistItem( + items: readonly WatchlistItem[], + mediaType: MediaType, + id: number, +): { items: WatchlistItem[]; index: number } { + const index = items.findIndex((entry) => entry.mediaType === mediaType && entry.id === id); + if (index === -1) return { items: [...items], index }; + return { items: [...items.slice(0, index), ...items.slice(index + 1)], index }; +} + +/** + * Desfaz uma remoção: devolve só aquele item, no lugar em que estava. Outras remoções + * ou inclusões feitas depois continuam valendo (restaurar uma cópia da lista inteira as + * desfaria também). Se o item já voltou à lista, nada muda. + */ +export function reinsertWatchlistItem( + items: readonly WatchlistItem[], + item: WatchlistItem, + index: number, +): WatchlistItem[] { + if (isInWatchlist(items, item.mediaType, item.id)) return [...items]; + // A lista fica do mais recente ao mais antigo: o lugar certo é antes do primeiro item + // salvo antes dele. A posição numérica de origem pode ter mudado com outras remoções, + // então só vale para itens antigos, guardados sem a data de inclusão. + const byDate = item.addedAt > 0 ? items.findIndex((entry) => entry.addedAt < item.addedAt) : -2; + const position = + byDate === -2 + ? Math.min(Math.max(index, 0), items.length) + : byDate === -1 + ? items.length + : byDate; + return [...items.slice(0, position), item, ...items.slice(position)].slice( + 0, + WATCHLIST_MAX_ITEMS, + ); +} diff --git a/src/pages/Watchlist.css b/src/pages/Watchlist.css index 911696e..821dfb5 100644 --- a/src/pages/Watchlist.css +++ b/src/pages/Watchlist.css @@ -1,15 +1,146 @@ @layer pages { - .watchlist__toolbar { + /* Minha lista (D-67): a coleção pessoal, com o total em destaque no dourado da marca. */ + .watchlist__summary { display: flex; + flex-wrap: wrap; align-items: center; justify-content: space-between; + gap: var(--space-2) var(--space-4); + margin-top: var(--space-2); + } + + .watchlist__total { + display: flex; + align-items: baseline; + gap: var(--space-2); + } + + .watchlist__total-number { + font-size: var(--text-numeral-lg); + font-variant-numeric: lining-nums tabular-nums; + line-height: var(--leading-numeral); + color: var(--color-accent-default); + } + + @supports (background-clip: text) { + .watchlist__total-number { + background: var(--gradient-accent-text); + background-clip: text; + color: transparent; + } + } + + .watchlist__total-label { + color: var(--color-text-secondary); + font-size: var(--text-sm); + } + + /* Filtro, ordenação e limpar numa barra separada da grade por um filete. */ + .watchlist__toolbar { + display: flex; + flex-wrap: wrap; + align-items: flex-end; gap: var(--space-4); margin-bottom: var(--space-5); - padding-bottom: var(--space-3); - border-bottom: var(--border-width) solid var(--color-border); + padding-bottom: var(--space-4); + background: var(--rule-fade) bottom left / 100% var(--border-width) no-repeat; + } + + .watchlist__filter-count { + padding: 1px 6px; + border-radius: var(--radius-full); + color: var(--color-text-secondary); + background: var(--color-surface-raised); + font-size: var(--text-xs); + font-variant-numeric: tabular-nums; + } + + .chip[aria-pressed="true"] .watchlist__filter-count { + color: var(--color-accent-default); + background: var(--color-accent-on); + } + + .watchlist__sort { + display: grid; + flex: 1 1 12rem; + gap: var(--space-2); + max-width: 280px; } - .watchlist__count { - color: var(--color-text-tertiary); + .watchlist__clear { + padding-inline: var(--space-2); + } + + /* Remover fica sobre o canto do card, fora do link (um botão não pode ficar dentro dele). */ + .watchlist__item { + position: relative; + } + + .watchlist__remove.icon-btn { + position: absolute; + top: var(--space-2); + right: var(--space-2); + z-index: 1; + color: var(--color-text-primary); + background: var(--color-badge-bg); + backdrop-filter: var(--glass-filter); + } + + .watchlist__remove.icon-btn:hover { + border-color: var(--color-danger-border); + color: var(--color-danger); + background: var(--color-badge-bg); + } + + /* Lista vazia: composição aberta, sem caixa, com os dois caminhos de descoberta. */ + .watchlist-empty { + display: grid; + justify-items: start; + gap: var(--space-3); + max-width: 36rem; + padding-block: var(--space-6) var(--space-7); + background: var(--rule-fade) top left / 100% var(--border-width) no-repeat; + } + + .watchlist-empty__mark { + display: grid; + width: 56px; + height: 56px; + place-items: center; + margin-bottom: var(--space-2); + border-radius: var(--radius-round); + color: var(--color-accent-default); + background: var(--color-accent-subtle); + box-shadow: inset 0 0 0 var(--border-width) rgb(var(--rgb-gold) / 35%); + font-size: var(--icon-lg); + } + + .watchlist-empty__title { + font-size: var(--text-2xl); + } + + .watchlist-empty__message { + color: var(--color-text-secondary); + } + + .watchlist-empty__actions { + display: flex; + flex-wrap: wrap; + gap: var(--space-3); + margin-top: var(--space-2); + } + + /* No celular: filtro na largura toda e ordenação com o rótulo ao lado, numa linha só. */ + @media (max-width: 599px) { + .watchlist__toolbar { + gap: var(--space-3); + } + + .watchlist__sort { + grid-template-columns: auto minmax(0, 1fr); + align-items: center; + max-width: none; + flex-basis: 100%; + } } } diff --git a/src/pages/Watchlist.tsx b/src/pages/Watchlist.tsx index a45f615..d84e28b 100644 --- a/src/pages/Watchlist.tsx +++ b/src/pages/Watchlist.tsx @@ -1,71 +1,269 @@ -import { useState } from "react"; -import { Link } from "react-router"; -import { PiTrash } from "react-icons/pi"; -import { messages, plural } from "../i18n"; +import { useEffect, useRef, useState } from "react"; +import { Link, useSearchParams } from "react-router"; +import { PiBookmarkSimple, PiTrash, PiX } from "react-icons/pi"; +import { interpolate, locale, messages, plural } from "../i18n"; import { useDocumentTitle } from "../hooks/useDocumentTitle"; import { useWatchlist } from "../hooks/useWatchlist"; +import { showToast } from "../lib/toast"; +import { + countWatchlist, + filterWatchlist, + isWatchlistSort, + sortWatchlist, + watchlistKey, + WATCHLIST_SORTS, + type WatchlistItem, + type WatchlistMedia, + type WatchlistSort, +} from "../lib/watchlist"; import type { MovieSummary } from "../types/tmdb"; -import PosterGrid from "../components/movie/PosterGrid"; +import PosterCard from "../components/movie/PosterCard"; import Dialog from "../components/ui/Dialog"; +import StateMessage from "../components/ui/StateMessage"; import "./Watchlist.css"; const text = messages.watchlist; -/** Filmes e séries salvos neste navegador, do mais recente ao mais antigo. */ +/** Filtro e ordem ficam na URL, como em Descobrir: sobrevivem ao recarregar e ao voltar. */ +const MEDIA_PARAM: Record, string> = { + movie: "filmes", + tv: "series", +}; +const SORT_PARAM: Record = { + recent: "", + oldest: "antigos", + title: "titulo", + rating: "nota", + release: "lancamento", +}; + +function readMedia(value: string | null): WatchlistMedia { + if (value === MEDIA_PARAM.movie) return "movie"; + if (value === MEDIA_PARAM.tv) return "tv"; + return "all"; +} + +function readSort(value: string | null): WatchlistSort { + return WATCHLIST_SORTS.find((sort) => SORT_PARAM[sort] === value) ?? "recent"; +} + +const MEDIA_OPTIONS: readonly { value: WatchlistMedia; label: string }[] = [ + { value: "all", label: text.filterAll }, + { value: "movie", label: text.filterMovies }, + { value: "tv", label: text.filterSeries }, +]; + +const toCard = (item: WatchlistItem): MovieSummary => ({ + id: item.id, + title: item.title, + poster_path: item.posterPath, + ...(item.date ? { release_date: item.date } : {}), + ...(item.voteAverage !== null ? { vote_average: item.voteAverage } : {}), + media_type: item.mediaType, +}); + +/** + * Filmes e séries salvos neste navegador (D-67): filtro por tipo, ordenação e remoção de + * cada título, com "Desfazer". O que fica guardado não muda de formato. + */ const Watchlist = () => { - const { items, clear } = useWatchlist(); + const { items, clear, remove, reinsert } = useWatchlist(); + const [searchParams, setSearchParams] = useSearchParams(); const [confirming, setConfirming] = useState(false); + // Depois de remover, o foco vai para o título vizinho (ou para o filtro, se a lista + // esvaziou), para quem usa teclado não ser jogado para o topo da página. + const pendingFocus = useRef(null); useDocumentTitle(text.title); - const cards: MovieSummary[] = items.map((item) => ({ - id: item.id, - title: item.title, - poster_path: item.posterPath, - ...(item.date ? { release_date: item.date } : {}), - ...(item.voteAverage !== null ? { vote_average: item.voteAverage } : {}), - media_type: item.mediaType, - })); + const media = readMedia(searchParams.get("tipo")); + const sort = readSort(searchParams.get("ordem")); + const counts = countWatchlist(items); + const visible = sortWatchlist(filterWatchlist(items, media), sort); + + useEffect(() => { + const key = pendingFocus.current; + if (key === null) return; + pendingFocus.current = null; + const target = + document.querySelector(`[data-watchlist-key="${key}"] a`) ?? + document.querySelector(".watchlist__filters [aria-pressed='true']") ?? + document.querySelector(".watchlist-empty__actions a"); + target?.focus(); + }, [items]); + + const update = (next: { media?: WatchlistMedia; sort?: WatchlistSort }) => { + const params = new URLSearchParams(); + const nextMedia = next.media ?? media; + const nextSort = next.sort ?? sort; + if (nextMedia !== "all") params.set("tipo", MEDIA_PARAM[nextMedia]); + if (SORT_PARAM[nextSort]) params.set("ordem", SORT_PARAM[nextSort]); + setSearchParams(params, { replace: true }); + }; + + const removeItem = (item: WatchlistItem, position: number) => { + const neighbor = visible[position + 1] ?? visible[position - 1]; + pendingFocus.current = neighbor ? watchlistKey(neighbor.mediaType, neighbor.id) : ""; + const removed = remove(item.mediaType, item.id); + if (!removed) { + pendingFocus.current = null; + return; + } + showToast(interpolate(text.removed, { title: item.title }), { + action: { + label: messages.toast.undo, + onAction: () => { + reinsert(removed.item, removed.index); + }, + }, + }); + }; + + const emptyFilterTitle = media === "tv" ? text.emptySeries : text.emptyMovies; return (
-
+

{text.kicker}

{text.heading}

{text.lede}

+ {items.length > 0 && ( +
+

+ + {visible.length.toLocaleString(locale)} + {" "} + + {plural(text.savedLabel, visible.length)} + +

+ +
+ )}
- {items.length > 0 && ( -
-

- {plural(text.count, items.length)} -

- -
- )} + {items.length > 0 ? ( + <> +
+
    + {MEDIA_OPTIONS.map(({ value, label }) => ( +
  • + +
  • + ))} +
+ +
+ + +
+
+ + {/* Título da seção para leitores de tela: os cards usam h3 (D-67). */} +

{text.listLabel}

- undefined} - emptyTitle={text.emptyTitle} - emptyMessage={text.emptyMessage} - emptyAction={ - - {text.emptyAction} - - } - /> + {visible.length > 0 ? ( +
    + {visible.map((item, index) => { + const key = watchlistKey(item.mediaType, item.id); + return ( +
  • + + +
  • + ); + })} +
+ ) : ( + { + update({ media: "all" }); + }} + > + {text.emptyFilterAction} + + } + /> + )} + + ) : ( +
+ +

+ {text.emptyTitle} +

+

{text.emptyMessage}

+
+ + {text.emptyAction} + + + {text.emptyActionSeries} + +
+
+ )}