Locations, facilities & aids

Navigation Aid Picker

A searchable field for choosing a navigation aid, such as a lighthouse or a buoy, built on shadcn/ui and the waykite API.

value = null

Type part of an aid's name to search; the button beside the field narrows the search to one country, and lists that country's aids before anything is typed. Many aids share names like "Channel Buoy 3", so each suggestion shows its kind, its international number and light where it has them, and its nearest port. The value is the aid's id, such as 'aid_0c1c9b4c42a7ee54fe722dd8'. Picking the selected aid again clears the field.

Installation

npx shadcn@latest add https://waykite.com/shadcn/r/waykite-navigation-aid-picker.json

The CLI installs the shadcn/ui components the picker uses, the country combobox, country flag, countries, useDebounce, useWaykite and WaykiteClient it builds on, and its npm packages. The picker gets its data from the WaykiteProvider above it: the waykite API with your publishable key, or another source with navigation.

Copying the files yourself

Add the country combobox (with the country flag and countries), useDebounce and useWaykite (with WaykiteClient) first, then:

npx shadcn@latest add button button-group combobox input-group spinner
npm install cn

Then copy this file:

'use client'
import { cn } from 'cn';import * as React from 'react';
import { CountryCombobox, type CountryControl } from '@/components/ui/country-combobox';import { CountryFlag } from '@/components/ui/country-flag';import { Button } from '@/components/ui/button';import { ButtonGroup } from '@/components/ui/button-group';import {  Combobox,  ComboboxContent,  ComboboxEmpty,  ComboboxInput,  ComboboxItem,  ComboboxList,  ComboboxTrigger,  ComboboxValue,} from '@/components/ui/combobox';import { InputGroupAddon } from '@/components/ui/input-group';import { Spinner } from '@/components/ui/spinner';import { useDebounce } from '@/hooks/use-debounce';import { useWaykiteNavigationAid, useWaykiteNavigationAidSearch } from '@/hooks/use-waykite';import { getCountry } from '@/lib/countries';import {  WAYKITE_NAVIGATION_AID_KIND_LABELS,  type WaykiteNavigationAid,  type WaykiteNavigationAidKind,} from '@/lib/waykite-client';
export interface WaykiteNavigationAidPickerProps {  /** Put on the field's button, for a `<label htmlFor>`. */  'id'?: string;
  /** The selected aid's id, e.g. `'aid_0c1c9b4c42a7ee54fe722dd8'`. */  'value'?: string | null;
  /** Called with the selected aid's id and the aid itself, or `null` for both when cleared. */  'onValueChange'?: (value: string | null, aid: WaykiteNavigationAid | null) => void;
  /** Shown while nothing is selected. */  'placeholder'?: string;
  /**   * Names the field and its country filter together, for screen readers.   * @default 'Navigation aid'   */  'aria-label'?: string;
  /**   * Shown in the search box, and in the list until something is typed.   * @default 'Type to search navigation aids...'   */  'searchPlaceholder'?: string;
  /**   * Shown when nothing matches the search.   * @default 'No navigation aids found.'   */  'emptyText'?: string;
  /**   * Shown in the list while the first search runs, before there are results to show.   * @default 'Searching...'   */  'searchingText'?: string;
  /**   * Only suggest aids in these countries (ISO 3166-1 alpha-2), e.g. `['NL']`: a country's aids show before anything   * is typed.   */  'countries'?: string[];
  /** Only suggest aids of these kinds, e.g. `['light']`. */  'kinds'?: WaykiteNavigationAidKind[];
  /** Marks the field invalid, e.g. from a form's validation, and styles it so. */  'aria-invalid'?: boolean;
  'disabled'?: boolean;  'className'?: string;
  /**   * The country filter beside the search: `CountryCombobox` (the default), `CountrySelect`, or an app's own.   * @default CountryCombobox   */  'countryComponent'?: CountryControl;}
/** A searchable field for choosing a navigation aid, such as a lighthouse or a buoy, from waykite, with a country filter. */export function WaykiteNavigationAidPicker({  id,  value,  onValueChange,  placeholder = 'Search navigation aids...',  countries,  kinds,  'aria-label': ariaLabel = 'Navigation aid',  searchPlaceholder = 'Type to search navigation aids...',  emptyText = 'No navigation aids found.',  searchingText = 'Searching...',  'aria-invalid': ariaInvalid,  disabled,  className,  'countryComponent': Country = CountryCombobox,}: WaykiteNavigationAidPickerProps) {  // The field as a whole: both popups, the search's and the country filter's, line up with it.  const group = React.useRef<HTMLDivElement>(null);  const [open, setOpen] = React.useState(false);  // As in the location picker, the country narrows the search and is not part of the value.  const [country, setCountry] = React.useState<string | null>(null);  const [query, setQuery] = React.useState('');  const debouncedQuery = useDebounce(query, 300);  const inCountries = country ? [country] : countries;
  const { results, isLoading, isValidating } = useWaykiteNavigationAidSearch({    query: debouncedQuery,    countries: inCountries,    kinds,    // Without a query or a country, every aid in the world would be listed.    enabled: open && (!!debouncedQuery || !!inCountries?.length),    limit: 20,  });
  // A value set from outside is not among the results until it is searched for: it is looked up on its own.  const saved = useWaykiteNavigationAid(value);  const selected = value ? (results.find((r) => r.id === value) ?? saved.data) : null;
  return (    <div className={cn('flex flex-col gap-1.5', className)}>      <ButtonGroup ref={group} aria-label={ariaLabel} className='w-full'>        <Country          value={country}          countries={countries}          onValueChange={(value) => setCountry((value && getCountry(value)?.iso2) || null)}          variant='flag'          anchor={group}          disabled={disabled}          allowClear        />
        <Combobox<WaykiteNavigationAid>          items={results}          itemToStringValue={(aid) => aid.id}          // The API has matched the query already; filtering its results again here would hide some of them.          filter={null}          value={selected}          open={open}          disabled={disabled}          onOpenChange={(nextOpen) => {            setOpen(nextOpen);            if (!nextOpen) setQuery('');          }}          onValueChange={(aid) => {            // Picking the selected aid again clears the field.            const next = aid && aid.id !== value ? aid : null;            onValueChange?.(next?.id ?? null, next);            setOpen(false);            setQuery('');          }}        >          <ComboboxTrigger            id={id}            aria-invalid={ariaInvalid}            render={<Button variant='outline' />}            className='min-w-0 flex-1 justify-between'          >            <ComboboxValue placeholder={placeholder}>              {value ? (                <span className='truncate'>{selected?.name ?? value}</span>              ) : (                <span className='text-muted-foreground'>{placeholder}</span>              )}            </ComboboxValue>          </ComboboxTrigger>          <ComboboxContent anchor={group} className='p-0'>            <ComboboxInput              value={query}              onChange={(e) => setQuery(e.target.value)}              placeholder={searchPlaceholder}              showTrigger={false}              showClear            >              {/* The previous results stay listed while a new search runs, so this is the sign that it does. */}              {isValidating && (                <InputGroupAddon align='inline-end'>                  <Spinner />                </InputGroupAddon>              )}            </ComboboxInput>            <ComboboxEmpty>{isLoading ? searchingText : query ? emptyText : searchPlaceholder}</ComboboxEmpty>            <ComboboxList>              {(aid: WaykiteNavigationAid) => (                <ComboboxItem key={aid.id} value={aid}>                  <CountryFlag countryCode={aid.country} className='size-4' shape='circle' />                  <span className='flex min-w-0 flex-col'>                    <span className='truncate'>{aid.name}</span>                    <span className='truncate text-xs text-muted-foreground'>                      {[WAYKITE_NAVIGATION_AID_KIND_LABELS[aid.kind], aid.international_number, aid.characteristics[0]]                        .filter(Boolean)                        .join(' · ')}                    </span>                  </span>                  <span className='ml-auto font-mono text-xs text-muted-foreground'>{aid.nearest_port.unlocode}</span>                </ComboboxItem>              )}            </ComboboxList>          </ComboboxContent>        </Combobox>      </ButtonGroup>    </div>  );}
/** * A navigation aid's id as its name, e.g. "Raffles (light)", for showing a saved id outside a form. Shows the id while * the name loads, and on its own when the aid is unknown. */export function WaykiteNavigationAidView({ id }: { id: string | null | undefined }) {  const aid = useWaykiteNavigationAid(id);  if (!id) return <>—</>;  if (aid.isLoading) {    return (      <span className='inline-flex items-center gap-1.5'>        {id}        <Spinner className='size-3' />      </span>    );  }  if (!aid.data) return <>{id}</>;  return (    <>      {aid.data.name} ({WAYKITE_NAVIGATION_AID_KIND_LABELS[aid.data.kind].toLowerCase()})    </>  );}

Usage

import * as React from 'react';

import { WaykiteNavigationAidPicker } from '@/components/ui/waykite-navigation-aid-picker';

export function ReportingPointField() {
  const [aid, setAid] = React.useState<string | null>(null);

  return <WaykiteNavigationAidPicker value={aid} onValueChange={setAid} placeholder='Select aid...' />;
}

Examples

Lights in one country

countries keeps the suggestions to some countries, and lists their aids as soon as the field opens; kinds keeps them to some kinds of aid:

value = null

With a value

value = "aid_0c1c9b4c42a7ee54fe722dd8"

Disabled

value = "aid_0c1c9b4c42a7ee54fe722dd8"

Showing a saved aid

WaykiteNavigationAidView, in the same file, shows a saved aid by its name and kind, such as "Raffles (light)". It shows the id while the name loads, and on its own for an aid it cannot find:

ReportReporting point
RP-0211aid_0c1c9b4c42a7ee54fe722dd8
RP-0212aid_xxxxxxxxxxxxxxxxxxxxxxxx

API reference

PropTypeDescription
valuestring | nullThe selected aid's id.
onValueChange(value: string | null, aid: WaykiteNavigationAid | null) => voidCalled with the aid's id and the full aid, or null for both when cleared.
countriesstring[]Only suggest aids in these countries (ISO 3166-1 alpha-2); their aids show before anything is typed.
kindsWaykiteNavigationAidKind[]Only suggest aids of these kinds, such as light, buoy, radio_beacon or drilling_unit.
placeholderstringShown while nothing is selected.
searchPlaceholderstringShown in the search box, and in the list until something is typed. Defaults to Type to search navigation aids....
emptyTextstringShown when nothing matches the search. Defaults to No navigation aids found.
searchingTextstringShown in the list while the first search runs. Defaults to Searching....
aria-labelstringNames the field and its country filter together, for screen readers. Defaults to Navigation aid.
idstringPut on the field's button, for a <label htmlFor>.
aria-invalidbooleanMarks the field invalid and styles it so, from your form's validation state.
disabledbooleanStops the field, and its country filter, from being changed.
countryComponentCountryControlThe country filter's control. Defaults to CountryCombobox; CountrySelect fits too.
classNamestringClasses for the outer element.

On this page