49 lines
1.7 KiB
TypeScript
49 lines
1.7 KiB
TypeScript
'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<string, string>
|
|
|
|
type AlternateLinksContextValue = {
|
|
links: AlternateLinks
|
|
setLinks: (links: AlternateLinks) => void
|
|
}
|
|
|
|
const AlternateLinksContext = createContext<AlternateLinksContextValue | null>(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
|
|
* <AlternateLinksUpdater> (or useSetAlternateLinks). The switcher reads them
|
|
* with useAlternateLinks().
|
|
*
|
|
* // layout.tsx
|
|
* import { AlternateLinksProvider } from '@intecion/ipal-kit/client'
|
|
* <AlternateLinksProvider>{children}</AlternateLinksProvider>
|
|
*/
|
|
export function AlternateLinksProvider({ children }: { children: React.ReactNode }) {
|
|
const [links, setLinksState] = useState<AlternateLinks>({})
|
|
const setLinks = useCallback((next: AlternateLinks) => setLinksState(next), [])
|
|
return (
|
|
<AlternateLinksContext value={{ links, setLinks }}>
|
|
{children}
|
|
</AlternateLinksContext>
|
|
)
|
|
}
|
|
|
|
/** 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 ?? (() => {})
|
|
}
|