From 615d66319277d2f1f63100ea5f1b0644a76cbb14 Mon Sep 17 00:00:00 2001 From: Gauthier Eholoum Date: Thu, 3 Dec 2026 01:50:51 +0000 Subject: [PATCH 1/2] feat: search providers by what their sheets state --- tests/{search-index.test.ts => search-match.test.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename tests/{search-index.test.ts => search-match.test.ts} (100%) diff --git a/tests/search-index.test.ts b/tests/search-match.test.ts similarity index 100% rename from tests/search-index.test.ts rename to tests/search-match.test.ts From ed64d240bdc3658dc7353a65a5fcb2767a93a67e Mon Sep 17 00:00:00 2001 From: Gauthier Eholoum Date: Thu, 3 Dec 2026 01:52:11 +0000 Subject: [PATCH 2/2] feat: add the search engine and its window --- data/reference/places.json | 21 ++ docs/architecture.md | 16 +- src/components/header/SearchDialog.astro | 308 ++++------------------- src/i18n/ui-en.ts | 24 +- src/i18n/ui-fr.ts | 26 +- src/i18n/ui-types.ts | 24 ++ src/lib/check-reference-data.ts | 6 +- src/lib/data-paths.ts | 1 + src/lib/dataset-types.ts | 3 +- src/lib/glossary-look.ts | 1 + src/lib/glossary-search.ts | 2 +- src/lib/load-dataset.ts | 6 +- src/lib/search-index.ts | 30 --- src/lib/search-match.ts | 24 -- src/lib/search-types.ts | 27 -- src/lib/site-data.ts | 1 + src/lib/site-types.ts | 11 +- src/pages/search/[locale].json.ts | 10 + src/schema/constants.ts | 1 + src/schema/reference.ts | 9 + src/search/build-index.ts | 148 +++++++++++ src/search/build-payload.ts | 43 ++++ src/search/elements.ts | 65 +++++ src/search/features.ts | 137 ++++++++++ src/search/parse-query.ts | 139 ++++++++++ src/search/payload-types.ts | 39 +++ src/search/render-results.ts | 126 ++++++++++ src/search/search.ts | 126 ++++++++++ src/search/section-look.ts | 20 ++ src/search/text.ts | 35 +++ src/search/types.ts | 97 +++++++ src/search/view-types.ts | 52 ++++ src/search/view.ts | 130 ++++++++++ src/search/vocabulary.ts | 65 +++++ src/search/window.ts | 267 ++++++++++++++++++++ src/styles/search.css | 108 ++++++++ tests/fixtures/records.ts | 1 + tests/load-dataset.test.ts | 1 + tests/search-engine.test.ts | 163 ++++++++++++ tests/search-match.test.ts | 66 +---- tests/search-view.test.ts | 70 ++++++ 41 files changed, 2030 insertions(+), 419 deletions(-) create mode 100644 data/reference/places.json delete mode 100644 src/lib/search-index.ts delete mode 100644 src/lib/search-types.ts create mode 100644 src/pages/search/[locale].json.ts create mode 100644 src/search/build-index.ts create mode 100644 src/search/build-payload.ts create mode 100644 src/search/elements.ts create mode 100644 src/search/features.ts create mode 100644 src/search/parse-query.ts create mode 100644 src/search/payload-types.ts create mode 100644 src/search/render-results.ts create mode 100644 src/search/search.ts create mode 100644 src/search/section-look.ts create mode 100644 src/search/text.ts create mode 100644 src/search/types.ts create mode 100644 src/search/view-types.ts create mode 100644 src/search/view.ts create mode 100644 src/search/vocabulary.ts create mode 100644 src/search/window.ts create mode 100644 src/styles/search.css create mode 100644 tests/search-engine.test.ts create mode 100644 tests/search-view.test.ts diff --git a/data/reference/places.json b/data/reference/places.json new file mode 100644 index 0000000..c1feb6b --- /dev/null +++ b/data/reference/places.json @@ -0,0 +1,21 @@ +[ + {"country": "BF", "aliases": ["Ouagadougou", "Bobo-Dioulasso"]}, + {"country": "BJ", "aliases": ["Cotonou", "Porto-Novo"]}, + {"country": "CD", "aliases": ["RDC", "DRC", "RD Congo", "DR Congo", "Congo Kinshasa", "Kinshasa", "Lubumbashi"]}, + {"country": "CG", "aliases": ["Congo Brazzaville", "Brazzaville", "Pointe-Noire"]}, + {"country": "CI", "aliases": ["Abidjan", "Yamoussoukro", "RCI"]}, + {"country": "CM", "aliases": ["Douala", "Yaoundé"]}, + {"country": "GA", "aliases": ["Libreville"]}, + {"country": "GH", "aliases": ["Accra", "Kumasi"]}, + {"country": "KE", "aliases": ["Nairobi", "Mombasa"]}, + {"country": "ML", "aliases": ["Bamako"]}, + {"country": "NE", "aliases": ["Niamey"]}, + {"country": "NG", "aliases": ["Lagos", "Abuja"]}, + {"country": "RW", "aliases": ["Kigali"]}, + {"country": "SN", "aliases": ["Dakar"]}, + {"country": "TD", "aliases": ["N'Djamena"]}, + {"country": "TG", "aliases": ["Lomé"]}, + {"country": "TZ", "aliases": ["Dar es Salaam", "Dodoma"]}, + {"country": "UG", "aliases": ["Kampala"]}, + {"country": "ZA", "aliases": ["Johannesburg", "Le Cap", "Cape Town", "Pretoria"]} +] diff --git a/docs/architecture.md b/docs/architecture.md index d130541..2496c56 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -7,13 +7,14 @@ Status: living document. Settled decisions are in `adr/`. ``` data/ providers/.json one file per provider, every claim sourced - reference/ countries, currencies, regulators, payment brands + reference/ countries, places, currencies, regulators, payment brands glossary/ terms of the glossary page, one file per section registers/ official registers, extracted from the source PDF LICENSE CC BY-SA 4.0 src/ schema/ zod schemas: the single definition of valid data lib/ loading and cross-file checks + search/ site search: declarations, index, query reading, window pages/ static site scripts/validate-data.ts runs every check, used by CI tests/ vitest @@ -23,6 +24,19 @@ tests/ vitest The site is a static build of `data/`. Only `verified` records are published; drafts stay in the repository until a maintainer checks them. +## Search + +The search window runs in the browser on one JSON file per language, built +from the same data as the pages. To make something a sheet states searchable, +add an entry to `src/search/features.ts`: its words, its section and a test on +the record. Languages of official SDKs, currencies and regulators are read from +the records and need no declaration. + +A method or a currency is matched in the country it is stated for. Unknown is +never a yes, and "without X" is not answered: a silent sheet states nothing. +`reference/places.json` holds other names of a country (cities, acronyms). It +only helps a search understand a word; it asserts nothing about a provider. + ## How a contribution becomes a published fact 1. Someone opens an issue form (new provider, correction, experience), or a diff --git a/src/components/header/SearchDialog.astro b/src/components/header/SearchDialog.astro index cca54f3..f0cf6fe 100644 --- a/src/components/header/SearchDialog.astro +++ b/src/components/header/SearchDialog.astro @@ -1,12 +1,12 @@ --- +import '../../styles/search.css'; + import type { Locale } from '../../i18n/locales'; import { ui } from '../../i18n/translate'; import { inlineJson } from '../../lib/inline-json'; -import { searchIndex } from '../../lib/search-index'; -import { currentSite } from '../../lib/site-data'; import { NEW_PROVIDER_URL } from '../../lib/site-links'; -/** Search window opened from the header bar, the mobile magnifier or ⌘K. Finds verified providers only. */ +/** Search window opened from the header bar, the mobile magnifier or ⌘K. See `src/search/`. */ interface Props { locale: Locale; } @@ -14,21 +14,14 @@ interface Props { const { locale } = Astro.props; const strings = ui(locale); const t = strings.search; -const site = currentSite(); - -const entries = searchIndex({ - providers: site.published, - locale, - brands: site.lookups.brands, - marks: site.lookups.marks, - meta: (provider) => t.countries(new Set(provider.coverage.map((entry) => entry.country)).size), -}); --- - +
- - +
-
-

{t.idle}

-

+

+ +
+ +

{t.idleTitle}

+

{t.idle}

+
- + + - + - - - - - + diff --git a/src/i18n/ui-en.ts b/src/i18n/ui-en.ts index 6b773c0..b6a40cf 100644 --- a/src/i18n/ui-en.ts +++ b/src/i18n/ui-en.ts @@ -22,12 +22,30 @@ export const UI_EN: UiStrings = { search: { dialogLabel: 'Search the directory', escape: 'esc', + placeholder: 'Search…', + clear: 'Clear', providers: 'Providers', countries: (count) => (count === 1 ? '1 country' : `${count} countries`), - idle: 'Type a provider name, a country or a payment method.', - found: { one: '1 provider found', other: '{count} providers found' }, + glossary: 'Glossary', + idleTitle: 'What are you looking for?', + idle: 'A provider, a country, a payment method or a feature such as “sandbox”.', + found: { one: '1 result', other: '{count} results' }, + partial: '{shown} of {total}', + more: { one: 'Show 1 more', other: 'Show {count} more' }, + corrected: 'Results for {name}. You typed “{query}”.', + ignored: 'Not recognised: {words}. These results answer the rest.', + or: ' or ', noResult: 'No results for “{query}”', - noResultHint: 'Try another spelling or a broader term.', + noResultHint: 'Try a provider name, a country or a payment method.', + notStated: 'No sheet states this yet', + notStatedHint: 'We understood: {criteria}. No verified provider meets all of it at once. Try with one word less.', + sectionAlone: '{section}: of which provider?', + sectionAloneHint: 'Add its name, for example “{query} wave”.', + negation: 'Search cannot leave things out', + negationHint: 'A sheet that says nothing is not a sheet that says no. Search “{criterion}” to see the providers that state it.', + loading: 'Loading…', + unavailable: 'Search could not load', + unavailableHint: 'Check your connection, then close and reopen this window.', suggest: 'Suggest a provider', keys: '↑↓ navigate · ↵ open · esc close', }, diff --git a/src/i18n/ui-fr.ts b/src/i18n/ui-fr.ts index b1a662d..f704c5f 100644 --- a/src/i18n/ui-fr.ts +++ b/src/i18n/ui-fr.ts @@ -22,12 +22,30 @@ export const UI_FR: UiStrings = { search: { dialogLabel: 'Rechercher dans l’annuaire', escape: 'échap', + placeholder: 'Rechercher…', + clear: 'Effacer', providers: 'Services', countries: (count) => (count === 1 ? '1 pays' : `${count} pays`), - idle: 'Tapez le nom d’un service, un pays ou un moyen de paiement.', - found: { one: '1 service trouvé', other: '{count} services trouvés' }, - noResult: 'Aucun résultat pour « {query} »', - noResultHint: 'Essayez une autre orthographe ou un terme plus large.', + glossary: 'Glossaire', + idleTitle: 'Que cherchez-vous ?', + idle: 'Un service, un pays, un moyen de paiement ou une fonction comme «\u00a0sandbox\u00a0».', + found: { one: '1 résultat', other: '{count} résultats' }, + partial: '{shown} sur {total}', + more: { one: 'Afficher l’autre', other: 'Afficher les {count} autres' }, + corrected: 'Résultats pour {name}. Vous avez écrit «\u00a0{query}\u00a0».', + ignored: 'Mot non reconnu : {words}. Les résultats portent sur le reste.', + or: ' ou ', + noResult: 'Aucun résultat pour «\u00a0{query}\u00a0»', + noResultHint: 'Essayez le nom d’un service, un pays ou un moyen de paiement.', + notStated: 'Aucune fiche ne l’indique pour l’instant', + notStatedHint: 'Nous avons compris : {criteria}. Aucun service vérifié ne remplit tout à la fois. Essayez avec un mot de moins.', + sectionAlone: '{section} : de quel service ?', + sectionAloneHint: 'Ajoutez son nom, par exemple «\u00a0{query} wave\u00a0».', + negation: 'La recherche ne sait pas exclure', + negationHint: 'Une fiche qui ne dit rien n’est pas une fiche qui dit non. Cherchez « {criterion} » pour voir les services qui l’indiquent.', + loading: 'Chargement…', + unavailable: 'La recherche n’a pas pu se charger', + unavailableHint: 'Vérifiez votre connexion, puis fermez et rouvrez cette fenêtre.', suggest: 'Proposer un service', keys: '↑↓ naviguer · ↵ ouvrir · échap fermer', }, diff --git a/src/i18n/ui-types.ts b/src/i18n/ui-types.ts index 6ca7270..b5c2452 100644 --- a/src/i18n/ui-types.ts +++ b/src/i18n/ui-types.ts @@ -56,14 +56,38 @@ export interface FooterLink { export interface SearchStrings { readonly dialogLabel: string; readonly escape: string; + readonly placeholder: string; + readonly clear: string; readonly providers: string; readonly countries: (count: number) => string; + readonly glossary: string; + readonly idleTitle: string; readonly idle: string; /** Read out by screen readers after each keystroke; `{count}` is replaced in the browser. */ readonly found: { readonly one: string; readonly other: string }; + /** `{shown}` of `{total}` providers, above a shortened list. */ + readonly partial: string; + readonly more: { readonly one: string; readonly other: string }; + /** The words typed stand for something spelt otherwise: `{name}`, `{query}`. */ + readonly corrected: string; + /** Words the search does not know: `{words}`. */ + readonly ignored: string; + readonly or: string; /** `{query}` is replaced in the browser by what the visitor typed. */ readonly noResult: string; readonly noResultHint: string; + /** Everything typed is understood (`{criteria}`), but no sheet states it all. */ + readonly notStated: string; + readonly notStatedHint: string; + /** A section such as "fees" was asked for without a provider: `{section}`. */ + readonly sectionAlone: string; + readonly sectionAloneHint: string; + /** A word such as "without" was used: `{criterion}`. */ + readonly negation: string; + readonly negationHint: string; + readonly loading: string; + readonly unavailable: string; + readonly unavailableHint: string; readonly suggest: string; readonly keys: string; } diff --git a/src/lib/check-reference-data.ts b/src/lib/check-reference-data.ts index 1ffb91b..98f3362 100644 --- a/src/lib/check-reference-data.ts +++ b/src/lib/check-reference-data.ts @@ -1,5 +1,5 @@ import type { Dataset, Issue, KnownIds, ReferenceContext, Report } from './dataset-types'; -import { BRANDS_FILE, COUNTRIES_FILE, CURRENCIES_FILE, REGULATORS_FILE } from './data-paths'; +import { BRANDS_FILE, COUNTRIES_FILE, CURRENCIES_FILE, PLACES_FILE, REGULATORS_FILE } from './data-paths'; import { requireCountry, requireCurrency, requireRegulator } from './require-known'; /** Reference lists and register snapshots: no duplicates, no dangling identifier. */ @@ -39,6 +39,10 @@ function checkCountryCurrencies(dataset: Dataset, ctx: ReferenceContext): void { } function checkListedCountries(dataset: Dataset, context: (file: string) => ReferenceContext): void { + const places = context(PLACES_FILE); + reportDuplicates(dataset.places.map(({ country }) => country), 'country code', places.report); + dataset.places.forEach((place, i) => requireCountry(places, place.country, `${i}.country`)); + const brands = context(BRANDS_FILE); const regulators = context(REGULATORS_FILE); diff --git a/src/lib/data-paths.ts b/src/lib/data-paths.ts index dade3e3..ea55872 100644 --- a/src/lib/data-paths.ts +++ b/src/lib/data-paths.ts @@ -1,6 +1,7 @@ /** Data files and directories, relative to the repository root. */ export const COUNTRIES_FILE = 'data/reference/countries.json'; export const CURRENCIES_FILE = 'data/reference/currencies.json'; +export const PLACES_FILE = 'data/reference/places.json'; export const BRANDS_FILE = 'data/reference/brands.json'; export const REGULATORS_FILE = 'data/reference/regulators.json'; export const LOGOS_FILE = 'data/reference/logos.json'; diff --git a/src/lib/dataset-types.ts b/src/lib/dataset-types.ts index eb72213..cd34de8 100644 --- a/src/lib/dataset-types.ts +++ b/src/lib/dataset-types.ts @@ -1,6 +1,6 @@ import type { GlossaryGroup } from '../schema/glossary'; import type { BrandLogo, Logo, MethodLogo } from '../schema/logo'; -import type { Brand, Country, Currency, Regulator } from '../schema/reference'; +import type { Brand, Country, Currency, Place, Regulator } from '../schema/reference'; import type { Register } from '../schema/register'; import type { Provider } from '../schema/provider'; @@ -24,6 +24,7 @@ export interface GlossaryFile { export interface Dataset { providers: ProviderFile[]; countries: Country[]; + places: Place[]; currencies: Currency[]; brands: Brand[]; regulators: Regulator[]; diff --git a/src/lib/glossary-look.ts b/src/lib/glossary-look.ts index 68fd356..a9efa61 100644 --- a/src/lib/glossary-look.ts +++ b/src/lib/glossary-look.ts @@ -26,6 +26,7 @@ const ICONS: Readonly> = { dispute: '', download: '', flask: '', + globe: '', hash: '', 'id-card': '', key: '', diff --git a/src/lib/glossary-search.ts b/src/lib/glossary-search.ts index bb5422f..54a0c70 100644 --- a/src/lib/glossary-search.ts +++ b/src/lib/glossary-search.ts @@ -59,7 +59,7 @@ function nearAny(terms: readonly string[], word: string): boolean { } /** Whether one added, missing, changed or swapped letter turns one word into the other. */ -function isOneEditAway(a: string, b: string): boolean { +export function isOneEditAway(a: string, b: string): boolean { if (Math.abs(a.length - b.length) > 1) return false; const start = commonPrefix(a, b); diff --git a/src/lib/load-dataset.ts b/src/lib/load-dataset.ts index 70a7efe..c21db24 100644 --- a/src/lib/load-dataset.ts +++ b/src/lib/load-dataset.ts @@ -6,7 +6,7 @@ import type { z } from 'zod'; import { glossaryGroupSchema } from '../schema/glossary'; import { brandLogosFileSchema, logosFileSchema, methodLogosFileSchema } from '../schema/logo'; import { providerSchema } from '../schema/provider'; -import { brandsFileSchema, countriesFileSchema, currenciesFileSchema, regulatorsFileSchema } from '../schema/reference'; +import { brandsFileSchema, countriesFileSchema, currenciesFileSchema, placesFileSchema, regulatorsFileSchema } from '../schema/reference'; import { registerSchema } from '../schema/register'; import { BRAND_LOGOS_DIR, @@ -19,6 +19,7 @@ import { LOGOS_FILE, METHOD_LOGOS_DIR, METHOD_LOGOS_FILE, + PLACES_FILE, PROVIDERS_DIR, PUBLIC_DIR, REGISTERS_DIR, @@ -33,6 +34,7 @@ export function loadDataset(root: string): LoadResult { const countries = parseFile(ctx, COUNTRIES_FILE, countriesFileSchema) ?? []; const currencies = parseFile(ctx, CURRENCIES_FILE, currenciesFileSchema) ?? []; + const places = parseFile(ctx, PLACES_FILE, placesFileSchema) ?? []; const brands = parseFile(ctx, BRANDS_FILE, brandsFileSchema) ?? []; const regulators = parseFile(ctx, REGULATORS_FILE, regulatorsFileSchema) ?? []; const providers = loadProviders(ctx); @@ -43,7 +45,7 @@ export function loadDataset(root: string): LoadResult { const glossary = loadGlossary(ctx); return { - dataset: { providers, countries, currencies, brands, regulators, registers, logos, brandLogos, methodLogos, glossary }, + dataset: { providers, countries, places, currencies, brands, regulators, registers, logos, brandLogos, methodLogos, glossary }, issues: ctx.issues, }; } diff --git a/src/lib/search-index.ts b/src/lib/search-index.ts deleted file mode 100644 index 00405a8..0000000 --- a/src/lib/search-index.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { countryName } from '../i18n/country-names'; -import { localePath } from '../i18n/translate'; -import { badgeTone } from './catalogue'; -import { normalise } from './search-match'; -import type { SearchEntry, SearchIndexInput } from './search-types'; -import { initial } from './site-format'; - -/** Search entries for verified providers, so a visitor finds them by name, country or payment brand. */ -export function searchIndex(input: SearchIndexInput): SearchEntry[] { - return input.providers.map((provider) => { - const countries = provider.coverage.map((entry) => entry.country); - const brands = provider.coverage.flatMap((entry) => entry.methods.flatMap((method) => (method.brand ? [method.brand] : []))); - const words = [ - provider.name, - ...countries, - ...countries.map((code) => countryName(input.locale, code)), - ...brands.map((brand) => input.brands.get(brand) ?? brand), - ]; - - return { - name: provider.name, - initial: initial(provider.name), - mark: input.marks.get(provider.slug) ?? null, - tone: badgeTone(provider.name), - href: localePath(input.locale, `/providers/${provider.slug}`), - meta: input.meta(provider), - terms: normalise([...new Set(words)].join(' ')), - }; - }); -} diff --git a/src/lib/search-match.ts b/src/lib/search-match.ts index 8f2f138..228bf13 100644 --- a/src/lib/search-match.ts +++ b/src/lib/search-match.ts @@ -1,23 +1,3 @@ -import type { SearchEntry } from './search-types'; - -/** Entries where every word of the query starts a word of their terms, names starting with the query first. */ -export function searchEntries(entries: readonly SearchEntry[], query: string): SearchEntry[] { - const words = normalise(query).split(/\s+/).filter(Boolean); - - if (words.length === 0) { - return []; - } - - const start = words.join(' '); - const matches = entries.filter((entry) => { - const terms = entry.terms.split(' '); - - return words.every((word) => terms.some((term) => term.startsWith(word))); - }); - - return matches.sort((a, b) => rank(a, start) - rank(b, start) || a.name.localeCompare(b.name)); -} - /** Lower case without accents or apostrophes, so "cote d ivoire" finds "Côte d’Ivoire". */ export function normalise(text: string): string { return text @@ -26,7 +6,3 @@ export function normalise(text: string): string { .replace(/[’']/g, ' ') .toLowerCase(); } - -function rank(entry: SearchEntry, start: string): number { - return normalise(entry.name).startsWith(start) ? 0 : 1; -} diff --git a/src/lib/search-types.ts b/src/lib/search-types.ts deleted file mode 100644 index d331c7f..0000000 --- a/src/lib/search-types.ts +++ /dev/null @@ -1,27 +0,0 @@ -import type { Locale } from '../i18n/locales'; -import type { Provider } from '../schema/provider'; - -/** One searchable provider, prepared at build time for a locale. */ -export interface SearchEntry { - name: string; - /** Letter shown in the badge until the provider has a logo. */ - initial: string; - /** Square logo as a site path, or `null` when none is published. */ - mark: string | null; - /** Colour of the letter badge, the same as on the catalogue card. */ - tone: number; - href: string; - /** Short context shown next to the name, such as the number of countries. */ - meta: string; - /** Normalised words a query is matched against: name, countries, payment brands. */ - terms: string; -} - -export interface SearchIndexInput { - providers: readonly Provider[]; - locale: Locale; - brands: ReadonlyMap; - /** Square logo of a provider by slug, as on the catalogue cards. */ - marks: ReadonlyMap; - meta: (provider: Provider) => string; -} diff --git a/src/lib/site-data.ts b/src/lib/site-data.ts index 169771c..9fc4d57 100644 --- a/src/lib/site-data.ts +++ b/src/lib/site-data.ts @@ -48,6 +48,7 @@ export function selectSite(dataset: Dataset): SiteData { scope: dataset.countries.map((country) => country.code), lookups: lookups(dataset), glossary: dataset.glossary.map(({ group }) => group), + reference: { countries: dataset.countries, places: dataset.places, brands: dataset.brands, regulators: dataset.regulators }, }; } diff --git a/src/lib/site-types.ts b/src/lib/site-types.ts index 30883cc..f634a9e 100644 --- a/src/lib/site-types.ts +++ b/src/lib/site-types.ts @@ -1,6 +1,6 @@ import type { GlossaryGroup } from '../schema/glossary'; import type { Provider } from '../schema/provider'; -import type { Country } from '../schema/reference'; +import type { Brand, Country, Place, Regulator } from '../schema/reference'; import type { MethodKind } from './offer-types'; /** Names to display for the identifiers used in data files. */ @@ -27,6 +27,14 @@ export interface BadgeLogo { wide: boolean; } +/** Reference lists the search reads names from. */ +export interface SearchReference { + countries: readonly Country[]; + places: readonly Place[]; + brands: readonly Brand[]; + regulators: readonly Regulator[]; +} + /** What the public site shows: verified providers only, drafts as a count. */ export interface SiteData { published: Provider[]; @@ -38,6 +46,7 @@ export interface SiteData { lookups: Lookups; /** Sections of the glossary, in page order. */ glossary: readonly GlossaryGroup[]; + reference: SearchReference; } /** A source as shown next to a value. */ diff --git a/src/pages/search/[locale].json.ts b/src/pages/search/[locale].json.ts new file mode 100644 index 0000000..20cb905 --- /dev/null +++ b/src/pages/search/[locale].json.ts @@ -0,0 +1,10 @@ +import type { APIRoute, GetStaticPaths } from 'astro'; + +import { LOCALES, type Locale } from '../../i18n/locales'; +import { currentSite } from '../../lib/site-data'; +import { buildSearchPayload } from '../../search/build-payload'; + +export const getStaticPaths = (() => LOCALES.map((locale) => ({ params: { locale }, props: { locale } }))) satisfies GetStaticPaths; + +/** Search data of one language, loaded by the search window when it first opens. */ +export const GET: APIRoute<{ locale: Locale }> = ({ props }) => Response.json(buildSearchPayload(currentSite(), props.locale)); diff --git a/src/schema/constants.ts b/src/schema/constants.ts index 3ed4c4b..334a190 100644 --- a/src/schema/constants.ts +++ b/src/schema/constants.ts @@ -130,6 +130,7 @@ export const GLOSSARY_ICONS = [ 'dispute', 'download', 'flask', + 'globe', 'hash', 'id-card', 'key', diff --git a/src/schema/reference.ts b/src/schema/reference.ts index 19ef0e8..e46f256 100644 --- a/src/schema/reference.ts +++ b/src/schema/reference.ts @@ -45,7 +45,16 @@ export const regulatorSchema = z.strictObject({ export type Regulator = z.infer; +/** Other names a country is searched by: capitals, large cities, acronyms. */ +export const placeSchema = z.strictObject({ + country: countryCodeSchema, + aliases: z.array(z.string().min(1)).min(1), +}); + +export type Place = z.infer; + export const countriesFileSchema = z.array(countrySchema); export const currenciesFileSchema = z.array(currencySchema); export const brandsFileSchema = z.array(brandSchema); export const regulatorsFileSchema = z.array(regulatorSchema); +export const placesFileSchema = z.array(placeSchema); diff --git a/src/search/build-index.ts b/src/search/build-index.ts new file mode 100644 index 0000000..8993af0 --- /dev/null +++ b/src/search/build-index.ts @@ -0,0 +1,148 @@ +import { countryName } from '../i18n/country-names'; +import { LOCALES, type Locale } from '../i18n/locales'; +import { catalogueStrings, providerStrings } from '../i18n/translate'; +import { describesCollection } from '../lib/offer-match'; +import { ownRegulators } from '../lib/own-licences'; +import { FAMILIES, METHOD_KINDS } from '../schema/constants'; +import type { Provider } from '../schema/provider'; +import type { SearchReference } from '../lib/site-types'; +import { FEATURES } from './features'; +import { phrase } from './text'; +import type { SearchEntity, SearchIndex, SearchProvider } from './types'; +import { ABILITIES, CURRENCY_WORDS, FAMILY_WORDS, METHOD_WORDS, SECTIONS, ZONES } from './vocabulary'; + +const LICENCE_LABEL: Readonly string>> = { en: (regulator) => `${regulator} licence`, fr: (regulator) => `Agrément ${regulator}` }; + +export interface SearchIndexInput { + readonly locale: Locale; + readonly providers: readonly Provider[]; + readonly reference: SearchReference; +} + +/** Everything the search knows, for one locale. Words of every language are accepted on every page. */ +export function buildSearchIndex(input: SearchIndexInput): SearchIndex { + return { + entities: [ + ...providerEntities(input), + ...countryEntities(input), + ...zoneEntities(input), + ...brandEntities(input), + ...methodEntities(input.locale), + ...currencyEntities(input.providers), + ...familyEntities(input.locale), + ...abilityEntities(input.locale), + ...featureEntities(input.locale), + ...sdkEntities(input.providers), + ...regulatorEntities(input), + ...sectionEntities(input.locale), + ], + providers: input.providers.map((provider) => searchProvider(provider, input.locale)), + }; +} + +function providerEntities({ providers }: SearchIndexInput): SearchEntity[] { + return providers.map((provider) => entity('provider', provider.slug, provider.name, [provider.name, provider.slug])); +} + +function countryEntities({ reference: { countries, places }, locale }: SearchIndexInput): SearchEntity[] { + return countries.map(({ code }) => { + const aliases = places.filter((place) => place.country === code).flatMap((place) => place.aliases); + + return named('country', code, countryName(locale, code), [code, ...LOCALES.map((language) => countryName(language, code))], aliases); + }); +} + +function zoneEntities({ reference: { countries }, locale }: SearchIndexInput): SearchEntity[] { + return ZONES.map((zone) => ({ + ...entity('zone', zone.id, zone.label[locale], zone.words), + countries: countries.filter((country) => country.monetary_union === zone.id).map((country) => country.code), + })); +} + +function brandEntities({ reference: { brands } }: SearchIndexInput): SearchEntity[] { + return brands.map((brand) => named('brand', brand.id, brand.name, [brand.name, brand.id], brand.former_names ?? [])); +} + +function methodEntities(locale: Locale): SearchEntity[] { + return METHOD_KINDS.map((kind) => entity('method', kind, providerStrings(locale).methods[kind], [...LOCALES.map((language) => providerStrings(language).methods[kind]), ...(METHOD_WORDS[kind] ?? [])])); +} + +function currencyEntities(providers: readonly Provider[]): SearchEntity[] { + const codes = new Set(providers.flatMap(({ coverage }) => coverage.flatMap((entry) => entry.currencies))); + + return [...codes].sort().map((code) => entity('currency', code, code, [code, ...(CURRENCY_WORDS[code] ?? [])])); +} + +function familyEntities(locale: Locale): SearchEntity[] { + return FAMILIES.map((family) => { + const labels = LOCALES.flatMap((language) => Object.values(catalogueStrings(language).families[family])); + + return entity('family', family, catalogueStrings(locale).families[family].one, [...labels, ...(FAMILY_WORDS[family] ?? [])]); + }); +} + +function abilityEntities(locale: Locale): SearchEntity[] { + return ABILITIES.map((ability) => entity('ability', ability.id, ability.label[locale], ability.words)); +} + +function featureEntities(locale: Locale): SearchEntity[] { + return FEATURES.map((feature) => ({ ...entity('feature', feature.id, feature.label[locale], feature.words), section: feature.section })); +} + +/** One entry per language of an official SDK, read from the records: a new language needs no declaration. */ +function sdkEntities(providers: readonly Provider[]): SearchEntity[] { + const languages = new Set(providers.flatMap((provider) => provider.integration.official_sdks?.value ?? [])); + + return [...languages].sort().map((language) => ({ ...entity('feature', sdkId(language), `SDK ${language}`, [language, `sdk ${language}`, `${language} sdk`]), section: 'integration' as const })); +} + +/** A regulator finds the providers holding one of its licences. */ +function regulatorEntities({ reference: { regulators }, providers, locale }: SearchIndexInput): SearchEntity[] { + const named = new Set(providers.flatMap((provider) => ownRegulators(provider))); + + return regulators + .filter((regulator) => named.has(regulator.id)) + .map((regulator) => ({ ...entity('feature', regulatorId(regulator.id), LICENCE_LABEL[locale](regulator.id.toUpperCase()), [regulator.id, regulator.name, `agréé ${regulator.id}`, `agrément ${regulator.id}`, `licence ${regulator.id}`]), section: 'licences' as const })); +} + +function sectionEntities(locale: Locale): SearchEntity[] { + return SECTIONS.map((section) => ({ ...entity('section', section.id, section.label[locale], section.words), section: section.id })); +} + +function entity(kind: SearchEntity['kind'], key: string, label: string, words: readonly string[]): SearchEntity { + return { id: `${kind}:${key}`, kind, label, words: [...new Set(words.map(phrase))] }; +} + +/** An entity also known by other names, which the results spell out. */ +function named(kind: SearchEntity['kind'], key: string, label: string, words: readonly string[], aliases: readonly string[]): SearchEntity { + return { ...entity(kind, key, label, [...words, ...aliases]), aliases: aliases.map(phrase) }; +} + +function searchProvider(provider: Provider, locale: Locale): SearchProvider { + const facts = [ + ...provider.families.map((family) => `family:${family}`), + ...FEATURES.filter((feature) => feature.test(provider)).map((feature) => `feature:${feature.id}`), + ...(provider.integration.official_sdks?.value ?? []).map((language) => `feature:${sdkId(language)}`), + ...ownRegulators(provider).map((regulator) => `feature:${regulatorId(regulator)}`), + ]; + + const details = Object.fromEntries(FEATURES.flatMap(({ id, test, detail }) => (detail !== undefined && test(provider) ? [[`feature:${id}`, detail(provider)[locale]]] : []))); + + return { slug: provider.slug, name: provider.name, facts: [...new Set(facts)], details, rows: provider.coverage.map(searchRow) }; +} + +/** What one coverage entry states. Its methods count only when it may describe collection, as in the catalogue. */ +function searchRow(entry: Provider['coverage'][number]): SearchProvider['rows'][number] { + const methods = describesCollection(entry) ? entry.methods.flatMap((method) => [`method:${method.kind}`, ...(method.brand === undefined ? [] : [`brand:${method.brand}`])]) : []; + const abilities = [...(entry.collection === true ? ['ability:collect'] : []), ...(entry.payout === true ? ['ability:payout'] : [])]; + + return { country: entry.country, facts: [...new Set([...methods, ...abilities, ...entry.currencies.map((code) => `currency:${code}`)])] }; +} + +function sdkId(language: string): string { + return `sdk-${phrase(language).replace(/ /g, '-')}`; +} + +function regulatorId(regulator: string): string { + return `regulator-${regulator}`; +} diff --git a/src/search/build-payload.ts b/src/search/build-payload.ts new file mode 100644 index 0000000..8264a25 --- /dev/null +++ b/src/search/build-payload.ts @@ -0,0 +1,43 @@ +import type { Locale } from '../i18n/locales'; +import { localePath } from '../i18n/translate'; +import { badgeTone } from '../lib/catalogue'; +import { glossaryEntries } from '../lib/glossary-entries'; +import { glossaryLook } from '../lib/glossary-look'; +import { initial } from '../lib/site-format'; +import type { SiteData } from '../lib/site-types'; +import { buildSearchIndex } from './build-index'; +import type { SearchPayload, SectionResult } from './payload-types'; +import { sectionLook } from './section-look'; +import { SECTIONS } from './vocabulary'; + +/** What the search window of a locale loads when it opens. */ +export function buildSearchPayload(site: SiteData, locale: Locale): SearchPayload { + return { + index: buildSearchIndex({ locale, providers: site.published, reference: site.reference }), + cards: providerCards(site, locale), + sections: SECTIONS.map(({ id, label }): SectionResult => ({ id, label: label[locale], ...sectionLook(id) })), + // Definitions mention countries and methods in passing: only names answer here. + terms: glossaryEntries(site.glossary, locale).map((entry) => ({ ...entry, body: '' })), + definitions: glossaryResults(site, locale), + }; +} + +function providerCards({ published, lookups }: SiteData, locale: Locale): SearchPayload['cards'] { + return Object.fromEntries( + published.map(({ slug, name }) => [ + slug, + { href: localePath(locale, `/providers/${slug}`), mark: lookups.marks.get(slug) ?? null, initial: initial(name), tone: badgeTone(name) }, + ]), + ); +} + +function glossaryResults({ glossary }: SiteData, locale: Locale): SearchPayload['definitions'] { + return Object.fromEntries( + glossary.flatMap((group) => + group.terms.map((term) => [ + term.id, + { name: term[locale].name, definition: term[locale].definition, href: `${localePath(locale, '/glossary')}#${term.id}`, ...glossaryLook(term, group.tone) }, + ]), + ), + ); +} diff --git a/src/search/elements.ts b/src/search/elements.ts new file mode 100644 index 0000000..8719bef --- /dev/null +++ b/src/search/elements.ts @@ -0,0 +1,65 @@ +import type { SearchIcon } from './payload-types'; +import type { SearchNote } from './view-types'; + +/** A new element with a class and an optional text, never parsed as HTML. */ +export function element(tag: K, className: string, text?: string): HTMLElementTagNameMap[K] { + const node = document.createElement(tag); + + node.className = className; + if (text !== undefined) node.textContent = text; + + return node; +} + +/** A drawing on its coloured disc, as in the glossary. */ +export function disc({ icon, background, foreground }: SearchIcon): HTMLElement { + const node = element('span', 'disc'); + + node.style.background = background; + node.style.color = foreground; + node.setAttribute('aria-hidden', 'true'); + node.innerHTML = `${icon}`; + + return node; +} + +/** The long arrow shown where a row leads somewhere. */ +export function arrow(): HTMLElement { + const node = element('span', 'arrow'); + + node.setAttribute('aria-hidden', 'true'); + node.innerHTML = ''; + + return node; +} + +/** A provider's logo, or its letter in the colour of its catalogue card. */ +export function badge({ mark, initial, tone }: { mark: string | null; initial: string; tone: number }): HTMLElement { + const node = element('span', mark === null ? `badge tone-${tone}` : 'badge has-mark'); + + node.setAttribute('aria-hidden', 'true'); + + if (mark === null) { + node.textContent = initial; + + return node; + } + + const image = element('img', ''); + image.src = mark; + image.alt = ''; + image.decoding = 'async'; + node.append(image); + + return node; +} + +/** A sentence with its telling part in bold. */ +export function noteLine({ text, strong }: SearchNote): HTMLElement { + const line = element('p', ''); + const start = text.indexOf(strong); + + line.append(text.slice(0, start), element('b', '', strong), text.slice(start + strong.length)); + + return line; +} diff --git a/src/search/features.ts b/src/search/features.ts new file mode 100644 index 0000000..0cc8714 --- /dev/null +++ b/src/search/features.ts @@ -0,0 +1,137 @@ +import { ownLicences } from '../lib/own-licences'; +import type { Provider } from '../schema/provider'; +import type { FeatureDeclaration } from './types'; + +/** + * Everything a sheet states that can be searched for. To make something searchable, add an + * entry here: an id, a label, the words people type, the section and a test on the record. + */ +export const FEATURES: readonly FeatureDeclaration[] = [ + { + id: 'sandbox', + label: { en: 'Sandbox (test mode)', fr: 'Sandbox (mode test)' }, + words: ['sandbox', 'mode test', 'test mode', 'bac à sable', 'environnement de test', 'test environment'], + section: 'integration', + test: ({ integration }) => integration.sandbox !== undefined && integration.sandbox.value !== 'none', + detail: ({ integration }) => + integration.sandbox?.value === 'self_serve' ? { en: 'Sandbox without approval', fr: 'Sandbox sans validation' } : { en: 'Sandbox after account approval', fr: 'Sandbox après validation du compte' }, + }, + { + id: 'sandbox-self-serve', + label: { en: 'Sandbox without approval', fr: 'Sandbox sans validation' }, + words: ['sandbox gratuit', 'sandbox libre', 'sandbox immédiat', 'sandbox sans kyc', 'sandbox without kyc', 'self serve sandbox'], + section: 'integration', + test: ({ integration }) => integration.sandbox?.value === 'self_serve', + }, + { + id: 'public-docs', + label: { en: 'Public documentation', fr: 'Documentation publique' }, + words: ['documentation', 'documentation publique', 'public documentation', 'doc', 'api publique', 'public api', 'api'], + section: 'integration', + test: ({ integration }) => integration.public_docs?.value === true, + }, + { + id: 'webhook', + label: { en: 'Verifiable notifications (webhooks)', fr: 'Notifications vérifiables (webhooks)' }, + words: ['webhook', 'callback', 'ipn', 'notification de paiement', 'payment notification', 'webhook signé', 'signed webhook', 'signature webhook'], + section: 'integration', + test: ({ integration }) => integration.webhook_signature !== undefined && integration.webhook_signature.value !== 'none', + }, + { + id: 'webhook-hmac', + label: { en: 'Notifications signed with HMAC', fr: 'Notifications signées HMAC' }, + words: ['hmac', 'webhook hmac', 'signature hmac'], + section: 'integration', + test: ({ integration }) => integration.webhook_signature?.value === 'hmac', + }, + { + id: 'sdk', + label: { en: 'Official SDKs', fr: 'SDK officiels' }, + words: ['sdk', 'sdk officiel', 'official sdk', 'bibliothèque', 'library', 'plugin'], + section: 'integration', + test: ({ integration }) => (integration.official_sdks?.value.length ?? 0) > 0, + }, + { + id: 'public-pricing', + label: { en: 'Published fees', fr: 'Tarifs publiés' }, + words: ['tarifs publics', 'tarifs publiés', 'prix publics', 'frais publics', 'tarifs affichés', 'public pricing', 'published fees'], + section: 'fees', + test: ({ integration }) => integration.public_pricing?.value === true, + }, + { + id: 'status-page', + label: { en: 'Status page', fr: 'Page d’état' }, + words: ['page d’état', 'page de statut', 'status page', 'uptime', 'statut'], + section: 'integration', + test: ({ integration }) => typeof integration.status_page?.value === 'string', + }, + { + id: 'individuals', + label: { en: 'Open to individuals, no company', fr: 'Ouvert aux particuliers, sans société' }, + words: ['particulier', 'sans société', 'sans entreprise', 'sans rccm', 'individual', 'without company', 'no company', 'freelance', 'indépendant'], + section: 'onboarding', + test: ({ onboarding }) => onboarding.individuals_allowed?.value === true, + }, + { + id: 'online-signup', + label: { en: 'Account opened online', fr: 'Ouverture de compte en ligne' }, + words: ['inscription en ligne', 'compte en ligne', 'ouverture en ligne', 'online signup', 'sign up online'], + section: 'onboarding', + test: ({ onboarding }) => onboarding.signup?.value === 'online', + }, + { + id: 'no-deposit', + label: { en: 'No security deposit', fr: 'Sans dépôt de garantie' }, + words: ['sans dépôt', 'sans caution', 'sans dépôt de garantie', 'no deposit', 'without deposit'], + section: 'onboarding', + test: ({ onboarding }) => onboarding.security_deposit?.value === false, + }, + { id: 'bulk-payout', label: { en: 'Bulk payout', fr: 'Envoi en masse' }, words: ['envoi en masse', 'paiement en masse', 'paiement de masse', 'bulk payout', 'mass payout', 'salaires', 'payroll'], section: 'coverage', test: can('bulk_payout') }, + { id: 'refund', label: { en: 'Refund', fr: 'Remboursement' }, words: ['remboursement', 'rembourser', 'refund'], section: 'coverage', test: can('refund') }, + { id: 'payout-reversal', label: { en: 'Payout reversal', fr: 'Annulation d’envoi' }, words: ['annulation d’envoi', 'annuler un envoi', 'payout reversal', 'reversal'], section: 'coverage', test: can('payout_reversal') }, + { + id: 'settlement-automatic', + label: { en: 'Automatic settlement', fr: 'Reversement automatique' }, + words: ['reversement automatique', 'automatic settlement', 'versement automatique'], + section: 'settlements', + test: ({ settlements }) => settlements.some((entry) => entry.trigger === 'automatic'), + }, + { + id: 'settlement-bank', + label: { en: 'Settlement to a bank account', fr: 'Reversement sur compte bancaire' }, + words: ['reversement bancaire', 'reversement banque', 'compte bancaire', 'bank settlement', 'settlement to bank'], + section: 'settlements', + test: ({ settlements }) => settlements.some((entry) => entry.destination === 'bank_account'), + }, + { + id: 'settlement-mobile', + label: { en: 'Settlement to mobile money', fr: 'Reversement sur mobile money' }, + words: ['reversement mobile money', 'reversement mobile', 'mobile money settlement'], + section: 'settlements', + test: ({ settlements }) => settlements.some((entry) => entry.destination === 'mobile_money'), + }, + { + id: 'settlement-known', + label: { en: 'Settlement time published', fr: 'Délai de reversement publié' }, + words: ['reversement', 'délai de reversement', 'settlement', 'settlement time'], + section: 'settlements', + test: ({ settlements }) => settlements.length > 0, + }, + { + id: 'licence-known', + label: { en: 'Licence found in a register', fr: 'Agrément trouvé au registre' }, + words: ['agrément', 'agréé', 'licence', 'license', 'licensed', 'régulé', 'regulated'], + section: 'licences', + test: (provider) => ownLicences(provider).length > 0, + }, + { id: 'payment-institution', label: { en: 'Payment institution', fr: 'Établissement de paiement' }, words: ['établissement de paiement', 'payment institution'], section: 'licences', test: licensedAs('payment_institution') }, + { id: 'e-money-institution', label: { en: 'E-money institution', fr: 'Établissement de monnaie électronique' }, words: ['établissement de monnaie électronique', 'monnaie électronique', 'eme', 'e-money institution', 'emi'], section: 'licences', test: licensedAs('e_money_institution') }, +]; + +function can(kind: Provider['capabilities'][number]['kind']): (provider: Provider) => boolean { + return ({ capabilities }) => capabilities.some((capability) => capability.kind === kind); +} + +function licensedAs(type: Provider['licences'][number]['type']): (provider: Provider) => boolean { + return (provider) => ownLicences(provider).some((licence) => licence.type === type); +} diff --git a/src/search/parse-query.ts b/src/search/parse-query.ts new file mode 100644 index 0000000..f123341 --- /dev/null +++ b/src/search/parse-query.ts @@ -0,0 +1,139 @@ +import { isOneEditAway } from '../lib/glossary-search'; +import { phrase, tokens, type Token } from './text'; +import type { ParsedQuery, QueryPart, SearchEntity } from './types'; +import { IGNORED_WORDS, NEGATIONS } from './vocabulary'; + +/** Longest phrase read at once, in words. */ +const MAX_WORDS = 5; + +/** Shortest word completed while it is being typed, or read with spaces moved. */ +const MIN_PREFIX = 3; + +/** Shortest word a typo is accepted in. */ +const MIN_TYPO = 5; + +/** Kinds that carry a proper name: any word of it can stand for the whole. */ +const NAMES: ReadonlySet = new Set(['provider', 'brand', 'country']); + +/** Whether a text names an entity, by one of its phrases. */ +type Match = (text: string, phraseOfEntity: string) => boolean; + +interface Found { + readonly part: QueryPart; + readonly length: number; +} + +/** + * Cuts a query into what it names. Reads the longest phrase first, in the order written; each + * phrase is taken as spelt, then run together, then as a beginning, then with one typo. + */ +export function parseQuery(text: string, entities: readonly SearchEntity[]): ParsedQuery { + const words = tokens(text); + const parts: QueryPart[] = []; + const negated: QueryPart[] = []; + const ignored: string[] = []; + let negating = false; + + for (let i = 0; i < words.length; ) { + const found = partAt(words, i, entities); + + if (found !== null) { + (negating ? negated : parts).push(found.part); + negating = false; + i += found.length; + continue; + } + + const token = words[i]; + i += 1; + if (token === undefined) continue; + + if (NEGATIONS.has(token.plain)) negating = true; + else if (!isSmall(token)) { + negating = false; + if (!ignored.includes(token.raw)) ignored.push(token.raw); + } + } + + return { parts, negated, ignored }; +} + +function partAt(words: readonly Token[], from: number, entities: readonly SearchEntity[]): Found | null { + return longest(words, from, entities, exactly) ?? beginning(words, from, entities) ?? longest(words, from, entities, nearly, true); +} + +/** The longest run of words that satisfies a match. */ +function longest(words: readonly Token[], from: number, entities: readonly SearchEntity[], match: Match, guessed = false): Found | null { + for (let length = Math.min(MAX_WORDS, words.length - from); length > 0; length -= 1) { + const run = words.slice(from, from + length); + + // A run of small words such as "en" or "de" names nothing, unless it is a code in capitals. + if (run.every((token) => isSmall(token) || NEGATIONS.has(token.plain)) && !isCode(words, from)) continue; + + const text = textOf(run); + const found = entities.filter((entity) => entity.words.some((phraseOfEntity) => match(text, phraseOfEntity)) && !isUnclearCode(entity, run, words)); + + if (found.length > 0) return { part: partOf(run, found, guessed), length }; + } + + return null; +} + +/** Spelt the same, spaces aside: "kkia pay" is Kkiapay and "notchpay" is Notch Pay. */ +function exactly(text: string, phraseOfEntity: string): boolean { + return text === phraseOfEntity || (text.length >= MIN_PREFIX && compact(text) === compact(phraseOfEntity)); +} + +/** What is being typed: a word of a name ("burkina", "flutterwav"), or the start of a phrase at the end of the query ("envoi en ma"). */ +function beginning(words: readonly Token[], from: number, entities: readonly SearchEntity[]): Found | null { + const token = words[from]; + + if (token === undefined || token.word.length < MIN_PREFIX || isSmall(token) || NEGATIONS.has(token.plain)) return null; + + const named = entities.filter((entity) => NAMES.has(entity.kind) && entity.words.some((phraseOfEntity) => phraseOfEntity.split(' ').some((word) => word.startsWith(token.word)))); + if (named.length > 0) return { part: partOf([token], named, false), length: 1 }; + + const rest = words.slice(from); + const text = textOf(rest); + const started = entities.filter((entity) => entity.words.some((phraseOfEntity) => phraseOfEntity.startsWith(text))); + + return started.length === 0 ? null : { part: partOf(rest, started, false), length: rest.length }; +} + +function nearly(text: string, phraseOfEntity: string): boolean { + const a = compact(text); + const b = compact(phraseOfEntity); + + return a.length >= MIN_TYPO && b.length >= MIN_TYPO && isOneEditAway(a, b); +} + +/** "ne" in a sentence is not Niger: a country code counts in capitals, or alone. */ +function isUnclearCode(entity: SearchEntity, run: readonly Token[], words: readonly Token[]): boolean { + const [token] = run; + if (entity.kind !== 'country' || run.length > 1 || token === undefined || token.raw.length !== 2) return false; + + return words.length > 1 && token.raw !== token.raw.toUpperCase(); +} + +function isCode(words: readonly Token[], at: number): boolean { + const raw = words[at]?.raw ?? ''; + + return raw.length === 2 && (raw === raw.toUpperCase() || words.length === 1); +} + +function isSmall({ plain, word }: Token): boolean { + return IGNORED_WORDS.has(plain) || IGNORED_WORDS.has(word); +} + +function partOf(run: readonly Token[], entities: readonly SearchEntity[], guessed: boolean): QueryPart { + return { text: run.map(({ raw }) => raw).join(' '), entities, guessed }; +} + +function textOf(run: readonly Token[]): string { + return run.map(({ word }) => word).join(' '); +} + +/** A phrase with its spaces closed up, to compare spellings. */ +export function compact(text: string): string { + return phrase(text).replace(/ /g, ''); +} diff --git a/src/search/payload-types.ts b/src/search/payload-types.ts new file mode 100644 index 0000000..87204ce --- /dev/null +++ b/src/search/payload-types.ts @@ -0,0 +1,39 @@ +import type { GlossaryEntry } from '../lib/glossary-types'; +import type { SearchIndex, SheetSection } from './types'; + +/** A drawing on its coloured disc. `icon` is inner SVG written in this repository. */ +export interface SearchIcon { + readonly icon: string; + readonly background: string; + readonly foreground: string; +} + +/** How a provider is drawn and where it opens. */ +export interface ProviderCard { + readonly href: string; + /** Square logo as a site path, or `null` when none is published. */ + readonly mark: string | null; + /** Letter and colour of the badge used without a logo. */ + readonly initial: string; + readonly tone: number; +} + +export interface GlossaryResult extends SearchIcon { + readonly name: string; + readonly definition: string; + readonly href: string; +} + +export interface SectionResult extends SearchIcon { + readonly id: SheetSection; + readonly label: string; +} + +/** Everything the search window loads, for one locale. */ +export interface SearchPayload { + readonly index: SearchIndex; + readonly cards: Readonly>; + readonly sections: readonly SectionResult[]; + readonly terms: readonly GlossaryEntry[]; + readonly definitions: Readonly>; +} diff --git a/src/search/render-results.ts b/src/search/render-results.ts new file mode 100644 index 0000000..06e7f02 --- /dev/null +++ b/src/search/render-results.ts @@ -0,0 +1,126 @@ +import { arrow, badge, disc, element } from './elements'; +import type { GlossaryResult } from './payload-types'; +import type { ProviderRow, SearchView, SectionRow } from './view-types'; + +export interface ResultLabels { + readonly providers: string; + readonly glossary: string; + /** "6 of 11", next to the group name. */ + readonly count: string; + /** "Show 5 more", or `null` when every provider is listed. */ + readonly more: string | null; +} + +/** The rows of a view. Every element with `role="option"` can be chosen, in document order. */ +export function renderResults(view: SearchView, labels: ResultLabels): HTMLElement[] { + const groups: HTMLElement[] = []; + + if (view.providers.length > 0) { + const rows = view.providers.map(providerOption); + const extra = view.sections.length > 0 ? [sectionGrid(view.sections)] : []; + const more = labels.more === null ? [] : [moreOption(labels.more)]; + + groups.push(group('providers', { title: labels.providers, count: labels.count }, [...rows, ...extra, ...more])); + } + + if (view.terms.length > 0) groups.push(group('glossary', { title: labels.glossary, count: '' }, view.terms.map(termOption))); + + return groups; +} + +function group(key: string, head: { title: string; count: string }, rows: readonly HTMLElement[]): HTMLElement { + const node = element('div', 'group'); + const heading = element('div', 'group-head'); + const title = element('span', '', head.title); + + title.id = `site-search-group-${key}`; + heading.setAttribute('role', 'presentation'); + heading.append(title, element('span', '', head.count)); + node.setAttribute('role', 'group'); + node.setAttribute('aria-labelledby', title.id); + node.append(heading, ...rows); + + return node; +} + +function providerOption(row: ProviderRow): HTMLElement { + const link = optionLink('row', row.href); + const main = element('span', 'main'); + main.append(element('span', 'name', row.name)); + + if (row.reasons.length > 0) { + const reasons = element('span', 'reasons'); + reasons.append(...row.reasons.map(reason)); + main.append(reasons); + } + + link.append(badge(row), main); + + if (row.section !== null) { + const section = element('span', 'section', row.section); + section.append(arrow()); + link.append(section); + } + + return link; +} + +function reason(text: string): HTMLElement { + const node = element('span', 'reason'); + const tick = element('span', 'tick', '✓'); + + tick.setAttribute('aria-hidden', 'true'); + node.append(tick, text); + + return node; +} + +function sectionGrid(sections: readonly SectionRow[]): HTMLElement { + const grid = element('div', 'sections'); + + grid.setAttribute('role', 'presentation'); + grid.append( + ...sections.map((section) => { + const link = optionLink('row section-row', section.href); + link.append(disc(section), element('span', 'name', section.label), arrow()); + + return link; + }), + ); + + return grid; +} + +function moreOption(text: string): HTMLElement { + const button = element('button', 'more', text); + + button.type = 'button'; + button.dataset['searchMore'] = ''; + + return asOption(button); +} + +function termOption(term: GlossaryResult): HTMLElement { + const link = optionLink('row', term.href); + const main = element('span', 'main'); + + main.append(element('span', 'name', term.name), element('span', 'definition', term.definition)); + link.append(disc(term), main); + + return link; +} + +function optionLink(className: string, href: string): HTMLAnchorElement { + const link = element('a', className); + link.href = href; + + return asOption(link); +} + +function asOption(node: T): T { + node.setAttribute('role', 'option'); + node.setAttribute('aria-selected', 'false'); + node.tabIndex = -1; + + return node; +} diff --git a/src/search/search.ts b/src/search/search.ts new file mode 100644 index 0000000..3c93edc --- /dev/null +++ b/src/search/search.ts @@ -0,0 +1,126 @@ +import { parseQuery } from './parse-query'; +import type { ProviderHit, QueryPart, SearchEntity, SearchIndex, SearchProvider, SearchResult, SheetSection } from './types'; + +/** Kinds stated per country, which must all hold in the same country. */ +const ROW_KINDS: ReadonlySet = new Set(['brand', 'method', 'currency', 'ability']); + +/** Providers that answer every part of a query, those named in it first, then by name. */ +export function search(index: SearchIndex, text: string): SearchResult { + const query = parseQuery(text, index.entities); + const named = query.parts.some(isProvider); + const asked = criteria(query.parts, named); + + if (asked.length === 0 || query.negated.length > 0) return { query, hits: [] }; + + const section = sectionAsked(query.parts, named); + const hits = index.providers + .flatMap((provider) => { + const reasons = reasonsOf(provider, asked); + + return reasons === null ? [] : [{ provider, first: isNamed(provider, asked), hit: { slug: provider.slug, reasons, section: section ?? sectionOfFeatures(provider, asked) } satisfies ProviderHit }]; + }) + .sort((a, b) => Number(b.first) - Number(a.first) || a.provider.name.localeCompare(b.provider.name, 'en')); + + return { query, hits: hits.map(({ hit }) => hit) }; +} + +/** + * What a provider must answer. Several provider names are alternatives. Next to a name, a section + * or a feature asks where to look in its sheet and leaves nobody out. + */ +function criteria(parts: readonly QueryPart[], named: boolean): QueryPart[] { + const names = parts.filter(isProvider); + const rest = parts.filter((part) => !isProvider(part)).flatMap((part) => { + const entities = part.entities.filter(({ kind }) => kind !== 'section' && !(named && kind === 'feature')); + + return entities.length === 0 ? [] : [{ ...part, entities }]; + }); + const [first] = names; + + return first === undefined ? rest : [{ ...first, entities: names.flatMap((part) => part.entities) }, ...rest]; +} + +/** The labels of what a provider answers, or `null` when it leaves a part of the query unanswered. */ +function reasonsOf(provider: SearchProvider, parts: readonly QueryPart[]): string[] | null { + const whole = parts.filter((part) => !isRowPart(part) && !isPlace(part)); + const answers = whole.map((part) => part.entities.filter((entity) => answersWhole(provider, entity))); + + if (answers.some((found) => found.length === 0)) return null; + + const rowLabels = rowReasons(provider, parts.filter(isRowPart), parts.filter((part) => isPlace(part) && !isRowPart(part))); + + if (rowLabels === null) return null; + + return [...new Set([...rowLabels, ...answers.flat().filter((entity) => entity.kind !== 'provider').map((entity) => provider.details[entity.id] ?? entity.label)])]; +} + +/** + * Each place asked for needs one coverage row that also states everything asked per country. + * With no place, one row of any country is enough. + */ +function rowReasons(provider: SearchProvider, perRow: readonly QueryPart[], places: readonly QueryPart[]): string[] | null { + const labels: string[] = []; + + for (const place of places.length === 0 ? [null] : places) { + const found = rowFor(provider, perRow, place); + + if (found === null) return null; + + labels.push(...found); + } + + return labels; +} + +function rowFor(provider: SearchProvider, perRow: readonly QueryPart[], place: QueryPart | null): string[] | null { + if (place === null && perRow.length === 0) return []; + + for (const row of provider.rows) { + const where = place === null ? [] : place.entities.filter((entity) => inPlace(row.country, entity) || answersWhole(provider, entity)); + if (place !== null && where.length === 0) continue; + + const found = perRow.map((part) => part.entities.filter((entity) => (ROW_KINDS.has(entity.kind) ? row.facts.includes(entity.id) : answersWhole(provider, entity)))); + if (found.every((entities) => entities.length > 0)) return [...where, ...found.flat()].filter((entity) => entity.kind !== 'provider').map((entity) => entity.label); + } + + return null; +} + +function answersWhole(provider: SearchProvider, entity: SearchEntity): boolean { + return entity.kind === 'provider' ? entity.id === `provider:${provider.slug}` : provider.facts.includes(entity.id); +} + +function inPlace(country: string, entity: SearchEntity): boolean { + return entity.id === `country:${country}` || (entity.kind === 'zone' && (entity.countries ?? []).includes(country)); +} + +function isRowPart(part: QueryPart): boolean { + return part.entities.some((entity) => ROW_KINDS.has(entity.kind)); +} + +function isPlace(part: QueryPart): boolean { + return part.entities.some((entity) => entity.kind === 'country' || entity.kind === 'zone'); +} + +function isProvider(part: QueryPart): boolean { + return part.entities.every(({ kind }) => kind === 'provider'); +} + +function isNamed(provider: SearchProvider, parts: readonly QueryPart[]): boolean { + return parts.some((part) => part.entities.some((entity) => entity.id === `provider:${provider.slug}`)); +} + +/** The section named, or next to a provider the one that states the feature asked for. */ +function sectionAsked(parts: readonly QueryPart[], named: boolean): SheetSection | null { + const entities = parts.flatMap((part) => part.entities); + const section = entities.find(({ kind }) => kind === 'section') ?? (named ? entities.find(({ kind }) => kind === 'feature') : undefined); + + return section?.section ?? null; +} + +/** Where the sheet states the first feature asked for. */ +function sectionOfFeatures(provider: SearchProvider, parts: readonly QueryPart[]): SheetSection | null { + const feature = parts.flatMap((part) => part.entities).find((entity) => entity.kind === 'feature' && provider.facts.includes(entity.id)); + + return feature?.section ?? null; +} diff --git a/src/search/section-look.ts b/src/search/section-look.ts new file mode 100644 index 0000000..e72cb92 --- /dev/null +++ b/src/search/section-look.ts @@ -0,0 +1,20 @@ +import { glossaryLook } from '../lib/glossary-look'; +import type { GlossaryIcon, GlossaryTone } from '../schema/constants'; +import type { SearchIcon } from './payload-types'; +import type { SheetSection } from './types'; + +const LOOKS: Readonly> = { + fees: { icon: 'percent', tone: 'money' }, + coverage: { icon: 'globe', tone: 'methods' }, + settlements: { icon: 'to-bank', tone: 'money' }, + integration: { icon: 'code', tone: 'technical' }, + onboarding: { icon: 'id-card', tone: 'actors' }, + licences: { icon: 'seal', tone: 'rules' }, +}; + +/** Icon and colours of a sheet section, drawn like the glossary. */ +export function sectionLook(section: SheetSection): SearchIcon { + const { icon, tone } = LOOKS[section]; + + return glossaryLook({ icon }, tone); +} diff --git a/src/search/text.ts b/src/search/text.ts new file mode 100644 index 0000000..e4e15c1 --- /dev/null +++ b/src/search/text.ts @@ -0,0 +1,35 @@ +import { normalise } from '../lib/search-match'; + +/** A word of a query: as typed, without case or accent, and as compared. */ +export interface Token { + readonly raw: string; + readonly plain: string; + readonly word: string; +} + +/** Words whose final -s is not a plural. */ +const NOT_PLURAL: ReadonlySet = new Set(['pays', 'sans']); + +/** Words of a text as the search compares them: no case, accent or punctuation, plural -s dropped. */ +export function tokens(text: string): Token[] { + return text + .split(/[^\p{L}\p{N}\p{M}]+/u) + .filter(Boolean) + .map((raw) => { + const plain = normalise(raw); + + return { raw, plain, word: singular(plain) }; + }); +} + +/** A text as the search stores it. */ +export function phrase(text: string): string { + return tokens(text) + .map(({ word }) => word) + .join(' '); +} + +/** "fees" and "fee" are one word; short words and -ss endings keep their last letter. */ +function singular(word: string): string { + return word.length > 3 && word.endsWith('s') && !word.endsWith('ss') && !NOT_PLURAL.has(word) ? word.slice(0, -1) : word; +} diff --git a/src/search/types.ts b/src/search/types.ts new file mode 100644 index 0000000..886257c --- /dev/null +++ b/src/search/types.ts @@ -0,0 +1,97 @@ +import type { Locale } from '../i18n/locales'; +import type { Provider } from '../schema/provider'; + +/** Sections of a provider sheet a result can open, by anchor. */ +export type SheetSection = 'coverage' | 'fees' | 'settlements' | 'integration' | 'onboarding' | 'licences'; + +/** A text in each language of the site. */ +export type Localised = Readonly>; + +/** + * Something a provider sheet states, that visitors can search for. Adding one entry to a + * declaration file is enough: the index, the search and the reasons shown read it from there. + */ +export interface FeatureDeclaration { + readonly id: string; + readonly label: Localised; + /** What visitors type, in any language. Case, accents and plurals in -s do not matter. */ + readonly words: readonly string[]; + /** Where the sheet states it. */ + readonly section: SheetSection; + /** Whether the sourced record states it. Unknown is not yes. */ + readonly test: (provider: Provider) => boolean; + /** What to show instead of the label, when records state it in different ways. */ + readonly detail?: (provider: Provider) => Localised; +} + +/** A word that asks for a section of a sheet, such as "fees" in "fedapay fees". */ +export interface SectionDeclaration { + readonly id: SheetSection; + readonly label: Localised; + readonly words: readonly string[]; +} + +/** What a word of a query can stand for. */ +export type EntityKind = 'provider' | 'country' | 'zone' | 'brand' | 'method' | 'currency' | 'family' | 'ability' | 'feature' | 'section'; + +/** One searchable thing, prepared at build time for a locale. */ +export interface SearchEntity { + /** `kind:key`, unique in the index. */ + readonly id: string; + readonly kind: EntityKind; + readonly label: string; + /** Normalised phrases that name it. */ + readonly words: readonly string[]; + /** Those of `words` that are another name of it, such as a city or a former brand. */ + readonly aliases?: readonly string[]; + /** For a zone: the countries it stands for. */ + readonly countries?: readonly string[]; + readonly section?: SheetSection; +} + +/** What one provider answers to, prepared at build time. */ +export interface SearchProvider { + readonly slug: string; + readonly name: string; + /** Ids true for the whole provider: its family and features. */ + readonly facts: readonly string[]; + /** Reasons that read differently from the entity label, by entity id. */ + readonly details: Readonly>; + /** One row per coverage entry, so a method is only found in the country it is stated for. */ + readonly rows: ReadonlyArray<{ readonly country: string; readonly facts: readonly string[] }>; +} + +export interface SearchIndex { + readonly entities: readonly SearchEntity[]; + readonly providers: readonly SearchProvider[]; +} + +/** A part of the query and what it may stand for: any of these entities answers it. */ +export interface QueryPart { + /** As typed. */ + readonly text: string; + readonly entities: readonly SearchEntity[]; + /** The words were not spelt like this: the entity was guessed. */ + readonly guessed: boolean; +} + +export interface ParsedQuery { + readonly parts: readonly QueryPart[]; + /** Parts the query asks to leave out ("without SDK"). */ + readonly negated: readonly QueryPart[]; + /** Words nothing in the index answers to. */ + readonly ignored: readonly string[]; +} + +/** A provider found, and the parts of the query it answers, as labels to show. */ +export interface ProviderHit { + readonly slug: string; + readonly reasons: readonly string[]; + /** Section of the sheet the query asks for. */ + readonly section: SheetSection | null; +} + +export interface SearchResult { + readonly query: ParsedQuery; + readonly hits: readonly ProviderHit[]; +} diff --git a/src/search/view-types.ts b/src/search/view-types.ts new file mode 100644 index 0000000..0dbeb76 --- /dev/null +++ b/src/search/view-types.ts @@ -0,0 +1,52 @@ +import type { GlossaryResult, ProviderCard, SectionResult } from './payload-types'; + +export interface ProviderRow extends ProviderCard { + readonly name: string; + readonly reasons: readonly string[]; + /** Label of the section the row opens, or `null` for the top of the sheet. */ + readonly section: string | null; +} + +export interface SectionRow extends SectionResult { + readonly href: string; +} + +export interface EmptyView { + readonly title: string; + readonly hint: string; + /** Whether a provider may be missing from the directory. */ + readonly suggest: boolean; +} + +/** A sentence above the results, and the part of it to bring out. */ +export interface SearchNote { + readonly text: string; + readonly strong: string; +} + +/** What the window shows for a query. */ +export interface SearchView { + readonly notes: readonly SearchNote[]; + readonly providers: readonly ProviderRow[]; + readonly total: number; + /** Sections of the one provider named. */ + readonly sections: readonly SectionRow[]; + readonly terms: readonly GlossaryResult[]; + /** Set when there is nothing else to show. */ + readonly empty: EmptyView | null; +} + +/** The sentences the window needs; `{...}` parts are filled in. */ +export interface ViewStrings { + readonly corrected: string; + readonly ignored: string; + readonly or: string; + readonly noResult: string; + readonly noResultHint: string; + readonly notStated: string; + readonly notStatedHint: string; + readonly negation: string; + readonly negationHint: string; + readonly sectionAlone: string; + readonly sectionAloneHint: string; +} diff --git a/src/search/view.ts b/src/search/view.ts new file mode 100644 index 0000000..6d44f4b --- /dev/null +++ b/src/search/view.ts @@ -0,0 +1,130 @@ +import { searchGlossary } from '../lib/glossary-search'; +import type { GlossaryResult, SearchPayload } from './payload-types'; +import { compact } from './parse-query'; +import { search } from './search'; +import type { ProviderHit, QueryPart, SearchResult, SheetSection } from './types'; +import type { EmptyView, ProviderRow, SearchNote, SearchView, SectionRow, ViewStrings } from './view-types'; + +/** Providers shown before the list is unfolded. */ +export const FIRST_ROWS = 6; + +/** Definitions shown, and how many matches make a word too vague to define. */ +const MAX_TERMS = 2; +const VAGUE_TERMS = 6; + +/** Reasons that fit under a provider name. */ +const MAX_REASONS = 4; + +/** Shortest unknown word worth pointing out: below, it is still being typed. */ +const MIN_UNKNOWN = 3; + +/** What the window shows for a query. `unfolded` lists every provider. */ +export function searchView(payload: SearchPayload, strings: ViewStrings, text: string, unfolded: boolean): SearchView { + const result = search(payload.index, text); + const shown = unfolded ? result.hits : result.hits.slice(0, FIRST_ROWS); + const terms = result.query.negated.length > 0 ? [] : definitionsOf(payload, text); + const found = result.hits.length > 0 || terms.length > 0; + + return { + notes: result.hits.length > 0 ? notesOf(result, strings) : [], + providers: shown.map((hit) => providerRow(payload, hit)), + total: result.hits.length, + sections: sectionsOf(payload, result), + terms, + empty: found ? null : emptyView(result, strings, text.trim()), + }; +} + +function definitionsOf(payload: SearchPayload, text: string): GlossaryResult[] { + const ids = searchGlossary(payload.terms, text); + + if (ids.length >= VAGUE_TERMS) return []; + + return ids.slice(0, MAX_TERMS).flatMap((id) => payload.definitions[id] ?? []); +} + +function notesOf({ query }: SearchResult, strings: ViewStrings): SearchNote[] { + const corrected = query.parts.filter((part) => part.guessed || isAlias(part)); + const unknown = query.ignored.filter((word) => word.length >= MIN_UNKNOWN); + const notes: SearchNote[] = []; + + if (corrected.length > 0) { + const name = corrected.map((part) => partLabel(part, strings.or)).join(', '); + const typed = corrected.map((part) => part.text).join(', '); + + notes.push({ text: fill(strings.corrected, { name, query: typed }), strong: name }); + } + + if (unknown.length > 0) { + const words = unknown.join(', '); + + notes.push({ text: fill(strings.ignored, { words }), strong: words }); + } + + return notes; +} + +/** "abidjan" and "flooz" are understood as something the results name otherwise. */ +function isAlias({ entities, text }: QueryPart): boolean { + return entities.length === 1 && (entities[0]?.aliases ?? []).some((alias) => compact(alias) === compact(text)); +} + +function partLabel({ entities }: QueryPart, or: string): string { + return [...new Set(entities.map((entity) => entity.label))].slice(0, 2).join(or); +} + +function providerRow(payload: SearchPayload, { slug, reasons, section }: ProviderHit): ProviderRow { + const card = cardOf(payload, slug); + + return { + ...card, + href: section === null ? card.href : sectionHref(card.href, section), + name: payload.index.providers.find((provider) => provider.slug === slug)?.name ?? slug, + reasons: reasons.slice(0, MAX_REASONS), + section: payload.sections.find(({ id }) => id === section)?.label ?? null, + }; +} + +/** The ways into a sheet, when the query names one provider. */ +function sectionsOf(payload: SearchPayload, { query, hits }: SearchResult): SectionRow[] { + const [hit] = hits; + const named = query.parts.some((part) => part.entities.some(({ id }) => id === `provider:${hit?.slug}`)); + + if (hit === undefined || hits.length > 1 || !named) return []; + + const { href } = cardOf(payload, hit.slug); + + return payload.sections.map((section) => ({ ...section, href: sectionHref(href, section.id) })); +} + +function cardOf(payload: SearchPayload, slug: string): SearchPayload['cards'][string] { + const card = payload.cards[slug]; + + if (card === undefined) throw new Error(`No search card for "${slug}"`); + + return card; +} + +function sectionHref(href: string, section: SheetSection): string { + return `${href}#${section}`; +} + +function emptyView({ query }: SearchResult, strings: ViewStrings, text: string): EmptyView { + const [excluded] = query.negated; + if (excluded !== undefined) return { title: strings.negation, hint: fill(strings.negationHint, { criterion: partLabel(excluded, strings.or) }), suggest: false }; + + const criteria = query.parts.map((part) => partLabel(part, strings.or)).join(', '); + + if (query.parts.length === 0) return { title: fill(strings.noResult, { query: text }), hint: strings.noResultHint, suggest: true }; + + if (query.parts.every((part) => part.entities.every(({ kind }) => kind === 'section'))) { + return { title: fill(strings.sectionAlone, { section: criteria }), hint: fill(strings.sectionAloneHint, { query: text }), suggest: false }; + } + + return { title: strings.notStated, hint: fill(strings.notStatedHint, { criteria }), suggest: false }; +} + +/** Puts values in the `{name}` places of a sentence. */ +export function fill(template: string, values: Readonly>): string { + return template.replace(/\{(\w+)\}/g, (place, name: string) => values[name] ?? place); +} diff --git a/src/search/vocabulary.ts b/src/search/vocabulary.ts new file mode 100644 index 0000000..24cea99 --- /dev/null +++ b/src/search/vocabulary.ts @@ -0,0 +1,65 @@ +import type { MethodKind } from '../lib/offer-types'; +import type { Family } from '../lib/catalogue-types'; +import type { Localised, SectionDeclaration } from './types'; + +/** Sections of a sheet visitors ask for together with a provider name. */ +export const SECTIONS: readonly SectionDeclaration[] = [ + { id: 'fees', label: { en: 'Fees', fr: 'Frais' }, words: ['frais', 'tarif', 'prix', 'commission', 'coût', 'fee', 'price', 'pricing', 'rate'] }, + { id: 'coverage', label: { en: 'Coverage', fr: 'Couverture' }, words: ['couverture', 'pays couverts', 'coverage'] }, + { id: 'settlements', label: { en: 'Settlement', fr: 'Reversement' }, words: ['délai', 'délais'] }, + { id: 'integration', label: { en: 'Integration', fr: 'Intégration' }, words: ['intégration', 'intégrer', 'integration'] }, + { id: 'onboarding', label: { en: 'Opening an account', fr: 'Ouverture de compte' }, words: ['ouvrir un compte', 'ouverture de compte', 'inscription', 'documents', 'kyc', 'open an account', 'signup'] }, + { id: 'licences', label: { en: 'Licences', fr: 'Licences' }, words: ['licences'] }, +]; + +/** Words for a payment method, beside its label. */ +export const METHOD_WORDS: Readonly>> = { + card: ['carte', 'carte bancaire', 'cb', 'card', 'bank card', 'credit card', 'debit card'], + mobile_money: ['mobile money', 'momo', 'argent mobile', 'paiement mobile'], + wallet: ['portefeuille électronique', 'e-wallet'], + bank_transfer: ['virement', 'virement bancaire', 'bank transfer'], + ussd: ['ussd'], + qr: ['qr', 'qr code'], + virtual_account: ['compte virtuel', 'virtual account'], + direct_debit: ['prélèvement', 'direct debit'], + cash: ['espèces', 'cash'], + apple_pay: ['apple pay'], + google_pay: ['google pay'], +}; + +/** Words for a provider family, beside its labels. */ +export const FAMILY_WORDS: Readonly>> = { + aggregator: ['agrégateur', 'aggregator', 'psp', 'passerelle de paiement', 'payment gateway'], + operator_api: ['opérateur', 'operator', 'telco'], + wallet: ['portefeuille', 'wallet'], + orchestrator: ['orchestrateur', 'orchestrator'], + merchant_of_record: ['merchant of record', 'mor', 'vendeur officiel'], + acquirer: ['banque acquéreuse', 'acquéreur', 'acquirer'], + switch: ['switch', 'switch interbancaire'], +}; + +/** What a provider does for a merchant in a country. */ +export const ABILITIES: ReadonlyArray<{ id: 'collect' | 'payout'; label: Localised; words: readonly string[] }> = [ + { id: 'collect', label: { en: 'Collect', fr: 'Encaisser' }, words: ['encaisser', 'encaissement', 'collecter', 'recevoir', 'accepter', 'collect', 'collection', 'pay-in', 'accept', 'receive'] }, + { id: 'payout', label: { en: 'Send', fr: 'Envoyer' }, words: ['envoyer', 'envoi', 'décaisser', 'décaissement', 'transférer', 'payout', 'send', 'disbursement'] }, +]; + +/** Monetary unions, as visitors name them. */ +export const ZONES: ReadonlyArray<{ id: 'uemoa' | 'cemac'; label: Localised; words: readonly string[] }> = [ + { id: 'uemoa', label: { en: 'WAEMU (UEMOA)', fr: 'UEMOA' }, words: ['uemoa', 'umoa', 'waemu', 'zone uemoa'] }, + { id: 'cemac', label: { en: 'CEMAC', fr: 'CEMAC' }, words: ['cemac', 'zone cemac'] }, +]; + +/** Words for a currency, beside its code. */ +export const CURRENCY_WORDS: Readonly> = { + XOF: ['franc cfa', 'fcfa', 'cfa'], + XAF: ['franc cfa', 'fcfa', 'cfa'], +}; + +/** Words that turn the next one around. A sheet that says nothing is not a sheet that says no, so these are not searched. */ +export const NEGATIONS: ReadonlySet = new Set(['sans', 'pas', 'non', 'aucun', 'aucune', 'sauf', 'no', 'not', 'without', 'except']); + +/** Words of a question that name nothing, in both languages. */ +export const IGNORED_WORDS: ReadonlySet = new Set( + 'a an and any are at avec au aux by can ce ces c cest comment d dans de des do does du en est et for from how i il in is it j je l la le les liste ma me mes mon my of on ou par pour propose proposent qu que quel quelle quelles quels qui quoi sa se service services solution solutions supporte sur the that to un une via which who with fournisseur fournisseurs prestataire prestataires provider providers offre offrent paiement payment payer pays country countries ligne online entre elle elles il ils ne n se on nous vous y mode moyen moyens afrique africa african africain com www faire veux voudrais cherche trouver want need find'.split(' '), +); diff --git a/src/search/window.ts b/src/search/window.ts new file mode 100644 index 0000000..e5f4bc2 --- /dev/null +++ b/src/search/window.ts @@ -0,0 +1,267 @@ +import { OVERLAY_EVENT } from '../lib/disclosure'; +import { badge, noteLine } from './elements'; +import type { SearchPayload } from './payload-types'; +import { renderResults } from './render-results'; +import { fill, searchView } from './view'; +import type { EmptyView, SearchNote, SearchView, ViewStrings } from './view-types'; + +/** Sentences of the window, as the page embeds them. */ +export interface WindowStrings extends ViewStrings { + readonly providers: string; + readonly glossary: string; + readonly found: { readonly one: string; readonly other: string }; + readonly partial: string; + readonly more: { readonly one: string; readonly other: string }; + readonly loading: string; + readonly unavailable: string; + readonly unavailableHint: string; +} + +/** Logos shown before anything is typed. */ +const IDLE_LOGOS = 4; + +/** The search window: loads its data when first opened, then answers each keystroke in the browser. */ +export class SearchWindow { + private readonly input: HTMLInputElement; + private readonly list: HTMLElement; + private readonly strings: WindowStrings; + private payload: SearchPayload | null = null; + private loading: Promise | null = null; + private failed = false; + private options: HTMLElement[] = []; + private active = -1; + private unfolded = false; + + constructor(private readonly dialog: HTMLDialogElement) { + this.input = this.find('[data-search-input]'); + this.list = this.find('[data-search-list]'); + this.strings = JSON.parse(this.find('[data-search-strings]').textContent ?? '{}') as WindowStrings; + + this.input.addEventListener('input', () => this.changed()); + this.input.addEventListener('keydown', (event) => this.onKey(event)); + this.find('[data-search-clear]').addEventListener('click', () => this.clear()); + dialog.querySelectorAll('[data-search-close]').forEach((button) => button.addEventListener('click', () => dialog.close())); + this.list.addEventListener('click', (event) => this.onListClick(event)); + this.list.addEventListener('mousemove', (event) => this.onHover(event)); + this.closeOnBackdrop(); + } + + open(): void { + if (this.dialog.open) return; + + document.dispatchEvent(new CustomEvent(OVERLAY_EVENT)); + this.dialog.showModal(); + // Focus in the same tap, or phones keep the keyboard closed. + this.input.focus(); + this.input.select(); + this.showLogos(); + this.render(); + void this.load(); + } + + /** Fetches the search data once; a failed load is tried again the next time the window opens. */ + load(): Promise { + this.loading ??= this.fetchPayload(); + + return this.loading; + } + + private async fetchPayload(): Promise { + this.failed = false; + + try { + const response = await fetch(this.dialog.dataset['searchUrl'] ?? ''); + if (!response.ok) throw new Error(`Search data answered ${response.status}`); + this.payload = (await response.json()) as SearchPayload; + } catch { + this.failed = true; + this.loading = null; + } + + this.showLogos(); + this.render(); + } + + /** Closes on a click on the backdrop, not when a text selection started in the field ends outside it. */ + private closeOnBackdrop(): void { + let pressedOnBackdrop = false; + + this.dialog.addEventListener('pointerdown', (event) => (pressedOnBackdrop = event.target === this.dialog)); + this.dialog.addEventListener('click', (event) => { + if (pressedOnBackdrop && event.target === this.dialog) this.dialog.close(); + }); + } + + private changed(): void { + this.unfolded = false; + this.list.scrollTop = 0; + this.render(); + } + + private clear(): void { + this.input.value = ''; + this.input.focus(); + this.changed(); + } + + private render(): void { + const query = this.input.value.trim(); + const view = this.viewOf(query); + + this.list.replaceChildren(...(view === null ? [] : renderResults(view, this.labels(view)))); + this.options = [...this.list.querySelectorAll('[role="option"]')]; + this.options.forEach((option, index) => (option.id = `site-search-option-${index}`)); + this.select(this.options.length > 0 ? 0 : -1); + + this.find('[data-search-clear]').hidden = query === ''; + this.find('[data-search-idle]').hidden = query !== ''; + this.list.hidden = this.options.length === 0; + this.input.setAttribute('aria-expanded', String(this.options.length > 0)); + this.showNotes(view?.notes ?? []); + this.showEmpty(view?.empty ?? null); + this.announce(view); + } + + /** What to show for a query, or `null` before anything is typed. */ + private viewOf(query: string): SearchView | null { + if (query === '') return null; + if (this.payload !== null) return searchView(this.payload, this.strings, query, this.unfolded); + + const { loading, unavailable, unavailableHint } = this.strings; + const empty: EmptyView = this.failed ? { title: unavailable, hint: unavailableHint, suggest: false } : { title: loading, hint: '', suggest: false }; + + return { notes: [], providers: [], total: 0, sections: [], terms: [], empty }; + } + + private labels(view: SearchView): { providers: string; glossary: string; count: string; more: string | null } { + const { providers, glossary, partial, more } = this.strings; + const hidden = view.total - view.providers.length; + const count = hidden === 0 ? String(view.total) : fill(partial, { shown: String(view.providers.length), total: String(view.total) }); + + return { providers, glossary, count, more: hidden === 0 ? null : fill(hidden === 1 ? more.one : more.other, { count: String(hidden) }) }; + } + + private showNotes(notes: readonly SearchNote[]): void { + const box = this.find('[data-search-notes]'); + + box.hidden = notes.length === 0; + box.replaceChildren(...notes.map(noteLine)); + } + + private showEmpty(empty: EmptyView | null): void { + this.find('[data-search-empty]').hidden = empty === null; + if (empty === null) return; + + this.find('[data-search-empty-title]').textContent = empty.title; + this.find('[data-search-empty-hint]').textContent = empty.hint; + this.find('[data-search-suggest]').hidden = !empty.suggest; + } + + private announce(view: SearchView | null): void { + const { one, other } = this.strings.found; + const count = view === null ? 0 : view.total + view.terms.length; + const found = view === null ? '' : (view.empty?.title ?? fill(count === 1 ? one : other, { count: String(count) })); + + this.find('[data-search-status]').textContent = view === null ? '' : [...view.notes.map(({ text }) => text), found].join(' '); + } + + /** A few logos picked anew each time, so none is favoured. */ + private showLogos(): void { + const marked = Object.values(this.payload?.cards ?? {}).filter((card) => card.mark !== null); + const picked = shuffle(marked).slice(0, IDLE_LOGOS); + + this.find('[data-search-logos]').replaceChildren(...picked.map(badge)); + } + + private onListClick(event: MouseEvent): void { + const option = optionOf(event); + if (option === null) return; + + if ('searchMore' in option.dataset) this.unfold(); + // A section of the page already open only scrolls: the window has to leave. + else if (!event.metaKey && !event.ctrlKey && !event.shiftKey) this.dialog.close(); + } + + private onHover(event: MouseEvent): void { + const option = optionOf(event); + + if (option !== null && this.options[this.active] !== option) this.select(this.options.indexOf(option), false); + } + + private unfold(): void { + const from = this.active; + + this.unfolded = true; + this.render(); + this.select(Math.min(from, this.options.length - 1)); + this.input.focus(); + } + + private onKey(event: KeyboardEvent): void { + const count = this.options.length; + + if (event.isComposing) return; + + if (event.key === 'Escape') { + event.preventDefault(); + this.dialog.close(); + } else if (event.key === 'ArrowDown' && count > 0) { + event.preventDefault(); + this.select((this.active + 1) % count); + } else if (event.key === 'ArrowUp' && count > 0) { + event.preventDefault(); + this.select((this.active - 1 + count) % count); + } else if (event.key === 'Enter') { + this.choose(event); + } + } + + private choose(event: KeyboardEvent): void { + const option = this.options[this.active]; + if (!option) return; + + event.preventDefault(); + + const aside = event.metaKey || event.ctrlKey || event.shiftKey; + if (aside && option instanceof HTMLAnchorElement) window.open(option.href, '_blank', 'noopener'); + else option.click(); + } + + private select(index: number, reveal = true): void { + const option = this.options[index]; + + this.active = option ? index : -1; + this.options.forEach((item) => item.setAttribute('aria-selected', String(item === option))); + + if (!option) { + this.input.removeAttribute('aria-activedescendant'); + return; + } + + this.input.setAttribute('aria-activedescendant', option.id); + if (!reveal) return; + + // The first row brings its group name back into view. + if (index === 0) this.list.scrollTop = 0; + else option.scrollIntoView({ block: 'nearest' }); + } + + private find(selector: string): T { + const found = this.dialog.querySelector(selector); + + if (!found) throw new Error(`Search dialog is missing ${selector}`); + + return found; + } +} + +function optionOf(event: Event): HTMLElement | null { + return event.target instanceof Element ? event.target.closest('[role="option"]') : null; +} + +function shuffle(items: readonly T[]): T[] { + return items + .map((item) => ({ item, order: Math.random() })) + .sort((a, b) => a.order - b.order) + .map(({ item }) => item); +} diff --git a/src/styles/search.css b/src/styles/search.css new file mode 100644 index 0000000..fb8bde4 --- /dev/null +++ b/src/styles/search.css @@ -0,0 +1,108 @@ +/* Search window. Its rows are built in the browser, so these rules are global, under `.search-dialog`. */ +.search-dialog { + width: min(720px, calc(100% - 32px)); max-width: none; height: min(600px, calc(100dvh - 48px)); max-height: none; margin: auto; padding: 0; + border: 0; border-radius: 28px; background: var(--surface); color: var(--ink); + box-shadow: var(--shadow-float); overflow: hidden; +} +.search-dialog[open] { display: flex; flex-direction: column; } +.search-dialog::backdrop { background: rgba(7, 40, 38, 0.5); } +.search-dialog [hidden] { display: none; } + +.search-dialog .field { flex: none; display: flex; align-items: center; gap: 14px; height: 72px; padding: 0 24px; box-shadow: inset 0 -1px 0 var(--line); } +.search-dialog .glass { flex: none; color: var(--ink-3); } +.search-dialog input { + flex: 1; min-width: 0; height: 100%; padding: 0; border: 0; background: transparent; + font: 400 30px var(--display); color: var(--ink); outline: none; caret-color: var(--lagune); +} +.search-dialog input::placeholder { color: var(--ink-3); opacity: 1; } +.search-dialog .back, .search-dialog .clear { display: none; } +.search-dialog .escape { flex: none; padding: 0; border: 0; background: none; cursor: pointer; } +.search-dialog .escape kbd { display: inline-block; padding: 4px 8px; border-radius: 8px; background: var(--sable-creux); color: var(--ink-2); font: 400 12px/1.5 var(--mono); } + +.search-dialog .idle, .search-dialog .empty { flex: 1; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; align-items: center; gap: 10px; text-align: center; } +.search-dialog .idle { justify-content: center; padding: 0 60px 10px; } +.search-dialog .empty { padding: 130px 60px 24px; } +.search-dialog .title { margin: 0; font: 400 30px/1.15 var(--display); overflow-wrap: anywhere; } +.search-dialog .empty .title { font-size: 28px; line-height: 1.2; } +.search-dialog .hint { margin: 0; max-width: 400px; color: var(--ink-2); font-size: 15px; line-height: 1.5; } +.search-dialog .idle .hint { max-width: 380px; } +.search-dialog .suggest { display: inline-flex; align-items: center; gap: 8px; min-height: 44px; color: var(--lagune); font-size: 14px; font-weight: 600; text-decoration: none; } + +.search-dialog .logos { display: flex; height: 52px; margin-bottom: 12px; } +.search-dialog .logos .badge.has-mark { width: 52px; height: 52px; margin: 0 -5px; padding: 5px; border-radius: 15px; background: #fff; box-shadow: 0 0 0 1px var(--sable-creux), 0 6px 16px rgba(8, 40, 38, 0.08); } +.search-dialog .logos .badge:nth-child(1) { transform: rotate(-8deg); } +.search-dialog .logos .badge:nth-child(2) { transform: translateY(-6px) rotate(3deg); } +.search-dialog .logos .badge:nth-child(3) { z-index: 1; transform: translateY(2px) rotate(-3deg); } +.search-dialog .logos .badge:nth-child(4) { transform: translateY(-5px) rotate(8deg); } + +.search-dialog .notes { flex: none; padding: 14px 24px 0; } +.search-dialog .notes p { margin: 0; color: var(--ink-2); font-size: 14px; line-height: 1.45; overflow-wrap: anywhere; } +.search-dialog .notes b { color: var(--ink); font-weight: 600; } +.search-dialog .results { flex: 1; min-height: 0; overflow-y: auto; overscroll-behavior: contain; padding: 14px 12px; } +.search-dialog .notes:not([hidden]) + .results { padding-top: 12px; } +.search-dialog .group-head { display: flex; justify-content: space-between; padding: 12px 12px 6px; color: var(--ink-3); font: 400 11px var(--mono); letter-spacing: 0.08em; text-transform: uppercase; } + +.search-dialog .row { position: relative; display: flex; align-items: center; gap: 14px; min-height: 64px; padding: 8px 12px; border-radius: 14px; color: var(--ink); text-decoration: none; } +.search-dialog [aria-selected='true'] { background: var(--sable); } +.search-dialog .row .badge, .search-dialog .disc { flex: none; width: 40px; height: 40px; } +.search-dialog .badge { display: grid; place-items: center; border-radius: 11px; font-size: 20px; } +.search-dialog .badge.has-mark { overflow: hidden; padding: 3px; background: var(--surface); box-shadow: inset 0 0 0 1px var(--sable-creux); } +.search-dialog .badge img { width: 100%; height: 100%; min-height: 0; border-radius: 8px; object-fit: contain; } +.search-dialog .disc { display: grid; place-items: center; border-radius: 50%; } +.search-dialog .disc svg { width: 20px; height: 20px; } +.search-dialog .main { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 4px; } +.search-dialog .name { font-size: 16px; font-weight: 600; line-height: 1.2; } +.search-dialog .reasons { display: flex; flex-wrap: wrap; gap: 3px 12px; color: var(--ink-2); font-size: 13.5px; line-height: 1.3; } +.search-dialog .reason { display: inline-flex; align-items: baseline; gap: 5px; } +.search-dialog .tick { color: var(--ok); font-weight: 700; } +.search-dialog .section { flex: none; display: inline-flex; align-items: center; gap: 6px; color: var(--lagune); font-size: 13.5px; font-weight: 600; } +.search-dialog .definition { display: -webkit-box; overflow: hidden; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; color: var(--ink-2); font-size: 13.5px; line-height: 19px; } + +.search-dialog .sections { display: grid; grid-template-columns: 1fr 1fr; gap: 6px 8px; padding: 8px 0; } +.search-dialog .section-row { min-height: 60px; padding: 0 14px 0 12px; } +.search-dialog .section-row .name { flex: 1; font-size: 15px; font-weight: 500; } +.search-dialog .arrow { display: inline-flex; } +.search-dialog .arrow svg { width: 14px; height: auto; } +.search-dialog .more { display: flex; align-items: center; width: 100%; min-height: 44px; padding: 0 12px 0 66px; border: 0; border-radius: 14px; background: none; color: var(--lagune); font: 600 14px var(--ui); cursor: pointer; } + +.search-dialog .keys { flex: none; margin: 0; padding: 12px 24px; box-shadow: inset 0 1px 0 var(--line); color: var(--ink-3); font: 400 12px var(--mono); } + +.search-dialog .badge.tone-0 { background: var(--lagune); color: var(--surface); } +.search-dialog .badge.tone-1 { background: var(--lagune-deep); color: var(--surface); } +.search-dialog .badge.tone-2 { background: var(--safran); color: var(--ink); } +.search-dialog .badge.tone-3 { background: var(--lagune-50); color: var(--lagune-deep); } +.search-dialog .badge.tone-4 { background: var(--safran-50); color: var(--safran-text); } +.search-dialog .badge.tone-5 { background: var(--sable-creux); color: var(--ink); } + +@media (max-width: 899px) { + .search-dialog { width: 100%; height: 100dvh; margin: 0; padding-top: env(safe-area-inset-top); border-radius: 0; box-shadow: none; } + .search-dialog .field { gap: 4px; height: 68px; padding: 0 8px 0 4px; } + .search-dialog .glass, .search-dialog .escape, .search-dialog .keys, .search-dialog .row > .section { display: none; } + .search-dialog .back, .search-dialog .clear { flex: none; display: grid; place-items: center; width: 48px; height: 48px; padding: 0; border: 0; background: none; color: var(--ink); cursor: pointer; } + .search-dialog .clear span { display: grid; place-items: center; width: 28px; height: 28px; border-radius: 50%; background: var(--sable-creux); color: var(--ink-2); } + .search-dialog input { font-size: 24px; } + + .search-dialog .idle { flex: 0 1 416px; padding: 0 40px; } + .search-dialog .idle .hint { font-size: 16px; } + .search-dialog .empty { padding: 96px 32px 24px; } + + .search-dialog .notes { padding: 16px 20px 0; } + .search-dialog .results { padding: 8px 0 calc(32px + env(safe-area-inset-bottom)); } + .search-dialog .notes:not([hidden]) + .results { padding-top: 4px; } + .search-dialog .group-head { padding: 16px 20px 4px; } + .search-dialog .row { min-height: 72px; padding: 10px 20px; border-radius: 0; } + .search-dialog .row::after { content: ''; position: absolute; left: 78px; right: 20px; bottom: 0; height: 1px; background: var(--line); } + .search-dialog [aria-selected='true'] { background: none; } + .search-dialog .row .badge, .search-dialog .disc { width: 44px; height: 44px; } + .search-dialog .name { font-size: 17px; } + .search-dialog .reasons, .search-dialog .definition { font-size: 14px; } + .search-dialog .sections { grid-template-columns: 1fr; gap: 0; padding: 4px 0; } + .search-dialog .section-row { min-height: 64px; padding: 0 20px; } + .search-dialog .section-row .name { font-size: 16px; } + .search-dialog .more { min-height: 56px; padding: 0 20px 0 78px; border-radius: 0; font-size: 16px; } +} + +/* A keyboard on a narrow window still needs to see which row it is on. */ +@media (max-width: 899px) and (hover: hover) { + .search-dialog [aria-selected='true'] { background: var(--sable); } +} diff --git a/tests/fixtures/records.ts b/tests/fixtures/records.ts index ac093b0..fd59df5 100644 --- a/tests/fixtures/records.ts +++ b/tests/fixtures/records.ts @@ -55,6 +55,7 @@ export const REFERENCE_DATA: Omit = { { code: 'TG', name_en: 'Togo', name_fr: 'Togo', region: 'west', currency: 'XOF' }, { code: 'CM', name_en: 'Cameroon', name_fr: 'Cameroun', region: 'central', currency: 'XAF' }, ], + places: [{ country: 'TG', aliases: ['Lomé'] }], currencies: [ { code: 'XOF', name: 'West African CFA franc' }, { code: 'XAF', name: 'Central African CFA franc' }, diff --git a/tests/load-dataset.test.ts b/tests/load-dataset.test.ts index 8448952..fc10697 100644 --- a/tests/load-dataset.test.ts +++ b/tests/load-dataset.test.ts @@ -24,6 +24,7 @@ function repository(files: Record): string { const REFERENCE_FILES = { 'data/reference/countries.json': JSON.stringify(REFERENCE_DATA.countries), + 'data/reference/places.json': JSON.stringify(REFERENCE_DATA.places), 'data/reference/currencies.json': JSON.stringify(REFERENCE_DATA.currencies), 'data/reference/brands.json': JSON.stringify(REFERENCE_DATA.brands), 'data/reference/regulators.json': JSON.stringify(REFERENCE_DATA.regulators), diff --git a/tests/search-engine.test.ts b/tests/search-engine.test.ts new file mode 100644 index 0000000..3f4b73f --- /dev/null +++ b/tests/search-engine.test.ts @@ -0,0 +1,163 @@ +import { describe, expect, it } from 'vitest'; + +import { loadSite } from '../src/lib/site-data'; +import { buildSearchPayload } from '../src/search/build-payload'; +import { FEATURES } from '../src/search/features'; +import { search } from '../src/search/search'; +import type { ProviderHit } from '../src/search/types'; + +const site = loadSite(process.cwd()); +const { published } = site; +const payload = buildSearchPayload(site, 'fr'); +const { index } = payload; + +const hits = (text: string): readonly ProviderHit[] => search(index, text).hits; +const slugs = (text: string): string[] => hits(text).map((hit) => hit.slug).sort(); +const providersWhere = (test: (provider: (typeof published)[number]) => boolean): string[] => published.filter(test).map(({ slug }) => slug).sort(); + +describe('declared features', () => { + it.each(FEATURES.map((feature) => [feature.id, feature] as const))('%s finds exactly the providers whose sheet states it', (_id, feature) => { + for (const words of feature.words) expect(slugs(words), words).toEqual(providersWhere(feature.test)); + }); + + it('never counts an unknown or a "none" as a sandbox', () => { + expect(slugs('sandbox')).toEqual(providersWhere(({ integration }) => ['self_serve', 'after_kyc'].includes(integration.sandbox?.value ?? ''))); + }); + + it('tells a sandbox open to all from one behind an approval', () => { + for (const { slug, reasons } of hits('sandbox')) { + const access = published.find((provider) => provider.slug === slug)?.integration.sandbox?.value; + + expect(reasons).toEqual([access === 'self_serve' ? 'Sandbox sans validation' : 'Sandbox après validation du compte']); + } + }); + + it('finds the languages of official SDKs without declaring them', () => { + expect(slugs('sdk flutter')).toEqual(providersWhere(({ integration }) => integration.official_sdks?.value.includes('Flutter') === true)); + }); + + it('leaves out the licence of a partner', () => { + expect(slugs('agréé bceao')).toEqual(providersWhere(({ licences }) => licences.some((licence) => licence.regulator === 'bceao' && licence.partner !== true))); + }); +}); + +describe('names and places', () => { + it.each([ + ['fedapai', 'fedapay'], + ['kkia pay', 'kkiapay'], + ['notchpay', 'notchpay'], + ['flutterwav', 'flutterwave'], + ])('%s finds %s', (text, slug) => expect(slugs(text)).toEqual([slug])); + + it('says when a name was guessed', () => { + expect(search(index, 'fedapai').query.parts[0]?.guessed).toBe(true); + expect(search(index, 'fedapay').query.parts[0]?.guessed).toBe(false); + }); + + it.each([ + ['Abidjan', 'Côte d’Ivoire'], + ['lome', 'Togo'], + ['RDC', 'Congo-Kinshasa'], + ['BJ', 'Bénin'], + ['flooz', 'moov money'], + ['tmoney', 'mixx by yas'], + ])('%s is %s', (alias, name) => { + expect(slugs(alias).length).toBeGreaterThan(0); + for (const slug of slugs(alias)) expect(slugs(name)).toContain(slug); + }); + + it('keeps both Congos apart only when asked to', () => { + expect(slugs('congo')).toEqual([...new Set([...slugs('RDC'), ...slugs('Brazzaville')])].sort()); + }); + + it('reads a currency in the coverage, not in the membership of a union', () => { + expect(slugs('XOF')).toEqual(providersWhere(({ coverage }) => coverage.some((entry) => entry.currencies.includes('XOF')))); + expect(slugs('fcfa')).toEqual(providersWhere(({ coverage }) => coverage.some((entry) => entry.currencies.some((code) => code === 'XOF' || code === 'XAF')))); + }); + + it('takes "momo" as mobile money at large', () => { + expect(slugs('momo')).toEqual(slugs('mobile money')); + }); + + it('puts the provider named first', () => { + expect(hits('wave')[0]?.slug).toBe('wave'); + }); +}); + +describe('words that must not mislead', () => { + it.each(['sans sdk', 'sans webhook', 'sans agrément', 'pas de sandbox', 'no sandbox', 'without sdk', 'not regulated', 'no licence'])('%s is not answered with its opposite', (text) => { + expect(hits(text)).toEqual([]); + expect(search(index, text).query.negated).toHaveLength(1); + }); + + it('still reads a declared phrase that starts with a negation', () => { + expect(slugs('sans société')).toEqual(slugs('particulier')); + }); + + it.each(['pas', 'elle', 'com', 'dev', 'pays', 'afrique', 'ligne', 'entre', 'paiement en ligne', 'online payments', 'mode de paiement'])('%s finds nothing on its own', (text) => { + expect(hits(text)).toEqual([]); + }); + + it('drops small words without changing the answer', () => { + expect(slugs('quels pays pour orange money')).toEqual(slugs('orange money')); + expect(slugs('je ne veux que wave')).toEqual(slugs('wave')); + }); + + it('reads a country code alone or in capitals', () => { + expect(slugs('ne')).toEqual(slugs('Niger')); + expect(slugs('BJ carte')).toEqual(slugs('bénin carte')); + }); +}); + +describe('a provider and what to see of it', () => { + it.each([ + ['paydunya fees', 'paydunya', 'fees'], + ['paydunya licences', 'paydunya', 'licences'], + ['paydunya status', 'paydunya', 'integration'], + ['jeko sandbox', 'jeko', 'integration'], + ])('%s opens the section whatever the sheet states', (text, slug, section) => { + expect(hits(text)).toEqual([{ slug, section, reasons: [] }]); + }); + + it('shows both providers when two are named', () => { + expect(slugs('fedapay paydunya')).toEqual(['fedapay', 'paydunya']); + }); +}); + +describe('several words', () => { + it('asks for a method in the country it is stated for', () => { + const expected = providersWhere(({ coverage }) => coverage.some((entry) => entry.country === 'CM' && entry.collection !== false && entry.methods.some((method) => method.brand === 'mtn-momo'))); + + expect(slugs('cameroun mtn')).toEqual(expected); + }); + + it('reads the order and the small words of a sentence freely', () => { + expect(slugs('quels services proposent un sandbox au Togo ?')).toEqual(slugs('togo sandbox')); + expect(slugs('payer par carte au Bénin')).toEqual(slugs('bénin carte')); + }); + + it('narrows with each word and tells why', () => { + expect(hits('flooz togo sandbox')[0]?.reasons).toEqual(['Togo', 'Moov Money', 'Sandbox sans validation']); + }); + + it('asks for every country named', () => { + expect(slugs('togo bénin')).toEqual(slugs('togo').filter((slug) => slugs('bénin').includes(slug))); + }); + + it('opens the section asked for', () => { + expect(hits('frais fedapay')).toMatchObject([{ slug: 'fedapay', section: 'fees' }]); + expect(hits('sandbox')[0]?.section).toBe('integration'); + }); + + it('keeps what it understood and lists the rest', () => { + const result = search(index, 'togo xylophone'); + + expect(result.query.ignored).toEqual(['xylophone']); + expect(result.hits.length).toBe(hits('togo').length); + }); + + it('finds nothing for an empty text or unrelated words', () => { + expect(hits('')).toEqual([]); + expect(hits('xylophone')).toEqual([]); + }); +}); diff --git a/tests/search-match.test.ts b/tests/search-match.test.ts index 0eddc7b..b0d4450 100644 --- a/tests/search-match.test.ts +++ b/tests/search-match.test.ts @@ -1,67 +1,9 @@ import { describe, expect, it } from 'vitest'; -import type { Locale } from '../src/i18n/locales'; -import { badgeTone } from '../src/lib/catalogue'; -import { searchIndex } from '../src/lib/search-index'; -import { normalise, searchEntries } from '../src/lib/search-match'; -import { providerSchema } from '../src/schema/provider'; -import { provider } from './fixtures/build'; -import { SOURCE } from './fixtures/records'; +import { normalise } from '../src/lib/search-match'; -const BRANDS = new Map([['orange-money', 'Orange Money']]); - -function entriesFor(locale: Locale) { - const providers = [ - providerSchema.parse( - provider({ - slug: 'alpha-pay', - name: 'Alpha Pay', - sources: { evidence: SOURCE }, - coverage: [{ country: 'CI', methods: [{ kind: 'mobile_money', brand: 'orange-money' }], currencies: ['XOF'], source: 'evidence' }], - }), - ), - providerSchema.parse( - provider({ - slug: 'pay-zen', - name: 'Pay Zen', - sources: { evidence: SOURCE }, - coverage: [{ country: 'KE', methods: [{ kind: 'card' }], currencies: ['KES'], source: 'evidence' }], - }), - ), - ]; - - return searchIndex({ providers, locale, brands: BRANDS, marks: new Map([['alpha-pay', '/marks/alpha-pay.png']]), meta: (entry) => `${entry.coverage.length} country` }); -} - -describe('searchIndex', () => { - it('links each provider to its page with its context', () => { - expect(entriesFor('en')[0]).toMatchObject({ name: 'Alpha Pay', initial: 'A', href: '/en/providers/alpha-pay', meta: '1 country' }); - }); - - it('gives a provider its logo, and one without a logo its letter in the catalogue colour', () => { - const [alpha, zen] = entriesFor('en'); - - expect(alpha?.mark).toBe('/marks/alpha-pay.png'); - expect(zen).toMatchObject({ mark: null, tone: badgeTone('Pay Zen') }); +describe('normalise', () => { + it('drops case, accents and apostrophes', () => { + expect(normalise('Côte d’Ivoire')).toBe('cote d ivoire'); }); }); - -describe('searchEntries', () => { - it.each([ - ['en', 'alpha', ['Alpha Pay']], - ['en', 'orange money', ['Alpha Pay']], - ['fr', 'cote d ivoire', ['Alpha Pay']], - ['fr', 'Côte d’Ivoire', ['Alpha Pay']], - ['en', 'kenya', ['Pay Zen']], - ['en', 'pay', ['Pay Zen', 'Alpha Pay']], - ['en', 'en', []], - ['en', 'nothing here', []], - ['en', ' ', []], - ] as const)('in %s finds %s', (locale, query, names) => { - expect(searchEntries(entriesFor(locale), query).map((entry) => entry.name)).toEqual(names); - }); -}); - -it('normalises accents, apostrophes and case', () => { - expect(normalise('Côte d’Ivoire')).toBe('cote d ivoire'); -}); diff --git a/tests/search-view.test.ts b/tests/search-view.test.ts new file mode 100644 index 0000000..415296f --- /dev/null +++ b/tests/search-view.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, it } from 'vitest'; + +import { ui } from '../src/i18n/translate'; +import { loadSite } from '../src/lib/site-data'; +import { buildSearchPayload } from '../src/search/build-payload'; +import { FIRST_ROWS, searchView } from '../src/search/view'; +import type { SearchView } from '../src/search/view-types'; + +const site = loadSite(process.cwd()); +const payload = buildSearchPayload(site, 'fr'); +const strings = ui('fr').search; +const view = (text: string, unfolded = false): SearchView => searchView(payload, strings, text, unfolded); + +describe('search view', () => { + it('shortens a long list until it is unfolded', () => { + const folded = view('sandbox'); + + expect(folded.providers).toHaveLength(FIRST_ROWS); + expect(view('sandbox', true).providers).toHaveLength(folded.total); + }); + + it('opens the section that answers, with its label', () => { + expect(view('sandbox').providers[0]).toMatchObject({ href: '/fr/providers/fedapay#integration', section: 'Intégration' }); + expect(view('frais fedapay').providers[0]).toMatchObject({ href: '/fr/providers/fedapay#fees', section: 'Frais' }); + expect(view('togo').providers[0]).toMatchObject({ section: null }); + }); + + it('offers the sections of the one provider named, and only then', () => { + expect(view('fedapay').sections.map(({ href }) => href)).toContain('/fr/providers/fedapay#licences'); + expect(view('sandbox').sections).toEqual([]); + }); + + it.each([ + ['fedapai', 'Résultats pour FedaPay. Vous avez écrit « fedapai ».'], + ['Abidjan', 'Résultats pour Côte d’Ivoire. Vous avez écrit « Abidjan ».'], + ['flooz', 'Résultats pour Moov Money. Vous avez écrit « flooz ».'], + ['togo xylophone', 'Mot non reconnu : xylophone. Les résultats portent sur le reste.'], + ])('says how %s was understood', (text, note) => { + expect(view(text).notes.map((shown) => shown.text)).toEqual([note]); + }); + + it('says nothing when the words are taken as written', () => { + for (const text of ['fedapay', 'togo', 'Côte d’Ivoire', 'sandbox']) expect(view(text).notes, text).toEqual([]); + }); + + it('defines what the glossary knows, and only by its names', () => { + expect(view('sandbox').terms[0]).toMatchObject({ name: 'Mode test', href: '/fr/glossary#sandbox' }); + expect(view('togo').terms).toEqual([]); + }); + + it.each([ + ['xylophone', 'Aucun résultat pour « xylophone »', true], + ['sandbox wave gabon', 'Aucune fiche ne l’indique pour l’instant', false], + ])('explains why %s finds nothing', (text, title, suggest) => { + expect(view(text).empty).toMatchObject({ title, suggest }); + }); + + it('answers in the language of the page, whatever the language typed', () => { + const english = searchView(buildSearchPayload(site, 'en'), ui('en').search, 'carte bancaire bénin', false); + + expect(english.providers[0]?.reasons).toEqual(['Benin', 'Card']); + expect(english.providers[0]?.href).toMatch(/^\/en\//); + }); + + it('never leaves the everyday searches empty', () => { + const searches = 'togo|Côte d’Ivoire|orange money|wave|mtn|RDC|congo|pay|fedapai|kkia pay|agrégateur|carte|visa|carte bancaire|webhook|qr code|reversement|envoi en masse|bceao|sandbox|mobile money|mobile money togo|encaisser au Sénégal|payer par carte au Bénin|quel agrégateur au Togo|frais fedapay|tmoney|mixx|flooz|momo|cameroun mtn|abidjan|uemoa|cemac|XOF|sans société|burkina|cote ivoire|ivoire|BJ|notchpay|remboursement|lome|sdk flutter|php|hmac'; + + for (const text of searches.split('|')) expect(view(text).empty, text).toBeNull(); + }); +});