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
64 changes: 64 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
name: CI

on:
push:
branches: [main]
pull_request:

# Dorongan baru ke cabang yang sama membatalkan jalan sebelumnya: hasil dari
# commit yang sudah tertimpa tidak ada gunanya ditunggu.
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

jobs:
verify:
name: Typecheck, lint, build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7

- uses: actions/setup-node@v7
with:
node-version: 22
cache: npm

- run: npm ci

# Nilai NEXT_PUBLIC_ ditanam saat build. Tanpa berkas ini build tetap
# berhasil tapi menghasilkan URL kosong, dan aplikasinya gagal senyap.
# Menyalin dari .env.example sekaligus menjaga berkas itu tetap sahih.
- run: cp .env.example .env.local

- run: npm run typecheck
- run: npm run lint
- run: npm run build

e2e:
name: End-to-end
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7

- uses: actions/setup-node@v7
with:
node-version: 22
cache: npm

- run: npm ci
- run: cp .env.example .env.local

- run: npx playwright install --with-deps chromium

# Hanya satu peramban di CI, bukan keenamnya. Test menembak PokeAPI
# sungguhan, dan enam kali beban itu dari alamat CI bersama mengundang
# kegagalan yang tidak ada hubungannya dengan perubahan kodenya.
# Cakupan lintas perangkat tetap dijalankan penuh di mesin lokal.
- run: npx playwright test --project=desktop-chrome

- if: failure()
uses: actions/upload-artifact@v7
with:
name: playwright-report
path: test-results/
retention-days: 7
99 changes: 79 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,36 +1,95 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
# PokeCatch

## Getting Started
A small browser game built on [PokeAPI](https://pokeapi.co): browse the Pokédex, throw a Pokéball, name what you catch, and keep a collection.

First, run the development server:
There is no backend and no account. The collection lives in the browser's `localStorage`, so it stays on the device that caught them.

## Features

- **Browse and search** every Pokémon in the API, not only the ones already loaded, with a filter for all 18 types.
- **Detail pages** with base stats, types, abilities, moves, the Pokédex entry, the evolution chain, and the Pokémon's cry.
- **Catch odds that follow the games.** Each species' `capture_rate` is mapped onto a 10–90% band, so a legendary really is harder to catch than a Caterpie, and a chip tells you which one you are facing.
- **Shiny encounters** at the usual 1/64, rolled once per visit to a detail page.
- **Collection management**: nickname on capture, release, and export or import the whole collection as JSON.

## Requirements

Node.js 20 or newer. 18.18+ also works; CI runs on 22.

## Getting started

```bash
npm install
cp .env.example .env.local
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```

Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
Then open <http://localhost:3000>.

### Environment variables

Both are required:

```
NEXT_PUBLIC_POKEMON_API_URL=https://pokeapi.co/api/v2/pokemon
NEXT_PUBLIC_POKEMON_IMAGE_URL=https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon
```

Two things are worth knowing about them:

You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
- They are **inlined at build time**, so changing `.env.local` means restarting the dev server or rebuilding.
- If they are missing, **nothing errors**. Requests fall back to a relative URL, the app receives its own HTML in reply, and the Pokémon list simply comes up empty. Every other endpoint the app uses is derived from these two, so there is nothing else to configure.

This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Scripts

## Learn More
| Command | What it does |
| --- | --- |
| `npm run dev` | Development server |
| `npm run build` | Production build |
| `npm start` | Serve the production build |
| `npm run lint` | ESLint |
| `npm run typecheck` | TypeScript, without emitting |
| `npm run test:e2e` | Playwright end-to-end tests |
| `npm run test:review` | Screenshot every route on every device, for review by eye |

## Testing

The Playwright suite runs against **the real PokeAPI**, not fixtures, so a broken environment or a changed response shape fails the tests instead of hiding behind a mock. It covers six targets — Chrome, Firefox, and Safari on desktop, plus iPad Pro 11, Pixel 5, and iPhone 12 — and includes a guard that fails if a page grows wider than the viewport or serves a broken image.

The suite uses port 3100 and always starts its own server, so it never attaches to whatever happens to be running on port 3000.

```bash
npm run test:e2e
npx playwright test --grep "stat bar" # one scenario
npx playwright test --ui # interactive
```

## Project structure

```
src/
app/ routes only — each one delegates to a page component
components/
pages/ one component per route, where the composition lives
ui/ shared pixel-art building blocks
hooks/ data fetching and state
services/ the only place that talks to PokeAPI
helpers/ the localStorage collection, import and export
context/ browse results and capture counts, shared app-wide
configs/ endpoints and site metadata, all derived from the two env vars
utils/ pure functions
types/ PokeAPI response shapes
styles/ design tokens as CSS custom properties
```

To learn more about Next.js, take a look at the following resources:
Data flows one way: **services → hooks → components**. Services throw, hooks turn failures into toasts, and components only render what a hook hands them.

- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
## Tech

You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
Next.js 15 (App Router) · React 18 · TypeScript · CSS Modules · axios · Playwright

## Deploy on Vercel
Styling is plain CSS Modules over custom properties — no utility framework, no CSS-in-JS. The pixel-art borders are an SVG data URI applied through `border-image`.

The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
## License

Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
[MIT](LICENSE) © 2024 wahidrizka
122 changes: 122 additions & 0 deletions e2e/pokecatch.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -411,3 +411,125 @@ test("a branching evolution chain lists every branch side by side", async ({ pag
await expect(page.getByText("→", { exact: true })).toHaveCount(1);
await expect(page.locator('a[href="/pokemon/sylveon"]')).toBeVisible();
});

/*
* Semua isi halaman diambil di peramban, jadi yang diuji di sini adalah bagian
* yang justru tidak dilihat pengguna: apa yang diterima perayap dan pratinjau
* tautan sebelum satu baris JavaScript pun berjalan.
*/
test("a pokemon page ships its own crawlable metadata", async ({ page }) => {
const response = await page.goto("/pokemon/pikachu");
expect(response?.status()).toBe(200);

const origin = new URL(page.url()).origin;
const isi = (pemilih: string) =>
page.locator(pemilih).getAttribute("content");

await expect(page).toHaveTitle("Pikachu | PokeCatch");
expect(await isi('meta[property="og:title"]')).toBe("Pikachu");
// Artwork resmi, bukan sprite 96x96 yang terlalu kecil untuk pratinjau.
const gambar = await isi('meta[property="og:image"]');
expect(gambar).toContain("official-artwork/25.png");
// Tautannya harus benar-benar hidup: pratinjau yang menunjuk gambar 404
// terlihat sama saja dengan tidak punya gambar sama sekali.
expect((await page.request.get(gambar!)).status()).toBe(200);
// og:url yang relatif tidak sah menurut spesifikasi Open Graph.
expect(await isi('meta[property="og:url"]')).toBe(
`${origin}/pokemon/pikachu`
);
expect(
await page.locator('link[rel="canonical"]').getAttribute("href")
).toBe(`${origin}/pokemon/pikachu`);
// Deskripsi berasal dari /pokemon-species, bukan teks umum situs.
expect(await isi('meta[name="description"]')).toContain("Mouse Pokémon");
});

test("an unknown pokemon name answers 404 instead of an empty page", async ({
page,
}) => {
const response = await page.goto("/pokemon/bukan-pokemon-asli");

expect(response?.status()).toBe(404);
await expect(page.getByRole("heading", { name: "404" })).toBeVisible();
await expect(page.getByRole("link", { name: /explore/i })).toBeVisible();
});

test("responses carry the security headers", async ({ page }) => {
const response = await page.goto("/pokemons");
const headers = response!.headers();

expect(headers["x-frame-options"]).toBe("DENY");
expect(headers["x-content-type-options"]).toBe("nosniff");
expect(headers["referrer-policy"]).toBe("strict-origin-when-cross-origin");
expect(headers["strict-transport-security"]).toContain("max-age=");
expect(headers["permissions-policy"]).toContain("camera=()");

const csp = headers["content-security-policy"];
expect(csp).toContain("frame-ancestors 'none'");
expect(csp).toContain("object-src 'none'");
// Font di-host sendiri sejak pindah ke next/font; tidak boleh ada jalan balik
// ke Google Fonts, karena pertukaran fontnya yang dulu merusak CLS.
expect(csp).not.toContain("fonts.googleapis.com");
expect(csp).not.toContain("fonts.gstatic.com");
});

test("the policy really blocks a foreign origin", async ({ page }) => {
await page.goto("/pokemons");

// Tanpa pemeriksaan ini, test header di atas hanya membuktikan teksnya ada,
// bukan bahwa peramban benar-benar menegakkannya.
//
// Sinyalnya harus securitypolicyviolation, bukan fetch yang gagal: fetch
// lintas-origin juga ditolak CORS, sehingga versi itu lulus bahkan ketika
// seluruh header dicabut. Sudah terbukti begitu saat diuji.
const pelanggaran = await page.evaluate(async () => {
const tercatat: string[] = [];
document.addEventListener("securitypolicyviolation", (event) => {
tercatat.push((event as SecurityPolicyViolationEvent).violatedDirective);
});

const script = document.createElement("script");
script.src = "https://cdn.jsdelivr.net/npm/tidak-ada.js";
document.body.appendChild(script);
await new Promise((resolve) => setTimeout(resolve, 1_000));

return tercatat;
});

expect(pelanggaran.join(",")).toContain("script-src");
});

test("sitemap and robots point at absolute urls", async ({
request,
baseURL,
}) => {
const robots = await request.get("/robots.txt");
expect(robots.status()).toBe(200);
const aturan = await robots.text();
expect(aturan).toContain("Disallow: /my-pokemon");
expect(aturan).toContain(`${baseURL}/sitemap.xml`);

const sitemap = await request.get("/sitemap.xml", { timeout: 45_000 });
expect(sitemap.status()).toBe(200);
const xml = await sitemap.text();
expect(xml).toContain(`<loc>${baseURL}/pokemon/pikachu</loc>`);
// Koleksi hanya ada di localStorage tiap peramban, jadi tidak ada yang bisa
// diindeks dari sana.
expect(xml).not.toContain("/my-pokemon");
});

test("a pokemon without official artwork still shares a live image", async ({
page,
}) => {
// mimikyu-busted punya sprite tapi tidak punya artwork resmi. Menyusun URL
// artwork dari pola id — seperti versi pertama fitur ini — menerbitkan
// pratinjau yang menunjuk gambar 404 untuk bentuk semacam ini.
await page.goto("/pokemon/mimikyu-busted");

const gambar = await page
.locator('meta[property="og:image"]')
.getAttribute("content");

expect(gambar).not.toContain("official-artwork");
expect((await page.request.get(gambar!)).status()).toBe(200);
});
47 changes: 46 additions & 1 deletion next.config.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,52 @@
import type { NextConfig } from "next";

const isDevelopment = process.env.NODE_ENV === "development";

/*
* Daftar origin diturunkan dari pengamatan lalu lintas nyata keempat rute,
* bukan dugaan: yang benar-benar dimuat halaman hanyalah dirinya sendiri,
* PokeAPI (xhr), serta repo PokeAPI di raw.githubusercontent.com — yang
* memasok gambar sekaligus suara Pokemon. Font ikut di-host sendiri, jadi
* tidak ada satu pun origin pihak ketiga yang boleh memuat kode atau gaya.
*
* 'unsafe-inline' pada script-src tidak terhindarkan tanpa nonce, dan nonce
* menuntut middleware yang membuat setiap rute dirender dinamis. Untuk aplikasi
* tanpa auth dan tanpa data pengguna di server, harganya lebih besar dari
* manfaatnya. 'unsafe-eval' dan ws: hanya di dev, tempat HMR membutuhkannya.
*/
const contentSecurityPolicy = [
"default-src 'self'",
`script-src 'self' 'unsafe-inline'${isDevelopment ? " 'unsafe-eval'" : ""}`,
"style-src 'self' 'unsafe-inline'",
"font-src 'self'",
// data: dipakai border-image SVG milik .pixelated-border
"img-src 'self' data: https://raw.githubusercontent.com",
"media-src 'self' https://raw.githubusercontent.com",
`connect-src 'self' https://pokeapi.co${isDevelopment ? " ws:" : ""}`,
"frame-ancestors 'none'",
"base-uri 'self'",
"form-action 'self'",
"object-src 'none'",
].join("; ");

const securityHeaders = [
{ key: "Content-Security-Policy", value: contentSecurityPolicy },
{ key: "X-Frame-Options", value: "DENY" },
{ key: "X-Content-Type-Options", value: "nosniff" },
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
{
key: "Permissions-Policy",
value: "camera=(), microphone=(), geolocation=(), browsing-topics=()",
},
// preload sengaja tidak dipakai: itu komitmen permanen yang sulit dibatalkan.
{
key: "Strict-Transport-Security",
value: "max-age=63072000; includeSubDomains",
},
];

const nextConfig: NextConfig = {
/* config options here */
headers: async () => [{ source: "/:path*", headers: securityHeaders }],
};

export default nextConfig;
4 changes: 4 additions & 0 deletions playwright.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,9 @@ export default defineConfig({
url: E2E_URL,
reuseExistingServer: false,
timeout: 120_000,
// SITE_URL membaca PORT untuk menyusun URL absolut di canonical, og:url,
// sitemap, dan robots. Tanpa ini semuanya menyebut :3000 sementara server
// melayani :3100, dan test metadata menguji alamat yang salah.
env: { PORT: String(E2E_PORT) },
},
});
23 changes: 23 additions & 0 deletions src/app/error.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
"use client";
import { Button, ErrorScreen } from "@/components";

/*
* error sengaja tidak diambil dari props: tidak ada layanan pemantauan untuk
* mengirimnya, dan menampilkannya ke pengguna tidak menolong siapa pun.
*/
export default function Error({ reset }: { error: Error; reset: () => void }) {
return (
<ErrorScreen
code="Oops"
title="A wild error appeared"
description="Something went wrong on the way here. Try again, or head back."
>
<Button as="button" onClick={reset}>
Try again
</Button>
<Button href="/" variant="light">
Home
</Button>
</ErrorScreen>
);
}
Loading