|
| 1 | +import { useRouter } from "next/router"; |
| 2 | + |
| 3 | +/** |
| 4 | + * @typedef {"ja"} DefaultLocale |
| 5 | + * @typedef {DefaultLocale | "en-US"} Locale |
| 6 | + * @typedef {{locale?: Locale | undefined; locales?: Locale[] | undefined; defaultLocale?: DefaultLocale | undefined}} TypedRouter |
| 7 | + * @typedef {Omit<import('next/router').NextRouter, "locale" | "locales" | "defaultLocale"> & TypedRouter} NextRouter |
| 8 | + * @template T |
| 9 | + * @type {(localesMap: Record<Locale, T>) => T} |
| 10 | + */ |
| 11 | +export default function useLocalesMap(localesMap) { |
| 12 | + /** @type {NextRouter} */ |
| 13 | + const router = useRouter(); |
| 14 | + const { locale, defaultLocale } = router; |
| 15 | + if (!localesMap) { |
| 16 | + throw new Error("Pass a locales map as argument to useLocalesMap"); |
| 17 | + } |
| 18 | + |
| 19 | + if (!isObject(localesMap)) { |
| 20 | + throw new Error("Locales map must be an object"); |
| 21 | + } |
| 22 | + |
| 23 | + if (!localesMap.hasOwnProperty(defaultLocale)) { |
| 24 | + throw new Error( |
| 25 | + `Locales map must contain default locale "${defaultLocale}"` |
| 26 | + ); |
| 27 | + } |
| 28 | + |
| 29 | + if ( |
| 30 | + localesMap.hasOwnProperty(locale) && |
| 31 | + typeof localesMap[locale] !== typeof localesMap[defaultLocale] |
| 32 | + ) { |
| 33 | + throw new Error( |
| 34 | + `Invalid locales map: Shape of "${locale}" must be the same as "${defaultLocale}"` |
| 35 | + ); |
| 36 | + } |
| 37 | + |
| 38 | + if ( |
| 39 | + ["string", "number", "symbol"].includes(typeof localesMap[defaultLocale]) |
| 40 | + ) { |
| 41 | + return localesMap[locale] || localesMap[defaultLocale]; |
| 42 | + } |
| 43 | + |
| 44 | + const target = JSON.parse(JSON.stringify(localesMap[defaultLocale])); |
| 45 | + return mergeDeep(target, localesMap[locale]); |
| 46 | +} |
| 47 | + |
| 48 | +/** |
| 49 | + * Simple object check. |
| 50 | + * @param {any} item |
| 51 | + * @returns {boolean} |
| 52 | + */ |
| 53 | +function isObject(item) { |
| 54 | + return item && typeof item === "object" && !Array.isArray(item); |
| 55 | +} |
| 56 | + |
| 57 | +/** |
| 58 | + * Deep merge two objects. |
| 59 | + * @template T |
| 60 | + * @param {Record<string, T>} target |
| 61 | + * @param {Record<string, T>} sources |
| 62 | + * @returns {Record<string, T>} |
| 63 | + */ |
| 64 | +function mergeDeep(target, ...sources) { |
| 65 | + if (!sources.length) return target; |
| 66 | + const source = sources.shift(); |
| 67 | + |
| 68 | + if (isObject(target) && isObject(source)) { |
| 69 | + for (const key in source) { |
| 70 | + if (isObject(source[key])) { |
| 71 | + if (!target[key]) Object.assign(target, { [key]: {} }); |
| 72 | + mergeDeep(target[key], source[key]); |
| 73 | + } else { |
| 74 | + Object.assign(target, { [key]: source[key] }); |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + return mergeDeep(target, ...sources); |
| 80 | +} |
0 commit comments