From d041fd4bc67a9c690943293499ada7cec871a62f Mon Sep 17 00:00:00 2001 From: rasm-its Date: Fri, 9 Oct 2026 17:01:52 +0200 Subject: [PATCH] Added languageswitcher, alternatelinkscontext components support --- dist/exports/client.d.ts | 2 + dist/exports/client.js | 1 + dist/exports/client.js.map | 2 +- dist/exports/next-middleware.d.ts | 1 + dist/exports/next-middleware.js | 1 + dist/exports/next-middleware.js.map | 2 +- dist/modules/i18n/AlternateLinksContext.d.ts | 22 +++++ dist/modules/i18n/AlternateLinksContext.js | 37 ++++++++ .../modules/i18n/AlternateLinksContext.js.map | 1 + dist/modules/i18n/AlternateLinksUpdater.d.ts | 19 ++++ dist/modules/i18n/AlternateLinksUpdater.js | 32 +++++++ .../modules/i18n/AlternateLinksUpdater.js.map | 1 + dist/modules/i18n/LanguageSwitcher.d.ts | 36 +++++++ dist/modules/i18n/LanguageSwitcher.js | 65 +++++++++++++ dist/modules/i18n/LanguageSwitcher.js.map | 1 + dist/modules/i18n/index.d.ts | 5 + dist/modules/i18n/index.js | 3 + dist/modules/i18n/index.js.map | 2 +- docs/i18n.md | 62 +++++++++++- src/exports/client.ts | 10 +- src/exports/next-middleware.ts | 1 + src/modules/i18n/AlternateLinksContext.tsx | 48 ++++++++++ src/modules/i18n/AlternateLinksUpdater.tsx | 31 ++++++ src/modules/i18n/LanguageSwitcher.tsx | 94 +++++++++++++++++++ src/modules/i18n/index.ts | 9 ++ 25 files changed, 483 insertions(+), 5 deletions(-) create mode 100644 dist/modules/i18n/AlternateLinksContext.d.ts create mode 100644 dist/modules/i18n/AlternateLinksContext.js create mode 100644 dist/modules/i18n/AlternateLinksContext.js.map create mode 100644 dist/modules/i18n/AlternateLinksUpdater.d.ts create mode 100644 dist/modules/i18n/AlternateLinksUpdater.js create mode 100644 dist/modules/i18n/AlternateLinksUpdater.js.map create mode 100644 dist/modules/i18n/LanguageSwitcher.d.ts create mode 100644 dist/modules/i18n/LanguageSwitcher.js create mode 100644 dist/modules/i18n/LanguageSwitcher.js.map create mode 100644 src/modules/i18n/AlternateLinksContext.tsx create mode 100644 src/modules/i18n/AlternateLinksUpdater.tsx create mode 100644 src/modules/i18n/LanguageSwitcher.tsx diff --git a/dist/exports/client.d.ts b/dist/exports/client.d.ts index a9acbac..a1f9e3f 100644 --- a/dist/exports/client.d.ts +++ b/dist/exports/client.d.ts @@ -14,6 +14,8 @@ export { ConsentProvider, CookieBanner, CookieButton, useConsent, useConsentCont export type { CookieBannerClassNames } from '../modules/consent/client.js'; export { buildLocalizedPath, getLocaleCodes, getLocalizedSlugs, switchLocalePath, } from '../modules/i18n/index.js'; export type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js'; +export { AlternateLinksProvider, AlternateLinksUpdater, LanguageSwitcher, useAlternateLinks, useSetAlternateLinks, } from '../modules/i18n/index.js'; +export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'; export { Turnstile } from '../modules/turnstile/client.js'; export { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'; export type { TurnstileProps } from '../modules/turnstile/client.js'; diff --git a/dist/exports/client.js b/dist/exports/client.js index b8cdf4c..9b515d4 100644 --- a/dist/exports/client.js +++ b/dist/exports/client.js @@ -13,6 +13,7 @@ export { Analytics } from '../modules/analytics/client.js'; // Pure i18n path helpers — no server/RSC deps, safe to import in client // components (e.g. a LanguageSwitcher that computes locale URLs on the client). export { buildLocalizedPath, getLocaleCodes, getLocalizedSlugs, switchLocalePath } from '../modules/i18n/index.js'; +export { AlternateLinksProvider, AlternateLinksUpdater, LanguageSwitcher, useAlternateLinks, useSetAlternateLinks } from '../modules/i18n/index.js'; export { Turnstile } from '../modules/turnstile/client.js'; export { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'; diff --git a/dist/exports/client.js.map b/dist/exports/client.js.map index 359461c..a579617 100644 --- a/dist/exports/client.js.map +++ b/dist/exports/client.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["'use client'\nexport { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'\nexport { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'\nexport {\n AccessibilityProvider,\n AccessibilityWidget,\n useAccessibility,\n} from '../modules/accessibility/client.js'\nexport type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'\n\nexport { Analytics } from '../modules/analytics/client.js'\n/**\n * Entry point: ipal-kit/client\n *\n * Client-side ('use client') exports — React hooks, providers, and UI\n * components. Kept separate from the main entry so server bundles don't pull in\n * client-only code.\n */\nexport {\n ConsentProvider,\n CookieBanner,\n CookieButton,\n useConsent,\n useConsentContext,\n} from '../modules/consent/client.js'\nexport type { CookieBannerClassNames } from '../modules/consent/client.js'\n// Pure i18n path helpers — no server/RSC deps, safe to import in client\n// components (e.g. a LanguageSwitcher that computes locale URLs on the client).\nexport {\n buildLocalizedPath,\n getLocaleCodes,\n getLocalizedSlugs,\n switchLocalePath,\n} from '../modules/i18n/index.js'\nexport type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js'\nexport { Turnstile } from '../modules/turnstile/client.js'\nexport { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'\nexport type { TurnstileProps } from '../modules/turnstile/client.js'\n"],"names":["MaskedField","TestEmailButton","AccessibilityProvider","AccessibilityWidget","useAccessibility","Analytics","ConsentProvider","CookieBanner","CookieButton","useConsent","useConsentContext","buildLocalizedPath","getLocaleCodes","getLocalizedSlugs","switchLocalePath","Turnstile","TurnstileProvider","useTurnstile"],"mappings":"AAAA;AACA,SAASA,WAAW,QAAQ,wDAAuD;AACnF,SAASC,eAAe,QAAQ,4DAA2D;AAC3F,SACEC,qBAAqB,EACrBC,mBAAmB,EACnBC,gBAAgB,QACX,qCAAoC;AAG3C,SAASC,SAAS,QAAQ,iCAAgC;AAC1D;;;;;;CAMC,GACD,SACEC,eAAe,EACfC,YAAY,EACZC,YAAY,EACZC,UAAU,EACVC,iBAAiB,QACZ,+BAA8B;AAErC,wEAAwE;AACxE,gFAAgF;AAChF,SACEC,kBAAkB,EAClBC,cAAc,EACdC,iBAAiB,EACjBC,gBAAgB,QACX,2BAA0B;AAEjC,SAASC,SAAS,QAAQ,iCAAgC;AAC1D,SAASC,iBAAiB,EAAEC,YAAY,QAAQ,iCAAgC"} \ No newline at end of file +{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["'use client'\nexport { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'\nexport { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'\nexport {\n AccessibilityProvider,\n AccessibilityWidget,\n useAccessibility,\n} from '../modules/accessibility/client.js'\nexport type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'\nexport { Analytics } from '../modules/analytics/client.js'\n/**\n * Entry point: ipal-kit/client\n *\n * Client-side ('use client') exports — React hooks, providers, and UI\n * components. Kept separate from the main entry so server bundles don't pull in\n * client-only code.\n */\nexport {\n ConsentProvider,\n CookieBanner,\n CookieButton,\n useConsent,\n useConsentContext,\n} from '../modules/consent/client.js'\n\nexport type { CookieBannerClassNames } from '../modules/consent/client.js'\n// Pure i18n path helpers — no server/RSC deps, safe to import in client\n// components (e.g. a LanguageSwitcher that computes locale URLs on the client).\nexport {\n buildLocalizedPath,\n getLocaleCodes,\n getLocalizedSlugs,\n switchLocalePath,\n} from '../modules/i18n/index.js'\nexport type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js'\nexport {\n AlternateLinksProvider,\n AlternateLinksUpdater,\n LanguageSwitcher,\n useAlternateLinks,\n useSetAlternateLinks,\n} from '../modules/i18n/index.js'\nexport type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'\nexport { Turnstile } from '../modules/turnstile/client.js'\nexport { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'\nexport type { TurnstileProps } from '../modules/turnstile/client.js'\n"],"names":["MaskedField","TestEmailButton","AccessibilityProvider","AccessibilityWidget","useAccessibility","Analytics","ConsentProvider","CookieBanner","CookieButton","useConsent","useConsentContext","buildLocalizedPath","getLocaleCodes","getLocalizedSlugs","switchLocalePath","AlternateLinksProvider","AlternateLinksUpdater","LanguageSwitcher","useAlternateLinks","useSetAlternateLinks","Turnstile","TurnstileProvider","useTurnstile"],"mappings":"AAAA;AACA,SAASA,WAAW,QAAQ,wDAAuD;AACnF,SAASC,eAAe,QAAQ,4DAA2D;AAC3F,SACEC,qBAAqB,EACrBC,mBAAmB,EACnBC,gBAAgB,QACX,qCAAoC;AAE3C,SAASC,SAAS,QAAQ,iCAAgC;AAC1D;;;;;;CAMC,GACD,SACEC,eAAe,EACfC,YAAY,EACZC,YAAY,EACZC,UAAU,EACVC,iBAAiB,QACZ,+BAA8B;AAGrC,wEAAwE;AACxE,gFAAgF;AAChF,SACEC,kBAAkB,EAClBC,cAAc,EACdC,iBAAiB,EACjBC,gBAAgB,QACX,2BAA0B;AAEjC,SACEC,sBAAsB,EACtBC,qBAAqB,EACrBC,gBAAgB,EAChBC,iBAAiB,EACjBC,oBAAoB,QACf,2BAA0B;AAEjC,SAASC,SAAS,QAAQ,iCAAgC;AAC1D,SAASC,iBAAiB,EAAEC,YAAY,QAAQ,iCAAgC"} \ No newline at end of file diff --git a/dist/exports/next-middleware.d.ts b/dist/exports/next-middleware.d.ts index 4e5702f..a2e8d73 100644 --- a/dist/exports/next-middleware.d.ts +++ b/dist/exports/next-middleware.d.ts @@ -7,3 +7,4 @@ */ export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from '../modules/i18n/index.js'; export type { LocaleMiddlewareResult } from '../modules/i18n/index.js'; +export { createProxy, DEFAULT_PROXY_MATCHER } from '../modules/i18n/index.js'; diff --git a/dist/exports/next-middleware.js b/dist/exports/next-middleware.js index 3ebd34f..00268f7 100644 --- a/dist/exports/next-middleware.js +++ b/dist/exports/next-middleware.js @@ -5,5 +5,6 @@ * client project's middleware.ts. Kept as a thin re-export so the Next-facing * surface is separate from the main package export. */ export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from '../modules/i18n/index.js'; +export { createProxy, DEFAULT_PROXY_MATCHER } from '../modules/i18n/index.js'; //# sourceMappingURL=next-middleware.js.map \ No newline at end of file diff --git a/dist/exports/next-middleware.js.map b/dist/exports/next-middleware.js.map index ad94411..53d10d0 100644 --- a/dist/exports/next-middleware.js.map +++ b/dist/exports/next-middleware.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/exports/next-middleware.ts"],"sourcesContent":["/**\n * Entry point: ipal-kit/next/middleware\n *\n * Re-exports the locale middleware factory and default matcher for use in a\n * client project's middleware.ts. Kept as a thin re-export so the Next-facing\n * surface is separate from the main package export.\n */\nexport { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from '../modules/i18n/index.js'\nexport type { LocaleMiddlewareResult } from '../modules/i18n/index.js'\n"],"names":["createLocaleMiddleware","DEFAULT_MIDDLEWARE_MATCHER"],"mappings":"AAAA;;;;;;CAMC,GACD,SAASA,sBAAsB,EAAEC,0BAA0B,QAAQ,2BAA0B"} \ No newline at end of file +{"version":3,"sources":["../../src/exports/next-middleware.ts"],"sourcesContent":["/**\n * Entry point: ipal-kit/next/middleware\n *\n * Re-exports the locale middleware factory and default matcher for use in a\n * client project's middleware.ts. Kept as a thin re-export so the Next-facing\n * surface is separate from the main package export.\n */\nexport { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from '../modules/i18n/index.js'\nexport type { LocaleMiddlewareResult } from '../modules/i18n/index.js'\nexport { createProxy, DEFAULT_PROXY_MATCHER } from '../modules/i18n/index.js'\n"],"names":["createLocaleMiddleware","DEFAULT_MIDDLEWARE_MATCHER","createProxy","DEFAULT_PROXY_MATCHER"],"mappings":"AAAA;;;;;;CAMC,GACD,SAASA,sBAAsB,EAAEC,0BAA0B,QAAQ,2BAA0B;AAE7F,SAASC,WAAW,EAAEC,qBAAqB,QAAQ,2BAA0B"} \ No newline at end of file diff --git a/dist/modules/i18n/AlternateLinksContext.d.ts b/dist/modules/i18n/AlternateLinksContext.d.ts new file mode 100644 index 0000000..9f64ad0 --- /dev/null +++ b/dist/modules/i18n/AlternateLinksContext.d.ts @@ -0,0 +1,22 @@ +/** Map of locale code → absolute-or-relative URL for the current page. */ +export type AlternateLinks = Record; +/** + * Holds the current page's per-locale URLs so a LanguageSwitcher links to the + * CORRECT localized slug instead of naively swapping the locale prefix + * (/pl/uslugi → /en/uslugi, which 404s when the English slug is /en/services). + * + * Wrap the app once; each page reports its own alternates via + * (or useSetAlternateLinks). The switcher reads them + * with useAlternateLinks(). + * + * // layout.tsx + * import { AlternateLinksProvider } from '@intecion/ipal-kit/client' + * {children} + */ +export declare function AlternateLinksProvider({ children }: { + children: React.ReactNode; +}): import("react/jsx-runtime").JSX.Element; +/** Read the current page's per-locale URLs (for a language switcher). */ +export declare function useAlternateLinks(): AlternateLinks; +/** Setter for the alternates (used by AlternateLinksUpdater). */ +export declare function useSetAlternateLinks(): (links: AlternateLinks) => void; diff --git a/dist/modules/i18n/AlternateLinksContext.js b/dist/modules/i18n/AlternateLinksContext.js new file mode 100644 index 0000000..e648aaa --- /dev/null +++ b/dist/modules/i18n/AlternateLinksContext.js @@ -0,0 +1,37 @@ +'use client'; +import { jsx as _jsx } from "react/jsx-runtime"; +import { createContext, use, useCallback, useState } from 'react'; +const AlternateLinksContext = /*#__PURE__*/ createContext(null); +/** + * Holds the current page's per-locale URLs so a LanguageSwitcher links to the + * CORRECT localized slug instead of naively swapping the locale prefix + * (/pl/uslugi → /en/uslugi, which 404s when the English slug is /en/services). + * + * Wrap the app once; each page reports its own alternates via + * (or useSetAlternateLinks). The switcher reads them + * with useAlternateLinks(). + * + * // layout.tsx + * import { AlternateLinksProvider } from '@intecion/ipal-kit/client' + * {children} + */ export function AlternateLinksProvider({ children }) { + const [links, setLinksState] = useState({}); + const setLinks = useCallback((next)=>setLinksState(next), []); + return /*#__PURE__*/ _jsx(AlternateLinksContext, { + value: { + links, + setLinks + }, + children: children + }); +} +/** Read the current page's per-locale URLs (for a language switcher). */ export function useAlternateLinks() { + const ctx = use(AlternateLinksContext); + return ctx?.links ?? {}; +} +/** Setter for the alternates (used by AlternateLinksUpdater). */ export function useSetAlternateLinks() { + const ctx = use(AlternateLinksContext); + return ctx?.setLinks ?? (()=>{}); +} + +//# sourceMappingURL=AlternateLinksContext.js.map \ No newline at end of file diff --git a/dist/modules/i18n/AlternateLinksContext.js.map b/dist/modules/i18n/AlternateLinksContext.js.map new file mode 100644 index 0000000..4355925 --- /dev/null +++ b/dist/modules/i18n/AlternateLinksContext.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/i18n/AlternateLinksContext.tsx"],"sourcesContent":["'use client'\n\nimport { createContext, use, useCallback, useState } from 'react'\n\n/** Map of locale code → absolute-or-relative URL for the current page. */\nexport type AlternateLinks = Record\n\ntype AlternateLinksContextValue = {\n links: AlternateLinks\n setLinks: (links: AlternateLinks) => void\n}\n\nconst AlternateLinksContext = createContext(null)\n\n/**\n * Holds the current page's per-locale URLs so a LanguageSwitcher links to the\n * CORRECT localized slug instead of naively swapping the locale prefix\n * (/pl/uslugi → /en/uslugi, which 404s when the English slug is /en/services).\n *\n * Wrap the app once; each page reports its own alternates via\n * (or useSetAlternateLinks). The switcher reads them\n * with useAlternateLinks().\n *\n * // layout.tsx\n * import { AlternateLinksProvider } from '@intecion/ipal-kit/client'\n * {children}\n */\nexport function AlternateLinksProvider({ children }: { children: React.ReactNode }) {\n const [links, setLinksState] = useState({})\n const setLinks = useCallback((next: AlternateLinks) => setLinksState(next), [])\n return (\n \n {children}\n \n )\n}\n\n/** Read the current page's per-locale URLs (for a language switcher). */\nexport function useAlternateLinks(): AlternateLinks {\n const ctx = use(AlternateLinksContext)\n return ctx?.links ?? {}\n}\n\n/** Setter for the alternates (used by AlternateLinksUpdater). */\nexport function useSetAlternateLinks(): (links: AlternateLinks) => void {\n const ctx = use(AlternateLinksContext)\n return ctx?.setLinks ?? (() => {})\n}\n"],"names":["createContext","use","useCallback","useState","AlternateLinksContext","AlternateLinksProvider","children","links","setLinksState","setLinks","next","value","useAlternateLinks","ctx","useSetAlternateLinks"],"mappings":"AAAA;;AAEA,SAASA,aAAa,EAAEC,GAAG,EAAEC,WAAW,EAAEC,QAAQ,QAAQ,QAAO;AAUjE,MAAMC,sCAAwBJ,cAAiD;AAE/E;;;;;;;;;;;;CAYC,GACD,OAAO,SAASK,uBAAuB,EAAEC,QAAQ,EAAiC;IAChF,MAAM,CAACC,OAAOC,cAAc,GAAGL,SAAyB,CAAC;IACzD,MAAMM,WAAWP,YAAY,CAACQ,OAAyBF,cAAcE,OAAO,EAAE;IAC9E,qBACE,KAACN;QAAsBO,OAAO;YAAEJ;YAAOE;QAAS;kBAC7CH;;AAGP;AAEA,uEAAuE,GACvE,OAAO,SAASM;IACd,MAAMC,MAAMZ,IAAIG;IAChB,OAAOS,KAAKN,SAAS,CAAC;AACxB;AAEA,+DAA+D,GAC/D,OAAO,SAASO;IACd,MAAMD,MAAMZ,IAAIG;IAChB,OAAOS,KAAKJ,YAAa,CAAA,KAAO,CAAA;AAClC"} \ No newline at end of file diff --git a/dist/modules/i18n/AlternateLinksUpdater.d.ts b/dist/modules/i18n/AlternateLinksUpdater.d.ts new file mode 100644 index 0000000..b2588e0 --- /dev/null +++ b/dist/modules/i18n/AlternateLinksUpdater.d.ts @@ -0,0 +1,19 @@ +import { type AlternateLinks } from './AlternateLinksContext.js'; +/** + * Reports the current page's per-locale URLs into AlternateLinksProvider. Render + * it on each page (a Server Component computes the links via resolveRoute / + * getLocalizedSlugs and passes them down). The switcher then links correctly. + * + * // page.tsx (RSC) — compute alternates from the resolved route + * import { AlternateLinksUpdater } from '@intecion/ipal-kit/client' + * const alternates = { pl: '/pl/uslugi/karne', en: '/en/services/criminal' } + * return <> + * + * {/* page content *\/} + * + * + * Renders nothing; it only pushes the links into context on mount/change. + */ +export declare function AlternateLinksUpdater({ links }: { + links: AlternateLinks; +}): null; diff --git a/dist/modules/i18n/AlternateLinksUpdater.js b/dist/modules/i18n/AlternateLinksUpdater.js new file mode 100644 index 0000000..258e157 --- /dev/null +++ b/dist/modules/i18n/AlternateLinksUpdater.js @@ -0,0 +1,32 @@ +'use client'; +import { useEffect } from 'react'; +import { useSetAlternateLinks } from './AlternateLinksContext.js'; +/** + * Reports the current page's per-locale URLs into AlternateLinksProvider. Render + * it on each page (a Server Component computes the links via resolveRoute / + * getLocalizedSlugs and passes them down). The switcher then links correctly. + * + * // page.tsx (RSC) — compute alternates from the resolved route + * import { AlternateLinksUpdater } from '@intecion/ipal-kit/client' + * const alternates = { pl: '/pl/uslugi/karne', en: '/en/services/criminal' } + * return <> + * + * {/* page content *\/} + * + * + * Renders nothing; it only pushes the links into context on mount/change. + */ export function AlternateLinksUpdater({ links }) { + const setLinks = useSetAlternateLinks(); + const key = JSON.stringify(links); + useEffect(()=>{ + setLinks(links); + // key covers link changes; setLinks is stable (useCallback). + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [ + key, + setLinks + ]); + return null; +} + +//# sourceMappingURL=AlternateLinksUpdater.js.map \ No newline at end of file diff --git a/dist/modules/i18n/AlternateLinksUpdater.js.map b/dist/modules/i18n/AlternateLinksUpdater.js.map new file mode 100644 index 0000000..ed0e5f2 --- /dev/null +++ b/dist/modules/i18n/AlternateLinksUpdater.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/i18n/AlternateLinksUpdater.tsx"],"sourcesContent":["'use client'\n\nimport { useEffect } from 'react'\n\nimport { type AlternateLinks, useSetAlternateLinks } from './AlternateLinksContext.js'\n\n/**\n * Reports the current page's per-locale URLs into AlternateLinksProvider. Render\n * it on each page (a Server Component computes the links via resolveRoute /\n * getLocalizedSlugs and passes them down). The switcher then links correctly.\n *\n * // page.tsx (RSC) — compute alternates from the resolved route\n * import { AlternateLinksUpdater } from '@intecion/ipal-kit/client'\n * const alternates = { pl: '/pl/uslugi/karne', en: '/en/services/criminal' }\n * return <>\n * \n * {/* page content *\\/}\n * \n *\n * Renders nothing; it only pushes the links into context on mount/change.\n */\nexport function AlternateLinksUpdater({ links }: { links: AlternateLinks }) {\n const setLinks = useSetAlternateLinks()\n const key = JSON.stringify(links)\n useEffect(() => {\n setLinks(links)\n // key covers link changes; setLinks is stable (useCallback).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [key, setLinks])\n return null\n}\n"],"names":["useEffect","useSetAlternateLinks","AlternateLinksUpdater","links","setLinks","key","JSON","stringify"],"mappings":"AAAA;AAEA,SAASA,SAAS,QAAQ,QAAO;AAEjC,SAA8BC,oBAAoB,QAAQ,6BAA4B;AAEtF;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASC,sBAAsB,EAAEC,KAAK,EAA6B;IACxE,MAAMC,WAAWH;IACjB,MAAMI,MAAMC,KAAKC,SAAS,CAACJ;IAC3BH,UAAU;QACRI,SAASD;IACT,6DAA6D;IAC7D,uDAAuD;IACzD,GAAG;QAACE;QAAKD;KAAS;IAClB,OAAO;AACT"} \ No newline at end of file diff --git a/dist/modules/i18n/LanguageSwitcher.d.ts b/dist/modules/i18n/LanguageSwitcher.d.ts new file mode 100644 index 0000000..f3e09a2 --- /dev/null +++ b/dist/modules/i18n/LanguageSwitcher.d.ts @@ -0,0 +1,36 @@ +import type { I18nConfig } from './types.js'; +export type LanguageSwitcherClassNames = { + item?: string; + itemActive?: string; + menu?: string; + root?: string; + trigger?: string; +}; +type LocaleItem = { + code: string; + label: string; +}; +/** + * Language switcher that links to the CORRECT localized URL per language, + * reading the current page's alternates from AlternateLinksProvider — so it + * never 404s on differing slugs (/pl/uslugi vs /en/services). + * + * Unstyled by default (classNames, like CookieBanner) — NOT a fixed + * light/dark variant, so it matches any project's design. A locale with no + * known alternate falls back to its root (/{code}). + * + * // layout/header (client), inside AlternateLinksProvider + * + */ +export declare function LanguageSwitcher({ classNames, config, currentLocale, renderLabel, }: { + classNames?: LanguageSwitcherClassNames; + config: I18nConfig; + currentLocale: string; + /** Custom label per locale (e.g. flag + code). Defaults to the config label. */ + renderLabel?: (locale: LocaleItem) => React.ReactNode; +}): import("react/jsx-runtime").JSX.Element; +export {}; diff --git a/dist/modules/i18n/LanguageSwitcher.js b/dist/modules/i18n/LanguageSwitcher.js new file mode 100644 index 0000000..40f83db --- /dev/null +++ b/dist/modules/i18n/LanguageSwitcher.js @@ -0,0 +1,65 @@ +'use client'; +import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; +import { useState } from 'react'; +import { useAlternateLinks } from './AlternateLinksContext.js'; +/** + * Language switcher that links to the CORRECT localized URL per language, + * reading the current page's alternates from AlternateLinksProvider — so it + * never 404s on differing slugs (/pl/uslugi vs /en/services). + * + * Unstyled by default (classNames, like CookieBanner) — NOT a fixed + * light/dark variant, so it matches any project's design. A locale with no + * known alternate falls back to its root (/{code}). + * + * // layout/header (client), inside AlternateLinksProvider + * + */ export function LanguageSwitcher({ classNames, config, currentLocale, renderLabel }) { + const alternates = useAlternateLinks(); + const [open, setOpen] = useState(false); + const cn = classNames ?? {}; + const locales = config.locales.map((l)=>({ + code: l.code, + label: l.label ?? l.code.toUpperCase() + })); + const hrefFor = (code)=>alternates[code] ?? `/${code}`; + const current = locales.find((l)=>l.code === currentLocale); + return /*#__PURE__*/ _jsxs("div", { + className: cn.root, + "data-ipal-langswitcher": true, + children: [ + /*#__PURE__*/ _jsx("button", { + "aria-expanded": open, + "aria-haspopup": "true", + className: cn.trigger, + onClick: ()=>setOpen((o)=>!o), + type: "button", + children: current ? renderLabel ? renderLabel(current) : current.label : currentLocale + }), + open && /*#__PURE__*/ _jsx("ul", { + className: cn.menu, + role: "menu", + children: locales.map((loc)=>{ + const active = loc.code === currentLocale; + return /*#__PURE__*/ _jsx("li", { + role: "none", + children: /*#__PURE__*/ _jsx("a", { + "aria-current": active ? 'true' : undefined, + className: `${cn.item ?? ''} ${active ? cn.itemActive ?? '' : ''}`.trim(), + href: hrefFor(loc.code), + hrefLang: loc.code, + onClick: ()=>setOpen(false), + role: "menuitem", + children: renderLabel ? renderLabel(loc) : loc.label + }) + }, loc.code); + }) + }) + ] + }); +} + +//# sourceMappingURL=LanguageSwitcher.js.map \ No newline at end of file diff --git a/dist/modules/i18n/LanguageSwitcher.js.map b/dist/modules/i18n/LanguageSwitcher.js.map new file mode 100644 index 0000000..ae370c8 --- /dev/null +++ b/dist/modules/i18n/LanguageSwitcher.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/i18n/LanguageSwitcher.tsx"],"sourcesContent":["'use client'\n\nimport { useState } from 'react'\n\nimport type { I18nConfig } from './types.js'\n\nimport { useAlternateLinks } from './AlternateLinksContext.js'\n\nexport type LanguageSwitcherClassNames = {\n item?: string\n itemActive?: string\n menu?: string\n root?: string\n trigger?: string\n}\n\ntype LocaleItem = { code: string; label: string }\n\n/**\n * Language switcher that links to the CORRECT localized URL per language,\n * reading the current page's alternates from AlternateLinksProvider — so it\n * never 404s on differing slugs (/pl/uslugi vs /en/services).\n *\n * Unstyled by default (classNames, like CookieBanner) — NOT a fixed\n * light/dark variant, so it matches any project's design. A locale with no\n * known alternate falls back to its root (/{code}).\n *\n * // layout/header (client), inside AlternateLinksProvider\n * \n */\nexport function LanguageSwitcher({\n classNames,\n config,\n currentLocale,\n renderLabel,\n}: {\n classNames?: LanguageSwitcherClassNames\n config: I18nConfig\n currentLocale: string\n /** Custom label per locale (e.g. flag + code). Defaults to the config label. */\n renderLabel?: (locale: LocaleItem) => React.ReactNode\n}) {\n const alternates = useAlternateLinks()\n const [open, setOpen] = useState(false)\n const cn = classNames ?? {}\n\n const locales: LocaleItem[] = config.locales.map((l) => ({\n code: l.code,\n label: l.label ?? l.code.toUpperCase(),\n }))\n\n const hrefFor = (code: string): string => alternates[code] ?? `/${code}`\n\n const current = locales.find((l) => l.code === currentLocale)\n\n return (\n
\n setOpen((o) => !o)}\n type=\"button\"\n >\n {current ? (renderLabel ? renderLabel(current) : current.label) : currentLocale}\n \n {open && (\n
    \n {locales.map((loc) => {\n const active = loc.code === currentLocale\n return (\n
  • \n setOpen(false)}\n role=\"menuitem\"\n >\n {renderLabel ? renderLabel(loc) : loc.label}\n \n
  • \n )\n })}\n
\n )}\n
\n )\n}\n"],"names":["useState","useAlternateLinks","LanguageSwitcher","classNames","config","currentLocale","renderLabel","alternates","open","setOpen","cn","locales","map","l","code","label","toUpperCase","hrefFor","current","find","div","className","root","data-ipal-langswitcher","button","aria-expanded","aria-haspopup","trigger","onClick","o","type","ul","menu","role","loc","active","li","a","aria-current","undefined","item","itemActive","trim","href","hrefLang"],"mappings":"AAAA;;AAEA,SAASA,QAAQ,QAAQ,QAAO;AAIhC,SAASC,iBAAiB,QAAQ,6BAA4B;AAY9D;;;;;;;;;;;;;;;CAeC,GACD,OAAO,SAASC,iBAAiB,EAC/BC,UAAU,EACVC,MAAM,EACNC,aAAa,EACbC,WAAW,EAOZ;IACC,MAAMC,aAAaN;IACnB,MAAM,CAACO,MAAMC,QAAQ,GAAGT,SAAS;IACjC,MAAMU,KAAKP,cAAc,CAAC;IAE1B,MAAMQ,UAAwBP,OAAOO,OAAO,CAACC,GAAG,CAAC,CAACC,IAAO,CAAA;YACvDC,MAAMD,EAAEC,IAAI;YACZC,OAAOF,EAAEE,KAAK,IAAIF,EAAEC,IAAI,CAACE,WAAW;QACtC,CAAA;IAEA,MAAMC,UAAU,CAACH,OAAyBP,UAAU,CAACO,KAAK,IAAI,CAAC,CAAC,EAAEA,MAAM;IAExE,MAAMI,UAAUP,QAAQQ,IAAI,CAAC,CAACN,IAAMA,EAAEC,IAAI,KAAKT;IAE/C,qBACE,MAACe;QAAIC,WAAWX,GAAGY,IAAI;QAAEC,wBAAsB;;0BAC7C,KAACC;gBACCC,iBAAejB;gBACfkB,iBAAc;gBACdL,WAAWX,GAAGiB,OAAO;gBACrBC,SAAS,IAAMnB,QAAQ,CAACoB,IAAM,CAACA;gBAC/BC,MAAK;0BAEJZ,UAAWZ,cAAcA,YAAYY,WAAWA,QAAQH,KAAK,GAAIV;;YAEnEG,sBACC,KAACuB;gBAAGV,WAAWX,GAAGsB,IAAI;gBAAEC,MAAK;0BAC1BtB,QAAQC,GAAG,CAAC,CAACsB;oBACZ,MAAMC,SAASD,IAAIpB,IAAI,KAAKT;oBAC5B,qBACE,KAAC+B;wBAAkBH,MAAK;kCACtB,cAAA,KAACI;4BACCC,gBAAcH,SAAS,SAASI;4BAChClB,WAAW,GAAGX,GAAG8B,IAAI,IAAI,GAAG,CAAC,EAAEL,SAAUzB,GAAG+B,UAAU,IAAI,KAAM,IAAI,CAACC,IAAI;4BACzEC,MAAM1B,QAAQiB,IAAIpB,IAAI;4BACtB8B,UAAUV,IAAIpB,IAAI;4BAClBc,SAAS,IAAMnB,QAAQ;4BACvBwB,MAAK;sCAEJ3B,cAAcA,YAAY4B,OAAOA,IAAInB,KAAK;;uBATtCmB,IAAIpB,IAAI;gBAarB;;;;AAKV"} \ No newline at end of file diff --git a/dist/modules/i18n/index.d.ts b/dist/modules/i18n/index.d.ts index a8a4c11..68f97ca 100644 --- a/dist/modules/i18n/index.d.ts +++ b/dist/modules/i18n/index.d.ts @@ -1,6 +1,11 @@ +export { AlternateLinksProvider, useAlternateLinks, useSetAlternateLinks, } from './AlternateLinksContext.js'; +export type { AlternateLinks } from './AlternateLinksContext.js'; +export { AlternateLinksUpdater } from './AlternateLinksUpdater.js'; export { createProxy, DEFAULT_PROXY_MATCHER } from './createProxy.js'; export { getLocalizedSlugs } from './getLocalizedSlugs.js'; export { getDefaultLocale, getLocaleCodes, getLocaleDefinition, isValidLocale } from './helpers.js'; +export { LanguageSwitcher } from './LanguageSwitcher.js'; +export type { LanguageSwitcherClassNames } from './LanguageSwitcher.js'; export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './localeMiddleware.js'; export type { LocaleMiddlewareResult } from './localeMiddleware.js'; export { buildLocalizationConfig } from './localizationConfig.js'; diff --git a/dist/modules/i18n/index.js b/dist/modules/i18n/index.js index bba2e5f..b9f6ef6 100644 --- a/dist/modules/i18n/index.js +++ b/dist/modules/i18n/index.js @@ -1,6 +1,9 @@ +export { AlternateLinksProvider, useAlternateLinks, useSetAlternateLinks } from './AlternateLinksContext.js'; +export { AlternateLinksUpdater } from './AlternateLinksUpdater.js'; export { createProxy, DEFAULT_PROXY_MATCHER } from './createProxy.js'; export { getLocalizedSlugs } from './getLocalizedSlugs.js'; export { getDefaultLocale, getLocaleCodes, getLocaleDefinition, isValidLocale } from './helpers.js'; +export { LanguageSwitcher } from './LanguageSwitcher.js'; export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './localeMiddleware.js'; export { buildLocalizationConfig } from './localizationConfig.js'; export { buildLocalizedPath, switchLocalePath } from './localizedPath.js'; diff --git a/dist/modules/i18n/index.js.map b/dist/modules/i18n/index.js.map index 9812ae8..1a83f85 100644 --- a/dist/modules/i18n/index.js.map +++ b/dist/modules/i18n/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/i18n/index.ts"],"sourcesContent":["export { createProxy, DEFAULT_PROXY_MATCHER } from './createProxy.js'\nexport { getLocalizedSlugs } from './getLocalizedSlugs.js'\nexport { getDefaultLocale, getLocaleCodes, getLocaleDefinition, isValidLocale } from './helpers.js'\nexport { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './localeMiddleware.js'\nexport type { LocaleMiddlewareResult } from './localeMiddleware.js'\nexport { buildLocalizationConfig } from './localizationConfig.js'\nexport { buildLocalizedPath, switchLocalePath } from './localizedPath.js'\nexport type { LocalizedSlugs } from './localizedPath.js'\nexport { LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale } from './negotiateLocale.js'\nexport type { I18nConfig, LocaleDefinition } from './types.js'\nexport { validateI18nConfig } from './validation.js'\n"],"names":["createProxy","DEFAULT_PROXY_MATCHER","getLocalizedSlugs","getDefaultLocale","getLocaleCodes","getLocaleDefinition","isValidLocale","createLocaleMiddleware","DEFAULT_MIDDLEWARE_MATCHER","buildLocalizationConfig","buildLocalizedPath","switchLocalePath","LOCALE_COOKIE_NAME","matchAcceptLanguage","negotiateLocale","validateI18nConfig"],"mappings":"AAAA,SAASA,WAAW,EAAEC,qBAAqB,QAAQ,mBAAkB;AACrE,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,mBAAmB,EAAEC,aAAa,QAAQ,eAAc;AACnG,SAASC,sBAAsB,EAAEC,0BAA0B,QAAQ,wBAAuB;AAE1F,SAASC,uBAAuB,QAAQ,0BAAyB;AACjE,SAASC,kBAAkB,EAAEC,gBAAgB,QAAQ,qBAAoB;AAEzE,SAASC,kBAAkB,EAAEC,mBAAmB,EAAEC,eAAe,QAAQ,uBAAsB;AAE/F,SAASC,kBAAkB,QAAQ,kBAAiB"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/i18n/index.ts"],"sourcesContent":["export {\n AlternateLinksProvider,\n useAlternateLinks,\n useSetAlternateLinks,\n} from './AlternateLinksContext.js'\nexport type { AlternateLinks } from './AlternateLinksContext.js'\nexport { AlternateLinksUpdater } from './AlternateLinksUpdater.js'\nexport { createProxy, DEFAULT_PROXY_MATCHER } from './createProxy.js'\nexport { getLocalizedSlugs } from './getLocalizedSlugs.js'\nexport { getDefaultLocale, getLocaleCodes, getLocaleDefinition, isValidLocale } from './helpers.js'\nexport { LanguageSwitcher } from './LanguageSwitcher.js'\nexport type { LanguageSwitcherClassNames } from './LanguageSwitcher.js'\nexport { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './localeMiddleware.js'\nexport type { LocaleMiddlewareResult } from './localeMiddleware.js'\nexport { buildLocalizationConfig } from './localizationConfig.js'\nexport { buildLocalizedPath, switchLocalePath } from './localizedPath.js'\nexport type { LocalizedSlugs } from './localizedPath.js'\nexport { LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale } from './negotiateLocale.js'\nexport type { I18nConfig, LocaleDefinition } from './types.js'\nexport { validateI18nConfig } from './validation.js'\n"],"names":["AlternateLinksProvider","useAlternateLinks","useSetAlternateLinks","AlternateLinksUpdater","createProxy","DEFAULT_PROXY_MATCHER","getLocalizedSlugs","getDefaultLocale","getLocaleCodes","getLocaleDefinition","isValidLocale","LanguageSwitcher","createLocaleMiddleware","DEFAULT_MIDDLEWARE_MATCHER","buildLocalizationConfig","buildLocalizedPath","switchLocalePath","LOCALE_COOKIE_NAME","matchAcceptLanguage","negotiateLocale","validateI18nConfig"],"mappings":"AAAA,SACEA,sBAAsB,EACtBC,iBAAiB,EACjBC,oBAAoB,QACf,6BAA4B;AAEnC,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,WAAW,EAAEC,qBAAqB,QAAQ,mBAAkB;AACrE,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,mBAAmB,EAAEC,aAAa,QAAQ,eAAc;AACnG,SAASC,gBAAgB,QAAQ,wBAAuB;AAExD,SAASC,sBAAsB,EAAEC,0BAA0B,QAAQ,wBAAuB;AAE1F,SAASC,uBAAuB,QAAQ,0BAAyB;AACjE,SAASC,kBAAkB,EAAEC,gBAAgB,QAAQ,qBAAoB;AAEzE,SAASC,kBAAkB,EAAEC,mBAAmB,EAAEC,eAAe,QAAQ,uBAAsB;AAE/F,SAASC,kBAAkB,QAAQ,kBAAiB"} \ No newline at end of file diff --git a/docs/i18n.md b/docs/i18n.md index 8d21671..4e7441b 100644 --- a/docs/i18n.md +++ b/docs/i18n.md @@ -248,4 +248,64 @@ Jeśli klient później doda drugi język, to PRZEBUDOWA, nie przełącznik: Warto to przewidzieć na starcie: jeśli jest szansa na drugi język, rozważ od razu strukturę wielojęzyczną (z [locale]), nawet dla jednego locale — wtedy prefiks -`/pl` jest, ale dodanie języka to tylko config, nie przebudowa struktury. \ No newline at end of file +`/pl` jest, ale dodanie języka to tylko config, nie przebudowa struktury. + +## Przełącznik języka bez 404 (AlternateLinks + LanguageSwitcher) + +Gdy slug różni się per język (`/pl/uslugi/karne` vs `/en/services/criminal`), +naiwny przełącznik (podmiana prefiksu `/pl` → `/en`) prowadzi do 404. Plugin +rozwiązuje to przez kontekst alternatywnych URL-i. + +### Jak to działa + +1. **AlternateLinksProvider** w layoutcie — trzyma URL-e per język bieżącej strony +2. **AlternateLinksUpdater** na każdej stronie — zgłasza jej alternatywne URL-e + (strona RSC wylicza je z resolveRoute/getLocalizedSlugs) +3. **LanguageSwitcher** — linkuje do poprawnych URL-i z kontekstu + +### Wpięcie + +```tsx +// layout.tsx +import { AlternateLinksProvider } from '@intecion/ipal-kit/client' +{children} + +// page.tsx (RSC) — wylicz alternatywy z routingu +import { AlternateLinksUpdater } from '@intecion/ipal-kit/client' +const alternates = { pl: '/pl/uslugi/karne', en: '/en/services/criminal' } +return <> + + {/* treść */} + + +// header (client) — przełącznik, headless, classNames jak CookieBanner +import { LanguageSwitcher } from '@intecion/ipal-kit/client' + +``` + +LanguageSwitcher jest BEZ stylów (classNames) — nie `variant="light|dark"`, żeby +pasował do każdego designu projektu. Locale bez znanego alternatywnego URL → +fallback na root `/{code}`. + +> **Skąd alternates na stronie:** strona RSC już rozwiązuje trasę (resolveRoute); +> z tego samego źródła wylicz slugi per język (getLocalizedSlugs/buildLocalizedPath) +> i przekaż do AlternateLinksUpdater. To eliminuje własny AlternateLinksContext +> (~150 linii) kopiowany w projektach. + +## Next matcher — MUSI być literałem inline + +Next.js analizuje `config.matcher` STATYCZNIE (AST) — musi być literałem tablicy +w pliku proxy/middleware, nie importem/zmienną. Mimo że plugin eksportuje +`DEFAULT_PROXY_MATCHER`, Next może nie rozpoznać go jako importu. Bezpiecznie: + +```ts +// proxy.ts — matcher INLINE (nie import) +export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] } +``` + +`DEFAULT_PROXY_MATCHER` używaj jako referencji wartości, ale jeśli Next narzeka +na matcher — wklej go inline. To ograniczenie Next, nie pluginu. \ No newline at end of file diff --git a/src/exports/client.ts b/src/exports/client.ts index 01f40a9..1ac082f 100644 --- a/src/exports/client.ts +++ b/src/exports/client.ts @@ -7,7 +7,6 @@ export { useAccessibility, } from '../modules/accessibility/client.js' export type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js' - export { Analytics } from '../modules/analytics/client.js' /** * Entry point: ipal-kit/client @@ -23,6 +22,7 @@ export { useConsent, useConsentContext, } from '../modules/consent/client.js' + export type { CookieBannerClassNames } from '../modules/consent/client.js' // Pure i18n path helpers — no server/RSC deps, safe to import in client // components (e.g. a LanguageSwitcher that computes locale URLs on the client). @@ -33,6 +33,14 @@ export { switchLocalePath, } from '../modules/i18n/index.js' export type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js' +export { + AlternateLinksProvider, + AlternateLinksUpdater, + LanguageSwitcher, + useAlternateLinks, + useSetAlternateLinks, +} from '../modules/i18n/index.js' +export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js' export { Turnstile } from '../modules/turnstile/client.js' export { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js' export type { TurnstileProps } from '../modules/turnstile/client.js' diff --git a/src/exports/next-middleware.ts b/src/exports/next-middleware.ts index ec33c56..93f50d3 100644 --- a/src/exports/next-middleware.ts +++ b/src/exports/next-middleware.ts @@ -7,3 +7,4 @@ */ export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from '../modules/i18n/index.js' export type { LocaleMiddlewareResult } from '../modules/i18n/index.js' +export { createProxy, DEFAULT_PROXY_MATCHER } from '../modules/i18n/index.js' diff --git a/src/modules/i18n/AlternateLinksContext.tsx b/src/modules/i18n/AlternateLinksContext.tsx new file mode 100644 index 0000000..68c1393 --- /dev/null +++ b/src/modules/i18n/AlternateLinksContext.tsx @@ -0,0 +1,48 @@ +'use client' + +import { createContext, use, useCallback, useState } from 'react' + +/** Map of locale code → absolute-or-relative URL for the current page. */ +export type AlternateLinks = Record + +type AlternateLinksContextValue = { + links: AlternateLinks + setLinks: (links: AlternateLinks) => void +} + +const AlternateLinksContext = createContext(null) + +/** + * Holds the current page's per-locale URLs so a LanguageSwitcher links to the + * CORRECT localized slug instead of naively swapping the locale prefix + * (/pl/uslugi → /en/uslugi, which 404s when the English slug is /en/services). + * + * Wrap the app once; each page reports its own alternates via + * (or useSetAlternateLinks). The switcher reads them + * with useAlternateLinks(). + * + * // layout.tsx + * import { AlternateLinksProvider } from '@intecion/ipal-kit/client' + * {children} + */ +export function AlternateLinksProvider({ children }: { children: React.ReactNode }) { + const [links, setLinksState] = useState({}) + const setLinks = useCallback((next: AlternateLinks) => setLinksState(next), []) + return ( + + {children} + + ) +} + +/** Read the current page's per-locale URLs (for a language switcher). */ +export function useAlternateLinks(): AlternateLinks { + const ctx = use(AlternateLinksContext) + return ctx?.links ?? {} +} + +/** Setter for the alternates (used by AlternateLinksUpdater). */ +export function useSetAlternateLinks(): (links: AlternateLinks) => void { + const ctx = use(AlternateLinksContext) + return ctx?.setLinks ?? (() => {}) +} diff --git a/src/modules/i18n/AlternateLinksUpdater.tsx b/src/modules/i18n/AlternateLinksUpdater.tsx new file mode 100644 index 0000000..05877fc --- /dev/null +++ b/src/modules/i18n/AlternateLinksUpdater.tsx @@ -0,0 +1,31 @@ +'use client' + +import { useEffect } from 'react' + +import { type AlternateLinks, useSetAlternateLinks } from './AlternateLinksContext.js' + +/** + * Reports the current page's per-locale URLs into AlternateLinksProvider. Render + * it on each page (a Server Component computes the links via resolveRoute / + * getLocalizedSlugs and passes them down). The switcher then links correctly. + * + * // page.tsx (RSC) — compute alternates from the resolved route + * import { AlternateLinksUpdater } from '@intecion/ipal-kit/client' + * const alternates = { pl: '/pl/uslugi/karne', en: '/en/services/criminal' } + * return <> + * + * {/* page content *\/} + * + * + * Renders nothing; it only pushes the links into context on mount/change. + */ +export function AlternateLinksUpdater({ links }: { links: AlternateLinks }) { + const setLinks = useSetAlternateLinks() + const key = JSON.stringify(links) + useEffect(() => { + setLinks(links) + // key covers link changes; setLinks is stable (useCallback). + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [key, setLinks]) + return null +} diff --git a/src/modules/i18n/LanguageSwitcher.tsx b/src/modules/i18n/LanguageSwitcher.tsx new file mode 100644 index 0000000..901513a --- /dev/null +++ b/src/modules/i18n/LanguageSwitcher.tsx @@ -0,0 +1,94 @@ +'use client' + +import { useState } from 'react' + +import type { I18nConfig } from './types.js' + +import { useAlternateLinks } from './AlternateLinksContext.js' + +export type LanguageSwitcherClassNames = { + item?: string + itemActive?: string + menu?: string + root?: string + trigger?: string +} + +type LocaleItem = { code: string; label: string } + +/** + * Language switcher that links to the CORRECT localized URL per language, + * reading the current page's alternates from AlternateLinksProvider — so it + * never 404s on differing slugs (/pl/uslugi vs /en/services). + * + * Unstyled by default (classNames, like CookieBanner) — NOT a fixed + * light/dark variant, so it matches any project's design. A locale with no + * known alternate falls back to its root (/{code}). + * + * // layout/header (client), inside AlternateLinksProvider + * + */ +export function LanguageSwitcher({ + classNames, + config, + currentLocale, + renderLabel, +}: { + classNames?: LanguageSwitcherClassNames + config: I18nConfig + currentLocale: string + /** Custom label per locale (e.g. flag + code). Defaults to the config label. */ + renderLabel?: (locale: LocaleItem) => React.ReactNode +}) { + const alternates = useAlternateLinks() + const [open, setOpen] = useState(false) + const cn = classNames ?? {} + + const locales: LocaleItem[] = config.locales.map((l) => ({ + code: l.code, + label: l.label ?? l.code.toUpperCase(), + })) + + const hrefFor = (code: string): string => alternates[code] ?? `/${code}` + + const current = locales.find((l) => l.code === currentLocale) + + return ( +
+ + {open && ( + + )} +
+ ) +} diff --git a/src/modules/i18n/index.ts b/src/modules/i18n/index.ts index 6a9ac44..14120ea 100644 --- a/src/modules/i18n/index.ts +++ b/src/modules/i18n/index.ts @@ -1,6 +1,15 @@ +export { + AlternateLinksProvider, + useAlternateLinks, + useSetAlternateLinks, +} from './AlternateLinksContext.js' +export type { AlternateLinks } from './AlternateLinksContext.js' +export { AlternateLinksUpdater } from './AlternateLinksUpdater.js' export { createProxy, DEFAULT_PROXY_MATCHER } from './createProxy.js' export { getLocalizedSlugs } from './getLocalizedSlugs.js' export { getDefaultLocale, getLocaleCodes, getLocaleDefinition, isValidLocale } from './helpers.js' +export { LanguageSwitcher } from './LanguageSwitcher.js' +export type { LanguageSwitcherClassNames } from './LanguageSwitcher.js' export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './localeMiddleware.js' export type { LocaleMiddlewareResult } from './localeMiddleware.js' export { buildLocalizationConfig } from './localizationConfig.js'