diff --git a/README.md b/README.md index 026f85a..f23daca 100644 --- a/README.md +++ b/README.md @@ -611,7 +611,8 @@ export function App({ locale, children }: { locale: string; children: React.Reac Hooks: `useLocale()`, `useLocales()`, `useLocaleSwitch()`, `useLocaleContext()`. `switchTo(locale)` writes the cookie and navigates (full page by default; pass -`navigate` to hook a router, `persist` to save server-side). +`navigate` to hook a router, `persist` to save server-side). Navigation does not +wait for `persist`, so `persist` must survive the page unloading — see below. ### Next.js (App Router) @@ -641,8 +642,78 @@ export default function RootLayout({ children }: { children: React.ReactNode }) ``` `RosettaProvider` reads the locale the middleware forced (`getServerLocale(config)`) -and provides it to the client. Persist the choice for signed-in users with a server -action: +and provides it to the client. `RosettaProvider` itself takes no `persist`; to save +the choice for signed-in users, resolve the locale yourself and render +`LocaleProvider` with a keepalive request: + +```tsx +// components/locale-persist.tsx +"use client"; +import { LocaleProvider } from "rosetta-i18n/react"; +import { localeConfig } from "@/i18n/config"; + +// The switch navigates immediately, so the save must survive the unload: +// `keepalive` lets the request outlive the page. Skip it when signed out. +function persistLocale(locale: string): Promise { + return fetch("/api/me", { + method: "PATCH", + keepalive: true, + headers: { "content-type": "application/json" }, + body: JSON.stringify({ locale }), + }).then( + () => undefined, + () => undefined, + ); +} + +export function LocalePersist({ + locale, + signedIn, + children, +}: { + locale: string; + signedIn: boolean; + children: React.ReactNode; +}) { + return ( + + {children} + + ); +} +``` + +Use it in the layout in place of `RosettaProvider`, passing the resolved locale: + +```tsx +// app/layout.tsx +import { getServerLocale } from "rosetta-i18n/next"; +import { LocalePersist } from "@/components/locale-persist"; + +export default async function RootLayout({ children }: { children: React.ReactNode }) { + const locale = await getServerLocale(localeConfig); + const signedIn = /* your session check */ false; + return ( + + + + {children} + + + + ); +} +``` + +Do **not** pass a server action as `persist`. The navigation aborts it, so the +account is often never updated, and the aborted response rejects. + +For a settings screen where the user stays on the page, `createSetLocaleAction` +is the right tool — `await` it and refresh once it resolves: ```ts // app/locale-actions.ts diff --git a/package.json b/package.json index ed985dc..c1d45f5 100644 --- a/package.json +++ b/package.json @@ -98,7 +98,10 @@ "@biomejs/biome": "2.5.12", "@types/node": "22.15.3", "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", + "jsdom": "^26.1.0", "react": "^19.3.0", + "react-dom": "^19.3.0", "rollup": "^4.63.1", "rollup-plugin-esbuild": "^6.1.1", "typescript": "5.9.2", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c87f7c6..e3494a2 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -24,9 +24,18 @@ importers: '@types/react': specifier: ^19.3.0 version: 19.3.0 + '@types/react-dom': + specifier: ^19.3.0 + version: 19.3.0(@types/react@19.3.0) + jsdom: + specifier: ^26.1.0 + version: 26.1.0 react: specifier: ^19.3.0 version: 19.3.0 + react-dom: + specifier: ^19.3.0 + version: 19.3.0(react@19.3.0) rollup: specifier: ^4.63.1 version: 4.63.3 @@ -38,10 +47,13 @@ importers: version: 5.9.2 vitest: specifier: ^3.2.7 - version: 3.2.7(@types/node@22.15.3)(lightningcss@1.33.0) + version: 3.2.7(@types/node@22.15.3)(jsdom@26.1.0)(lightningcss@1.33.0) packages: + '@asamuzakjp/css-color@3.2.0': + resolution: {integrity: sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==} + '@astrojs/compiler-binding-android-arm64@0.5.1': resolution: {integrity: sha512-nMb2nMIJtcWLNH+fV75Enmi+jp4tIOYOfsv4XtpgdOWkqc9P4uSSdK5u1xb340AzrXo5V18SxLl/nc3vcqtamQ==} engines: {node: ^20.19.0 || >=22.12.0} @@ -250,6 +262,34 @@ packages: resolution: {integrity: sha512-dlT1m5e/0yUL0kRNcQn7yGLVThkgbB0Ga/1AmfDDC/8ik6AIiSf2QLQO2zPYvefsHP0aFgxO93cVLCCfDp7kzQ==} engines: {node: '>= 20.12.0'} + '@csstools/color-helpers@5.1.0': + resolution: {integrity: sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==} + engines: {node: '>=18'} + + '@csstools/css-calc@2.1.4': + resolution: {integrity: sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==} + engines: {node: '>=18'} + peerDependencies: + '@csstools/css-parser-algorithms': ^3.0.5 + '@csstools/css-tokenizer': ^3.0.4 + + '@csstools/css-color-parser@3.1.0': + resolution: {integrity: sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==} + engines: {node: '>=18'} + peerDependencies: + '@csstools/css-parser-algorithms': ^3.0.5 + '@csstools/css-tokenizer': ^3.0.4 + + '@csstools/css-parser-algorithms@3.0.5': + resolution: {integrity: sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==} + engines: {node: '>=18'} + peerDependencies: + '@csstools/css-tokenizer': ^3.0.4 + + '@csstools/css-tokenizer@3.0.4': + resolution: {integrity: sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==} + engines: {node: '>=18'} + '@emnapi/core@1.11.1': resolution: {integrity: sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ==} @@ -922,6 +962,11 @@ packages: '@types/node@22.15.3': resolution: {integrity: sha512-lX7HFZeHf4QG/J7tBZqrCAXwz9J5RD56Y6MpP0eJkka8p+K0RY/yBTW7CYFJ4VGCclxqOLKmiGP5juQc6MKgcw==} + '@types/react-dom@19.3.0': + resolution: {integrity: sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==} + peerDependencies: + '@types/react': ^19.3.0 + '@types/react@19.3.0': resolution: {integrity: sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==} @@ -960,6 +1005,10 @@ packages: '@vitest/utils@3.2.7': resolution: {integrity: sha512-x6BDOd7dyo3PFLY3I9/HJ25X/6OurhGXk2/B9gOZNPF7XDVjeBK4k01lQE5uvDpbuheErh91qYuE1E2OEjK3Rw==} + agent-base@7.1.4: + resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==} + engines: {node: '>= 14'} + am-i-vibing@0.4.0: resolution: {integrity: sha512-MxT4XZL7pzLHpuvhDKdMaQHMGGkJDLluKBLsbstn+8wv9sWcFT6h+0ve9qkml95amVTZtZV83gQe2hY+ojgHLg==} hasBin: true @@ -1083,9 +1132,17 @@ packages: resolution: {integrity: sha512-0LrrStPOdJj+SPCCrGhzryycLjwcgUSHBtxNA8aIDxf0GLsRh1cKYhB00Gd1lDOS4yGH69+SNn13+TWbVHETFQ==} engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0, npm: '>=7.0.0'} + cssstyle@4.6.0: + resolution: {integrity: sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==} + engines: {node: '>=18'} + csstype@3.2.3: resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} + data-urls@5.0.0: + resolution: {integrity: sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==} + engines: {node: '>=18'} + debug@4.4.3: resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} engines: {node: '>=6.0'} @@ -1095,6 +1152,9 @@ packages: supports-color: optional: true + decimal.js@10.6.0: + resolution: {integrity: sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==} + deep-eql@5.0.2: resolution: {integrity: sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==} engines: {node: '>=6'} @@ -1144,6 +1204,10 @@ packages: resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==} engines: {node: '>=0.12'} + entities@6.0.1: + resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==} + engines: {node: '>=0.12'} + es-module-lexer@1.7.0: resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==} @@ -1225,6 +1289,10 @@ packages: hast-util-whitespace@3.0.0: resolution: {integrity: sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==} + html-encoding-sniffer@4.0.0: + resolution: {integrity: sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==} + engines: {node: '>=18'} + html-escaper@3.0.3: resolution: {integrity: sha512-RuMffC89BOWQoY0WKGpIhn5gX3iI54O6nRA0yC124NYVtzjmFWBIiFd8M0x+ZdX0P9R4lADg1mgP8C7PxGOWuQ==} @@ -1234,6 +1302,18 @@ packages: http-cache-semantics@4.2.0: resolution: {integrity: sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==} + http-proxy-agent@7.0.2: + resolution: {integrity: sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==} + engines: {node: '>= 14'} + + https-proxy-agent@7.0.6: + resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==} + engines: {node: '>= 14'} + + iconv-lite@0.6.3: + resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==} + engines: {node: '>=0.10.0'} + iron-webcrypto@1.2.1: resolution: {integrity: sha512-feOM6FaSr6rEABp/eDfVseKyTMDt+KGpeB35SkVn9Tyn0CqvVsY3EwI0v5i8nMHyJnzCIQf7nsy3p41TPkJZhg==} @@ -1246,6 +1326,9 @@ packages: resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==} engines: {node: '>=12'} + is-potential-custom-element-name@1.0.1: + resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==} + js-tokens@9.0.1: resolution: {integrity: sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==} @@ -1253,6 +1336,15 @@ packages: resolution: {integrity: sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==} hasBin: true + jsdom@26.1.0: + resolution: {integrity: sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==} + engines: {node: '>=18'} + peerDependencies: + canvas: ^3.0.0 + peerDependenciesMeta: + canvas: + optional: true + jsonc-parser@3.3.1: resolution: {integrity: sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==} @@ -1329,6 +1421,9 @@ packages: loupe@3.2.1: resolution: {integrity: sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==} + lru-cache@10.4.3: + resolution: {integrity: sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==} + lru-cache@11.5.3: resolution: {integrity: sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==} engines: {node: 20 || >=22} @@ -1419,6 +1514,9 @@ packages: nth-check@2.1.1: resolution: {integrity: sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==} + nwsapi@2.2.28: + resolution: {integrity: sha512-IlVB7OS7qrOsVYlpnFIkETjMwT9jwvmocJmmM+GZU/PAB3uGi9Ezd7vcWhWBUnSc0ya4ppmQITOyP1ez9gg8cg==} + obug@3.0.0: resolution: {integrity: sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==} engines: {node: '>=12.20.0'} @@ -1450,6 +1548,9 @@ packages: package-manager-detector@1.8.0: resolution: {integrity: sha512-yQA4H19AmPEoMUeavPMDIe1higySl/gH/yaQrkT/s07Qp+7pp2hYz30N3z2l5BkjVkF9Ow6o0wjJamm2y7Sn0A==} + parse5@7.3.0: + resolution: {integrity: sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==} + pathe@2.0.3: resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} @@ -1490,6 +1591,10 @@ packages: property-information@7.2.0: resolution: {integrity: sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg==} + punycode@2.3.1: + resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} + engines: {node: '>=6'} + radix3@1.1.2: resolution: {integrity: sha512-b484I/7b8rDEdSDKckSSBA8knMpcdsXudlE/LNL639wFoHKwLbEkQFZHWEYwDC0wa0FKUcCY+GAF73Z7wxNVFA==} @@ -1538,6 +1643,12 @@ packages: engines: {node: '>=18.0.0', npm: '>=8.0.0'} hasBin: true + rrweb-cssom@0.8.0: + resolution: {integrity: sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==} + + safer-buffer@2.1.2: + resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} + satteri@0.10.5: resolution: {integrity: sha512-Ao1LKpAEa9Wdg0otgbVKViZHEq9ebdXe4DMrp3s9vQAU0HNIuHnFEuMuOcm0ZIXyV0Yzxj91NvhLpvXZJO/5ZQ==} @@ -1545,6 +1656,10 @@ packages: resolution: {integrity: sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==} engines: {node: '>=11.0.0'} + saxes@6.0.0: + resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==} + engines: {node: '>=v12.22.7'} + scheduler@0.28.0: resolution: {integrity: sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==} @@ -1613,6 +1728,9 @@ packages: engines: {node: '>=16'} hasBin: true + symbol-tree@3.2.4: + resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==} + tiny-inflate@1.0.3: resolution: {integrity: sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==} @@ -1646,6 +1764,21 @@ packages: resolution: {integrity: sha512-u8KszXvGfU68hVcZpRHKG28T0krMuv2G5nDhiHaMLen/gIuFEgIJhaJuO69qjnXg5paSrbPMFfx3brNuN8eVSg==} engines: {node: '>=14.0.0'} + tldts-core@6.1.86: + resolution: {integrity: sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==} + + tldts@6.1.86: + resolution: {integrity: sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==} + hasBin: true + + tough-cookie@5.1.2: + resolution: {integrity: sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==} + engines: {node: '>=16'} + + tr46@5.1.1: + resolution: {integrity: sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==} + engines: {node: '>=18'} + trim-lines@3.0.1: resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==} @@ -1897,11 +2030,51 @@ packages: jsdom: optional: true + w3c-xmlserializer@5.0.0: + resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==} + engines: {node: '>=18'} + + webidl-conversions@7.0.0: + resolution: {integrity: sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==} + engines: {node: '>=12'} + + whatwg-encoding@3.1.1: + resolution: {integrity: sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==} + engines: {node: '>=18'} + deprecated: Use @exodus/bytes instead for a more spec-conformant and faster implementation + + whatwg-mimetype@4.0.0: + resolution: {integrity: sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==} + engines: {node: '>=18'} + + whatwg-url@14.2.0: + resolution: {integrity: sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==} + engines: {node: '>=18'} + why-is-node-running@2.3.0: resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} engines: {node: '>=8'} hasBin: true + ws@8.22.0: + resolution: {integrity: sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==} + engines: {node: '>=10.0.0'} + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: '>=5.0.2' + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + + xml-name-validator@5.0.0: + resolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==} + engines: {node: '>=18'} + + xmlchars@2.2.0: + resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==} + xxhash-wasm@1.1.0: resolution: {integrity: sha512-147y/6YNh+tlp6nd/2pWq38i9h6mz/EuQ6njIrmW8D1BS5nCqs0P6DG+m6zTGnNz5I+uhZ0SHxBs9BsPrwcKDA==} @@ -1921,6 +2094,14 @@ packages: snapshots: + '@asamuzakjp/css-color@3.2.0': + dependencies: + '@csstools/css-calc': 2.1.4(@csstools/css-parser-algorithms@3.0.5(@csstools/css-tokenizer@3.0.4))(@csstools/css-tokenizer@3.0.4) + '@csstools/css-color-parser': 3.1.0(@csstools/css-parser-algorithms@3.0.5(@csstools/css-tokenizer@3.0.4))(@csstools/css-tokenizer@3.0.4) + '@csstools/css-parser-algorithms': 3.0.5(@csstools/css-tokenizer@3.0.4) + '@csstools/css-tokenizer': 3.0.4 + lru-cache: 10.4.3 + '@astrojs/compiler-binding-android-arm64@0.5.1': optional: true @@ -2096,6 +2277,26 @@ snapshots: fast-wrap-ansi: 0.2.2 sisteransi: 1.0.5 + '@csstools/color-helpers@5.1.0': {} + + '@csstools/css-calc@2.1.4(@csstools/css-parser-algorithms@3.0.5(@csstools/css-tokenizer@3.0.4))(@csstools/css-tokenizer@3.0.4)': + dependencies: + '@csstools/css-parser-algorithms': 3.0.5(@csstools/css-tokenizer@3.0.4) + '@csstools/css-tokenizer': 3.0.4 + + '@csstools/css-color-parser@3.1.0(@csstools/css-parser-algorithms@3.0.5(@csstools/css-tokenizer@3.0.4))(@csstools/css-tokenizer@3.0.4)': + dependencies: + '@csstools/color-helpers': 5.1.0 + '@csstools/css-calc': 2.1.4(@csstools/css-parser-algorithms@3.0.5(@csstools/css-tokenizer@3.0.4))(@csstools/css-tokenizer@3.0.4) + '@csstools/css-parser-algorithms': 3.0.5(@csstools/css-tokenizer@3.0.4) + '@csstools/css-tokenizer': 3.0.4 + + '@csstools/css-parser-algorithms@3.0.5(@csstools/css-tokenizer@3.0.4)': + dependencies: + '@csstools/css-tokenizer': 3.0.4 + + '@csstools/css-tokenizer@3.0.4': {} + '@emnapi/core@1.11.1': dependencies: '@emnapi/wasi-threads': 1.2.2 @@ -2562,6 +2763,10 @@ snapshots: dependencies: undici-types: 6.21.0 + '@types/react-dom@19.3.0(@types/react@19.3.0)': + dependencies: + '@types/react': 19.3.0 + '@types/react@19.3.0': dependencies: csstype: 3.2.3 @@ -2612,6 +2817,8 @@ snapshots: loupe: 3.2.1 tinyrainbow: 2.0.0 + agent-base@7.1.4: {} + am-i-vibing@0.4.0: dependencies: process-ancestry: 0.1.0 @@ -2792,12 +2999,24 @@ snapshots: dependencies: css-tree: 2.2.1 + cssstyle@4.6.0: + dependencies: + '@asamuzakjp/css-color': 3.2.0 + rrweb-cssom: 0.8.0 + csstype@3.2.3: {} + data-urls@5.0.0: + dependencies: + whatwg-mimetype: 4.0.0 + whatwg-url: 14.2.0 + debug@4.4.3: dependencies: ms: 2.1.3 + decimal.js@10.6.0: {} + deep-eql@5.0.2: {} defu@6.1.7: {} @@ -2838,6 +3057,8 @@ snapshots: entities@4.5.0: {} + entities@6.0.1: {} + es-module-lexer@1.7.0: {} es-module-lexer@2.3.2: {} @@ -2950,24 +3171,75 @@ snapshots: dependencies: '@types/hast': 3.0.5 + html-encoding-sniffer@4.0.0: + dependencies: + whatwg-encoding: 3.1.1 + html-escaper@3.0.3: {} html-void-elements@3.0.0: {} http-cache-semantics@4.2.0: {} + http-proxy-agent@7.0.2: + dependencies: + agent-base: 7.1.4 + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + https-proxy-agent@7.0.6: + dependencies: + agent-base: 7.1.4 + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + iconv-lite@0.6.3: + dependencies: + safer-buffer: 2.1.2 + iron-webcrypto@1.2.1: {} is-docker@4.0.0: {} is-plain-obj@4.1.0: {} + is-potential-custom-element-name@1.0.1: {} + js-tokens@9.0.1: {} js-yaml@4.3.2: dependencies: argparse: 2.0.1 + jsdom@26.1.0: + dependencies: + cssstyle: 4.6.0 + data-urls: 5.0.0 + decimal.js: 10.6.0 + html-encoding-sniffer: 4.0.0 + http-proxy-agent: 7.0.2 + https-proxy-agent: 7.0.6 + is-potential-custom-element-name: 1.0.1 + nwsapi: 2.2.28 + parse5: 7.3.0 + rrweb-cssom: 0.8.0 + saxes: 6.0.0 + symbol-tree: 3.2.4 + tough-cookie: 5.1.2 + w3c-xmlserializer: 5.0.0 + webidl-conversions: 7.0.0 + whatwg-encoding: 3.1.1 + whatwg-mimetype: 4.0.0 + whatwg-url: 14.2.0 + ws: 8.22.0 + xml-name-validator: 5.0.0 + transitivePeerDependencies: + - bufferutil + - supports-color + - utf-8-validate + jsonc-parser@3.3.1: {} lightningcss-android-arm64@1.33.0: @@ -3021,6 +3293,8 @@ snapshots: loupe@3.2.1: {} + lru-cache@10.4.3: {} + lru-cache@11.5.3: {} magic-string@0.30.21: @@ -3117,6 +3391,8 @@ snapshots: dependencies: boolbase: 1.0.0 + nwsapi@2.2.28: {} + obug@3.0.0: {} ofetch@1.5.1: @@ -3148,6 +3424,10 @@ snapshots: package-manager-detector@1.8.0: {} + parse5@7.3.0: + dependencies: + entities: 6.0.1 + pathe@2.0.3: {} pathval@2.0.1: {} @@ -3178,6 +3458,8 @@ snapshots: property-information@7.2.0: {} + punycode@2.3.1: {} + radix3@1.1.2: {} react-dom@19.3.0(react@19.3.0): @@ -3271,6 +3553,10 @@ snapshots: '@rollup/rollup-win32-x64-msvc': 4.63.3 fsevents: 2.3.3 + rrweb-cssom@0.8.0: {} + + safer-buffer@2.1.2: {} + satteri@0.10.5: dependencies: '@types/estree-jsx': 1.0.5 @@ -3290,6 +3576,10 @@ snapshots: sax@1.6.1: {} + saxes@6.0.0: + dependencies: + xmlchars: 2.2.0 + scheduler@0.28.0: {} semver@7.8.5: @@ -3378,6 +3668,8 @@ snapshots: picocolors: 1.1.1 sax: 1.6.1 + symbol-tree@3.2.4: {} + tiny-inflate@1.0.3: {} tinybench@2.9.0: {} @@ -3399,6 +3691,20 @@ snapshots: tinyspy@4.0.6: {} + tldts-core@6.1.86: {} + + tldts@6.1.86: + dependencies: + tldts-core: 6.1.86 + + tough-cookie@5.1.2: + dependencies: + tldts: 6.1.86 + + tr46@5.1.1: + dependencies: + punycode: 2.3.1 + trim-lines@3.0.1: {} trough@2.2.0: {} @@ -3534,7 +3840,7 @@ snapshots: optionalDependencies: vite: 8.3.1(@types/node@22.15.3)(esbuild@0.28.2) - vitest@3.2.7(@types/node@22.15.3)(lightningcss@1.33.0): + vitest@3.2.7(@types/node@22.15.3)(jsdom@26.1.0)(lightningcss@1.33.0): dependencies: '@types/chai': 5.2.3 '@vitest/expect': 3.2.7 @@ -3561,6 +3867,7 @@ snapshots: why-is-node-running: 2.3.0 optionalDependencies: '@types/node': 22.15.3 + jsdom: 26.1.0 transitivePeerDependencies: - jiti - less @@ -3575,11 +3882,34 @@ snapshots: - tsx - yaml + w3c-xmlserializer@5.0.0: + dependencies: + xml-name-validator: 5.0.0 + + webidl-conversions@7.0.0: {} + + whatwg-encoding@3.1.1: + dependencies: + iconv-lite: 0.6.3 + + whatwg-mimetype@4.0.0: {} + + whatwg-url@14.2.0: + dependencies: + tr46: 5.1.1 + webidl-conversions: 7.0.0 + why-is-node-running@2.3.0: dependencies: siginfo: 2.0.0 stackback: 0.0.2 + ws@8.22.0: {} + + xml-name-validator@5.0.0: {} + + xmlchars@2.2.0: {} + xxhash-wasm@1.1.0: {} yargs-parser@22.0.0: {} diff --git a/src/react.test.ts b/src/react.test.ts new file mode 100644 index 0000000..1b0c1de --- /dev/null +++ b/src/react.test.ts @@ -0,0 +1,153 @@ +// @vitest-environment jsdom + +import { act, createElement } from "react"; +import { createRoot } from "react-dom/client"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { LocaleConfig } from "./locale/core"; +import { LocaleProvider, useLocaleSwitch } from "./react"; + +type Persist = (locale: string) => void | Promise; + +// React 19 reads this to decide whether `act` is expected. +( + globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean } +).IS_REACT_ACT_ENVIRONMENT = true; + +const config: LocaleConfig = { + locales: ["en", "ja", "es"], + defaultLocale: "en", + localizedPaths: ["/", "/pricing"], + localizedPathPrefixes: ["/blog/"], +}; + +// The provider hands `switchTo` out through context; this child records it so +// tests can call it directly. +let switchTo: ((locale: string) => void) | null = null; + +function CaptureSwitch() { + switchTo = useLocaleSwitch(); + return null; +} + +interface Mounted { + container: HTMLDivElement; + navigate: ReturnType; + rerender: (props: { locale: string; persist?: Persist }) => void; + unmount: () => void; +} + +const mounted: Mounted[] = []; + +function mount(locale: string, persist?: Persist): Mounted { + const container = document.createElement("div"); + document.body.appendChild(container); + const root = createRoot(container); + const navigate = vi.fn(); + + const render = (props: { locale: string; persist?: Persist }) => { + act(() => + root.render( + createElement(LocaleProvider, { + config, + locale: props.locale, + navigate, + persist: props.persist, + // biome-ignore lint/correctness/noChildrenProp: React 19's overloads require `children` in props here. + children: createElement(CaptureSwitch), + }), + ), + ); + }; + + render({ locale, persist }); + const entry: Mounted = { + container, + navigate, + rerender: (props) => render(props), + unmount: () => { + act(() => root.unmount()); + container.remove(); + }, + }; + mounted.push(entry); + return entry; +} + +function setPathname(pathname: string) { + window.history.pushState({}, "", pathname); +} + +function cookieValue(): string { + return document.cookie; +} + +beforeEach(() => { + // biome-ignore lint/suspicious/noDocumentCookie: clearing state between tests; document.cookie is the portable choice. + document.cookie = "locale=; Max-Age=0; Path=/"; + setPathname("/pricing"); + switchTo = null; +}); + +afterEach(() => { + while (mounted.length > 0) mounted.pop()?.unmount(); +}); + +describe("LocaleProvider switchTo", () => { + it("writes the cookie and navigates to the localized URL", () => { + const m = mount("en"); + act(() => switchTo?.("ja")); + + expect(cookieValue()).toContain("locale=ja"); + expect(m.navigate).toHaveBeenCalledWith("/ja/pricing"); + }); + + it("does not navigate when the path has no localized variant", () => { + setPathname("/legal"); + const m = mount("en"); + act(() => switchTo?.("ja")); + expect(m.navigate).not.toHaveBeenCalled(); + }); + + it("does not navigate when the target is the current locale", () => { + const m = mount("en"); + act(() => switchTo?.("en")); + expect(m.navigate).not.toHaveBeenCalled(); + }); + + it("still navigates when persist throws synchronously", () => { + const m = mount("en", () => { + throw new Error("boom"); + }); + act(() => switchTo?.("ja")); + expect(m.navigate).toHaveBeenCalledWith("/ja/pricing"); + }); + + it("still navigates and reports no unhandled rejection when persist rejects", async () => { + const onUnhandled = vi.fn(); + window.addEventListener("unhandledrejection", onUnhandled); + + const m = mount("en", () => Promise.reject(new Error("save failed"))); + act(() => switchTo?.("ja")); + + expect(m.navigate).toHaveBeenCalledWith("/ja/pricing"); + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 0)); + }); + expect(onUnhandled).not.toHaveBeenCalled(); + + window.removeEventListener("unhandledrejection", onUnhandled); + }); + + it("resets pending when the locale changes, so a second switch works", () => { + const m = mount("en"); + act(() => switchTo?.("ja")); + expect(m.navigate).toHaveBeenCalledWith("/ja/pricing"); + + // Simulate the router landing on the new locale without remounting. + m.rerender({ locale: "ja" }); + + act(() => switchTo?.("es")); + expect(m.navigate).toHaveBeenCalledWith("/es/pricing"); + expect(m.navigate).toHaveBeenCalledTimes(2); + }); +}); diff --git a/src/react.tsx b/src/react.tsx index 9ee59b1..d569e91 100644 --- a/src/react.tsx +++ b/src/react.tsx @@ -45,7 +45,11 @@ export interface LocaleProviderProps { navigate?: (href: string) => void; /** * Persist the choice server-side (the cookie is already written). Use for - * signed-in users, e.g. a server action that stores the locale. + * signed-in users. Because `switchTo` navigates immediately and does NOT + * wait for this to settle, `persist` must survive the page unloading: send + * the locale with `fetch(url, { keepalive: true })` or `navigator.sendBeacon`. + * Do not pass a server action — it is aborted when the page navigates, and a + * rejected save would otherwise surface as an unhandled rejection. */ persist?: (locale: string) => void | Promise; children: ReactNode; @@ -73,7 +77,14 @@ export function LocaleProvider({ persist, children, }: LocaleProviderProps) { - const [pending, setPending] = useState(false); + const [pendingLocale, setPendingLocale] = useState(null); + const pending = pendingLocale !== null; + // Keyed to the target locale so it clears the moment the new locale lands: a + // router-based `navigate` rerenders the provider with the new `locale`, while + // the default `location.assign` unloads the page first and never needs it. + if (pendingLocale !== null && pendingLocale === locale) { + setPendingLocale(null); + } const switchTo = useCallback( (next: string) => { @@ -82,12 +93,15 @@ export function LocaleProvider({ typeof window === "undefined" ? "/" : window.location.pathname; const plan = planSwitch(config, pathname, next); if (!plan) return; // current path has no localized variant - setPending(true); + setPendingLocale(next); writeCookie(plan.cookie.name, plan.cookie.value, plan.cookie.options); - try { - void persist?.(next); - } catch { - /* persistence is best-effort */ + // Best-effort and never awaited: catches a synchronous throw AND a + // rejected promise, so a failed save can't surface as an unhandled + // rejection. Navigation must not wait on it (see the `persist` docs). + if (persist) { + Promise.resolve() + .then(() => persist(next)) + .catch(() => {}); } (navigate ?? defaultNavigate)(plan.href); }, @@ -131,7 +145,7 @@ export function useLocales(): readonly string[] { return useLocaleContext().config.locales; } -/** `[locale, switchTo]` — the switcher primitive. */ +/** The switcher primitive: `switchTo(locale)` writes the cookie and navigates. */ export function useLocaleSwitch(): (locale: string) => void { return useLocaleContext().switchTo; }