Let visitors choose their country, grouped by the site's regions (#4856)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
conico974
2026-11-27 11:20:40 +01:00
committed by GitHub
parent dda28fc436
commit 0f7ca03599
55 changed files with 1373 additions and 48 deletions
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": minor
---
Let visitors choose their country in a country picker, overriding the detected one, on sites that enable it and declare regions. Countries are grouped by the site's regions, then under "Other".
@@ -19,7 +19,7 @@ export function AnnotationPopover(props: { children: React.ReactNode; body: Reac
>
<dfn
data-annotation=""
className="not-italic cursor-help underline decoration-dotted decoration-1 underline-offset-2"
className="cursor-help not-italic underline decoration-dotted decoration-1 underline-offset-2"
// oxlint-disable-next-line jsx-a11y/no-noninteractive-tabindex -- we want to be able to focus the definition to open the tooltip
tabIndex={0}
>
@@ -3,6 +3,7 @@ import type { Metadata } from 'next';
import { SiteInsightsDisplayContext } from '@gitbook/api';
import { PaginatedUpdatesProvider } from '../DocumentView/PaginatedUpdates';
import { CountryPicker } from '../Header/CountryPicker';
import { HeaderMobileMenu } from '../Header/HeaderMobileMenu';
import { SpacesDropdown, TranslationsDropdown } from '../Header/SpacesDropdown';
import { PageBody } from '../PageBody';
@@ -84,6 +85,19 @@ export async function EmbeddableDocsPage(
const variants = categorizeVariants(context);
const pageInput = { linker: context.linker, pages: context.revision.pages, page };
const translationsDropdown =
variants.translations.length > 1 ? (
<TranslationsDropdown
context={context}
siteSpace={
variants.translations.find((space) => space.id === context.siteSpace.id) ??
context.siteSpace
}
siteSpaces={variants.translations}
asEmbeddable
className="max-md:[&_.button-content]:block"
/>
) : null;
return (
<EmbeddableFrame className="site-background">
@@ -120,6 +134,12 @@ export async function EmbeddableDocsPage(
asEmbeddable: true,
})}
>
{context.countryPicker ? (
<CountryPicker
context={context}
className="my-1.5 ml-2 self-start"
/>
) : null}
{variants.translations.length > 1 ? (
<TranslationsDropdown
context={context}
@@ -149,18 +169,16 @@ export async function EmbeddableDocsPage(
context={context}
withTrademark={false}
header={
!context.sections && variants.translations.length > 1 ? (
<TranslationsDropdown
context={context}
siteSpace={
variants.translations.find(
(space) => space.id === context.siteSpace.id
) ?? context.siteSpace
}
siteSpaces={variants.translations}
asEmbeddable
className="max-md:[&_.button-content]:block"
/>
!context.sections && context.countryPicker ? (
<div className="flex flex-wrap items-center gap-2">
<CountryPicker
context={context}
className="max-md:[&_.button-content]:block"
/>
{translationsDropdown}
</div>
) : !context.sections ? (
translationsDropdown
) : null
}
innerHeader={
@@ -0,0 +1,33 @@
import type { ButtonProps } from '../primitives';
import { CountryPickerClient } from './CountryPickerClient';
import { getContentLocale } from '@/intl/server';
import type { GitBookSiteContext } from '@/lib/context';
import { tcls } from '@/lib/tailwind';
import { VISITOR_COUNTRY_PATH } from '@/lib/visitor-country';
/**
* Dropdown letting the visitor override the country detected for them.
*/
export function CountryPicker(props: {
context: GitBookSiteContext;
className?: string;
variant?: ButtonProps['variant'];
}) {
const { context, className, variant = 'blank' } = props;
if (!context.countryPicker) {
return null;
}
return (
<CountryPickerClient
locale={getContentLocale(context)}
regions={context.countryPicker}
visitorCountryURL={context.linker.toPathInSite(VISITOR_COUNTRY_PATH)}
variant={variant}
className={tcls(
'bg-transparent lg:max-w-64 max-md:[&_.button-content]:hidden',
className
)}
/>
);
}
@@ -0,0 +1,297 @@
'use client';
import { Combobox } from '@base-ui/react/combobox';
import * as React from 'react';
import { Icon } from '@gitbook/icons';
import { Button, type ButtonProps, ToggleChevron } from '../primitives';
import { DROPDOWN_POPUP_CLASS, DROPDOWN_POSITIONER_CLASS } from '../primitives/DropdownMenu';
import { tString, useLanguage } from '@/intl/client';
import {
COUNTRY_CODES,
getCountryFlag,
getCountryLocales,
getCountryName,
groupCountriesByRegion,
normalizeCountryCode,
parseCountryChoice,
} from '@/lib/countries';
import { type ClassValue, tcls } from '@/lib/tailwind';
import { type SiteRegions, VISITOR_COUNTRY_PARAM } from '@/lib/visitor-country';
/** An entry of the picker. An empty value is the automatic choice. */
type CountryOption = { value: string; label: string; flag?: string };
/** A group of entries, under a heading unless it is the automatic choice's. */
type CountryOptionGroup = { value: string; label: string | null; items: CountryOption[] };
/** The visitor's countries, as returned by the middleware. */
type VisitorCountries = { detected: string | undefined; chosen: string | undefined };
const visitorCountriesRequests = new Map<string, Promise<VisitorCountries | null>>();
function fetchVisitorCountries(url: string): Promise<VisitorCountries | null> {
let request = visitorCountriesRequests.get(url);
if (!request) {
request = (async () => {
try {
const response = await fetch(url);
if (!response.ok) {
return null;
}
const data = await response.json<{
detected?: string | null;
chosen?: string | null;
}>();
return {
detected: normalizeCountryCode(data.detected),
chosen: parseCountryChoice(data.chosen),
};
} catch {
return null;
}
})();
visitorCountriesRequests.set(url, request);
// Retry on the next mount rather than keeping a transient failure.
request.then((result) => {
if (!result) {
visitorCountriesRequests.delete(url);
}
});
}
return request;
}
/**
* The visitor's detected and chosen countries: undefined while loading, null if they couldn't be fetched.
*/
function useVisitorCountries(url: string): VisitorCountries | null | undefined {
const [countries, setCountries] = React.useState<VisitorCountries | null | undefined>(
undefined
);
React.useEffect(() => {
let cancelled = false;
fetchVisitorCountries(url).then((result) => {
if (!cancelled) {
setCountries(result);
}
});
return () => {
cancelled = true;
};
}, [url]);
return countries;
}
export function CountryPickerClient(props: {
locale: string;
regions: SiteRegions;
visitorCountryURL: string;
variant: ButtonProps['variant'];
className?: ClassValue;
}) {
const { locale, regions, visitorCountryURL, variant, className } = props;
const language = useLanguage();
// Fetched rather than rendered, so static routes stay shared across countries.
const visitorCountries = useVisitorCountries(visitorCountryURL);
const isLoading = visitorCountries === undefined;
const chosen = visitorCountries?.chosen;
const detected = visitorCountries?.detected;
const detectedName = detected ? getCountryName(detected, locale) : undefined;
const locales = React.useMemo(() => getCountryLocales(locale), [locale]);
const filter = Combobox.useFilter({ locale: locales });
const otherLabel = tString(language, 'country_picker_other');
const countryGroups = React.useMemo(
() =>
groupCountriesByRegion(regions, COUNTRY_CODES, locale).map(
(group): CountryOptionGroup => ({
value: group.type === 'region' ? `region:${group.name}` : 'other',
label: group.type === 'region' ? group.label : otherLabel,
items: group.countries.map(({ code, name }) => ({
value: code,
label: name,
flag: getCountryFlag(code),
})),
})
),
[regions, locale, otherLabel]
);
const detectedRegion = detected
? countryGroups.find(
(group) =>
group.value !== 'other' && group.items.some((item) => item.value === detected)
)?.label
: undefined;
const automaticOption: CountryOption = {
value: '',
label:
detected && detectedName
? tString(
language,
'country_picker_automatic_detected',
`${getCountryFlag(detected)} ${detectedName}${detectedRegion ? ` · ${detectedRegion}` : ''}`
)
: tString(language, 'country_picker_automatic'),
};
const options: CountryOptionGroup[] = [
{ value: 'automatic', label: null, items: [automaticOption] },
...countryGroups,
];
const selected =
(chosen &&
countryGroups
.flatMap((group) => group.items)
.find((option) => option.value === chosen)) ||
automaticOption;
const currentCountry = chosen ?? detected;
const currentName = chosen ? getCountryName(chosen, locale) : detectedName;
const buttonLabel = currentName ?? tString(language, 'country_picker_automatic');
const selectCountry = (option: CountryOption | null) => {
const country = option?.value || undefined;
if (!option || country === chosen) {
return;
}
// The middleware stores the choice in the site's cookie, then redirects to the URL without the param.
const url = new URL(window.location.href);
url.searchParams.set(VISITOR_COUNTRY_PARAM, country ?? '');
window.location.assign(url);
};
return (
<Combobox.Root
items={options}
value={selected}
onValueChange={selectCountry}
isItemEqualToValue={(item, value) => item.value === value.value}
filter={(option: CountryOption, query) =>
option.value
? filter.contains(option.label, query) ||
option.value === query.trim().toUpperCase()
: // The automatic entry names the detected country, which shouldn't match it.
query.trim() === ''
}
>
<Combobox.Trigger
render={
<Button
icon="location-dot"
data-testid="country-picker-button"
size="small"
variant={variant}
trailing={<ToggleChevron />}
className={tcls('group/dropdown bg-tint-base', className)}
aria-label={tString(language, 'country_picker_label', buttonLabel)}
aria-busy={isLoading || undefined}
>
<span className="button-content">
{isLoading ? (
// Until the countries are known, so the label doesn't flash "Automatic".
<span
aria-hidden
className="inline-block h-3 w-24 animate-[pulse_2s_infinite] rounded-sm bg-tint-solid/2 align-middle circular-corners:rounded-2xl"
/>
) : (
<>
{currentCountry && currentName ? (
<span aria-hidden className="me-1.5">
{getCountryFlag(currentCountry)}
</span>
) : null}
{buttonLabel}
{!chosen && currentName ? (
<span className="ms-1.5 text-xs text-tint-subtle">
{tString(language, 'country_picker_auto_hint')}
</span>
) : null}
</>
)}
</span>
</Button>
}
/>
<Combobox.Portal>
<Combobox.Positioner
collisionPadding={8}
align="start"
className={DROPDOWN_POSITIONER_CLASS}
>
<Combobox.Popup
data-testid="country-picker-popup"
className={tcls(
DROPDOWN_POPUP_CLASS,
'w-80 max-w-[calc(100vw-1rem)] overflow-hidden'
)}
>
<div className="relative flex shrink-0 items-center">
<Icon
icon="magnifying-glass"
className="pointer-events-none absolute start-2.5 size-3.5 text-tint-subtle"
/>
<Combobox.Input
placeholder={tString(language, 'country_picker_search')}
aria-label={tString(language, 'country_picker_search')}
// Under 16px, iOS zooms into the page when the input gets focus.
className="outline-hidden w-full rounded-sm border border-tint bg-tint-base py-1.5 pe-3 ps-8 text-base text-tint-strong placeholder:text-tint-subtle focus:border-primary straight-corners:rounded-none circular-corners:rounded-lg md:text-sm"
/>
</div>
<Combobox.Empty className="px-3 py-1 text-sm text-tint-subtle empty:hidden">
{tString(language, 'country_picker_no_results')}
</Combobox.Empty>
<Combobox.List className="flex min-h-0 flex-col gap-1 overflow-y-auto empty:hidden">
{(group: CountryOptionGroup) => (
<Combobox.Group
key={group.value}
items={group.items}
className="flex flex-col gap-1"
>
{group.label ? (
<Combobox.GroupLabel className="px-3 pb-0.5 pt-2 text-xs font-semibold uppercase text-tint-subtle">
{group.label}
</Combobox.GroupLabel>
) : null}
<Combobox.Collection>
{(option: CountryOption) => (
<Combobox.Item
key={option.value}
value={option}
className="data-selected:text-primary-strong data-highlighted:bg-tint-hover flex cursor-pointer items-center gap-2 rounded-sm px-3 py-1 text-sm straight-corners:rounded-none circular-corners:rounded-lg"
>
{option.flag ? (
<span aria-hidden className="shrink-0">
{option.flag}
</span>
) : (
<Icon
icon="location-crosshairs"
className="size-4 shrink-0 text-tint-subtle"
/>
)}
<span
className="min-w-0 flex-1 truncate"
title={option.label}
>
{option.label}
</span>
<Combobox.ItemIndicator>
<Icon
icon="check"
className="size-3.5 shrink-0 text-primary"
/>
</Combobox.ItemIndicator>
</Combobox.Item>
)}
</Combobox.Collection>
</Combobox.Group>
)}
</Combobox.List>
</Combobox.Popup>
</Combobox.Positioner>
</Combobox.Portal>
</Combobox.Root>
);
}
@@ -7,6 +7,7 @@ import {
encodeClientSiteSections,
shouldRenderSiteSectionNavigation,
} from '../SiteSections';
import { CountryPicker } from './CountryPicker';
import { HeaderLink } from './HeaderLink';
import { HeaderLinkMore } from './HeaderLinkMore';
import { HeaderLinks } from './HeaderLinks';
@@ -155,7 +156,8 @@ export async function Header(props: {
{customization.header.links.length > 0 ||
headerSocialAccounts.length > 0 ||
(!withSections && variants.translations.length > 1) ? (
(!withSections &&
(variants.translations.length > 1 || context.countryPicker)) ? (
<HeaderLinks>
{customization.header.links.map((link) => {
return (
@@ -189,6 +191,12 @@ export async function Header(props: {
context={context}
/>
) : null}
{!withSections && context.countryPicker ? (
<CountryPicker
context={context}
className="flex! -mx-3 site-header:theme-bold:text-header-link hover:site-header:theme-bold:bg-header-link/3 focus-visible:site-header:theme-bold:bg-header-link/3 aria-expanded:site-header:theme-bold:bg-header-link/5"
/>
) : null}
{!withSections && variants.translations.length > 1 ? (
<TranslationsDropdown
context={context}
@@ -210,6 +218,12 @@ export async function Header(props: {
{visibleSections && withSections ? (
<div className="lg:chat-open:pr-(--ai-chat-width) transition-[padding] duration-300 motion-reduce:transition-none">
<SiteSectionTabs sections={encodeClientSiteSections(context, visibleSections)}>
{context.countryPicker ? (
<CountryPicker
context={context}
className="-mx-3 my-1.5 ml-2 self-start"
/>
) : null}
{variants.translations.length > 1 ? (
<TranslationsDropdown
context={context}
@@ -7,6 +7,7 @@ import { AIChatProvider } from '../AI';
import type { RenderAIMessageOptions } from '../AI';
import { AIChat, AskAIParagraphButton, AskAITextSelection } from '../AIChat';
import { Announcement } from '../Announcement';
import { CountryPicker } from '../Header/CountryPicker';
import { SpacesDropdown, TranslationsDropdown } from '../Header/SpacesDropdown';
import { CurrentContentProvider } from '../hooks';
import { InsightsProvider, VisitorProvider } from '../Insights';
@@ -145,7 +146,7 @@ export function SpaceLayout(props: SpaceLayoutProps) {
) : null}
{/* Chat panel shifts content left when open. Clipped so blocks bleeding into the gutters (card carousels) can't widen the page. */}
<div className="overflow-x-clip lg:chat-open:mr-(--ai-chat-width) motion-safe:transition-all motion-safe:duration-300">
<div className="lg:chat-open:mr-(--ai-chat-width) overflow-x-clip motion-safe:transition-all motion-safe:duration-300">
<div
className={tcls(
'flex',
@@ -187,6 +188,13 @@ export function SpaceLayout(props: SpaceLayoutProps) {
)}
>
<HeaderLogo context={context} />
{context.countryPicker ? (
<CountryPicker
context={context}
className="[&_.button-leading-icon]:block! ml-auto py-2 [&_.button-content]:hidden"
variant="header"
/>
) : null}
{variants.translations.length > 1 ? (
<TranslationsDropdown
context={context}
@@ -196,7 +204,10 @@ export function SpaceLayout(props: SpaceLayoutProps) {
) ?? siteSpace
}
siteSpaces={variants.translations}
className="[&_.button-leading-icon]:block! ml-auto py-2 [&_.button-content]:hidden"
className={tcls(
'[&_.button-leading-icon]:block! py-2 [&_.button-content]:hidden',
context.countryPicker ? '' : 'ml-auto'
)}
variant="header"
/>
) : null}
@@ -25,10 +25,10 @@ const DropdownMenuContext = createContext<{
setOpen: () => {},
});
const DROPDOWN_POSITIONER_CLASS =
export const DROPDOWN_POSITIONER_CLASS =
'z-50 flex max-h-(--available-height) min-w-28 xs:min-w-40 max-w-(--available-width) flex-col pt-2 outline-hidden data-anchor-hidden:hidden';
// The exit animation has to live on the popup: Base UI keeps it mounted until *its* animations end.
const DROPDOWN_POPUP_CLASS =
export const DROPDOWN_POPUP_CLASS =
'flex origin-(--transform-origin) animate-scale-in flex-col gap-1 overflow-auto circular-corners:rounded-xl rounded-md straight-corners:rounded-none border border-tint bg-tint-base p-2 shadow-lg outline-hidden data-closed:animate-scale-out';
const HOVER_CLOSE_DELAY_MS = 150;
@@ -43,7 +43,7 @@ export function HoverCard(
>
<PreviewCard.Popup
{...popupProps}
className="pointer-events-auto animate-scale-in data-closed:animate-scale-out"
className="animate-scale-in data-closed:animate-scale-out pointer-events-auto"
>
<div
className={tcls(
@@ -209,4 +209,11 @@ export const ar: TranslationLanguage = {
auth_error_invalid_request: 'طلب غير صالح. يرجى البدء من جديد من التطبيق.',
auth_error_failed:
'لم نتمكن من إكمال التفويض. قد تكون صلاحية الطلب قد انتهت — يرجى البدء من جديد من التطبيق.',
country_picker_label: 'البلد: ${1}',
country_picker_automatic: 'تلقائي',
country_picker_automatic_detected: 'تلقائي (${1})',
country_picker_auto_hint: 'تلقائي',
country_picker_search: 'ابحث عن بلد',
country_picker_no_results: 'لم يتم العثور على أي بلد',
country_picker_other: 'أخرى',
};
@@ -214,4 +214,11 @@ export const bg: TranslationLanguage = {
auth_error_invalid_request: 'Невалидна заявка. Моля, започнете отново от приложението.',
auth_error_failed:
'Не успяхме да завършим оторизацията. Заявката може да е изтекла — моля, започнете отново от приложението.',
country_picker_label: 'Държава: ${1}',
country_picker_automatic: 'Автоматично',
country_picker_automatic_detected: 'Автоматично (${1})',
country_picker_auto_hint: 'авто',
country_picker_search: 'Търсене на държава',
country_picker_no_results: 'Няма намерени държави',
country_picker_other: 'Други',
};
@@ -212,4 +212,11 @@ export const cs: TranslationLanguage = {
auth_error_invalid_request: 'Neplatný požadavek. Začněte prosím znovu z aplikace.',
auth_error_failed:
'Autorizaci se nepodařilo dokončit. Požadavek mohl vypršet — začněte prosím znovu z aplikace.',
country_picker_label: 'Země: ${1}',
country_picker_automatic: 'Automaticky',
country_picker_automatic_detected: 'Automaticky (${1})',
country_picker_auto_hint: 'auto',
country_picker_search: 'Hledat zemi',
country_picker_no_results: 'Žádná země nenalezena',
country_picker_other: 'Ostatní',
};
@@ -211,4 +211,11 @@ export const da: TranslationLanguage = {
auth_error_invalid_request: 'Ugyldig anmodning. Start venligst forfra fra programmet.',
auth_error_failed:
'Vi kunne ikke fuldføre autorisationen. Anmodningen kan være udløbet — start venligst forfra fra programmet.',
country_picker_label: 'Land: ${1}',
country_picker_automatic: 'Automatisk',
country_picker_automatic_detected: 'Automatisk (${1})',
country_picker_auto_hint: 'auto',
country_picker_search: 'Søg efter land',
country_picker_no_results: 'Ingen lande fundet',
country_picker_other: 'Andre',
};
@@ -217,4 +217,11 @@ export const de: TranslationLanguage = {
auth_error_invalid_request: 'Ungültige Anfrage. Bitte starten Sie erneut in der Anwendung.',
auth_error_failed:
'Die Autorisierung konnte nicht abgeschlossen werden. Die Anfrage ist möglicherweise abgelaufen — bitte starten Sie erneut in der Anwendung.',
country_picker_label: 'Land: ${1}',
country_picker_automatic: 'Automatisch',
country_picker_automatic_detected: 'Automatisch (${1})',
country_picker_auto_hint: 'auto',
country_picker_search: 'Land suchen',
country_picker_no_results: 'Keine Länder gefunden',
country_picker_other: 'Andere',
};
@@ -216,4 +216,11 @@ export const el: TranslationLanguage = {
auth_error_invalid_request: 'Μη έγκυρο αίτημα. Ξεκινήστε ξανά από την εφαρμογή.',
auth_error_failed:
'Δεν μπορέσαμε να ολοκληρώσουμε την εξουσιοδότηση. Το αίτημα μπορεί να έχει λήξει — ξεκινήστε ξανά από την εφαρμογή.',
country_picker_label: 'Χώρα: ${1}',
country_picker_automatic: 'Αυτόματα',
country_picker_automatic_detected: 'Αυτόματα (${1})',
country_picker_auto_hint: 'αυτόματα',
country_picker_search: 'Αναζήτηση χώρας',
country_picker_no_results: 'Δεν βρέθηκαν χώρες',
country_picker_other: 'Άλλες',
};
@@ -210,4 +210,11 @@ export const en = {
auth_error_invalid_request: 'Invalid request. Please start again from the application.',
auth_error_failed:
'We could not complete the authorization. The request may have expired — please start again from the application.',
country_picker_label: 'Country: ${1}',
country_picker_automatic: 'Automatic',
country_picker_automatic_detected: 'Automatic (${1})',
country_picker_auto_hint: 'auto',
country_picker_search: 'Search countries',
country_picker_no_results: 'No countries found',
country_picker_other: 'Other',
};
@@ -214,4 +214,11 @@ export const es: TranslationLanguage = {
auth_error_invalid_request: 'Solicitud no válida. Vuelve a empezar desde la aplicación.',
auth_error_failed:
'No hemos podido completar la autorización. La solicitud puede haber caducado: vuelve a empezar desde la aplicación.',
country_picker_label: 'País: ${1}',
country_picker_automatic: 'Automático',
country_picker_automatic_detected: 'Automático (${1})',
country_picker_auto_hint: 'auto',
country_picker_search: 'Buscar país',
country_picker_no_results: 'No se encontraron países',
country_picker_other: 'Otros',
};
@@ -212,4 +212,11 @@ export const et: TranslationLanguage = {
auth_error_invalid_request: 'Vigane päring. Palun alustage rakendusest uuesti.',
auth_error_failed:
'Autoriseerimist ei saanud lõpule viia. Päring võis aeguda — palun alustage rakendusest uuesti.',
country_picker_label: 'Riik: ${1}',
country_picker_automatic: 'Automaatne',
country_picker_automatic_detected: 'Automaatne (${1})',
country_picker_auto_hint: 'auto',
country_picker_search: 'Otsi riiki',
country_picker_no_results: 'Riike ei leitud',
country_picker_other: 'Muud',
};
@@ -212,4 +212,11 @@ export const fi: TranslationLanguage = {
auth_error_invalid_request: 'Virheellinen pyyntö. Aloita uudelleen sovelluksesta.',
auth_error_failed:
'Valtuutusta ei voitu viimeistellä. Pyyntö on saattanut vanhentua — aloita uudelleen sovelluksesta.',
country_picker_label: 'Maa: ${1}',
country_picker_automatic: 'Automaattinen',
country_picker_automatic_detected: 'Automaattinen (${1})',
country_picker_auto_hint: 'auto',
country_picker_search: 'Hae maata',
country_picker_no_results: 'Maita ei löytynyt',
country_picker_other: 'Muut',
};
@@ -211,4 +211,11 @@ export const fr: TranslationLanguage = {
auth_error_invalid_request: 'Requête invalide. Veuillez recommencer depuis l’application.',
auth_error_failed:
'Nous n’avons pas pu finaliser l’autorisation. La requête a peut-être expiré — veuillez recommencer depuis l’application.',
country_picker_label: 'Pays : ${1}',
country_picker_automatic: 'Automatique',
country_picker_automatic_detected: 'Automatique (${1})',
country_picker_auto_hint: 'auto',
country_picker_search: 'Rechercher un pays',
country_picker_no_results: 'Aucun pays trouvé',
country_picker_other: 'Autres',
};
@@ -207,4 +207,11 @@ export const he: TranslationLanguage = {
auth_expired_description: 'התחילו את ההתחברות מחדש מהיישום.',
auth_error_invalid_request: 'בקשה לא חוקית. התחילו מחדש מהיישום.',
auth_error_failed: 'לא הצלחנו להשלים את ההרשאה. ייתכן שתוקף הבקשה פג — התחילו מחדש מהיישום.',
country_picker_label: 'מדינה: ${1}',
country_picker_automatic: 'אוטומטי',
country_picker_automatic_detected: 'אוטומטי (${1})',
country_picker_auto_hint: 'אוטומטי',
country_picker_search: 'חיפוש מדינה',
country_picker_no_results: 'לא נמצאו מדינות',
country_picker_other: 'אחרות',
};
@@ -211,4 +211,11 @@ export const hi: TranslationLanguage = {
auth_error_invalid_request: 'अमान्य अनुरोध। कृपया ऐप्लिकेशन से फिर से शुरू करें।',
auth_error_failed:
'हम प्राधिकरण पूरा नहीं कर सके। अनुरोध की अवधि समाप्त हो सकती है — कृपया ऐप्लिकेशन से फिर से शुरू करें।',
country_picker_label: 'देश: ${1}',
country_picker_automatic: 'स्वचालित',
country_picker_automatic_detected: 'स्वचालित (${1})',
country_picker_auto_hint: 'स्वतः',
country_picker_search: 'देश खोजें',
country_picker_no_results: 'कोई देश नहीं मिला',
country_picker_other: 'अन्य',
};
@@ -212,4 +212,11 @@ export const hr: TranslationLanguage = {
auth_error_invalid_request: 'Nevažeći zahtjev. Molimo ponovno započnite iz aplikacije.',
auth_error_failed:
'Nismo mogli dovršiti autorizaciju. Zahtjev je možda istekao — molimo ponovno započnite iz aplikacije.',
country_picker_label: 'Država: ${1}',
country_picker_automatic: 'Automatski',
country_picker_automatic_detected: 'Automatski (${1})',
country_picker_auto_hint: 'auto',
country_picker_search: 'Pretraži države',
country_picker_no_results: 'Nije pronađena nijedna država',
country_picker_other: 'Ostale',
};
@@ -214,4 +214,11 @@ export const hu: TranslationLanguage = {
auth_error_invalid_request: 'Érvénytelen kérés. Kérjük, kezdje újra az alkalmazásból.',
auth_error_failed:
'Nem tudtuk befejezni az engedélyezést. A kérés lejárhatott — kérjük, kezdje újra az alkalmazásból.',
country_picker_label: 'Ország: ${1}',
country_picker_automatic: 'Automatikus',
country_picker_automatic_detected: 'Automatikus (${1})',
country_picker_auto_hint: 'auto',
country_picker_search: 'Ország keresése',
country_picker_no_results: 'Nincs találat',
country_picker_other: 'Egyéb',
};
@@ -211,4 +211,11 @@ export const id: TranslationLanguage = {
auth_error_invalid_request: 'Permintaan tidak valid. Silakan mulai lagi dari aplikasi.',
auth_error_failed:
'Kami tidak dapat menyelesaikan otorisasi. Permintaan mungkin telah kedaluwarsa — silakan mulai lagi dari aplikasi.',
country_picker_label: 'Negara: ${1}',
country_picker_automatic: 'Otomatis',
country_picker_automatic_detected: 'Otomatis (${1})',
country_picker_auto_hint: 'otomatis',
country_picker_search: 'Cari negara',
country_picker_no_results: 'Negara tidak ditemukan',
country_picker_other: 'Lainnya',
};
@@ -214,4 +214,11 @@ export const it: TranslationLanguage = {
auth_error_invalid_request: 'Richiesta non valida. Ricomincia dall’applicazione.',
auth_error_failed:
'Non è stato possibile completare l’autorizzazione. La richiesta potrebbe essere scaduta: ricomincia dall’applicazione.',
country_picker_label: 'Paese: ${1}',
country_picker_automatic: 'Automatico',
country_picker_automatic_detected: 'Automatico (${1})',
country_picker_auto_hint: 'auto',
country_picker_search: 'Cerca un paese',
country_picker_no_results: 'Nessun paese trovato',
country_picker_other: 'Altri',
};
@@ -211,4 +211,11 @@ export const ja: TranslationLanguage = {
auth_error_invalid_request: '無効なリクエストです。アプリケーションからやり直してください。',
auth_error_failed:
'認証を完了できませんでした。リクエストの有効期限が切れた可能性があります — アプリケーションからやり直してください。',
country_picker_label: '国: ${1}',
country_picker_automatic: '自動',
country_picker_automatic_detected: '自動(${1})',
country_picker_auto_hint: '自動',
country_picker_search: '国を検索',
country_picker_no_results: '国が見つかりません',
country_picker_other: 'その他',
};
@@ -211,4 +211,11 @@ export const ko: TranslationLanguage = {
auth_error_invalid_request: '잘못된 요청입니다. 애플리케이션에서 다시 시작하세요.',
auth_error_failed:
'인증을 완료할 수 없습니다. 요청이 만료되었을 수 있습니다 — 애플리케이션에서 다시 시작하세요.',
country_picker_label: '국가: ${1}',
country_picker_automatic: '자동',
country_picker_automatic_detected: '자동 (${1})',
country_picker_auto_hint: '자동',
country_picker_search: '국가 검색',
country_picker_no_results: '국가를 찾을 수 없습니다',
country_picker_other: '기타',
};
@@ -212,4 +212,11 @@ export const lt: TranslationLanguage = {
auth_error_invalid_request: 'Neteisinga užklausa. Pradėkite iš programos iš naujo.',
auth_error_failed:
'Nepavyko užbaigti autorizacijos. Užklausos laikas galėjo pasibaigti — pradėkite iš programos iš naujo.',
country_picker_label: 'Šalis: ${1}',
country_picker_automatic: 'Automatinė',
country_picker_automatic_detected: 'Automatinė (${1})',
country_picker_auto_hint: 'auto',
country_picker_search: 'Ieškoti šalies',
country_picker_no_results: 'Šalių nerasta',
country_picker_other: 'Kitos',
};
@@ -211,4 +211,11 @@ export const lv: TranslationLanguage = {
auth_error_invalid_request: 'Nederīgs pieprasījums. Lūdzu, sāciet no lietotnes vēlreiz.',
auth_error_failed:
'Neizdevās pabeigt autorizāciju. Pieprasījuma derīgums, iespējams, ir beidzies — lūdzu, sāciet no lietotnes vēlreiz.',
country_picker_label: 'Valsts: ${1}',
country_picker_automatic: 'Automātiski',
country_picker_automatic_detected: 'Automātiski (${1})',
country_picker_auto_hint: 'auto',
country_picker_search: 'Meklēt valsti',
country_picker_no_results: 'Neviena valsts nav atrasta',
country_picker_other: 'Citas',
};
@@ -212,4 +212,11 @@ export const ms: TranslationLanguage = {
auth_error_invalid_request: 'Permintaan tidak sah. Sila mulakan semula dari aplikasi.',
auth_error_failed:
'Kami tidak dapat melengkapkan kebenaran. Permintaan mungkin telah tamat tempoh — sila mulakan semula dari aplikasi.',
country_picker_label: 'Negara: ${1}',
country_picker_automatic: 'Automatik',
country_picker_automatic_detected: 'Automatik (${1})',
country_picker_auto_hint: 'auto',
country_picker_search: 'Cari negara',
country_picker_no_results: 'Tiada negara ditemui',
country_picker_other: 'Lain-lain',
};
@@ -212,4 +212,11 @@ export const nl: TranslationLanguage = {
auth_error_invalid_request: 'Ongeldig verzoek. Begin opnieuw vanuit de applicatie.',
auth_error_failed:
'We konden de autorisatie niet voltooien. Het verzoek is mogelijk verlopen — begin opnieuw vanuit de applicatie.',
country_picker_label: 'Land: ${1}',
country_picker_automatic: 'Automatisch',
country_picker_automatic_detected: 'Automatisch (${1})',
country_picker_auto_hint: 'auto',
country_picker_search: 'Land zoeken',
country_picker_no_results: 'Geen landen gevonden',
country_picker_other: 'Overige',
};
@@ -213,4 +213,11 @@ export const no: TranslationLanguage = {
auth_error_invalid_request: 'Ugyldig forespørsel. Start på nytt fra programmet.',
auth_error_failed:
'Vi kunne ikke fullføre autorisasjonen. Forespørselen kan ha utløpt — start på nytt fra programmet.',
country_picker_label: 'Land: ${1}',
country_picker_automatic: 'Automatisk',
country_picker_automatic_detected: 'Automatisk (${1})',
country_picker_auto_hint: 'auto',
country_picker_search: 'Søk etter land',
country_picker_no_results: 'Fant ingen land',
country_picker_other: 'Andre',
};
@@ -213,4 +213,11 @@ export const pl: TranslationLanguage = {
auth_error_invalid_request: 'Nieprawidłowe żądanie. Rozpocznij ponownie z aplikacji.',
auth_error_failed:
'Nie udało się zakończyć autoryzacji. Żądanie mogło wygasnąć — rozpocznij ponownie z aplikacji.',
country_picker_label: 'Kraj: ${1}',
country_picker_automatic: 'Automatycznie',
country_picker_automatic_detected: 'Automatycznie (${1})',
country_picker_auto_hint: 'auto',
country_picker_search: 'Szukaj kraju',
country_picker_no_results: 'Nie znaleziono krajów',
country_picker_other: 'Inne',
};
@@ -214,4 +214,11 @@ export const pt_br: TranslationLanguage = {
auth_error_invalid_request: 'Solicitação inválida. Comece novamente pelo aplicativo.',
auth_error_failed:
'Não conseguimos concluir a autorização. A solicitação pode ter expirado — comece novamente pelo aplicativo.',
country_picker_label: 'País: ${1}',
country_picker_automatic: 'Automático',
country_picker_automatic_detected: 'Automático (${1})',
country_picker_auto_hint: 'auto',
country_picker_search: 'Buscar país',
country_picker_no_results: 'Nenhum país encontrado',
country_picker_other: 'Outros',
};
@@ -212,4 +212,11 @@ export const pt: TranslationLanguage = {
auth_error_invalid_request: 'Pedido inválido. Comece novamente a partir da aplicação.',
auth_error_failed:
'Não foi possível concluir a autorização. O pedido pode ter expirado — comece novamente a partir da aplicação.',
country_picker_label: 'País: ${1}',
country_picker_automatic: 'Automático',
country_picker_automatic_detected: 'Automático (${1})',
country_picker_auto_hint: 'auto',
country_picker_search: 'Pesquisar país',
country_picker_no_results: 'Nenhum país encontrado',
country_picker_other: 'Outros',
};
@@ -214,4 +214,11 @@ export const ro: TranslationLanguage = {
auth_error_invalid_request: 'Cerere invalidă. Reia din aplicație.',
auth_error_failed:
'Nu am putut finaliza autorizarea. Cererea poate să fi expirat — reia din aplicație.',
country_picker_label: 'Țară: ${1}',
country_picker_automatic: 'Automată',
country_picker_automatic_detected: 'Automată (${1})',
country_picker_auto_hint: 'auto',
country_picker_search: 'Caută o țară',
country_picker_no_results: 'Nu s-a găsit nicio țară',
country_picker_other: 'Altele',
};
@@ -213,4 +213,11 @@ export const ru: TranslationLanguage = {
auth_error_invalid_request: 'Неверный запрос. Начните заново из приложения.',
auth_error_failed:
'Не удалось завершить авторизацию. Возможно, срок действия запроса истёк — начните заново из приложения.',
country_picker_label: 'Страна: ${1}',
country_picker_automatic: 'Автоматически',
country_picker_automatic_detected: 'Автоматически (${1})',
country_picker_auto_hint: 'авто',
country_picker_search: 'Поиск страны',
country_picker_no_results: 'Страны не найдены',
country_picker_other: 'Другие',
};
@@ -213,4 +213,11 @@ export const sk: TranslationLanguage = {
auth_error_invalid_request: 'Neplatná požiadavka. Začnite znova z aplikácie.',
auth_error_failed:
'Autorizáciu sa nepodarilo dokončiť. Požiadavka mohla vypršať — začnite znova z aplikácie.',
country_picker_label: 'Krajina: ${1}',
country_picker_automatic: 'Automaticky',
country_picker_automatic_detected: 'Automaticky (${1})',
country_picker_auto_hint: 'auto',
country_picker_search: 'Hľadať krajinu',
country_picker_no_results: 'Nenašla sa žiadna krajina',
country_picker_other: 'Ostatné',
};
@@ -212,4 +212,11 @@ export const sl: TranslationLanguage = {
auth_error_invalid_request: 'Neveljavna zahteva. Znova začnite v aplikaciji.',
auth_error_failed:
'Avtorizacije nismo mogli dokončati. Zahteva je morda potekla — znova začnite v aplikaciji.',
country_picker_label: 'Država: ${1}',
country_picker_automatic: 'Samodejno',
country_picker_automatic_detected: 'Samodejno (${1})',
country_picker_auto_hint: 'samodejno',
country_picker_search: 'Iskanje države',
country_picker_no_results: 'Ni najdenih držav',
country_picker_other: 'Drugo',
};
@@ -214,4 +214,11 @@ export const sv: TranslationLanguage = {
auth_error_invalid_request: 'Ogiltig förfrågan. Börja om från programmet.',
auth_error_failed:
'Vi kunde inte slutföra auktoriseringen. Förfrågan kan ha upphört att gälla — börja om från programmet.',
country_picker_label: 'Land: ${1}',
country_picker_automatic: 'Automatisk',
country_picker_automatic_detected: 'Automatisk (${1})',
country_picker_auto_hint: 'auto',
country_picker_search: 'Sök land',
country_picker_no_results: 'Inga länder hittades',
country_picker_other: 'Övriga',
};
@@ -207,4 +207,11 @@ export const th: TranslationLanguage = {
auth_error_invalid_request: 'คำขอไม่ถูกต้อง โปรดเริ่มอีกครั้งจากแอปพลิเคชัน',
auth_error_failed:
'เราไม่สามารถดำเนินการอนุญาตให้เสร็จสิ้นได้ คำขออาจหมดอายุแล้ว — โปรดเริ่มอีกครั้งจากแอปพลิเคชัน',
country_picker_label: 'ประเทศ: ${1}',
country_picker_automatic: 'อัตโนมัติ',
country_picker_automatic_detected: 'อัตโนมัติ (${1})',
country_picker_auto_hint: 'อัตโนมัติ',
country_picker_search: 'ค้นหาประเทศ',
country_picker_no_results: 'ไม่พบประเทศ',
country_picker_other: 'อื่นๆ',
};
@@ -211,4 +211,11 @@ export const tr: TranslationLanguage = {
auth_error_invalid_request: 'Geçersiz istek. Lütfen uygulamadan yeniden başlayın.',
auth_error_failed:
'Yetkilendirmeyi tamamlayamadık. İsteğin süresi dolmuş olabilir — lütfen uygulamadan yeniden başlayın.',
country_picker_label: 'Ülke: ${1}',
country_picker_automatic: 'Otomatik',
country_picker_automatic_detected: 'Otomatik (${1})',
country_picker_auto_hint: 'otomatik',
country_picker_search: 'Ülke ara',
country_picker_no_results: 'Ülke bulunamadı',
country_picker_other: 'Diğer',
};
@@ -211,4 +211,11 @@ export const uk: TranslationLanguage = {
auth_error_invalid_request: 'Некоректний запит. Почніть знову із застосунку.',
auth_error_failed:
'Не вдалося завершити авторизацію. Можливо, термін дії запиту сплив — почніть знову із застосунку.',
country_picker_label: 'Країна: ${1}',
country_picker_automatic: 'Автоматично',
country_picker_automatic_detected: 'Автоматично (${1})',
country_picker_auto_hint: 'авто',
country_picker_search: 'Пошук країни',
country_picker_no_results: 'Країн не знайдено',
country_picker_other: 'Інші',
};
@@ -211,4 +211,11 @@ export const vi: TranslationLanguage = {
auth_error_invalid_request: 'Yêu cầu không hợp lệ. Vui lòng bắt đầu lại từ ứng dụng.',
auth_error_failed:
'Chúng tôi không thể hoàn tất việc cấp quyền. Yêu cầu có thể đã hết hạn — vui lòng bắt đầu lại từ ứng dụng.',
country_picker_label: 'Quốc gia: ${1}',
country_picker_automatic: 'Tự động',
country_picker_automatic_detected: 'Tự động (${1})',
country_picker_auto_hint: 'tự động',
country_picker_search: 'Tìm quốc gia',
country_picker_no_results: 'Không tìm thấy quốc gia nào',
country_picker_other: 'Khác',
};
@@ -205,4 +205,11 @@ export const yue: TranslationLanguage = {
auth_expired_description: '請由應用程式重新開始登入。',
auth_error_invalid_request: '請求無效。請由應用程式重新開始。',
auth_error_failed: '我們無法完成授權。請求可能已經過期 — 請由應用程式重新開始。',
country_picker_label: '國家:${1}',
country_picker_automatic: '自動',
country_picker_automatic_detected: '自動(${1})',
country_picker_auto_hint: '自動',
country_picker_search: '搜尋國家',
country_picker_no_results: '搵唔到國家',
country_picker_other: '其他',
};
@@ -205,4 +205,11 @@ export const zh_tw: TranslationLanguage = {
auth_expired_description: '請從應用程式重新開始登入。',
auth_error_invalid_request: '請求無效。請從應用程式重新開始。',
auth_error_failed: '我們無法完成授權。請求可能已過期 — 請從應用程式重新開始。',
country_picker_label: '國家/地區:${1}',
country_picker_automatic: '自動',
country_picker_automatic_detected: '自動(${1})',
country_picker_auto_hint: '自動',
country_picker_search: '搜尋國家/地區',
country_picker_no_results: '找不到國家/地區',
country_picker_other: '其他',
};
@@ -205,4 +205,11 @@ export const zh: TranslationLanguage = {
auth_expired_description: '请从应用重新开始登录。',
auth_error_invalid_request: '请求无效。请从应用重新开始。',
auth_error_failed: '我们无法完成授权。请求可能已过期 — 请从应用重新开始。',
country_picker_label: '国家/地区:${1}',
country_picker_automatic: '自动',
country_picker_automatic_detected: '自动(${1})',
country_picker_auto_hint: '自动',
country_picker_search: '搜索国家/地区',
country_picker_no_results: '未找到国家/地区',
country_picker_other: '其他',
};
+16 -11
View File
@@ -46,6 +46,7 @@ import {
getSiteStructureSections,
listAllSiteSpaces,
} from '@/lib/sites';
import { type SiteRegions, getCountryPickerRegions } from '@/lib/visitor-country';
/**
* Data about the site URL. Provided by the middleware.
@@ -218,6 +219,9 @@ export type GitBookSiteContext = GitBookSpaceContext & {
/** Context ID used by adaptive content. It represents an unique identifier for the authentication context */
contextId?: string;
/** Regions grouping the country picker, or null when the site doesn't show it. */
countryPicker: SiteRegions | null;
/** Whether this request is a fallback rendering. */
isFallback: boolean;
@@ -356,17 +360,17 @@ export async function fetchSiteContextByIds(
): Promise<GitBookSiteContext> {
const { dataFetcher } = baseContext;
const [{ site: orgSite, structure: siteStructure, customizations, scripts }, spaceContext] =
await Promise.all([
throwIfDataError(
dataFetcher.getPublishedContentSite({
organizationId: ids.organization,
siteId: ids.site,
siteShareKey: ids.shareKey,
})
),
fetchSpaceContextByIds(baseContext, ids),
]);
const [publishedSite, spaceContext] = await Promise.all([
throwIfDataError(
dataFetcher.getPublishedContentSite({
organizationId: ids.organization,
siteId: ids.site,
siteShareKey: ids.shareKey,
})
),
fetchSpaceContextByIds(baseContext, ids),
]);
const { site: orgSite, structure: siteStructure, customizations, scripts } = publishedSite;
const { publicChangeRequestPreviews } = orgSite as Site & {
publicChangeRequestPreviews?: boolean;
@@ -500,6 +504,7 @@ export async function fetchSiteContextByIds(
visibleSections,
scripts,
contextId: ids.contextId,
countryPicker: getCountryPickerRegions(publishedSite),
isFallback: ids.isFallback,
noIndexSearch: ids.noIndexSearch,
siteRevision: ids.siteRevision,
+122
View File
@@ -0,0 +1,122 @@
import { describe, expect, it } from 'bun:test';
import {
COUNTRY_CODES,
type CountryGroup,
getCountryFlag,
getCountryList,
getCountryName,
groupCountriesByRegion,
parseCountryChoice,
} from './countries';
describe('parseCountryChoice', () => {
it('upper-cases assigned ISO 3166-1 alpha-2 codes', () => {
expect(parseCountryChoice('fr')).toBe('FR');
expect(parseCountryChoice(' US ')).toBe('US');
});
it.each([undefined, null, '', 'XX', 'T1', 'ZZ', 'EU', 'FRA', '1A'])('rejects %p', (value) => {
expect(parseCountryChoice(value)).toBeUndefined();
});
});
describe('getCountryName', () => {
it('names the country in the locale', () => {
expect(getCountryName('DE', 'fr')).toBe('Allemagne');
expect(getCountryName('DE', 'en')).toBe('Germany');
});
it('falls back to English for an invalid locale', () => {
expect(getCountryName('DE', 'not a locale')).toBe('Germany');
});
});
describe('getCountryList', () => {
it('lists every country sorted by its localized name', () => {
const list = getCountryList('fr');
const names = list.map((country) => country.name);
expect(list).toHaveLength(249);
expect(names).toEqual([...names].sort(new Intl.Collator('fr').compare));
expect(list.find((country) => country.code === 'DE')?.name).toBe('Allemagne');
});
});
/** Each group as `label: codes`, with "other" for the remaining countries. */
function summarize(groups: CountryGroup[]): string[] {
return groups.map(
(group) =>
`${group.type === 'region' ? group.label : 'other'}: ${group.countries.map((country) => country.code).join(' ')}`
);
}
describe('groupCountriesByRegion', () => {
const codes = ['AU', 'CA', 'DE', 'ES', 'FR', 'JP', 'MX', 'US'];
it('keeps the declaration order of regions and sorts their countries by localized name', () => {
const groups = groupCountriesByRegion(
{
northAmerica: { label: 'North America', countries: ['US', 'MX', 'CA'] },
europe: { label: 'Europe', countries: ['FR', 'DE', 'ES'] },
},
codes,
'fr'
);
// In French: Allemagne, Espagne, France; Canada, États-Unis, Mexique.
expect(summarize(groups)).toEqual([
'North America: CA US MX',
'Europe: DE ES FR',
'other: AU JP',
]);
expect(groups[0]).toMatchObject({ type: 'region', name: 'northAmerica' });
expect(groups[1]?.countries[0]).toEqual({ code: 'DE', name: 'Allemagne' });
});
it('falls back to the region name when it has no label', () => {
const groups = groupCountriesByRegion({ emea: { countries: ['FR'] } }, codes, 'en');
expect(groups[0]).toMatchObject({ type: 'region', name: 'emea', label: 'emea' });
});
it('puts every country in no region under "other"', () => {
const groups = groupCountriesByRegion(
{ europe: { label: 'Europe', countries: ['FR', 'DE'] } },
COUNTRY_CODES,
'en'
);
const other = groups.find((group) => group.type === 'other');
expect(groups.map((group) => group.type)).toEqual(['region', 'other']);
expect(other?.countries).toHaveLength(COUNTRY_CODES.length - 2);
expect(other?.countries.map((country) => country.code)).not.toContain('FR');
});
it('ignores unknown codes, repeated countries and regions left empty', () => {
const groups = groupCountriesByRegion(
{
europe: { label: 'Europe', countries: ['fr', 'ZZ'] },
again: { label: 'Again', countries: ['FR'] },
empty: { label: 'Empty', countries: [] },
},
codes,
'en'
);
expect(summarize(groups)).toEqual(['Europe: FR', 'other: AU CA DE JP MX ES US']);
});
it.each([undefined, null, {}])('puts every country under "other" for regions %p', (regions) => {
const groups = groupCountriesByRegion(regions, codes, 'en');
expect(summarize(groups)).toEqual(['other: AU CA FR DE JP MX ES US']);
});
});
describe('getCountryFlag', () => {
it('builds the flag from regional indicator symbols', () => {
expect(getCountryFlag('FR')).toBe('🇫🇷');
expect(getCountryFlag('us')).toBe('🇺🇸');
});
});
+159
View File
@@ -0,0 +1,159 @@
/**
* ISO 3166-1 alpha-2 codes of every officially assigned country.
*/
export const COUNTRY_CODES: readonly string[] = [
'AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ',
'BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ',
'CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ',
'DE DJ DK DM DO DZ',
'EC EE EG EH ER ES ET',
'FI FJ FK FM FO FR',
'GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY',
'HK HM HN HR HT HU',
'ID IE IL IM IN IO IQ IR IS IT',
'JE JM JO JP',
'KE KG KH KI KM KN KP KR KW KY KZ',
'LA LB LC LI LK LR LS LT LU LV LY',
'MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ',
'NA NC NE NF NG NI NL NO NP NR NU NZ',
'OM',
'PA PE PF PG PH PK PL PM PN PR PS PT PW PY',
'QA',
'RE RO RS RU RW',
'SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ',
'TC TD TF TG TH TJ TK TL TM TN TO TR TT TV TW TZ',
'UA UG UM US UY UZ',
'VA VC VE VG VI VN VU',
'WF WS',
'YE YT',
'ZA ZM ZW',
]
.join(' ')
.split(' ');
const COUNTRY_CODE_SET = new Set(COUNTRY_CODES);
/**
* Upper-case a two-letter country code, or return undefined when it isn't one.
*/
export function normalizeCountryCode(value: string | null | undefined): string | undefined {
const country = value?.trim().toUpperCase() ?? '';
// Cloudflare uses XX for unknown and T1 for Tor, which are not ISO codes.
if (!/^[A-Z]{2}$/.test(country) || country === 'XX' || country === 'T1') {
return undefined;
}
return country;
}
/**
* Parse a country chosen by the visitor: only assigned ISO 3166-1 alpha-2 codes are accepted.
*/
export function parseCountryChoice(value: string | null | undefined): string | undefined {
const country = normalizeCountryCode(value);
return country && COUNTRY_CODE_SET.has(country) ? country : undefined;
}
/**
* The locales to format country names with: the site's, when valid, then English.
*/
export function getCountryLocales(locale: string): string[] {
try {
return [...Intl.getCanonicalLocales(locale), 'en'];
} catch {
return ['en'];
}
}
function createCountryDisplayNames(locales: string[]): Intl.DisplayNames | null {
try {
return new Intl.DisplayNames(locales, { type: 'region', fallback: 'code' });
} catch {
return null;
}
}
function formatCountryName(country: string, displayNames: Intl.DisplayNames | null): string {
try {
return displayNames?.of(country) ?? country;
} catch {
return country;
}
}
/**
* Get the name of a country in a locale, falling back to its code.
*/
export function getCountryName(country: string, locale: string): string {
return formatCountryName(country, createCountryDisplayNames(getCountryLocales(locale)));
}
export type CountryEntry = { code: string; name: string };
/** A group of the country picker: a site region, or every country in no region. */
export type CountryGroup =
| { type: 'region'; name: string; label: string; countries: CountryEntry[] }
| { type: 'other'; countries: CountryEntry[] };
/**
* Get countries with their name in a locale, sorted by name.
*/
export function getCountryList(
locale: string,
countryCodes: readonly string[] = COUNTRY_CODES
): CountryEntry[] {
const locales = getCountryLocales(locale);
const displayNames = createCountryDisplayNames(locales);
const collator = new Intl.Collator(locales);
return countryCodes
.map((code) => ({ code, name: formatCountryName(code, displayNames) }))
.sort((a, b) => collator.compare(a.name, b.name));
}
/**
* Group countries by the site's regions, in declaration order, then the rest under "other".
* Each group is sorted by localized name, and empty groups are left out.
*/
export function groupCountriesByRegion(
regions: { [name: string]: { label?: string; countries: string[] } } | null | undefined,
countryCodes: readonly string[],
locale: string
): CountryGroup[] {
const countries = getCountryList(locale, countryCodes);
const assigned = new Set<string>();
const groups: CountryGroup[] = [];
for (const [name, region] of Object.entries(regions ?? {})) {
// The API keeps each country in one region; the first one wins should that change.
const codes = new Set(
region.countries.map((code) => code.toUpperCase()).filter((code) => !assigned.has(code))
);
codes.forEach((code) => assigned.add(code));
const regionCountries = countries.filter((country) => codes.has(country.code));
if (regionCountries.length > 0) {
groups.push({
type: 'region',
name,
label: region.label?.trim() || name,
countries: regionCountries,
});
}
}
const otherCountries = countries.filter((country) => !assigned.has(country.code));
if (otherCountries.length > 0) {
groups.push({ type: 'other', countries: otherCountries });
}
return groups;
}
/**
* The flag emoji of a country, from the regional indicator symbols of its code.
*/
export function getCountryFlag(country: string): string {
return String.fromCodePoint(
...[...country.toUpperCase()].map((letter) => 0x1f1e6 + letter.charCodeAt(0) - 65)
);
}
@@ -0,0 +1,36 @@
import type { PublishedContentSite, SiteCustomizationSettings } from '@gitbook/api';
/** Cookie storing the country the visitor chose over their detected one. */
export const VISITOR_COUNTRY_COOKIE = 'gitbook-visitor-country';
export const VISITOR_COUNTRY_COOKIE_MAX_AGE = 365 * 24 * 60 * 60;
/** URL param choosing the visitor's country, outside `visitor.*` which carries unsigned claims. */
export const VISITOR_COUNTRY_PARAM = 'gitbook.country';
/** Middleware route returning the visitor's detected and chosen countries. */
export const VISITOR_COUNTRY_PATH = '~gitbook/visitor/country';
// TEMPORARY (RND-13578): drop once `@gitbook/api` ships `PublishedContentSite.regions` and
// `SiteCustomizationSettings.countryPicker`, then alias `SiteRegions` to `PublishedContentSite['regions']`.
/** The regions a site declares in its adaptive schema, in declaration order. */
export type SiteRegions = {
[regionName: string]: { label?: string; countries: string[] };
};
type PublishedContentSiteWithRegions = PublishedContentSite & {
customizations: { site: SiteCustomizationSettings & { countryPicker?: { enabled: boolean } } };
regions?: SiteRegions;
};
/**
* The regions to group the country picker by, or null when the site doesn't show the picker.
* It shows only when enabled and when the site declares at least one region.
*/
export function getCountryPickerRegions(
publishedSite: PublishedContentSiteWithRegions
): SiteRegions | null {
const { customizations, regions } = publishedSite;
if (customizations.site.countryPicker?.enabled !== true || !regions) {
return null;
}
return Object.keys(regions).length > 0 ? regions : null;
}
+219 -1
View File
@@ -1,7 +1,8 @@
import { describe, expect, it } from 'bun:test';
import type { JwtPayload } from 'jwt-decode';
import { NextResponse } from 'next/server';
import { NextRequest, NextResponse } from 'next/server';
import { getVisitorAuthBasePath } from './data/visitor';
import {
type ResponseCookies,
getResponseCookiesForVisitorAuth,
@@ -9,11 +10,15 @@ import {
getVisitorAuthCookieName,
getVisitorAuthCookieValue,
getVisitorCountry,
getVisitorCountryCookieName,
getVisitorCountryData,
getVisitorCountryResponseCookie,
getVisitorToken,
getVisitorType,
getVisitorUnsignedClaims,
isRevalidationRequest,
normalizeVisitorURL,
serveVisitorCountryRequest,
} from './visitors';
describe('getVisitorAuthToken', () => {
@@ -711,3 +716,216 @@ describe('getVisitorCountry', () => {
).toBe('FR');
});
});
describe('getVisitorCountryData', () => {
const revalidationHeaders = new Headers({
'user-agent': 'GitBook-Open-Revalidation-Worker',
'x-gitbook-country': 'DE',
});
const detectedHeaders = () => new Headers({ 'x-open-next-country': 'FR' });
const countryCookie = { name: getVisitorCountryCookieName('/docs/'), value: 'JP' };
it('sends the detected country without a choice', () => {
expect(
getVisitorCountryData({
cookies: [],
headers: detectedHeaders(),
url: new URL('https://example.com/docs'),
})
).toEqual({ country: 'FR', chosen: undefined, choiceFromParam: undefined });
});
it('reads the country from the gitbook.country param', () => {
expect(
getVisitorCountryData({
cookies: [countryCookie],
headers: detectedHeaders(),
url: new URL('https://example.com/docs?gitbook.country=us'),
})
).toEqual({ country: 'US', chosen: 'US', choiceFromParam: { country: 'US' } });
});
it('clears the choice with an empty gitbook.country param', () => {
expect(
getVisitorCountryData({
cookies: [countryCookie],
headers: detectedHeaders(),
url: new URL('https://example.com/docs?gitbook.country='),
})
).toEqual({ country: 'FR', chosen: undefined, choiceFromParam: { country: undefined } });
});
it("ignores another site's choice on the same host", () => {
expect(
getVisitorCountryData({
cookies: [{ name: getVisitorCountryCookieName('/other/'), value: 'JP' }],
headers: detectedHeaders(),
url: new URL('https://example.com/docs/page'),
}).chosen
).toBeUndefined();
});
it('skips an invalid choice for a more specific base path', () => {
expect(
getVisitorCountryData({
cookies: [
{ name: getVisitorCountryCookieName('/docs/'), value: 'XX' },
{ name: getVisitorCountryCookieName('/'), value: 'US' },
],
headers: detectedHeaders(),
url: new URL('https://example.com/docs/page'),
}).chosen
).toBe('US');
});
it('reads back the choice written for a proxied site', () => {
const url = new URL('https://proxy.gitbook.site/site/site_abc/docs/page');
const basePath = getVisitorAuthBasePath(url, { siteBasePath: '/docs/' });
expect(
getVisitorCountryData({
cookies: [{ name: getVisitorCountryCookieName(basePath), value: 'JP' }],
headers: detectedHeaders(),
url,
}).chosen
).toBe('JP');
});
it('prefers the choice of the most specific base path', () => {
expect(
getVisitorCountryData({
cookies: [{ name: getVisitorCountryCookieName('/'), value: 'US' }, countryCookie],
headers: detectedHeaders(),
url: new URL('https://example.com/docs/page'),
}).chosen
).toBe('JP');
});
it('replaces the detected country with the one from the cookie', () => {
expect(
getVisitorCountryData({
cookies: [countryCookie],
headers: detectedHeaders(),
url: new URL('https://example.com/docs'),
})
).toEqual({ country: 'JP', chosen: 'JP', choiceFromParam: undefined });
});
it('uses the chosen country when none is detected', () => {
expect(
getVisitorCountryData({
cookies: [countryCookie],
headers: new Headers(),
url: new URL('https://example.com/docs'),
}).country
).toBe('JP');
});
it.each(['XX', 'T1', 'ZZ', 'FRA', 'F', '1A', 'é', ' '])(
'ignores the invalid country %p',
(value) => {
expect(
getVisitorCountryData({
cookies: [{ name: getVisitorCountryCookieName('/docs/'), value }],
headers: detectedHeaders(),
url: new URL('https://example.com/docs'),
})
).toEqual({ country: 'FR', chosen: undefined, choiceFromParam: undefined });
const fromParam = getVisitorCountryData({
cookies: [],
headers: detectedHeaders(),
url: new URL(
`https://example.com/docs?gitbook.country=${encodeURIComponent(value)}`
),
});
expect(fromParam.country).toBe('FR');
expect(fromParam.chosen).toBeUndefined();
}
);
it('keeps the saved choice when the gitbook.country param is invalid', () => {
expect(
getVisitorCountryData({
cookies: [countryCookie],
headers: detectedHeaders(),
url: new URL('https://example.com/docs?gitbook.country=Europe'),
})
).toEqual({ country: 'JP', chosen: 'JP', choiceFromParam: undefined });
});
it('ignores the param and cookie on revalidation requests', () => {
expect(
getVisitorCountryData({
cookies: [countryCookie],
headers: revalidationHeaders,
url: new URL('https://example.com/docs?gitbook.country=US'),
})
).toEqual({ country: 'DE', chosen: undefined, choiceFromParam: undefined });
});
it('leaves visitor.country to the unsigned claims', () => {
const url = new URL('https://example.com/docs?visitor.country=fr');
expect(
getVisitorCountryData({ cookies: [], headers: detectedHeaders(), url }).chosen
).toBeUndefined();
expect(getVisitorUnsignedClaims({ cookies: [], url }).all).toEqual({ country: 'fr' });
});
it('keeps the country out of the unsigned claims but strips it from the URL', () => {
const url = new URL('https://example.com/docs?gitbook.country=US&visitor.plan=pro&page=2');
expect(getVisitorUnsignedClaims({ cookies: [], url })).toEqual({
all: { plan: 'pro' },
fromVisitorParams: { plan: 'pro' },
});
expect(normalizeVisitorURL(url).toString()).toBe('https://example.com/docs?page=2');
});
});
describe('getVisitorCountryResponseCookie', () => {
it('persists the choice in a cookie scoped to the site', () => {
expect(
getVisitorCountryResponseCookie({
siteBasePath: '/docs/',
country: 'US',
headers: new Headers(),
})
).toMatchObject({
name: getVisitorCountryCookieName('/docs/'),
value: 'US',
options: { path: '/', sameSite: 'lax', maxAge: 365 * 24 * 60 * 60 },
});
});
it('clears the choice', () => {
expect(
getVisitorCountryResponseCookie({
siteBasePath: '/docs/',
country: undefined,
headers: new Headers(),
})
).toMatchObject({ value: '', options: { maxAge: 0 } });
});
it('names the cookie the same with or without slashes around the base path', () => {
expect(getVisitorCountryCookieName('docs')).toBe(getVisitorCountryCookieName('/docs/'));
});
});
describe('serveVisitorCountryRequest', () => {
it('returns the detected and chosen countries without caching', async () => {
const request = new NextRequest('https://example.com/docs/~gitbook/visitor/country', {
headers: {
'x-open-next-country': 'fr',
cookie: `${getVisitorCountryCookieName('/docs/')}=JP`,
},
});
const response = serveVisitorCountryRequest(request, request.nextUrl);
expect(response.headers.get('cache-control')).toBe('private, no-store');
expect(JSON.parse(await response.text())).toEqual({ detected: 'FR', chosen: 'JP' });
});
});
+125 -14
View File
@@ -10,6 +10,13 @@ import {
getChunkedCookieValue,
getChunkedResponseCookies,
} from './chunked-cookies';
import { normalizeCountryCode, parseCountryChoice } from './countries';
import { withLeadingSlash, withTrailingSlash } from './paths';
import {
VISITOR_COUNTRY_COOKIE,
VISITOR_COUNTRY_COOKIE_MAX_AGE,
VISITOR_COUNTRY_PARAM,
} from './visitor-country';
const VISITOR_AUTH_PARAM = 'jwt_token';
const VISITOR_PARAM_PREFIX = 'visitor.';
@@ -114,21 +121,11 @@ export function getVisitorType(request: {
*/
export function getVisitorCountry(request: { headers: Headers }): string | undefined {
// The revalidation worker forwards the original visitor country; only trust it from there.
const country = (
return normalizeCountryCode(
(isRevalidationRequest(request.headers) && request.headers.get('x-gitbook-country')) ||
request.headers.get('x-open-next-country') ||
request.headers.get('x-vercel-ip-country') ||
''
)
.trim()
.toUpperCase();
// Cloudflare uses XX for unknown and T1 for Tor, which are not ISO codes.
if (!/^[A-Z]{2}$/.test(country) || country === 'XX' || country === 'T1') {
return undefined;
}
return country;
request.headers.get('x-open-next-country') ||
request.headers.get('x-vercel-ip-country')
);
}
/**
@@ -168,6 +165,117 @@ export function isRevalidationRequest(headers: Headers): boolean {
return headers.get('user-agent')?.toLowerCase() === 'gitbook-open-revalidation-worker';
}
/**
* The visitor's country, as sent to the API.
*/
export type VisitorCountryData = {
/** Country sent to the API: the chosen one, otherwise the detected one. */
country: string | undefined;
/** Country the visitor chose in the country picker. */
chosen: string | undefined;
/** Choice passed in the URL, to persist once the site's base path is known. */
choiceFromParam: { country: string | undefined } | undefined;
};
/**
* Get the name of the country cookie for a site. Scoped to the site so that sites sharing a host
* keep their own choice.
*/
export function getVisitorCountryCookieName(siteBasePath: string): string {
return getPathScopedCookieName(
VISITOR_COUNTRY_COOKIE,
withTrailingSlash(withLeadingSlash(siteBasePath))
);
}
/**
* Get the visitor's country: the one chosen through the `gitbook.country` param or else the
* country cookie, otherwise the detected one. An empty param clears the choice.
*/
export function getVisitorCountryData({
cookies,
headers,
url,
}: {
cookies: RequestCookies;
headers: Headers;
url: URL | NextRequest['nextUrl'];
}): VisitorCountryData {
const detected = getVisitorCountry({ headers });
// The revalidation worker pins the country it forwards.
if (isRevalidationRequest(headers)) {
return { country: detected, chosen: undefined, choiceFromParam: undefined };
}
const fromParam = url.searchParams.get(VISITOR_COUNTRY_PARAM);
const chosenFromParam = parseCountryChoice(fromParam);
// An invalid value is ignored rather than clearing a saved choice.
if (fromParam !== null && (chosenFromParam || fromParam.trim() === '')) {
return {
country: chosenFromParam ?? detected,
chosen: chosenFromParam,
choiceFromParam: { country: chosenFromParam },
};
}
// The site isn't resolved yet, so the most specific base path with a choice wins.
let chosen: string | undefined;
for (const basePath of getUrlBasePathCombinations(url)) {
const name = getVisitorCountryCookieName(basePath);
chosen = parseCountryChoice(cookies.find((cookie) => cookie.name === name)?.value);
if (chosen) {
break;
}
}
return { country: chosen ?? detected, chosen, choiceFromParam: undefined };
}
/**
* Cookie persisting, or clearing, the country chosen through the URL for a site.
*/
export function getVisitorCountryResponseCookie({
siteBasePath,
country,
headers,
}: {
siteBasePath: string;
country: string | undefined;
headers: Headers;
}): ResponseCookie {
return {
name: getVisitorCountryCookieName(siteBasePath),
value: country ?? '',
options: {
path: '/',
// Inside an embed, a Lax cookie would be dropped as third-party.
...(headers.get('sec-fetch-dest') === 'iframe'
? getVisitorCookieCrossSiteOptions(headers)
: { sameSite: 'lax' as const, secure: IS_SECURE }),
maxAge: country ? VISITOR_COUNTRY_COOKIE_MAX_AGE : 0,
},
};
}
/**
* Handler for the visitor country middleware route, read by the country picker. Static routes are
* shared across countries, so they can't render the visitor's countries themselves.
*/
export function serveVisitorCountryRequest(
request: NextRequest,
siteRequestURL: URL | NextRequest['nextUrl']
) {
const { chosen } = getVisitorCountryData({
cookies: request.cookies.getAll(),
headers: request.headers,
url: siteRequestURL,
});
return NextResponse.json(
{ detected: getVisitorCountry(request) ?? null, chosen: chosen ?? null },
{ headers: { 'cache-control': 'private, no-store' } }
);
}
/**
* Get the visitor token for the request. This token can either be in the
* query parameters or stored as a cookie.
@@ -441,6 +549,9 @@ export function normalizeVisitorURL(url: URL): URL {
if (url.searchParams.has(VISITOR_AUTH_PARAM)) {
withoutVisitorParamsURL.searchParams.delete(VISITOR_AUTH_PARAM);
}
if (url.searchParams.has(VISITOR_COUNTRY_PARAM)) {
withoutVisitorParamsURL.searchParams.delete(VISITOR_COUNTRY_PARAM);
}
for (const [urlParam] of url.searchParams.entries()) {
if (urlParam.startsWith(VISITOR_PARAM_PREFIX)) {
+26 -3
View File
@@ -75,16 +75,19 @@ import {
UPDATES_PAGE_SEARCH_PARAM,
parseUpdatesPageParam,
} from '@/lib/updates-url';
import { VISITOR_COUNTRY_PATH } from '@/lib/visitor-country';
import {
type ResponseCookies,
getPathScopedCookieName,
getResponseCookiesForVisitorAuth,
getVisitorCountry,
getVisitorCountryData,
getVisitorCountryResponseCookie,
getVisitorData,
getVisitorType,
isRevalidationRequest,
normalizeVisitorURL,
serveVisitorClaimsDataRequest,
serveVisitorCountryRequest,
} from '@/lib/visitors';
import { waitUntil } from '@/lib/waitUntil';
import { serveResizedImage } from '@/routes/image';
@@ -347,6 +350,9 @@ async function serveSiteRequest(requestURL: URL, request: NextRequest, match: UR
if (siteRequestURL.pathname.endsWith('/~gitbook/visitor')) {
return serveVisitorClaimsDataRequest(request, siteRequestURL);
}
if (siteRequestURL.pathname.endsWith(`/${VISITOR_COUNTRY_PATH}`)) {
return serveVisitorCountryRequest(request, siteRequestURL);
}
//
// Detect and extract the visitor authentication token from the request
@@ -362,7 +368,13 @@ async function serveSiteRequest(requestURL: URL, request: NextRequest, match: UR
//
request.headers.delete('x-gitbook-disable-tracking');
const visitorCountry = getVisitorCountry(request);
// The country picker's choice is honoured on every site: the lookup doesn't return the
// customization that enables the picker, and fetching it here would slow down every request.
const visitorCountry = getVisitorCountryData({
cookies: request.cookies.getAll(),
headers: request.headers,
url: siteRequestURL,
});
const withAPIToken = async (apiToken: string | null) => {
const lookup = await lookupPublishedContentByUrl({
@@ -371,7 +383,7 @@ async function serveSiteRequest(requestURL: URL, request: NextRequest, match: UR
jwtToken: visitorToken?.token ?? undefined,
unsignedClaims,
type: getVisitorType(request),
...(visitorCountry ? { country: visitorCountry } : {}),
...(visitorCountry.country ? { country: visitorCountry.country } : {}),
},
// When the visitor auth token is pulled from the cookie, set redirectOnError when calling resolvePublishedContentByUrl to allow
// redirecting when the token is invalid as we could be dealing with stale token stored in the cookie.
@@ -471,6 +483,17 @@ async function serveSiteRequest(requestURL: URL, request: NextRequest, match: UR
return createRedirectResponse(siteURLData.redirect);
}
if (visitorCountry.choiceFromParam) {
cookies.push(
getVisitorCountryResponseCookie({
// Proxied requests can't read back a cookie scoped to the resolved base path.
siteBasePath: getVisitorAuthBasePath(siteRequestURL, siteURLData),
country: visitorCountry.choiceFromParam.country,
headers: request.headers,
})
);
}
// Handles OAuth protected resource metadata for non-VA adaptive content sites.
// Only the `~gitbook/mcp/auth` endpoint advertises auth here; the base `~gitbook/mcp`
// endpoint stays public so clients doing proactive PRM discovery don't start an OAuth