diff --git a/.gitignore b/.gitignore index cd90fa0..5b73dd5 100644 --- a/.gitignore +++ b/.gitignore @@ -27,3 +27,4 @@ yarn-error.log* /personal-website-bruno /website-api-bruno /.github/.idea +dist-ssr diff --git a/index.html b/index.html index dcd8c1a..1f0d6e5 100644 --- a/index.html +++ b/index.html @@ -11,18 +11,8 @@ - - - - - - - - - @@ -40,10 +30,11 @@ work correctly both with client-side routing and a non-root public URL. Learn how to configure a non-root public URL by running `npm run build`. --> - Svit Spindler + - - + + +
diff --git a/netlify.toml b/netlify.toml index 9ad46b3..23402ee 100644 --- a/netlify.toml +++ b/netlify.toml @@ -1,58 +1,74 @@ -# Routes of the single-page app, served by index.html. Keep this list in sync with the -# s in src/index.tsx: `npm run check-netlify-routes` (run in CI) compares them. -# Real files in build/ always win over these rules, and "/" is index.html itself. +# Every page is prerendered at build time (scripts/prerender.mjs, run by `npm run build`) into +# build//index.html, and "/" is build/index.html. Each route gets one rewrite to its own +# file, so /contact is served as-is (status 200): no redirect to /contact/, no .html in the URL. +# force = true makes the rewrite win over Netlify's directory handling for build/contact/. +# Keep this list in sync with the s in src/AppRoutes.tsx: `npm run check-netlify-routes` +# (run in CI) compares them. +[build] + command = "npm run build" + publish = "build" + [[redirects]] from = "/contact" - to = "/index.html" + to = "/contact/index.html" status = 200 + force = true [[redirects]] from = "/donate" - to = "/index.html" + to = "/donate/index.html" status = 200 + force = true [[redirects]] from = "/uninstall" - to = "/index.html" + to = "/uninstall/index.html" status = 200 + force = true [[redirects]] from = "/microsoft-automatic-rewards" - to = "/index.html" + to = "/microsoft-automatic-rewards/index.html" status = 200 + force = true [[redirects]] from = "/microsoft-automatic-rewards/mobile/privacy" - to = "/index.html" + to = "/microsoft-automatic-rewards/mobile/privacy/index.html" status = 200 + force = true [[redirects]] from = "/microsoft-automatic-rewards/mobile/website" - to = "/index.html" + to = "/microsoft-automatic-rewards/mobile/website/index.html" status = 200 + force = true [[redirects]] from = "/microsoft-automatic-rewards/mobile/test-app" - to = "/index.html" + to = "/microsoft-automatic-rewards/mobile/test-app/index.html" status = 200 + force = true [[redirects]] from = "/prolific-studies-notifier" - to = "/index.html" + to = "/prolific-studies-notifier/index.html" status = 200 + force = true [[redirects]] from = "/free-game-claimer" - to = "/index.html" + to = "/free-game-claimer/index.html" status = 200 + force = true -# Everything else doesn't exist: the app still renders its "Page not found" page, but with -# a real 404 status. Crawlers and agents (e.g. /.well-known/ard.json) then see a missing +# Everything else doesn't exist: the prerendered "Page not found" page, with a real 404 +# status. Crawlers and agents (e.g. /.well-known/ard.json) then see a missing # page instead of a 200, and a tab from an older deploy that asks for a removed /static/ # chunk gets a clean failure, after which src/index.tsx reloads it. [[redirects]] from = "/*" - to = "/index.html" + to = "/404.html" status = 404 # Vite emits its JS, CSS and fonts into /static/ with a content hash in each file name, diff --git a/package.json b/package.json index acf9399..3dbd916 100644 --- a/package.json +++ b/package.json @@ -24,7 +24,7 @@ }, "scripts": { "dev": "vite", - "build": "vite build", + "build": "vite build && vite build --ssr src/entry-server.tsx && node scripts/sitemap-generator.js build/sitemap.xml && node scripts/prerender.mjs", "preview": "vite preview", "predeploy": "npm run build", "deploy": "gh-pages -d build", diff --git a/public/assets/og/free-game-claimer.png b/public/assets/og/free-game-claimer.png new file mode 100644 index 0000000..972ddbc Binary files /dev/null and b/public/assets/og/free-game-claimer.png differ diff --git a/public/assets/og/home.png b/public/assets/og/home.png new file mode 100644 index 0000000..17b37e5 Binary files /dev/null and b/public/assets/og/home.png differ diff --git a/public/assets/og/prolific-studies-notifier.png b/public/assets/og/prolific-studies-notifier.png new file mode 100644 index 0000000..13a007d Binary files /dev/null and b/public/assets/og/prolific-studies-notifier.png differ diff --git a/public/llms.txt b/public/llms.txt index e96b91d..21e1c5c 100644 --- a/public/llms.txt +++ b/public/llms.txt @@ -1,6 +1,6 @@ # Svit Spindler -> Portfolio of Svit Spindler, a computer science graduate and software developer with hands-on experience in mobile, web, backend and database development. The site lists work experience, hobby projects (Chrome extensions, mobile apps, websites and a video game) and ways to get in touch. +> Svit Spindler is a full-stack software engineer in Ljubljana (Java, Spring Boot, Kotlin, TypeScript, React, Next.js) with a computer science degree from the University of Ljubljana. This portfolio lists his work experience, Digitalna Košarica, three free browser extensions with 40,000+ users in total, and hobby projects (mobile apps, websites and a video game), and tells you how to get in touch. The site is available in English and Slovenian (add `?lang=sl` to a URL for Slovenian). @@ -25,7 +25,7 @@ The site is available in English and Slovenian (add `?lang=sl` to a URL for Slov - [Digitalna Košarica](https://digitalna-kosarica.si/): price comparison website for Slovenian grocery stores, built with Spring Boot, PostgreSQL/TimescaleDB and Next.js - [Search Automatic Rewards](https://svitspindler.com/microsoft-automatic-rewards): Chrome and Firefox extension that automates daily Microsoft Rewards points, with Google's Featured badge ([source](https://github.com/spin311/MicrosoftRewardsWebsite)) - [Prolific Studies Notifier](https://svitspindler.com/prolific-studies-notifier): Chrome and Firefox extension that alerts users to new Prolific studies ([source](https://github.com/spin311/ProlificAutomaticStudies)) -- [Free Game Claimer](https://svitspindler.com/free-game-claimer): Chrome and Firefox extension that automatically claims free games from Epic, Steam, GOG, IndieGala and Prime Gaming ([source](https://github.com/spin311/epic-free-games-claim)) +- [Free Game Claimer](https://svitspindler.com/free-game-claimer): Chrome and Firefox extension that automatically claims free games from Epic, Steam, GOG, IndieGala and Prime Gaming; available in 7 languages ([source](https://github.com/spin311/epic-free-games-claim)) - [Gobar](https://juicevodka.github.io/Gobar/): mobile app that identifies mushrooms with an AI model; won "Best Carbon footprint reduction app" at DragonHack 2023 ([source](https://github.com/JuiceVodka/Gobar)) - [KeSi](https://juicevodka.github.io/KeSi/): Android location-guessing game similar to GeoGuessr, built at DragonHack 2024 with Kotlin ([source](https://github.com/JuiceVodka/KeSi)) - [ChatGPT prompt engineering](https://spin311.github.io/diploma/): website for a thesis experiment that compiles Python code alongside a ChatGPT chat; Java and HSQLDB backend on AWS ([source](https://github.com/spin311/hiter-inzeniring-diploma)) diff --git a/public/robots.txt b/public/robots.txt index a2f6e89..e342982 100644 --- a/public/robots.txt +++ b/public/robots.txt @@ -1,4 +1,22 @@ # https://www.robotstxt.org/robotstxt.html +# Search engines, link previews and AI crawlers are all welcome. /uninstall stays out +# of search through its noindex tag, not here: a crawler blocked by robots.txt never +# fetches the page, so it would never see the tag. User-agent: * Disallow: + +# AI crawlers and agents, named explicitly so the permission is unambiguous. +User-agent: GPTBot +User-agent: OAI-SearchBot +User-agent: ChatGPT-User +User-agent: ClaudeBot +User-agent: Claude-User +User-agent: Claude-SearchBot +User-agent: PerplexityBot +User-agent: Perplexity-User +User-agent: Google-Extended +User-agent: Applebot-Extended +User-agent: CCBot +Disallow: + Sitemap: https://svitspindler.com/sitemap.xml diff --git a/public/sitemap.xml b/public/sitemap.xml index 0113df8..3f79817 100644 --- a/public/sitemap.xml +++ b/public/sitemap.xml @@ -1 +1 @@ -https://svitspindler.com/daily1.0https://svitspindler.com/contactmonthly0.7https://svitspindler.com/donatemonthlyhttps://svitspindler.com/uninstallmonthlyhttps://svitspindler.com/microsoft-automatic-rewardsmonthlyhttps://svitspindler.com/microsoft-automatic-rewards/mobile/privacymonthlyhttps://svitspindler.com/microsoft-automatic-rewards/mobile/websitemonthlyhttps://svitspindler.com/microsoft-automatic-rewards/mobile/test-appmonthlyhttps://svitspindler.com/prolific-studies-notifiermonthlyhttps://svitspindler.com/free-game-claimermonthly \ No newline at end of file +https://svitspindler.com/2026-11-26T00:00:00.000Zhttps://svitspindler.com/contact2026-11-26T00:00:00.000Zhttps://svitspindler.com/donate2026-11-26T00:00:00.000Zhttps://svitspindler.com/microsoft-automatic-rewards2026-11-26T00:00:00.000Zhttps://svitspindler.com/microsoft-automatic-rewards/mobile/privacy2026-11-26T00:00:00.000Zhttps://svitspindler.com/microsoft-automatic-rewards/mobile/website2026-11-26T00:00:00.000Zhttps://svitspindler.com/microsoft-automatic-rewards/mobile/test-app2026-11-26T00:00:00.000Zhttps://svitspindler.com/prolific-studies-notifier2026-11-26T00:00:00.000Zhttps://svitspindler.com/free-game-claimer2026-11-26T00:00:00.000Z \ No newline at end of file diff --git a/scripts/check-netlify-routes.js b/scripts/check-netlify-routes.js index ece7ac9..4b14d61 100644 --- a/scripts/check-netlify-routes.js +++ b/scripts/check-netlify-routes.js @@ -1,8 +1,8 @@ const fs = require('fs'); const path = require('path'); -// --- Load route paths from index.tsx --- -const indexPath = path.resolve(__dirname, '../src/index.tsx'); +// --- Load route paths from AppRoutes.tsx --- +const indexPath = path.resolve(__dirname, '../src/AppRoutes.tsx'); const indexContent = fs.readFileSync(indexPath, 'utf-8'); const routeRegex = / ${match[2]}`); + } +} + +// Every route needs page metadata in src/seo/routes.ts, or the prerender would give it +// the not-found page's head +const seoPath = path.resolve(__dirname, '../src/seo/routes.ts'); +const seoContent = fs.readFileSync(seoPath, 'utf-8'); +const seoPaths = new Set(); +const seoRegex = /\bpath:\s*"([^"]+)"/g; +while ((match = seoRegex.exec(seoContent)) !== null) { + seoPaths.add(match[1]); } +const missingFromSeo = [...routes].filter(r => !seoPaths.has(r)); // --- Compare sets --- const missingFromNetlify = [...routes].filter(r => !rewrites.has(r)); const unknownInNetlify = [...rewrites].filter(r => !routes.has(r)); -if (missingFromNetlify.length > 0 || unknownInNetlify.length > 0) { +if ( + missingFromNetlify.length > 0 || + unknownInNetlify.length > 0 || + wrongTarget.length > 0 || + missingFromSeo.length > 0 +) { if (missingFromNetlify.length > 0) { console.error('❌ These routes have no rewrite in netlify.toml, so Netlify would answer them with a 404:'); missingFromNetlify.forEach(route => console.error(` - ${route}`)); } if (unknownInNetlify.length > 0) { - console.error('❌ These netlify.toml rewrites match no route in src/index.tsx:'); + console.error('❌ These netlify.toml rewrites match no route in src/AppRoutes.tsx:'); unknownInNetlify.forEach(route => console.error(` - ${route}`)); } + if (wrongTarget.length > 0) { + console.error('❌ These rewrites must point at their own prerendered file (/index.html):'); + wrongTarget.forEach(route => console.error(` - ${route}`)); + } + if (missingFromSeo.length > 0) { + console.error('❌ These routes have no entry in src/seo/routes.ts, so they would be prerendered without their own head tags:'); + missingFromSeo.forEach(route => console.error(` - ${route}`)); + } process.exit(1); } else { - console.log('✅ All routes have a rewrite in netlify.toml.'); + console.log('✅ All routes have a rewrite in netlify.toml and an entry in src/seo/routes.ts.'); } diff --git a/scripts/check-sitemap.js b/scripts/check-sitemap.js index 15e2d31..9444ae3 100644 --- a/scripts/check-sitemap.js +++ b/scripts/check-sitemap.js @@ -1,8 +1,8 @@ const fs = require('fs'); const path = require('path'); -// --- Load route paths from index.js --- -const indexPath = path.resolve(__dirname, '../src/index.tsx'); +// --- Load route paths from AppRoutes.tsx --- +const indexPath = path.resolve(__dirname, '../src/AppRoutes.tsx'); const indexContent = fs.readFileSync(indexPath, 'utf-8'); const routeRegex = / m[1]) : [] +); + // --- Compare sets --- -const missingFromSitemap = [...routes].filter(r => !sitemapUrls.has(r) && r !== '*'); +const missingFromSitemap = [...routes].filter(r => !sitemapUrls.has(r) && r !== '*' && !noindexPaths.has(r)); +const noindexInSitemap = [...noindexPaths].filter(r => sitemapUrls.has(r)); -if (missingFromSitemap.length > 0) { - console.error('❌ The following routes are missing from the sitemap:'); - missingFromSitemap.forEach(route => console.error(` - ${route}`)); +if (missingFromSitemap.length > 0 || noindexInSitemap.length > 0) { + if (missingFromSitemap.length > 0) { + console.error('❌ The following routes are missing from the sitemap:'); + missingFromSitemap.forEach(route => console.error(` - ${route}`)); + } + if (noindexInSitemap.length > 0) { + console.error('❌ The following noindex pages must not be in the sitemap:'); + noindexInSitemap.forEach(route => console.error(` - ${route}`)); + } process.exit(1); } else { console.log('✅ All routes are present in the sitemap.'); diff --git a/scripts/og/README.txt b/scripts/og/README.txt new file mode 100644 index 0000000..dfcc99f --- /dev/null +++ b/scripts/og/README.txt @@ -0,0 +1,17 @@ +Share images (Open Graph / Twitter cards) for the site, 1200x630 PNG in public/assets/og/. +src/seo/routes.ts picks one per page: home.png for most pages, the extension's own image +for /free-game-claimer and /prolific-studies-notifier. + +They are generated from template.html and committed; this is not part of `npm run build`. +To change one, edit template.html (the three variants are the .card blocks) and run, from the +repository root, with any Playwright installation and its Chromium: + + PLAYWRIGHT_CORE_PATH="$(npm root -g)/@playwright/cli/node_modules/playwright-core" \ + CHROME_PATH="$HOME/Library/Caches/ms-playwright/chromium-1248/chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing" \ + node scripts/og/generate.mjs + +(PLAYWRIGHT_CORE_PATH can be left out when playwright-core resolves from the repository.) +Then shrink them if one is over ~150 KB, for example with pngquant or +`python3 -c "from PIL import Image; im = Image.open(f).convert('RGB').quantize(256); im.save(f, optimize=True)"`. +Never put Microsoft's logo, its four-colour squares or its name in an image: see +the Microsoft Rewards notes in the marketing plan. diff --git a/scripts/og/generate.mjs b/scripts/og/generate.mjs new file mode 100644 index 0000000..8130e33 --- /dev/null +++ b/scripts/og/generate.mjs @@ -0,0 +1,23 @@ +// Renders the share images in public/assets/og/ from scripts/og/template.html. +// Not part of the Netlify build: run it by hand when a page's share image should change +// and commit the PNGs. See scripts/og/README.txt. +import { createRequire } from "node:module"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const outDir = path.resolve(here, "../../public/assets/og"); +const variants = ["home", "free-game-claimer", "prolific-studies-notifier"]; + +const require = createRequire(import.meta.url); +const { chromium } = require(process.env.PLAYWRIGHT_CORE_PATH ?? "playwright-core"); + +const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH }); +const page = await browser.newPage({ viewport: { width: 1200, height: 630 } }); +for (const variant of variants) { + await page.goto(`${pathToFileURL(path.join(here, "template.html")).href}?v=${variant}`); + await page.evaluate(() => document.fonts.ready); + await page.screenshot({ path: path.join(outDir, `${variant}.png`) }); + console.log(`wrote public/assets/og/${variant}.png`); +} +await browser.close(); diff --git a/scripts/og/template.html b/scripts/og/template.html new file mode 100644 index 0000000..8c5bda9 --- /dev/null +++ b/scripts/og/template.html @@ -0,0 +1,84 @@ + + + + + +Share image + + + + + + + + + + + + diff --git a/scripts/prerender.mjs b/scripts/prerender.mjs new file mode 100644 index 0000000..bcc74de --- /dev/null +++ b/scripts/prerender.mjs @@ -0,0 +1,47 @@ +// Writes every route's real HTML into build/, after `vite build` (client, build/) and +// `vite build --ssr` (server bundle, dist-ssr/). See "build" in package.json. +// +// / -> build/index.html +// /foo -> build/foo/index.html (netlify.toml rewrites /foo to it, status 200) +// not found -> build/404.html (netlify.toml's catch-all, status 404) +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const buildDir = path.join(root, "build"); +const serverEntry = path.join(root, "dist-ssr", "entry-server.mjs"); + +const HEAD_MARKER = ""; +const ROOT_MARKER = '
'; + +const { render, PRERENDER_PATHS, NOT_FOUND_PATH } = await import( + pathToFileURL(serverEntry).href +); + +const template = await readFile(path.join(buildDir, "index.html"), "utf8"); +for (const marker of [HEAD_MARKER, ROOT_MARKER]) { + if (!template.includes(marker)) { + throw new Error(`build/index.html has no ${marker}; cannot prerender`); + } +} + +function outputFile(urlPath) { + if (urlPath === "/") return path.join(buildDir, "index.html"); + if (urlPath === NOT_FOUND_PATH) return path.join(buildDir, "404.html"); + return path.join(buildDir, urlPath, "index.html"); +} + +// Sequential: react-helmet keeps its collected tags in module state +for (const urlPath of [...PRERENDER_PATHS, NOT_FOUND_PATH]) { + // The not-found page is the one the router answers for a path no route has + const requestUrl = urlPath === NOT_FOUND_PATH ? "/page-that-does-not-exist" : urlPath; + const { html, head } = await render(requestUrl); + const page = template + .replace(HEAD_MARKER, () => head) + .replace(ROOT_MARKER, () => `
${html}
`); + const file = outputFile(urlPath); + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, page); + console.log(`prerendered ${urlPath} -> ${path.relative(root, file)}`); +} diff --git a/scripts/sitemap-generator.js b/scripts/sitemap-generator.js index d7d7575..083abde 100644 --- a/scripts/sitemap-generator.js +++ b/scripts/sitemap-generator.js @@ -1,30 +1,34 @@ +// Writes the sitemap. `npm run build` runs it with build/sitemap.xml so is the +// build date; without an argument it refreshes the committed public/sitemap.xml. +// Pages with noindex (see NOINDEX_PATHS in src/seo/routes.ts) stay out of it. const { SitemapStream, streamToPromise } = require('sitemap'); const { writeFileSync, mkdirSync, existsSync } = require('fs'); -const { resolve } = require('path'); +const { dirname, resolve } = require('path'); + +const lastmod = new Date().toISOString().slice(0, 10); // Define links for your routes const links = [ - { url: '/', changefreq: 'daily', priority: 1.0 }, - { url: '/contact', changefreq: 'monthly', priority: 0.7 }, - { url: '/donate', changefreq: 'monthly' }, - { url: '/uninstall', changefreq: 'monthly' }, - { url: '/microsoft-automatic-rewards', changefreq: 'monthly' }, - { url: '/microsoft-automatic-rewards/mobile/privacy', changefreq: 'monthly' }, - { url: '/microsoft-automatic-rewards/mobile/website', changefreq: 'monthly' }, - { url: '/microsoft-automatic-rewards/mobile/test-app', changefreq: 'monthly' }, - { url: '/prolific-studies-notifier', changefreq: 'monthly' }, - { url: '/free-game-claimer', changefreq: 'monthly' }, -]; + { url: '/' }, + { url: '/contact' }, + { url: '/donate' }, + { url: '/microsoft-automatic-rewards' }, + { url: '/microsoft-automatic-rewards/mobile/privacy' }, + { url: '/microsoft-automatic-rewards/mobile/website' }, + { url: '/microsoft-automatic-rewards/mobile/test-app' }, + { url: '/prolific-studies-notifier' }, + { url: '/free-game-claimer' }, +].map((link) => ({ ...link, lastmod })); // Create the stream and define your site hostname -const sitemap = new SitemapStream({ hostname: 'https://svitspindler.com' }); // Replace with your real domain +const sitemap = new SitemapStream({ hostname: 'https://svitspindler.com' }); -// Absolute path to public/sitemap.xml -const sitemapPath = resolve(__dirname, '..', 'public', 'sitemap.xml'); +const sitemapPath = process.argv[2] + ? resolve(process.argv[2]) + : resolve(__dirname, '..', 'public', 'sitemap.xml'); -// Ensure public directory exists -const publicDir = resolve(__dirname, '..', 'public'); -if (!existsSync(publicDir)) mkdirSync(publicDir); +const outputDir = dirname(sitemapPath); +if (!existsSync(outputDir)) mkdirSync(outputDir, { recursive: true }); // Write sitemap streamToPromise(sitemap) @@ -32,7 +36,10 @@ streamToPromise(sitemap) writeFileSync(sitemapPath, data.toString()); console.log(`✅ Sitemap successfully created at ${sitemapPath}`); }) - .catch(console.error); + .catch((error) => { + console.error(error); + process.exit(1); + }); // Push URLs into the stream links.forEach(link => sitemap.write(link)); diff --git a/src/App.css b/src/App.css index 3a6a6bb..3702d45 100644 --- a/src/App.css +++ b/src/App.css @@ -18,7 +18,7 @@ h2 { } p, li, label, select, b, a, span, button { - font-family: 'Poppins', sans-serif; + font-family: 'Poppins', 'Poppins Fallback', sans-serif; } html { diff --git a/src/App.tsx b/src/App.tsx index e3f14c9..b0581a6 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -9,7 +9,7 @@ import { } from "@fortawesome/free-solid-svg-icons"; import { faGithub } from "@fortawesome/free-brands-svg-icons/faGithub"; import { faLinkedin } from "@fortawesome/free-brands-svg-icons/faLinkedin"; -import { Helmet } from "react-helmet"; +import RouteMeta from "./seo/RouteMeta"; import Header from "./components/header/Header"; import Footer from "./components/footer/Footer"; @@ -62,13 +62,7 @@ function App() { ]; return ( <> - - Svit Spindler - - +
diff --git a/src/AppRoutes.tsx b/src/AppRoutes.tsx new file mode 100644 index 0000000..2cc0fb7 --- /dev/null +++ b/src/AppRoutes.tsx @@ -0,0 +1,144 @@ +import React, { ComponentType, lazy, Suspense } from "react"; +import { Route, Routes } from "react-router-dom"; + +import App from "./App"; +import { ThemeProvider } from "./context/ThemeContext"; +import { LanguageProvider } from "./context/LanguageContext"; +import { NotificationProvider } from "./context/NotificationContext"; +import SidebarButtons from "./components/sidebar-buttons/SidebarButtons"; +import ScrollToTop from "./components/scroll-to-top/ScrollToTop"; + +type PageModule = { default: ComponentType }; +type Page = ComponentType & { preload: () => Promise }; + +/** + * React.lazy that can be loaded ahead of rendering. Once `preload()` has resolved the page + * renders without suspending, so a client render that replaces prerendered HTML + * (src/index.tsx) never shows a blank frame while the route's chunk downloads. + */ +function lazyPage(load: () => Promise): Page { + let loaded: ComponentType | undefined; + const preload = () => + load().then((module) => { + loaded = module.default; + return module; + }); + const Lazy = lazy(preload); + const Page = () => { + const Loaded = loaded; + return Loaded ? : ; + }; + return Object.assign(Page, { preload }); +} + +// Only the home page ships in the main bundle; every other route is fetched when visited. +const ContactMe = lazyPage(() => import("./components/contact-me/ContactMe")); +const NotFound = lazyPage(() => import("./components/not-found/NotFound")); +const MicrosoftAutomaticRewards = lazyPage( + () => + import( + "./components/extensions/microsoftAutomaticRewards/MicrosoftAutomaticRewards" + ), +); +const DonatePage = lazyPage( + () => import("./components/extensions/donate/DonatePage"), +); +const Uninstall = lazyPage( + () => import("./components/extensions/uninstall/uninstall"), +); +const Website = lazyPage( + () => + import( + "./components/extensions/microsoftAutomaticRewards/mobile/website/website" + ), +); +const Privacy = lazyPage( + () => + import( + "./components/extensions/microsoftAutomaticRewards/mobile/privacy/Privacy" + ), +); +const TestList = lazyPage( + () => + import( + "./components/extensions/microsoftAutomaticRewards/mobile/test-list/TestList" + ), +); +const ProlificStudiesNotifier = lazyPage( + () => + import( + "./components/extensions/prolificStudiesNotifier/ProlificStudiesNotifier" + ), +); + +const FreeGameClaimer = lazyPage( + () => import("./components/extensions/freeGameClaimer/FreeGameClaimer"), +); + +const PAGES_BY_PATH: Record = { + "/contact": ContactMe, + "/donate": DonatePage, + "/uninstall": Uninstall, + "/microsoft-automatic-rewards": MicrosoftAutomaticRewards, + "/microsoft-automatic-rewards/mobile/privacy": Privacy, + "/microsoft-automatic-rewards/mobile/website": Website, + "/microsoft-automatic-rewards/mobile/test-app": TestList, + "/prolific-studies-notifier": ProlificStudiesNotifier, + "/free-game-claimer": FreeGameClaimer, +}; + +/** Downloads the chunk of the page that `pathname` shows (the not-found page if none). */ +export function preloadRoute(pathname: string): Promise { + return (PAGES_BY_PATH[pathname] ?? NotFound).preload(); +} + +/** + * The whole app below the router. The browser (src/index.tsx) wraps it in a + * BrowserRouter and the prerender (src/entry-server.tsx) in a StaticRouter, so both + * render the same tree. Keep every route's path in src/seo/routes.ts as well. + */ +function AppRoutes() { + return ( + + + + + + + + } /> + } /> + } /> + } /> + } + /> + } + /> + } + /> + } + /> + } + /> + } /> + + } /> + + + + + + ); +} + +export default AppRoutes; diff --git a/src/components/contact-me/ContactMe.tsx b/src/components/contact-me/ContactMe.tsx index cef0d29..cb882e0 100644 --- a/src/components/contact-me/ContactMe.tsx +++ b/src/components/contact-me/ContactMe.tsx @@ -1,14 +1,11 @@ -import { Helmet } from "react-helmet"; +import RouteMeta from "../../seo/RouteMeta"; import React from "react"; import Contact from "../footer/contact/Contact"; function ContactMe() { return ( <> - - Contact Me - - +
diff --git a/src/components/extensions/donate/Donate.css b/src/components/extensions/donate/Donate.css index 0795024..90dfc97 100644 --- a/src/components/extensions/donate/Donate.css +++ b/src/components/extensions/donate/Donate.css @@ -66,7 +66,7 @@ border-radius: 8px; background: transparent; color: var(--primary-color); - font-family: 'Poppins', sans-serif; + font-family: 'Poppins', 'Poppins Fallback', sans-serif; font-size: 1rem; font-weight: 600; text-decoration: none; @@ -136,7 +136,7 @@ align-items: center; gap: 0.5rem; cursor: pointer; - font-family: 'Poppins', sans-serif; + font-family: 'Poppins', 'Poppins Fallback', sans-serif; font-weight: 600; list-style: none; } @@ -201,7 +201,7 @@ .donate-page h1 { margin: 0 0 1rem; - font-family: "Kay Pho Du", serif; + font-family: "Kay Pho Du", "Kay Pho Du Fallback", serif; font-size: 2.75rem; line-height: 1.2; } diff --git a/src/components/extensions/donate/DonatePage.tsx b/src/components/extensions/donate/DonatePage.tsx index babe38b..0b7d565 100644 --- a/src/components/extensions/donate/DonatePage.tsx +++ b/src/components/extensions/donate/DonatePage.tsx @@ -1,6 +1,6 @@ import "./Donate.css"; import React from "react"; -import { Helmet } from "react-helmet"; +import RouteMeta from "../../../seo/RouteMeta"; import { Link } from "react-router-dom"; import { useLanguage } from "../../../context/LanguageContext"; @@ -60,10 +60,7 @@ function DonatePage() { return ( <> - - {text.DONATE.page_meta_title} - - +

{text.DONATE.page_title}

diff --git a/src/components/extensions/freeGameClaimer/FreeGameClaimer.tsx b/src/components/extensions/freeGameClaimer/FreeGameClaimer.tsx index 6e58257..8a1e694 100644 --- a/src/components/extensions/freeGameClaimer/FreeGameClaimer.tsx +++ b/src/components/extensions/freeGameClaimer/FreeGameClaimer.tsx @@ -29,10 +29,6 @@ function FreeGameClaimer() { return ( diff --git a/src/components/extensions/microsoftAutomaticRewards/MicrosoftAutomaticRewards.tsx b/src/components/extensions/microsoftAutomaticRewards/MicrosoftAutomaticRewards.tsx index 470f3db..926c33e 100644 --- a/src/components/extensions/microsoftAutomaticRewards/MicrosoftAutomaticRewards.tsx +++ b/src/components/extensions/microsoftAutomaticRewards/MicrosoftAutomaticRewards.tsx @@ -29,10 +29,6 @@ function MicrosoftAutomaticRewards() { return ( diff --git a/src/components/extensions/microsoftAutomaticRewards/mobile/privacy/Privacy.tsx b/src/components/extensions/microsoftAutomaticRewards/mobile/privacy/Privacy.tsx index 30152b4..dc7c026 100644 --- a/src/components/extensions/microsoftAutomaticRewards/mobile/privacy/Privacy.tsx +++ b/src/components/extensions/microsoftAutomaticRewards/mobile/privacy/Privacy.tsx @@ -1,17 +1,11 @@ import "./Privacy.css"; -import { Helmet } from "react-helmet"; +import RouteMeta from "../../../../../seo/RouteMeta"; import React from "react"; function Privacy() { return ( <> - - Privacy Policy - - +

Privacy Policy for Search automatic rewards

diff --git a/src/components/extensions/microsoftAutomaticRewards/mobile/test-list/TestList.tsx b/src/components/extensions/microsoftAutomaticRewards/mobile/test-list/TestList.tsx index 611d45e..01ff0d6 100644 --- a/src/components/extensions/microsoftAutomaticRewards/mobile/test-list/TestList.tsx +++ b/src/components/extensions/microsoftAutomaticRewards/mobile/test-list/TestList.tsx @@ -1,5 +1,5 @@ import React from "react"; -import { Helmet } from "react-helmet"; +import RouteMeta from "../../../../../seo/RouteMeta"; import BackArrow from "../../../../back-arrow/BackArrow"; import useIsMobile from "../../../../../hooks/useIsMobile"; import { useLanguage } from "../../../../../context/LanguageContext"; @@ -39,10 +39,7 @@ function TestList() { return ( <> - - Microsoft Rewards App - - +

diff --git a/src/components/extensions/microsoftAutomaticRewards/mobile/website/website.tsx b/src/components/extensions/microsoftAutomaticRewards/mobile/website/website.tsx index c6a7eb0..bf2f1fe 100644 --- a/src/components/extensions/microsoftAutomaticRewards/mobile/website/website.tsx +++ b/src/components/extensions/microsoftAutomaticRewards/mobile/website/website.tsx @@ -8,12 +8,13 @@ import React, { } from "react"; import { Link, useSearchParams } from "react-router-dom"; import { Tooltip } from "react-tooltip"; -import { Helmet } from "react-helmet"; +import RouteMeta from "../../../../../seo/RouteMeta"; import { generate } from "random-words"; import BackArrow from "../../../../back-arrow/BackArrow"; import ImageTooltip from "../../../../image-tooltip/ImageTooltip"; import useIsMobile from "../../../../../hooks/useIsMobile"; +import { readStorage } from "../../../../../helpers/preferences"; import { useLanguage } from "../../../../../context/LanguageContext"; import "./website.css"; @@ -44,7 +45,7 @@ function Website() { return { searchNu, searchDelay, isWordsSelected: true }; } - const savedInputs = localStorage.getItem("websiteFormInputs"); + const savedInputs = readStorage("websiteFormInputs"); return savedInputs ? (JSON.parse(savedInputs) as Inputs) : { searchNu: 12, searchDelay: 7, isWordsSelected: true }; @@ -156,10 +157,7 @@ function Website() { return ( <> - - Microsoft Rewards Website - - +
diff --git a/src/components/extensions/prolificStudiesNotifier/ProlificStudiesNotifier.tsx b/src/components/extensions/prolificStudiesNotifier/ProlificStudiesNotifier.tsx index b2c5923..c93db1d 100644 --- a/src/components/extensions/prolificStudiesNotifier/ProlificStudiesNotifier.tsx +++ b/src/components/extensions/prolificStudiesNotifier/ProlificStudiesNotifier.tsx @@ -32,10 +32,6 @@ function ProlificStudiesNotifier() { return ( diff --git a/src/components/extensions/shared/ExtensionPage.css b/src/components/extensions/shared/ExtensionPage.css index 8cbc915..e2c82cf 100644 --- a/src/components/extensions/shared/ExtensionPage.css +++ b/src/components/extensions/shared/ExtensionPage.css @@ -142,7 +142,7 @@ gap: 1rem; padding: 0.9rem 0; cursor: pointer; - font-family: 'Poppins', sans-serif; + font-family: 'Poppins', 'Poppins Fallback', sans-serif; font-weight: 600; list-style: none; } diff --git a/src/components/extensions/shared/ExtensionPage.tsx b/src/components/extensions/shared/ExtensionPage.tsx index 93ad00c..4c692ae 100644 --- a/src/components/extensions/shared/ExtensionPage.tsx +++ b/src/components/extensions/shared/ExtensionPage.tsx @@ -9,7 +9,7 @@ import { import { faChrome } from "@fortawesome/free-brands-svg-icons/faChrome"; import { faFirefoxBrowser } from "@fortawesome/free-brands-svg-icons/faFirefoxBrowser"; import { faGithub } from "@fortawesome/free-brands-svg-icons/faGithub"; -import { Helmet } from "react-helmet"; +import RouteMeta from "../../../seo/RouteMeta"; import { useLanguage } from "../../../context/LanguageContext"; import { Link, Section } from "../../../types/ComponentTypes"; @@ -22,7 +22,6 @@ import { ExtensionInfo } from "../extensionInfo"; type ExtensionPageProps = { extension: ExtensionInfo; - meta: { title: string; description: string }; icon: { src: string; srcSet?: string; alt: string }; /** Sidebar entries for the page's own sections, between Home and Donate. */ sections: Section[]; @@ -32,7 +31,6 @@ type ExtensionPageProps = { /** Shared frame of an extension page: sidebar, header with store links, donate, contact. */ function ExtensionPage({ extension, - meta, icon, sections, children, @@ -77,10 +75,7 @@ function ExtensionPage({ return ( <> - - {meta.title} - - +
diff --git a/src/components/extensions/uninstall/uninstall.tsx b/src/components/extensions/uninstall/uninstall.tsx index 3ce2828..709b764 100644 --- a/src/components/extensions/uninstall/uninstall.tsx +++ b/src/components/extensions/uninstall/uninstall.tsx @@ -1,4 +1,4 @@ -import { Helmet } from "react-helmet"; +import RouteMeta from "../../../seo/RouteMeta"; import React, { ChangeEvent, FormEvent, useEffect, useState } from "react"; import { useSearchParams } from "react-router-dom"; import { Tooltip } from "react-tooltip"; @@ -86,10 +86,7 @@ function Uninstall() { }, [inputs, wasSent, text.EXTENSION.other]); return ( <> - - Uninstall - - +

{text.EXTENSION.form_title}

{text.EXTENSION.form_explanation}

diff --git a/src/components/header/Header.css b/src/components/header/Header.css index f3ed8b0..fad09ec 100644 --- a/src/components/header/Header.css +++ b/src/components/header/Header.css @@ -1,12 +1,12 @@ .App-header { - font-family: "Kay Pho Du", serif; + font-family: "Kay Pho Du", "Kay Pho Du Fallback", serif; font-weight: 400; font-style: normal; margin-bottom: 5em; } .name { - font-family: "Kay Pho Du", serif; + font-family: "Kay Pho Du", "Kay Pho Du Fallback", serif; text-align: center; } diff --git a/src/components/main/experience/Experience.css b/src/components/main/experience/Experience.css index cc682ef..a867c58 100644 --- a/src/components/main/experience/Experience.css +++ b/src/components/main/experience/Experience.css @@ -11,7 +11,7 @@ .company { grid-area: company; - font-family: Poppins, sans-serif; + font-family: Poppins, 'Poppins Fallback', sans-serif; } .year { diff --git a/src/components/not-found/NotFound.tsx b/src/components/not-found/NotFound.tsx index d804996..9870323 100644 --- a/src/components/not-found/NotFound.tsx +++ b/src/components/not-found/NotFound.tsx @@ -1,5 +1,6 @@ import "./NotFound.css"; -import { Helmet } from "react-helmet"; +import RouteMeta from "../../seo/RouteMeta"; +import { NOT_FOUND_PATH } from "../../seo/routes"; import React from "react"; import BackArrow from "../back-arrow/BackArrow"; @@ -9,10 +10,7 @@ function NotFound() { const { text } = useLanguage(); return ( <> - - 404 {text.GENERAL.not_found} - - +

404 {text.GENERAL.not_found}

diff --git a/src/context/LanguageContext.tsx b/src/context/LanguageContext.tsx index 6523cad..bcc9839 100644 --- a/src/context/LanguageContext.tsx +++ b/src/context/LanguageContext.tsx @@ -11,7 +11,8 @@ import parse from "html-react-parser"; import enText from "../assets/translations/en.json"; import sloText from "../assets/translations/sl.json"; import { ReactNodeProps } from "../types/PropTypes"; -import { isLanguage, Language } from "../types/enums"; +import { Language } from "../types/enums"; +import { readStoredLanguage } from "../helpers/preferences"; type LanguageContextType = { language: Language; @@ -32,10 +33,8 @@ const LanguageContext = createContext({ }); export function LanguageProvider({ children }: ReactNodeProps) { - const [language, setLanguage] = useState(() => { - const storedLanguage = localStorage.getItem("language"); - return isLanguage(storedLanguage) ? storedLanguage : Language.ENGLISH; - }); + // Reads storage only in the browser; the server renders English + const [language, setLanguage] = useState(readStoredLanguage); // Stable so consumers can list it as an effect dependency. const changeLanguage = useCallback((newLanguage: Language) => { diff --git a/src/context/ThemeContext.tsx b/src/context/ThemeContext.tsx index 81e37a1..757a3ba 100644 --- a/src/context/ThemeContext.tsx +++ b/src/context/ThemeContext.tsx @@ -1,5 +1,6 @@ import React, { createContext, useContext, useEffect, useState } from "react"; import { ReactNodeProps } from "../types/PropTypes"; +import { readStoredDarkMode } from "../helpers/preferences"; type ThemeContextType = { darkMode: boolean; @@ -9,10 +10,8 @@ type ThemeContextType = { const ThemeContext = createContext(undefined); export function ThemeProvider({ children }: ReactNodeProps) { - const [darkMode, setDarkMode] = useState(() => { - const stored = localStorage.getItem("darkMode"); - return stored ? (JSON.parse(stored) as boolean) : false; - }); + // Reads storage only in the browser; the server renders the light theme + const [darkMode, setDarkMode] = useState(readStoredDarkMode); useEffect(() => { localStorage.setItem("darkMode", JSON.stringify(darkMode)); diff --git a/src/entry-server.tsx b/src/entry-server.tsx new file mode 100644 index 0000000..ac988cf --- /dev/null +++ b/src/entry-server.tsx @@ -0,0 +1,58 @@ +import React from "react"; +import { renderToPipeableStream } from "react-dom/server"; +import { Helmet } from "react-helmet"; +import { StaticRouter } from "react-router-dom"; +import { Writable } from "node:stream"; + +import AppRoutes from "./AppRoutes"; + +export { NOT_FOUND_PATH, PRERENDER_PATHS } from "./seo/routes"; + +export type RenderedPage = { + /** Markup for the inside of
*/ + html: string; + /** Tags react-helmet collected, ready for */ + head: string; +}; + +/** + * Renders one URL to static HTML. Resolves after every lazy route has loaded, so the + * markup is the finished page and not a Suspense fallback. + */ +export function render(url: string): Promise { + return new Promise((resolve, reject) => { + const chunks: Buffer[] = []; + const sink = new Writable({ + write(chunk: Buffer, _encoding, callback) { + chunks.push(chunk); + callback(); + }, + }); + sink.on("finish", () => { + const helmet = Helmet.renderStatic(); + resolve({ + html: Buffer.concat(chunks).toString("utf8"), + head: [helmet.title, helmet.meta, helmet.link, helmet.script] + .map((tags) => tags.toString()) + .join("\n "), + }); + }); + + const stream = renderToPipeableStream( + + + + + , + { + onAllReady() { + stream.pipe(sink); + }, + onShellError: reject, + onError(error) { + reject(error instanceof Error ? error : new Error(String(error))); + }, + }, + ); + }); +} diff --git a/src/fontAwesome.ts b/src/fontAwesome.ts new file mode 100644 index 0000000..14c2b9c --- /dev/null +++ b/src/fontAwesome.ts @@ -0,0 +1,7 @@ +import { config } from "@fortawesome/fontawesome-svg-core"; +import "@fortawesome/fontawesome-svg-core/styles.css"; + +// Font Awesome normally injects its stylesheet when the JS runs. The prerendered HTML is on +// screen before that, so its icons would be unsized and the page would jump. The CSS is +// bundled into index.html instead. +config.autoAddCss = false; diff --git a/src/helpers/preferences.ts b/src/helpers/preferences.ts new file mode 100644 index 0000000..ae16d4d --- /dev/null +++ b/src/helpers/preferences.ts @@ -0,0 +1,58 @@ +import { isLanguage, Language } from "../types/enums"; + +const LANGUAGE_KEY = "language"; +const DARK_MODE_KEY = "darkMode"; +const WEBSITE_FORM_KEY = "websiteFormInputs"; +const WEBSITE_FORM_PATH = "/microsoft-automatic-rewards/mobile/website"; + +/** localStorage read that is safe on the server and in browsers that block storage. */ +export function readStorage(key: string): string | null { + if (typeof window === "undefined") { + return null; + } + try { + return window.localStorage.getItem(key); + } catch { + return null; + } +} + +export function readStoredLanguage(): Language { + const stored = readStorage(LANGUAGE_KEY); + return isLanguage(stored) ? stored : Language.ENGLISH; +} + +export function readStoredDarkMode(): boolean { + const stored = readStorage(DARK_MODE_KEY); + if (!stored) { + return false; + } + try { + return JSON.parse(stored) === true; + } catch { + return false; + } +} + +/** + * The prerendered HTML is the default visit: English, light theme, nothing saved. + * Hydrating it for any other visitor would mismatch, so those visitors get a client + * render instead. + */ +export function canHydratePrerenderedHtml( + pathname: string, + search: string, +): boolean { + const langParam = new URLSearchParams(search).get("lang"); + if (isLanguage(langParam) && langParam !== Language.ENGLISH) { + return false; + } + if (readStoredLanguage() !== Language.ENGLISH || readStoredDarkMode()) { + return false; + } + // The mobile-searches form restores its last inputs from localStorage + return !( + pathname.startsWith(WEBSITE_FORM_PATH) && + readStorage(WEBSITE_FORM_KEY) !== null + ); +} diff --git a/src/hooks/useFlipAnimation.ts b/src/hooks/useFlipAnimation.ts index 31e0e6d..e7934ea 100644 --- a/src/hooks/useFlipAnimation.ts +++ b/src/hooks/useFlipAnimation.ts @@ -1,4 +1,8 @@ -import { useLayoutEffect, useRef } from "react"; +import { useEffect, useLayoutEffect, useRef } from "react"; + +// useLayoutEffect warns when the page is prerendered; there is nothing to measure then +const useIsomorphicLayoutEffect = + typeof window === "undefined" ? useEffect : useLayoutEffect; const DURATION_MS = 500; @@ -35,7 +39,7 @@ function useFlipAnimation(order: unknown) { runningAnimations.current.forEach((animation) => animation.cancel()); }; - useLayoutEffect(() => { + useIsomorphicLayoutEffect(() => { const first = firstPositions.current; firstPositions.current = null; if ( diff --git a/src/hooks/useIsMobile.ts b/src/hooks/useIsMobile.ts index af3a3e9..0785971 100644 --- a/src/hooks/useIsMobile.ts +++ b/src/hooks/useIsMobile.ts @@ -1,17 +1,27 @@ -import { useEffect, useState } from "react"; +import { useCallback, useSyncExternalStore } from "react"; + +function subscribeToResize(onChange: () => void) { + window.addEventListener("resize", onChange); + return () => { + window.removeEventListener("resize", onChange); + }; +} + +/** The server and the hydrating client both see a desktop width; React then re-renders. */ +function getServerSnapshot() { + return false; +} function useIsMobile(breakpoint = 767) { - const [isMobile, setisMobile] = useState(window.innerWidth <= breakpoint); - useEffect(() => { - const handleResize = () => { - setisMobile(window.innerWidth <= breakpoint); - }; - window.addEventListener("resize", handleResize); - return () => { - window.removeEventListener("resize", handleResize); - }; - }, [breakpoint]); - return isMobile; + const getSnapshot = useCallback( + () => window.innerWidth <= breakpoint, + [breakpoint], + ); + return useSyncExternalStore( + subscribeToResize, + getSnapshot, + getServerSnapshot, + ); } export default useIsMobile; diff --git a/src/index.css b/src/index.css index 8f25a0b..3451e1a 100644 --- a/src/index.css +++ b/src/index.css @@ -66,3 +66,26 @@ body { .w-40 { width: 40%; } + +/* Metric-matched stand-ins for the web fonts, used until the real ones arrive. They take + the same width and line height as Poppins 400 and Kay Pho Du 700, so the swap does not + reflow the prerendered text. Values come from the fonts' own metrics against Arial and + Times New Roman Bold (size-adjust = average letter width ratio; overrides = font + ascent/descent/line gap divided by size-adjust). Liberation fonts are the Linux twins. */ +@font-face { + font-family: "Poppins Fallback"; + src: local("Arial"), local("Liberation Sans"), local("Helvetica"); + size-adjust: 114.1%; + ascent-override: 92.02%; + descent-override: 30.67%; + line-gap-override: 8.76%; +} +@font-face { + font-family: "Kay Pho Du Fallback"; + font-weight: 700; + src: local("Times New Roman Bold"), local("TimesNewRomanPS-BoldMT"), local("Liberation Serif Bold"); + size-adjust: 107.88%; + ascent-override: 87.99%; + descent-override: 23.76%; + line-gap-override: 0%; +} diff --git a/src/index.tsx b/src/index.tsx index 0ffc699..c69c60c 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -1,60 +1,13 @@ -import React, { lazy, Suspense } from "react"; -import ReactDOM from "react-dom/client"; +import React from "react"; +import { hydrateRoot, createRoot } from "react-dom/client"; import "@fontsource/kay-pho-du/700.css"; import "@fontsource/poppins/400.css"; import "./index.css"; -import { BrowserRouter, Route, Routes } from "react-router-dom"; +import "./fontAwesome"; +import { BrowserRouter } from "react-router-dom"; -import App from "./App"; -import { ThemeProvider } from "./context/ThemeContext"; -import { LanguageProvider } from "./context/LanguageContext"; -import { NotificationProvider } from "./context/NotificationContext"; -import SidebarButtons from "./components/sidebar-buttons/SidebarButtons"; -import ScrollToTop from "./components/scroll-to-top/ScrollToTop"; - -// Only the home page ships in the main bundle; every other route is fetched when visited. -const ContactMe = lazy(() => import("./components/contact-me/ContactMe")); -const NotFound = lazy(() => import("./components/not-found/NotFound")); -const MicrosoftAutomaticRewards = lazy( - () => - import( - "./components/extensions/microsoftAutomaticRewards/MicrosoftAutomaticRewards" - ), -); -const DonatePage = lazy( - () => import("./components/extensions/donate/DonatePage"), -); -const Uninstall = lazy( - () => import("./components/extensions/uninstall/uninstall"), -); -const Website = lazy( - () => - import( - "./components/extensions/microsoftAutomaticRewards/mobile/website/website" - ), -); -const Privacy = lazy( - () => - import( - "./components/extensions/microsoftAutomaticRewards/mobile/privacy/Privacy" - ), -); -const TestList = lazy( - () => - import( - "./components/extensions/microsoftAutomaticRewards/mobile/test-list/TestList" - ), -); -const ProlificStudiesNotifier = lazy( - () => - import( - "./components/extensions/prolificStudiesNotifier/ProlificStudiesNotifier" - ), -); - -const FreeGameClaimer = lazy( - () => import("./components/extensions/freeGameClaimer/FreeGameClaimer"), -); +import AppRoutes, { preloadRoute } from "./AppRoutes"; +import { canHydratePrerenderedHtml } from "./helpers/preferences"; // A deploy replaces the hashed route chunks, so a tab opened before it can ask for // files that no longer exist. Reload to pick up the new index.html, at most once per @@ -71,52 +24,24 @@ window.addEventListener("vite:preloadError", (event) => { window.location.reload(); }); -const root = ReactDOM.createRoot(document.getElementById("root")!); -root.render( +const container = document.getElementById("root")!; +const app = ( - - - - - - - - - } /> - } /> - } /> - } /> - } - /> - } - /> - } - /> - } - /> - } - /> - } - /> - - } /> - - - - - - - , + + + + ); + +// Netlify serves every page prerendered (scripts/prerender.mjs). That HTML shows the +// default visit (English, light theme), so only visitors who match it can hydrate it; +// everyone else, and `vite dev` where #root is empty, gets a client render. The route's +// chunk is loaded first so the prerendered page stays on screen until the app can +// replace it, with no blank frame in between. +const { pathname, search } = window.location; +if (container.hasChildNodes() && canHydratePrerenderedHtml(pathname, search)) { + hydrateRoot(container, app); +} else { + const render = () => createRoot(container).render(app); + preloadRoute(pathname.replace(/(.)\/$/, "$1")).then(render, render); +} diff --git a/src/seo/RouteMeta.tsx b/src/seo/RouteMeta.tsx new file mode 100644 index 0000000..907f550 --- /dev/null +++ b/src/seo/RouteMeta.tsx @@ -0,0 +1,50 @@ +import React from "react"; +import { Helmet } from "react-helmet"; + +import { useLanguage } from "../context/LanguageContext"; +import { getPageMeta, SITE_NAME, type Translations } from "./routes"; + +/** `<` is escaped so a value can never close the script tag. */ +const serializeJsonLd = (data: object) => + JSON.stringify(data).replace(/ from src/seo/routes.ts. The same component runs in the prerender, + * where its tags are written into the static HTML (react-helmet marks them with + * data-react-helmet), and in the browser, where it replaces those tags. + */ +function RouteMeta({ path }: { path: string }) { + const { text } = useLanguage(); + const meta = getPageMeta(path, text as Translations); + + return ( + + {meta.title} + + {/* A noindex page with a canonical sends Google two conflicting signals */} + {!meta.noindex && } + {meta.noindex && } + + + + + + + + + + + + + + + {meta.jsonLd.map((data, index) => ( + + ))} + + ); +} + +export default RouteMeta; diff --git a/src/seo/routes.ts b/src/seo/routes.ts new file mode 100644 index 0000000..b071ed7 --- /dev/null +++ b/src/seo/routes.ts @@ -0,0 +1,259 @@ +import enText from "../assets/translations/en.json"; +import { + FREE_GAME_CLAIMER, + PROLIFIC_STUDIES_NOTIFIER, + SEARCH_AUTOMATIC_REWARDS, + type ExtensionInfo, +} from "../components/extensions/extensionInfo"; + +/** + * Single source of every page's data. The prerender (scripts/prerender.mjs, through + * src/entry-server.tsx) and the client's both read it, so the HTML that + * crawlers get and what the app sets after it starts can't drift apart. + */ + +export type Translations = Record>; + +export const SITE_URL = "https://svitspindler.com"; +export const SITE_NAME = "Svit Spindler"; +const OG_IMAGE_WIDTH = 1200; +const OG_IMAGE_HEIGHT = 630; +const PERSON_ID = `${SITE_URL}/#person`; +const WEBSITE_ID = `${SITE_URL}/#website`; + +/** Pages that crawlers should not index; also left out of the sitemap. */ +export const NOINDEX_PATHS = ["/uninstall"]; + +type ShareImage = "home" | "free-game-claimer" | "prolific-studies-notifier"; + +export type PageMeta = { + path: string; + title: string; + description: string; + canonical: string; + noindex: boolean; + image: { url: string; alt: string; width: number; height: number }; + jsonLd: object[]; +}; + +type RouteDefinition = { + path: string; + /** Title and description; translations are passed so extension pages follow the language. */ + meta: (text: Translations) => { title: string; description: string }; + image?: ShareImage; + jsonLd?: (meta: { title: string; description: string }) => object[]; +}; + +const HOME_DESCRIPTION = + "Full-stack software engineer in Ljubljana working with Java, Spring Boot, Kotlin, TypeScript and React. Builder of Digitalna Košarica and browser extensions with 40,000+ users."; + +const IMAGE_ALTS: Record = { + home: "Svit Spindler, full-stack software engineer in Ljubljana", + "free-game-claimer": + "Free Game Claimer, a browser extension that claims free games from Epic, Steam, GOG, IndieGala and Prime Gaming", + "prolific-studies-notifier": + "Prolific Studies Notifier, a browser extension that alerts you to new Prolific studies", +}; + +const withoutQuery = (url: string) => url.split("?")[0]; + +const personReference = { + "@type": "Person", + "@id": PERSON_ID, + name: SITE_NAME, + url: `${SITE_URL}/`, +}; + +const person = { + ...personReference, + jobTitle: "Full-Stack Software Engineer", + image: `${SITE_URL}/assets/images/profile@2x.webp`, + email: "mailto:svit.spindler@gmail.com", + address: { + "@type": "PostalAddress", + addressLocality: "Ljubljana", + addressCountry: "SI", + }, + worksFor: { + "@type": "Organization", + name: "Opti Solutions", + url: "https://opti-solutions.si/", + }, + alumniOf: { + "@type": "CollegeOrUniversity", + name: "University of Ljubljana, Faculty of Computer and Information Science", + }, + knowsAbout: [ + "Java", + "Spring Boot", + "Kotlin", + "TypeScript", + "React", + "Next.js", + "PostgreSQL", + "Docker", + ], + sameAs: [ + "https://www.linkedin.com/in/svit-spindler-591a7a28b/", + "https://github.com/spin311", + ], +}; + +const website = { + "@type": "WebSite", + "@id": WEBSITE_ID, + name: SITE_NAME, + url: `${SITE_URL}/`, + author: { "@id": PERSON_ID }, +}; + +function softwareApplication(extension: ExtensionInfo) { + const stores = [ + withoutQuery(extension.chromeUrl), + withoutQuery(extension.firefoxUrl), + extension.githubUrl, + ]; + return ({ description }: { title: string; description: string }) => [ + { + "@context": "https://schema.org", + "@type": "SoftwareApplication", + name: extension.name, + description, + url: `${SITE_URL}${extension.page}`, + applicationCategory: "BrowserApplication", + operatingSystem: "Chrome, Firefox", + offers: { "@type": "Offer", price: "0", priceCurrency: "EUR" }, + author: personReference, + installUrl: stores[0], + sameAs: stores, + }, + ]; +} + +const ROUTES: RouteDefinition[] = [ + { + path: "/", + meta: () => ({ + title: "Svit Spindler, Full-Stack Software Engineer in Ljubljana", + description: HOME_DESCRIPTION, + }), + jsonLd: () => [ + { "@context": "https://schema.org", ...person }, + { "@context": "https://schema.org", ...website }, + ], + }, + { + path: "/contact", + meta: () => ({ + title: "Contact Svit Spindler", + description: + "Send Svit Spindler a message about work, a project or one of the browser extensions.", + }), + }, + { + path: "/donate", + meta: (text) => ({ + title: text.DONATE.page_meta_title, + description: text.DONATE.page_meta_description, + }), + }, + { + path: "/uninstall", + meta: () => ({ + title: "Uninstall feedback | Svit Spindler", + description: + "Tell Svit Spindler why you uninstalled one of his browser extensions.", + }), + }, + { + path: "/microsoft-automatic-rewards", + meta: (text) => ({ + title: text.MICROSOFT.meta_title, + description: text.MICROSOFT.meta_description, + }), + jsonLd: softwareApplication(SEARCH_AUTOMATIC_REWARDS), + }, + { + path: "/microsoft-automatic-rewards/mobile/privacy", + meta: () => ({ + title: "Privacy policy of the Search Automatic Rewards app", + description: + "What data the Search Automatic Rewards mobile app by Svit Spindler collects and how it is used.", + }), + }, + { + path: "/microsoft-automatic-rewards/mobile/website", + meta: () => ({ + title: "Search Automatic Rewards on your phone's browser", + description: + "Website version of Search Automatic Rewards for mobile devices. It opens new Bing tabs to run your daily searches.", + }), + }, + { + path: "/microsoft-automatic-rewards/mobile/test-app", + meta: () => ({ + title: "Search Automatic Rewards mobile app", + description: + "Open the Search Automatic Rewards mobile app on your phone: scan the QR code or use the website version.", + }), + }, + { + path: "/prolific-studies-notifier", + meta: (text) => ({ + title: text.PROLIFIC.meta_title, + description: text.PROLIFIC.meta_description, + }), + image: "prolific-studies-notifier", + jsonLd: softwareApplication(PROLIFIC_STUDIES_NOTIFIER), + }, + { + path: "/free-game-claimer", + meta: (text) => ({ + title: text.CLAIMER.meta_title, + description: text.CLAIMER.meta_description, + }), + image: "free-game-claimer", + jsonLd: softwareApplication(FREE_GAME_CLAIMER), + }, +]; + +/** Not a route of its own: the page behind the `*` route and Netlify's 404. */ +export const NOT_FOUND_PATH = "/404"; +const NOT_FOUND: RouteDefinition = { + path: NOT_FOUND_PATH, + meta: (text) => ({ + title: `404 ${text.GENERAL.not_found} | ${SITE_NAME}`, + description: "This page does not exist.", + }), +}; + +/** Paths the prerender writes a page for, with the not-found page last. */ +export const PRERENDER_PATHS = ROUTES.map((route) => route.path); + +function canonicalUrl(path: string): string { + return path === "/" ? `${SITE_URL}/` : `${SITE_URL}${path}`; +} + +/** Everything a page puts in . `text` is the current language's translations. */ +export function getPageMeta( + path: string, + text: Translations = enText as Translations, +): PageMeta { + const route = + ROUTES.find((candidate) => candidate.path === path) ?? NOT_FOUND; + const meta = route.meta(text); + const image = route.image ?? "home"; + return { + path: route.path, + ...meta, + canonical: canonicalUrl(route.path), + noindex: route === NOT_FOUND || NOINDEX_PATHS.includes(route.path), + image: { + url: `${SITE_URL}/assets/og/${image}.png`, + alt: IMAGE_ALTS[image], + width: OG_IMAGE_WIDTH, + height: OG_IMAGE_HEIGHT, + }, + jsonLd: route.jsonLd?.(meta) ?? [], + }; +} diff --git a/vite.config.ts b/vite.config.ts index 168f856..172b301 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -28,17 +28,25 @@ function inlineStylesheets(): Plugin { }; } -export default defineConfig({ +export default defineConfig(({ isSsrBuild }) => ({ plugins: [react(), inlineStylesheets()], + // The prerender (scripts/prerender.mjs) imports the server bundle in plain Node, where + // react-helmet and the JSON translations need bundling rather than a CJS/ESM import. + ssr: { noExternal: true }, build: { - outDir: "build", // keep same output as CRA + // The server bundle is a build tool, not a deploy artifact (see npm run build) + outDir: isSsrBuild ? "dist-ssr" : "build", // client output keeps the CRA name // Hashed build output, kept apart from the unhashed files in public/assets so // netlify.toml can cache it as immutable assetsDir: "static", - sourcemap: true, + sourcemap: !isSsrBuild, + // Pages are prerendered, so their markup is on screen before a route's JS chunk loads. + // Route stylesheets must already be in index.html (inlined below), or the page + // would first paint unstyled and jump when its chunk's CSS arrives. + cssCodeSplit: false, // Fonts come in unicode-range subsets the browser fetches only when a page needs // them; inlining the small ones would put every subset into index.html instead. assetsInlineLimit: (filePath) => /\.woff2?$/.test(filePath) ? false : undefined, }, -}); +}));