UNPKG

next-intlayer

Version:

Simplify internationalization i18n in Next.js with context providers, hooks, locale detection, and multilingual content integration.

1 lines 2.53 kB
{"version":3,"file":"useLocale.mjs","names":["useLocaleReact"],"sources":["../../../src/client/useLocale.ts"],"sourcesContent":["'use client';\n\nimport { getLocalizedUrl, getPathWithoutLocale } from '@intlayer/core';\nimport type { LocalesValues } from '@intlayer/types';\nimport { usePathname, useRouter } from 'next/navigation.js';\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport { useLocale as useLocaleReact } from 'react-intlayer';\n\ntype UseLocaleProps = {\n onChange?: 'replace' | 'push' | ((locale: LocalesValues) => void);\n};\n\nconst usePathWithoutLocale = () => {\n const pathname = usePathname(); // updates on client navigations\n const [fullPath, setFullPath] = useState(pathname);\n\n useEffect(() => {\n // Runs only on client; avoids suspense.\n const search = typeof window !== 'undefined' ? window.location.search : '';\n setFullPath(search ? `${pathname}${search}` : pathname);\n }, [pathname]);\n\n // Your own helper\n return useMemo(() => getPathWithoutLocale(fullPath), [fullPath]);\n};\n\nexport const useLocale = ({ onChange }: UseLocaleProps = {}) => {\n const { replace, push } = useRouter();\n const pathWithoutLocale = usePathWithoutLocale();\n\n const redirectionFunction = useCallback(\n (locale: LocalesValues) => {\n if (!onChange) return;\n\n if (typeof onChange === 'function') {\n onChange(locale);\n return;\n }\n\n const pathWithLocale = getLocalizedUrl(pathWithoutLocale, locale);\n\n if (onChange === 'replace') {\n replace(pathWithLocale);\n }\n if (onChange === 'push') {\n push(pathWithLocale);\n }\n },\n [replace, push, pathWithoutLocale, onChange]\n );\n\n const reactLocaleHook = useLocaleReact({\n onLocaleChange: redirectionFunction,\n });\n\n return {\n ...reactLocaleHook,\n pathWithoutLocale,\n };\n};\n"],"mappings":";;;;;;;;;AAYA,MAAM,6BAA6B;CACjC,MAAM,WAAW,aAAa;CAC9B,MAAM,CAAC,UAAU,eAAe,SAAS,SAAS;AAElD,iBAAgB;EAEd,MAAM,SAAS,OAAO,WAAW,cAAc,OAAO,SAAS,SAAS;AACxE,cAAY,SAAS,GAAG,WAAW,WAAW,SAAS;IACtD,CAAC,SAAS,CAAC;AAGd,QAAO,cAAc,qBAAqB,SAAS,EAAE,CAAC,SAAS,CAAC;;AAGlE,MAAa,aAAa,EAAE,aAA6B,EAAE,KAAK;CAC9D,MAAM,EAAE,SAAS,SAAS,WAAW;CACrC,MAAM,oBAAoB,sBAAsB;AA2BhD,QAAO;EACL,GALsBA,YAAe,EACrC,gBAtB0B,aACzB,WAA0B;AACzB,OAAI,CAAC,SAAU;AAEf,OAAI,OAAO,aAAa,YAAY;AAClC,aAAS,OAAO;AAChB;;GAGF,MAAM,iBAAiB,gBAAgB,mBAAmB,OAAO;AAEjE,OAAI,aAAa,UACf,SAAQ,eAAe;AAEzB,OAAI,aAAa,OACf,MAAK,eAAe;KAGxB;GAAC;GAAS;GAAM;GAAmB;GAAS,CAC7C,EAIA,CAAC;EAIA;EACD"}