diff --git a/packages/gitbook/src/components/DocumentView/Annotation/AnnotationPopover.tsx b/packages/gitbook/src/components/DocumentView/Annotation/AnnotationPopover.tsx index 4766a46fb..d5eafad62 100644 --- a/packages/gitbook/src/components/DocumentView/Annotation/AnnotationPopover.tsx +++ b/packages/gitbook/src/components/DocumentView/Annotation/AnnotationPopover.tsx @@ -19,7 +19,7 @@ export function AnnotationPopover(props: { children: React.ReactNode; body: Reac > diff --git a/packages/gitbook/src/components/Embeddable/EmbeddableDocsPage.tsx b/packages/gitbook/src/components/Embeddable/EmbeddableDocsPage.tsx index d63e44128..ebd08e3e4 100644 --- a/packages/gitbook/src/components/Embeddable/EmbeddableDocsPage.tsx +++ b/packages/gitbook/src/components/Embeddable/EmbeddableDocsPage.tsx @@ -2,6 +2,7 @@ import type { Metadata } from 'next'; import { SiteInsightsDisplayContext } from '@gitbook/api'; +import { CountryPicker } from '../Header/CountryPicker'; import { HeaderMobileMenu } from '../Header/HeaderMobileMenu'; import { SpacesDropdown, TranslationsDropdown } from '../Header/SpacesDropdown'; import { PageBody } from '../PageBody'; @@ -48,6 +49,19 @@ export async function EmbeddableDocsPage( }); const variants = categorizeVariants(context); + const translationsDropdown = + variants.translations.length > 1 ? ( + space.id === context.siteSpace.id) ?? + context.siteSpace + } + siteSpaces={variants.translations} + asEmbeddable + className="max-md:[&_.button-content]:block" + /> + ) : null; return ( @@ -88,6 +102,12 @@ export async function EmbeddableDocsPage( asEmbeddable: true, })} > + {context.countryPicker ? ( + + ) : null} {variants.translations.length > 1 ? ( 1 ? ( - space.id === context.siteSpace.id - ) ?? context.siteSpace - } - siteSpaces={variants.translations} - asEmbeddable - className="max-md:[&_.button-content]:block" - /> + !context.sections && context.countryPicker ? ( +
+ + {translationsDropdown} +
+ ) : !context.sections ? ( + translationsDropdown ) : null } innerHeader={ diff --git a/packages/gitbook/src/components/Header/CountryPicker.tsx b/packages/gitbook/src/components/Header/CountryPicker.tsx new file mode 100644 index 000000000..9b5e2b917 --- /dev/null +++ b/packages/gitbook/src/components/Header/CountryPicker.tsx @@ -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 ( + + ); +} diff --git a/packages/gitbook/src/components/Header/CountryPickerClient.tsx b/packages/gitbook/src/components/Header/CountryPickerClient.tsx new file mode 100644 index 000000000..f48b7c104 --- /dev/null +++ b/packages/gitbook/src/components/Header/CountryPickerClient.tsx @@ -0,0 +1,294 @@ +'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_COOKIE, + VISITOR_COUNTRY_COOKIE_MAX_AGE, +} 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>(); + +function fetchVisitorCountries(url: string): Promise { + 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, or null until they are known. + */ +function useVisitorCountries(url: string): VisitorCountries | null { + const [countries, setCountries] = React.useState(null); + React.useEffect(() => { + let cancelled = false; + fetchVisitorCountries(url).then((result) => { + if (!cancelled) { + setCountries(result); + } + }); + return () => { + cancelled = true; + }; + }, [url]); + return countries; +} + +/** + * Store the country the visitor chose, or clear it to go back to the detected one. + */ +function setVisitorCountryCookie(country: string | undefined) { + const isSecure = window.location.protocol === 'https:'; + // Inside a cross-site embed, a Lax cookie would be dropped as third-party. + const isCrossSiteFrame = isSecure && window.self !== window.top; + const attributes = [ + 'Path=/', + `Max-Age=${country ? VISITOR_COUNTRY_COOKIE_MAX_AGE : 0}`, + ...(isCrossSiteFrame ? ['SameSite=None', 'Partitioned'] : ['SameSite=Lax']), + ...(isSecure ? ['Secure'] : []), + ]; + document.cookie = `${VISITOR_COUNTRY_COOKIE}=${encodeURIComponent(country ?? '')}; ${attributes.join('; ')}`; +} + +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 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; + } + setVisitorCountryCookie(country); + // A full navigation runs the middleware again, so the content follows the new country. + window.location.reload(); + }; + + return ( + 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() === '' + } + > + } + className={tcls('group/dropdown bg-tint-base', className)} + aria-label={tString(language, 'country_picker_label', buttonLabel)} + > + + {currentCountry && currentName ? ( + + {getCountryFlag(currentCountry)} + + ) : null} + {buttonLabel} + {!chosen && currentName ? ( + + {tString(language, 'country_picker_auto_hint')} + + ) : null} + + + } + /> + + + +
+ + +
+ + {tString(language, 'country_picker_no_results')} + + + {(group: CountryOptionGroup) => ( + + {group.label ? ( + + {group.label} + + ) : null} + + {(option: CountryOption) => ( + + {option.flag ? ( + + {option.flag} + + ) : ( + + )} + {option.label} + + + + + )} + + + )} + +
+
+
+
+ ); +} diff --git a/packages/gitbook/src/components/Header/Header.tsx b/packages/gitbook/src/components/Header/Header.tsx index 32ccb9687..d24bb3898 100644 --- a/packages/gitbook/src/components/Header/Header.tsx +++ b/packages/gitbook/src/components/Header/Header.tsx @@ -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)) ? ( {customization.header.links.map((link) => { return ( @@ -189,6 +191,12 @@ export async function Header(props: { context={context} /> ) : null} + {!withSections && context.countryPicker ? ( + + ) : null} {!withSections && variants.translations.length > 1 ? ( + {context.countryPicker ? ( + + ) : null} {variants.translations.length > 1 ? ( +
+ {context.countryPicker ? ( + + ) : null} {variants.translations.length > 1 ? ( ) : null} diff --git a/packages/gitbook/src/components/primitives/DropdownMenu.tsx b/packages/gitbook/src/components/primitives/DropdownMenu.tsx index 83ed2c766..409cdfc10 100644 --- a/packages/gitbook/src/components/primitives/DropdownMenu.tsx +++ b/packages/gitbook/src/components/primitives/DropdownMenu.tsx @@ -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; diff --git a/packages/gitbook/src/components/primitives/HoverCard.tsx b/packages/gitbook/src/components/primitives/HoverCard.tsx index e65324882..9337d9098 100644 --- a/packages/gitbook/src/components/primitives/HoverCard.tsx +++ b/packages/gitbook/src/components/primitives/HoverCard.tsx @@ -43,7 +43,7 @@ export function HoverCard( >
{ 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, diff --git a/packages/gitbook/src/lib/countries.test.ts b/packages/gitbook/src/lib/countries.test.ts new file mode 100644 index 000000000..929cf4922 --- /dev/null +++ b/packages/gitbook/src/lib/countries.test.ts @@ -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('🇺🇸'); + }); +}); diff --git a/packages/gitbook/src/lib/countries.ts b/packages/gitbook/src/lib/countries.ts new file mode 100644 index 000000000..79b05b7de --- /dev/null +++ b/packages/gitbook/src/lib/countries.ts @@ -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(); + 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) + ); +} diff --git a/packages/gitbook/src/lib/visitor-country.ts b/packages/gitbook/src/lib/visitor-country.ts new file mode 100644 index 000000000..6a4fa0dc5 --- /dev/null +++ b/packages/gitbook/src/lib/visitor-country.ts @@ -0,0 +1,33 @@ +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; + +/** 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; +} diff --git a/packages/gitbook/src/lib/visitors.test.ts b/packages/gitbook/src/lib/visitors.test.ts index b1d27acef..f54416abe 100644 --- a/packages/gitbook/src/lib/visitors.test.ts +++ b/packages/gitbook/src/lib/visitors.test.ts @@ -1,6 +1,6 @@ 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 { type ResponseCookies, @@ -9,11 +9,13 @@ import { getVisitorAuthCookieName, getVisitorAuthCookieValue, getVisitorCountry, + getVisitorCountryData, getVisitorToken, getVisitorType, getVisitorUnsignedClaims, isRevalidationRequest, normalizeVisitorURL, + serveVisitorCountryRequest, } from './visitors'; describe('getVisitorAuthToken', () => { @@ -711,3 +713,152 @@ 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: 'gitbook-visitor-country', 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, responseCookie: undefined }); + }); + + it('reads the country from the gitbook.country param and persists it in a cookie', () => { + const data = getVisitorCountryData({ + cookies: [countryCookie], + headers: detectedHeaders(), + url: new URL('https://example.com/docs?gitbook.country=us'), + }); + + expect(data.country).toBe('US'); + expect(data.chosen).toBe('US'); + expect(data.responseCookie).toMatchObject({ + name: 'gitbook-visitor-country', + value: 'US', + options: { path: '/', sameSite: 'lax', maxAge: 365 * 24 * 60 * 60 }, + }); + }); + + it('clears the choice with an empty gitbook.country param', () => { + const data = getVisitorCountryData({ + cookies: [countryCookie], + headers: detectedHeaders(), + url: new URL('https://example.com/docs?gitbook.country='), + }); + + expect(data.country).toBe('FR'); + expect(data.chosen).toBeUndefined(); + expect(data.responseCookie).toMatchObject({ + name: 'gitbook-visitor-country', + value: '', + options: { maxAge: 0 }, + }); + }); + + 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', responseCookie: 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: 'gitbook-visitor-country', value }], + headers: detectedHeaders(), + url: new URL('https://example.com/docs'), + }) + ).toEqual({ country: 'FR', chosen: undefined, responseCookie: 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', responseCookie: 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, responseCookie: 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('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: 'gitbook-visitor-country=JP', + }, + }); + + const response = serveVisitorCountryRequest(request); + + expect(response.headers.get('cache-control')).toBe('private, no-store'); + expect(JSON.parse(await response.text())).toEqual({ detected: 'FR', chosen: 'JP' }); + }); +}); diff --git a/packages/gitbook/src/lib/visitors.ts b/packages/gitbook/src/lib/visitors.ts index 4ef79c1e5..a760aa554 100644 --- a/packages/gitbook/src/lib/visitors.ts +++ b/packages/gitbook/src/lib/visitors.ts @@ -10,9 +10,13 @@ import { getChunkedCookieValue, getChunkedResponseCookies, } from './chunked-cookies'; +import { normalizeCountryCode, parseCountryChoice } from './countries'; +import { VISITOR_COUNTRY_COOKIE, VISITOR_COUNTRY_COOKIE_MAX_AGE } from './visitor-country'; const VISITOR_AUTH_PARAM = 'jwt_token'; const VISITOR_PARAM_PREFIX = 'visitor.'; +// Outside `visitor.*`, which carries the adaptive schema's unsigned claims. +const VISITOR_COUNTRY_PARAM = 'gitbook.country'; export const VISITOR_TOKEN_COOKIE = 'gitbook-visitor-token'; const VISITOR_UNSIGNED_CLAIMS_PREFIX = 'gitbook-visitor-public'; const IS_SECURE = process.env.NODE_ENV === 'production'; @@ -114,21 +118,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 +162,82 @@ 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; + /** Cookie persisting a choice passed in the URL. */ + responseCookie: ResponseCookie | undefined; +}; + +/** + * 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, responseCookie: 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, + responseCookie: { + name: VISITOR_COUNTRY_COOKIE, + value: chosenFromParam ?? '', + 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: chosenFromParam ? VISITOR_COUNTRY_COOKIE_MAX_AGE : 0, + }, + }, + }; + } + + const chosen = parseCountryChoice( + cookies.find((cookie) => cookie.name === VISITOR_COUNTRY_COOKIE)?.value + ); + return { country: chosen ?? detected, chosen, responseCookie: undefined }; +} + +/** + * 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) { + const { chosen } = getVisitorCountryData({ + cookies: request.cookies.getAll(), + headers: request.headers, + url: request.nextUrl, + }); + 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 +511,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)) { diff --git a/packages/gitbook/src/middleware.ts b/packages/gitbook/src/middleware.ts index f737d5558..4c473e408 100644 --- a/packages/gitbook/src/middleware.ts +++ b/packages/gitbook/src/middleware.ts @@ -64,16 +64,18 @@ import { createRobotsTxtResponse, isRobotsTxtRequest, } from '@/lib/robots'; +import { VISITOR_COUNTRY_PATH } from '@/lib/visitor-country'; import { type ResponseCookies, getPathScopedCookieName, getResponseCookiesForVisitorAuth, - getVisitorCountry, + getVisitorCountryData, getVisitorData, getVisitorType, isRevalidationRequest, normalizeVisitorURL, serveVisitorClaimsDataRequest, + serveVisitorCountryRequest, } from '@/lib/visitors'; import { waitUntil } from '@/lib/waitUntil'; import { serveResizedImage } from '@/routes/image'; @@ -242,6 +244,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); + } // // Detect and extract the visitor authentication token from the request @@ -257,7 +262,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({ @@ -266,7 +277,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. @@ -297,6 +308,9 @@ async function serveSiteRequest(requestURL: URL, request: NextRequest, match: UR visitorParamsCookie, ] : []; + if (visitorCountry.responseCookie) { + cookies.push(visitorCountry.responseCookie); + } // // Handle redirects