Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

7.7 KB
Raw Blame
/**
 * What kind of place a search result is, and which of a trip's categories it
 * most likely belongs in. Shared so the place form (#2282) and the trip
 * assistant, which proposes found places itself, file a result the same way.
 */

export type PlaceKind =
  'lodging' | 'food' | 'drinks' | 'sight' | 'shopping' | 'transport' | 'beach' | 'nature' | 'activity';

/** A trip category as far as the guess reads it. */
export interface PlaceKindCategory {
  id: number;
  name: string | null;
  icon?: string | null;
}

/**
 * What a search result says it is, read from whichever vocabulary its source speaks:
 * Google `types`, the OpenStreetMap tag value, or the TREK Places (Overture) category.
 * Checked in order, first hit wins, so the specific kinds sit before the broad ones
 * ("bar" before "restaurant" would misfile a "restaurant_bar" otherwise).
 */
const KIND_TERMS: ReadonlyArray<[PlaceKind, readonly string[]]> = [
  [
    'lodging',
    [
      'hotel',
      'hostel',
      'motel',
      'guest_house',
      'lodging',
      'resort',
      'camp_site',
      'campground',
      'campsite',
      'chalet',
      'bed_and_breakfast',
      'alpine_hut',
      'apartment',
      'caravan_site',
    ],
  ],
  ['beach', ['beach']],
  [
    'drinks',
    [
      'cafe',
      'coffee',
      'bar',
      'pub',
      'biergarten',
      'night_club',
      'nightclub',
      'bakery',
      'ice_cream',
      'wine_bar',
      'brewery',
      'tea_house',
    ],
  ],
  ['food', ['restaurant', 'fast_food', 'food', 'meal_', 'bistro', 'diner', 'pizzeria', 'steakhouse']],
  ['transport', ['station', 'airport', 'aerodrome', 'ferry_terminal', 'bus_stop', 'terminal', 'car_rental', 'parking']],
  ['shopping', ['shop', 'store', 'mall', 'supermarket', 'market', 'department_store', 'boutique']],
  [
    'sight',
    [
      'museum',
      'attraction',
      'viewpoint',
      'monument',
      'memorial',
      'castle',
      'artwork',
      'gallery',
      'church',
      'cathedral',
      'place_of_worship',
      'historic',
      'ruins',
      'landmark',
      'zoo',
      'aquarium',
      'palace',
      'tower',
    ],
  ],
  [
    'nature',
    [
      'park',
      'nature_reserve',
      'national_park',
      'peak',
      'waterfall',
      'forest',
      'garden',
      'natural_feature',
      'lake',
      'hiking',
    ],
  ],
  [
    'activity',
    [
      'amusement_park',
      'theme_park',
      'stadium',
      'sports',
      'spa',
      'gym',
      'cinema',
      'theatre',
      'theater',
      'bowling',
      'swimming',
      'golf',
      'climbing',
      'ski',
    ],
  ],
];

/** How a trip's category of that kind is recognised: words in its name, then its icon. */
const KIND_CATEGORY: Readonly<Record<PlaceKind, { names: readonly string[]; icons: readonly string[] }>> = {
  lodging: {
    names: [
      'hotel',
      'accommodation',
      'lodging',
      'unterkunft',
      'hébergement',
      'alojamiento',
      'alloggio',
      'stay',
      'hostel',
      'camping',
    ],
    icons: ['🏨', '🛏️', '🏠', 'BedDouble', 'Home', 'Tent'],
  },
  food: {
    names: ['restaurant', 'food', 'essen', 'ristorante', 'restaurante', 'eat'],
    icons: ['🍽️', '🍴', 'UtensilsCrossed', 'Utensils'],
  },
  drinks: {
    names: ['cafe', 'café', 'bar', 'coffee', 'kaffee', 'pub', 'drinks'],
    icons: ['☕', '🍺', '🍸', 'Coffee', 'Beer', 'Wine'],
  },
  sight: {
    names: ['attraction', 'sight', 'sehenswürdigkeit', 'museum', 'attraktion', 'culture', 'kultur'],
    icons: ['🏛️', '📸', 'Landmark', 'Library', 'Camera', 'Church'],
  },
  shopping: { names: ['shopping', 'shop', 'einkauf', 'store', 'markt'], icons: ['🛍️', 'ShoppingBag', 'Store'] },
  transport: {
    names: ['transport', 'verkehr', 'transit', 'station'],
    icons: ['🚌', '🚆', '✈️', 'Bus', 'Train', 'Plane', 'BusFront', 'TrainFront', 'PlaneTakeoff'],
  },
  beach: { names: ['beach', 'strand', 'plage', 'playa', 'spiaggia'], icons: ['🏖️', 'Waves'] },
  nature: {
    names: ['nature', 'natur', 'park', 'outdoor', 'hiking', 'wandern'],
    icons: ['🌿', '🌲', '⛰️', 'TreePine', 'Leaf', 'Mountain'],
  },
  activity: {
    names: ['activity', 'aktivität', 'activité', 'actividad', 'attività', 'sport'],
    icons: ['🎯', 'Activity', 'Dumbbell', 'Ticket'],
  },
};

/** The words a result carries about itself, lower-cased, whatever the source. */
function resultTerms(result: Record<string, unknown>): string[] {
  const terms: string[] = [];
  if (Array.isArray(result.types)) {
    for (const type of result.types) if (typeof type === 'string') terms.push(type.toLowerCase());
  }
  if (typeof result.category === 'string') terms.push(result.category.toLowerCase());
  return terms;
}

export function kindOfResult(result: Record<string, unknown>): PlaceKind | null {
  const terms = resultTerms(result);
  if (terms.length === 0) return null;
  for (const [kind, words] of KIND_TERMS) {
    if (terms.some((term) => words.some((word) => term.includes(word)))) return kind;
  }
  return null;
}

/**
 * The trip category of a kind: recognised by its name, then by its icon, since
 * categories are the admin's own, freely named and freely iconed. Null when
 * nothing matches, because a wrong category that looks deliberate is worse
 * than none.
 */
export function categoryIdForKind(kind: PlaceKind | null, categories: readonly PlaceKindCategory[]): number | null {
  if (!kind) return null;
  const { names, icons } = KIND_CATEGORY[kind];
  const byName = categories.find((category) => {
    const name = (category.name || '').toLowerCase();
    return names.some((word) => name.includes(word));
  });
  if (byName) return byName.id;
  const byIcon = categories.find((category) => category.icon != null && icons.includes(category.icon));
  return byIcon ? byIcon.id : null;
}

/**
 * Narrower categories a trip may keep beside the broad kinds: a resupply stop on a
 * hike is filed under its own category when the admin made one, and under the
 * broad kind's (Bar/Cafe, Shopping) otherwise. Matched like KIND_CATEGORY.
 */
const SPECIFIC_CATEGORIES: ReadonlyArray<{
  terms: readonly string[];
  names: readonly string[];
  icons: readonly string[];
}> = [
  {
    terms: ['bakery'],
    names: ['bakery', 'bäckerei', 'boulangerie', 'panadería', 'panaderia', 'panetteria', 'bakkerij'],
    icons: ['🥖', '🥐', '🍞', 'Croissant'],
  },
  {
    terms: ['supermarket', 'convenience', 'grocery', 'greengrocer'],
    names: [
      'grocer',
      'supermarket',
      'lebensmittel',
      'supermarkt',
      'épicerie',
      'epicerie',
      'supermarché',
      'supermercado',
      'alimentación',
      'alimentari',
      'supermercato',
    ],
    icons: ['🛒', '🧺', 'ShoppingBasket', 'ShoppingCart'],
  },
];

function specificCategoryId(result: Record<string, unknown>, categories: readonly PlaceKindCategory[]): number | null {
  const terms = resultTerms(result);
  for (const { terms: words, names, icons } of SPECIFIC_CATEGORIES) {
    if (!terms.some((term) => words.some((word) => term.includes(word)))) continue;
    const byName = categories.find((category) => {
      const name = (category.name || '').toLowerCase();
      return names.some((word) => name.includes(word));
    });
    if (byName) return byName.id;
    const byIcon = categories.find((category) => category.icon != null && icons.includes(category.icon));
    if (byIcon) return byIcon.id;
  }
  return null;
}

/** The trip category a picked search result most likely belongs in (#2282), or null. */
export function guessCategoryId(
  result: Record<string, unknown>,
  categories: readonly PlaceKindCategory[],
): number | null {
  return specificCategoryId(result, categories) ?? categoryIdForKind(kindOfResult(result), categories);
}