|
| 1 | +import { useEffect, useState } from 'preact/hooks'; |
| 2 | + |
| 3 | +import { defaultLocale } from '../site.json' with { type: 'json' }; |
| 4 | + |
| 5 | +const LOCALE_COOKIE = 'NEXT_LOCALE'; |
| 6 | + |
| 7 | +/** |
| 8 | + * Retrieves the locale from the NEXT_LOCALE cookie. |
| 9 | + * |
| 10 | + * @returns {string|null} The locale from the NEXT_LOCALE cookie, or null if not found. |
| 11 | + */ |
| 12 | +const getNextLocaleFromCookie = () => { |
| 13 | + if (typeof document === 'undefined') { |
| 14 | + return null; |
| 15 | + } |
| 16 | + |
| 17 | + const localeCookie = document.cookie |
| 18 | + .split(';') |
| 19 | + .map((cookie) => cookie.trim()) |
| 20 | + .find((cookie) => cookie.startsWith(`${LOCALE_COOKIE}=`)); |
| 21 | + |
| 22 | + if (!localeCookie) { |
| 23 | + return null; |
| 24 | + } |
| 25 | + |
| 26 | + return decodeURIComponent(localeCookie.slice(LOCALE_COOKIE.length + 1)); |
| 27 | +}; |
| 28 | + |
| 29 | +/** |
| 30 | + * Replaces the default locale in a link with the provided locale. |
| 31 | + * |
| 32 | + * @param {string} link - The link to be localized. |
| 33 | + * @param {string|null} nextLocale - The locale to apply to the link. |
| 34 | + * @returns {string} - The localized link. |
| 35 | + */ |
| 36 | +const replaceLocaleInLink = (link, nextLocale) => { |
| 37 | + if (!link.startsWith('/') || !link.startsWith(`/${defaultLocale}`)) { |
| 38 | + return link; |
| 39 | + } |
| 40 | + |
| 41 | + const localizedPrefix = nextLocale ? `/${nextLocale}` : ''; |
| 42 | + |
| 43 | + if (link === `/${defaultLocale}`) { |
| 44 | + return localizedPrefix || '/'; |
| 45 | + } |
| 46 | + |
| 47 | + return link.replace(`/${defaultLocale}/`, `${localizedPrefix}/`); |
| 48 | +}; |
| 49 | + |
| 50 | +/** |
| 51 | + * Localizes a given link based on the provided locale. |
| 52 | + * |
| 53 | + * @param {string} link - The link to be localized. |
| 54 | + * @param {string|null} nextLocale - The locale to apply to the link. |
| 55 | + * @returns {string} - The localized link. |
| 56 | + */ |
| 57 | +const localizeLink = (link, nextLocale) => { |
| 58 | + if (nextLocale === null) { |
| 59 | + return link; |
| 60 | + } |
| 61 | + |
| 62 | + return replaceLocaleInLink(link, nextLocale); |
| 63 | +}; |
| 64 | + |
| 65 | +/** |
| 66 | + * Custom hook to get a function that localizes links based on the NEXT_LOCALE cookie. |
| 67 | + * @returns {function(string): string} A function that takes a link and returns the localized version of that link. |
| 68 | + */ |
| 69 | +const useLocalizedLink = () => { |
| 70 | + const [nextLocale, setNextLocale] = useState(null); |
| 71 | + |
| 72 | + useEffect(() => { |
| 73 | + setNextLocale(getNextLocaleFromCookie()); |
| 74 | + }, []); |
| 75 | + |
| 76 | + return (link) => localizeLink(link, nextLocale); |
| 77 | +}; |
| 78 | + |
| 79 | +export default useLocalizedLink; |
0 commit comments