@djangocfg/layouts 2.1.658 → 2.1.659

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/README.md +2 -0
  2. package/package.json +12 -12
  3. package/src/components/LocaleSuggestion/LocaleSuggestion.test.tsx +142 -0
  4. package/src/components/LocaleSuggestion/LocaleSuggestion.tsx +114 -0
  5. package/src/components/LocaleSuggestion/LocaleSuggestionView.tsx +56 -0
  6. package/src/components/LocaleSuggestion/README.md +37 -0
  7. package/src/components/LocaleSuggestion/decide.test.ts +148 -0
  8. package/src/components/LocaleSuggestion/decide.ts +152 -0
  9. package/src/components/LocaleSuggestion/i18n/dictionaries.test.ts +27 -0
  10. package/src/components/LocaleSuggestion/i18n/index.ts +38 -0
  11. package/src/components/LocaleSuggestion/i18n/locales/ar.ts +7 -0
  12. package/src/components/LocaleSuggestion/i18n/locales/da.ts +7 -0
  13. package/src/components/LocaleSuggestion/i18n/locales/de.ts +7 -0
  14. package/src/components/LocaleSuggestion/i18n/locales/en.ts +7 -0
  15. package/src/components/LocaleSuggestion/i18n/locales/es.ts +7 -0
  16. package/src/components/LocaleSuggestion/i18n/locales/fr.ts +7 -0
  17. package/src/components/LocaleSuggestion/i18n/locales/it.ts +7 -0
  18. package/src/components/LocaleSuggestion/i18n/locales/ja.ts +7 -0
  19. package/src/components/LocaleSuggestion/i18n/locales/ko.ts +7 -0
  20. package/src/components/LocaleSuggestion/i18n/locales/nl.ts +7 -0
  21. package/src/components/LocaleSuggestion/i18n/locales/no.ts +7 -0
  22. package/src/components/LocaleSuggestion/i18n/locales/pl.ts +7 -0
  23. package/src/components/LocaleSuggestion/i18n/locales/ptBR.ts +7 -0
  24. package/src/components/LocaleSuggestion/i18n/locales/ru.ts +7 -0
  25. package/src/components/LocaleSuggestion/i18n/locales/sv.ts +7 -0
  26. package/src/components/LocaleSuggestion/i18n/locales/tr.ts +7 -0
  27. package/src/components/LocaleSuggestion/i18n/locales/zh.ts +7 -0
  28. package/src/components/LocaleSuggestion/i18n/types.ts +9 -0
  29. package/src/components/LocaleSuggestion/index.ts +5 -0
  30. package/src/components/LocaleSuggestion/memory.ts +23 -0
  31. package/src/components/index.ts +3 -1
  32. package/src/layouts/AppLayout/BaseApp.tsx +3 -0
  33. package/src/layouts/types/index.ts +1 -0
  34. package/src/layouts/types/layout.types.ts +16 -0
package/README.md CHANGED
@@ -145,6 +145,8 @@ const { locale, locales, changeLocale } = useLocaleSwitcher();
145
145
 
146
146
  When `routing` is set, `BaseApp` mounts a locale-aware `<Link>` adapter so every layout-rendered link keeps the active locale prefix. Drop it for default-locale-only apps.
147
147
 
148
+ With two or more `locales`, `BaseApp` also offers the visitor their browser's language once, quietly ([`LocaleSuggestion`](src/components/LocaleSuggestion/README.md)); `i18n.suggestion: false` turns it off.
149
+
148
150
  ---
149
151
 
150
152
  ## Monitor & debug
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@djangocfg/layouts",
3
- "version": "2.1.658",
3
+ "version": "2.1.659",
4
4
  "description": "Simple, straightforward layout components for Next.js - import and use with props",
5
5
  "keywords": [
6
6
  "layouts",
@@ -91,11 +91,11 @@
91
91
  "test": "vitest run"
92
92
  },
93
93
  "peerDependencies": {
94
- "@djangocfg/analytics": "^2.1.658",
95
- "@djangocfg/api": "^2.1.658",
96
- "@djangocfg/devtools": "^2.1.658",
97
- "@djangocfg/i18n": "^2.1.658",
98
- "@djangocfg/ui-core": "^2.1.658",
94
+ "@djangocfg/analytics": "^2.1.659",
95
+ "@djangocfg/api": "^2.1.659",
96
+ "@djangocfg/devtools": "^2.1.659",
97
+ "@djangocfg/i18n": "^2.1.659",
98
+ "@djangocfg/ui-core": "^2.1.659",
99
99
  "@hookform/resolvers": "^5.2.2 || ^7.0.2",
100
100
  "consola": "^3.4.2",
101
101
  "lucide-react": "^1.68.0",
@@ -123,12 +123,12 @@
123
123
  "qrcode.react": "^4.2.0"
124
124
  },
125
125
  "devDependencies": {
126
- "@djangocfg/analytics": "^2.1.658",
127
- "@djangocfg/api": "^2.1.658",
128
- "@djangocfg/devtools": "^2.1.658",
129
- "@djangocfg/i18n": "^2.1.658",
130
- "@djangocfg/typescript-config": "^2.1.658",
131
- "@djangocfg/ui-core": "^2.1.658",
126
+ "@djangocfg/analytics": "^2.1.659",
127
+ "@djangocfg/api": "^2.1.659",
128
+ "@djangocfg/devtools": "^2.1.659",
129
+ "@djangocfg/i18n": "^2.1.659",
130
+ "@djangocfg/typescript-config": "^2.1.659",
131
+ "@djangocfg/ui-core": "^2.1.659",
132
132
  "@storybook/react-vite": "^10.6.5",
133
133
  "@types/node": "^25.9.5",
134
134
  "@types/react": "19.3.0",
@@ -0,0 +1,142 @@
1
+ // @vitest-environment jsdom
2
+ import React, { act } from 'react';
3
+ import { createRoot, type Root } from 'react-dom/client';
4
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
5
+
6
+ import { LayoutI18nProvider } from '../../shared/LayoutI18nProvider';
7
+ import type { I18nLayoutConfig } from '../../layouts/types/layout.types';
8
+ import { LocaleSuggestion } from './LocaleSuggestion';
9
+ import { readMemory } from './memory';
10
+
11
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
12
+
13
+ let host: HTMLElement | null = null;
14
+ let root: Root | null = null;
15
+
16
+ const setLanguages = (languages: string[]) =>
17
+ Object.defineProperty(navigator, 'languages', { value: languages, configurable: true });
18
+
19
+ async function mount(i18n: Partial<I18nLayoutConfig> = {}, delay = 1500) {
20
+ const config: I18nLayoutConfig = {
21
+ locale: 'en',
22
+ locales: ['en', 'de', 'ar'],
23
+ onLocaleChange: vi.fn(),
24
+ ...i18n,
25
+ };
26
+ host = document.createElement('div');
27
+ document.body.appendChild(host);
28
+ root = createRoot(host);
29
+ await act(async () =>
30
+ root!.render(
31
+ <LayoutI18nProvider value={config}>
32
+ <LocaleSuggestion />
33
+ </LayoutI18nProvider>,
34
+ ),
35
+ );
36
+ await act(async () => {
37
+ await vi.advanceTimersByTimeAsync(delay);
38
+ });
39
+ return config;
40
+ }
41
+
42
+ const card = () => document.querySelector<HTMLElement>('[data-locale-suggestion]');
43
+
44
+ beforeEach(() => {
45
+ vi.useFakeTimers();
46
+ localStorage.clear();
47
+ setLanguages(['de-DE', 'en']);
48
+ });
49
+
50
+ afterEach(() => {
51
+ act(() => root?.unmount());
52
+ host?.remove();
53
+ host = root = null;
54
+ vi.useRealTimers();
55
+ });
56
+
57
+ describe('LocaleSuggestion', () => {
58
+ it('shows nothing until the page has settled', async () => {
59
+ await mount({}, 1000);
60
+ expect(card()).toBeNull();
61
+ await act(async () => {
62
+ await vi.advanceTimersByTimeAsync(600);
63
+ });
64
+ expect(card()).not.toBeNull();
65
+ });
66
+
67
+ it('speaks the browser language and names the target in its own language', async () => {
68
+ await mount();
69
+ expect(card()?.textContent).toContain('Deutsch');
70
+ expect(card()?.textContent).toContain('Diese Seite ist in Deutsch verfügbar');
71
+ expect(card()?.getAttribute('lang')).toBe('de-DE');
72
+ expect(card()?.getAttribute('dir')).toBe('ltr');
73
+ });
74
+
75
+ it('is right-to-left for an Arabic browser', async () => {
76
+ setLanguages(['ar']);
77
+ await mount();
78
+ expect(card()?.getAttribute('dir')).toBe('rtl');
79
+ });
80
+
81
+ it('switches on the primary button and does not remember it as a dismissal', async () => {
82
+ const config = await mount();
83
+ const button = [...card()!.querySelectorAll('button')].find((b) => b.textContent?.includes('Deutsch'))!;
84
+ await act(async () => button.click());
85
+ expect(config.onLocaleChange).toHaveBeenCalledWith('de');
86
+ expect(card()).toBeNull();
87
+ });
88
+
89
+ it('remembers a dismissal for the pair and stays quiet on the next visit', async () => {
90
+ await mount();
91
+ await act(async () => card()!.querySelector<HTMLButtonElement>('[data-slot=banner-close]')!.click());
92
+ expect(card()).toBeNull();
93
+ expect(Object.keys(readMemory().dismissed)).toEqual(['de>en']);
94
+
95
+ act(() => root?.unmount());
96
+ host?.remove();
97
+ await mount();
98
+ expect(card()).toBeNull();
99
+ });
100
+
101
+ it('closes on Escape from inside the card', async () => {
102
+ await mount();
103
+ await act(async () => {
104
+ card()!.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
105
+ });
106
+ expect(card()).toBeNull();
107
+ expect(readMemory().dismissed['de>en']).toBeTypeOf('number');
108
+ });
109
+
110
+ it('a one-language site mounts nothing: no listener, no storage read, no write', async () => {
111
+ const listen = vi.spyOn(window, 'addEventListener');
112
+ const read = vi.spyOn(Storage.prototype, 'getItem');
113
+ const write = vi.spyOn(Storage.prototype, 'setItem');
114
+ await mount({ locales: ['en'] });
115
+ expect(card()).toBeNull();
116
+ expect(listen.mock.calls.filter(([type]) => type === 'languagechange')).toEqual([]);
117
+ expect(read).not.toHaveBeenCalled();
118
+ expect(write).not.toHaveBeenCalled();
119
+ expect(localStorage.length).toBe(0);
120
+ listen.mockRestore();
121
+ read.mockRestore();
122
+ write.mockRestore();
123
+ });
124
+
125
+ it('can be turned off, and excluded by path', async () => {
126
+ await mount({ suggestion: false });
127
+ expect(card()).toBeNull();
128
+ act(() => root?.unmount());
129
+ host?.remove();
130
+ window.history.pushState({}, '', '/legal/terms');
131
+ await mount({ suggestion: { exclude: ['/legal'] } });
132
+ expect(card()).toBeNull();
133
+ window.history.pushState({}, '', '/');
134
+ });
135
+
136
+ it('shows nothing to automation', async () => {
137
+ Object.defineProperty(navigator, 'webdriver', { value: true, configurable: true });
138
+ await mount();
139
+ expect(card()).toBeNull();
140
+ Object.defineProperty(navigator, 'webdriver', { value: false, configurable: true });
141
+ });
142
+ });
@@ -0,0 +1,114 @@
1
+ 'use client';
2
+
3
+ import { useEffect, useMemo, useState } from 'react';
4
+
5
+ import { useBrowserLanguages, useLocation } from '@djangocfg/ui-core/hooks';
6
+
7
+ import type { I18nLayoutConfig } from '../../layouts/types/layout.types';
8
+ import { useLayoutI18nOptional } from '../../shared/LayoutI18nProvider';
9
+ import {
10
+ decideSuggestion,
11
+ dismissPair,
12
+ isAutomated,
13
+ isExcludedPath,
14
+ reconcileMemory,
15
+ suggestLocale,
16
+ } from './decide';
17
+ import { readMemory, writeMemory } from './memory';
18
+ import { LocaleSuggestionView } from './LocaleSuggestionView';
19
+
20
+ export const DEFAULT_DELAY_MS = 1500;
21
+
22
+ /**
23
+ * Offers the visitor the site's language they browse in, once, quietly.
24
+ * Mounted by `BaseApp`; reads `i18n` from the layout context, so an app needs no setup.
25
+ * Renders nothing on the server and on the first client render (no hydration difference), nothing for
26
+ * one-language sites, crawlers and automation, and nothing until the page has settled for `delayMs`.
27
+ */
28
+ export function LocaleSuggestion() {
29
+ const i18n = useLayoutI18nOptional();
30
+ // First check, before any hook that subscribes or reads storage: fewer than two locales, or switched off, mounts nothing.
31
+ if (!i18n || i18n.suggestion === false || i18n.locales.length < 2) return null;
32
+ return <LocaleSuggestionHost i18n={i18n} />;
33
+ }
34
+
35
+ function LocaleSuggestionHost({ i18n }: { i18n: I18nLayoutConfig }) {
36
+ const { languages } = useBrowserLanguages();
37
+ const { pathname } = useLocation();
38
+ const [settled, setSettled] = useState(false);
39
+ const [target, setTarget] = useState<string | null>(null);
40
+
41
+ const option = i18n?.suggestion;
42
+ const enabled = option !== false;
43
+ const options = option === false || option === undefined ? undefined : option;
44
+ const delayMs = options?.delayMs ?? DEFAULT_DELAY_MS;
45
+ const ttlDays = options?.ttlDays;
46
+ const exclude = options?.exclude;
47
+ const current = i18n?.locale;
48
+ const siteLocales = i18n?.locales;
49
+ const localesKey = siteLocales?.join(',') ?? '';
50
+ const languagesKey = languages.join(',');
51
+ const eligible = enabled && !!current && (siteLocales?.length ?? 0) > 1 && languages.length > 0;
52
+
53
+ // The page must be visible and quiet for `delayMs` before anything appears.
54
+ useEffect(() => {
55
+ if (!eligible) return;
56
+ let timer: ReturnType<typeof setTimeout> | undefined;
57
+ const start = () => {
58
+ timer = setTimeout(() => setSettled(true), delayMs);
59
+ };
60
+ const onVisible = () => {
61
+ if (!document.hidden) {
62
+ document.removeEventListener('visibilitychange', onVisible);
63
+ start();
64
+ }
65
+ };
66
+ if (document.hidden) document.addEventListener('visibilitychange', onVisible);
67
+ else start();
68
+ return () => {
69
+ clearTimeout(timer);
70
+ document.removeEventListener('visibilitychange', onVisible);
71
+ };
72
+ }, [eligible, delayMs]);
73
+
74
+ // Decide once per (languages, locale): record the page view, then ask the pure rule.
75
+ useEffect(() => {
76
+ if (!eligible || !current || !siteLocales) {
77
+ setTarget(null);
78
+ return;
79
+ }
80
+ if (isAutomated(navigator.userAgent, navigator.webdriver)) {
81
+ setTarget(null);
82
+ return;
83
+ }
84
+ const now = Date.now();
85
+ const input = { browserLanguages: languages, siteLocales, current, ttlDays };
86
+ const memory = reconcileMemory(readMemory(), { current, candidate: suggestLocale(input), now, ttlDays });
87
+ writeMemory(memory);
88
+ setTarget(decideSuggestion({ ...input, memory, now }));
89
+ // `languages` and `siteLocales` are keyed by their content: a new array with the same tags must not re-run this.
90
+ // eslint-disable-next-line react-hooks/exhaustive-deps
91
+ }, [eligible, current, languagesKey, localesKey, ttlDays]);
92
+
93
+ const excluded = useMemo(() => isExcludedPath(pathname, exclude), [pathname, exclude]);
94
+
95
+ if (!settled || !target || excluded) return null;
96
+ const browserLanguage = languages[0] ?? target;
97
+
98
+ const close = () => {
99
+ writeMemory(dismissPair(readMemory(), target, i18n.locale, Date.now()));
100
+ setTarget(null);
101
+ };
102
+
103
+ return (
104
+ <LocaleSuggestionView
105
+ browserLanguage={browserLanguage}
106
+ target={target}
107
+ onSwitch={() => {
108
+ setTarget(null);
109
+ i18n.onLocaleChange(target);
110
+ }}
111
+ onDismiss={close}
112
+ />
113
+ );
114
+ }
@@ -0,0 +1,56 @@
1
+ 'use client';
2
+
3
+ import { Banner, BannerActions, BannerClose, BannerContent, BannerTitle, Button } from '@djangocfg/ui-core/components';
4
+ import { cn } from '@djangocfg/ui-core/lib';
5
+
6
+ import { getLocaleMeta } from '../../layouts/_components/locale-switcher/localeMeta';
7
+ import { fill, useLocaleSuggestionCopy } from './i18n';
8
+
9
+ export interface LocaleSuggestionViewProps {
10
+ /** The visitor's browser language tag: the card is written in it. */
11
+ browserLanguage: string;
12
+ /** The site locale on offer; named in its own language. */
13
+ target: string;
14
+ onSwitch: () => void;
15
+ onDismiss: () => void;
16
+ className?: string;
17
+ }
18
+
19
+ /**
20
+ * The hint card. Fixed, so it never moves the page; a polite status, so it never takes focus; Esc inside it closes it.
21
+ * It speaks the visitor's language (`lang`, `dir`), not the page's.
22
+ */
23
+ export function LocaleSuggestionView({ browserLanguage, target, onSwitch, onDismiss, className }: LocaleSuggestionViewProps) {
24
+ const copy = useLocaleSuggestionCopy(browserLanguage);
25
+ const language = getLocaleMeta(target).native;
26
+ const rtl = getLocaleMeta(browserLanguage).rtl === true;
27
+
28
+ return (
29
+ <Banner
30
+ lang={browserLanguage}
31
+ dir={rtl ? 'rtl' : 'ltr'}
32
+ data-locale-suggestion=""
33
+ onKeyDown={(event) => {
34
+ if (event.key === 'Escape') onDismiss();
35
+ }}
36
+ onOpenChange={(open) => {
37
+ if (!open) onDismiss();
38
+ }}
39
+ className={cn(
40
+ 'fixed inset-x-4 bottom-4 z-50 w-auto flex-col items-stretch gap-3 rounded-lg border shadow-lg',
41
+ 'md:inset-x-auto md:end-4 md:w-96',
42
+ className,
43
+ )}
44
+ >
45
+ <BannerContent>
46
+ <BannerTitle className="leading-snug">{fill(copy.title, { language })}</BannerTitle>
47
+ </BannerContent>
48
+ <BannerActions className="justify-between">
49
+ <Button size="sm" onClick={onSwitch}>
50
+ {fill(copy.switch, { language })}
51
+ </Button>
52
+ <BannerClose aria-label={copy.dismiss} title={copy.dismiss} />
53
+ </BannerActions>
54
+ </Banner>
55
+ );
56
+ }
@@ -0,0 +1,37 @@
1
+ # LocaleSuggestion
2
+
3
+ The "This page is available in Deutsch" hint. `BaseApp` mounts it; an app that already passes `i18n` has nothing to do.
4
+
5
+ ```tsx
6
+ <BaseApp i18n={{ locale, locales, onLocaleChange, routing }}> {/* hint is on */}
7
+ <BaseApp i18n={{ ..., suggestion: false }}> {/* off */}
8
+ <BaseApp i18n={{ ..., suggestion: { exclude: [/^\/[a-z]{2}\/legal/], delayMs: 2000, ttlDays: 90 } }}>
9
+ ```
10
+
11
+ ## When it shows
12
+
13
+ The first browser language (`navigator.languages`, in order) that the site speaks decides. It is offered only if that
14
+ language is not the page's own. `de-AT` offers `de`; `pt` offers `pt-BR`; `en-GB` on `en` says nothing; a language the
15
+ site lacks says nothing (no nearest guess). One-language sites, crawlers and automation get nothing. The card is fixed
16
+ (no layout shift), appears 1.5 s after the page settles and the tab is visible, and never takes focus. Esc inside it,
17
+ or the close button, dismisses.
18
+
19
+ ## What it remembers
20
+
21
+ One key, `cfg.ui.locale_hint` (`CFG_KEYS.uiLocaleHint`, via `cfgStorage`): the last site locale shown and the dismissed
22
+ pairs `"<offered>><shown>"` with a date. A dismissal silences that pair for `ttlDays` (180), not the hint in general.
23
+ Switching language yourself (switcher, URL, the button) closes the pair too.
24
+
25
+ ## `exclude`
26
+
27
+ Pathname prefixes or RegExps matched against `location.pathname` **including the locale prefix** (`/en/legal`). Use it
28
+ for pages whose language is fixed by meaning.
29
+
30
+ ## Copy
31
+
32
+ Self-contained, 17 locales in `i18n/locales/`, written in the **browser's** language (the card carries `lang` and `dir`)
33
+ with the target named in its own (`getLocaleMeta(code).native`). A browser language without a bundled dictionary reads
34
+ English. Add a string to `i18n/types.ts` and all 17 files; `dictionaries.test.ts` checks it.
35
+
36
+ Logic is in `decide.ts` (pure, tested), storage in `memory.ts`. Plan and rejected alternatives:
37
+ `frontend/@dev/active/locale-suggestion/PLAN.md`.
@@ -0,0 +1,148 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import {
4
+ decideSuggestion,
5
+ dismissPair,
6
+ emptyMemory,
7
+ isAutomated,
8
+ isExcludedPath,
9
+ matchSiteLocale,
10
+ MAX_PAIRS,
11
+ reconcileMemory,
12
+ suggestLocale,
13
+ } from './decide';
14
+
15
+ const DAY = 24 * 60 * 60 * 1000;
16
+ const NOW = Date.UTC(2026, 10, 14);
17
+ const SITE = ['en', 'ru', 'de', 'pt-BR'];
18
+
19
+ const decide = (over: Partial<Parameters<typeof decideSuggestion>[0]> = {}) =>
20
+ decideSuggestion({ browserLanguages: ['de'], siteLocales: SITE, current: 'en', memory: emptyMemory(), now: NOW, ...over });
21
+
22
+ describe('matchSiteLocale', () => {
23
+ it.each([
24
+ ['de', 'de', true],
25
+ ['DE', 'de', true],
26
+ ['pt-br', 'pt-BR', true],
27
+ ['de-AT', 'de', false],
28
+ ['pt', 'pt-BR', false],
29
+ ['pt-PT', 'pt-BR', false],
30
+ ['nb', null, false],
31
+ ['fi', null, false],
32
+ ['', null, false],
33
+ ])('%s -> %s', (tag, locale, exact) => {
34
+ const hit = matchSiteLocale(tag, SITE);
35
+ expect(hit?.locale ?? null).toBe(locale);
36
+ if (hit) expect(hit.exact).toBe(exact);
37
+ });
38
+
39
+ it('maps nb and nn to the site no', () => {
40
+ expect(matchSiteLocale('nb-NO', ['en', 'no'])?.locale).toBe('no');
41
+ expect(matchSiteLocale('nn', ['en', 'no'])?.locale).toBe('no');
42
+ });
43
+
44
+ it('never turns Traditional Chinese into Simplified', () => {
45
+ expect(matchSiteLocale('zh-TW', ['en', 'zh-CN'])).toBeNull();
46
+ expect(matchSiteLocale('zh', ['en', 'zh-CN'])?.locale).toBe('zh-CN');
47
+ });
48
+ });
49
+
50
+ describe('suggestLocale', () => {
51
+ it('offers the first browser language the site speaks', () => {
52
+ expect(decide()).toBe('de');
53
+ expect(decide({ browserLanguages: ['fi', 'ru', 'de'] })).toBe('ru');
54
+ });
55
+
56
+ it('says nothing when the top supported language is already the page', () => {
57
+ expect(decide({ browserLanguages: ['en', 'de'] })).toBeNull();
58
+ expect(decide({ browserLanguages: ['fi', 'en', 'de'] })).toBeNull();
59
+ });
60
+
61
+ it('says nothing when the site has none of the browser languages', () => {
62
+ expect(decide({ browserLanguages: ['fi', 'sv'] })).toBeNull();
63
+ expect(decide({ browserLanguages: [] })).toBeNull();
64
+ });
65
+
66
+ it('says nothing for a one-language site', () => {
67
+ expect(decide({ siteLocales: ['en'], current: 'en' })).toBeNull();
68
+ expect(decide({ siteLocales: [], current: 'en' })).toBeNull();
69
+ });
70
+
71
+ it('maps a regional browser tag to the site language (de-AT -> de)', () => {
72
+ expect(decide({ browserLanguages: ['de-AT'] })).toBe('de');
73
+ });
74
+
75
+ it('does not interrupt for a regional variant of the page language', () => {
76
+ expect(decide({ browserLanguages: ['en-GB'] })).toBeNull();
77
+ expect(decide({ browserLanguages: ['pt-PT'], current: 'pt-BR' })).toBeNull();
78
+ });
79
+
80
+ it('offers a regional variant the site itself has', () => {
81
+ const site = ['en-US', 'en-GB', 'ru'];
82
+ expect(suggestLocale({ browserLanguages: ['en-GB'], siteLocales: site, current: 'en-US' })).toBe('en-GB');
83
+ });
84
+ });
85
+
86
+ describe('memory', () => {
87
+ it('a dismissed pair stays silent', () => {
88
+ const memory = dismissPair(emptyMemory(), 'de', 'en', NOW);
89
+ expect(decide({ memory, now: NOW + DAY })).toBeNull();
90
+ });
91
+
92
+ it('a dismissal is per pair: another current locale or another browser language asks again', () => {
93
+ const memory = dismissPair(emptyMemory(), 'de', 'en', NOW);
94
+ expect(decide({ memory, current: 'ru' })).toBe('de');
95
+ expect(decide({ memory, browserLanguages: ['ru'] })).toBe('ru');
96
+ });
97
+
98
+ it('a dismissal expires after the ttl', () => {
99
+ const memory = dismissPair(emptyMemory(), 'de', 'en', NOW);
100
+ expect(decide({ memory, now: NOW + 179 * DAY })).toBeNull();
101
+ expect(decide({ memory, now: NOW + 181 * DAY })).toBe('de');
102
+ expect(decide({ memory, now: NOW + 8 * DAY, ttlDays: 7 })).toBe('de');
103
+ });
104
+
105
+ it('records the locale shown; the first visit closes nothing', () => {
106
+ const next = reconcileMemory(emptyMemory(), { current: 'en', candidate: 'de', now: NOW });
107
+ expect(next).toEqual({ v: 1, seen: 'en', dismissed: {} });
108
+ });
109
+
110
+ it('a locale change by the visitor counts as consent', () => {
111
+ // Was on en, now on ru while the browser prefers de: they picked ru, do not nag.
112
+ const next = reconcileMemory({ v: 1, seen: 'en', dismissed: {} }, { current: 'ru', candidate: 'de', now: NOW });
113
+ expect(next.dismissed['de>ru']).toBe(NOW);
114
+ expect(decide({ memory: next, current: 'ru' })).toBeNull();
115
+ });
116
+
117
+ it('staying on the same locale closes nothing', () => {
118
+ const next = reconcileMemory({ v: 1, seen: 'en', dismissed: {} }, { current: 'en', candidate: 'de', now: NOW });
119
+ expect(next.dismissed).toEqual({});
120
+ });
121
+
122
+ it('drops expired pairs and keeps the newest MAX_PAIRS', () => {
123
+ const dismissed: Record<string, number> = { 'old>x': NOW - 400 * DAY };
124
+ for (let i = 0; i < MAX_PAIRS + 5; i += 1) dismissed[`p${i}>x`] = NOW - i * 1000;
125
+ const next = reconcileMemory({ v: 1, seen: 'en', dismissed }, { current: 'en', candidate: null, now: NOW });
126
+ expect(Object.keys(next.dismissed)).toHaveLength(MAX_PAIRS);
127
+ expect(next.dismissed['old>x']).toBeUndefined();
128
+ expect(next.dismissed['p0>x']).toBe(NOW);
129
+ });
130
+ });
131
+
132
+ describe('guards', () => {
133
+ it('recognises crawlers and automation', () => {
134
+ expect(isAutomated('Mozilla/5.0 (compatible; Googlebot/2.1)', false)).toBe(true);
135
+ expect(isAutomated('HeadlessChrome/120', false)).toBe(true);
136
+ expect(isAutomated('Mozilla/5.0 Safari', true)).toBe(true);
137
+ expect(isAutomated('Mozilla/5.0 (iPhone; CPU iPhone OS 18_0) Safari/605.1', false)).toBe(false);
138
+ expect(isAutomated(undefined, undefined)).toBe(false);
139
+ });
140
+
141
+ it('matches excluded paths by prefix or pattern', () => {
142
+ expect(isExcludedPath('/en/legal/terms', ['/en/legal'])).toBe(true);
143
+ expect(isExcludedPath('/en/pricing', ['/en/legal'])).toBe(false);
144
+ expect(isExcludedPath('/ru/legal', [/^\/[a-z]{2}\/legal/g])).toBe(true);
145
+ expect(isExcludedPath('/ru/legal', [/^\/[a-z]{2}\/legal/g])).toBe(true);
146
+ expect(isExcludedPath('/x', undefined)).toBe(false);
147
+ });
148
+ });
@@ -0,0 +1,152 @@
1
+ /**
2
+ * The decision behind the locale hint: pure, no React, no storage, so every rule is a table row in a test.
3
+ * Product rules and the rejected alternatives: `@dev/active/locale-suggestion/PLAN.md`.
4
+ */
5
+
6
+ export const DEFAULT_TTL_DAYS = 180;
7
+ /** Dismissed pairs kept in storage; the oldest are dropped first. */
8
+ export const MAX_PAIRS = 24;
9
+ const DAY_MS = 24 * 60 * 60 * 1000;
10
+
11
+ /** What the browser remembers between visits (stored under `CFG_KEYS.uiLocaleHint`). */
12
+ export interface SuggestionMemory {
13
+ v: 1;
14
+ /** The last site locale this browser showed. A different one now means the visitor chose it. */
15
+ seen?: string;
16
+ /** `"<site locale suggested>><site locale shown>"` → when it was dismissed (epoch ms). */
17
+ dismissed: Record<string, number>;
18
+ }
19
+
20
+ export const emptyMemory = (): SuggestionMemory => ({ v: 1, dismissed: {} });
21
+
22
+ /** Language tags hosts report that name a site locale under another code (same table as `resolveLocale`). */
23
+ const ALIASES: Readonly<Record<string, string>> = { nb: 'no', nn: 'no' };
24
+
25
+ const norm = (tag: string): string => tag.trim().replace('_', '-').toLowerCase();
26
+ const baseOf = (tag: string): string => norm(tag).split('-')[0] ?? '';
27
+
28
+ export interface SiteMatch {
29
+ /** The site's own spelling of the locale (`pt-BR`). */
30
+ locale: string;
31
+ /** The browser tag named this very locale, not just its language. */
32
+ exact: boolean;
33
+ }
34
+
35
+ /**
36
+ * The site locale a browser language tag points at, or `null`.
37
+ * Exact tag, then alias (`nb` → `no`), then the base language (`de-AT` → `de`), then a sibling of the same language
38
+ * (`pt` → `pt-BR`). Chinese siblings are never guessed (`zh-TW` is not `zh-CN`). No "nearest language" beyond that:
39
+ * a language the site does not have is silence, not a guess.
40
+ */
41
+ export function matchSiteLocale(tag: string, siteLocales: readonly string[]): SiteMatch | null {
42
+ const wanted = norm(tag);
43
+ if (!wanted) return null;
44
+ const byLower = new Map(siteLocales.map((l) => [norm(l), l] as const));
45
+
46
+ const exact = byLower.get(wanted);
47
+ if (exact) return { locale: exact, exact: true };
48
+
49
+ const base = baseOf(wanted);
50
+ const aliased = byLower.get(ALIASES[wanted] ?? ALIASES[base] ?? '');
51
+ if (aliased) return { locale: aliased, exact: false };
52
+
53
+ const baseHit = byLower.get(base);
54
+ if (baseHit) return { locale: baseHit, exact: false };
55
+
56
+ const hasRegion = wanted.includes('-');
57
+ if (base === 'zh' && hasRegion) return null;
58
+ const sibling = siteLocales.find((l) => baseOf(l) === base);
59
+ return sibling ? { locale: sibling, exact: false } : null;
60
+ }
61
+
62
+ export interface CandidateInput {
63
+ /** `navigator.languages`, preferred first. */
64
+ browserLanguages: readonly string[];
65
+ siteLocales: readonly string[];
66
+ /** The locale the page is shown in. */
67
+ current: string;
68
+ }
69
+
70
+ /**
71
+ * The language to offer, ignoring memory. The first browser language the site speaks decides:
72
+ * if that is already the page's language the visitor is served and nothing is offered, even when a lower-ranked
73
+ * language differs. A regional variant of the page's language (`en-GB` on `en`) is not a reason to interrupt,
74
+ * unless the site itself offers that exact variant.
75
+ */
76
+ export function suggestLocale({ browserLanguages, siteLocales, current }: CandidateInput): string | null {
77
+ if (siteLocales.length < 2) return null;
78
+ for (const tag of browserLanguages) {
79
+ const hit = matchSiteLocale(tag, siteLocales);
80
+ if (!hit) continue;
81
+ if (norm(hit.locale) === norm(current)) return null;
82
+ if (baseOf(hit.locale) === baseOf(current) && !hit.exact) return null;
83
+ return hit.locale;
84
+ }
85
+ return null;
86
+ }
87
+
88
+ export const pairKey = (suggested: string, current: string): string => `${norm(suggested)}>${norm(current)}`;
89
+
90
+ /**
91
+ * Memory after this page view. Records `seen`; and when the visitor is on a different locale than last time, they
92
+ * chose it (switcher, URL or our own button), so the pair is closed as if dismissed. Expired and surplus pairs go.
93
+ */
94
+ export function reconcileMemory(
95
+ memory: SuggestionMemory,
96
+ input: { current: string; candidate: string | null; now: number; ttlDays?: number },
97
+ ): SuggestionMemory {
98
+ const ttl = (input.ttlDays ?? DEFAULT_TTL_DAYS) * DAY_MS;
99
+ let dismissed = { ...memory.dismissed };
100
+ if (memory.seen && norm(memory.seen) !== norm(input.current) && input.candidate) {
101
+ dismissed[pairKey(input.candidate, input.current)] = input.now;
102
+ }
103
+ const live = Object.entries(dismissed)
104
+ .filter(([, at]) => input.now - at < ttl)
105
+ .sort((a, b) => b[1] - a[1])
106
+ .slice(0, MAX_PAIRS);
107
+ dismissed = Object.fromEntries(live);
108
+ return { v: 1, seen: input.current, dismissed };
109
+ }
110
+
111
+ /** Memory after the visitor closed the hint for this pair. */
112
+ export function dismissPair(
113
+ memory: SuggestionMemory,
114
+ suggested: string,
115
+ current: string,
116
+ now: number,
117
+ ): SuggestionMemory {
118
+ return { ...memory, dismissed: { ...memory.dismissed, [pairKey(suggested, current)]: now } };
119
+ }
120
+
121
+ export interface DecideInput extends CandidateInput {
122
+ memory: SuggestionMemory;
123
+ now: number;
124
+ ttlDays?: number;
125
+ }
126
+
127
+ /** The locale to offer now, or `null`. */
128
+ export function decideSuggestion(input: DecideInput): string | null {
129
+ const candidate = suggestLocale(input);
130
+ if (!candidate) return null;
131
+ const at = input.memory.dismissed[pairKey(candidate, input.current)];
132
+ const ttl = (input.ttlDays ?? DEFAULT_TTL_DAYS) * DAY_MS;
133
+ if (at !== undefined && input.now - at < ttl) return null;
134
+ return candidate;
135
+ }
136
+
137
+ const BOT_UA = /bot|crawl|spider|slurp|headless|lighthouse|pagespeed|preview|monitor|facebookexternalhit|python-requests|curl\//i;
138
+
139
+ /** Crawlers and automation get no hint: nothing to decide, nothing to render. */
140
+ export function isAutomated(userAgent: string | undefined, webdriver: boolean | undefined): boolean {
141
+ return webdriver === true || BOT_UA.test(userAgent ?? '');
142
+ }
143
+
144
+ /** True when `pathname` is covered by an `exclude` entry (string prefix or RegExp). */
145
+ export function isExcludedPath(pathname: string, exclude: readonly (string | RegExp)[] | undefined): boolean {
146
+ if (!exclude?.length) return false;
147
+ return exclude.some((rule) => {
148
+ if (typeof rule === 'string') return pathname.startsWith(rule);
149
+ rule.lastIndex = 0;
150
+ return rule.test(pathname);
151
+ });
152
+ }
@@ -0,0 +1,27 @@
1
+ import { join } from 'node:path';
2
+ import { checkDictionaries } from '@djangocfg/i18n/copy/testing';
3
+ import { describe, expect, it } from 'vitest';
4
+
5
+ import { LOCALE_SUGGESTION_DICTIONARIES } from './index';
6
+ import { en } from './locales/en';
7
+
8
+ describe('locale suggestion dictionaries', () => {
9
+ it('covers every locale, file, key and placeholder', () => {
10
+ expect(checkDictionaries(LOCALE_SUGGESTION_DICTIONARIES, join(import.meta.dirname, 'locales'))).toEqual([]);
11
+ });
12
+
13
+ it('is translated, not a copy of English', () => {
14
+ const same = Object.entries(LOCALE_SUGGESTION_DICTIONARIES)
15
+ .filter(([locale]) => locale !== 'en')
16
+ .flatMap(([locale, copy]) =>
17
+ (Object.keys(en) as (keyof typeof en)[])
18
+ .filter((key) => copy[key] === en[key])
19
+ .map((key) => `${locale}.${key}`),
20
+ );
21
+ expect(same).toEqual([]);
22
+ });
23
+
24
+ it('resolves pt-BR to Portuguese', () => {
25
+ expect(LOCALE_SUGGESTION_DICTIONARIES['pt-BR'].dismiss).toBe('Fechar');
26
+ });
27
+ });
@@ -0,0 +1,38 @@
1
+ 'use client';
2
+
3
+ import { createCopy, type Locale } from '@djangocfg/i18n/copy';
4
+
5
+ import { ar } from './locales/ar';
6
+ import { da } from './locales/da';
7
+ import { de } from './locales/de';
8
+ import { en } from './locales/en';
9
+ import { es } from './locales/es';
10
+ import { fr } from './locales/fr';
11
+ import { it } from './locales/it';
12
+ import { ja } from './locales/ja';
13
+ import { ko } from './locales/ko';
14
+ import { nl } from './locales/nl';
15
+ import { no } from './locales/no';
16
+ import { pl } from './locales/pl';
17
+ import { ptBR } from './locales/ptBR';
18
+ import { ru } from './locales/ru';
19
+ import { sv } from './locales/sv';
20
+ import { tr } from './locales/tr';
21
+ import { zh } from './locales/zh';
22
+
23
+ import type { LocaleSuggestionCopy } from './types';
24
+
25
+ export type { LocaleSuggestionCopy } from './types';
26
+ export { fill } from '@djangocfg/i18n/copy';
27
+
28
+ /** Every bundled dictionary, typed complete over the shared `Locale` union. */
29
+ export const LOCALE_SUGGESTION_DICTIONARIES: Readonly<Record<Locale, LocaleSuggestionCopy>> = {
30
+ en, ru, ko, ja, de, fr, zh, it, es, nl, ar, tr, pl, sv, no, da,
31
+ 'pt-BR': ptBR,
32
+ };
33
+
34
+ /**
35
+ * The hint speaks the VISITOR's language, not the page's: `useLocaleSuggestionCopy(browserTag)`.
36
+ * A tag with no bundled dictionary resolves to English.
37
+ */
38
+ export const useLocaleSuggestionCopy = createCopy(LOCALE_SUGGESTION_DICTIONARIES).useCopy;
@@ -0,0 +1,7 @@
1
+ import type { LocaleSuggestionCopy } from '../types';
2
+
3
+ export const ar: LocaleSuggestionCopy = {
4
+ title: "هذه الصفحة متاحة باللغة: {{language}}",
5
+ switch: "التبديل إلى {{language}}",
6
+ dismiss: "إغلاق",
7
+ };
@@ -0,0 +1,7 @@
1
+ import type { LocaleSuggestionCopy } from '../types';
2
+
3
+ export const da: LocaleSuggestionCopy = {
4
+ title: "Denne side findes på {{language}}",
5
+ switch: "Skift til {{language}}",
6
+ dismiss: "Luk",
7
+ };
@@ -0,0 +1,7 @@
1
+ import type { LocaleSuggestionCopy } from '../types';
2
+
3
+ export const de: LocaleSuggestionCopy = {
4
+ title: "Diese Seite ist in {{language}} verfügbar",
5
+ switch: "Zu {{language}} wechseln",
6
+ dismiss: "Schließen",
7
+ };
@@ -0,0 +1,7 @@
1
+ import type { LocaleSuggestionCopy } from '../types';
2
+
3
+ export const en: LocaleSuggestionCopy = {
4
+ title: "This page is available in {{language}}",
5
+ switch: "Switch to {{language}}",
6
+ dismiss: "Dismiss",
7
+ };
@@ -0,0 +1,7 @@
1
+ import type { LocaleSuggestionCopy } from '../types';
2
+
3
+ export const es: LocaleSuggestionCopy = {
4
+ title: "Esta página está disponible en {{language}}",
5
+ switch: "Cambiar a {{language}}",
6
+ dismiss: "Cerrar",
7
+ };
@@ -0,0 +1,7 @@
1
+ import type { LocaleSuggestionCopy } from '../types';
2
+
3
+ export const fr: LocaleSuggestionCopy = {
4
+ title: "Cette page est disponible en {{language}}",
5
+ switch: "Passer à {{language}}",
6
+ dismiss: "Fermer",
7
+ };
@@ -0,0 +1,7 @@
1
+ import type { LocaleSuggestionCopy } from '../types';
2
+
3
+ export const it: LocaleSuggestionCopy = {
4
+ title: "Questa pagina è disponibile in {{language}}",
5
+ switch: "Passa a {{language}}",
6
+ dismiss: "Chiudi",
7
+ };
@@ -0,0 +1,7 @@
1
+ import type { LocaleSuggestionCopy } from '../types';
2
+
3
+ export const ja: LocaleSuggestionCopy = {
4
+ title: "このページは{{language}}でも利用できます",
5
+ switch: "{{language}}に切り替える",
6
+ dismiss: "閉じる",
7
+ };
@@ -0,0 +1,7 @@
1
+ import type { LocaleSuggestionCopy } from '../types';
2
+
3
+ export const ko: LocaleSuggestionCopy = {
4
+ title: "{{language}} 버전을 이용할 수 있습니다",
5
+ switch: "전환: {{language}}",
6
+ dismiss: "닫기",
7
+ };
@@ -0,0 +1,7 @@
1
+ import type { LocaleSuggestionCopy } from '../types';
2
+
3
+ export const nl: LocaleSuggestionCopy = {
4
+ title: "Deze pagina is beschikbaar in {{language}}",
5
+ switch: "Overschakelen naar {{language}}",
6
+ dismiss: "Sluiten",
7
+ };
@@ -0,0 +1,7 @@
1
+ import type { LocaleSuggestionCopy } from '../types';
2
+
3
+ export const no: LocaleSuggestionCopy = {
4
+ title: "Denne siden finnes på {{language}}",
5
+ switch: "Bytt til {{language}}",
6
+ dismiss: "Lukk",
7
+ };
@@ -0,0 +1,7 @@
1
+ import type { LocaleSuggestionCopy } from '../types';
2
+
3
+ export const pl: LocaleSuggestionCopy = {
4
+ title: "Ta strona jest dostępna w języku: {{language}}",
5
+ switch: "Przełącz na {{language}}",
6
+ dismiss: "Zamknij",
7
+ };
@@ -0,0 +1,7 @@
1
+ import type { LocaleSuggestionCopy } from '../types';
2
+
3
+ export const ptBR: LocaleSuggestionCopy = {
4
+ title: "Esta página está disponível em {{language}}",
5
+ switch: "Mudar para {{language}}",
6
+ dismiss: "Fechar",
7
+ };
@@ -0,0 +1,7 @@
1
+ import type { LocaleSuggestionCopy } from '../types';
2
+
3
+ export const ru: LocaleSuggestionCopy = {
4
+ title: "Эта страница доступна на языке: {{language}}",
5
+ switch: "Перейти: {{language}}",
6
+ dismiss: "Закрыть",
7
+ };
@@ -0,0 +1,7 @@
1
+ import type { LocaleSuggestionCopy } from '../types';
2
+
3
+ export const sv: LocaleSuggestionCopy = {
4
+ title: "Den här sidan finns på {{language}}",
5
+ switch: "Byt till {{language}}",
6
+ dismiss: "Stäng",
7
+ };
@@ -0,0 +1,7 @@
1
+ import type { LocaleSuggestionCopy } from '../types';
2
+
3
+ export const tr: LocaleSuggestionCopy = {
4
+ title: "Bu sayfa {{language}} dilinde de mevcut",
5
+ switch: "{{language}} diline geç",
6
+ dismiss: "Kapat",
7
+ };
@@ -0,0 +1,7 @@
1
+ import type { LocaleSuggestionCopy } from '../types';
2
+
3
+ export const zh: LocaleSuggestionCopy = {
4
+ title: "本页面提供{{language}}版本",
5
+ switch: "切换到{{language}}",
6
+ dismiss: "关闭",
7
+ };
@@ -0,0 +1,9 @@
1
+ /** Strings of the locale hint. English is the schema of record; `{{language}}` is the target language's own name. */
2
+ export interface LocaleSuggestionCopy {
3
+ /** "This page is available in {{language}}" */
4
+ title: string;
5
+ /** Primary button: "Switch to {{language}}" */
6
+ switch: string;
7
+ /** Accessible name of the close button. */
8
+ dismiss: string;
9
+ }
@@ -0,0 +1,5 @@
1
+ export { LocaleSuggestion } from './LocaleSuggestion';
2
+ export { LocaleSuggestionView } from './LocaleSuggestionView';
3
+ export type { LocaleSuggestionViewProps } from './LocaleSuggestionView';
4
+ export { decideSuggestion, matchSiteLocale } from './decide';
5
+ export type { SuggestionMemory } from './decide';
@@ -0,0 +1,23 @@
1
+ import { CFG_KEYS, cfgStorage } from '@djangocfg/api/storage';
2
+
3
+ import { emptyMemory, type SuggestionMemory } from './decide';
4
+
5
+ const SPEC = CFG_KEYS.uiLocaleHint;
6
+
7
+ /** The stored memory; anything malformed reads as empty and is overwritten on the next write. */
8
+ export function readMemory(): SuggestionMemory {
9
+ const raw = cfgStorage.readJSON<unknown>(SPEC.key, SPEC.store);
10
+ if (!raw || typeof raw !== 'object') return emptyMemory();
11
+ const { seen, dismissed } = raw as { seen?: unknown; dismissed?: unknown };
12
+ const pairs: Record<string, number> = {};
13
+ if (dismissed && typeof dismissed === 'object') {
14
+ for (const [key, at] of Object.entries(dismissed)) {
15
+ if (typeof at === 'number' && Number.isFinite(at)) pairs[key] = at;
16
+ }
17
+ }
18
+ return { v: 1, seen: typeof seen === 'string' ? seen : undefined, dismissed: pairs };
19
+ }
20
+
21
+ export function writeMemory(memory: SuggestionMemory): void {
22
+ cfgStorage.writeJSON(SPEC.key, memory, SPEC.store);
23
+ }
@@ -14,4 +14,6 @@ export * from './errors';
14
14
  export * from './RedirectPage';
15
15
 
16
16
  // ErrorsTracker
17
- export * from './errors/ErrorsTracker';
17
+ export * from './errors/ErrorsTracker';
18
+ // Locale hint (mounted by BaseApp)
19
+ export * from './LocaleSuggestion';
@@ -15,6 +15,7 @@
15
15
  * - AuthProvider (authentication context)
16
16
  * - AuthDialog (global auth prompt dialog)
17
17
  * - AnalyticsProvider (Google Analytics, optional)
18
+ * - LocaleSuggestion (offers the visitor's language when `i18n` has several locales)
18
19
  * - PwaProvider (PWA installation, optional)
19
20
  * - ErrorTrackingProvider (error handling)
20
21
  * - ErrorBoundary (React error boundary, enabled by default)
@@ -61,6 +62,7 @@ import { AuthDialog } from '../../snippets/AuthDialog';
61
62
 
62
63
  import type { BaseLayoutProps } from '../types/layout.types';
63
64
  import { LayoutI18nProvider } from '../../shared/LayoutI18nProvider';
65
+ import { LocaleSuggestion } from '../../components/LocaleSuggestion';
64
66
  import { ProjectNameProvider } from '../../shared/ProjectContext';
65
67
  import { PwaManifestCheck, PwaMetaGuard } from './pwaMeta';
66
68
  import { resolveDevtoolsBaseUrl } from './devtoolsBaseUrl';
@@ -188,6 +190,7 @@ export function BaseApp({
188
190
  ) : (
189
191
  children
190
192
  )}
193
+ <LocaleSuggestion />
191
194
  </ProjectNameProvider>
192
195
  </LayoutI18nProvider>
193
196
  {/* Auth Dialog - only when auth is enabled */}
@@ -51,6 +51,7 @@ export type {
51
51
  BaseLayoutProps,
52
52
  DevtoolsConfig,
53
53
  I18nLayoutConfig,
54
+ LocaleSuggestionOptions,
54
55
  LayoutVisualVariant,
55
56
  LayoutVisualConfig,
56
57
  LayoutBoxedRadius,
@@ -160,6 +160,22 @@ export interface I18nLayoutConfig {
160
160
  * sent back to the default locale on every navbar / footer click.
161
161
  */
162
162
  routing?: NextIntlRouting;
163
+ /**
164
+ * The "this page is available in <your language>" hint shown when the browser's language is a site locale other than
165
+ * the current one. On by default when `locales.length > 1` (nothing renders for a one-language site); `false` turns it
166
+ * off for the app. An object tunes it.
167
+ */
168
+ suggestion?: false | LocaleSuggestionOptions;
169
+ }
170
+
171
+ /** Tuning for the locale hint (`I18nLayoutConfig.suggestion`). */
172
+ export interface LocaleSuggestionOptions {
173
+ /** Pathname prefixes or patterns where the language is fixed by meaning (legal text, a translated landing); never shown there. */
174
+ exclude?: (string | RegExp)[];
175
+ /** Quiet time after the page settles before the hint appears. Default 1500 ms. */
176
+ delayMs?: number;
177
+ /** How long a dismissal for one language pair is remembered. Default 180 days. */
178
+ ttlDays?: number;
163
179
  }
164
180
 
165
181
  // ============================================================================