Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/intlayer-addon.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@tanstack/create': minor
'@tanstack/cli': minor
---

Add an Intlayer i18n add-on for React and Solid.
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Intlayer i18n

This add-on sets up [Intlayer](https://intlayer.org/doc/environment/tanstack-start) with localized routes.

- Locales and routing are configured in `intlayer.config.ts` (`prefix-no-default`: `/demo/intlayer`, `/fr/demo/intlayer`).
- Routes under `src/routes/{-$locale}/` are localized. Its `route.tsx` validates the locale prefix and provides `IntlayerProvider`.
- Use `LocalizedLink` and `useLocalizedNavigate` to keep the current locale when navigating.
- Content is declared in `*.content.ts` files, outside `src/routes`. The `vite-intlayer` plugin builds them into `.intlayer`.
- To localize the whole app, move your routes under `src/routes/{-$locale}/`, or run `npx intlayer init`.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@

# Intlayer
.intlayer
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import { type IntlayerConfig, Locales } from 'intlayer'

/**
* Intlayer configuration file documentation
* @see https://intlayer.org/doc/concept/configuration
*/

const config: IntlayerConfig = {
internationalization: {
locales: [Locales.ENGLISH, Locales.FRENCH, Locales.SPANISH],
/**
* Default locale used as a fallback if the requested locale is not found.
*/
defaultLocale: Locales.ENGLISH,
},
routing: {
/**
* Locale routing strategy.
* - "prefix-no-default": Prefix all except the default locale (e.g., /dashboard, /fr/dashboard).
* - "prefix-all": Prefix all locales (e.g., /en/dashboard, /fr/dashboard).
* - "no-prefix": No locale in the URL.
* - "search-params": Use search params to define the locale (e.g., /dashboard/?locale=en, /dashboard/?locale=fr)
* Default: "prefix-no-default"
*/
mode: 'prefix-no-default',

/**
* Enables the Intlayer locale-routing proxy (middleware).
* Handles locale detection, redirects and rewrites in dev, preview and SSR.
* Leave unset for auto mode: dev and preview servers keep locale routing
* URL-driven by ignoring the stored locale. `true` forces the full
* behaviour everywhere, `false` disables the proxy.
* Default: undefined (auto)
*/
enableProxy: false,
},
editor: {
/**
* Whether the visual editor is enabled.
*/
enabled: false,

/**
* URL of your application for origin validation.
*/
applicationURL: 'http://localhost:3000',
},
ai: {
/**
* AI provider to use.
* Options: 'openai', 'anthropic', 'mistral', 'deepseek', 'gemini', 'ollama', 'openrouter', 'alibaba', 'fireworks', 'groq', 'huggingface', 'bedrock', 'googlevertex', 'togetherai', 'lmstudio', 'moonshotai'
*/
provider: 'openai',
model: 'gpt-5.6-terra',
apiKey: process.env.OPENAI_API_KEY,
/**
* Additional context for the translations
*
* Can be use in addition of the dictionary `description` field
*/
applicationContext: [''].join('\n'),
},
compiler: {
enabled: false,

/**
* Defines the output files path for autogenerated content (compiler / autofill / extract)
*
* - `./` paths are resolved relative to the component directory.
* - `/` paths are resolved relative to the project root (`baseDir`).
*
* - Including the `{{locale}}` variable in the path will trigger the generation of separate dictionaries per locale.
*
* Example:
* ```ts
* {
* // Create Multilingual .content.ts files close to the component
* output: ({ fileName, extension }) => `./${fileName}${extension}`,
* }
* ```
*
* ```ts
* {
* // Create centralize per-locale JSON at the root of the project
* output: ({ key, locale }) => `/locales/${locale}/${key}.content.json`,
* }
* ```
*
* Variable list:
* - `fileName`: The name of the file.
* - `key`: The key of the content.
* - `locale`: The locale of the content.
* - `extension`: The extension of the file.
* - `componentFileName`: The name of the component file.
* - `componentExtension`: The extension of the component file.
* - `format`: The format of the dictionary.
* - `componentFormat`: The format of the component dictionary.
* - `componentDirPath`: The directory path of the component.
*/
output: ({ fileName }) => `./${fileName}.content.ts`,

/**
* Indicates if the components should be saved after being transformed.
*
* - If `true`, the compiler will rewrite the component file in the disk. So the transformation will be permanent, and the compiler will skip the transformation for the next process. That way, the compiler can transform the app, and then it can be removed.
*
* - If `false`, the compiler will inject the `useIntlayer()` function call into the code in the build output only, and keep the base codebase intact. The transformation will be done only in memory.
*/
saveComponents: false,
},
dictionary: {
/**
* Controls how dictionaries are imported.
* - "static": Statically imported at build time.
* - "dynamic": Dynamically imported using Suspense.
* - "fetch": Fetched dynamically via the live sync API.
*/
importMode: 'static',
},
build: {
/**
* Minify the dictionaries to reduce the bundle size.
*/
minify: true,

/**
* Purge the unused keys in a dictionaries
*/
purge: true,

/**
* Indicates if the build should check TypeScript types
*/
checkTypes: false,
},
}

export default config
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { useLocation } from '@tanstack/react-router'
import {
getHTMLTextDir,
getLocaleName,
getPathWithoutLocale,
getPrefix,
} from 'intlayer'
import { useLocale } from 'react-intlayer'

import { LocalizedLink, type To } from './localized-link'

export default function IntlayerLocaleSwitcher() {
const { pathname } = useLocation()

const { availableLocales, locale, setLocale } = useLocale()

const pathWithoutLocale = getPathWithoutLocale(pathname)

return (
<div>
<button
type="button"
className="demo-button"
popoverTarget="localePopover"
>
{getLocaleName(locale)}
</button>
<div id="localePopover" popover="auto" className="demo-card m-auto p-2">
<ul className="flex flex-col gap-1">
{availableLocales.map((localeItem) => (
<li key={localeItem}>
<LocalizedLink
className="demo-button w-full justify-start"
aria-current={locale === localeItem ? 'page' : undefined}
onClick={(event) => {
// Ctrl/Cmd/Shift/Alt-click opens the link elsewhere: keep this page's locale
if (
event.metaKey ||
event.ctrlKey ||
event.shiftKey ||
event.altKey
)
return
setLocale(localeItem)
event.currentTarget
.closest<HTMLElement>('[popover]')
?.hidePopover()
}}
params={{ locale: getPrefix(localeItem).localePrefix }}
to={pathWithoutLocale as To}
replace // Will ensure that the "go back" browser button will redirect to the previous page
>
<span dir={getHTMLTextDir(localeItem)} lang={localeItem}>
{getLocaleName(localeItem, localeItem)}
</span>
</LocalizedLink>
</li>
))}
</ul>
</div>
</div>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { type Dictionary, t } from 'intlayer'

const intlayerDemoContent = {
key: 'intlayer-demo',
content: {
title: t({
en: 'Hello from Intlayer',
fr: 'Bonjour depuis Intlayer',
es: 'Hola desde Intlayer',
}),
description: t({
en: 'Localized routes live under src/routes/{-$locale}: /demo/intlayer, /fr/demo/intlayer…',
fr: 'Les routes localisées sont dans src/routes/{-$locale} : /demo/intlayer, /fr/demo/intlayer…',
es: 'Las rutas localizadas están en src/routes/{-$locale}: /demo/intlayer, /fr/demo/intlayer…',
}),
currentLocale: t({
en: 'Current locale:',
fr: 'Langue actuelle :',
es: 'Idioma actual:',
}),
learnMore: t({
en: 'Learn how Intlayer works with TanStack Start',
fr: 'Découvrir Intlayer avec TanStack Start',
es: 'Descubre Intlayer con TanStack Start',
}),
},
} satisfies Dictionary

export default intlayerDemoContent
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import type { FC } from 'react'

import { Link, type LinkComponentProps } from '@tanstack/react-router'
import { useLocale } from 'react-intlayer'
import { getPrefix } from 'intlayer'

export const LOCALE_ROUTE = '{-$locale}' as const

/**
* Adds the locale segment to absolute paths. An omitted `to` goes to the locale
* root, and relative paths ('.', '..') are kept as is.
*/
export const localizeTo = (to?: string) =>
to === undefined || to.startsWith('/') ? `/${LOCALE_ROUTE}${to ?? ''}` : to

/** Adds the locale param, keeping the function form of `params`. */
export const localizeParams = (locale: string | undefined, params?: unknown) =>
typeof params === 'function'
? (prev: Record<string, unknown>) => ({ locale, ...params(prev) })
: { locale, ...(typeof params === 'object' ? params : {}) }

export type To = StripLocalePrefix<LinkComponentProps['to']>

export type StripLocalePrefix<T extends string | undefined> = T extends
| `/${typeof LOCALE_ROUTE}/`
| `/${typeof LOCALE_ROUTE}`
? '/'
: T extends `/${typeof LOCALE_ROUTE}/${infer Rest}`
? `/${Rest}`
: T

type LocalizedLinkProps = {
to?: To
} & Omit<LinkComponentProps, 'to'>

export const LocalizedLink: FC<LocalizedLinkProps> = (props) => {
const { locale } = useLocale()
const { localePrefix } = getPrefix(locale)

return (
<Link
{...props}
params={
localizeParams(
localePrefix,
props.params,
) as LinkComponentProps['params']
}
to={localizeTo(props.to) as LinkComponentProps['to']}
/>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { useNavigate } from '@tanstack/react-router'
import { getPrefix } from 'intlayer'
import { useLocale } from 'react-intlayer'
import {
localizeParams,
localizeTo,
type StripLocalePrefix,
} from '@/components/localized-link'
import type { FileRouteTypes } from '@/routeTree.gen'

type NavigateFn = ReturnType<typeof useNavigate>
type BaseNavigateOptions = Parameters<NavigateFn>[0]

type LocalizedTo = StripLocalePrefix<FileRouteTypes['to']>

export type LocalizedNavigateOptions = Omit<
BaseNavigateOptions,
'to' | 'params'
> & {
to: LocalizedTo
params?: Omit<NonNullable<BaseNavigateOptions['params']>, 'locale'>
}

type LocalizedNavigate = (
options: LocalizedNavigateOptions,
) => ReturnType<NavigateFn>

export const useLocalizedNavigate = () => {
const navigate = useNavigate()

const { locale } = useLocale()

const localizedNavigate: LocalizedNavigate = (args: any) => {
const { localePrefix } = getPrefix(locale)
const { to, params, ...rest } =
typeof args === 'string' ? { to: args } : args

return navigate({
...rest,
to: localizeTo(to),
params: localizeParams(localePrefix, params),
} as any)
}

return localizedNavigate
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { createFileRoute } from '@tanstack/react-router'
import { useIntlayer, useLocale } from 'react-intlayer'

import IntlayerLocaleSwitcher from '@/components/IntlayerLocaleSwitcher'

export const Route = createFileRoute('/{-$locale}/demo/intlayer')({
component: IntlayerDemo,
})

function IntlayerDemo() {
const content = useIntlayer('intlayer-demo')
const { locale } = useLocale()

return (
<main className="demo-page demo-center text-center">
<section className="demo-panel flex w-full max-w-2xl flex-col items-center gap-4">
<h1 className="text-2xl font-bold">{content.title}</h1>
<p className="demo-muted text-lg">{content.description}</p>
<p>
{content.currentLocale} <strong>{locale}</strong>
</p>
<IntlayerLocaleSwitcher />
<a
href="https://intlayer.org/doc/environment/tanstack-start"
target="_blank"
rel="noopener noreferrer"
>
{content.learnMore}
</a>
</section>
</main>
)
}
Loading