diff --git a/.bun-version b/.bun-version new file mode 100644 index 00000000..d4c4950a --- /dev/null +++ b/.bun-version @@ -0,0 +1 @@ +1.3.9 diff --git a/.github/dependabot.yml b/.github/dependabot.yml index f49eed66..b6500529 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,6 +1,8 @@ version: 2 updates: - - package-ecosystem: 'npm' + # The lockfile is bun.lock, which the npm ecosystem can't update: its PRs changed package.json alone and + # failed `bun install --frozen-lockfile`. + - package-ecosystem: 'bun' directory: '/' schedule: interval: 'weekly' @@ -12,3 +14,14 @@ updates: applies-to: version-updates patterns: - '*' + # The workflows pin actions to commit SHAs, so something has to move those forward. + - package-ecosystem: 'github-actions' + directory: '/' + schedule: + interval: 'weekly' + assignees: + - 'bradp' + groups: + actions: + patterns: + - '*' diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index ac04fac3..7a22418b 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -18,7 +18,42 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 - name: Set up Bun uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + # One version everywhere, so a new Bun release can't change what the lockfile installs unannounced. + bun-version-file: .bun-version - name: Install dependencies run: bun install --frozen-lockfile - name: Check code quality run: bun run check + + browser: + name: Browser tests + runs-on: ubuntu-latest + timeout-minutes: 20 + env: + # Any value: the build signs its social card links with it, and the server the tests run against checks them. + OG_CARD_SECRET: for-the-browser-tests-only + + steps: + - name: Checkout code + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + - name: Set up Bun + uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + # One version everywhere, so a new Bun release can't change what the lockfile installs unannounced. + bun-version-file: .bun-version + - name: Install dependencies + run: bun install --frozen-lockfile + - name: Build the site + run: bun run build + - name: Install Chromium + run: bunx playwright install --with-deps chromium + - name: Run the browser and accessibility tests + run: bun run test:e2e + - name: Keep the traces of failed tests + if: failure() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: playwright-traces + path: test-results/ + retention-days: 7 diff --git a/.github/workflows/update-data.yml b/.github/workflows/update-data.yml index 6994609e..20d7d576 100644 --- a/.github/workflows/update-data.yml +++ b/.github/workflows/update-data.yml @@ -28,6 +28,9 @@ jobs: - name: Set up Bun uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + # One version everywhere, so a new Bun release can't change what the lockfile installs unannounced. + bun-version-file: .bun-version - name: Install dependencies run: bun install --frozen-lockfile --ignore-scripts @@ -35,11 +38,22 @@ jobs: - name: Update data run: bun run update:data + # The trap effects come from a community spreadsheet, not the API. If the sheet is down or reads + # wrong, the script exits without writing, and the rest of the update still goes out. + - name: Update trap effects + run: bun run update:trap-effects + continue-on-error: true + + # The push below goes straight to main, and a push made with GITHUB_TOKEN doesn't start the Code Quality + # workflow. So this is the only check the new data gets: the unit tests read it (links, names, catch rates). + - name: Check the new data + run: bun run test + - name: Commit changes run: | git config --local user.name "Mousebot" git config --local user.email "mousebot@mouse.rip" - git add src/data/generated + git add src/data/generated src/data/trap-effects.json if git diff --cached --quiet; then echo "No changes to commit" exit 0 diff --git a/.gitignore b/.gitignore index a4c00a15..c597b631 100644 --- a/.gitignore +++ b/.gitignore @@ -40,3 +40,7 @@ static-mouse-rip/ .open-next/ .wrangler/ scripts/tableau-out/ + +# Playwright +/test-results/ +/playwright-report/ diff --git a/README.md b/README.md index b64895cf..e4363bff 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,12 @@ When you're finished, run lint, formatting, and TypeScript checks: Use `bun run format` to apply formatting and `bun run build` to verify production page generation. +Mouse, item, group, location, and tool pages link to a social card that `/og/card` draws on request. The site signs those +links and the route only draws signed ones, so a production build needs `OG_CARD_SECRET` set to a long random string, +both when the pages are built and in the deployed Worker. An `.env.local` covers both when you deploy from your own +machine. Without it everything still works: those pages use the site-wide card, and `bun run dev` signs with a +stand-in key. + If you're happy with your changes, you can submit a Pull Request! ## 🗒️ Updating the content diff --git a/_redirects b/_redirects deleted file mode 100644 index 98d378e4..00000000 --- a/_redirects +++ /dev/null @@ -1 +0,0 @@ -/cre https://tsitu.github.io/MH-Tools/cre.html diff --git a/bun.lock b/bun.lock index 7ea7b3f0..b703fba8 100644 --- a/bun.lock +++ b/bun.lock @@ -9,26 +9,25 @@ "@heroicons/react": "^2.2.0", "@opennextjs/cloudflare": "^1.20.8", "clsx": "^2.1.1", - "framer-motion": "^12.38.0", - "next": "^16.4.3", + "next": "^16.4.6", "next-view-transitions": "^0.3.5", "postcss": "^8.5.10", "react": "^19.2.5", "react-dom": "^19.2.5", "react-markdown": "^10.1.0", - "react-virtualized-auto-sizer": "^1.0.26", - "react-window": "^1.8.11", "rehype-raw": "^7.0.0", "remark-gfm": "^4.0.1", "zod": "^3.25.76", }, "devDependencies": { + "@axe-core/playwright": "^4.14.1", "@clack/prompts": "^0.11.0", + "@playwright/test": "^1.65.1", "@tailwindcss/postcss": "^4.2.2", + "@types/bun": "^1.4.5", "@types/node": "^20.19.39", "@types/react": "^19.2.14", "@types/react-dom": "^19.2.3", - "@types/react-window": "^1.8.8", "oxfmt": "^0.62.0", "oxlint": "^1.76.0", "tailwindcss": "^4.2.2", @@ -156,7 +155,7 @@ "@aws/lambda-invoke-store": ["@aws/lambda-invoke-store@0.2.4", "", {}, "sha512-iY8yvjE0y651BixKNPgmv1WrQc+GZ142sb0z4gYnChDDY2YqI4P/jsSopBWrKfAt7LOJAkOXt7rC/hms+WclQQ=="], - "@babel/runtime": ["@babel/runtime@7.29.2", "", {}, "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g=="], + "@axe-core/playwright": ["@axe-core/playwright@4.14.1", "", { "dependencies": { "axe-core": "~4.14.1" }, "peerDependencies": { "playwright-core": ">= 1.0.0" } }, "sha512-cSN1ijrWLnlOof22sPN4RtWGSoPpt7GzOVyOKomyhnPsy1fPNoRdBiJAUziuCRs8KoK50kKufiMUFt7itAuwOg=="], "@clack/core": ["@clack/core@0.5.0", "", { "dependencies": { "picocolors": "^1.0.0", "sisteransi": "^1.0.5" } }, "sha512-p3y0FIOwaYRUPRcMO7+dlmLh8PSRcrjuTndsiA0WAFbWES0mLZlrjVoBRZ9DzkPFJZG6KGkJmoEAY0ZcVWTkow=="], @@ -328,23 +327,23 @@ "@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="], - "@next/env": ["@next/env@16.4.3", "", {}, "sha512-a7tz1QCcWWkwC/rPJcPMJk/UNRu9CFhDd3OHYE5hddbJrs8BqRTalxI6GlKCWEGzRLHN+S/B7a4PAHCtm25aBQ=="], + "@next/env": ["@next/env@16.4.6", "", {}, "sha512-SunBjJ6t+oBtecS3dTjdVuMhUogP5wD/vrGL5EVuQYM1iS4O5ilL51HkiJ3sPjMzRHiCChvr4dbaSJbR7F3lxA=="], - "@next/swc-darwin-arm64": ["@next/swc-darwin-arm64@16.4.3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-4yq5EXBt+VDtAZwTyfijaFp5D2C5oz3Ikw5a2kiX2K9nw72vrZX2q5UuAlkPtUMO1tQz6JTKpaKWjS7OOefTDQ=="], + "@next/swc-darwin-arm64": ["@next/swc-darwin-arm64@16.4.6", "", { "os": "darwin", "cpu": "arm64" }, "sha512-kJ4VVZkley17xKaJx72QN2IBqjrj7zenCQZaUF0l9ShS/1Mt2kW4+Z5KGG6vgr3L/J562xTOizVyM1iA/u5nlg=="], - "@next/swc-darwin-x64": ["@next/swc-darwin-x64@16.4.3", "", { "os": "darwin", "cpu": "x64" }, "sha512-1Rvkn/LUhnEF8WxnRkOrqGhbwXui1bkWFxONKIbN+r7C+9KHDSZ+iUoj4CzymVMWUyZIyx9szcb9+kbKhD500A=="], + "@next/swc-darwin-x64": ["@next/swc-darwin-x64@16.4.6", "", { "os": "darwin", "cpu": "x64" }, "sha512-eIPGZIqC+8JKaeZmvnCANJQF4xWkkHqSnAAajtFxgwDMAOnCgxNvP52SeWZ41PyVwoe+Le/NQuZSaQ8j7YshSA=="], - "@next/swc-linux-arm64-gnu": ["@next/swc-linux-arm64-gnu@16.4.3", "", { "os": "linux", "cpu": "arm64" }, "sha512-dCKpXErGg3abUM6t5JTJV/ottVBTStJB5lRJTbgdUdQaQ+jNHiK56Hsc0YAEg/rinSh42hYG3HWiYmEMdilnxg=="], + "@next/swc-linux-arm64-gnu": ["@next/swc-linux-arm64-gnu@16.4.6", "", { "os": "linux", "cpu": "arm64" }, "sha512-9nI6O8vvczH2D9ZNdMGqb/3NuT15T9ksOZnAmx9/gjF2cOi74+xxyf1Hk96uIMfm14c9y6wHeBq6SH8g6udvcA=="], - "@next/swc-linux-arm64-musl": ["@next/swc-linux-arm64-musl@16.4.3", "", { "os": "linux", "cpu": "arm64" }, "sha512-WwYbhWkhYBvBtib1K4W0kL8MW2snBD2A5b3SN4vPpqalZbZs5+bQ1yzAdepVoOqrFfEW3dmREy4Zs1MrWcrFbw=="], + "@next/swc-linux-arm64-musl": ["@next/swc-linux-arm64-musl@16.4.6", "", { "os": "linux", "cpu": "arm64" }, "sha512-7/qPhTxDp2ScluOJOhLuhWmlA17o1yZ0SIgpISBCpBxXgtnK4+KGywBpFkfLPiU1rnSM1faFGzYkH6i7JdTrqA=="], - "@next/swc-linux-x64-gnu": ["@next/swc-linux-x64-gnu@16.4.3", "", { "os": "linux", "cpu": "x64" }, "sha512-QymWvfUwDEC5/lpJOsxX5VAbyoR2D13+2Jsjz4be7gT4LPqEgdpkeLIR/HFfCLgKzoMhpJbp6I/JnogyNZHcaA=="], + "@next/swc-linux-x64-gnu": ["@next/swc-linux-x64-gnu@16.4.6", "", { "os": "linux", "cpu": "x64" }, "sha512-oOpbNa8XOW1qCGd9VvzC4fbkkRxEls7/WI6tz+YHC0xRA7KpV1U7DrAnCPjzVyOk/karzWEepCOcTIDmwK8FwQ=="], - "@next/swc-linux-x64-musl": ["@next/swc-linux-x64-musl@16.4.3", "", { "os": "linux", "cpu": "x64" }, "sha512-Vmjd9D7DpA4Vv3cUlr82QWgJD/BQZmns801vtC5VWHg6jCIA4a5vMKpQnfrM2pyCrp2eV0ENdUg4PlN3bAc2Yw=="], + "@next/swc-linux-x64-musl": ["@next/swc-linux-x64-musl@16.4.6", "", { "os": "linux", "cpu": "x64" }, "sha512-aM8CZ+OR2EwXaAYw7KGkW2GDmNDsLBIRe1MMRZCJPTdw/xhTD0IMUVO4sf3KqrzuRouGzwwLZn34+gFeVXiUQA=="], - "@next/swc-win32-arm64-msvc": ["@next/swc-win32-arm64-msvc@16.4.3", "", { "os": "win32", "cpu": "arm64" }, "sha512-lG1pPdPLk7gTyGb00n5JIMLdBJgjb+UEhSdZvFbhUMg0DyC6z4B7RnpSKF9VCd4imkLObVbXOFA0kFCpw7yFow=="], + "@next/swc-win32-arm64-msvc": ["@next/swc-win32-arm64-msvc@16.4.6", "", { "os": "win32", "cpu": "arm64" }, "sha512-U0p7/tEtqvHX2crhd841CDwKtp5CFkKXVjOhmfccR3Pvp64sj8KBwRqsvltqLOwVBbj0NtkxwXSDpEHYGbxeXQ=="], - "@next/swc-win32-x64-msvc": ["@next/swc-win32-x64-msvc@16.4.3", "", { "os": "win32", "cpu": "x64" }, "sha512-NmQC9RkJdnPXRaMxtkCzobB3teVjqF33oSOnwDfi+XYGWWYpt+xlGK3mtktSKLbdjwaWbJu2OkkMiRFGUUncKg=="], + "@next/swc-win32-x64-msvc": ["@next/swc-win32-x64-msvc@16.4.6", "", { "os": "win32", "cpu": "x64" }, "sha512-3ZG15/5WIdlTQsIEvc9sPTTSL5XFrlLklIKmfF4fwsDnoAhu6NcBDXsk3mbGxNyo6aVLEGex+fHCv2MahY7a9g=="], "@node-minify/core": ["@node-minify/core@9.0.2", "", { "dependencies": { "@node-minify/utils": "9.0.1", "glob": "10.3.3", "mkdirp": "3.0.1" } }, "sha512-FNhv29Wom6wKrrFKaeAfmZqz7TX5A1E6P+bpd0VIc+DYWMLUIhAViS8riaZg3A1oD0s06s+5BG2Fg7RqMKiKHw=="], @@ -434,6 +433,8 @@ "@pkgjs/parseargs": ["@pkgjs/parseargs@0.11.0", "", {}, "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg=="], + "@playwright/test": ["@playwright/test@1.65.1", "", { "dependencies": { "playwright": "1.65.1" }, "bin": { "playwright": "cli.js" } }, "sha512-y+NCIRm2LvY4slUVWvGh1nujJ8RF/hEisIsq2mtUPgdQC4L701bq5hZGMhrpeXjACvwvO9tj5dJqhvM6TP9lbw=="], + "@poppinss/colors": ["@poppinss/colors@4.1.6", "", { "dependencies": { "kleur": "^4.1.5" } }, "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg=="], "@poppinss/dumper": ["@poppinss/dumper@0.6.5", "", { "dependencies": { "@poppinss/colors": "^4.1.5", "@sindresorhus/is": "^7.0.2", "supports-color": "^10.0.0" } }, "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw=="], @@ -588,6 +589,8 @@ "@tsconfig/node18": ["@tsconfig/node18@18.2.7", "", {}, "sha512-UyenTORreCUh8MKh2qbLGGHTRrxjBbSwvX0ZoWs6Jx1jrNS62PXEA3+VaLvmb0YDQrgGU3v3h7zB9Xs/BN1ozg=="], + "@types/bun": ["@types/bun@1.4.5", "", { "dependencies": { "bun-types": "1.4.5" } }, "sha512-DpgwNI9z0L1S0gtb45QLCWgwCUcMLnsHYMJHQvpNj7erGiCGBvpggltAIeARrtobNMKMuy0UP7i56tKKgwFs/Q=="], + "@types/debug": ["@types/debug@4.1.13", "", { "dependencies": { "@types/ms": "*" } }, "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw=="], "@types/estree": ["@types/estree@1.0.8", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="], @@ -608,8 +611,6 @@ "@types/react-dom": ["@types/react-dom@19.3.0", "", { "peerDependencies": { "@types/react": "^19.3.0" } }, "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q=="], - "@types/react-window": ["@types/react-window@1.8.8", "", { "dependencies": { "@types/react": "*" } }, "sha512-8Ls660bHR1AUA2kuRvVG9D/4XpRC6wjAaPT9dil7Ckc76eP9TKWZwwmgfq8Q1LANX3QNDnoU4Zp48A3w+zK69Q=="], - "@types/unist": ["@types/unist@3.0.3", "", {}, "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q=="], "@ungap/structured-clone": ["@ungap/structured-clone@1.3.1", "", {}, "sha512-mUFwbeTqrVgDQxFveS+df2yfap6iuP20NAKAsBt5jDEoOTDew+zwLAOilHCeQJOVSvmgCX4ogqIrA0mnyr08yQ=="], @@ -636,6 +637,8 @@ "aws4fetch": ["aws4fetch@1.0.20", "", {}, "sha512-/djoAN709iY65ETD6LKCtyyEI04XIBP5xVvfmNxsEP0uJB5tyaGBztSryRr4HqMStr9R06PisQE7m9zDTXKu6g=="], + "axe-core": ["axe-core@4.14.1", "", {}, "sha512-FHfa+lmNjQZfJz1q8wKqIDwC6DExcHt/pkjNQb09a3NPjCKg2rhu5qb2S4r76ASyFNNtuFooJpZe37OgudVGtQ=="], + "bail": ["bail@2.0.2", "", {}, "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw=="], "balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="], @@ -652,6 +655,8 @@ "buffer-from": ["buffer-from@1.1.2", "", {}, "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="], + "bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], + "bytes": ["bytes@3.1.2", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="], "call-bind-apply-helpers": ["call-bind-apply-helpers@1.0.2", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="], @@ -784,8 +789,6 @@ "forwarded": ["forwarded@0.2.0", "", {}, "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow=="], - "framer-motion": ["framer-motion@12.43.0", "", { "dependencies": { "motion-dom": "^12.43.0", "motion-utils": "^12.39.0", "tslib": "^2.4.0" }, "peerDependencies": { "@emotion/is-prop-valid": "*", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@emotion/is-prop-valid", "react", "react-dom"] }, "sha512-1eaL3RvR/kAlbG7UYcpMptEyzPoENO0c6w7ZnB3/hh2vSAz/6uGAFn6fdoqTBguNstf3MsFhJHsD/0DHiclG+g=="], - "fresh": ["fresh@2.0.0", "", {}, "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A=="], "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], @@ -934,8 +937,6 @@ "media-typer": ["media-typer@1.1.0", "", {}, "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw=="], - "memoize-one": ["memoize-one@5.2.1", "", {}, "sha512-zYiwtZUcYyXKo/np96AGZAckk+FWWsUdJ3cHGGmld7+AhvcWmQyGCYUh1hc4Q/pkOhb65dQR/pqCyK0cOaHz4Q=="], - "merge-descriptors": ["merge-descriptors@2.0.0", "", {}, "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g=="], "micromark": ["micromark@4.0.2", "", { "dependencies": { "@types/debug": "^4.0.0", "debug": "^4.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "micromark-core-commonmark": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-encode": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-sanitize-uri": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA=="], @@ -1008,17 +1009,13 @@ "mnemonist": ["mnemonist@0.38.3", "", { "dependencies": { "obliterator": "^1.6.1" } }, "sha512-2K9QYubXx/NAjv4VLq1d1Ly8pWNC5L3BrixtdkyTegXWJIqY+zLNDhhX/A+ZwWt70tB1S8H4BE8FLYEFyNoOBw=="], - "motion-dom": ["motion-dom@12.43.0", "", { "dependencies": { "motion-utils": "^12.39.0" } }, "sha512-azKON4d9S65PEoFUiQTMTgPheEmzf2QngdRc50AKfJp9Q9mmcBVw22c8eMq9k8kxOFHdL7+WZY7N/5F/lwiDag=="], - - "motion-utils": ["motion-utils@12.39.0", "", {}, "sha512-8nadJAJjTtqRkmRF36FoJTrywK9nnFmnPwnSMyxaOCU7GDjN9RTMJIxx9De8ErM+vpPhMccr/6fo5WciyQLnMQ=="], - "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], "nanoid": ["nanoid@3.3.20", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ=="], "negotiator": ["negotiator@1.0.0", "", {}, "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg=="], - "next": ["next@16.4.3", "", { "dependencies": { "@next/env": "16.4.3", "@swc/helpers": "0.5.23", "baseline-browser-mapping": "^2.9.19", "caniuse-lite": "^1.0.30001579", "postcss": "8.5.23", "styled-jsx": "5.1.6" }, "optionalDependencies": { "@next/swc-darwin-arm64": "16.4.3", "@next/swc-darwin-x64": "16.4.3", "@next/swc-linux-arm64-gnu": "16.4.3", "@next/swc-linux-arm64-musl": "16.4.3", "@next/swc-linux-x64-gnu": "16.4.3", "@next/swc-linux-x64-musl": "16.4.3", "@next/swc-win32-arm64-msvc": "16.4.3", "@next/swc-win32-x64-msvc": "16.4.3", "sharp": "^0.35.5" }, "peerDependencies": { "@opentelemetry/api": "^1.1.0", "@playwright/test": "^1.51.1", "babel-plugin-react-compiler": "*", "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "sass": "^1.3.0" }, "optionalPeers": ["@opentelemetry/api", "@playwright/test", "babel-plugin-react-compiler", "sass"], "bin": { "next": "dist/bin/next" } }, "sha512-OqxKTGi9u80FydydsMNYNjnuje9Au+kvHlt2GZ//ftdpDHm1dxKqAaENoOOTX5wKzn+9vaKUNIfZeyZUuLhCnA=="], + "next": ["next@16.4.6", "", { "dependencies": { "@next/env": "16.4.6", "@swc/helpers": "0.5.23", "baseline-browser-mapping": "^2.9.19", "caniuse-lite": "^1.0.30001579", "postcss": "8.5.23", "styled-jsx": "5.1.6" }, "optionalDependencies": { "@next/swc-darwin-arm64": "16.4.6", "@next/swc-darwin-x64": "16.4.6", "@next/swc-linux-arm64-gnu": "16.4.6", "@next/swc-linux-arm64-musl": "16.4.6", "@next/swc-linux-x64-gnu": "16.4.6", "@next/swc-linux-x64-musl": "16.4.6", "@next/swc-win32-arm64-msvc": "16.4.6", "@next/swc-win32-x64-msvc": "16.4.6", "sharp": "^0.35.5" }, "peerDependencies": { "@opentelemetry/api": "^1.1.0", "@playwright/test": "^1.51.1", "babel-plugin-react-compiler": "*", "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "sass": "^1.3.0" }, "optionalPeers": ["@opentelemetry/api", "@playwright/test", "babel-plugin-react-compiler", "sass"], "bin": { "next": "dist/bin/next" } }, "sha512-QZJiYhaZLJMo2KpkQGQIwvmd79WVsAWeYIU554a8d7zArS3si/IRy3lBNV/rtYhE70oLwdLYhPAXLPx8HwcwtA=="], "next-view-transitions": ["next-view-transitions@0.3.5", "", { "peerDependencies": { "next": ">=14.0.0", "react": ">=18.2.0 || ^19.0.0", "react-dom": ">=18.2.0 || ^19.0.0" } }, "sha512-yP8OPNydLmKpmE94hLurLGEzPsUy1uyl9iSv8oxaC2JwhSXTD86SVwk1NMMQT7Ado4kMENDJ7fNBIXHy3GU/Lg=="], @@ -1056,6 +1053,10 @@ "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], + "playwright": ["playwright@1.65.1", "", { "dependencies": { "playwright-core": "1.65.1" }, "bin": { "playwright": "cli.js" } }, "sha512-vJ1FuoOrNwOKHUIVEvSt3jT1L+wjjDpwhwIstKtfvTh8XIG4FG4bIFuvNdMxi81LGfAhUgUZleVFaOLY4RIUUw=="], + + "playwright-core": ["playwright-core@1.65.1", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw=="], + "postcss": ["postcss@8.5.32", "", { "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", "source-map-js": "^1.2.2" } }, "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g=="], "property-information": ["property-information@7.2.0", "", {}, "sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg=="], @@ -1078,10 +1079,6 @@ "react-stately": ["react-stately@3.46.0", "", { "dependencies": { "@internationalized/date": "^3.12.1", "@internationalized/number": "^3.6.6", "@internationalized/string": "^3.2.8", "@react-types/shared": "^3.34.0", "@swc/helpers": "^0.5.0", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1" } }, "sha512-OdxhWvHgs2L4OJGIs7hnuTr5WjjMM6enhNEAMRqiekhF8+ITvA2LRwNftOZwcogaoCslGYq5S2VQTQwnm0GbCA=="], - "react-virtualized-auto-sizer": ["react-virtualized-auto-sizer@1.0.26", "", { "peerDependencies": { "react": "^15.3.0 || ^16.0.0-alpha || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^15.3.0 || ^16.0.0-alpha || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-CblNyiNVw2o+hsa5/49NH2ogGxZ+t+3aweRvNSq7TVjDIlwk7ir4lencEg5HxHeSzwNarSkNkiu0qJSOXtxm5A=="], - - "react-window": ["react-window@1.8.11", "", { "dependencies": { "@babel/runtime": "^7.0.0", "memoize-one": ">=3.1.1 <6" }, "peerDependencies": { "react": "^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-+SRbUVT2scadgFSWx+R1P754xHPEqvcfSfVX10QYg6POOz+WNgkN48pS+BtZNIMGiL1HYrSEiCkwsMS15QogEQ=="], - "rehype-raw": ["rehype-raw@7.0.0", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-raw": "^9.0.0", "vfile": "^6.0.0" } }, "sha512-/aE8hCfKlQeA8LmyeyQvQF3eBiLRGNlfBJEvWH7ivp9sBqs7TNqBL5X3v157rM4IFETqDnIOO+z5M/biZbo9Ww=="], "remark-gfm": ["remark-gfm@4.0.1", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-gfm": "^3.0.0", "micromark-extension-gfm": "^3.0.0", "remark-parse": "^11.0.0", "remark-stringify": "^11.0.0", "unified": "^11.0.0" } }, "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg=="], @@ -1302,8 +1299,6 @@ "@types/node-fetch/@types/node": ["@types/node@20.19.39", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-orrrD74MBUyK8jOAD/r0+lfa1I2MO6I+vAkmAWzMYbCcgrN4lCrmK52gRFQq/JRxfYPfonkr4b0jcY7Olqdqbw=="], - "@types/react-window/@types/react": ["@types/react@19.2.14", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w=="], - "cliui/string-width": ["string-width@7.2.0", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="], "cliui/strip-ansi": ["strip-ansi@7.2.0", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="], diff --git a/bunfig.toml b/bunfig.toml new file mode 100644 index 00000000..3efd7387 --- /dev/null +++ b/bunfig.toml @@ -0,0 +1,3 @@ +[test] +root = "./tests" +preload = ["./tests/setup.ts"] diff --git a/e2e/accessibility.spec.ts b/e2e/accessibility.spec.ts new file mode 100644 index 00000000..ba16aa74 --- /dev/null +++ b/e2e/accessibility.spec.ts @@ -0,0 +1,85 @@ +import AxeBuilder from '@axe-core/playwright'; +import type { Page } from '@playwright/test'; + +import { expect, test } from './fixtures'; +import { PAGES } from './pages'; + +/** Pages with their tools filled in, so the results get checked as well as the empty form. */ +const FILLED: { name: string; path: string; fill?: (page: Page) => Promise }[] = [ + { + name: 'map planner with a plan', + path: '/map-planner', + fill: async (page) => { + await page.getByRole('textbox').first().fill('Glazy\nAbominable Snow\nZombie\nBurglar\nNot a mouse'); + await expect(page.getByText(/setups? attracts? at least one of your mice/)).toBeVisible(); + }, + }, + { + name: 'rank-up calculator with an answer', + path: '/rank-up-calculator?title=baron_baroness&target=duke_dutchess&progress=42.5&mouse=Glazy', + fill: async (page) => { + await expect(page.getByRole('region', { name: 'Result' })).toContainText('catches of Glazy Mouse'); + }, + }, + { + name: 'catch rate estimator with results', + path: '/catch-rate-estimator?location=meadow&cheese=cheddar_cheese&weapon=floating_law_upgraded_weapon&base=rainbow_diamond_refractor_base&charm=ultimate_ancient_trinket', + fill: async (page) => { + await expect(page.getByText('Overall catch rate')).toBeVisible(); + await page.getByText('Auras and other bonuses').click(); + }, + }, + { + name: 'best setup with results and my items', + path: '/best-setup?location=fort_rox&stage=Midnight&cheese=crescent_cheese&own_weapons=dark_magic_mirror_weapon,acronym_weapon&own_bases=rift_base', + fill: async (page) => { + await expect(page.getByText('The setups that catch the most mice per 100 hunts.')).toBeVisible(); + }, + }, + { name: 'rankings, focused on a mouse', path: '/mice/rankings?by=gold&mouse=glazed' }, + { name: 'items, filtered', path: '/items?type=stat&sub=currency&tradable=1' }, + { name: 'mice, filtered to nothing', path: '/mice?q=zzzz' }, + { name: 'mice, with a power type chosen', path: '/mice?weakto=arcane' }, + { name: 'userscripts, on a tag with a two-digit count', path: '/userscripts/tags/ui' }, + { + name: 'search open with results', + path: '/', + fill: async (page) => { + await page.keyboard.press('ControlOrMeta+k'); + await page.getByRole('combobox').or(page.getByRole('searchbox')).last().fill('glazy'); + await expect(page.getByRole('option').first()).toBeVisible(); + }, + }, +]; + +const CHECKS = [...PAGES.map((path) => ({ name: path, path, fill: undefined })), ...FILLED]; + +/** The WCAG 2.2 A and AA rules, which add a minimum size for things to tap. */ +async function audit(page: Page) { + const { violations } = await new AxeBuilder({ page }) + .withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa']) + .analyze(); + return violations.map((violation) => ({ + rule: violation.id, + impact: violation.impact, + help: violation.help, + targets: violation.nodes.slice(0, 5).map((node) => node.target.join(' ')), + count: violation.nodes.length, + })); +} + +for (const scheme of ['light', 'dark'] as const) { + test.describe(`${scheme} mode`, () => { + test.use({ colorScheme: scheme }); + + for (const check of CHECKS) { + test(`${check.name} meets WCAG 2.2 AA`, async ({ page }) => { + await page.goto(check.path, { waitUntil: 'networkidle' }); + await check.fill?.(page); + // Let transitions finish, so colours are measured at rest. + await page.waitForTimeout(400); + expect(await audit(page)).toEqual([]); + }); + } + }); +} diff --git a/e2e/best-setup.spec.ts b/e2e/best-setup.spec.ts new file mode 100644 index 00000000..f120f9e1 --- /dev/null +++ b/e2e/best-setup.spec.ts @@ -0,0 +1,132 @@ +import { expect, test } from './fixtures'; + +const FORT_ROX = '/best-setup?location=fort_rox&stage=Midnight&cheese=crescent_cheese'; + +test('ranks every weapon and base for a location', async ({ page }) => { + await page.goto(FORT_ROX); + await expect(page.getByText('The setups that catch the most mice per 100 hunts.')).toBeVisible(); + const first = page.locator('#results ol > li').first(); + await expect(first).toContainText('Shadow power'); + // Each result opens in the estimator with its setup filled in. + await first.getByRole('link', { name: 'See each mouse' }).click(); + await expect(page).toHaveURL(/\/catch-rate-estimator\?.*weapon=/); + await expect(page.getByText('Overall catch rate')).toBeVisible(); +}); + +test('aims for one mouse', async ({ page }) => { + await page.goto(FORT_ROX); + await page.getByRole('radio', { name: /One mouse/ }).click(); + // A label around a select takes in its options' text, so find it by the label's first word. + await page + .locator('label', { hasText: /^Mouse/ }) + .locator('select') + .selectOption({ label: 'Nightmancer Mouse' }); + await expect(page.getByText('The setups that catch the most Nightmancer Mouse per 100 hunts.')).toBeVisible(); + await expect(page).toHaveURL(/target=nightmancer/); +}); + +test('items sent in a link are searched, saved, and taken out of the address', async ({ page }) => { + await page.goto(`${FORT_ROX}&own_weapons=dark_magic_mirror_weapon,acronym_weapon&own_bases=rift_base`); + await expect(page.getByText(/Searching your 2 weapons, 1 base, and 0 charms/)).toBeVisible(); + await expect(page.locator('#results ol > li')).toHaveCount(2); + await expect(page).not.toHaveURL(/own_weapons/); + // Still there on the next visit. + await page.goto(FORT_ROX); + await expect(page.locator('#results ol > li')).toHaveCount(2); +}); + +test('ticking items narrows the search', async ({ page }) => { + await page.goto(FORT_ROX); + await page.getByRole('radio', { name: 'Only mine' }).click(); + // Exact, so the screen-reader status line that says the same thing with a full stop isn't matched too. + await expect(page.getByText('No weapons or bases to try', { exact: true })).toBeVisible(); + await page.getByLabel('Find weapons').fill('Dark Magic'); + await page.getByRole('button', { name: 'Tick all shown', exact: true }).click(); + await page.getByRole('button', { name: /^Bases/ }).click(); + await page.getByLabel('Find bases').fill('Rift Base'); + await page.getByRole('checkbox', { name: 'Rift Base', exact: true }).check(); + await expect(page.locator('#results ol > li').first()).toContainText('Dark Magic Mirrors'); + await expect(page.locator('#results ol > li').first()).toContainText('Rift Base'); +}); + +test('looking at every item and coming back keeps the ticked items', async ({ page }) => { + await page.goto(FORT_ROX); + await page.getByRole('radio', { name: 'Only mine' }).click(); + await page.getByLabel('Find weapons').fill('Dark Magic'); + await page.getByRole('button', { name: 'Tick all shown', exact: true }).click(); + await expect(page.getByText(/Searching your 2 weapons/)).toBeVisible(); + + await page.getByRole('radio', { name: 'Every item' }).click(); + await expect(page.getByText(/Searching every weapon and base in the game/)).toBeVisible(); + await page.getByRole('radio', { name: 'Only mine' }).click(); + await expect(page.getByText(/Searching your 2 weapons/)).toBeVisible(); + + // The list, and the choice to search every item, are both there on the next visit. + await page.getByRole('radio', { name: 'Every item' }).click(); + await page.goto(FORT_ROX); + await expect(page.getByRole('radio', { name: 'Every item' })).toBeChecked(); + await page.getByRole('radio', { name: 'Only mine' }).click(); + await expect(page.getByText(/Searching your 2 weapons/)).toBeVisible(); +}); + +test('clearing every tick at once can be undone', async ({ page }) => { + await page.goto(`${FORT_ROX}&own_weapons=dark_magic_mirror_weapon,acronym_weapon&own_bases=rift_base`); + await expect(page.getByText(/Searching your 2 weapons, 1 base,/)).toBeVisible(); + await page.getByRole('button', { name: 'Untick all', exact: true }).click(); + await expect(page.getByText(/Searching your 0 weapons, 1 base,/)).toBeVisible(); + await page.getByRole('button', { name: 'Undo', exact: true }).click(); + await expect(page.getByText(/Searching your 2 weapons, 1 base,/)).toBeVisible(); +}); + +test('a list from a link can be swapped back for the saved one', async ({ page }) => { + await page.goto(`${FORT_ROX}&own_weapons=dark_magic_mirror_weapon,acronym_weapon&own_bases=rift_base`); + await expect(page.getByText(/Searching your 2 weapons, 1 base,/)).toBeVisible(); + // Someone else's link, with a different list in it. + await page.goto(`${FORT_ROX}&own_weapons=acronym_weapon&own_bases=rift_base`); + await expect(page.getByText(/Searching your 1 weapon, 1 base,.*These came from the link you opened/)).toBeVisible(); + await page.getByRole('button', { name: 'Use my saved items instead' }).click(); + await expect(page.getByText(/Searching your 2 weapons, 1 base,/)).toBeVisible(); + // A link with the parameters but no items in them changes nothing. + await page.goto(`${FORT_ROX}&own_weapons=&own_bases=`); + await expect(page.getByText(/Searching your 2 weapons, 1 base,/)).toBeVisible(); + await expect(page).not.toHaveURL(/own_weapons/); +}); + +test('a link that only names a location keeps the charm, shield and bonuses', async ({ page }) => { + await page.goto(`${FORT_ROX}&gs=0&bonus_luck=5&charm=ultimate_ancient_trinket`); + await expect(page.getByRole('checkbox', { name: 'Golden Shield' })).not.toBeChecked(); + // What a location page's "Best setup here" opens. + await page.goto('/best-setup?location=meadow'); + await expect(page.getByLabel('Location')).toHaveValue('meadow'); + await expect(page.getByRole('checkbox', { name: 'Golden Shield' })).not.toBeChecked(); + await expect(page.getByLabel('Extra luck')).toHaveValue('5'); + await expect(page.getByRole('combobox', { name: 'Charm' })).toHaveValue('Ultimate Ancient Charm'); +}); + +test('setups that tie at the top say so', async ({ page }) => { + await page.goto('/best-setup?location=meadow&cheese=cheddar_cheese'); + await expect(page.getByText(/catch the same, so any of them will do\./)).toBeVisible(); +}); + +test('a mouse page opens Best Setup aimed at that mouse, with the saved shield and bonuses', async ({ page }) => { + await page.goto(`${FORT_ROX}&gs=0&bonus_luck=5`); + await expect(page.getByRole('checkbox', { name: 'Golden Shield' })).not.toBeChecked(); + + await page.goto('/mice/glazed'); + await page.getByRole('link', { name: 'Best setup for this mouse' }).click(); + await expect(page).toHaveURL(/\/best-setup\?location=winter_hunt_fortress.*target=glazed/); + await expect(page.getByText('The setups that catch the most Glazy Mouse per 100 hunts.')).toBeVisible(); + await expect(page.getByRole('radio', { name: /One mouse/ })).toBeChecked(); + await expect(page.getByRole('checkbox', { name: 'Golden Shield' })).not.toBeChecked(); + await expect(page.getByLabel('Extra luck')).toHaveValue('5'); +}); + +test('the choices work with the arrow keys, as radios do', async ({ page }) => { + await page.goto(FORT_ROX); + await page.getByRole('radio', { name: /Most catches/ }).focus(); + await page.keyboard.press('ArrowRight'); + await expect(page.getByRole('radio', { name: /One mouse/ })).toBeChecked(); + await expect(page.getByRole('radio', { name: /One mouse/ })).toBeFocused(); + await page.keyboard.press('ArrowLeft'); + await expect(page.getByRole('radio', { name: /Most catches/ })).toBeChecked(); +}); diff --git a/e2e/catch-rate.spec.ts b/e2e/catch-rate.spec.ts new file mode 100644 index 00000000..ce69b7fa --- /dev/null +++ b/e2e/catch-rate.spec.ts @@ -0,0 +1,158 @@ +import { expect, test } from './fixtures'; + +const STINGER = + '/catch-rate-estimator?location=meadow&cheese=cheddar_cheese&weapon=floating_law_upgraded_weapon&base=rainbow_diamond_refractor_base&charm=ultimate_ancient_trinket'; + +const stat = (page: import('@playwright/test').Page, label: string) => + page + .locator('dl > div') + .filter({ has: page.getByText(label, { exact: true }) }) + .locator('dd'); + +test('a shared link opens with its setup and results', async ({ page }) => { + await page.goto(STINGER); + await expect(page.getByText('Overall catch rate')).toBeVisible(); + await expect(stat(page, 'Power')).toHaveText('16,027'); + await expect(stat(page, 'Luck')).toHaveText('77'); + await expect(stat(page, 'Attraction bonus')).toHaveText('73%'); + await expect(page.getByRole('table')).toContainText('Mouse'); +}); + +test('what a hunt earns, with a way to see how long a rank-up takes', async ({ page }) => { + await page.goto(STINGER); + await expect(page.getByText('Each hunt earns, on average')).toBeVisible(); + await expect(stat(page, 'Points')).toHaveText(/^[\d,]+$/); + await expect(stat(page, 'Gold')).toHaveText(/^[\d,]+$/); + await page.getByRole('link', { name: 'Hunts to your next title at this pace' }).click(); + await expect(page).toHaveURL(/\/rank-up-calculator\?.*perhunt=\d+/); + await expect(page.getByLabel(/Wisdom per hunt/)).not.toHaveValue(''); +}); + +test('picking a setup by hand fills in the results and the link', async ({ page }) => { + await page.goto('/catch-rate-estimator'); + await expect(page.getByText('Pick a location, weapon, and base')).toBeVisible(); + await page.getByLabel('Location').selectOption({ label: 'Meadow' }); + await page.getByRole('combobox', { name: 'Weapon' }).fill('S.T.I.N'); + await page.getByRole('option', { name: /S\.T\.I\.N\.G\.E\.R\. Trap/ }).click(); + await page.getByRole('combobox', { name: 'Base' }).fill('Rainbow Diamond'); + await page.getByRole('option', { name: /Rainbow Diamond Refractor Base/ }).click(); + await expect(page.getByText('Overall catch rate')).toBeVisible(); + await expect(page).toHaveURL(/weapon=floating_law_upgraded_weapon/); + await expect(page).toHaveURL(/base=rainbow_diamond_refractor_base/); +}); + +test('matching the camp works out the aura bonuses', async ({ page }) => { + await page.goto(STINGER); + await page.getByText('Auras and other bonuses').click(); + await page.getByLabel('Power shown').fill('20741'); + await page.getByLabel('Luck shown').fill('83'); + await page.getByRole('button', { name: 'Use +45% power and +6 luck' }).click(); + await expect(stat(page, 'Power')).toHaveText('20,741'); + await expect(stat(page, 'Luck')).toHaveText('83'); + await expect(page).toHaveURL(/bonus_power=45/); +}); + +test('a mouse the power type can’t catch says so', async ({ page }) => { + await page.goto( + '/catch-rate-estimator?location=fort_rox&stage=Midnight&cheese=crescent_cheese&weapon=chrome_monstrobot_weapon&base=rainbow_diamond_refractor_base', + ); + await expect(page.getByText(/None of these mice can be caught with Physical power/)).toBeVisible(); + await expect(page.getByText('Immune').first()).toBeVisible(); +}); + +test('a return visit picks up the last setup', async ({ page }) => { + await page.goto(STINGER); + await expect(stat(page, 'Power')).toHaveText('16,027'); + await page.goto('/catch-rate-estimator'); + await expect(stat(page, 'Power')).toHaveText('16,027'); +}); + +test('a location page link keeps the trap from the last visit', async ({ page }) => { + await page.goto(`${STINGER}&gs=0`); + await expect(stat(page, 'Power')).toHaveText(/\d/); + // What "Catch rates here" on a location page opens. + await page.goto('/catch-rate-estimator?location=harbour'); + await expect(page.getByLabel('Location')).toHaveValue('harbour'); + await expect(page.getByRole('combobox', { name: 'Weapon' })).toHaveValue('S.T.I.N.G.E.R. Trap'); + await expect(page.getByRole('combobox', { name: 'Base' })).toHaveValue('Rainbow Diamond Refractor Base'); + await expect(page.getByRole('checkbox', { name: 'Golden Shield' })).not.toBeChecked(); + await expect(page.getByText('Overall catch rate')).toBeVisible(); + // And it is still the saved setup afterwards. + await page.goto('/catch-rate-estimator'); + await expect(page.getByRole('combobox', { name: 'Weapon' })).toHaveValue('S.T.I.N.G.E.R. Trap'); +}); + +test('typing into a filled picker replaces what was picked', async ({ page }) => { + await page.goto(STINGER); + await expect(page.getByText('Overall catch rate')).toBeVisible(); + await page.getByRole('combobox', { name: 'Weapon' }).click(); + await page.keyboard.type('Sandtail'); + await expect(page.getByRole('combobox', { name: 'Weapon' })).toHaveValue('Sandtail'); + await page.getByRole('option', { name: /Sandtail Sentinel/ }).click(); + await expect(page).toHaveURL(/weapon=sentinel_weapon/); +}); + +test('a number field with a default can be cleared and retyped', async ({ page }) => { + await page.goto('/catch-rate-estimator?location=zugzwang_tower&weapon=floating_law_upgraded_weapon&base=rift_base'); + const amplifier = page.getByLabel(/Amplifier/); + await expect(amplifier).toHaveValue('100'); + await amplifier.click(); + await page.keyboard.press('End'); + for (let i = 0; i < 3; i++) await page.keyboard.press('Backspace'); + await expect(amplifier).toHaveValue(''); + await page.keyboard.type('150'); + await expect(amplifier).toHaveValue('150'); + await expect(page).toHaveURL(/amp=150/); + // Over the maximum is held to it once the field is left. + await amplifier.fill('999'); + await amplifier.blur(); + await expect(amplifier).toHaveValue('175'); +}); + +test('clearing a bonus leaves the bonuses panel open', async ({ page }) => { + await page.goto(`${STINGER}&bonus_luck=5`); + const luck = page.getByLabel('Extra luck'); + await expect(luck).toBeVisible(); + await luck.fill(''); + await expect(luck).toBeVisible(); + await luck.fill('-7'); + await expect(page.getByText('+0% power, −7 luck')).toBeVisible(); +}); + +test('a setup picked up from the last visit goes into the address, and Start over clears both', async ({ page }) => { + await page.goto(STINGER); + await expect(stat(page, 'Power')).toHaveText('16,027'); + await page.goto('/catch-rate-estimator'); + await expect(stat(page, 'Power')).toHaveText('16,027'); + await expect(page).toHaveURL(/weapon=floating_law_upgraded_weapon/); + + await page.getByRole('button', { name: 'Start over' }).click(); + await expect(page.getByText('Pick a location, weapon, and base')).toBeVisible(); + await expect(page).toHaveURL(/\/catch-rate-estimator$/); + await page.reload(); + await expect(page.getByText('Pick a location, weapon, and base')).toBeVisible(); +}); + +test('a location opens on the cheese most hunted there', async ({ page }) => { + await page.goto('/catch-rate-estimator?location=mountain&weapon=floating_law_upgraded_weapon&base=rift_base'); + await expect(page.getByLabel('Cheese')).not.toHaveValue('abominable_asiago_cheese'); + await expect(page.getByText('Overall catch rate')).toBeVisible(); +}); + +test('an item page’s link swaps that item into the saved setup', async ({ page }) => { + await page.goto(STINGER); + await expect(stat(page, 'Power')).toHaveText('16,027'); + await page.goto('/items/acronym-weapon'); + await page.getByRole('link', { name: 'Try it in the catch rate estimator' }).click(); + await expect(page).toHaveURL(/location=meadow.*weapon=acronym_weapon.*base=rainbow_diamond_refractor_base/); + await expect(stat(page, 'Power type')).toHaveText('Arcane'); +}); + +test('a mouse page’s link opens its best place with the saved trap', async ({ page }) => { + await page.goto(STINGER); + await expect(stat(page, 'Power')).toHaveText('16,027'); + await page.goto('/mice/glazed'); + await page.getByRole('link', { name: 'Your catch rate there' }).click(); + await expect(page).toHaveURL(/location=winter_hunt_fortress.*weapon=floating_law_upgraded_weapon/); + await expect(page.getByRole('table')).toContainText('Glazy Mouse'); +}); diff --git a/e2e/essence.spec.ts b/e2e/essence.spec.ts new file mode 100644 index 00000000..27106aae --- /dev/null +++ b/e2e/essence.spec.ts @@ -0,0 +1,23 @@ +import { expect, test } from './fixtures'; + +test('amounts pasted from the Crafting Table fill every box, wherever the cursor is', async ({ page, context }) => { + await context.grantPermissions(['clipboard-read', 'clipboard-write']); + await page.goto('/essence-calculator'); + await page.evaluate(() => navigator.clipboard.writeText('12 Aleth Essence\n5 Ber Essence\n1,250 Cynd Essence')); + // With a box focused, as it has to be on a phone, the pasted text used to be typed into that box as well. + await page.getByLabel('Aleth').click(); + await page.keyboard.press('ControlOrMeta+v'); + await expect(page.getByLabel('Aleth')).toHaveValue('12'); + await expect(page.getByLabel('Ber')).toHaveValue('5'); + await expect(page.getByLabel('Cynd')).toHaveValue('1250'); +}); + +test('a plain number pastes into the box it was pasted in', async ({ page, context }) => { + await context.grantPermissions(['clipboard-read', 'clipboard-write']); + await page.goto('/essence-calculator'); + await page.evaluate(() => navigator.clipboard.writeText('40')); + await page.getByLabel('Ber').click(); + await page.keyboard.press('ControlOrMeta+v'); + await expect(page.getByLabel('Ber')).toHaveValue('40'); + await expect(page.getByLabel('Aleth')).toHaveValue(''); +}); diff --git a/e2e/fixtures.ts b/e2e/fixtures.ts new file mode 100644 index 00000000..1b24ace7 --- /dev/null +++ b/e2e/fixtures.ts @@ -0,0 +1,89 @@ +import { expect, test as base, type Page } from '@playwright/test'; + +/** A 1×1 transparent PNG, served for every game image so the tests don't wait on i.mouse.rip. */ +const PIXEL = Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', + 'base64', +); + +/** Timers that are always current, whenever the tests run. */ +export function timers() { + const hour = 3_600_000; + const now = Date.now(); + const iso = (offset: number) => new Date(now + offset).toISOString(); + return { + now: iso(0), + daily_reset: { at: iso(10 * hour) }, + locations: [ + { + id: 'forbidden_grove', + name: 'Forbidden Grove', + current: { name: 'Open', starts_at: iso(-hour), ends_at: iso(2 * hour) }, + upcoming: [ + { name: 'Closed', starts_at: iso(2 * hour), ends_at: iso(6 * hour) }, + { name: 'Open', starts_at: iso(6 * hour), ends_at: iso(26 * hour) }, + ], + }, + ], + }; +} + +/** Where the Relic Hunter is, as api.mouse.rip answers. */ +export function relicHunter() { + return { + id: 'laboratory', + name: 'Laboratory', + image: 'https://www.mousehuntgame.com/images/environments/laboratory.jpg', + last_seen: new Date(Date.now() - 20 * 60_000).toISOString(), + }; +} + +/** A month of prices ending `endedDaysAgo` days back, so an item's price chart has something to draw. */ +export function marketHistory(itemId: number, endedDaysAgo = 0) { + const day = 86_400_000; + const start = Date.now() - (30 + endedDaysAgo) * day; + return { + item_info: { item_id: itemId, name: 'Test item', currently_tradeable: true }, + market_data: Array.from({ length: 30 }, (_, i) => ({ + date: new Date(start + i * day).toISOString().slice(0, 10), + price: 1000 + i * 10, + sb_price: 1 + i / 100, + volume: 100 + i, + })), + }; +} + +/** Serve the site's outside requests from here, so a slow or changed service can't fail a test. */ +async function stubOutsideServices(page: Page) { + await page.route('https://i.mouse.rip/**', (route) => + route.fulfill({ status: 200, contentType: 'image/png', body: PIXEL }), + ); + await page.route('https://api.mouse.rip/timers', (route) => route.fulfill({ json: timers() })); + await page.route('https://api.mouse.rip/relic-hunter', (route) => route.fulfill({ json: relicHunter() })); + await page.route('https://api.markethunt.win/items', (route) => route.fulfill({ json: [] })); + await page.route(/^https:\/\/api\.markethunt\.win\/items\/(\d+)$/, (route) => + route.fulfill({ json: marketHistory(Number(route.request().url().split('/').pop())) }), + ); +} + +/** + * Every test fails on a console error or an uncaught exception: that's how a hydration mismatch shows up, + * and it's easy to miss by eye. + */ +export const test = base.extend<{ consoleErrors: string[] }>({ + consoleErrors: [ + async ({ page }, use) => { + const errors: string[] = []; + page.on('console', (message) => { + if (message.type() === 'error') errors.push(message.text()); + }); + page.on('pageerror', (error) => errors.push(error.message)); + await stubOutsideServices(page); + await use(errors); + expect(errors, 'console errors').toEqual([]); + }, + { auto: true }, + ], +}); + +export { expect }; diff --git a/e2e/items.spec.ts b/e2e/items.spec.ts new file mode 100644 index 00000000..19f45c37 --- /dev/null +++ b/e2e/items.spec.ts @@ -0,0 +1,85 @@ +import { expect, marketHistory, test } from './fixtures'; + +for (const viewport of [ + { name: 'desktop', width: 1280, height: 900 }, + { name: 'phone', width: 390, height: 844 }, +]) { + test(`Tradable only stays put as the type chips change (${viewport.name})`, async ({ page }) => { + await page.setViewportSize(viewport); + await page.goto('/items'); + const toggle = page.getByText('Tradable only'); + await expect(toggle).toBeVisible(); + const before = await toggle.boundingBox(); + + await page.getByLabel('Search items by name').fill('egg'); + await page.waitForTimeout(400); + expect(await toggle.boundingBox()).toEqual(before); + + await toggle.click(); + await page.waitForTimeout(400); + expect(await toggle.boundingBox()).toEqual(before); + }); +} + +test('Special items split into the game’s own groups', async ({ page }) => { + await page.goto('/items?type=stat'); + const groups = page.getByRole('group', { name: 'Special groups' }); + await expect(groups).toBeVisible(); + await groups.getByRole('button', { name: /Currency/ }).click(); + await expect(page).toHaveURL(/sub=currency/); +}); + +test('a type page links to each of its groups', async ({ page }) => { + await page.goto('/items/type/stat'); + const nav = page.getByRole('navigation', { name: /by group/ }); + await expect(nav.getByRole('link')).not.toHaveCount(0); +}); + +test('a price shows its trend while the item is trading', async ({ page }) => { + await page.goto('/items/super-brie-cheese'); + await expect(page.getByText(/over 90 days/)).toBeVisible(); + await expect(page.getByText(/Last traded/)).toHaveCount(0); +}); + +test('an item that stopped trading says when, instead of a trend', async ({ page }) => { + await page.route(/^https:\/\/api\.markethunt\.win\/items\/\d+$/, (route) => + route.fulfill({ json: marketHistory(114, 400) }), + ); + await page.goto('/items/super-brie-cheese'); + await expect(page.getByText(/^Last traded \w+ \d+, \d{4}$/)).toBeVisible(); + await expect(page.getByText(/over 90 days/)).toHaveCount(0); +}); + +test('a price response that has changed shape leaves the page standing', async ({ page }) => { + await page.route(/^https:\/\/api\.markethunt\.win\/items\/\d+$/, (route) => + route.fulfill({ json: { market_data: [null, { date: 5 }, 'nope'] } }), + ); + await page.goto('/items/super-brie-cheese', { waitUntil: 'networkidle' }); + await expect(page.getByRole('heading', { level: 1 })).toHaveText(/SUPER/); + await expect(page.getByRole('heading', { name: 'Marketplace price' })).toHaveCount(0); +}); + +test('the price chart can be read as a table', async ({ page }) => { + await page.goto('/items/super-brie-cheese'); + await page.getByText('Show these prices as a table').click(); + const table = page.getByRole('table', { name: 'Price and amount traded for each day in the chart' }); + await expect(table.getByRole('row')).toHaveCount(31); +}); + +test('Show all is still on after a visit to an item and Back, at the same place in the list', async ({ page }) => { + const results = 'main ul a[href^="/items/"]'; + await page.goto('/items?tradable=1'); + await expect(page.locator(results)).toHaveCount(400); + await page.getByRole('button', { name: 'Show all' }).click(); + await expect(page.locator(results)).not.toHaveCount(400); + + const link = page.locator(results).nth(700); + await link.scrollIntoViewIfNeeded(); + const before = await page.evaluate(() => window.scrollY); + await link.click(); + await expect(page).toHaveURL(/\/items\/[a-z0-9-]+$/); + await page.goBack(); + await expect(page).toHaveURL(/\/items\?tradable=1$/); + await expect.poll(() => page.locator(results).count()).toBeGreaterThan(700); + await expect.poll(() => page.evaluate(() => window.scrollY)).toBeGreaterThan(before - 400); +}); diff --git a/e2e/map-planner.spec.ts b/e2e/map-planner.spec.ts new file mode 100644 index 00000000..90359e86 --- /dev/null +++ b/e2e/map-planner.spec.ts @@ -0,0 +1,39 @@ +import { expect, test } from './fixtures'; + +const MAP = ['- Glazy', '2. Abominable Snow Mouse', 'Zombie', 'Burglar', 'Bionic', 'Granite', 'Diamond', 'Not a mouse']; + +test('plans a pasted map, and the link brings it back', async ({ page }) => { + await page.goto('/map-planner'); + await page.getByRole('textbox').first().fill(MAP.join('\n')); + await expect(page.getByText(/Not recognized: Not a mouse/)).toBeVisible(); + await expect(page.getByText('Guaranteed attractions')).toBeVisible(); + await expect(page.getByText(/setups? attracts? at least one of your mice/)).toBeVisible(); + await expect(page).toHaveURL(/mice=/); + + const shared = page.url(); + await page.goto('about:blank'); + await page.goto(shared); + await expect(page.getByText('Abominable Snow Mouse').first()).toBeVisible(); + await expect(page.getByText(/setups? attracts? at least one of your mice/)).toBeVisible(); +}); + +test('sorting reorders the setups', async ({ page }) => { + await page.goto('/map-planner'); + await page.getByRole('textbox').first().fill(MAP.slice(0, 7).join('\n')); + const select = page.getByRole('combobox').first(); + for (const option of ['Most mice', 'Quickest to clear', 'Best overall']) { + await select.selectOption({ label: option }); + await expect(select).toHaveValue(/\w+/); + } +}); + +test('a mouse that only comes with a charm says which', async ({ page }) => { + await page.goto('/map-planner'); + await page.getByRole('textbox').first().fill('Zurreal the Eternal'); + const card = page + .locator('main ol > li') + .filter({ hasText: 'Crystal Library' }) + .filter({ hasText: 'per hunt' }) + .first(); + await expect(card).toContainText('Scholar Charm'); +}); diff --git a/e2e/mice.spec.ts b/e2e/mice.spec.ts new file mode 100644 index 00000000..e1c83029 --- /dev/null +++ b/e2e/mice.spec.ts @@ -0,0 +1,24 @@ +import { expect, test } from './fixtures'; + +const results = 'main ul a[href^="/mice/"]'; + +test('Show all is still on after a visit to a mouse and Back, at the same place in the list', async ({ page }) => { + await page.goto('/mice?q=mouse'); + await expect(page.locator(results)).toHaveCount(400); + await page.getByRole('button', { name: /^Show all/ }).click(); + await expect(page.locator(results)).not.toHaveCount(400); + + const link = page.locator(results).nth(700); + await link.scrollIntoViewIfNeeded(); + const before = await page.evaluate(() => window.scrollY); + await link.click(); + await expect(page).toHaveURL(/\/mice\/[a-z0-9-]+$/); + await page.goBack(); + await expect(page).toHaveURL(/\/mice\?q=mouse$/); + await expect.poll(() => page.locator(results).count()).toBeGreaterThan(700); + await expect.poll(() => page.evaluate(() => window.scrollY)).toBeGreaterThan(before - 400); + + // A different filter starts capped again. + await page.getByLabel('Search mice by name').fill('mous'); + await expect(page.locator(results)).toHaveCount(400); +}); diff --git a/e2e/pages.spec.ts b/e2e/pages.spec.ts new file mode 100644 index 00000000..5333eed2 --- /dev/null +++ b/e2e/pages.spec.ts @@ -0,0 +1,73 @@ +import { expect, test } from './fixtures'; +import { PAGES } from './pages'; + +for (const path of PAGES) { + test(`${path} renders and hydrates`, async ({ page }) => { + const response = await page.goto(path, { waitUntil: 'networkidle' }); + expect(response?.status()).toBe(200); + await expect(page.locator('h1').first()).toBeVisible(); + await expect(page).toHaveTitle(/\S/); + }); +} + +test('an unknown page is a 404 with a way back', async ({ page, consoleErrors }) => { + const response = await page.goto('/mice/not-a-real-mouse'); + expect(response?.status()).toBe(404); + await expect(page.getByRole('link', { name: /home/i }).first()).toBeVisible(); + // The browser logs the 404 response itself. + consoleErrors.splice(0); +}); + +test('a mouse address typed from its name offers the mouse', async ({ page, consoleErrors }) => { + await page.goto('/mice/glazy'); + const suggestions = page.getByRole('region', { name: 'Were you looking for one of these?' }); + await expect(suggestions.getByRole('link', { name: /Glazy Mouse/ })).toHaveAttribute('href', '/mice/glazed'); + consoleErrors.splice(0); +}); + +test('the /cre short link goes to the catch rate estimator', async ({ page }) => { + await page.goto('/cre'); + await expect(page).toHaveURL(/\/catch-rate-estimator$/); +}); + +test('a linked page is fetched when its link is pointed at, not when it scrolls into view', async ({ page }) => { + const fetched: string[] = []; + page.on('request', (request) => { + if (request.url().includes('_rsc=')) fetched.push(new URL(request.url()).pathname); + }); + await page.goto('/groups/common', { waitUntil: 'networkidle' }); + await page.mouse.wheel(0, 4000); + await page.waitForTimeout(500); + expect(fetched).toEqual([]); + + const link = page.locator('main a[href^="/mice/"]').first(); + const href = await link.getAttribute('href'); + await link.hover(); + await expect.poll(() => fetched).toContain(href); +}); + +test('the items and mice pages arrive with their content, not waiting on JavaScript', async ({ browser }) => { + const context = await browser.newContext({ javaScriptEnabled: false }); + const page = await context.newPage(); + await page.goto('/items'); + await expect(page.getByRole('heading', { name: 'Browse by type' })).toBeVisible(); + await expect(page.locator('a[href="/items/type/weapon"]')).toBeVisible(); + await page.goto('/mice'); + await expect(page.getByRole('heading', { name: 'Browse by group' })).toBeVisible(); + await context.close(); +}); + +test('a trap effects link opens on its location, and the list is in the page without JavaScript', async ({ + page, + browser, +}) => { + await page.goto('/trap-special-effects?location=meadow'); + await expect(page.getByLabel('Location', { exact: true })).toHaveValue('meadow'); + await expect(page.getByRole('heading', { level: 2, name: 'Meadow' })).toBeVisible(); + + const context = await browser.newContext({ javaScriptEnabled: false }); + const plain = await context.newPage(); + await plain.goto('/trap-special-effects'); + await expect(plain.getByRole('heading', { name: 'In many locations' })).toBeVisible(); + await context.close(); +}); diff --git a/e2e/pages.ts b/e2e/pages.ts new file mode 100644 index 00000000..60ff1282 --- /dev/null +++ b/e2e/pages.ts @@ -0,0 +1,35 @@ +/** One of each kind of page, so a page that fails to render or hydrate fails here. */ +export const PAGES = [ + '/', + '/mice', + '/mice/glazed', + '/mice/rankings', + '/groups/common', + '/items', + '/items/type/stat', + '/items/super-brie-cheese', + '/items/birthday-gift-convertible', + '/regions/gnawnia', + '/locations/meadow', + '/locations/forbidden-grove', + '/guides', + '/guides/fort-rox', + '/tools', + '/extensions', + '/spreadsheets', + '/userscripts', + '/userscripts/minluck-and-cre-tool', + '/userscripts/tags/stats', + '/minlucks', + '/titles', + '/catch-rate-estimator', + '/best-setup', + '/map-planner', + '/rank-up-calculator', + '/trap-special-effects', + '/essence-calculator', + '/queso-pump-calculator', + '/valour-rift-floors', + '/relic-hunter', + '/about', +]; diff --git a/e2e/rank-up.spec.ts b/e2e/rank-up.spec.ts new file mode 100644 index 00000000..955e74b0 --- /dev/null +++ b/e2e/rank-up.spec.ts @@ -0,0 +1,78 @@ +import { expect, test } from './fixtures'; + +const result = (page: import('@playwright/test').Page) => page.getByRole('region', { name: 'Result' }); + +async function fillBaronToCount(page: import('@playwright/test').Page) { + await page.getByLabel('Current title').selectOption({ label: 'Baron/Baroness' }); + await page.getByLabel('Progress to the next title (%)').fill('42.5'); + await page.getByLabel('Target title').selectOption({ label: 'Count/Countess' }); +} + +test('works out the wisdom and catches needed', async ({ page }) => { + await page.goto('/rank-up-calculator'); + await fillBaronToCount(page); + await expect(result(page)).toContainText('4,900,621'); + await page.getByLabel(/In catches of/).fill('Glazy'); + await page.getByRole('option', { name: 'Glazy Mouse' }).click(); + await expect(result(page)).toContainText('1,362 catches of Glazy Mouse'); + await expect(page).toHaveURL(/title=baron_baroness.*progress=42\.5.*mouse=Glazy/); +}); + +test('a shared link opens with its entries', async ({ page }) => { + await page.goto('/rank-up-calculator?title=baron_baroness&target=count_countess&progress=42.5&mouse=Glazy'); + await expect(result(page)).toContainText('4,900,621'); + await expect(result(page)).toContainText('1,362 catches of Glazy Mouse'); +}); + +test('a return visit picks up where it left off', async ({ page }) => { + await page.goto('/rank-up-calculator'); + await fillBaronToCount(page); + await expect(result(page)).toContainText('4,900,621'); + await page.goto('/rank-up-calculator'); + await expect(result(page)).toContainText('4,900,621'); + await expect(page.getByLabel('Current title')).toHaveValue(/\d+/); +}); + +test('exact wisdom replaces the title and progress', async ({ page }) => { + await page.goto('/rank-up-calculator'); + await page.getByLabel(/Exact wisdom/).fill('7500000'); + await expect(page.getByLabel(/Exact wisdom/)).toHaveValue('7,500,000'); + await expect(page.getByLabel('Progress to the next title (%)')).toBeDisabled(); + // On a first visit the target is Recruit; the wisdom is past that, so the target moves on from where it is. + await expect(result(page)).toContainText('Wisdom needed for Count/Countess'); + await expect(page.getByLabel('Target title').locator('option').first()).toHaveText('Count/Countess'); +}); + +test('the mouse list only loads when it is wanted', async ({ page }) => { + const requested: string[] = []; + page.on('request', (request) => requested.push(request.url())); + await page.goto('/rank-up-calculator', { waitUntil: 'networkidle' }); + const before = requested.length; + await page.getByLabel(/In catches of/).fill('Glaz'); + await expect(page.getByRole('option', { name: 'Glazy Mouse' })).toBeVisible(); + expect(requested.length).toBeGreaterThan(before); +}); + +test('entries from the last visit go into the address, and Start over clears them', async ({ page }) => { + await page.goto('/rank-up-calculator'); + await fillBaronToCount(page); + await expect(result(page)).toContainText('4,900,621'); + await page.goto('/rank-up-calculator'); + await expect(page).toHaveURL(/title=baron_baroness.*progress=42\.5/); + + await page.getByRole('button', { name: 'Start over' }).click(); + await expect(page.getByLabel('Progress to the next title (%)')).toHaveValue(''); + await expect(page).toHaveURL(/\/rank-up-calculator$/); + await page.reload(); + await expect(page.getByLabel('Current title').locator('option:checked')).toHaveText('Novice'); +}); + +test('wisdom per hunt from the estimator goes on top of the saved entries', async ({ page }) => { + await page.goto('/rank-up-calculator'); + await fillBaronToCount(page); + await expect(result(page)).toContainText('4,900,621'); + await page.goto('/rank-up-calculator?perhunt=500'); + await expect(result(page)).toContainText('4,900,621'); + await expect(result(page)).toContainText('About 9,802 hunts at 500 wisdom a hunt.'); + await expect(page).toHaveURL(/title=baron_baroness.*perhunt=500/); +}); diff --git a/e2e/rankings.spec.ts b/e2e/rankings.spec.ts new file mode 100644 index 00000000..111bd6e9 --- /dev/null +++ b/e2e/rankings.spec.ts @@ -0,0 +1,81 @@ +import { expect, test } from './fixtures'; + +const rows = 'main tbody tr'; + +test('shows 100 mice and loads more on scroll', async ({ page }) => { + await page.goto('/mice/rankings'); + await expect(page.locator(rows)).toHaveCount(100); + await page.getByRole('button', { name: /^Show 100 more of/ }).scrollIntoViewIfNeeded(); + await expect(page.locator(rows)).toHaveCount(200); +}); + +test('ranks are shared on ties and kept when filtering', async ({ page }) => { + await page.goto('/mice/rankings?by=points'); + const ranks = await page.locator(`${rows} td:first-child`).allInnerTexts(); + expect(ranks.slice(0, 5)).toEqual(['1', '2', '3', '3', '3']); + + await page.getByRole('searchbox', { name: 'Find a mouse' }).fill('glazy'); + await expect(page.locator(rows)).toHaveCount(1); + await expect(page.locator(rows).first()).toContainText('Glazy Mouse'); + await expect(page.locator(`${rows} td:first-child`).first()).not.toHaveText('1'); + + await page.getByRole('searchbox', { name: 'Find a mouse' }).fill('zzzz'); + await expect(page.getByText('No mice match “zzzz”.')).toBeVisible(); +}); + +test('sorting keeps the choice in the URL', async ({ page }) => { + await page.goto('/mice/rankings'); + await page.getByRole('button', { name: 'Wisdom' }).click(); + await expect(page).toHaveURL(/by=wisdom/); + await expect(page.getByRole('button', { name: 'Wisdom' })).toHaveAttribute('aria-pressed', 'true'); + await page.getByLabel('Group').selectOption('Event Mice'); + await expect(page).toHaveURL(/group=Event\+Mice/); +}); + +test('a rank on a mouse page lands on that mouse, highlighted, even far down the list', async ({ page }) => { + await page.goto('/mice/draconic-warden'); + await page + .getByRole('link', { name: /^[\d,]+$/ }) + .nth(1) + .click(); + await expect(page).toHaveURL(/\/mice\/rankings\?by=gold&mouse=draconic-warden/); + const row = page.locator('#draconic-warden'); + await expect(row).toBeInViewport(); + await expect(row).toHaveClass(/bg-pink-50/); + // Centred, not stuck under the header or at the bottom. + const box = await row.boundingBox(); + expect(box?.y).toBeGreaterThan(200); + expect(box?.y).toBeLessThan(700); +}); + +test('the name filter goes in the address, and an empty result can be cleared', async ({ page }) => { + await page.goto('/mice/rankings'); + const search = page.getByRole('searchbox', { name: 'Find a mouse' }); + await search.fill('glazy'); + await expect(page).toHaveURL(/q=glazy/); + + await page.goto('/mice/rankings?by=gold&q=glazy'); + await expect(page.locator(rows)).toHaveCount(1); + + await search.fill('zzzz'); + await page.getByRole('button', { name: 'Clear the search' }).click(); + await expect(page.locator(rows)).toHaveCount(100); + await expect(search).toBeFocused(); +}); + +test('going to a mouse and Back returns to the same place in a long list', async ({ page }) => { + await page.goto('/mice/rankings'); + for (const count of [200, 300]) { + await page.getByRole('button', { name: /^Show 100 more of/ }).scrollIntoViewIfNeeded(); + await expect(page.locator(rows)).toHaveCount(count); + } + const link = page.locator(rows).nth(250).getByRole('link'); + await link.scrollIntoViewIfNeeded(); + const before = await page.evaluate(() => window.scrollY); + await link.click(); + await expect(page.getByRole('heading', { level: 1 })).not.toHaveText('Mice ranked'); + await page.goBack(); + await expect(page.getByRole('heading', { level: 1 })).toHaveText('Mice ranked'); + expect(await page.locator(rows).count()).toBeGreaterThanOrEqual(300); + await expect.poll(() => page.evaluate(() => window.scrollY)).toBeGreaterThan(before - 400); +}); diff --git a/e2e/relic-hunter.spec.ts b/e2e/relic-hunter.spec.ts new file mode 100644 index 00000000..479114d7 --- /dev/null +++ b/e2e/relic-hunter.spec.ts @@ -0,0 +1,20 @@ +import { expect, relicHunter, test } from './fixtures'; + +test('names where she is, links to it, and says how fresh that is', async ({ page }) => { + await page.goto('/relic-hunter'); + const card = page.getByRole('status').filter({ hasText: 'Currently hiding in' }); + await expect(card.getByRole('link', { name: 'Laboratory' })).toHaveAttribute('href', '/locations/laboratory'); + await expect(card).toContainText('Last seen there 20 minutes ago'); +}); + +test('a failed load offers another try', async ({ page, consoleErrors }) => { + let calls = 0; + await page.route('https://api.mouse.rip/relic-hunter', (route) => + calls++ === 0 ? route.fulfill({ status: 503, body: 'down' }) : route.fulfill({ json: relicHunter() }), + ); + await page.goto('/relic-hunter'); + await page.getByRole('button', { name: 'Try again' }).click(); + await expect(page.getByRole('status').getByRole('link', { name: 'Laboratory' })).toBeVisible(); + // The browser logs the 503 itself. + consoleErrors.splice(0); +}); diff --git a/e2e/search.spec.ts b/e2e/search.spec.ts new file mode 100644 index 00000000..b4bb7047 --- /dev/null +++ b/e2e/search.spec.ts @@ -0,0 +1,54 @@ +import { expect, test } from './fixtures'; + +test('the search box finds a mouse and opens its page', async ({ page }) => { + await page.goto('/'); + await page.keyboard.press('ControlOrMeta+k'); + const box = page.getByRole('combobox').or(page.getByRole('searchbox')).last(); + await box.fill('glazy'); + await expect(page.getByRole('option').first()).toContainText('Glazy Mouse'); + await page.keyboard.press('Enter'); + await expect(page).toHaveURL(/\/mice\/glazed$/); + await expect(page.getByRole('heading', { level: 1 })).toHaveText(/Glazy/); +}); + +test('search copes with typos and everyday words', async ({ page }) => { + await page.goto('/'); + await page.keyboard.press('ControlOrMeta+k'); + const box = page.getByRole('combobox').or(page.getByRole('searchbox')).last(); + for (const [query, first] of [ + ['relc hunter', 'Relic Hunter'], + ["i'm new", 'MouseHunt Essentials Guide'], + ['tse', 'Trap and base special effects'], + ]) { + await box.fill(query); + await expect(page.getByRole('option').first()).toContainText(first); + } +}); + +test('searching from the phone menu leaves the new page clear', async ({ page }) => { + await page.setViewportSize({ width: 390, height: 844 }); + await page.goto('/about'); + await page.getByRole('button', { name: 'Open navigation' }).click(); + await page + .getByRole('dialog') + .getByRole('button', { name: /Search/ }) + .click(); + const box = page.getByRole('combobox'); + await expect(box).toBeFocused(); + await box.fill('glazy'); + await expect(page.getByRole('option').first()).toContainText('Glazy Mouse'); + await page.keyboard.press('Enter'); + await expect(page).toHaveURL(/\/mice\/glazed$/); + await expect(page.getByRole('dialog')).toHaveCount(0); + await expect(page.getByRole('heading', { level: 1 })).toBeInViewport(); +}); + +test('“timers” opens the site’s own timers', async ({ page }) => { + await page.goto('/about'); + await page.keyboard.press('ControlOrMeta+k'); + await page.getByRole('combobox').fill('timers'); + await expect(page.getByRole('option').first()).toContainText('Location timers'); + await page.keyboard.press('Enter'); + await expect(page).toHaveURL(/\/#timers-heading$/); + await expect(page.getByRole('heading', { name: 'Right now' })).toBeInViewport(); +}); diff --git a/e2e/social-card.spec.ts b/e2e/social-card.spec.ts new file mode 100644 index 00000000..9980d8e3 --- /dev/null +++ b/e2e/social-card.spec.ts @@ -0,0 +1,20 @@ +import { expect, test } from './fixtures'; + +test('a card link the site didn’t sign gets the site-wide card, not its own words', async ({ request }) => { + for (const link of ['/og/card?title=Anything+at+all', '/og/card?title=Common&sig=0123456789abcdef0123456789abcdef']) { + const response = await request.get(link, { maxRedirects: 0 }); + expect(response.status()).toBe(302); + expect(response.headers().location).toBe('/og'); + } +}); + +test('a page’s own card link renders', async ({ page, request }) => { + // A tool's card draws an icon, not a picture, so rendering it asks nothing of the image host. + await page.goto('/catch-rate-estimator'); + const card = await page.locator('meta[property="og:image"]').getAttribute('content'); + test.skip(!card?.includes('/og/card'), 'Built without OG_CARD_SECRET, so pages use the site-wide card.'); + const { pathname, search } = new URL(card!); + const response = await request.get(pathname + search, { maxRedirects: 0 }); + expect(response.status()).toBe(200); + expect(response.headers()['content-type']).toBe('image/png'); +}); diff --git a/e2e/timers.spec.ts b/e2e/timers.spec.ts new file mode 100644 index 00000000..b95dd675 --- /dev/null +++ b/e2e/timers.spec.ts @@ -0,0 +1,30 @@ +import { expect, test, timers } from './fixtures'; + +test('timers come back by themselves after a failed first load', async ({ page, consoleErrors }) => { + let calls = 0; + await page.route('https://api.mouse.rip/timers', (route) => + calls++ === 0 ? route.fulfill({ status: 503, body: 'down' }) : route.fulfill({ json: timers() }), + ); + await page.clock.install(); + await page.goto('/'); + await expect(page.getByText('Location timers are unavailable right now.')).toBeVisible(); + // The clock ticks every 30 seconds, and a tick with nothing loaded tries again. + await page.clock.fastForward(31_000); + await expect(page.getByText('Forbidden Grove')).toBeVisible(); + // The browser logs the 503 itself. + consoleErrors.splice(0); +}); + +test('a timers response that has changed shape counts as unavailable, not a crash', async ({ page }) => { + await page.route('https://api.mouse.rip/timers', (route) => route.fulfill({ json: { locations: 'soon' } })); + await page.goto('/', { waitUntil: 'networkidle' }); + await expect(page.getByText('Location timers are unavailable right now.')).toBeVisible(); + await expect(page.getByRole('heading', { level: 1 })).toBeVisible(); +}); + +test('the home page writes out when each stage ends and when the day resets', async ({ page }) => { + await page.goto('/'); + const card = page.getByRole('link', { name: /Forbidden Grove/ }); + await expect(card).toContainText(/ends in 2h 0m\s*\w{3} \d{1,2}:\d{2}/); + await expect(page.getByText(/Daily reset in 10h 0m · \w{3} \d{1,2}:\d{2}/)).toBeVisible(); +}); diff --git a/next.config.ts b/next.config.ts index 005851dd..35d90b33 100644 --- a/next.config.ts +++ b/next.config.ts @@ -1,10 +1,46 @@ import type { NextConfig } from 'next'; +/** + * What the pages load today, written down as a policy. + * + * Sent as Report-Only for now: the browser logs anything that would break it without blocking, so it can be + * checked on the live site (Cloudflare can add scripts of its own) before it's enforced. 'unsafe-inline' stays + * because prerendered pages carry inline bootstrap scripts, which rules out per-request nonces. + */ +const CONTENT_SECURITY_POLICY = [ + "default-src 'self'", + "script-src 'self' 'unsafe-inline'", + "style-src 'self' 'unsafe-inline'", + "img-src 'self' data: https://i.mouse.rip", + "font-src 'self'", + "connect-src 'self' https://api.mouse.rip https://api.markethunt.win", + "object-src 'none'", + "base-uri 'self'", + "form-action 'self'", + "frame-ancestors 'self'", +].join('; '); + const nextConfig: NextConfig = { + // Nobody needs to be told which framework this is. + poweredByHeader: false, async redirects() { return [ + // A short link hunters pass around. It used to live in a Cloudflare Pages _redirects file, which Workers + // doesn't read. + { source: '/cre', destination: '/catch-rate-estimator', permanent: true }, // Prices are on each item's page now. { source: '/marketplace', destination: '/items?tradable=1', permanent: true }, + // Retired userscripts that a listed one replaces. + { + source: '/userscripts/minluck-and-catch-rate-estimate', + destination: '/userscripts/minluck-and-cre-tool', + permanent: true, + }, + { + source: '/userscripts/449489-mousehunt-better-gifts-gift-buttons', + destination: '/userscripts/gifting-buttons', + permanent: true, + }, ]; }, async headers() { @@ -16,6 +52,14 @@ const nextConfig: NextConfig = { { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' }, { key: 'X-Frame-Options', value: 'SAMEORIGIN' }, { key: 'Content-Security-Policy', value: "frame-ancestors 'self'" }, + // The site already redirects http to https; this tells browsers to skip the http request next time. + { key: 'Strict-Transport-Security', value: 'max-age=31536000' }, + // The site uses none of these, so nothing embedded in it can ask for them either. + { key: 'Permissions-Policy', value: 'camera=(), microphone=(), geolocation=(), payment=(), usb=()' }, + // `next dev` needs eval for hot reloading, which would fill the console with reports. + ...(process.env.NODE_ENV === 'production' + ? [{ key: 'Content-Security-Policy-Report-Only', value: CONTENT_SECURITY_POLICY }] + : []), ], }, { diff --git a/package.json b/package.json index 3d187738..907abf75 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ "cf-typegen": "wrangler types --env-interface CloudflareEnv ./cloudflare-env.d.ts", "cf:build": "opennextjs-cloudflare build", "cf:deploy": "opennextjs-cloudflare deploy", - "check": "bun run lint && bun run format:check && bunx tsc --noEmit", + "check": "bun run lint && bun run format:check && bunx tsc --noEmit && bun run test", "dev": "next dev --turbopack", "deploy": "opennextjs-cloudflare build && opennextjs-cloudflare deploy", "format": "oxfmt .", @@ -17,8 +17,11 @@ "lint:fix": "oxlint --fix .", "preview": "opennextjs-cloudflare build && opennextjs-cloudflare preview", "start": "next start", + "test": "bun test", + "test:e2e": "playwright test", "update": "bun run update:data && bun run update:images", "update:data": "bun ./scripts/update-data.js", + "update:trap-effects": "bun ./scripts/update-trap-effects.js", "update:images": "bun ./scripts/update-images.js" }, "dependencies": { @@ -26,26 +29,25 @@ "@heroicons/react": "^2.2.0", "@opennextjs/cloudflare": "^1.20.8", "clsx": "^2.1.1", - "framer-motion": "^12.38.0", - "next": "^16.4.3", + "next": "^16.4.6", "next-view-transitions": "^0.3.5", "postcss": "^8.5.10", "react": "^19.2.5", "react-dom": "^19.2.5", "react-markdown": "^10.1.0", - "react-virtualized-auto-sizer": "^1.0.26", - "react-window": "^1.8.11", "rehype-raw": "^7.0.0", "remark-gfm": "^4.0.1", "zod": "^3.25.76" }, "devDependencies": { + "@axe-core/playwright": "^4.14.1", "@clack/prompts": "^0.11.0", + "@playwright/test": "^1.65.1", "@tailwindcss/postcss": "^4.2.2", + "@types/bun": "^1.4.5", "@types/node": "^20.19.39", "@types/react": "^19.2.14", "@types/react-dom": "^19.2.3", - "@types/react-window": "^1.8.8", "oxfmt": "^0.62.0", "oxlint": "^1.76.0", "tailwindcss": "^4.2.2", diff --git a/playwright.config.ts b/playwright.config.ts new file mode 100644 index 00000000..2741077d --- /dev/null +++ b/playwright.config.ts @@ -0,0 +1,31 @@ +import { defineConfig, devices } from '@playwright/test'; + +/** + * Browser tests against a production build. Run `bun run build` first; `bun run test:e2e` then starts the + * built site on port 3100. To test a server that's already running (`bun run dev`, say), set + * E2E_BASE_URL=http://localhost:3000. + */ +const external = process.env.E2E_BASE_URL; +const baseURL = external ?? 'http://localhost:3100'; + +export default defineConfig({ + testDir: './e2e', + fullyParallel: true, + forbidOnly: Boolean(process.env.CI), + retries: process.env.CI ? 1 : 0, + reporter: process.env.CI ? [['github'], ['list']] : 'list', + use: { + baseURL, + trace: 'retain-on-failure', + ...devices['Desktop Chrome'], + viewport: { width: 1280, height: 900 }, + }, + webServer: external + ? undefined + : { + command: 'bunx next start -p 3100', + url: baseURL, + reuseExistingServer: !process.env.CI, + timeout: 120_000, + }, +}); diff --git a/public/_headers b/public/_headers index fcf9539e..069fb609 100644 --- a/public/_headers +++ b/public/_headers @@ -1,3 +1,11 @@ # https://developers.cloudflare.com/workers/static-assets/headers /_next/static/* Cache-Control: public,max-age=31536000,immutable + +# Not content-hashed, so a week and a grace period, the same as i.mouse.rip. +/images/* + Cache-Control: public,max-age=604800,stale-while-revalidate=86400 + +# Static files are served before the worker runs, so next.config.ts's headers don't reach them. +/* + X-Content-Type-Options: nosniff diff --git a/public/images/essence/small/aleth.png b/public/images/essence/small/aleth.png new file mode 100644 index 00000000..bf1ee54f Binary files /dev/null and b/public/images/essence/small/aleth.png differ diff --git a/public/images/essence/small/ber.png b/public/images/essence/small/ber.png new file mode 100644 index 00000000..bc94a744 Binary files /dev/null and b/public/images/essence/small/ber.png differ diff --git a/public/images/essence/small/cynd.png b/public/images/essence/small/cynd.png new file mode 100644 index 00000000..fe80b220 Binary files /dev/null and b/public/images/essence/small/cynd.png differ diff --git a/public/images/essence/small/dol.png b/public/images/essence/small/dol.png new file mode 100644 index 00000000..0f04d6fa Binary files /dev/null and b/public/images/essence/small/dol.png differ diff --git a/public/images/essence/small/est.png b/public/images/essence/small/est.png new file mode 100644 index 00000000..e4ca2392 Binary files /dev/null and b/public/images/essence/small/est.png differ diff --git a/public/images/essence/small/fel.png b/public/images/essence/small/fel.png new file mode 100644 index 00000000..4d3cb7d0 Binary files /dev/null and b/public/images/essence/small/fel.png differ diff --git a/public/images/essence/small/gur.png b/public/images/essence/small/gur.png new file mode 100644 index 00000000..1fde2580 Binary files /dev/null and b/public/images/essence/small/gur.png differ diff --git a/public/images/essence/small/hix.png b/public/images/essence/small/hix.png new file mode 100644 index 00000000..c4b2abac Binary files /dev/null and b/public/images/essence/small/hix.png differ diff --git a/public/images/essence/small/icuri.png b/public/images/essence/small/icuri.png new file mode 100644 index 00000000..06eaf989 Binary files /dev/null and b/public/images/essence/small/icuri.png differ diff --git a/public/images/guides/fort-rox-8.png b/public/images/guides/fort-rox-8.png deleted file mode 100644 index 144f4ea9..00000000 Binary files a/public/images/guides/fort-rox-8.png and /dev/null differ diff --git a/public/images/items/large/airship-balloon-vrift-stat-item.png b/public/images/items/large/airship-balloon-vrift-stat-item.png new file mode 100644 index 00000000..6d8f6a49 Binary files /dev/null and b/public/images/items/large/airship-balloon-vrift-stat-item.png differ diff --git a/public/images/items/large/cerulean-chrome-ingot-stat-item.png b/public/images/items/large/cerulean-chrome-ingot-stat-item.png new file mode 100644 index 00000000..3c8f5027 Binary files /dev/null and b/public/images/items/large/cerulean-chrome-ingot-stat-item.png differ diff --git a/public/images/items/large/chrome-dragon-slayer-cannon-kit-crafting-item.png b/public/images/items/large/chrome-dragon-slayer-cannon-kit-crafting-item.png new file mode 100644 index 00000000..2fee8bc7 Binary files /dev/null and b/public/images/items/large/chrome-dragon-slayer-cannon-kit-crafting-item.png differ diff --git a/public/images/items/large/dragons-eye-stat-item.png b/public/images/items/large/dragons-eye-stat-item.png new file mode 100644 index 00000000..6621a46b Binary files /dev/null and b/public/images/items/large/dragons-eye-stat-item.png differ diff --git a/public/images/items/large/idea-germ-stat-item.png b/public/images/items/large/idea-germ-stat-item.png new file mode 100644 index 00000000..174e699e Binary files /dev/null and b/public/images/items/large/idea-germ-stat-item.png differ diff --git a/public/images/items/large/mythical-dragon-heart-stat-item.png b/public/images/items/large/mythical-dragon-heart-stat-item.png new file mode 100644 index 00000000..7cde47fb Binary files /dev/null and b/public/images/items/large/mythical-dragon-heart-stat-item.png differ diff --git a/public/images/items/large/mythical-rainbow-diamond-convertible.png b/public/images/items/large/mythical-rainbow-diamond-convertible.png new file mode 100644 index 00000000..851c0fb5 Binary files /dev/null and b/public/images/items/large/mythical-rainbow-diamond-convertible.png differ diff --git a/public/images/items/large/origin-of-dragons-scroll-case-convertible.png b/public/images/items/large/origin-of-dragons-scroll-case-convertible.png new file mode 100644 index 00000000..5fd33a2a Binary files /dev/null and b/public/images/items/large/origin-of-dragons-scroll-case-convertible.png differ diff --git a/public/images/items/large/sb-supply-pack.png b/public/images/items/large/sb-supply-pack.png new file mode 100644 index 00000000..6a364404 Binary files /dev/null and b/public/images/items/large/sb-supply-pack.png differ diff --git a/public/images/items/large/winter-hunt-2025-journal-theme-collectible.png b/public/images/items/large/winter-hunt-2025-journal-theme-collectible.png new file mode 100644 index 00000000..b7be10d8 Binary files /dev/null and b/public/images/items/large/winter-hunt-2025-journal-theme-collectible.png differ diff --git a/public/images/logo-72.png b/public/images/logo-72.png new file mode 100644 index 00000000..1b183dca Binary files /dev/null and b/public/images/logo-72.png differ diff --git a/public/images/stats/luck.png b/public/images/stats/luck.png new file mode 100644 index 00000000..89924f59 Binary files /dev/null and b/public/images/stats/luck.png differ diff --git a/public/images/titles/apprentice.png b/public/images/titles/apprentice.png new file mode 100644 index 00000000..16f624a9 Binary files /dev/null and b/public/images/titles/apprentice.png differ diff --git a/public/images/titles/archduke-archduchess.png b/public/images/titles/archduke-archduchess.png new file mode 100644 index 00000000..24f4cd14 Binary files /dev/null and b/public/images/titles/archduke-archduchess.png differ diff --git a/public/images/titles/baron-baroness.png b/public/images/titles/baron-baroness.png new file mode 100644 index 00000000..7af9b5d3 Binary files /dev/null and b/public/images/titles/baron-baroness.png differ diff --git a/public/images/titles/count-countess.png b/public/images/titles/count-countess.png new file mode 100644 index 00000000..95a02b78 Binary files /dev/null and b/public/images/titles/count-countess.png differ diff --git a/public/images/titles/duke-dutchess.png b/public/images/titles/duke-dutchess.png new file mode 100644 index 00000000..ae4150d0 Binary files /dev/null and b/public/images/titles/duke-dutchess.png differ diff --git a/public/images/titles/elder.png b/public/images/titles/elder.png new file mode 100644 index 00000000..fe88f75d Binary files /dev/null and b/public/images/titles/elder.png differ diff --git a/public/images/titles/fabled.png b/public/images/titles/fabled.png new file mode 100644 index 00000000..e69316cf Binary files /dev/null and b/public/images/titles/fabled.png differ diff --git a/public/images/titles/grand-duke.png b/public/images/titles/grand-duke.png new file mode 100644 index 00000000..9061f44b Binary files /dev/null and b/public/images/titles/grand-duke.png differ diff --git a/public/images/titles/grandmaster.png b/public/images/titles/grandmaster.png new file mode 100644 index 00000000..a1f86840 Binary files /dev/null and b/public/images/titles/grandmaster.png differ diff --git a/public/images/titles/hero.png b/public/images/titles/hero.png new file mode 100644 index 00000000..ea9c13bd Binary files /dev/null and b/public/images/titles/hero.png differ diff --git a/public/images/titles/initiate.png b/public/images/titles/initiate.png new file mode 100644 index 00000000..8991c5ed Binary files /dev/null and b/public/images/titles/initiate.png differ diff --git a/public/images/titles/journeyman.png b/public/images/titles/journeyman.png new file mode 100644 index 00000000..04e53cf8 Binary files /dev/null and b/public/images/titles/journeyman.png differ diff --git a/public/images/titles/knight.png b/public/images/titles/knight.png new file mode 100644 index 00000000..0e5c10b9 Binary files /dev/null and b/public/images/titles/knight.png differ diff --git a/public/images/titles/legendary.png b/public/images/titles/legendary.png new file mode 100644 index 00000000..04a6e836 Binary files /dev/null and b/public/images/titles/legendary.png differ diff --git a/public/images/titles/lord-lady.png b/public/images/titles/lord-lady.png new file mode 100644 index 00000000..d9bfbe76 Binary files /dev/null and b/public/images/titles/lord-lady.png differ diff --git a/public/images/titles/master.png b/public/images/titles/master.png new file mode 100644 index 00000000..7a3d553d Binary files /dev/null and b/public/images/titles/master.png differ diff --git a/public/images/titles/novice.png b/public/images/titles/novice.png new file mode 100644 index 00000000..46f76711 Binary files /dev/null and b/public/images/titles/novice.png differ diff --git a/public/images/titles/recruit.png b/public/images/titles/recruit.png new file mode 100644 index 00000000..b72bfa5d Binary files /dev/null and b/public/images/titles/recruit.png differ diff --git a/public/images/titles/sage.png b/public/images/titles/sage.png new file mode 100644 index 00000000..0858c137 Binary files /dev/null and b/public/images/titles/sage.png differ diff --git a/public/images/titles/viceroy.png b/public/images/titles/viceroy.png new file mode 100644 index 00000000..2de2f28c Binary files /dev/null and b/public/images/titles/viceroy.png differ diff --git a/scripts/add-item.js b/scripts/add-item.js index b690914d..966818b1 100644 --- a/scripts/add-item.js +++ b/scripts/add-item.js @@ -39,7 +39,9 @@ async function addItem() { .replace(/^www\./, '') .replace(/\..+$/, '') .replace(/^\w/, (c) => c.toUpperCase()); - } catch {} + } catch { + // Not a full URL yet, so there's no hostname to suggest a source from. + } } return text({ @@ -116,7 +118,6 @@ async function addItem() { } } - // add tags only for userscripts let tags = []; if ('userscript' === item.category) { const tagsInput = await text({ diff --git a/scripts/catch-rate-data.js b/scripts/catch-rate-data.js new file mode 100644 index 00000000..d0c90692 --- /dev/null +++ b/scripts/catch-rate-data.js @@ -0,0 +1,133 @@ +/** + * Builds src/data/generated/catch-rate.json: everything the catch rate estimator and Best Setup need, in one + * compact file the browser loads when someone opens either tool. + * + * - Populations, from api.mouse.rip/attraction: which mice each location, stage, cheese and charm attracts. + * - Mice: power and effectiveness against each power type. + * - Weapons, bases and charms with their stats, from the game's item data. + * - The mouse groups the special cases need (dragons, weremice, chess pieces…), from api.mouse.rip/cre-mice-groups. + * + * Names are stored once in lookup tables and the populations point into them by index. + */ + +/** The game's cheese-effect names, as freshness steps from -6 to 6. */ +export const FRESHNESS = { + 'Uber Stale': -6, + 'Ultimately Stale': -5, + 'Insanely Stale': -4, + 'Extremely Stale': -3, + 'Very Stale': -2, + Stale: -1, + 'No Effect': 0, + Fresh: 1, + 'Very Fresh': 2, + 'Extremely Fresh': 3, + 'Insanely Fresh': 4, + 'Ultimately Fresh': 5, + 'Uber Fresh': 6, +}; + +/** Power types in the order each mouse's effectiveness is stored. */ +export const POWER_TYPE_ORDER = [ + 'arcane', + 'draconic', + 'forgotten', + 'hydro', + 'law', + 'physical', + 'rift', + 'shadow', + 'tactical', +]; + +const percent = (fraction) => Math.round((fraction ?? 0) * 1000) / 10; + +/** [type, name, powerType, power, bonus %, attraction %, luck, freshness] for a weapon, base or charm. */ +function itemRow(item) { + const stats = item.has_stats && typeof item.has_stats === 'object' ? item.has_stats : {}; + return [ + item.type, + item.name, + stats.power_type || '', + stats.power ?? 0, + percent(stats.power_bonus), + percent(stats.attraction_bonus), + stats.luck ?? 0, + FRESHNESS[stats.cheese_effect] ?? 0, + ]; +} + +const byName = (a, b) => a[1].localeCompare(b[1]); + +export function buildCatchRateData({ attraction, mice, items, groups }) { + const ofClass = (classification) => + items + .filter((item) => item.classification === classification) + .map(itemRow) + .sort(byName); + const weapons = ofClass('weapon'); + const bases = ofClass('base'); + const charms = ofClass('trinket'); + + const locations = []; + const stages = ['-']; + const cheeses = []; + const charmTypes = ['-']; + const index = (list, value, key = (entry) => entry) => { + let at = list.findIndex((entry) => key(entry) === value); + if (at === -1) at = list.push(value) - 1; + return at; + }; + const locationIndex = new Map(); + const cheeseIndex = new Map(); + const mouseIndex = new Map(mice.map((mouse, i) => [mouse.type, i])); + + const populations = []; + for (const record of attraction) { + if (!locationIndex.has(record.location)) { + locationIndex.set(record.location, locations.push({ id: record.location, name: record.location_name }) - 1); + } + if (!cheeseIndex.has(record.cheese)) { + cheeseIndex.set(record.cheese, cheeses.push({ type: record.cheese, name: record.cheese_name }) - 1); + } + const row = [ + locationIndex.get(record.location), + index(stages, record.stage || '-'), + cheeseIndex.get(record.cheese), + index(charmTypes, record.charm || '-'), + record.source === 'mhct' ? 0 : 1, + record.sample_size ?? 0, + ]; + for (const mouse of record.mice) { + const at = mouseIndex.get(mouse.type); + if (at === undefined || !(mouse.rate > 0)) continue; + row.push(at, Math.round(mouse.rate * 100)); + } + if (row.length > 6) populations.push(row); + } + + return { + locations, + stages, + cheeses, + // Charms a population is specific to, by type; '-' is no particular charm. + populationCharms: charmTypes, + populations, + mice: mice.map((mouse) => { + const eff = mouse.effectivenesses ?? {}; + return [ + mouse.type, + mouse.name, + eff.power ?? 0, + ...POWER_TYPE_ORDER.map((type) => eff[type] ?? 0), + mouse.points ?? 0, + mouse.gold ?? 0, + mouse.wisdom ?? 0, + ]; + }), + weapons, + bases, + charms, + groups, + }; +} diff --git a/scripts/image-signature.js b/scripts/image-signature.js new file mode 100644 index 00000000..41d0f8ed --- /dev/null +++ b/scripts/image-signature.js @@ -0,0 +1,29 @@ +import fs from 'node:fs'; + +/** + * The image format a file's first bytes say it is, or null when they aren't an image we serve. + * + * A server can answer 200 with an HTML error page, or a download can stop short, and either would + * otherwise be saved under a .png name and published as a broken image. + */ +export function imageType(bytes) { + if (!bytes || bytes.length < 4) return null; + const at = (offset, values) => values.every((value, i) => bytes[offset + i] === value); + if (at(0, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return 'png'; + if (at(0, [0xff, 0xd8, 0xff])) return 'jpeg'; + if (at(0, [0x47, 0x49, 0x46, 0x38])) return 'gif'; + if (bytes.length >= 12 && at(0, [0x52, 0x49, 0x46, 0x46]) && at(8, [0x57, 0x45, 0x42, 0x50])) return 'webp'; + return null; +} + +/** imageType() for a file on disk, reading only its first bytes. */ +export function fileImageType(file) { + const fd = fs.openSync(file, 'r'); + try { + const bytes = Buffer.alloc(12); + const read = fs.readSync(fd, bytes, 0, 12, 0); + return imageType(bytes.subarray(0, read)); + } finally { + fs.closeSync(fd); + } +} diff --git a/scripts/update-data.js b/scripts/update-data.js index 3fc3e11a..66b1357a 100644 --- a/scripts/update-data.js +++ b/scripts/update-data.js @@ -1,6 +1,8 @@ import fs from 'node:fs'; import path from 'node:path'; +import { buildCatchRateData } from './catch-rate-data.js'; + const DATA_DIR = path.join(__dirname, '../src/data/generated'); // Override to update from a local `wrangler dev` of the API. const API_URL = process.env.API_URL ?? 'https://api.mouse.rip'; @@ -69,7 +71,12 @@ const requireRecord = (value, label) => { // Labels allowed to shrink past the coverage floor on this run, for when the API // deliberately serves less (e.g. ALLOW_SHRINK=item-drops,location-loot). -const ALLOW_SHRINK = new Set((process.env.ALLOW_SHRINK ?? '').split(',').map((label) => label.trim()).filter(Boolean)); +const ALLOW_SHRINK = new Set( + (process.env.ALLOW_SHRINK ?? '') + .split(',') + .map((label) => label.trim()) + .filter(Boolean), +); export const validateMinimumCoverage = (label, currentCount, previousCount, ratio = 0.9) => { const minimum = Math.max(1, Math.floor(previousCount * ratio)); @@ -85,6 +92,23 @@ export const validateMinimumCoverage = (label, currentCount, previousCount, rati } }; +// The game API sometimes returns names HTML-escaped (e.g. "<3 Gift Basket", +// without the semicolon). React renders those literally, so decode them once here. +const NAME_KEYS = new Set(['name', 'mouse_name', 'abbreviated_name', 'convertible']); +const ENTITIES = { lt: '<', gt: '>', amp: '&', quot: '"', apos: "'", '#39': "'" }; + +const decodeEntities = (value) => value.replace(/&(lt|gt|amp|quot|apos|#39);?/g, (_, entity) => ENTITIES[entity]); + +const decodeNameEntities = (value) => { + if (Array.isArray(value)) return value.map(decodeNameEntities); + if (value && 'object' === typeof value) { + for (const [key, child] of Object.entries(value)) { + value[key] = NAME_KEYS.has(key) && 'string' === typeof child ? decodeEntities(child) : decodeNameEntities(child); + } + } + return value; +}; + const updateDataFiles = async () => { const files = [ { file: 'environments-events', shape: 'array', validateCoverage: false }, @@ -193,6 +217,8 @@ const updateDataFiles = async () => { group: mouse.group, subgroup: mouse.subgroup, minlucks: mouse.minlucks, + // For the rank-up calculator's "in catches of" answer. + wisdom: mouse.wisdom, eff: Object.keys(eff).length > 0 ? eff : undefined, }; }); @@ -213,7 +239,9 @@ const fetchJson = async (endpoint) => { if (undefined === json || null === json) { throw new TypeError(`${endpoint} returned no JSON data`); } - return json; + // Every response, not just the item list: names reach the site from several + // endpoints (reverse convertibles, attraction, map relations…). + return decodeNameEntities(json); }; /** @@ -252,7 +280,7 @@ export const fetchPerEntity = async ( } if (!response.ok) throw new Error(`HTTP ${response.status}`); const json = await response.json(); - rows = requireArray(json, `${label} entity ${id}`); + rows = decodeNameEntities(requireArray(json, `${label} entity ${id}`)); } catch (error) { lastError = error; if (attempt === 2) break; @@ -311,6 +339,159 @@ export const validateItemReferences = (label, ids, itemIds) => { } }; +/** + * Loot seen in at least this share of locations is left off as event or global loot. + * + * Event and global drops (Party, Snowball and Wealth charms, SUPER|brie+, Ful'Mina's Gift…) + * turn up at nearly every location, often at high rates, and would top every + * location's loot list without saying anything about the place. Real location + * loot is the opposite: almost every item drops in fewer than five locations. + */ +export const GLOBAL_LOOT_SHARE = 0.4; + +/** + * Seasonal event loot that any mouse can drop while the event runs. + * + * Lunar New Year candles, Spring Egg Hunt eggs and charge charms, Winter Hunt + * gift boxes, birthday cupcakes, the yearly charms: it reaches too few locations + * for the share rule to catch, but says nothing about the place. + * + * Listed by ID, not matched by name: plenty of real location loot shares a word + * with event loot (Golden Goose Egg in Bountiful Beanstalk, Festive Spirit in + * Cinnamon Hill), and the Great Winter Hunt's own locations keep their loot. + * Each year's new charms need adding here. + */ +export const EVENT_LOOT_IDS = new Set([ + 151, // Red Pocket Envelope + 437, // Red Winter Hunt Gift Box + 547, // Antique Green Plaid Egg + 549, // Antique Blue Argyle Egg + 550, // Antique Stripy Red Egg + 551, // Antique Wavy Purple Egg + 552, // Antique Scalloped Pink Egg + 553, // Gift Egg + 554, // Antique Sharing Egg + 555, // Antique Friendly Egg + 556, // Antique Caring Egg + 700, // Dreaded Charm + 701, // Spooky Charm + 823, // Party Charm + 1029, // Purple Winter Hunt Gift Box + 1164, // Eggscavator Charge Charm + 1228, // Sugar Rush Plushie + 1237, // Ultimate Spooky Charm + 1288, // Festive Ultimate Luck Charm + 1289, // Festive Ultimate Power Charm + 1290, // Snowball Charm + 1439, // High Charge Egg + 1442, // Low Charge Egg + 1443, // Lucky Egg + 1448, // Medium Charge Egg + 1451, // Gnawnia Rift Egg + 1576, // Super Spooky Charm + 1688, // Cupcake Charm + 1699, // Enlarged Rift Egg + 1714, // Eggstra Charge Charm + 1715, // Egg Basket Box Trap Skin + 1990, // Orange Winter Hunt Gift Box + 2038, // Extra Sweet Cupcake Charm + 2262, // 2017 Charm + 2269, // Lunar Lantern Candle + 2286, // Sprinkly Sweet Cupcake Charm + 2307, // Enerchi Egg + 2523, // Extreme Snowball Charm + 2527, // Super Snowball Charm + 2528, // Ultimate Snowball Charm + 2539, // 2018 Charm + 2547, // Red Lunar Lantern Candle + 2598, // Rainy Egg + 2603, // Windy Egg + 2701, // Extreme Spooky Charm + 2734, // 2019 Charm + 2799, // Over 9,000 Egg + 2801, // Queso Pump Egg + 2803, // Wild Tonic Egg + 2806, // Lightning Storm Egg + 2812, // Dragonshard Egg + 2957, // 2020 Charm + 2958, // Rift 2020 Charm + 2959, // Rift Extreme Snowball Charm + 2960, // Rift Snowball Charm + 2961, // Rift Super Snowball Charm + 2962, // Rift Ultimate Snowball Charm + 2990, // Extreme Party Charm + 2991, // Super Party Charm + 2992, // Ultimate Party Charm + 2995, // 20K Golden Egg + 3153, // 2021 Charm + 3154, // Rift 2021 Charm + 3366, // 2022 Charm + 3367, // Rift 2022 Charm + 3527, // 2023 Charm + 3528, // Rift 2023 Charm + 3630, // 2024 Charm + 3631, // Rift 2024 Charm + 3810, // Golden Winter Hunt Gift Box + 3817, // 2025 Charm + 3818, // Rift 2025 Charm + 3957, // 2026 Charm + 3958, // Rift 2026 Charm +]); + +/** + * Event loot that is real loot in the event's own locations but a stray drop + * anywhere else. Keyed by item ID, with the locations (as keyed in + * location-loot) where it belongs. + */ +const WINTER_HUNT_LOCATIONS = ['event area', 'cinnamon hill', 'golem workshop', 'ice fortress']; +export const EVENT_LOOT_HOMES = new Map([ + [3521, WINTER_HUNT_LOCATIONS], // Festive Spirit +]); + +/** Whether a drop at this location says something about the place rather than an event. */ +export const isLocationLoot = (itemId, location) => { + if (EVENT_LOOT_IDS.has(itemId)) return false; + const homes = EVENT_LOOT_HOMES.get(itemId); + return !homes || homes.includes(location); +}; + +export const withoutGlobalLoot = (lootByLocation) => { + const locationCount = Object.keys(lootByLocation).length; + const seenIn = new Map(); + for (const rows of Object.values(lootByLocation)) { + for (const row of rows) seenIn.set(row.id, (seenIn.get(row.id) ?? 0) + 1); + } + const isGlobal = (id) => seenIn.get(id) >= locationCount * GLOBAL_LOOT_SHARE; + return Object.fromEntries( + Object.entries(lootByLocation).map(([location, rows]) => [location, rows.filter((row) => !isGlobal(row.id))]), + ); +}; + +/** + * The most useful single place to hunt a mouse, for the search index. + * + * The highest rate without a charm, preferring rows with a real sample (MH-Tools + * rows have none and count as fine). When every row needs a charm, the charm is + * part of the answer, so it's kept. Keep in step with bestAttractionRow() in + * src/lib/attraction.ts. + */ +export const bestSpot = (rows) => { + const plain = rows.filter((row) => !row.charm); + const pool = plain.length > 0 ? plain : rows; + const trusted = pool.filter((row) => null === row.total_hunts || row.total_hunts >= 100); + const pick = [...(trusted.length > 0 ? trusted : pool)].sort((a, b) => b.rate - a.rate)[0]; + if (!pick) return undefined; + return { + location: pick.location, + stage: pick.stage ?? undefined, + cheese: pick.cheese, + charm: pick.charm ?? undefined, + rate: pick.rate, + // Null for MH-Tools rates, which publish no sample size. + hunts: pick.total_hunts ?? null, + }; +}; + /** * Pull the relational datasets the API generates. These are what let an item * page say what it opens into, what opens into it, and where a mouse is found — @@ -463,6 +644,12 @@ const updateRelationalData = async (items, mice) => { // at the location would hide that one mouse always drops it. Built from every // row, not just the ones the item pages keep. const itemsById = new Map(items.map((item) => [item.id, item])); + // The mice that live at each location. A drop recorded there from any other + // mouse came from an event visitor, not from the place itself. + const regionList = pendingFiles.has('mice-regions') + ? JSON.parse(pendingFiles.get('mice-regions')) + : readGenerated('mice-regions', []); + const nativeMice = new Map(regionList.map((region) => [region.name.toLowerCase(), new Set(region.mouse_ids)])); const lootByLocation = new Map(); for (const [mouseId, rows] of Object.entries(loot)) { const mouse = miceById.get(Number(mouseId)); @@ -470,6 +657,10 @@ const updateRelationalData = async (items, mice) => { // From one mouse at a location, a small sample is mostly charm effects and event loot. if (row.catches < MIN_LOCATION_LOOT_CATCHES) continue; const location = (DROP_LOCATION_ALIASES[row.location] ?? row.location).toLowerCase(); + const native = nativeMice.get(location); + if (native && !native.has(Number(mouseId))) continue; + if (!isLocationLoot(row.item_id, location)) continue; + const item = itemsById.get(row.item_id); const byItem = lootByLocation.get(location) ?? new Map(); lootByLocation.set(location, byItem); const current = byItem.get(row.item_id); @@ -479,7 +670,6 @@ const updateRelationalData = async (items, mice) => { ) { continue; } - const item = itemsById.get(row.item_id); byItem.set(row.item_id, { id: item.id, slug: slugify(item.type), @@ -496,11 +686,13 @@ const updateRelationalData = async (items, mice) => { validateMinimumCoverage('location-loot', lootByLocation.size, Object.keys(readGenerated('location-loot', {})).length); stage( 'location-loot', - Object.fromEntries( - [...lootByLocation].map(([location, byItem]) => [ - location, - [...byItem.values()].sort((a, b) => b.rate - a.rate || a.name.localeCompare(b.name)), - ]), + withoutGlobalLoot( + Object.fromEntries( + [...lootByLocation].map(([location, byItem]) => [ + location, + [...byItem.values()].sort((a, b) => b.rate - a.rate || a.name.localeCompare(b.name)), + ]), + ), ), ); @@ -530,9 +722,30 @@ const updateRelationalData = async (items, mice) => { Object.keys(attraction).length, Object.keys(readGenerated('mice-attraction', {})).length, ); + const storedAttraction = Object.fromEntries( + Object.entries(attraction).map(([id, rows]) => [id, best(rows, 'rate', 50)]), + ); + stage('mice-attraction', storedAttraction); + stage('map-planner', buildMapPlanner(attraction)); + + // The catch rate estimator and Best Setup: every population, with mouse and item stats to work catch rates out. + console.log('Updating catch-rate...'); + const creGroups = requireRecord(await fetchJson('cre-mice-groups'), 'cre-mice-groups'); + stage('catch-rate', buildCatchRateData({ attraction: populations, mice, items, groups: creGroups })); + + // Fold each mouse's best place to hunt into the client search index, so search + // can answer "where do I catch it" without shipping the full attraction table. + // Picked from the stored rows, so it matches what the mouse page shows. + const searchIndex = pendingFiles.has('mice-search') + ? JSON.parse(pendingFiles.get('mice-search')) + : readGenerated('mice-search', []); stage( - 'mice-attraction', - Object.fromEntries(Object.entries(attraction).map(([id, rows]) => [id, best(rows, 'rate', 50)])), + 'mice-search', + searchIndex.map((mouse) => { + const { best: _previous, ...rest } = mouse; + const spot = bestSpot(storedAttraction[mouse.id] ?? []); + return spot ? { ...rest, best: spot } : rest; + }), ); // The maps each mouse turns up on. Maps seen fewer than five times, and @@ -557,6 +770,59 @@ const updateRelationalData = async (items, mice) => { // flushPendingFiles, and only when some other file changed. }; +/** Below this, a setup can't help plan a map, so the planner never sees it. In hundredths of a percent. */ +const PLANNER_MIN_RATE = 100; + +/** + * The attraction rows the map planner needs, small enough to send to the browser. + * + * One row per mouse and setup (location, stage, cheese), without a charm where MHCT + * has that, since a charm is a choice the planner shouldn't make for you. Names are + * stored once in lookup tables and rows point into them by index. + */ +export function buildMapPlanner(attraction) { + const tables = { locations: [], stages: [''], cheeses: [], charms: [''] }; + const indexes = Object.fromEntries( + Object.keys(tables).map((key) => [key, new Map(tables[key].map((v, i) => [v, i]))]), + ); + const indexOf = (key, value) => { + let index = indexes[key].get(value); + if (index === undefined) { + index = tables[key].push(value) - 1; + indexes[key].set(value, index); + } + return index; + }; + + const mice = {}; + for (const [id, rows] of Object.entries(attraction)) { + const plain = rows.filter((row) => !row.charm); + const bySetup = new Map(); + for (const row of plain.length > 0 ? plain : rows) { + if (row.rate < PLANNER_MIN_RATE || !row.location || !row.cheese) continue; + const key = `${row.location}|${row.stage ?? ''}|${row.cheese}`; + const current = bySetup.get(key); + if (!current || row.rate > current.rate) bySetup.set(key, row); + } + if (bySetup.size === 0) continue; + mice[id] = [...bySetup.values()] + .sort((a, b) => b.rate - a.rate) + .map((row) => { + const entry = [ + indexOf('locations', row.location), + indexOf('stages', row.stage ?? ''), + indexOf('cheeses', row.cheese), + row.rate, + row.total_hunts ?? 0, + ]; + if (row.charm) entry.push(indexOf('charms', row.charm)); + return entry; + }); + } + + return { ...tables, mice }; +} + if (import.meta.main) { updateDataFiles().catch((error) => { console.error(error); diff --git a/scripts/update-images.js b/scripts/update-images.js index ee944c6e..c2e4b636 100644 --- a/scripts/update-images.js +++ b/scripts/update-images.js @@ -1,8 +1,11 @@ import fs from 'node:fs'; import path from 'node:path'; +import { fileImageType, imageType } from './image-signature.js'; + // Downloads the images the site serves into static-mouse-rip/images, from the -// data `update:data` already saved. Images that are already there are skipped. +// data `update:data` already saved. Images that are already there are skipped, unless they aren't +// really images, in which case they're downloaded again. const root = path.join(import.meta.dir, '..'); const output = path.join(root, 'static-mouse-rip', 'images'); @@ -13,12 +16,31 @@ async function readJson(file) { const FETCH_TIMEOUT_MS = 30_000; +/** Where the game's art lives. The URLs come out of fetched data, so anything else in them isn't followed. */ +const IMAGE_HOSTS = new Set(['www.mousehuntgame.com', 'i.mouse.rip']); + +function isImageUrl(url) { + try { + const { protocol, hostname } = new URL(url); + return protocol === 'https:' && IMAGE_HOSTS.has(hostname); + } catch { + return false; + } +} + /** Save the first of `urls` that downloads. Returns whether the image is there. */ async function fetchImage(urls, destination) { if (!destination) return false; - if (fs.existsSync(destination)) return true; + if (fs.existsSync(destination)) { + if (fileImageType(destination)) return true; + console.warn(`Downloading ${path.relative(root, destination)} again: it isn't a valid image.`); + } for (const url of [urls].flat().filter(Boolean)) { + if (!isImageUrl(url)) { + console.error(`Skipping ${url}: not an https URL on a host the game's art comes from.`); + continue; + } let data; try { const response = await fetch(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) }); @@ -31,7 +53,10 @@ async function fetchImage(urls, destination) { console.error(`Failed to fetch ${url}: ${error.message}`); continue; } - if (data.length === 0) continue; + if (!imageType(data)) { + console.error(`Skipping ${url}: the response isn't an image.`); + continue; + } await fs.promises.mkdir(path.dirname(destination), { recursive: true }); await fs.promises.writeFile(destination, data); @@ -51,7 +76,8 @@ function slug(value) { */ function imagePath(id, ...segments) { const name = slug(id); - if (!/^[a-z0-9-]+$/.test(name)) { + // Some ids have capitals (bristle_woods_rift_theme_scrap_III_crafting_item), and the site asks for them as-is. + if (!/^[A-Za-z0-9-]+$/.test(name)) { console.warn(`Skipping image with unexpected id: ${id}`); return null; } diff --git a/scripts/update-trap-effects.js b/scripts/update-trap-effects.js new file mode 100644 index 00000000..f7f3fd30 --- /dev/null +++ b/scripts/update-trap-effects.js @@ -0,0 +1,118 @@ +/** + * Rebuild src/data/trap-effects.json from the community Location Trap Effects spreadsheet. + * + * The sheet has one row per location: region (only on a region's first row), location, then one cell per + * trap, base or charm, holding its name on the first line and its effect below. + */ +import fs from 'node:fs'; +import path from 'node:path'; + +const SHEET_CSV = + 'https://docs.google.com/spreadsheets/d/e/2PACX-1vRg_s_It1mDCefWgwc-7Gexr5Hc7lKBztFue9kYZidI76iodSUan3BoGsagLCI1M26U_zG7uVMe9kgK/pub?gid=0&single=true&output=csv'; +const OUT_FILE = path.join(__dirname, '../src/data/trap-effects.json'); + +/** The sheet's own shorthand, which reads as a mistake or as filler once it's out of the sheet. */ +const NAME_FIXES = { 'Black Widow': 'Black Widow Base' }; +const EFFECT_FIXES = { + 'Black Widow drops bonus loot': 'Bonus loot from the Black Widow Mouse', + 'Doubles tier 2 potions drops': 'Doubles tier 2 potion drops', +}; +// Ultimate Chrome Base rows end with a pointer back to the sheet's "Everywhere" rows, which the page already lists. +const TRAILING_NOTES = [/\s*\.\.\.\s*and Everywhere things$/i, /\s*\.\.\.\s*and so much more!$/i]; + +/** Minimal RFC 4180 parser: quoted fields may hold commas, doubled quotes and newlines. */ +export function parseCsv(text) { + const rows = []; + let row = []; + let field = ''; + let quoted = false; + for (let i = 0; i < text.length; i++) { + const char = text[i]; + if (quoted) { + if (char === '"' && text[i + 1] === '"') { + field += '"'; + i++; + } else if (char === '"') { + quoted = false; + } else { + field += char; + } + } else if (char === '"') { + quoted = true; + } else if (char === ',') { + row.push(field); + field = ''; + } else if (char === '\n' || char === '\r') { + if (char === '\r' && text[i + 1] === '\n') i++; + row.push(field); + rows.push(row); + row = []; + field = ''; + } else { + field += char; + } + } + if (field || row.length > 0) { + row.push(field); + rows.push(row); + } + return rows; +} + +const tidy = (value) => + value + .replaceAll('\r', '') + .replace(/\s+/g, ' ') + .replace(/\s+([.,])/g, '$1') + .trim(); + +function parseCell(cell) { + const lines = cell + .replaceAll('\r', '') + .split('\n') + .map((line) => line.trim()) + .filter(Boolean); + // A name that wraps ends its first line with a slash: "(Chrome) Stormwrought Ballista/" then "Dragon Slayer Cannon". + while (lines.length > 2 && lines[0].endsWith('/')) { + lines.splice(0, 2, `${lines[0]} ${lines[1]}`); + } + const name = tidy(lines[0] ?? ''); + let effect = tidy(lines.slice(1).join(' ')); + for (const note of TRAILING_NOTES) effect = effect.replace(note, ''); + return { name: NAME_FIXES[name] ?? name, effect: EFFECT_FIXES[effect] ?? effect }; +} + +export function sheetToEffects(rows) { + const locations = []; + let region = ''; + for (const row of rows.slice(1)) { + if (row[0]?.trim()) region = tidy(row[0]); + const location = tidy(row[1] ?? ''); + if (!location) continue; + const effects = row + .slice(2) + .filter((cell) => cell.trim()) + .map(parseCell) + .filter((effect) => effect.name); + locations.push({ region, location, effects }); + } + return locations; +} + +async function main() { + const response = await fetch(SHEET_CSV, { signal: AbortSignal.timeout(60_000) }); + if (!response.ok) throw new Error(`Sheet request failed: ${response.status} ${response.statusText}`); + const locations = sheetToEffects(parseCsv(await response.text())); + const effectCount = locations.reduce((sum, location) => sum + location.effects.length, 0); + if (locations.length < 50 || effectCount < 100) { + throw new Error(`Sheet parsed to ${locations.length} locations and ${effectCount} effects; refusing to overwrite.`); + } + fs.writeFileSync(OUT_FILE, `${JSON.stringify(locations, null, 2)}\n`, 'utf-8'); + console.log( + `Wrote ${locations.length} locations and ${effectCount} effects to ${path.relative(process.cwd(), OUT_FILE)}`, + ); +} + +if (import.meta.main) { + await main(); +} diff --git a/src/app/about/page.tsx b/src/app/about/page.tsx index 7a618314..e1298cfc 100644 --- a/src/app/about/page.tsx +++ b/src/app/about/page.tsx @@ -1,77 +1,114 @@ -import { Heading, Subheading } from '@/components/heading'; -import { Divider } from '@/components/divider'; +import { Subheading } from '@/components/heading'; +import { PageHeader } from '@/components/page-header'; import { PageLink } from '@/components/page-link'; import { pageMetadata } from '@/seo'; import React from 'react'; export const metadata = pageMetadata({ - title: 'About mouse.rip - Your MouseHunt Resource Hub', + title: 'About mouse.rip', description: - 'Learn more about mouse.rip, your comprehensive resource for MouseHunt guides, tools, and community-created content.', + 'mouse.rip is a community-built MouseHunt site with guides, a mouse and item database, minlucks, calculators, and links to community tools.', path: '/about', }); +const features: { href: string; name: string; description: string }[] = [ + { href: '/guides', name: 'Guides', description: 'strategy and how-tos from other hunters.' }, + { + href: '/mice', + name: 'Mice', + description: 'every mouse, with stats, minlucks, attraction rates, and where to catch it.', + }, + { href: '/items', name: 'Items', description: 'every item, with drop sources and Marketplace prices.' }, + { href: '/minlucks', name: 'Minlucks', description: 'the luck you need to guarantee a catch with each power type.' }, + { + href: '/essence-calculator', + name: 'Essence calculator', + description: 'what your essences craft into.', + }, + { + href: '/queso-pump-calculator', + name: 'Queso pump calculator', + description: 'the fastest cheese for farming Nachore.', + }, + { href: '/valour-rift-floors', name: 'Valour Rift floors', description: 'which floor types come next.' }, + { + href: '/catch-rate-estimator', + name: 'Catch rate estimator', + description: 'your catch rate for every mouse with your setup.', + }, + { + href: '/best-setup', + name: 'Best setup', + description: 'the trap that catches the most where you hunt.', + }, + { + href: '/map-planner', + name: 'Treasure map planner', + description: 'where to hunt for the most mice on your map.', + }, + { + href: '/rank-up-calculator', + name: 'Rank-up calculator', + description: 'the wisdom you need for your next title.', + }, + { href: '/relic-hunter', name: 'Relic Hunter', description: 'where she is today, and every riddle she leaves.' }, + { href: '/titles', name: 'Titles and ranks', description: 'what each title unlocks and the wisdom it takes.' }, + { + href: '/trap-special-effects', + name: 'Trap and base special effects', + description: 'gear that does something extra in certain locations.', + }, + { href: '/tools', name: 'Tools', description: 'community calculators, simulators, and planners.' }, + { href: '/extensions', name: 'Extensions', description: 'browser add-ons for the game.' }, + { href: '/userscripts', name: 'Userscripts', description: 'small scripts that tweak the game page.' }, + { href: '/spreadsheets', name: 'Spreadsheets', description: 'trackers and number-crunching sheets.' }, +]; + export default async function About() { return ( -
- About mouse.rip - - +
+ -
-

- Welcome to mouse.rip your ultimate resource hub for the MouseHunt game. We are - dedicated to providing comprehensive tools, detailed guides, and valuable information to help you become a - master hunter in the world of Gnawnia. -

-

- Our mission is to create a centralized platform where MouseHunt players of all levels can find the resources - they need to enhance their gameplay experience. +

+

+ Use it to learn the game or to look something up mid-hunt, then follow the links out to MHWiki, MHCT, and + Markethunt when you want more detail.

- Our Features + What's here -
    -
  • - Guides - Detailed guides covering all aspects of MouseHunt, from beginner - tips to advanced strategies. -
  • -
  • - Extensions - Browser extensions to enhance your MouseHunt experience. -
  • -
  • - Spreadsheets - Comprehensive spreadsheets for tracking progress, - planning hunts, and managing resources. -
  • -
  • - Tools - Various tools to assist with calculations, information lookup, - simulations, and more. -
  • -
  • - Userscripts - Custom scripts to customize your MouseHunt interface - and enhance the user experience. -
  • +
      + {features.map(({ href, name, description }) => ( +
    • + + {name} + + : {description} +
    • + ))}
    - Connect with Us + Get involved -

    - Join us on GitHub or{' '} - Discord to connect with other hunters, ask - questions, share your ideas, and contribute to the community. +

    + Come say hi on the MouseHunt Community Discord to ask + questions, suggest something, or share a tool you've made. The code lives on{' '} + GitHub, and pull requests are welcome.

    - - - Disclaimer - -

    - mouse.rip is a fan-made resource hub created by and for the MouseHunt - community.This website is not affiliated with, endorsed, or sponsored by HitGrab. All game content and materials - belong to HitGrab. -

    +
    + Disclaimer +

    + mouse.rip is a fan-made site created by and for the MouseHunt community. It is not affiliated with, endorsed + by, or sponsored by HitGrab. All game content and materials belong to{' '} + HitGrab. +

    +
); } diff --git a/src/app/application-layout.tsx b/src/app/application-layout.tsx index e4a1fe31..920e725f 100644 --- a/src/app/application-layout.tsx +++ b/src/app/application-layout.tsx @@ -1,6 +1,7 @@ 'use client'; import { usePathname } from 'next/navigation'; -import React, { type ReactNode } from 'react'; +import React, { useId, useState, type ReactNode } from 'react'; +import { preconnect } from 'react-dom'; import { Navbar, NavbarItem, NavbarSection, NavbarSpacer } from '@/components/navbar'; import { @@ -18,6 +19,7 @@ import { SidebarLayout } from '@/components/sidebar-layout'; import { SearchProvider } from '@/components/search/search-context'; import { SearchButton } from '@/components/search/search-button'; import { Footer } from '@/components/footer'; +import { PrefetchOnIntent } from '@/components/prefetch-on-intent'; // Imported directly: going through @/lib/site-data would bundle every site // dataset into this client component, and so into every page. @@ -27,6 +29,7 @@ import type { LocationRegion } from '@/types'; import { AcademicCapIcon, BoltIcon, + ChevronRightIcon, HomeIcon, QuestionMarkCircleIcon, SwatchIcon, @@ -40,179 +43,220 @@ import { locationImageUrl } from '@/lib/image-urls'; const locations = locationsData as LocationRegion[]; +/** The site's own tools. They live at the top level, but in the sidebar they belong to Tools. */ +const TOOL_PATHS = [ + '/catch-rate-estimator', + '/best-setup', + '/map-planner', + '/rank-up-calculator', + '/minlucks', + '/relic-hunter', + '/valour-rift-floors', + '/essence-calculator', + '/queso-pump-calculator', +]; + +/** + * One region of locations, collapsed unless the current page is inside it, so the + * sidebar isn't 70 links long. The current region opens itself on arrival, but + * can still be collapsed. + */ +function LocationRegionGroup({ region, pathname }: { region: LocationRegion; pathname: string }) { + const containsCurrent = region.locations.some((location) => pathname === `/locations/${location.id}`); + const [expanded, setExpanded] = useState(containsCurrent); + const [wasCurrent, setWasCurrent] = useState(containsCurrent); + if (containsCurrent !== wasCurrent) { + setWasCurrent(containsCurrent); + if (containsCurrent) setExpanded(true); + } + // The desktop sidebar and the mobile drawer each render this, so the ID must be per instance. + const listId = useId(); + + return ( +
+ + {expanded && ( +
+ {region.locations.map((location) => ( + + + {location.name} + + ))} +
+ )} +
+ ); +} + interface ApplicationLayoutProps { children: ReactNode; } export function ApplicationLayout({ children }: ApplicationLayoutProps) { const pathname = usePathname(); + // Nearly every page's art comes from the image host; opening the connection early takes a round trip off the + // first image. + preconnect('https://i.mouse.rip'); return ( + } navbar={ - + {/* The logo is the home link; a current-page underline beneath it reads as a stray rule. */} + - + mouse.rip - - - + {/* The home page leads with its own search field; a second one up here only splits attention. */} + {pathname !== '/' && ( + + + + )} } sidebar={ - + -
- -
+ {pathname !== '/' && ( +
+ +
+ )} - + Locations {locations.map((region) => ( -
- - {region.name} - -
- {region.locations.map((location) => ( - - - {location.name} - - ))} -
- + ))} - + - + - GitHub + + GitHub (opens in a new tab) + - + - Discord + + Discord (opens in a new tab) + @@ -220,7 +264,6 @@ export function ApplicationLayout({ children }: ApplicationLayoutProps) { } > {children} -
); diff --git a/src/app/best-setup/best-setup.tsx b/src/app/best-setup/best-setup.tsx new file mode 100644 index 00000000..4120a5ef --- /dev/null +++ b/src/app/best-setup/best-setup.tsx @@ -0,0 +1,872 @@ +'use client'; + +import clsx from 'clsx'; +import React, { useDeferredValue, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'; +import { usePathname, useRouter, useSearchParams } from 'next/navigation'; + +import { Announce } from '@/components/announce'; +import { GameImage } from '@/components/game-image'; +import { ItemPicker } from '@/components/item-picker'; +import { Link } from '@/components/link'; +import { bestSetups, score, tiedForBest, type Goal, type RankedSetup } from '@/lib/catch-rate/best-setup'; +import type { Catalog } from '@/lib/catch-rate/data'; +import { findPopulation, type Extras, type Setup } from '@/lib/catch-rate/engine'; +import { EMPTY_SETUP, applyChanges, overlayOnSaved, setupFromParams, setupToParams } from '@/lib/catch-rate/options'; +import { itemImageUrl } from '@/lib/image-urls'; +import { powerTypeLabel } from '@/lib/power-types'; +import { formatCount, formatNumber } from '@/utils'; + +import { + CatalogStatus, + ExtrasCard, + NumberField, + Toggle, + WhereFields, + cardClasses, + hintClasses, + labelClasses, + fieldClasses, + useCatchRateCatalog, + useItemOptions, + JumpToResults, + NoDataHint, + startOverClasses, +} from '../catch-rate-estimator/fields'; + +const SETUP_KEY = 'mouse.rip:best-setup'; +const OWNED_KEY = 'mouse.rip:owned-items'; +const ON_SERVER = 'server'; +const PAGE = 25; + +/** The weapons, bases and charms a hunter owns, by type. */ +export interface OwnedItems { + weapons: string[]; + bases: string[]; + charms: string[]; +} + +const KINDS = [ + { key: 'weapons', label: 'Weapons', param: 'own_weapons' }, + { key: 'bases', label: 'Bases', param: 'own_bases' }, + { key: 'charms', label: 'Charms', param: 'own_charms' }, +] as const; + +const noSubscribe = () => () => {}; + +/** + * Arrow keys for a group of role="radio" buttons, as a screen reader tells its user to expect: they move to the + * next choice and pick it. Each button also takes tabIndex 0 only when it's the one chosen. + */ +function radioKeys(event: React.KeyboardEvent) { + const step = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 }[event.key]; + if (!step) return; + const radios = [...event.currentTarget.querySelectorAll('[role="radio"]:not(:disabled)')]; + const next = + radios[(radios.indexOf(document.activeElement as HTMLButtonElement) + step + radios.length) % radios.length]; + if (!next) return; + event.preventDefault(); + next.focus(); + next.click(); +} +function read(key: string): string { + try { + return window.localStorage.getItem(key) ?? ''; + } catch { + // Storage is blocked (private browsing, say); start fresh. + return ''; + } +} +function write(key: string, value: string) { + try { + window.localStorage.setItem(key, value); + } catch { + // Blocked storage only means the next visit starts fresh. + } +} + +const NO_ITEMS: OwnedItems = { weapons: [], bases: [], charms: [] }; +const isEmpty = (items: OwnedItems) => KINDS.every(({ key }) => items[key].length === 0); +const sameItems = (a: OwnedItems, b: OwnedItems) => + KINDS.every(({ key }) => a[key].length === b[key].length && a[key].every((type) => b[key].includes(type))); + +/** The saved list, and whether the search was down to it. The list is kept while every item is searched. */ +function parseOwned(stored: string): { items: OwnedItems; mineOnly: boolean } | null { + try { + const value: unknown = JSON.parse(stored); + if (!value || typeof value !== 'object') return null; + const list = (key: string) => { + const entry = (value as Record)[key]; + return Array.isArray(entry) ? entry.filter((item): item is string => typeof item === 'string') : []; + }; + return { + items: { weapons: list('weapons'), bases: list('bases'), charms: list('charms') }, + mineOnly: (value as Record).all !== true, + }; + } catch { + // Nothing saved, or something else under the key. + return null; + } +} + +/** Items in a link (own_weapons=a,b&own_bases=…), for MouseHunt Improved or a bookmarklet to send a hunter's own. */ +function ownedFromParams(params: URLSearchParams): OwnedItems | null { + const list = (param: string) => (params.get(param) ?? '').split(',').filter(Boolean); + const items = { weapons: list('own_weapons'), bases: list('own_bases'), charms: list('own_charms') }; + // A link with the parameters but nothing in them isn't a list to switch to. + return isEmpty(items) ? null : items; +} + +interface Settings { + setup: Setup; + goal: Goal; + tryCharms: boolean; +} + +function goalFromParams(params: URLSearchParams): Goal { + const target = params.get('target'); + if (target) return { kind: 'mouse', mouse: target }; + const aim = params.get('aim'); + return aim === 'points' || aim === 'gold' ? { kind: aim } : { kind: 'catches' }; +} + +function settingsFromParams(params: URLSearchParams): Settings { + return { + setup: setupFromParams(params), + goal: goalFromParams(params), + tryCharms: params.get('try_charms') === '1', + }; +} + +function settingsToParams({ setup, goal, tryCharms }: Settings): URLSearchParams { + // The weapon and base are what Best Setup finds, so they don't go in its link. + const params = setupToParams({ ...setup, weapon: '', base: '' }); + if (goal.kind === 'mouse') params.set('target', goal.mouse); + else if (goal.kind !== 'catches') params.set('aim', goal.kind); + if (tryCharms) params.set('try_charms', '1'); + return params; +} + +/** A shared link wins; without one, pick up where this device left off. */ +export function BestSetupFromUrl() { + const params = useSearchParams(); + const storedSetup = useSyncExternalStore( + noSubscribe, + () => read(SETUP_KEY), + () => ON_SERVER, + ); + const storedOwned = useSyncExternalStore( + noSubscribe, + () => read(OWNED_KEY), + () => ON_SERVER, + ); + const link = new URLSearchParams(params.toString()); + const linked = link.has('location'); + const ready = storedSetup !== ON_SERVER; + // A link that names only the place (a location page's "Best setup here") keeps the hunter's charm, shield and + // bonuses; the tool's own links always carry a cheese. A link from elsewhere on the site that does name a + // cheese, such as a mouse page's, asks for the same with keep=1. + const keepsSettings = linked && ready && (!link.has('cheese') || link.get('keep') === '1'); + const initial = linked + ? settingsFromParams(keepsSettings ? overlayOnSaved(storedSetup, link) : link) + : ready && storedSetup + ? settingsFromParams(new URLSearchParams(storedSetup)) + : undefined; + const linkedItems = ownedFromParams(link); + const saved = ready ? parseOwned(storedOwned) : null; + return ( + link.has(param))} + syncUrl={ready} + /> + ); +} + +/** A list to go back to: the one a link replaced, or the one before every tick was set or cleared at once. */ +interface Undo { + items: OwnedItems; + of: 'link' | 'all'; +} + +export function BestSetup({ + initial, + initialItems = NO_ITEMS, + initialMineOnly = false, + importedItems = false, + replacedItems, + itemsInAddress = false, + syncUrl, +}: { + initial?: Settings; + initialItems?: OwnedItems; + initialMineOnly?: boolean; + /** The list came in the link that was opened. */ + importedItems?: boolean; + /** The saved list the link's took the place of, when it was a different one. */ + replacedItems?: OwnedItems; + /** The address still carries a list, to take out once it's saved. */ + itemsInAddress?: boolean; + syncUrl: boolean; +}) { + const router = useRouter(); + const pathname = usePathname(); + const { catalog, failed } = useCatchRateCatalog(); + const [settings, setSettings] = useState( + initial ?? { setup: { ...EMPTY_SETUP }, goal: { kind: 'catches' }, tryCharms: false }, + ); + // The hunter's ticked items, and whether the search is down to them. The two are kept apart so that looking at + // every item and coming back doesn't cost them the list. + const [items, setItems] = useState(initialItems); + const [mineOnly, setMineOnly] = useState(initialMineOnly); + const [undo, setUndo] = useState(replacedItems ? { items: replacedItems, of: 'link' } : null); + // The address is cleaned of the list once it's saved, so remember here that it came from a link. + const [imported] = useState(importedItems); + + // Remember the settings and the item list for the next visit, including ones that came in a link. + useEffect(() => { + if (syncUrl) write(SETUP_KEY, settingsToParams(settings).toString()); + }, [settings, syncUrl]); + useEffect(() => { + if (!syncUrl) return; + // Nothing ticked and nothing saved before: leave storage alone. + if (!mineOnly && isEmpty(items) && !read(OWNED_KEY)) return; + write(OWNED_KEY, JSON.stringify(mineOnly ? items : { ...items, all: true })); + }, [items, mineOnly, syncUrl]); + // Items sent in a link are saved above; take them out of the address so it can be shared. + useEffect(() => { + if (!syncUrl || !itemsInAddress) return; + const params = new URLSearchParams(window.location.search); + for (const { param } of KINDS) params.delete(param); + const query = params.toString(); + router.replace(query ? `${pathname}?${query}` : pathname, { scroll: false }); + }, [syncUrl, itemsInAddress, router, pathname]); + + const update = (next: Settings) => { + setSettings(next); + if (!syncUrl) return; + const query = settingsToParams(next).toString(); + router.replace(query ? `${pathname}?${query}` : pathname, { scroll: false }); + }; + + // Settings picked up from the last visit, or filled out from a link that kept them, aren't in the address yet. + // Put them there once, so the address can be copied and shared without touching the form first. + const addressed = useRef(false); + useEffect(() => { + if (!syncUrl || addressed.current || itemsInAddress) return; + addressed.current = true; + const query = settingsToParams(settings).toString(); + if (query && query !== window.location.search.slice(1)) { + window.history.replaceState(null, '', `${pathname}?${query}`); + } + }, [syncUrl, settings, pathname, itemsInAddress]); + + // A link may name only a location; fill in a valid stage and cheese. Memoised so the search below runs when the + // settings change and not on every render (each address update re-renders this). + const complete = useMemo(() => { + if (!catalog || !settings.setup.location) return settings; + let setup = applyChanges(catalog, settings.setup, {}); + let goal = settings.goal; + if (goal.kind === 'mouse') { + const target = goal.mouse; + const attracts = (candidate: Setup) => + findPopulation(candidate, catalog)?.mice.some((entry) => entry.type === target) ?? false; + // A link aims for a mouse, and the saved charm it's laid over can bring its own set of mice without that + // one. Then the charm gives way; if the mouse still isn't there, there's nothing to aim for. + if (!attracts(setup)) { + if (setup.charm && attracts({ ...setup, charm: '' })) setup = { ...setup, charm: '' }; + else goal = { kind: 'catches' }; + } + } + return { ...settings, setup, goal }; + }, [catalog, settings]); + + if (!catalog) return ; + return ( + { + // Ticking or clearing everything at once can be taken back; a single tick after that settles it. + setUndo(all ? { items, of: 'all' } : null); + setItems(next); + }} + imported={imported} + undo={undo} + onUndo={() => { + if (!undo) return; + setItems(undo.items); + setUndo(null); + }} + /> + ); +} + +function BestSetupForm({ + catalog, + settings, + onChange, + items, + mineOnly, + onMineOnly, + onItems, + imported, + undo, + onUndo, +}: { + catalog: Catalog; + settings: Settings; + onChange: (settings: Settings) => void; + items: OwnedItems; + mineOnly: boolean; + onMineOnly: (mineOnly: boolean) => void; + onItems: (items: OwnedItems, all?: boolean) => void; + imported: boolean; + undo: Undo | null; + onUndo: () => void; +}) { + const { setup, goal, tryCharms } = settings; + // Null while every item in the game is being searched. + const owned = mineOnly ? items : null; + const options = useItemOptions(catalog, setup); + const setSetup = (next: Setup) => { + const population = findPopulation(next, catalog); + // A target mouse that isn't attracted here any more falls back to most catches. + const losesTarget = goal.kind === 'mouse' && !population?.mice.some((mouse) => mouse.type === goal.mouse); + onChange({ ...settings, setup: next, goal: losesTarget ? { kind: 'catches' } : goal }); + }; + const setExtra = (key: K, value: Extras[K]) => + setSetup({ ...setup, extras: { ...setup.extras, [key]: value } }); + + const candidates = useMemo(() => { + const known = (list: string[], map: Map) => list.filter((type) => map.has(type)); + return { + weapons: owned ? known(owned.weapons, catalog.weapons) : [...catalog.weapons.keys()], + bases: owned ? known(owned.bases, catalog.bases) : [...catalog.bases.keys()], + charms: tryCharms ? (owned ? known(owned.charms, catalog.charms) : [...catalog.charms.keys()]) : [], + }; + }, [catalog, owned, tryCharms]); + // Item details (an Isle Idol skin, a Golem charge…) only ask about items the hunter has ticked as their own. + // Searching every item, those use their defaults rather than filling the form with questions. + const ownItems = useMemo( + () => ({ weapons: new Set(owned?.weapons ?? []), bases: new Set(owned?.bases ?? []) }), + [owned], + ); + + const population = setup.location && setup.cheese ? findPopulation(setup, catalog) : undefined; + // Trying every pair takes long enough to feel on a phone, so the search runs behind the form: a keystroke shows + // at once, and the results catch up. + const wanted = useMemo(() => ({ setup, candidates, goal }), [setup, candidates, goal]); + const searched = useDeferredValue(wanted); + const results = useMemo( + () => + searched.setup.location && searched.setup.cheese && findPopulation(searched.setup, catalog) + ? bestSetups(searched.setup, catalog, searched.candidates, searched.goal) + : [], + [searched, catalog], + ); + const searching = searched !== wanted; + + return ( +
+
event.preventDefault()}> + setSetup(next)} /> + +
+ What to aim for +
+ {( + [ + ['catches', 'Most catches', 'Everything the cheese attracts'], + ['mouse', 'One mouse', 'For a map or a tricky catch'], + ['points', 'Most points', 'What each catch scores'], + ['gold', 'Most gold', 'What each catch pays'], + ] as const + ).map(([kind, title, blurb]) => ( + + ))} +
+ {goal.kind === 'mouse' && population && ( + + )} +
+ +
+ Charm and bonuses + setSetup(applyChanges(catalog, setup, { charm }))} + placeholder="No charm" + clearable + clearLabel="No charm" + /> + onChange({ ...settings, tryCharms: next })}> + Also try {owned ? 'each of my charms' : 'every charm'}{' '} + (on the 50 strongest traps) + +
+ setSetup({ ...setup, goldenShield })}> + Golden Shield + + setSetup({ ...setup, riftstalker })}> + Riftstalker Codex + +
+
+ setSetup({ ...setup, bonusPower: value ?? 0 })} + /> + setSetup({ ...setup, bonusLuck: value ?? 0 })} + /> +
+

For auras and anything else your camp adds that isn’t on the items.

+
+ + + + {/* "Only mine" lists every weapon in the game as a checkbox; this is the way past them to the results. */} + + Skip to the results + + + {setup.location && ( + + )} + + + +
+

+ Best setups +

+ + {results.length > 0 + ? `Best setup: ${catalog.weapons.get(results[0].weapon)?.name ?? 'a weapon'} with ${ + catalog.bases.get(results[0].base)?.name ?? 'a base' + }${results[0].charm ? ` and ${catalog.charms.get(results[0].charm)?.name ?? 'a charm'}` : ''}. ${formatNumber(results.length)} setups ranked.` + : population + ? 'No weapons or bases to try.' + : ''} + + charm.hint).map((charm) => charm.name)} + /> +
+
+ ); +} + +/** Which items to search: everything in the game, or the hunter's own, kept on this device. */ +function OwnedItemsCard({ + catalog, + items, + mineOnly, + onMineOnly, + onItems, + imported, + undo, + onUndo, +}: { + catalog: Catalog; + items: OwnedItems; + mineOnly: boolean; + onMineOnly: (mineOnly: boolean) => void; + /** `all` when every tick shown was set or cleared at once, which can be undone. */ + onItems: (items: OwnedItems, all?: boolean) => void; + imported: boolean; + undo: Undo | null; + onUndo: () => void; +}) { + const [kind, setKind] = useState<(typeof KINDS)[number]['key']>('weapons'); + const [query, setQuery] = useState(''); + const all = { weapons: catalog.weapons, bases: catalog.bases, charms: catalog.charms }; + const list = [...all[kind].values()]; + const needle = query.trim().toLowerCase(); + const shown = needle ? list.filter((item) => item.name.toLowerCase().includes(needle)) : list; + const mine = new Set(items[kind]); + const set = (types: string[], everyShown = false) => onItems({ ...items, [kind]: types }, everyShown); + const linkClasses = + 'font-medium text-pink-700 underline decoration-pink-700/30 underline-offset-2 hover:text-pink-900 hover:decoration-pink-900 dark:text-pink-300 dark:decoration-pink-300/40 dark:hover:text-pink-200'; + + return ( +
+ Your items +
+

Your items

+

+ {mineOnly + ? `Searching your ${formatCount(items.weapons.length, 'weapon')}, ${formatCount(items.bases.length, 'base')}, and ${formatCount(items.charms.length, 'charm')}.` + : isEmpty(items) + ? 'Searching every weapon and base in the game. Tick the ones you own to see what you can use today.' + : 'Searching every weapon and base in the game.'} + {imported && mineOnly ? ' These came from the link you opened.' : ''} + {undo?.of === 'link' && mineOnly && ( + <> + {' '} + + + )} +

+
+
+ {( + [ + [false, 'Every item'], + [true, 'Only mine'], + ] as const + ).map(([value, label]) => ( + + ))} +
+ + {mineOnly && ( +
+
+ {KINDS.map(({ key, label }) => ( + + ))} +
+ setQuery(event.target.value)} + /> +
+ + + {undo?.of === 'all' && ( + + )} +
+
    + {shown.map((item) => ( +
  • + +
  • + ))} + {shown.length === 0 && ( +
  • Nothing matches.
  • + )} +
+
+ )} +
+ ); +} + +function Results({ + catalog, + setup, + goal, + results, + hasPopulation, + cheese, + charmsWithData, +}: { + catalog: Catalog; + setup: Setup; + goal: Goal; + results: RankedSetup[]; + hasPopulation: boolean; + cheese: string; + /** Charms that have their own attraction data for this location and cheese. */ + charmsWithData: string[]; +}) { + const [shown, setShown] = useState(PAGE); + if (setup.location && !hasPopulation) { + return ( +
+

No attraction data for this cheese here

+

+ +

+
+ ); + } + if (!setup.location) { + return ( +
+

Pick where you’re hunting

+

+ The best weapon and base for the location and cheese show up here. +

+
+ ); + } + if (results.length === 0) { + return ( +
+

No weapons or bases to try

+

+ Tick at least one weapon and one base under Your items. +

+
+ ); + } + + const targetName = goal.kind === 'mouse' ? catalog.mice.get(goal.mouse)?.name : undefined; + const name = (map: Map, type: string) => map.get(type)?.name ?? type; + const tied = tiedForBest(results, goal); + + return ( +
+

+ {goal.kind === 'mouse' + ? `The setups that catch the most ${targetName ?? 'of that mouse'} per 100 hunts.` + : goal.kind === 'catches' + ? 'The setups that catch the most mice per 100 hunts.' + : `The setups that earn the most ${goal.kind} per hunt, before any bonuses.`} + {tied > 1 && + (goal.kind === 'catches' || goal.kind === 'mouse' + ? ` ${tied === results.length ? 'Every setup listed catches' : `The first ${tied} catch`} the same, so any of them will do.` + : ` ${tied === results.length ? 'Every setup listed earns' : `The first ${tied} earn`} the same, so any of them will do.`)} +

+
    + {results.slice(0, shown).map((result, index) => { + const link = setupToParams({ ...setup, weapon: result.weapon, base: result.base, charm: result.charm }); + return ( +
  1. + + {index + 1} + +
    + {( + [ + [result.weapon, name(catalog.weapons, result.weapon)], + [result.base, name(catalog.bases, result.base)], + ...(result.charm ? [[result.charm, name(catalog.charms, result.charm)]] : []), + ] as [string, string][] + ).map(([type, itemName]) => ( +

    + + {itemName} +

    + ))} +

    + {formatNumber(result.trap.power)} {powerTypeLabel(result.trap.powerType)} power,{' '} + {formatNumber(result.trap.luck)} luck, {result.trap.attraction}% attraction bonus +

    +
    +
    +

    + + {goal.kind === 'points' || goal.kind === 'gold' + ? formatNumber(Math.round(score(result, goal))) + : score(result, goal).toFixed(goal.kind === 'mouse' ? 2 : 1)} + + + {goal.kind === 'mouse' + ? `per 100 hunts, ${((result.target?.catchRate ?? 0) * 100).toFixed(1)}% catch rate` + : goal.kind === 'catches' + ? `per 100 hunts, ${(result.catchRate * 100).toFixed(1)}% caught` + : `${goal.kind} per hunt, ${(result.catchRate * 100).toFixed(1)}% caught`} + +

    + + See each mouse + +
    +
  2. + ); + })} +
+ {results.length > shown && ( + + )} +
+ ); +} diff --git a/src/app/best-setup/page.tsx b/src/app/best-setup/page.tsx new file mode 100644 index 00000000..133ae600 --- /dev/null +++ b/src/app/best-setup/page.tsx @@ -0,0 +1,42 @@ +import React, { Suspense } from 'react'; + +import { TrophyIcon } from '@heroicons/react/20/solid'; +import { Breadcrumbs } from '@/components/breadcrumbs'; +import { PageHeader } from '@/components/page-header'; +import { PageLink } from '@/components/page-link'; + +import { ogCard, pageMetadata } from '@/seo'; +import { BestSetup, BestSetupFromUrl } from './best-setup'; + +export const metadata = pageMetadata({ + title: 'MouseHunt Best Setup', + description: + 'Rank every MouseHunt weapon, base, and charm for a location and cheese by catches, points, or gold, or find the best setup for one mouse.', + path: '/best-setup', + image: ogCard({ title: 'Best setup', eyebrow: 'MouseHunt tool', icon: 'trophy', accent: 'amber' }), +}); + +export default function BestSetupPage() { + return ( +
+ + + Pick where you’re hunting to rank every weapon and base by how many mice they’d catch, or aim for one mouse, + points, or gold. Built on{' '} + tsitu’s Best Setup, with the same + catch rates as the catch rate estimator. + + } + icon={TrophyIcon} + iconClassName="bg-amber-100 text-amber-700 dark:bg-amber-950 dark:text-amber-300" + /> + {/* Best Setup reads a shared link with useSearchParams, which needs a Suspense boundary to prerender. */} + }> + + +
+ ); +} diff --git a/src/app/catch-rate-estimator/estimator.tsx b/src/app/catch-rate-estimator/estimator.tsx new file mode 100644 index 00000000..f0de38e8 --- /dev/null +++ b/src/app/catch-rate-estimator/estimator.tsx @@ -0,0 +1,501 @@ +'use client'; + +import clsx from 'clsx'; +import React, { useEffect, useRef, useState, useSyncExternalStore } from 'react'; +import { usePathname, useRouter, useSearchParams } from 'next/navigation'; + +import { Announce } from '@/components/announce'; +import { GameImage } from '@/components/game-image'; +import { ItemPicker } from '@/components/item-picker'; +import { Link } from '@/components/link'; +import type { Catalog } from '@/lib/catch-rate/data'; +import { estimate, matchShownTotals, type Extras, type Setup } from '@/lib/catch-rate/engine'; +import { + EMPTY_SETUP, + applyChanges, + overlayOnSaved, + resolveStage, + setupFromParams, + setupToParams, +} from '@/lib/catch-rate/options'; +import { mouseImageUrl } from '@/lib/image-urls'; +import { powerTypeLabel } from '@/lib/power-types'; +import { formatCount, formatNumber } from '@/utils'; + +import { + CatalogStatus, + ExtrasCard, + NumberField, + Toggle, + WhereFields, + cardClasses, + fieldClasses, + hintClasses, + labelClasses, + useCatchRateCatalog, + useItemOptions, + JumpToResults, + NoDataHint, + startOverClasses, +} from './fields'; + +const STORAGE_KEY = 'mouse.rip:catch-rate-estimator'; +const ON_SERVER = 'server'; + +function readStorage(): string { + try { + return window.localStorage.getItem(STORAGE_KEY) ?? ''; + } catch { + // Storage is blocked (private browsing, say); start fresh. + return ''; + } +} +const noSubscribe = () => () => {}; + +/** "86.4%", but a whole 100% without the ".0". */ +function percent(value: number, digits = 1): string { + return value >= 100 - 0.5 * 10 ** -digits ? '100%' : `${value.toFixed(digits)}%`; +} + +/** "+6" or "−7", for a bonus that can go either way. */ +function signed(value: number): string { + return value < 0 ? `−${Math.abs(value)}` : `+${value}`; +} + +/** A shared link wins; without one, pick up the setup this device used last. */ +export function CatchRateEstimatorFromUrl() { + const params = useSearchParams(); + const stored = useSyncExternalStore(noSubscribe, readStorage, () => ON_SERVER); + const link = new URLSearchParams(params.toString()); + const linked = ['location', 'weapon', 'base', 'charm'].some((param) => link.has(param)); + // A link with no trap in it (a location page's "Catch rates here") keeps the hunter's own trap, and one with no + // place in it (an item page's "Try it") keeps their own place. Either waits for the saved setup like a visit + // with no link does. + const keepsSaved = linked && ((!link.has('weapon') && !link.has('base')) || !link.has('location')); + const ready = (linked && !keepsSaved) || stored !== ON_SERVER; + const initial = !ready + ? EMPTY_SETUP + : linked + ? setupFromParams(keepsSaved ? overlayOnSaved(stored, link) : link) + : stored + ? setupFromParams(new URLSearchParams(stored)) + : EMPTY_SETUP; + // The estimator takes its setup once, so it mounts again when the saved one arrives. + // Until the saved setup is read, don't save or touch the URL, or the empty first render would overwrite both. + return ; +} + +export function CatchRateEstimator({ initial = EMPTY_SETUP, syncUrl }: { initial?: Setup; syncUrl: boolean }) { + const router = useRouter(); + const pathname = usePathname(); + const { catalog, failed } = useCatchRateCatalog(); + const [setup, setSetup] = useState(initial); + + // Remember the setup on screen, including one opened from a link, for the next visit. + useEffect(() => { + if (!syncUrl) return; + try { + window.localStorage.setItem(STORAGE_KEY, setupToParams(setup).toString()); + } catch { + // Blocked storage only means the next visit starts fresh. + } + }, [setup, syncUrl]); + + const update = (next: Setup) => { + setSetup(next); + if (!syncUrl) return; + const query = setupToParams(next).toString(); + router.replace(query ? `${pathname}?${query}` : pathname, { scroll: false }); + }; + + // A setup picked up from the last visit, or filled out from a link that only named a location, isn't in the + // address yet. Put it there once, so the address can be copied and shared without touching the form first. + const addressed = useRef(false); + useEffect(() => { + if (!syncUrl || addressed.current) return; + addressed.current = true; + const query = setupToParams(setup).toString(); + if (query && query !== window.location.search.slice(1)) { + window.history.replaceState(null, '', `${pathname}?${query}`); + } + }, [syncUrl, setup, pathname]); + + if (!catalog) return ; + // A link may name only a location (a location page, or another tool); fill in a valid stage and cheese. + const complete = setup.location ? applyChanges(catalog, setup, {}) : setup; + return ; +} + +function EstimatorForm({ + catalog, + setup, + onChange, +}: { + catalog: Catalog; + setup: Setup; + onChange: (setup: Setup) => void; +}) { + const options = useItemOptions(catalog, setup); + + const choose = (changes: Partial) => onChange(applyChanges(catalog, setup, changes)); + const setExtra = (key: K, value: Extras[K]) => + onChange({ ...setup, extras: { ...setup.extras, [key]: value } }); + + // The data has Iceberg stages for each special base; the base picks which one. + const resolved = { ...setup, stage: resolveStage(catalog, setup.location, setup.stage, setup.base) }; + const result = estimate(resolved, catalog); + + return ( +
+
event.preventDefault()}> + + +
+ Your trap + choose({ weapon })} + /> + choose({ base })} /> + choose({ charm })} + placeholder="No charm" + clearable + clearLabel="No charm" + /> +
+ onChange({ ...setup, goldenShield })}> + Golden Shield + + onChange({ ...setup, riftstalker })}> + Riftstalker Codex + +
+
+ + + + + {(setup.location || setup.weapon || setup.base) && ( + + )} + + + +
+

+ Catch rates +

+ + {result + ? `Catch rate ${percent(result.overall.catchRate * 100)} overall, across ${formatCount(result.mice.length, 'mouse', 'mice')}.` + : setup.location && setup.weapon && setup.base + ? 'No attraction data for this setup.' + : ''} + + charm.hint).map((charm) => charm.name)} + /> +
+
+ ); +} + +/** Bonuses the estimator can’t see, such as auras, with a helper that works them out from the camp. */ +function BonusCard({ catalog, setup, onChange }: { catalog: Catalog; setup: Setup; onChange: (setup: Setup) => void }) { + const [shownPower, setShownPower] = useState(''); + const [shownLuck, setShownLuck] = useState(''); + // Starts open when there's a bonus to show, then stays how the hunter leaves it: following the bonus instead + // would shut the panel on them the moment they clear a field. + const [open, setOpen] = useState(Boolean(setup.bonusPower || setup.bonusLuck)); + const matched = + shownPower && shownLuck + ? matchShownTotals(setup, catalog, { power: Number(shownPower), luck: Number(shownLuck) }) + : undefined; + + return ( +
setOpen(event.currentTarget.open)}> + + Auras and other bonuses + {(setup.bonusPower !== 0 || setup.bonusLuck !== 0) && ( + + {signed(setup.bonusPower)}% power, {signed(setup.bonusLuck)} luck + + )} + +
+

+ Auras, events, and some location effects add power and luck that aren’t on the items. Add them here, or type + in the power and luck your camp shows and let the estimator work them out. +

+
+ onChange({ ...setup, bonusPower: v ?? 0 })} + /> + onChange({ ...setup, bonusLuck: v ?? 0 })} + /> +
+
+

Match my camp

+
+ + +
+ +
+
+
+ ); +} + +function Results({ + setup, + result, + cheese, + charmsWithData, +}: { + setup: Setup; + result: ReturnType; + cheese: string; + /** Charms that have their own attraction data for this location and cheese. */ + charmsWithData: string[]; +}) { + if (!setup.location || !setup.weapon || !setup.base) { + return ( +
+

Pick a location, weapon, and base

+

+ The catch rate for every mouse there shows up here as you go. +

+
+ ); + } + if (!result) { + return ( +
+

No attraction data for this setup

+

+ +

+
+ ); + } + + const { trap, overall } = result; + const stats: [string, string][] = [ + ['Power', formatNumber(trap.power)], + ['Luck', formatNumber(trap.luck)], + ['Attraction bonus', percent(trap.attraction, 0)], + ['Power type', powerTypeLabel(trap.powerType)], + ]; + const perHunt: [string, string][] = [ + ['Points', formatNumber(Math.round(result.perHunt.points))], + ['Gold', formatNumber(Math.round(result.perHunt.gold))], + ['Wisdom', formatNumber(Math.round(result.perHunt.wisdom))], + ]; + + return ( +
+
+
+

+ Overall catch rate + + {percent(overall.catchRate * 100)} + +

+

+ {percent(overall.attraction)} of hunts attract a mouse. + {overall.minluck !== undefined && overall.minluck > 0 && ( + {formatNumber(overall.minluck)} luck catches every mouse here. + )} + {result.population.source === 'mhct' && result.population.sample > 0 && ( + + Attraction rates from {formatNumber(result.population.sample)} hunts on MHCT. + + )} +

+
+
+ {stats.map(([label, value]) => ( +
+
{label}
+
{value}
+
+ ))} +
+
+

Each hunt earns, on average

+
+ {perHunt.map(([label, value]) => ( +
+
{label}
+
{value}
+
+ ))} +
+ {result.perHunt.wisdom >= 1 && ( + + Hunts to your next title at this pace + + )} +
+
+ + {result.mice.every((mouse) => mouse.minluck === undefined) && ( +

+ None of these mice can be caught with {powerTypeLabel(trap.powerType)} power. Try a weapon of another power + type; each mouse’s page lists what it’s weak to. +

+ )} + +
+ + + + + + + + + + + + + {result.mice.map((mouse) => ( + + + + + + + + ))} + +
Catch rate for each mouse
MouseAttractionCatch rate + Catches per 100 hunts + Minluck
+ + + {mouse.name} + + {/* On a phone the attraction and minluck columns fold into a line under the name. */} + + {percent(mouse.attraction, 2)} attraction + {mouse.minluck !== undefined && mouse.minluck > 0 ? `, minluck ${formatNumber(mouse.minluck)}` : ''} + + + {percent(mouse.attraction, 2)} + + + + {mouse.catches.toFixed(2)} + + {mouse.minluck === undefined ? ( + — + ) : ( + formatNumber(mouse.minluck) + )} +
+
+
+ ); +} + +function CatchRateCell({ rate, immune }: { rate: number; immune: boolean }) { + if (immune) { + return ( + + Immune + + ); + } + const value = rate * 100; + const tone = + value >= 80 + ? 'bg-emerald-50 text-emerald-800 ring-emerald-200 dark:bg-emerald-950/50 dark:text-emerald-200 dark:ring-emerald-900' + : value >= 40 + ? 'bg-amber-50 text-amber-900 ring-amber-200 dark:bg-amber-950/40 dark:text-amber-200 dark:ring-amber-900' + : 'bg-rose-50 text-rose-800 ring-rose-200 dark:bg-rose-950/50 dark:text-rose-200 dark:ring-rose-900'; + // Rounded down, so a catch that can still fail never reads as 100%. + const shown = value >= 100 ? '100' : value < 10 ? value.toFixed(2) : (Math.floor(value * 10) / 10).toFixed(1); + return ( + + {shown}% + + ); +} diff --git a/src/app/catch-rate-estimator/fields.tsx b/src/app/catch-rate-estimator/fields.tsx new file mode 100644 index 00000000..5922dd3c --- /dev/null +++ b/src/app/catch-rate-estimator/fields.tsx @@ -0,0 +1,503 @@ +'use client'; + +/** The form pieces the catch rate estimator and Best Setup share. */ + +import clsx from 'clsx'; +import React, { useEffect, useMemo, useState } from 'react'; + +import type { PickerOption } from '@/components/item-picker'; +import { loadCatchRateData } from '@/lib/client-index'; +import { buildCatalog, group, type Catalog } from '@/lib/catch-rate/data'; +import { findPopulation, type Extras, type Setup } from '@/lib/catch-rate/engine'; +import { applyChanges, cheesesFor, specialCharmsFor, stagesFor } from '@/lib/catch-rate/options'; +import { EMPOWERABLE_CHEESES, GOLEM_GUARDIAN, ISLE_IDOL, PRESTIGE_BASES } from '@/lib/catch-rate/special'; +import { itemImageUrl } from '@/lib/image-urls'; +import { powerTypeLabel } from '@/lib/power-types'; + +export const cardClasses = + // min-w-0: a fieldset otherwise never shrinks below its widest line, and pushes off a phone's screen. + 'min-w-0 rounded-2xl bg-white p-4 shadow-xs ring-1 ring-zinc-200 sm:p-5 dark:bg-zinc-900 dark:ring-zinc-800'; +export const labelClasses = 'flex flex-col gap-1.5 text-sm font-medium text-zinc-950 dark:text-white'; +export const hintClasses = 'text-xs font-normal text-zinc-600 dark:text-zinc-400'; +export const fieldClasses = + 'w-full rounded-xl border border-zinc-950/45 bg-white px-3 py-2.5 text-base/6 text-zinc-950 shadow-xs placeholder:text-zinc-500 hover:border-zinc-950/60 focus:border-pink-500 focus:outline-hidden focus:ring-2 focus:ring-pink-500 sm:py-2 sm:text-sm/6 dark:border-white/35 dark:bg-white/5 dark:text-white dark:placeholder:text-zinc-400 dark:scheme-dark dark:hover:border-white/45'; + +/** The catch rate data, loaded once the page is in the browser. */ +export function useCatchRateCatalog(): { catalog: Catalog | null; failed: boolean } { + const [catalog, setCatalog] = useState(null); + const [failed, setFailed] = useState(false); + useEffect(() => { + let current = true; + loadCatchRateData() + .then((raw) => { + if (current) setCatalog(buildCatalog(raw)); + }) + .catch(() => { + if (current) setFailed(true); + }); + return () => { + current = false; + }; + }, []); + return { catalog, failed }; +} + +export function CatalogStatus({ failed }: { failed: boolean }) { + return failed ? ( +

+ The catch rate data didn’t load. Check your connection and reload the page. +

+ ) : ( +
+ ); +} + +/** Weapons, bases and charms as picker options, with the game's art. */ +export function useItemOptions(catalog: Catalog, setup: Setup) { + const specialCharms = useMemo( + () => specialCharmsFor(catalog, setup.location, setup.stage, setup.cheese), + [catalog, setup.location, setup.stage, setup.cheese], + ); + const weapons = useMemo( + () => + [...catalog.weapons.values()].map((item) => ({ + value: item.type, + name: item.name, + image: itemImageUrl(item.type), + hint: item.powerType ? powerTypeLabel(item.powerType) : undefined, + })), + [catalog], + ); + const bases = useMemo( + () => + [...catalog.bases.values()].map((item) => ({ + value: item.type, + name: item.name, + image: itemImageUrl(item.type), + })), + [catalog], + ); + const charms = useMemo( + () => + [...catalog.charms.values()].map((item) => ({ + value: item.type, + name: item.name, + image: itemImageUrl(item.type), + hint: specialCharms.has(item.type) ? 'Own attraction data' : undefined, + })), + [catalog, specialCharms], + ); + return { weapons, bases, charms }; +} + +/** Location, stage and cheese, kept valid as each changes. */ +export function WhereFields({ + catalog, + setup, + onChange, +}: { + catalog: Catalog; + setup: Setup; + onChange: (setup: Setup) => void; +}) { + const locations = useMemo(() => [...catalog.locations].sort((a, b) => a.name.localeCompare(b.name)), [catalog]); + const stages = useMemo(() => (setup.location ? stagesFor(catalog, setup.location) : []), [catalog, setup.location]); + const cheeses = useMemo( + () => (setup.location ? cheesesFor(catalog, setup.location, setup.stage) : []), + [catalog, setup.location, setup.stage], + ); + const choose = (changes: Partial) => onChange(applyChanges(catalog, setup, changes)); + + return ( +
+ Where you’re hunting + + {stages.length > 1 && ( + + )} + {setup.location && ( + + )} + {EMPOWERABLE_CHEESES.has(setup.cheese) && ( + onChange({ ...setup, empowered })}> + Empowered (20% power bonus) + + )} +
+ ); +} + +export function Toggle({ + checked, + onChange, + children, +}: { + checked: boolean; + onChange: (checked: boolean) => void; + children: React.ReactNode; +}) { + return ( + + ); +} + +export function NumberField({ + label, + hint, + value, + onChange, + min, + max, +}: { + label: string; + hint?: string; + value: number | undefined; + onChange: (value: number | undefined) => void; + min: number; + max: number; +}) { + // What's being typed, kept apart from the number while the field has focus. Without it an emptied field refills + // with its default under the cursor, and a number over the maximum is rewritten before it's finished. + const [typing, setTyping] = useState(null); + return ( + + ); +} + +export function LevelSelect({ + label, + value, + max, + onChange, +}: { + label: string; + value: number | undefined; + max: number; + onChange: (value: number) => void; +}) { + return ( + + ); +} + +/** The location and item states that change the numbers, shown only when they apply. */ +export function ExtrasCard({ + catalog, + setup, + onExtra, + items, +}: { + catalog: Catalog; + setup: Setup; + onExtra: (key: K, value: Extras[K]) => void; + /** For Best Setup: the weapons and bases being tried, in place of the setup's own. */ + items?: { weapons: Set; bases: Set }; +}) { + const { location, stage, extras } = setup; + const dragons = group(catalog, 'dragon'); + const population = findPopulation(setup, catalog); + const hasWeapon = (type: string) => (items ? items.weapons.has(type) : setup.weapon === type); + const hasBase = (type: string) => (items ? items.bases.has(type) : setup.base === type); + const fields: React.ReactNode[] = []; + + if (location === 'rift_furoma') { + fields.push( + onExtra('battery', v)} + />, + ); + } + if (location === 'fort_rox') { + fields.push( +
+ onExtra('ballista', v)} /> + onExtra('cannon', v)} /> +
, + ); + if (stage === 'Heart of the Meteor') { + fields.push( + onExtra('meteorWidth', v)} + />, + ); + } + } + if (location === 'zugzwang_tower') { + fields.push( + onExtra('amplifier', v)} + />, + ); + } + if (location === 'sand_crypts') { + fields.push( + onExtra('salt', v)} + />, + ); + } + if (location === 'ancient_city') { + fields.push( + onExtra('zokorBossDefeated', v)}> + District boss defeated (Forgotten does double) + , + ); + if (stage.startsWith('Lair')) { + fields.push( + onExtra('zokorWidth', v)} + />, + ); + } + } + if (location === 'desert_warpath' && (stage === 'Wave 4' || stage === 'Portal')) { + fields.push( + onExtra('warpathGuards', v)}> + Guards still standing (the boss can’t be caught yet) + , + ); + } + if (location === 'rift_bristle_woods' && stage.startsWith('Acolyte')) { + fields.push( + onExtra('acolyteSand', v)}> + The Acolyte still has sand + , + ); + } + if ([...PRESTIGE_BASES].some(hasBase)) { + fields.push( + onExtra('umbraFloor', v)} + />, + ); + } + if (hasWeapon(GOLEM_GUARDIAN)) { + fields.push( +
+ + onExtra('golemCharge', v)} + /> +
, + ); + } + if (hasWeapon(ISLE_IDOL)) { + fields.push( + , + ); + } + if (hasBase('denture_base') || hasBase('upgraded_denture_base')) { + fields.push( + onExtra('dentureToothless', v)}> + Denture Base is toothless (out of charge) + , + ); + } + if (hasWeapon('chrono_gwh_weapon')) { + fields.push( + onExtra('acolyteCatches', v)} + />, + ); + } + if (population?.mice.some((mouse) => dragons.has(mouse.type))) { + fields.push( + onExtra('dragonsMight', v)}> + Dragon’s Might aura (300% against dragons) + , + ); + } + + if (fields.length === 0) return null; + return ( +
+ Location and item details +

A few more details

+ {fields} +
+ ); +} + +/** + * On a phone the results sit under a long form. This rides at the bottom of the screen while the form is in view + * and jumps down to them. + */ +export function JumpToResults({ target }: { target: string }) { + return ( + + ); +} + +/** What to try when a location, stage and cheese have no mice to show. */ +export function NoDataHint({ cheese, charmsWithData }: { cheese: string; charmsWithData: string[] }) { + if (charmsWithData.length === 0) return <>Try another cheese or stage.; + const list = new Intl.ListFormat('en', { type: 'disjunction' }).format(charmsWithData.slice(0, 4)); + return ( + <> + {cheese} only has attraction data here with a charm. Pick {list} + {charmsWithData.length > 4 ? ', or another marked “Own attraction data”,' : ''} under Charm, or try another + cheese. + + ); +} + +export const startOverClasses = + 'text-sm font-medium text-zinc-600 underline decoration-zinc-300 underline-offset-2 hover:text-zinc-950 focus:outline-hidden focus-visible:ring-2 focus-visible:ring-pink-500 dark:text-zinc-400 dark:decoration-zinc-600 dark:hover:text-white'; diff --git a/src/app/catch-rate-estimator/page.tsx b/src/app/catch-rate-estimator/page.tsx new file mode 100644 index 00000000..acefadaf --- /dev/null +++ b/src/app/catch-rate-estimator/page.tsx @@ -0,0 +1,43 @@ +import React, { Suspense } from 'react'; + +import { ScaleIcon } from '@heroicons/react/20/solid'; +import { Breadcrumbs } from '@/components/breadcrumbs'; +import { PageHeader } from '@/components/page-header'; +import { PageLink } from '@/components/page-link'; + +import { ogCard, pageMetadata } from '@/seo'; +import { CatchRateEstimator, CatchRateEstimatorFromUrl } from './estimator'; + +export const metadata = pageMetadata({ + title: 'MouseHunt Catch Rate Estimator', + description: + 'Pick a MouseHunt location, cheese, and trap setup to see the attraction rate, catch rate, and minluck for every mouse there.', + path: '/catch-rate-estimator', + image: ogCard({ title: 'Catch rate estimator', eyebrow: 'MouseHunt tool', icon: 'scale', accent: 'pink' }), +}); + +export default function CatchRateEstimatorPage() { + return ( +
+ + + Pick where you’re hunting and your trap to see how often you’ll attract and catch each mouse there. Built on{' '} + tsitu’s catch rate estimator, with + attraction rates from MHCT. + + } + icon={ScaleIcon} + iconClassName="bg-pink-100 text-pink-700 dark:bg-pink-950 dark:text-pink-300" + /> + {/* The estimator reads a shared link with useSearchParams, which needs a Suspense boundary to prerender. */} + }> + + +
+ ); +} diff --git a/src/app/error.tsx b/src/app/error.tsx new file mode 100644 index 00000000..50d79596 --- /dev/null +++ b/src/app/error.tsx @@ -0,0 +1,52 @@ +'use client'; + +import React, { useEffect } from 'react'; + +import { Heading } from '@/components/heading'; +import { Link } from '@/components/site-link'; + +const buttonClasses = + 'rounded-lg px-4 py-2 text-sm font-semibold focus:outline-hidden focus-visible:ring-2 focus-visible:ring-pink-500 focus-visible:ring-offset-2 dark:focus-visible:ring-offset-zinc-900'; + +/** + * Shown in place of a page that threw while rendering, with the sidebar still there to leave by. Without it a + * single bad value (a response that has changed shape, a script that failed to load after a deploy) blanks the + * whole page behind the browser's "Application error". + */ +export default function PageError({ error, retry }: { error: unknown; retry: () => void }) { + useEffect(() => { + console.error(error); + }, [error]); + + return ( +
+ This page hit a snag +

+ Something went wrong while showing it. Reloading usually fixes that, especially if the site was updated while + you had it open. +

+
+ + + + Back to home + +
+
+ ); +} diff --git a/src/app/essence-calculator/metadata.ts b/src/app/essence-calculator/metadata.ts index 8d29f444..001f9c94 100644 --- a/src/app/essence-calculator/metadata.ts +++ b/src/app/essence-calculator/metadata.ts @@ -1,8 +1,8 @@ -import { pageMetadata } from '@/seo'; +import { ogCard, pageMetadata } from '@/seo'; export const metadata = pageMetadata({ title: 'MouseHunt Essence Calculator', - description: - 'Calculate your final essence counts after crafting higher-tier essences in MouseHunt. Optimize your essence usage with this handy tool.', + description: 'Calculate your final essence counts after crafting higher-tier essences in MouseHunt.', path: '/essence-calculator', + image: ogCard({ title: 'Essence calculator', eyebrow: 'MouseHunt tool', icon: 'beaker', accent: 'violet' }), }); diff --git a/src/app/essence-calculator/page.tsx b/src/app/essence-calculator/page.tsx index bb8165dc..d3f1600b 100644 --- a/src/app/essence-calculator/page.tsx +++ b/src/app/essence-calculator/page.tsx @@ -1,210 +1,232 @@ 'use client'; import Image from 'next/image'; -import React, { useEffect, useState, type ChangeEvent } from 'react'; +import React, { useEffect, type ChangeEvent } from 'react'; -import { Heading } from '@/components/heading'; +import { useStoredState } from '@/lib/use-stored-state'; + +import { Button } from '@/components/button'; import { Input } from '@/components/input'; +import { Breadcrumbs } from '@/components/breadcrumbs'; +import { PageHeader } from '@/components/page-header'; import { PageLink } from '@/components/page-link'; import { formatNumber } from '@/utils'; +import { HEADLINE_PANEL } from '@/components/panel'; +import { BeakerIcon } from '@heroicons/react/20/solid'; const ESSENCES: string[] = ['Aleth', 'Ber', 'Cynd', 'Dol', 'Est', 'Fel', 'Gur', 'Hix', 'Icuri']; -export default function EssenceCalculator() { - const [amounts, setAmounts] = useState(Array(ESSENCES.length).fill('')); - const [finalCounts, setFinalCounts] = useState(null); +/** Craft every 3 of an essence up into 1 of the next, all the way to Icuri. */ +function calculateFinalEssences(base: number[]): number[] { + const result = [...base]; - const handleChange = (idx: number, value: string) => { - const newAmounts = [...amounts]; - newAmounts[idx] = value.replace(/[^0-9]/g, ''); - setAmounts(newAmounts); - }; + for (let i = 0; i < ESSENCES.length - 1; i++) { + const craftable = Math.floor(result[i] / 3); + result[i] = result[i] % 3; + result[i + 1] += craftable; + } - const calculateFinalEssences = () => { - const baseCounts = amounts.map((a) => parseInt(a || '0', 10)); - const result = [...baseCounts]; + return result; +} - for (let i = 0; i < ESSENCES.length - 1; i++) { - const craftable = Math.floor(result[i] / 3); - result[i] = result[i] % 3; - result[i + 1] += craftable; - } +/** How many of each essence can be crafted from the ones below it. */ +function computeCraftables(base: number[]): number[] { + const craftable = Array(ESSENCES.length).fill(0); + const temp = [...base]; - setFinalCounts(result); - }; + for (let i = 0; i < ESSENCES.length - 1; i++) { + craftable[i + 1] = Math.floor(temp[i] / 3); + temp[i + 1] += craftable[i + 1]; + temp[i] = temp[i] % 3; + } + + return craftable; +} - const computeCraftables = (): number[] => { - const base = amounts.map((a) => parseInt(a || '0', 10)); - const craftable = Array(ESSENCES.length).fill(0); - const temp = [...base]; +function Summary({ finalCounts, crafted }: { finalCounts: number[]; crafted: boolean }) { + if (!crafted) { + return <>Nothing to craft.; + } - for (let i = 0; i < ESSENCES.length - 1; i++) { - craftable[i + 1] = Math.floor(temp[i] / 3); - temp[i + 1] += craftable[i + 1]; - temp[i] = temp[i] % 3; - } + const highest = finalCounts + .map((val, idx) => ({ idx, val })) + .reverse() + .find((e) => e.val > 0); - return craftable; + if (!highest) { + return <>Nothing to craft.; + } + + const highestIdx = highest.idx; + + const remaining = finalCounts + .map((val, idx) => ({ val, name: ESSENCES[idx] })) + .filter((e, idx) => e.val > 0 && idx !== highestIdx) + .reverse(); + + const prettyRemaining = new Intl.ListFormat('en', { type: 'conjunction' }).format( + remaining.map((e) => `${formatNumber(e.val)} ${e.name}`), + ); + + return ( + <> + You’ll end up with{' '} + + {formatNumber(highest.val)} {ESSENCES[highestIdx]} + + {remaining.length > 0 && <>, with {prettyRemaining} left over}. + + ); +} + +/** Saved amounts from an earlier visit: one string of digits per essence. */ +function parseAmounts(saved: unknown): string[] | undefined { + if (!Array.isArray(saved) || saved.length !== ESSENCES.length) return undefined; + return saved.every((amount) => typeof amount === 'string' && /^\d*$/.test(amount)) ? saved : undefined; +} + +export default function EssenceCalculator() { + const [amounts, setAmounts] = useStoredState( + 'mouse.rip:essence-calculator', + Array(ESSENCES.length).fill(''), + parseAmounts, + ); + + const handleChange = (idx: number, value: string) => { + const newAmounts = [...amounts]; + newAmounts[idx] = value.replace(/[^0-9]/g, ''); + setAmounts(newAmounts); }; useEffect(() => { const handlePaste = (e: ClipboardEvent) => { if (!e.clipboardData) return; const text = e.clipboardData.getData('text'); - - setAmounts((current) => { - const newAmounts = [...current]; - ESSENCES.forEach((essence, idx) => { - const regex = new RegExp(`(\\d+[\\d,]*)\\s+${essence} Essence`, 'i'); - const match = text.match(regex); - if (match) { - newAmounts[idx] = match[1].replace(/,/g, ''); - } - }); - return newAmounts; - }); + const pasted = ESSENCES.map((essence) => + text.match(new RegExp(`(\\d+[\\d,]*)\\s+${essence} Essence`, 'i'))?.[1].replace(/,/g, ''), + ); + // A plain number pasted into one box is left to that box. + if (!pasted.some(Boolean)) return; + // The amounts are filled in here. Left alone, the browser would also type the whole pasted text into the + // focused box, which keeps its digits and ends up with a number nobody entered. + e.preventDefault(); + setAmounts((current) => current.map((amount, idx) => pasted[idx] ?? amount)); }; window.addEventListener('paste', handlePaste); return () => window.removeEventListener('paste', handlePaste); - }, []); + }, [setAmounts]); - const craftableFromLower = computeCraftables(); + const base = amounts.map((a) => parseInt(a || '0', 10)); + const hasInput = amounts.some((a) => a !== ''); + const craftableFromLower = computeCraftables(base); + const finalCounts = calculateFinalEssences(base); return ( -
- Essence Calculator - -

- Tip: You can copy your current amounts from the{' '} - - Crafting Table - {' '} - and press Ctrl+V (or Cmd+V) and the calculator will automatically fill out the amounts for each essence. -

- -
{ - e.preventDefault(); - calculateFinalEssences(); - }} - className="mt-6 space-y-6" - aria-label="Essence calculator form" - > -
- - +
+ + + Enter how many of each essence you have to see what they craft up into. You can also copy your amounts from + the{' '} + + Crafting Table + {' '} + and paste them anywhere on this page. + + } + /> + + e.preventDefault()} aria-label="Essence amounts"> +
+
+ - - + {ESSENCES.map((essence, idx) => ( - - + - - ))}
Essence - Current + + You have - Can Craft + Can craft
-
+
+ + ) => handleChange(idx, e.target.value)} - className="w-24 text-right" - aria-label={`Amount of ${essence} Essence`} + className="ml-auto w-24 sm:w-28 [&_input]:text-right" /> - {craftableFromLower[idx] > 0 ? `${craftableFromLower[idx]}` : ''} + + {craftableFromLower[idx] > 0 ? formatNumber(craftableFromLower[idx]) : ''}
- -
- -
- {finalCounts && ( -
-

- {(() => { - const highest = finalCounts - .map((val, idx) => ({ idx, val })) - .reverse() - .find((e) => e.val > 0); - - if (!highest) { - return 'You cannot craft any essences.'; - } - - const highestIdx = highest.idx; - - const remaining = finalCounts - .map((val, idx) => ({ val, name: ESSENCES[idx] })) - .filter((e, idx) => e.val > 0 && idx !== highestIdx) - .reverse(); - - const formattedRemaining = remaining.map((e) => `${formatNumber(e.val)} ${e.name}`).join(', '); - const lastComma = formattedRemaining.lastIndexOf(', '); - const prettyRemaining = - lastComma !== -1 - ? formattedRemaining.slice(0, lastComma) + ' and' + formattedRemaining.slice(lastComma + 1) - : formattedRemaining; - - return ( - <> - You can craft {formatNumber(highest.val)} {ESSENCES[highestIdx]} - {remaining.length > 0 && <> with {prettyRemaining} remaining}. - - ); - })()} -

-
- )} - - {!finalCounts && ( -

- Did you know? It takes 6,561 Aleth Essence to craft 1 Icuri Essence. + {/* The live region stays mounted so the first summary is announced; the box only appears with input. */} +

+

+ {hasInput &&

n > 0)} />}

- )} + {hasInput && ( + + )} +
); } diff --git a/src/app/extensions/page.tsx b/src/app/extensions/page.tsx index 1379e18f..3a7b3788 100644 --- a/src/app/extensions/page.tsx +++ b/src/app/extensions/page.tsx @@ -1,33 +1,76 @@ -import { BoltIcon } from '@heroicons/react/20/solid'; -import { PageHeader } from '@/components/page-header'; -import { ItemList } from '@/components/item-list'; - +import { ArrowUpRightIcon, BoltIcon } from '@heroicons/react/20/solid'; +import clsx from 'clsx'; import React from 'react'; +import { Breadcrumbs } from '@/components/breadcrumbs'; +import { PageHeader } from '@/components/page-header'; import { getResourcesByCategory } from '@/lib/site-data'; import { pageMetadata } from '@/seo'; export const metadata = pageMetadata({ title: 'MouseHunt Browser Extensions', - description: - 'Browser extensions that improve MouseHunt — quality-of-life upgrades, helper tools, and data tracking for catch-rate calculators.', + description: 'Browser extensions that add in-game improvements to MouseHunt and log your hunts for community tools.', path: '/extensions', }); +const button = + 'inline-flex min-h-10 items-center gap-1.5 rounded-full px-4 text-sm font-semibold transition-colors focus:outline-hidden focus-visible:ring-2 focus-visible:ring-pink-500 focus-visible:ring-offset-2 dark:focus-visible:ring-offset-zinc-900'; + +function OutLink({ href, className, children }: { href: string; className: string; children: React.ReactNode }) { + return ( + + {children} + + ); +} + export default async function Extensions() { const items = getResourcesByCategory('extension'); return ( <> + - +
    + {items.map((item) => ( +
  • +

    {item.name}

    +

    {item.description}

    +
    + {item.install?.map(({ browser, url }) => ( + + Add to {browser} + + ))} + + {item.install?.length ? `Source on ${item.source ?? 'GitHub'}` : `Get it on ${item.source ?? 'GitHub'}`} + +
    +
  • + ))} +
); } diff --git a/src/app/groups/[slug]/page.tsx b/src/app/groups/[slug]/page.tsx index afc707c8..9b74f846 100644 --- a/src/app/groups/[slug]/page.tsx +++ b/src/app/groups/[slug]/page.tsx @@ -7,7 +7,7 @@ import { MouseGrid } from '@/components/mouse-grid'; import { getAllMiceGroups, getMiceForGroup, getMiceGroupBySlug } from '@/lib/game-data'; import { ogCard, pageMetadata } from '@/seo'; -import { cleanDescription } from '@/utils'; +import { cleanDescription, formatCount } from '@/utils'; import { mouseGroupImageUrl } from '@/lib/image-urls'; import { SectionHeading } from '@/components/section-heading'; @@ -23,14 +23,15 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str if (!group) return { title: 'Not Found' }; return pageMetadata({ - title: `${group.name} — MouseHunt Mice`, + title: `${group.name}: MouseHunt Mouse Group`, description: cleanDescription(group.description).slice(0, 160) || `Every mouse in the ${group.name} group in MouseHunt.`, path: `/groups/${slug}`, image: ogCard({ title: group.name, eyebrow: 'Mouse group', - subtitle: `${group.mouse_ids.length} mice`, + subtitle: formatCount(group.mouse_ids.length, 'mouse', 'mice'), + banner: mouseGroupImageUrl(group.id), accent: 'emerald', }), }); @@ -42,6 +43,14 @@ export default async function GroupPage({ params }: { params: Promise<{ slug: st if (!group) notFound(); const mice = getMiceForGroup(group); + // Groups like the Gauntlet or the seasons split into subgroups; show each under its own heading, in game order. + const sections: { name: string; mice: typeof mice }[] = []; + for (const mouse of mice) { + const name = mouse.subgroup || group.name; + const section = sections.find((entry) => entry.name === name); + if (section) section.mice.push(mouse); + else sections.push({ name, mice: [mouse] }); + } return (
@@ -64,10 +73,25 @@ export default async function GroupPage({ params }: { params: Promise<{ slug: st

)} - {mice.length} mice in this group -
- -
+ + {mice.length} {mice.length === 1 ? 'mouse' : 'mice'} + + {sections.length > 1 ? ( + sections.map((section) => ( +
+

+ {section.name} {section.mice.length} +

+
+ +
+
+ )) + ) : ( +
+ +
+ )}
); } diff --git a/src/app/guides/[slug]/guide-content.ts b/src/app/guides/[slug]/guide-content.ts index d9e5df27..32f0a54d 100644 --- a/src/app/guides/[slug]/guide-content.ts +++ b/src/app/guides/[slug]/guide-content.ts @@ -16,3 +16,32 @@ export function getGuideBody(slug: string): string | null { return null; } } + +/** A guide gets a contents list when it has this many sections and is long enough to need one. */ +const MIN_SECTIONS = 4; +const MIN_LENGTH = 4000; + +/** + * The guide's sections, from its `##` headings, for a contents list at the top. Empty when the guide is short or + * writes its own contents. The ids come from the same headingId the rendered headings use, so the links land. + */ +export function guideSections( + body: string, + headingId: (text: string) => string | undefined, +): { id: string; title: string }[] { + if (body.length < MIN_LENGTH || /^\*\*Contents\*\*$/m.test(body)) return []; + const sections: { id: string; title: string }[] = []; + let fenced = false; + for (const line of body.split('\n')) { + if (line.startsWith('```')) fenced = !fenced; + if (fenced || !line.startsWith('## ')) continue; + const title = line + .slice(3) + .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1') + .replace(/[*_`]/g, '') + .trim(); + const id = headingId(title); + if (id) sections.push({ id, title }); + } + return sections.length >= MIN_SECTIONS ? sections : []; +} diff --git a/src/app/guides/[slug]/page.tsx b/src/app/guides/[slug]/page.tsx index 15fbb88a..0275a8dd 100644 --- a/src/app/guides/[slug]/page.tsx +++ b/src/app/guides/[slug]/page.tsx @@ -3,12 +3,12 @@ import { AcademicCapIcon } from '@heroicons/react/20/solid'; import { Breadcrumbs } from '@/components/breadcrumbs'; import { PageHeader } from '@/components/page-header'; -import { Markdown } from '@/components/markdown'; +import { Markdown, headingId } from '@/components/markdown'; import { PageLink } from '@/components/page-link'; import { getGuide, getOnSiteGuides } from '@/lib/site-data'; import { pageMetadata } from '@/seo'; -import { getGuideBody } from './guide-content'; +import { getGuideBody, guideSections } from './guide-content'; import { scriptJson } from '@/components/json-ld'; // Only build the guides we know about; unknown slugs 404 instead of trying to @@ -30,13 +30,30 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str } return pageMetadata({ - title: `${guide.name} — MouseHunt Guide`, + title: `${guide.name}: MouseHunt Guide`, description: guide.description, path: guide.url, type: 'article', }); } +/** Where a guide first appeared, by name rather than as a long raw link. */ +function sourceName(url: string): string { + try { + const host = new URL(url).hostname.replace(/^www\./, ''); + const names: Record = { + 'docs.google.com': 'Google Docs', + 'reddit.com': 'Reddit', + 'old.reddit.com': 'Reddit', + 'mhwiki.hitgrab.com': 'MHWiki', + 'pastebin.com': 'Pastebin', + }; + return names[host] ?? host; + } catch { + return url; + } +} + export default async function Guide({ params }: { params: Promise<{ slug: string }> }) { const { slug } = await params; const guide = getGuide(slug); @@ -47,6 +64,7 @@ export default async function Guide({ params }: { params: Promise<{ slug: string } const url = `https://mouse.rip${guide.url}`; + const sections = guideSections(body, headingId); return ( // Guides are long-form prose, so they keep a readable measure inside the @@ -75,14 +93,36 @@ export default async function Guide({ params }: { params: Promise<{ slug: string iconClassName="bg-pink-100 text-pink-700 dark:bg-pink-950 dark:text-pink-300" /> + {sections.length > 0 && ( + + )} +
{body}
{guide.sourceUrl && (
- Originally published at {guide.sourceUrl}. Reproduced here for - easier reading. + First published on {sourceName(guide.sourceUrl)}.
)}
diff --git a/src/app/guides/page.tsx b/src/app/guides/page.tsx index 9c9b8e0f..7217a377 100644 --- a/src/app/guides/page.tsx +++ b/src/app/guides/page.tsx @@ -1,33 +1,71 @@ import { AcademicCapIcon } from '@heroicons/react/20/solid'; +import { Breadcrumbs } from '@/components/breadcrumbs'; import { PageHeader } from '@/components/page-header'; import { ItemList } from '@/components/item-list'; +import { SectionHeading } from '@/components/section-heading'; +import { ToolCard, type Tint } from '@/components/tool-card'; import React from 'react'; +import { itemImageUrl, titleImageUrl } from '@/lib/image-urls'; import { getResourcesByCategory } from '@/lib/site-data'; import { pageMetadata } from '@/seo'; export const metadata = pageMetadata({ title: 'MouseHunt Guides', description: - 'MouseHunt strategy and how-to guides, from your first hunt to endgame optimization, written and curated by experienced hunters.', + 'MouseHunt strategy and how-to guides written by other hunters, covering traps, locations, and rank progression.', path: '/guides', }); +/** mouse.rip's own reference pages: game facts rather than strategy, kept here instead of in the sidebar. */ +const reference: { href: string; name: string; description: string; image: string; tint: Tint }[] = [ + { + href: '/titles', + name: 'Titles and ranks', + description: 'Every hunter rank from Novice to Fabled, and what each one needs.', + image: titleImageUrl('fabled'), + tint: 'pink', + }, + { + href: '/trap-special-effects', + name: 'Trap and base special effects', + description: 'Traps and bases that behave differently in specific locations.', + image: itemImageUrl('chrome_acronym_weapon'), + tint: 'sky', + }, +]; + export default async function Guides() { const items = await getResourcesByCategory('guide'); return ( <> + - +
+ Guides + +
+ + {/* The site's own reference pages come after the guides, which are what most visitors came for. */} +
+ Game reference +
    + {reference.map(({ href, name, description, image, tint }) => ( +
  • + +
  • + ))} +
+
); } diff --git a/src/app/items/[slug]/convertible-contents.tsx b/src/app/items/[slug]/convertible-contents.tsx index 32b3940e..39dc413e 100644 --- a/src/app/items/[slug]/convertible-contents.tsx +++ b/src/app/items/[slug]/convertible-contents.tsx @@ -2,18 +2,26 @@ import React, { useEffect, useState } from 'react'; -import { Link } from 'next-view-transitions'; +import { Link } from '@/components/site-link'; import type { ConvertibleRow } from '@/types'; -import { formatGold } from '@/utils'; +import { formatGold, formatNumber } from '@/utils'; import { itemImageUrl } from '@/lib/image-urls'; import { SectionHeading } from '@/components/section-heading'; import { SourceLink } from '@/components/source-link'; +import { formatPriceDate, isCurrentPrice } from './market-price'; + interface MarkethuntListRow { item_info: { item_id: number }; // null for items Markethunt tracks but has no market data for (~10% of rows). - latest_market_data: { price: number } | null; + latest_market_data: { price: number; date?: string } | null; +} + +/** An item's latest Markethunt price and the day it's from. */ +interface LatestPrice { + price: number; + date?: string; } /** @@ -25,18 +33,21 @@ const INTRINSIC_PRICES: Record = { 431: 1 }; // The list covers every item, so share one request across convertible pages for // the whole session instead of refetching it on each navigation. -let pricesPromise: Promise> | null = null; +let pricesPromise: Promise> | null = null; -function loadMarketPrices(): Promise> { +function loadMarketPrices(): Promise> { if (!pricesPromise) { - pricesPromise = fetch('https://api.markethunt.win/items') + pricesPromise = fetch('https://api.markethunt.win/items', { signal: AbortSignal.timeout(15_000) }) .then((res) => (res.ok ? (res.json() as Promise) : Promise.reject())) .then((rows) => { if (!Array.isArray(rows)) throw new Error('Unexpected Markethunt response'); return new Map( - rows.flatMap((row) => - row.latest_market_data ? [[row.item_info.item_id, row.latest_market_data.price] as [number, number]] : [], - ), + rows.flatMap((row) => { + const latest = row?.latest_market_data; + return latest && typeof latest.price === 'number' && typeof row.item_info?.item_id === 'number' + ? [[row.item_info.item_id, { price: latest.price, date: latest.date }] as [number, LatestPrice]] + : []; + }), ); }) .catch((error) => { @@ -49,13 +60,14 @@ function loadMarketPrices(): Promise> { } /** - * Current marketplace prices by item id, fetched once from Markethunt. Stays - * null unless the fetch actually succeeds: with no market data, the only rewards - * we could price are the intrinsic ones, and totalling those alone would state a - * confident "worth ~X gold" that is off by orders of magnitude. + * The latest marketplace price for each item id, fetched once from Markethunt. + * + * Stays null unless the fetch actually succeeds: with no market data, the only + * rewards we could price are the intrinsic ones, and totalling those alone would + * state a confident "worth ~X gold" that is off by orders of magnitude. */ -function useMarketPrices(): Map | null { - const [prices, setPrices] = useState | null>(null); +function useMarketPrices(): Map | null { + const [prices, setPrices] = useState | null>(null); useEffect(() => { let active = true; @@ -70,9 +82,9 @@ function useMarketPrices(): Map | null { return prices; } -/** Expected gold from one row: drop chance × average quantity × current price. */ -function rowValue(row: ConvertibleRow, prices: Map | null): number | null { - const price = INTRINSIC_PRICES[row.id] ?? prices?.get(row.id); +/** Expected gold from one row: drop chance × average quantity × latest price. */ +function rowValue(row: ConvertibleRow, prices: Map | null): number | null { + const price = INTRINSIC_PRICES[row.id] ?? prices?.get(row.id)?.price; if (price == null) return null; const averageQuantity = ((row.min ?? row.max ?? 0) + (row.max ?? row.min ?? 0)) / 2; const chance = Number(row.chance) / 100; @@ -82,8 +94,8 @@ function rowValue(row: ConvertibleRow, prices: Map | null): numb function formatQuantity(min: number, max: number): string { if (!min && !max) return ''; - if (min === max) return `${min}`; - return `${min}–${max}`; + if (min === max) return formatNumber(min); + return `${formatNumber(min)}–${formatNumber(max)}`; } /** @@ -98,18 +110,21 @@ export function ConvertibleContents({ itemId, rows }: { itemId: number; rows: Co const expectedValue = valued.reduce((sum, { value }) => sum + (value ?? 0), 0); const pricedCount = valued.filter(({ value }) => value != null).length; const showValues = prices !== null && pricedCount > 0; - const ownPrice = prices?.get(itemId); + const own = prices?.get(itemId); + // Read once the prices are in: they arrive in the browser, so there's no server render to match. + const [now] = useState(() => Date.now()); + const ownIsCurrent = own?.date ? isCurrentPrice(own.date, now) : true; return (
What’s inside

- Possible rewards from opening this, with observed chances from . + From .

-
+
- + @@ -166,17 +181,21 @@ export function ConvertibleContents({ itemId, rows }: { itemId: number; rows: Co ~{formatGold(expectedValue)} gold {' '} on average - {ownPrice != null && ( - <> - {' '} - — it currently sells for {formatGold(ownPrice)} gold on the - marketplace - - )} + {own != null && + (ownIsCurrent ? ( + <> + , and it currently sells for {formatGold(own.price)} gold on the + Marketplace + + ) : ( + <> + , and it last sold for {formatGold(own.price)} gold on the + Marketplace, on {formatPriceDate(own.date!)} + + ))} .{' '} - - Covers {pricedCount} of {valued.length} possible rewards, at current Markethunt prices; each reward’s - average value is its chance × quantity × price. + + Covers {pricedCount} of {valued.length} rewards, at the latest price Markethunt has for each.

)} diff --git a/src/app/items/[slug]/item-data.tsx b/src/app/items/[slug]/item-data.tsx index a12a1dab..21b05d86 100644 --- a/src/app/items/[slug]/item-data.tsx +++ b/src/app/items/[slug]/item-data.tsx @@ -1,18 +1,22 @@ import React from 'react'; -import { Link } from 'next-view-transitions'; +import { Link } from '@/components/site-link'; import { LocationCell } from '@/components/mhct-cells'; import type { ConvertibleRow, FoundInConvertible, ItemDropper, MapRelation } from '@/types'; -import { formatNumber } from '@/utils'; +import { formatCompactNumber, formatNumber } from '@/utils'; import { itemImageUrl } from '@/lib/image-urls'; import { ConvertibleContents } from './convertible-contents'; import { SectionHeading } from '@/components/section-heading'; import { SourceLink } from '@/components/source-link'; +import { GameImage } from '@/components/game-image'; // Common items (Gold, SB+) come from hundreds of openables; listing them all // makes the page several hundred KB. -const FOUND_IN_LIMIT = 50; +// Shown before the "Show all" disclosure, so the ranked drop table isn't pushed down. +const FOUND_IN_PREVIEW = 8; +// Drop rows shown before "Show all"; the long tail is mostly tiny samples. +const DROPS_PREVIEW = 10; function formatQuantity(min: number, max: number): string { if (!min && !max) return ''; @@ -20,8 +24,74 @@ function formatQuantity(min: number, max: number): string { return `${min}–${max}`; } +function DropsTable({ rows }: { rows: ItemDropper[] }) { + return ( +
+
Reward Quantity
+ + + + + + + + + + + {rows.map((row) => ( + + + + + + + + ))} + +
MouseLocationQty + Rate + Drop rate + Sample
+ + {row.mouse_name} + + + + {row.locations.length > 1 && ( +
+ + +{row.locations.length - 1} more + Fewer + +
    + {row.locations.slice(1).map((location) => ( +
  • + +
  • + ))} +
+
+ )} +
+ {formatQuantity(row.min, row.max) || '—'} + + {row.drop_likelihood}%{/* On phones Qty and Sample are hidden, so the sample rides under the rate. */} + + {formatCompactNumber(row.catches)} catches + + + {formatNumber(row.catches)} catches +
+
+ ); +} + /** * Everything an item page knows about where it comes from and where it goes. + * * All of it is baked in at build time (see scripts/update-data.js), so it * server-renders — the only thing still fetched from the client is the live * Markethunt price, inside ConvertibleContents. @@ -30,6 +100,7 @@ export function ItemData({ itemId, obtainHint, contents, + isConvertible = false, drops, foundIn, mapRelations, @@ -38,6 +109,8 @@ export function ItemData({ itemId: number; obtainHint?: string; contents: ConvertibleRow[]; + /** A convertible with no contents on record still says so, rather than leaving out the section. */ + isConvertible?: boolean; drops: ItemDropper[]; foundIn: FoundInConvertible[]; mapRelations: MapRelation[]; @@ -51,111 +124,75 @@ export function ItemData({ How to get it {obtainHint && ( -

+

{obtainHint}

)} - {foundIn.length > 0 && ( + {drops.length > 0 && (
-

From openables

-

- Chests, baskets, and other items that can contain this. +

Hunting drops

+

+ From .

+
+ +
+ {drops.length > DROPS_PREVIEW && ( +
+ + Show all {formatNumber(drops.length)} + Show fewer + +
+ +
+
+ )} +
+ )} + {foundIn.length > 0 && ( +
0 ? 'mt-8' : 'mt-5'}> +

+ Found inside{' '} + ({formatNumber(foundIn.length)}) +

    - {foundIn.slice(0, FOUND_IN_LIMIT).map((source) => ( + {foundIn.slice(0, FOUND_IN_PREVIEW).map((source) => (
  • - {source.slug ? ( - - {/* eslint-disable-next-line @next/next/no-img-element */} - - {source.name} - - ) : ( - - {source.name} - - )} +
  • ))} - {foundIn.length > FOUND_IN_LIMIT && ( -
  • - and {formatNumber(foundIn.length - FOUND_IN_LIMIT)} more -
  • - )}
-
- )} - - {drops.length > 0 && ( -
-

Hunting drops

-

- The mice that drop it and how often, from . Rates are crowdsourced — check - the sample size before trusting one. -

-
- - - - - - - - - - - - {drops.map((row) => ( - - - - - - - + {foundIn.length > FOUND_IN_PREVIEW && ( +
+ + Show all {formatNumber(foundIn.length)} + Show fewer + +
    + {foundIn.slice(FOUND_IN_PREVIEW).map((source) => ( +
  • + +
  • ))} -
-
MouseLocationQtyDrop rateSample
- - {row.mouse_name} - - - - {row.locations.length > 1 && ( - - {' '} - +{row.locations.length - 1} more - - )} - - {formatQuantity(row.min, row.max) || '—'} - - {row.drop_likelihood}% - - {formatNumber(row.catches)} catches -
-
+ + + )}
)}
)} {contents.length > 0 && } + {isConvertible && contents.length === 0 && ( +
+ What’s inside +

+ has no record of what this one holds yet. +

+
+ )} {mapRelations.length > 0 && }
@@ -180,21 +217,16 @@ function MapRelations({ return (
{isScrollCase ? 'Maps it opens' : 'Which map awards it'} -

- {isScrollCase - ? 'Opening this scroll case starts one of these maps. Completing a map awards its treasure chest.' - : 'This chest is awarded for completing the map below, which starts from its scroll case.'} -

{relations.map((relation) => (
{relation.map.name} {!isScrollCase && ( - + from{' '} @@ -204,15 +236,15 @@ function MapRelations({ {relation.chests.map((chest) => (
  • {chest.rare && ( - + Rare )} @@ -242,8 +274,25 @@ function ItemChipLink({ const slug = itemSlugs[id]; if (plain || !slug) return <>{name}; return ( - + {name} ); } + +/** A chest or other openable this item comes out of, as a pill with its picture. */ +function SourceChip({ source }: { source: { name: string; slug?: string } }) { + const classes = + 'inline-flex min-h-9 items-center gap-2 rounded-full bg-white px-3 py-1.5 text-sm ring-1 ring-zinc-200 dark:bg-zinc-900 dark:ring-zinc-800'; + return source.slug ? ( + + + {source.name} + + ) : ( + {source.name} + ); +} diff --git a/src/app/items/[slug]/market-price.tsx b/src/app/items/[slug]/market-price.tsx index b5decd9b..2a691145 100644 --- a/src/app/items/[slug]/market-price.tsx +++ b/src/app/items/[slug]/market-price.tsx @@ -1,5 +1,6 @@ 'use client'; +import { ArrowUpRightIcon } from '@heroicons/react/20/solid'; import React, { useEffect, useMemo, useState } from 'react'; import { formatGold, formatSb } from '@/utils'; @@ -24,9 +25,9 @@ type State = | { status: 'error' }; const RANGES = [ - { key: '90d', label: '90d', days: 90 }, - { key: '1y', label: '1y', days: 365 }, - { key: 'all', label: 'All', days: Number.POSITIVE_INFINITY }, + { key: '90d', label: '90d', days: 90, period: 'over 90 days' }, + { key: '1y', label: '1y', days: 365, period: 'over the past year' }, + { key: 'all', label: 'All', days: Number.POSITIVE_INFINITY, period: null }, ] as const; type RangeKey = (typeof RANGES)[number]['key']; @@ -35,14 +36,43 @@ function formatCompact(value: number): string { return new Intl.NumberFormat('en-US', { notation: 'compact', maximumFractionDigits: 1 }).format(value); } +const dateFormat = new Intl.DateTimeFormat('en-US', { + month: 'short', + day: 'numeric', + year: 'numeric', + timeZone: 'UTC', +}); + +/** Markethunt's YYYY-MM-DD as "Oct 14, 2026". Read as UTC so the day doesn't shift with the visitor's time zone. */ +export function formatPriceDate(date: string): string { + const parsed = new Date(`${date}T00:00:00Z`); + return Number.isNaN(parsed.getTime()) ? date : dateFormat.format(parsed); +} +const formatDate = formatPriceDate; + +/** Markethunt only has a price for days an item traded. Past this, the latest one is history, not today's price. */ +const CURRENT_PRICE_DAYS = 14; + +/** Whether a Markethunt date is recent enough to call its price current. */ +export function isCurrentPrice(date: string, now: number): boolean { + const time = new Date(`${date}T00:00:00Z`).getTime(); + return Number.isFinite(time) && now - time <= CURRENT_PRICE_DAYS * 86_400_000; +} + +/** A day's entry with the fields the card needs, whatever else the response holds. */ +function isPricePoint(point: unknown): point is PricePoint { + if (!point || typeof point !== 'object') return false; + const { date, price } = point as Record; + return typeof date === 'string' && typeof price === 'number' && Number.isFinite(price); +} + // Chart geometry (SVG user units; the element itself is responsive). const W = 640; -const H = 240; +const H = 220; const PRICE_TOP = 10; const PRICE_BOTTOM = 168; const VOL_TOP = 178; const VOL_BOTTOM = 214; -const LABEL_Y = 234; export function PriceChart({ points }: { points: PricePoint[] }) { const [hoverIndex, setHoverIndex] = useState(null); @@ -88,136 +118,181 @@ export function PriceChart({ points }: { points: PricePoint[] }) { }; const stroke = geometry.up ? '#059669' : '#e11d48'; + // Screen readers get the shape of the chart as a sentence, since the chart itself is visual only. + const first = series[0]; + const last = series[series.length - 1]; + const summary = `Price history from ${formatDate(first.date)} to ${formatDate(last.date)}: ${formatGold(first.price)} to ${formatGold( + last.price, + )} gold, ranging ${formatGold(geometry.min)} to ${formatGold(geometry.max)}.`; return (
    -
    - {hovered ? ( + {/* Hover readout. Holds its height when empty so the chart doesn't jump. */} +
    + {hovered && ( <> - {hovered.date} + {formatDate(hovered.date)} {formatGold(hovered.price)} gold - {formatSb(hovered.sb_price)} SB + {formatSb(hovered.sb_price)} SUPER|brie+ {hovered.volume != null ? `${formatCompact(hovered.volume)} traded` : ''} - ) : ( - - {series[0].date} – {series[series.length - 1].date} - )}
    - setHoverIndex(null)} - > - {/* Gridlines at min / mid / max */} - {[geometry.max, (geometry.max + geometry.min) / 2, geometry.min].map((value, i) => ( - - - +
    + {/* Y-axis labels sit in their own gutter so the line never runs over them. Text lives in HTML, + not the SVG: the SVG stretches to fit, which would distort it. */} + + setHoverIndex(null)} + > + {/* Gridlines at min / mid / max */} + {[geometry.max, (geometry.max + geometry.min) / 2, geometry.min].map((value, i) => ( + + + + ))} + + + + + {/* Volume bars */} + {series.map((point, index) => { + const volume = point.volume ?? 0; + if (volume <= 0) return null; + const height = (volume / geometry.maxVolume) * (VOL_BOTTOM - VOL_TOP); + return ( + + ); + })} + + {/* Hover crosshair */} + {hovered && hoverIndex !== null && ( + + + + + )} + +
    +
    ); } export function MarketPrice({ itemId }: { itemId: number }) { - const [result, setResult] = useState<{ itemId: number; state: State } | null>(null); + const [result, setResult] = useState<{ itemId: number; attempt: number; state: State } | null>(null); + const [attempt, setAttempt] = useState(0); // Don't leave the previous item's chart up while this one loads. - const state: State = result?.itemId === itemId ? result.state : { status: 'loading' }; + const state: State = result?.itemId === itemId && result.attempt === attempt ? result.state : { status: 'loading' }; useEffect(() => { let active = true; - const setState = (next: State) => setResult({ itemId, state: next }); - fetch(`https://api.markethunt.win/items/${itemId}`) + const setState = (next: State) => setResult({ itemId, attempt, state: next }); + // Without a limit, a request that stalls leaves the loading block pulsing with no "Try again". + fetch(`https://api.markethunt.win/items/${itemId}`, { signal: AbortSignal.timeout(15_000) }) .then((res) => (res.ok ? (res.json() as Promise) : Promise.reject())) .then((data) => { if (!active) return; - if (!data.market_data || data.market_data.length === 0) { + // Markethunt isn't ours: keep only the days that read as a date and a price, so a change on their side + // shows as no chart rather than breaking the page. + const points = Array.isArray(data?.market_data) ? data.market_data.filter(isPricePoint) : []; + if (points.length === 0) { setState({ status: 'empty' }); } else { - setState({ status: 'ready', data }); + setState({ status: 'ready', data: { ...data, market_data: points } }); } }) .catch(() => active && setState({ status: 'error' })); return () => { active = false; }; - }, [itemId]); + }, [itemId, attempt]); - // Don't render the section at all if this item isn't on the marketplace. - if (state.status === 'empty' || state.status === 'error') return null; + // Items with no marketplace history get no section at all. + if (state.status === 'empty') return null; return (
    Marketplace price - {state.status === 'loading' && ( -
    + {state.status === 'loading' && attempt === 0 && ( +
    + )} + + {/* While a retry is under way the message stays, with its button, so the keyboard isn't left on nothing. */} + {(state.status === 'error' || (state.status === 'loading' && attempt > 0)) && ( +

    + Couldn’t load prices from Markethunt.{' '} + {' '} + or{' '} + + open it on Markethunt + + . +

    )} {state.status === 'ready' && } @@ -228,10 +303,15 @@ export function MarketPrice({ itemId }: { itemId: number }) { function MarketCard({ itemId, data }: { itemId: number; data: MarkethuntResponse }) { const series = data.market_data!; const [range, setRange] = useState('90d'); + const [showTable, setShowTable] = useState(false); const latest = series[series.length - 1]; const latestTime = new Date(latest.date).getTime(); + // Read once: the card is drawn after the prices arrive in the browser, so there's no server render to match. + const [now] = useState(() => Date.now()); + const current = isCurrentPrice(latest.date, now); + const selected = RANGES.find((option) => option.key === range)!; const window = useMemo(() => { const days = RANGES.find((option) => option.key === range)!.days; if (!Number.isFinite(days)) return series; @@ -240,54 +320,76 @@ function MarketCard({ itemId, data }: { itemId: number; data: MarkethuntResponse return sliced.length > 1 ? sliced : series.slice(-2); }, [series, range, latestTime]); - // Price ~30 days ago, by date, for the trend figure. - const monthAgo = series.find((point) => new Date(point.date).getTime() >= latestTime - 30 * 86400000) ?? series[0]; - const change = monthAgo.price ? ((latest.price - monthAgo.price) / monthAgo.price) * 100 : 0; + // The trend figure covers the same span as the chart, so it changes with the range buttons. + const start = window[0]; + const change = start.price ? ((latest.price - start.price) / start.price) * 100 : 0; const up = change >= 0; + const period = selected.period ?? `since ${formatDate(start.date)}`; const high = window.reduce((best, point) => (point.price > best.price ? point : best), window[0]); const low = window.reduce((best, point) => (point.price < best.price ? point : best), window[0]); return ( -
    +
    {formatGold(latest.price)} - gold + gold
    -
    - - {up ? '▲' : '▼'} {Math.abs(change).toFixed(1)}% / 30d - - {formatSb(latest.sb_price)} SB +
    + {current ? ( + + + {up ? 'Up' : 'Down'} {Math.abs(change).toFixed(1)}% {period} + + ) : ( + // An item that hasn't traded lately: the date matters more than a trend that ended back then. + + Last traded {formatDate(latest.date)} + + )} + {/* SUPER|brie+ priced in itself is always 1 SB; skip the noise. */} + {Math.abs(latest.sb_price - 1) > 0.001 && ( + {formatSb(latest.sb_price)} SUPER|brie+ + )}
    -
    +
    {RANGES.map((option) => ( ))}
    -
    - High {formatCompact(high.price)} ({high.date}) ¡ Low {formatCompact(low.price)} ({low.date}) +
    +
    + High {formatCompact(high.price)} on {formatDate(high.date)} +
    +
    + Low {formatCompact(low.price)} on {formatDate(low.date)} +
    @@ -296,18 +398,64 @@ function MarketCard({ itemId, data }: { itemId: number; data: MarkethuntResponse
    -
    + {/* Hovering the chart reads out a day's price, which a keyboard or a screen reader can't do. The same days, + newest first, as a table; its rows are only made once it's opened. */} +
    setShowTable(event.currentTarget.open)}> + + Show these prices as a table + + {showTable && ( +
    + + + + + + + + + + + {[...window].reverse().map((point) => ( + + + + + + ))} + +
    Price and amount traded for each day in the chart
    + Day + + Price + + Traded +
    + {formatDate(point.date)} + + {formatGold(point.price)} + + {point.volume != null ? formatGold(point.volume) : ''} +
    +
    + )} +
    + +
    - {latest.volume != null ? `${formatGold(latest.volume)} traded` : 'Volume unavailable'} · as of {latest.date} · - data from Markethunt + + {latest.volume != null && `${formatGold(latest.volume)} traded, `}as of {formatDate(latest.date)} + - View on Markethunt → + Price history on Markethunt + (opens in a new tab) +
    diff --git a/src/app/items/[slug]/page.tsx b/src/app/items/[slug]/page.tsx index f2d01a5e..c7a4ad0d 100644 --- a/src/app/items/[slug]/page.tsx +++ b/src/app/items/[slug]/page.tsx @@ -1,13 +1,15 @@ +import clsx from 'clsx'; import { notFound } from 'next/navigation'; import React from 'react'; import { Breadcrumbs } from '@/components/breadcrumbs'; import { ExternalRefs } from '@/components/external-refs'; import { Heading } from '@/components/heading'; -import { Link } from 'next-view-transitions'; +import { Link } from '@/components/site-link'; -import { getLocations } from '@/lib/site-data'; +import { getLocations, getTitles } from '@/lib/site-data'; import { + estimatorParamFor, getAllGameItems, getConvertibleContents, getConvertiblesContaining, @@ -21,12 +23,14 @@ import { descriptionToParagraphs, powerTypeLabel, POWER_TYPE_CHIP } from '@/lib/ import type { GameItem, GameItemStats, MapRelation } from '@/types'; import { JsonLd } from '@/components/json-ld'; import { itemJsonLd, itemSeo } from '@/lib/entity-seo'; -import { itemImageUrl } from '@/lib/image-urls'; +import { itemCdnImageUrl, itemImageUrl } from '@/lib/image-urls'; import { ogCard, pageMetadata } from '@/seo'; import { formatNumber, titleCase } from '@/utils'; +import { classificationLabel, classificationName } from '@/lib/item-classifications'; import { ItemData } from './item-data'; import { MarketPrice } from './market-price'; import { SectionHeading } from '@/components/section-heading'; +import { GameImage } from '@/components/game-image'; export const dynamicParams = false; @@ -43,7 +47,7 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str contents: item.classification === 'convertible' ? getConvertibleContents(item.id) : [], drops: getItemDrops(item.id), }); - const cardImage = pickImage(item); + const cardImage = item?.images ? itemCdnImageUrl(item.type, 'large') : undefined; const stats = item.has_stats && typeof item.has_stats === 'object' ? item.has_stats : null; const cardSubtitle = stats ? [ @@ -53,7 +57,7 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str stats.has_cheese_effect && stats.cheese_effect ? stats.cheese_effect : null, ] .filter(Boolean) - .join(' ¡ ') + .join(', ') : ''; return pageMetadata({ title, @@ -61,7 +65,7 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str path: `/items/${slug}`, image: ogCard({ title: item.name, - eyebrow: titleCase(item.classification), + eyebrow: classificationName(item.classification), subtitle: cardSubtitle || undefined, image: cardImage, accent: 'blue', @@ -133,7 +137,7 @@ function rankNote(item: GameItem, stats: GameItemStats): string | null { item.classification === 'weapon' ? `${stats.power_type ? `${powerTypeLabel(stats.power_type)} ` : ''}weapons` : 'bases'; - return `${parts.join(' ¡ ')} of ${peers.length} ${peerLabel}`; + return `${parts.join(' and ')} of ${peers.length} ${peerLabel}`; } /** Locations this item can be used in, linked to their pages when we have one. */ @@ -170,19 +174,43 @@ function skinTarget(item: GameItem): GameItem | undefined { return skinTargets.get(item.type); } -/** Items of the same classification that share the most tags with this one. */ +/** How many items of each classification carry each tag, for weighing a shared tag by how rare it is. */ +const tagCounts = new Map>(); +function tagCountsFor(classification: string): Map { + let counts = tagCounts.get(classification); + if (!counts) { + counts = new Map(); + for (const peer of itemsWithClassification(classification)) { + for (const tag of new Set(peer.tags ?? [])) counts.set(tag, (counts.get(tag) ?? 0) + 1); + } + tagCounts.set(classification, counts); + } + return counts; +} + +/** + * Items of the same classification that share the most telling tags with this one. A tag on more than a quarter of + * them ("convertibles", "treasure_chests") says nothing; rarer shared tags count for more. + */ function relatedItems(item: GameItem): GameItem[] { - const tags = new Set((item.tags ?? []).filter((tag) => tag !== item.classification)); - if (tags.size === 0) return []; + const peers = itemsWithClassification(item.classification); + const counts = tagCountsFor(item.classification); + const weights = new Map(); + for (const tag of new Set(item.tags ?? [])) { + const count = counts.get(tag) ?? 0; + if (tag === item.classification || count < 2 || count > peers.length / 4) continue; + weights.set(tag, Math.log(peers.length / count)); + } + if (weights.size === 0) return []; - return itemsWithClassification(item.classification) + return peers .filter((peer) => peer.id !== item.id) .map((peer) => ({ peer, - shared: (peer.tags ?? []).filter((tag) => tags.has(tag)).length, + score: [...new Set(peer.tags ?? [])].reduce((sum, tag) => sum + (weights.get(tag) ?? 0), 0), })) - .filter(({ shared }) => shared > 0) - .sort((a, b) => b.shared - a.shared || a.peer.name.localeCompare(b.peer.name)) + .filter(({ score }) => score > 0) + .sort((a, b) => b.score - a.score || a.peer.name.localeCompare(b.peer.name)) .slice(0, 8) .map(({ peer }) => peer); } @@ -190,8 +218,10 @@ function relatedItems(item: GameItem): GameItem[] { function StatRow({ label, value }: { label: string; value: React.ReactNode }) { return (
    - {label} - {value} + {label} + + {value} +
    ); } @@ -206,7 +236,7 @@ function StatsTable({ stats }: { stats: GameItemStats }) { label="Power type" value={ {powerTypeLabel(stats.power_type)} @@ -228,7 +258,7 @@ function StatsTable({ stats }: { stats: GameItemStats }) { label="Cheese effect" value={ + {/* The game stores the title's id ("archduke_archduchess"); show its name. */} + {getTitles().find((title) => title.id === stats.min_title)?.name ?? titleCase(stats.min_title)} + + } />, ); @@ -254,8 +292,8 @@ function StatsTable({ stats }: { stats: GameItemStats }) { return (
    -

    Trap stats

    -
    + Stats +
    {rows}
    @@ -280,7 +318,6 @@ export default async function ItemPage({ params }: { params: Promise<{ slug: str const flags: { label: string; limit?: boolean }[] = [ item.is_tradable ? { label: 'Tradable' } : null, item.is_givable ? { label: 'Givable' } : null, - isConvertible ? { label: 'Openable' } : null, item.is_limited_edition ? { label: 'Limited edition', limit: true } : null, item.is_quantity_limited ? { @@ -296,6 +333,7 @@ export default async function ItemPage({ params }: { params: Promise<{ slug: str ].filter(Boolean) as { label: string; limit?: boolean }[]; const ranks = stats ? rankNote(item, stats) : null; + const estimatorParam = estimatorParamFor(item.type); const environments = itemEnvironments(item); const mapRelations = getMapRelationsForItem(item.id); const contents = isConvertible ? getConvertibleContents(item.id) : []; @@ -312,53 +350,70 @@ export default async function ItemPage({ params }: { params: Promise<{ slug: str -
    - {image && ( - // eslint-disable-next-line @next/next/no-img-element - {item.name} - )} -
    - {item.name} -
    - - {titleCase(item.classification)} - - {flags.map((flag) => ( - - {flag.label} - - ))} -
    - {skinFor && ( -

    - A skin for the{' '} +

    +
    + {image && ( + // eslint-disable-next-line @next/next/no-img-element + + )} +
    + {item.name} +
    - {skinFor.name} + {classificationName(item.classification)} - . -

    - )} - {stats && } - {ranks &&

    {ranks}

    } + {flags.map((flag) => ( + + {flag.label} + + ))} +
    + {skinFor && ( +

    + A skin for the{' '} + + {skinFor.name} + + . +

    + )} +
    + {/* Under the picture on a phone, where beside it would squeeze the table; under the title from sm up. */} + {(stats || ranks || estimatorParam) && ( +
    + {stats && } + {ranks &&

    {ranks}

    } + {estimatorParam && ( +

    + + Try it in the catch rate estimator + +

    + )} +
    + )}
    {item.is_tradable && } @@ -367,6 +422,7 @@ export default async function ItemPage({ params }: { params: Promise<{ slug: str itemId={item.id} obtainHint={item.obtain_hint} contents={contents} + isConvertible={isConvertible} drops={drops} foundIn={getConvertiblesContaining(item.id)} mapRelations={mapRelations} @@ -382,14 +438,14 @@ export default async function ItemPage({ params }: { params: Promise<{ slug: str {environment.name} ) : ( {environment.name} @@ -407,11 +463,10 @@ export default async function ItemPage({ params }: { params: Promise<{ slug: str {skin.images?.thumbnail && ( - // eslint-disable-next-line @next/next/no-img-element - + )} {skin.name} @@ -433,17 +488,16 @@ export default async function ItemPage({ params }: { params: Promise<{ slug: str {related.length > 0 && (
    - Related {titleCase(item.classification).toLowerCase()}s + Related {classificationLabel(item.classification).toLowerCase()}
      {related.map((peer) => (
    • {peer.images?.thumbnail && ( - // eslint-disable-next-line @next/next/no-img-element - + )} {peer.name} diff --git a/src/app/items/items-browser.tsx b/src/app/items/items-browser.tsx index 1638b89f..05d89d5f 100644 --- a/src/app/items/items-browser.tsx +++ b/src/app/items/items-browser.tsx @@ -2,14 +2,23 @@ import React, { useEffect, useMemo, useRef, useState } from 'react'; -import { Link } from 'next-view-transitions'; +import { Link } from '@/components/site-link'; import { useSearchParams } from 'next/navigation'; import { MagnifyingGlassIcon } from '@heroicons/react/20/solid'; import { loadItemIndex, type IndexedItem } from '@/lib/client-index'; -import { CLASSIFICATION_DESCRIPTIONS } from '@/lib/item-classifications'; +import { + CLASSIFICATION_DESCRIPTIONS, + SUBGROUPS, + classificationLabel, + classificationName, + itemSubgroup, + subgroupLabel, + subgroupsPresent, +} from '@/lib/item-classifications'; import { itemImageUrl } from '@/lib/image-urls'; -import { formatNumber, titleCase } from '@/utils'; +import { useRememberedCount } from '@/lib/use-remembered-count'; +import { formatNumber } from '@/utils'; import { SectionHeading } from '@/components/section-heading'; /** The mice browser's cap too: past this, rows render on request. */ @@ -24,8 +33,11 @@ function useDebouncedValue(value: T, delay: number) { return debounced; } +const emptyActionClasses = + 'rounded-full bg-white px-3 py-1 text-sm font-medium text-pink-700 ring-1 ring-zinc-200 hover:ring-pink-300 focus:outline-hidden focus-visible:ring-2 focus-visible:ring-pink-500 dark:bg-zinc-900 dark:text-pink-300 dark:ring-zinc-700'; + const pillBase = - 'shrink-0 rounded-full px-3 py-1 text-sm font-medium transition focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500'; + 'shrink-0 rounded-full px-3 py-1 text-sm font-medium transition focus:outline-hidden focus-visible:ring-2 focus-visible:ring-pink-500'; function filtersFromUrl(params: URLSearchParams, classificationOrder: string[]) { const type = params.get('type'); @@ -34,16 +46,51 @@ function filtersFromUrl(params: URLSearchParams, classificationOrder: string[]) query: params.get('q') ?? '', tradableOnly: params.get('tradable') === '1', tag: params.get('tag') ?? null, + sub: params.get('sub') ?? null, }; } -export function ItemsBrowser({ - counts, - classificationOrder, -}: { +/** A familiar item to picture each type. */ +const TYPE_ART: Record = { + weapon: 'acronym_weapon', + base: 'valour_rift_prestige_base', + bait: 'super_brie_cheese', + trinket: 'super_power_trinket', + potion: 'greater_radioactive_blue_cheese_potion', + crafting_item: 'curds_and_whey_craft_item', + convertible: 'treasure_map_scroll_case_convertible', + collectible: 'christmas_coal_collectible', + stat: 'gold_stat_item', + map_piece: 'gnawnia_map_piece', + skin: 'jet_black_acronym_skin', +}; + +interface ItemsBrowserProps { /** Per-type totals, so the default view renders without the item list. */ counts: Record; classificationOrder: string[]; +} + +/** + * The browser with its filters read off the address. Reading the address stops prerendering at the nearest + * Suspense boundary, so the page gives that boundary a plain ItemsBrowser as its fallback: that's what lands in + * the HTML, and this takes over once the page is running. + */ +export function ItemsBrowserFromUrl(props: ItemsBrowserProps) { + const searchParams = useSearchParams(); + return ; +} + +export function ItemsBrowser({ + counts, + classificationOrder, + search = '', + syncUrl = false, +}: ItemsBrowserProps & { + /** The address's query string. Empty for the prerendered view, which has no filters. */ + search?: string; + /** Off for the prerendered view, which mustn't rewrite an address it couldn't read. */ + syncUrl?: boolean; }) { // The item list itself is code-split and only fetched once the visitor // actually filters — the landing view is just the type cards, and the chunk is @@ -52,22 +99,29 @@ export function ItemsBrowser({ const [loadFailed, setLoadFailed] = useState(false); // The URL is the source of truth for the view, so a filtered page is linkable. - const searchParams = useSearchParams(); - const search = searchParams.toString(); - const initial = filtersFromUrl(searchParams, classificationOrder); + const initial = filtersFromUrl(new URLSearchParams(search), classificationOrder); const [query, setQuery] = useState(initial.query); const [active, setActive] = useState(initial.active); const [tradableOnly, setTradableOnly] = useState(initial.tradableOnly); // Set only by following a tag link from an item page; cleared from here. const [tag, setTag] = useState(initial.tag); + // A sub-group of the chosen type, for the types the game splits up. + const [sub, setSub] = useState(initial.sub); + const subgroups = active ? SUBGROUPS[active] : undefined; + const chooseType = (key: string | null) => { + setActive(key); + setSub(null); + }; // Reflect the active filters back into the URL so the view stays shareable. // replaceState feeds back into useSearchParams, so remember what we wrote to // tell our own edits apart from a real navigation. // Writes are deferred so typing doesn't call replaceState on every keystroke. + const searchRef = useRef(null); const written = useRef(search); useEffect(() => { + if (!syncUrl) return; const timer = setTimeout(() => { const params = new URLSearchParams(window.location.search); if (active) params.set('type', active); @@ -78,12 +132,14 @@ export function ItemsBrowser({ else params.delete('tradable'); if (tag) params.set('tag', tag); else params.delete('tag'); + if (sub) params.set('sub', sub); + else params.delete('sub'); const next = params.toString(); written.current = next; window.history.replaceState(null, '', next ? `?${next}` : window.location.pathname); }, 200); return () => clearTimeout(timer); - }, [active, query, tradableOnly, tag]); + }, [active, query, tradableOnly, tag, sub, syncUrl]); // A soft navigation (the sidebar's Items link, a /items?type= card) changes the // URL out from under us; adopt it so the browser doesn't stay stuck on the @@ -95,6 +151,7 @@ export function ItemsBrowser({ setQuery(next.query); setTradableOnly(next.tradableOnly); setTag(next.tag); + setSub(next.sub); }, [search, classificationOrder]); // Filtering 4,000+ items on every keystroke is wasted work; wait for a pause. @@ -126,30 +183,63 @@ export function ItemsBrowser({ [items], ); - const grouped = useMemo(() => { + // Sections are types, or a split type's sub-groups once that type is chosen. + const { grouped, subCounts } = useMemo(() => { const q = debouncedQuery.trim().toLowerCase(); const map = new Map(); + const perSub: Record = {}; for (const { item, lowerName } of sortedItems) { if (active && item.classification !== active) continue; if (tradableOnly && !item.tradable) continue; if (tag && !item.tags?.includes(tag)) continue; if (q && !lowerName.includes(q)) continue; - const list = map.get(item.classification) ?? []; + const group = subgroups ? (itemSubgroup(item) ?? '') : item.classification; + if (subgroups) perSub[group] = (perSub[group] ?? 0) + 1; + if (sub && group !== sub) continue; + const list = map.get(group) ?? []; list.push(item); - map.set(item.classification, list); + map.set(group, list); } - return classificationOrder.filter((key) => map.has(key)).map((key) => [key, map.get(key)!] as const); - }, [sortedItems, debouncedQuery, active, tradableOnly, tag, classificationOrder]); + const order = active && subgroups ? subgroupsPresent(active, map.keys()) : classificationOrder; + return { + grouped: order.filter((key) => map.has(key)).map((key) => [key, map.get(key)!] as const), + subCounts: perSub, + }; + }, [sortedItems, debouncedQuery, active, subgroups, sub, tradableOnly, tag, classificationOrder]); + const sectionName = (key: string) => (active && subgroups ? subgroupLabel(active, key) : classificationName(key)); const total = grouped.reduce((sum, [, list]) => sum + list.length, 0); + // What each type chip would show if picked: every filter except the type itself. + const chipCounts = useMemo(() => { + if (!items) return counts; + const q = debouncedQuery.trim().toLowerCase(); + const out: Record = {}; + for (const { item, lowerName } of sortedItems) { + if (tradableOnly && !item.tradable) continue; + if (tag && !item.tags?.includes(tag)) continue; + if (q && !lowerName.includes(q)) continue; + out[item.classification] = (out[item.classification] ?? 0) + 1; + } + return out; + }, [items, counts, sortedItems, debouncedQuery, tradableOnly, tag]); + // Broad filters (a whole type, tradable only) can match thousands of items, so - // render the first ROW_LIMIT until asked. Changing the filters re-caps it. - const filterKey = [debouncedQuery.trim(), active, tradableOnly, tag].join('|'); - const [expandedFor, setExpandedFor] = useState(null); - const showAll = expandedFor === filterKey; + // render the first ROW_LIMIT until asked. Changing the filters re-caps it. The count is kept across a visit to + // an item's page and Back, so "Show all" doesn't have to be pressed again to return to the same item. + const filterKey = [debouncedQuery.trim(), active, sub, tradableOnly, tag].join('|'); + const [limit, setLimit] = useRememberedCount( + syncUrl ? `items|${filterKey}` : null, + ROW_LIMIT, + !filtering || items !== null || loadFailed, + ); + const [lastFilterKey, setLastFilterKey] = useState(filterKey); + if (filterKey !== lastFilterKey) { + setLastFilterKey(filterKey); + setLimit(ROW_LIMIT); + } const visible = useMemo(() => { - let budget = showAll ? Number.POSITIVE_INFINITY : ROW_LIMIT; + let budget = limit; const out = []; for (const [key, list] of grouped) { if (budget <= 0) break; @@ -158,69 +248,120 @@ export function ItemsBrowser({ out.push([key, list, shown] as const); } return out; - }, [grouped, showAll]); + }, [grouped, limit]); + + // Types with a description get a card; the rest are rare enough for a line of links. + const mainTypes = classificationOrder.filter((key) => CLASSIFICATION_DESCRIPTIONS[key]); + const otherTypes = classificationOrder.filter((key) => !CLASSIFICATION_DESCRIPTIONS[key]); return (
      -
      -
      + {filtering && active && subgroups && items && ( +
      + {[null, ...subgroupsPresent(active, Object.keys(subCounts))].map((key) => ( + + ))} +
      + )} + {tag && (
      ) : total === 0 ? ( -

      No items match your filters.

      +
      +

      + No items match + {debouncedQuery.trim() ? ` “${debouncedQuery.trim()}”` : ' these filters'} + {active ? ` among ${classificationLabel(active).toLowerCase()}` : ''}. +

      +

      + {/* The search may match items of another type; offer the way there first. */} + {active && Object.entries(chipCounts).some(([key, count]) => key !== active && count > 0) && ( + + )} + +

      +
      ) : (
      {visible.map(([key, list, shown]) => (

      - {titleCase(key)} - + {sectionName(key)} + {formatNumber(list.length)}

      @@ -285,8 +492,7 @@ export function ItemsBrowser({
    • {/* eslint-disable-next-line @next/next/no-img-element */} - {item.name} + + {item.name} +
    • ); @@ -306,13 +514,13 @@ export function ItemsBrowser({
    ))} - {total > ROW_LIMIT && !showAll && ( -

    - Showing the first {formatNumber(ROW_LIMIT)} of {formatNumber(total)}.{' '} + {total > limit && ( +

    + Showing the first {formatNumber(limit)} of {formatNumber(total)}.{' '} diff --git a/src/app/items/page.tsx b/src/app/items/page.tsx index b63c1b53..83df7829 100644 --- a/src/app/items/page.tsx +++ b/src/app/items/page.tsx @@ -2,16 +2,17 @@ import React, { Suspense } from 'react'; import { CheeseIcon } from '@/components/game-icons'; import { PageHeader } from '@/components/page-header'; +import { Breadcrumbs } from '@/components/breadcrumbs'; import { getAllGameItems } from '@/lib/game-data'; import { orderClassifications } from '@/lib/item-classifications'; import { pageMetadata } from '@/seo'; -import { ItemsBrowser } from './items-browser'; +import { ItemsBrowser, ItemsBrowserFromUrl } from './items-browser'; export const metadata = pageMetadata({ title: 'MouseHunt Items', description: - 'Every item in MouseHunt — weapons, bases, charms, cheese, collectibles, and more. Filter by type or name for stats, descriptions, and drop info.', + 'Every item in MouseHunt: weapons, bases, charms, cheese, collectibles, and more. Filter by type or name for stats, descriptions, and drop info.', path: '/items', }); @@ -32,21 +33,22 @@ export default function ItemsIndexPage() { return (

    + - {/* ItemsBrowser reads the filters off the URL with useSearchParams, which - would opt this page into dynamic rendering without a boundary here. The - page must stay static: game-data reads its JSON off disk at build time, - and that disk isn't there in the Cloudflare worker. */} - - + {/* The browser reads its filters off the URL with useSearchParams, which would opt this page into dynamic + rendering without a boundary here. The page must stay static: game-data reads its JSON off disk at build + time, and that disk isn't there in the Cloudflare worker. The fallback is the browser with no filters, + so the search box and type cards are in the HTML and not waiting on JavaScript. */} + }> +
    ); diff --git a/src/app/items/type/[type]/page.tsx b/src/app/items/type/[type]/page.tsx index 25a3f1d8..c5000865 100644 --- a/src/app/items/type/[type]/page.tsx +++ b/src/app/items/type/[type]/page.tsx @@ -3,10 +3,17 @@ import React from 'react'; import { Breadcrumbs } from '@/components/breadcrumbs'; import { JsonLd } from '@/components/json-ld'; -import { Link } from 'next-view-transitions'; +import { Link } from '@/components/site-link'; import { getAllGameItems, itemSlug } from '@/lib/game-data'; -import { CLASSIFICATION_DESCRIPTIONS, classificationLabel, orderClassifications } from '@/lib/item-classifications'; +import { + CLASSIFICATION_DESCRIPTIONS, + classificationLabel, + itemSubgroup, + orderClassifications, + subgroupLabel, + subgroupsPresent, +} from '@/lib/item-classifications'; import { pageMetadata, ogCard } from '@/seo'; import { formatNumber } from '@/utils'; import { itemImageUrl } from '@/lib/image-urls'; @@ -61,6 +68,15 @@ export default async function ItemTypePage({ params }: { params: Promise<{ type: const label = classificationLabel(type); + // The big types are split into the groups the game uses, each its own section. + const byGroup = new Map(); + for (const item of items) { + const id = itemSubgroup(item); + if (id) byGroup.set(id, [...(byGroup.get(id) ?? []), item]); + } + const groups = + byGroup.size > 1 ? subgroupsPresent(type, byGroup.keys()).map((id) => ({ id, items: byGroup.get(id)! })) : null; + return (
    {label}

    - {CLASSIFICATION_DESCRIPTIONS[type] ?? `Every ${label.toLowerCase()} in MouseHunt.`} {formatNumber(items.length)}{' '} - in total — open any one for its stats, where it drops, and what’s inside it. + {CLASSIFICATION_DESCRIPTIONS[type] ?? `All ${label.toLowerCase()} in MouseHunt.`} {formatNumber(items.length)}{' '} + in total.{' '} + + Search or filter them + + .

    - + {subgroupLabel(type, id)} + {formatNumber(inGroup.length)} + + ))} + +
    + {groups.map(({ id, items: inGroup }) => ( +
    +

    + {subgroupLabel(type, id)} + + {formatNumber(inGroup.length)} + +

    + +
    + ))} +
    + + ) : ( + + )}
    ); } + +function ItemColumns({ items, className }: { items: ReturnType; className?: string }) { + return ( +
      + {items.map((item) => { + const slug = itemSlug(item.type); + return ( +
    • + + {/* eslint-disable-next-line @next/next/no-img-element */} + + + {item.name} + + +
    • + ); + })} +
    + ); +} diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 39a251c9..a38bba6d 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -16,13 +16,15 @@ const geistSans = Geist({ const geistMono = Geist_Mono({ variable: '--font-geist-mono', subsets: ['latin'], + // Only keyboard hints and code in guides use it, so it loads when one of those is on the page. + preload: false, }); import type { Metadata, Viewport } from 'next'; import { scriptJson } from '@/components/json-ld'; const SITE_DESCRIPTION = - 'Your comprehensive resource for MouseHunt guides, browser extensions, tools, spreadsheets, and userscripts to enhance your MouseHunt experience.'; + 'A community-built MouseHunt hub: every mouse and item with minlucks, drops, and prices, plus guides, calculators, extensions, userscripts, and spreadsheets.'; export const metadata: Metadata = { metadataBase: new URL('https://mouse.rip'), @@ -51,7 +53,7 @@ export const metadata: Metadata = { description: SITE_DESCRIPTION, url: 'https://mouse.rip', locale: 'en_US', - images: [{ url: '/og', width: 1200, height: 630, alt: 'mouse.rip — MouseHunt guides, tools, and resources' }], + images: [{ url: '/og', width: 1200, height: 630, alt: 'mouse.rip: MouseHunt guides, tools, and resources' }], }, twitter: { card: 'summary_large_image', @@ -73,8 +75,8 @@ export const viewport: Viewport = { initialScale: 1, colorScheme: 'light dark', themeColor: [ - { media: '(prefers-color-scheme: light)', color: '#fcfcfb' }, - { media: '(prefers-color-scheme: dark)', color: '#0a0a0a' }, + { media: '(prefers-color-scheme: light)', color: '#fbfaf8' }, + { media: '(prefers-color-scheme: dark)', color: '#0c0a09' }, ], }; @@ -86,12 +88,14 @@ export default async function RootLayout({ children }: RootLayoutProps) { return ( Skip to content diff --git a/src/app/locations/[id]/live-stage.tsx b/src/app/locations/[id]/live-stage.tsx new file mode 100644 index 00000000..3d014042 --- /dev/null +++ b/src/app/locations/[id]/live-stage.tsx @@ -0,0 +1,78 @@ +'use client'; + +import clsx from 'clsx'; +import React, { createContext, useContext } from 'react'; + +import { useTimersContext } from '@/components/timers'; +import { attractionStageName, stagesAt } from '@/lib/timers'; + +/** The attraction-data name of the stage running now at this location, or null until the timer loads. */ +const LiveStageContext = createContext(null); + +/** + * Reads the location's timer once for the whole mice list, from the page's + * TimersProvider. Until it loads (or outside a rotating location, where there's + * no provider), rows render exactly as the server sent them. + */ +export function LiveStageProvider({ locationName, children }: { locationName: string; children: React.ReactNode }) { + const timers = useTimersContext(); + const state = timers?.state; + const timer = state?.status === 'ready' ? state.data.locations.find((entry) => entry.name === locationName) : null; + const current = timer && timers ? stagesAt(timer, timers.now)?.current : undefined; + return ( + + {children} + + ); +} + +/** + * A mouse row. When the location's timer is known and this mouse is best caught + * in a different stage, its portrait greys out; rows for the running stage stay + * as they are, since at most locations that's most of the list. + */ +export function LiveStageRow({ + stage, + className, + children, +}: { + stage?: string | null; + className?: string; + children: React.ReactNode; +}) { + const live = useContext(LiveStageContext); + const offStage = Boolean(stage && live && stage !== live); + return ( +
  • + {children} +
  • + ); +} + +/** The row's stage, with a "not now" tag when a different stage is running. */ +export function LiveStageLabel({ stage }: { stage: string }) { + const live = useContext(LiveStageContext); + return ( + <> + {' during '} + {stage} + {live && live !== stage && ( + + not now + + )} + + ); +} + +/** One line saying which stage is running, shown only when some mice here need another. */ +export function LiveStageNote({ stages }: { stages: string[] }) { + const live = useContext(LiveStageContext); + if (!live || !stages.some((stage) => stage !== live)) return null; + return ( +

    + {live} is running now. Mice best caught in + another stage are grayed out. +

    + ); +} diff --git a/src/app/locations/[id]/location-art.tsx b/src/app/locations/[id]/location-art.tsx new file mode 100644 index 00000000..2adc34d5 --- /dev/null +++ b/src/app/locations/[id]/location-art.tsx @@ -0,0 +1,36 @@ +import clsx from 'clsx'; + +/** The game's header picture for a location. */ +const SOURCE = { width: 760, height: 127 }; + +/** The widest strip of that picture that's all scenery, the same one the social card shows. */ +const CROP = { left: 230, width: 470, height: 70 }; + +/** + * A strip of a location's header art from the game, without the game's own frame. + * + * Every header comes in the same frame: a MouseHunt logo on the left and wooden trim sweeping along the bottom + * and up the right. The frame is identical on all of them, so one crop from the top of the picture clears it. + */ +export function LocationArt({ src, className }: { src: string; className?: string }) { + return ( +
    + {/* The whole picture, scaled and slid so only its crop is inside the box. */} + {/* eslint-disable-next-line @next/next/no-img-element */} + +
    + ); +} diff --git a/src/app/locations/[id]/location-loot.tsx b/src/app/locations/[id]/location-loot.tsx new file mode 100644 index 00000000..8e2d3854 --- /dev/null +++ b/src/app/locations/[id]/location-loot.tsx @@ -0,0 +1,106 @@ +import React from 'react'; + +import { Link } from '@/components/site-link'; + +import { GameImage } from '@/components/game-image'; +import { SectionHeading } from '@/components/section-heading'; +import { SourceLink } from '@/components/source-link'; +import { itemImageUrl } from '@/lib/image-urls'; +import type { LocationLootRow } from '@/types'; +import { formatNumber } from '@/utils'; + +// Shown before "Show all", so the table doesn't bury the sections below it. +const LOOT_PREVIEW = 10; + +function quantity(row: LocationLootRow): string { + if (!row.min && !row.max) return ''; + return row.min === row.max ? `×${formatNumber(row.min)}` : `×${formatNumber(row.min)}–${formatNumber(row.max)}`; +} + +function LootRow({ row }: { row: LocationLootRow }) { + return ( + + + + + {row.name} + + + from{' '} + + {row.mouse_name} + + + + + {row.rate}% + {quantity(row) && ( + {quantity(row)} + )} + + {formatNumber(row.catches)} {row.catches === 1 ? 'catch' : 'catches'} + + + + ); +} + +function LootTable({ rows }: { rows: LocationLootRow[] }) { + return ( +
    + + + + + + + + + {rows.map((row) => ( + + ))} + +
    Item and best mouseDrop rate
    +
    + ); +} + +/** + * What the mice that live here drop. Each item shows the resident mouse most + * likely to drop it; event and site-wide drops are filtered out when the data + * is built (see scripts/update-data.js). + */ +export function LocationLoot({ rows }: { rows: LocationLootRow[] }) { + if (rows.length === 0) return null; + const preview = rows.slice(0, LOOT_PREVIEW); + const rest = rows.slice(LOOT_PREVIEW); + + return ( +
    + Loot found here +

    + From . Event and site-wide drops are left out. +

    +
    + +
    + {rest.length > 0 && ( +
    + + Show all {rows.length} + Show fewer + +
    + +
    +
    + )} +
    + ); +} diff --git a/src/app/locations/[id]/location-mice.tsx b/src/app/locations/[id]/location-mice.tsx new file mode 100644 index 00000000..c2fd8112 --- /dev/null +++ b/src/app/locations/[id]/location-mice.tsx @@ -0,0 +1,215 @@ +import 'server-only'; + +import React from 'react'; + +import { Link } from '@/components/site-link'; + +import { ColorScaleBadge } from '@/components/color-scale-badge'; +import { GameImage } from '@/components/game-image'; +import { SectionHeading } from '@/components/section-heading'; +import { SourceLink } from '@/components/source-link'; +import lookup from '@/data/generated/name-lookup.json'; +import { getMiceForRegionName, getMouseAttraction, mouseSlug } from '@/lib/game-data'; +import { itemImageUrl, mouseImageUrl } from '@/lib/image-urls'; +import { POWER_TYPES, powerTypeSetLabel } from '@/lib/power-types'; +import { bestAttractionRow, formatAttractionRate } from '@/lib/attraction'; +import { LiveStageLabel, LiveStageNote, LiveStageProvider, LiveStageRow } from './live-stage'; +import type { AttractionRow, Mouse } from '@/types'; + +const cheeseLookup = lookup.cheese as Record; + +interface LocationMouse { + mouse: Mouse; + slug: string; + best?: AttractionRow; + minluck?: { value: number; types: string[] }; +} + +interface CheeseGroup { + cheese: string | null; + mice: LocationMouse[]; +} + +function cheeseSlug(cheese: string): string | undefined { + const key = cheese.trim().toLowerCase(); + return cheeseLookup[key] ?? cheeseLookup[`${key} cheese`]; +} + +/** The best charm-free attraction row for a mouse here, skipping tiny samples when possible. */ +function bestRowAt(mouseId: number, locationName: string): AttractionRow | undefined { + return bestAttractionRow( + getMouseAttraction(mouseId).filter((row) => row.location === locationName && row.charm === null), + ); +} + +/** The lowest minluck a mouse has, and every power type that shares it. */ +function lowestMinluck(mouse: Mouse): LocationMouse['minluck'] { + const minlucks = (mouse.minlucks ?? {}) as Record; + let value = Infinity; + let types: string[] = []; + for (const type of POWER_TYPES) { + const luck = minlucks[type]; + if (typeof luck !== 'number' || luck <= 0) continue; + if (luck < value) { + value = luck; + types = [type]; + } else if (luck === value) { + types.push(type); + } + } + return types.length > 0 ? { value, types } : undefined; +} + +/** + * Every mouse the game lists for this location, grouped by the cheese that + * attracts each one best here. Groups with the most mice come first; mice with + * no attraction data go last. + */ +export function getLocationMiceByCheese(locationName: string): { groups: CheeseGroup[]; total: number } { + const mice = getMiceForRegionName(locationName).map((mouse) => ({ + mouse, + slug: mouseSlug(mouse.type), + best: bestRowAt(mouse.id, locationName), + minluck: lowestMinluck(mouse), + })); + + const byCheese = new Map(); + for (const entry of mice) { + const key = entry.best?.cheese ?? null; + byCheese.set(key, [...(byCheese.get(key) ?? []), entry]); + } + + const groups = [...byCheese.entries()].map(([cheese, entries]) => ({ + cheese, + mice: entries.sort((a, b) => (b.best?.rate ?? 0) - (a.best?.rate ?? 0) || a.mouse.name.localeCompare(b.mouse.name)), + })); + + groups.sort((a, b) => { + if (a.cheese === null) return 1; + if (b.cheese === null) return -1; + return b.mice.length - a.mice.length || (b.mice[0].best?.rate ?? 0) - (a.mice[0].best?.rate ?? 0); + }); + + return { groups, total: mice.length }; +} + +function CheeseTitle({ cheese }: { cheese: string | null }) { + if (cheese === null) { + return No attraction data yet; + } + const slug = cheeseSlug(cheese); + const content = ( + <> + {slug && } + {cheese} + + ); + return slug ? ( + + {content} + + ) : ( + {content} + ); +} + +function MouseRow({ entry }: { entry: LocationMouse }) { + const { mouse, slug, best, minluck } = entry; + return ( + + {/* eslint-disable-next-line @next/next/no-img-element */} + +
    + + {mouse.name} + + {best && ( +
    + {formatAttractionRate(best.rate)} attraction + {best.stage && } +
    + )} +
    +
    + {minluck ? ( + <> + + + {powerTypeSetLabel(minluck.types)} + + + ) : ( + No minluck + )} +
    +
    + ); +} + +export function LocationMice({ + locationName, + groups, + total, +}: { + locationName: string; + groups: CheeseGroup[]; + total: number; +}) { + return ( + +
    + + {total} {total === 1 ? 'mouse' : 'mice'} found here + +

    + Grouped by the cheese that attracts each mouse best here, with its lowest minluck. Attraction rates from{' '} + and . See the{' '} + + full minluck table + + . +

    + group.mice.flatMap((entry) => entry.best?.stage ?? [])))]} + /> + +
    + {groups.map((group) => ( +
    +

    + + + {group.mice.length} {group.mice.length === 1 ? 'mouse' : 'mice'} + +

    +
      + {group.mice.map((entry) => ( + + ))} +
    +
    + ))} +
    +
    +
    + ); +} diff --git a/src/app/locations/[id]/page.tsx b/src/app/locations/[id]/page.tsx index 43173713..2e43ee85 100644 --- a/src/app/locations/[id]/page.tsx +++ b/src/app/locations/[id]/page.tsx @@ -1,27 +1,30 @@ import { notFound } from 'next/navigation'; import React from 'react'; -import { Avatar } from '@/components/avatar'; import { Breadcrumbs } from '@/components/breadcrumbs'; +import { ExternalRefs } from '@/components/external-refs'; import { Heading } from '@/components/heading'; import { ItemList } from '@/components/item-list'; -import { MouseGrid } from '@/components/mouse-grid'; -import { Link } from 'next-view-transitions'; +import { Link } from '@/components/site-link'; import { getResourcesForLocation, getLocation, getLocations, getTrapEffects } from '@/lib/site-data'; -import { getItemsForEnvironment, getLocationLoot, getMiceForRegionName, itemSlug } from '@/lib/game-data'; +import { getItemsForEnvironment, getLocationLoot, itemSlug } from '@/lib/game-data'; import { ogCard, pageMetadata } from '@/seo'; -import { cleanDescription, formatNumber } from '@/utils'; +import { cleanDescription } from '@/utils'; import { itemImageUrl, locationHeaderImageUrl, locationImageUrl } from '@/lib/image-urls'; import { SectionHeading } from '@/components/section-heading'; -import { SourceLink } from '@/components/source-link'; +import { ClampedText } from '@/components/clamped-text'; +import { GameImage } from '@/components/game-image'; -export const dynamicParams = false; - -const LOOT_ROWS_SHOWN = 40; +import { LocationArt } from './location-art'; +import { LocationMice, getLocationMiceByCheese } from './location-mice'; +import { LocationLoot } from './location-loot'; +import { LocationTimerPanel, TimersProvider } from '@/components/timers'; +import { TIMER_LOCATION_NAMES } from '@/lib/timer-locations'; +import { ToolCard } from '@/components/tool-card'; +import catchRateData from '@/data/generated/catch-rate.json'; -// Temporarily hidden: "Items for this location", "Loot found here", and the mice grid. -const SHOW_EXTRA_SECTIONS = false; +export const dynamicParams = false; export async function generateMetadata({ params }: { params: Promise<{ id: string }> }) { const resolvedParams = await params; @@ -32,17 +35,22 @@ export async function generateMetadata({ params }: { params: Promise<{ id: strin } const where = location.article ? location.article : location.name; + // Most of the page is the mouse list, so the title leads with that. + const hasMice = Boolean(location.name && getLocationMiceByCheese(location.name).total > 0); return pageMetadata({ - title: `MouseHunt Resources for ${where}`, + title: hasMice ? `${location.name}: Mice, Best Cheese & Minlucks` : `${location.name ?? where}: MouseHunt Location`, description: location.description ? cleanDescription(location.description) - : `Guides, tools, and community resources for ${where} in MouseHunt.`, + : `The mice found in ${where} in MouseHunt, the cheese that attracts each one, and their minlucks.`, path: `/locations/${resolvedParams.id}`, image: location.name ? ogCard({ title: location.name, eyebrow: 'Location', - image: locationImageUrl(location.id), + // The header art is the biggest picture the game has of a location; its square one is 54px. + ...(location.headerImage + ? { banner: locationHeaderImageUrl(location.environmentId ?? location.id) } + : { image: locationImageUrl(location.id) }), accent: 'emerald', }) : undefined, @@ -68,6 +76,22 @@ export function generateStaticParams() { return paths.flat(); } +/** A resource tagged to more locations than this is general advice, not about this place. */ +const MAX_LOCAL_LOCATIONS = 10; + +const linkClass = + 'underline decoration-zinc-300 underline-offset-2 hover:text-zinc-900 dark:decoration-zinc-600 dark:hover:text-zinc-200'; + +/** The sidebar region (Gnawnia, Rift Plane…) a location is listed under. */ +function regionFor(locationId: string) { + return getLocations().find((region) => region.locations.some((location) => location.id === locationId)); +} + +/** Shares one timer fetch between the timer panel and the mice list's live stage. */ +function WithTimers({ enabled, children }: { enabled: boolean; children: React.ReactNode }) { + return enabled ? {children} : <>{children}; +} + export default async function Location({ params }: { params: Promise<{ id: string }> }) { const resolvedParams = await params; const location = getLocation(resolvedParams.id); @@ -75,42 +99,112 @@ export default async function Location({ params }: { params: Promise<{ id: strin if (!location) { notFound(); } - const items = getResourcesForLocation(resolvedParams.id); - const mice = location.name ? getMiceForRegionName(location.name) : []; + const name = location.name ?? 'Location'; + const regionEntry = regionFor(resolvedParams.id); + const region = regionEntry?.name; + const description = location.description ? cleanDescription(location.description) : undefined; + // Only rotating locations have a timer; the rest never fetch one. + const rotating = Boolean(location.name && TIMER_LOCATION_NAMES.includes(location.name)); + + const { groups: cheeseGroups, total: miceTotal } = location.name + ? getLocationMiceByCheese(location.name) + : { groups: [], total: 0 }; const trapEffects = location.name ? (getTrapEffects().find((entry) => entry.location === location.name)?.effects ?? []) : []; const environmentKey = location.environmentId ?? location.id; + // The catch rate tools know locations by the game's id; match this page to one by name. + const catchRateLocation = catchRateData.locations.find((entry) => entry.name === location.name)?.id; const locationItems = getItemsForEnvironment(environmentKey); - const loot = location.name ? getLocationLoot(location.name) : []; + + // Guides and tools written for this location lead the page. Site-wide ones, and broad ones + // like the Essentials guide that's tagged to every early location, wait at the bottom. + const resources = getResourcesForLocation(resolvedParams.id); + const isLocal = (resource: (typeof resources)[number]) => + !resource.locations?.includes('all') && (resource.locations?.length ?? 0) <= MAX_LOCAL_LOCATIONS; + const localResources = resources.filter(isLocal); + const generalResources = resources.filter((resource) => !isLocal(resource)); return ( - <> - + + + + {location.headerImage && } - {location.headerImage && ( - // eslint-disable-next-line @next/next/no-img-element +
    + {/* eslint-disable-next-line @next/next/no-img-element */} +
    + {name} + {regionEntry && region !== name && ( +

    + + {regionEntry.name} + +

    + )} +
    +
    + + {description && {description}} + + {rotating && location.name && } + + {localResources.length > 0 && ( +
    + Guides and tools for {name} + +
    )} - - - MouseHunt Resources for {location.article ? location.article : location.name} - + {miceTotal > 0 && location.name && ( + + )} + + {catchRateLocation && ( +
    + Plan your hunt here +
      +
    • + +
    • +
    • + +
    • +
    +
    + )} - + {location.name && } - {SHOW_EXTRA_SECTIONS && locationItems.length > 0 && ( -
    + {locationItems.length > 0 && ( +
    Items for this location -

    - Gear, bait, and other items that are specific to hunting here. -

      {locationItems.map((item) => { const slug = itemSlug(item.type); @@ -118,10 +212,9 @@ export default async function Location({ params }: { params: Promise<{ id: strin
    • - {/* eslint-disable-next-line @next/next/no-img-element */} - + {item.name}
    • @@ -131,87 +224,31 @@ export default async function Location({ params }: { params: Promise<{ id: strin
    )} - {SHOW_EXTRA_SECTIONS && loot.length > 0 && ( -
    - Loot found here -

    - How often the mouse most likely to drop each item here drops it, from . -

    -
    - - - - - - - - - - {loot.slice(0, LOOT_ROWS_SHOWN).map((row) => ( - - - - - - ))} - -
    ItemDrop rateSample
    - - {/* eslint-disable-next-line @next/next/no-img-element */} - - {row.name} - -
    - from{' '} - - {row.mouse_name} - -
    -
    - {row.rate.toFixed(2)}% - - {formatNumber(row.catches)} catches -
    -
    - {loot.length > LOOT_ROWS_SHOWN && ( -

    - Showing the {LOOT_ROWS_SHOWN} most likely of {loot.length} items seen dropping here. -

    - )} -
    - )} - {trapEffects.length > 0 && ( -
    - Trap special effects here -

    - Traps with unique behavior in this location. See{' '} - - all trap special effects +

    + Trap and base special effects here +

    + See{' '} + + all trap and base special effects .

    -
    +
    - + - - + + {trapEffects.map((effect) => ( - - + - + ))} @@ -220,14 +257,14 @@ export default async function Location({ params }: { params: Promise<{ id: strin )} - {SHOW_EXTRA_SECTIONS && mice.length > 0 && ( -
    - {mice.length} mice found here -
    - -
    + {generalResources.length > 0 && ( +
    + More guides and tools +
    )} - + + {location.name && } + ); } diff --git a/src/app/manifest.ts b/src/app/manifest.ts index 265242e9..16577171 100644 --- a/src/app/manifest.ts +++ b/src/app/manifest.ts @@ -4,7 +4,7 @@ import type { MetadataRoute } from 'next'; // Next serves this at /manifest.webmanifest and auto-adds the . export default function manifest(): MetadataRoute.Manifest { return { - name: 'mouse.rip — MouseHunt Resources', + name: 'mouse.rip: MouseHunt Resources', short_name: 'mouse.rip', description: 'Community-built MouseHunt guides, extensions, tools, spreadsheets, and userscripts.', start_url: '/', diff --git a/src/app/map-planner/map-planner.tsx b/src/app/map-planner/map-planner.tsx new file mode 100644 index 00000000..4978df9e --- /dev/null +++ b/src/app/map-planner/map-planner.tsx @@ -0,0 +1,493 @@ +'use client'; + +import clsx from 'clsx'; +import React, { useEffect, useMemo, useRef, useState } from 'react'; +import { useSearchParams } from 'next/navigation'; +import { ChevronDownIcon, XMarkIcon } from '@heroicons/react/20/solid'; + +import { GameImage } from '@/components/game-image'; +import { Link } from '@/components/link'; +import { SectionHeading } from '@/components/section-heading'; +import { loadMouseIndex, loadPlannerData, type IndexedMouse } from '@/lib/client-index'; +import { mouseImageUrl } from '@/lib/image-urls'; +import { + MIN_HUNTS, + RATE_FLOOR, + SORTS, + buildPlan, + formatHunts, + formatRate, + initialSetups, + normalizeMouseName, + parseMice, + rankSetups, + type PlannerData, + type Place, + type Row, + type Setup, + type SortKey, +} from '@/lib/map-plan'; +import { formatCount, formatNumber } from '@/utils'; + +const INITIAL_SETUPS = 20; +const OTHER_SETUPS_PER_MOUSE = 3; + +const selectClasses = + 'rounded-lg border border-zinc-950/45 bg-white px-3 py-1.5 text-sm/6 text-zinc-950 shadow-sm hover:border-zinc-950/60 focus:border-pink-500 focus:outline-hidden focus:ring-2 focus:ring-pink-500 dark:border-white/35 dark:bg-white/5 dark:text-white dark:scheme-dark dark:hover:border-white/45'; +const linkClasses = 'font-medium text-pink-700 hover:text-pink-900 dark:text-pink-300 dark:hover:text-pink-200'; + +function useDebouncedValue(value: T, delay: number) { + const [debounced, setDebounced] = useState(value); + useEffect(() => { + const timer = setTimeout(() => setDebounced(value), delay); + return () => clearTimeout(timer); + }, [value, delay]); + return debounced; +} + +export function MapPlannerFromUrl({ places }: { places: Record }) { + const searchParams = useSearchParams(); + const initialIds = (searchParams.get('mice') ?? '') + .split(',') + .map((id) => Number.parseInt(id, 10)) + .filter((id) => id > 0); + return ; +} + +export function MapPlanner({ + places, + initialIds, + syncUrl, +}: { + places: Record; + /** Mice from a shared ?mice= link. */ + initialIds: number[]; + /** Off for the prerendered fallback, which mustn't rewrite a link it couldn't read. */ + syncUrl: boolean; +}) { + const [mice, setMice] = useState(null); + const [data, setData] = useState(null); + const [loadFailed, setLoadFailed] = useState(false); + const [text, setText] = useState(''); + const [sort, setSort] = useState('best'); + const [showAll, setShowAll] = useState(false); + + // A shared link's mice, kept from the first render so the load below fills them in once. + const linkedIds = useRef(initialIds); + const textRef = useRef(null); + + useEffect(() => { + let alive = true; + Promise.all([loadMouseIndex(), loadPlannerData()]) + .then(([loadedMice, loadedData]) => { + if (!alive) return; + setMice(loadedMice); + setData(loadedData); + const byId = new Map(loadedMice.map((mouse) => [mouse.id, mouse])); + const names = linkedIds.current.map((id) => byId.get(id)?.name).filter(Boolean); + if (names.length > 0) setText((current) => current || names.join('\n')); + }) + .catch(() => alive && setLoadFailed(true)); + return () => { + alive = false; + }; + }, []); + + const debouncedText = useDebouncedValue(text, 200); + const { matched, unmatched } = useMemo( + () => (mice ? parseMice(debouncedText, mice) : { matched: [], unmatched: [] }), + [debouncedText, mice], + ); + + useEffect(() => { + if (!syncUrl || !mice) return; + const params = new URLSearchParams(window.location.search); + if (matched.length > 0) params.set('mice', matched.map((mouse) => mouse.id).join(',')); + else params.delete('mice'); + const next = params.toString(); + window.history.replaceState(null, '', next ? `?${next}` : window.location.pathname); + }, [matched, mice, syncUrl]); + + const plan = useMemo( + () => (data && matched.length > 0 ? buildPlan(matched, data, places) : null), + [matched, data, places], + ); + const ranked = useMemo(() => (plan ? rankSetups(plan.setups, sort) : []), [plan, sort]); + // Every mouse appears in the first view, even when its only setups rank low. + const initial = useMemo(() => initialSetups(ranked, INITIAL_SETUPS), [ranked]); + const visible = showAll ? ranked : initial; + + const removeMouse = (mouse: IndexedMouse) => { + const names = new Set([normalizeMouseName(mouse.name), normalizeMouseName(mouse.abbreviated_name ?? '')]); + setText((current) => + current + .split(/[\n,;\t]+/) + .filter((part) => !names.has(normalizeMouseName(part.replace(/^\s*(?:[-*•]|\d+[.)])\s*/, '')))) + .join('\n'), + ); + // The chip and its button are gone now; put the keyboard back in the list they came from. + textRef.current?.focus(); + }; + + return ( +
    +
    + +

    + One per line, or separated by commas. “Mouse” at the end is optional. +

    +
    TrapEffectTrapEffect
    +
    {effect.name} {effect.effect}{effect.effect}