Skip to main content

Ports (part 2 of 2)

Part of Architecture, which is built from ARCHITECTURE.md in the repository, where it is edited.

Announcement flow. A hook or component calls announce(message, { priority, keep }) with a Message (or plain text, for copy not yet moved). LiveRegionProvider formats a Message with the active catalogue just before it hands the text to the announcer, so the throttle, the de-duplication and keep act on the words that will be spoken, and one outcome is still spoken once. A component that shows one of these messages formats it with useFormatMessage(). A hook that keeps a message of its own to avoid saying it twice (the search box) compares the message by key and parameters.

The layer catalogue. LayerCatalogue (packages/core/src/ports/layers.ts) is a port, unlike the plain-data BasemapCatalogue described below: its state changes while the app runs, so it has getState(), subscribe(listener) and refresh(), and it has three implementations (static, runtime and the fake) that share one contract suite, contracts/layerCatalogue.contract.ts. The state is loading, failed (network or invalid) or ready; ready carries the layers, the definitions that were skipped with their problems, and a refresh state (idle, loading or failed). A catalogue with no layers is ready with none, and a failed refresh keeps the last list. getState() returns the same object until something changes and is also the server snapshot, so useDataLayers reads the catalogue with useSyncExternalStore, and no method uses this, so getState and subscribe can be passed on alone. refresh() never rejects: a failure is the state.

  • createStaticLayerCatalogue(definitions, options) is ready from the first read, on the server too, never changes, and still throws at start-up on any invalid definition or duplicate id, which suits definitions in the build.
  • createRuntimeLayerCatalogue({ load, options, onSkipped }) takes the host's load(signal), so the host owns the endpoint and any credentials and the SDK fetches nothing. It is loading when built and on the server. It calls load on the first subscription (or the first refresh()) and only once for that, so React's StrictMode, which subscribes, unsubscribes and subscribes again, makes one request. One request is in flight at a time, and a second refresh() gets the pending promise. The signal is aborted only by dispose(), which is for the host's teardown, and a result that arrives after it is ignored. It loads again only when the host calls refresh(); it has no timer.
  • partitionDefinitions(raw, options, previous) is how the runtime catalogue keeps one bad definition from costing the list. It validates each value with validateLayerDefinition, skips a non-object (with no id) and a definition whose id an earlier valid one already has (the first wins), and does not throw whatever an entry holds: an entry that cannot be read at all is skipped with the problem definition: could not be read. A definition that is deeply equal to the previous one with the same id keeps the previous object, and an unchanged list keeps the previous array, so a refresh that changes nothing changes no reference. The comparison follows at most MAX_JSON_DEPTH (100) levels and counts anything deeper as changed. The runtime catalogue also treats a payload that cannot be read as invalid, so a server cannot make refresh() reject or leave the state loading.

The Layers section shows the layers of a ready catalogue and says what the catalogue is doing besides holding layers. useDataLayers returns catalogue (the status, the skipped count, the refresh state, and awaited, which is true when the catalogue was not ready at mount) and retryCatalogue(), which calls refresh() only after a failed load or a failed refresh. While the catalogue is loading the section says "Loading layers" and is aria-busy, and a runtime catalogue renders that on the server too. After a failed load it says "Layers could not be loaded." with a Try again button. A ready list with no layers says "No layers are available." only when awaited: a host whose first state was ready and empty has no Layers section. Skipped definitions read "1 layer could not be shown" or "3 layers could not be shown". A failed refresh keeps the last list and says "Layers could not be updated. Showing the last list." with Try again, which is not said while the section is hidden. There is no general refresh button, and a refresh the host starts shows nothing while it loads. Try again stays in place, busy, while it retries, so focus stays on it; when the catalogue recovers and the button has gone, focus moves to the section heading if the button had focus or had just been pressed, and the person has not moved it elsewhere. A retry is one that has been seen loading and has stopped, so a catalogue that publishes loading after refresh() returns is handled too. The line above the layers is the intro prop of LayersSection and SheetContent, which defaults to "Open data from public providers. Nothing is requested until you turn a layer on." and which a host behind a login replaces. What each transition says aloud is under "Data layers". The status lines are plain text, not a live region (packages/map/src/layers/CatalogueStatus.tsx). The reference site uses the static catalogue, which is ready on the first render, so it shows none of these states.

BasemapDefinition is a typed data module, not a port. It is the only place that names a tile source or an attribution string. A raster source is a tile URL template and a tile size, a vector source is a style URL, and a hybrid source is image tiles (a tile URL template, a tile size and maxTileZoom, the deepest level with real detail) under the line and symbol layers of a label style (labelStyleUrl) that draw from the source layers it names (labelSourceLayers), less any layer it names to leave out (labelOmitLayers, such as ferry routes). A definition may set nonCommercial when its provider's licence allows only non-commercial use; the SDK's own list holds none, which a test in core checks, together with an allow-list of the SDK's source origins. The default basemap follows the theme until a visitor chooses one: DEFAULT_BASEMAP_ID (Bright) in the light theme and DEFAULT_DARK_BASEMAP_ID (Fiord) in the dark theme. Settings.basemapId is null until a person picks a basemap, so a stored id, even the default's, is a choice that stays across theme changes and reloads, and a visitor with null follows the theme live. An id that names no basemap (a removed one, or the "auto" of earlier versions) counts as no choice. DEFAULT_BASEMAP_BACKGROUND and DEFAULT_DARK_BASEMAP_BACKGROUND are the land colours of the two defaults; the mapBackground token carries the same value for each theme (a test in packages/web keeps them equal), so the server-rendered placeholder and the map host match the default before it draws. A shared link names the basemap that was showing, whatever its theme, and a link without one shows the viewer's default; the address codec is unchanged, because it already wrote the basemap id whenever the view settled or a basemap changed. The reference host offers six of the SDK's seven basemaps and none of its own (see below), so there a saved or linked colorful opens on the default. The placeholder also holds the decorative ChromeSkeleton, so the chrome is in its final place on the first paint.

Host-supplied basemaps. The SDK ships only the built-in basemaps (BASEMAPS). A host that wants another builds a BasemapCatalogue with createBasemapCatalogue(basemaps, defaultId, themeDefaultIds) and passes it as the optional Services.basemaps; without it the ui offers the built-in catalogue (BUILT_IN_BASEMAP_CATALOGUE, Bright the default in the light theme and Fiord in the dark theme). themeDefaultIds ({ light, dark }, each optional) names the basemap to show in a theme when nothing is chosen, and a theme left out uses defaultId; the host decides the pairing, the SDK only reads it through defaultBasemapFor(catalogue, theme) and resolveBasemapFor(catalogue, id, theme). The catalogue is plain data with get(id) and resolve(id), not a port: it has one shape and no second implementation, so it has no fake and no contract suite, and portRegistry lists it under DATA_SERVICE_NAMES beside the ports. The picker (BasemapPicker), the saved-or-linked choice (useBasemapChoice) and the default all read it through useBasemaps(), and an id the catalogue does not hold, such as the retired "maptoolkit-dark", resolves to its default (resolveBasemapFor gives the theme's default). A provider whose licence the host accepts, and that the reusable SDK packages must not carry, is defined in the host and added to a catalogue the host builds. The reference host defines none today, and it does not offer the whole built-in list either: packages/web/src/basemaps/hostBasemaps.ts builds the host's catalogue from a subset of BASEMAPS with getBasemap and createBasemapCatalogue (copies of the SDK's definitions, with the host's preview path added), and createServices() passes it. It holds Bright, Liberty, Positron, Streets, Fiord and Dark, in that order, with Bright the default in the light theme and Fiord (appearance: "dark") the default in the dark theme. Topographic and Satellite were removed from it: Topographic because its provider is a volunteer-run project with no availability guarantee, and Satellite because its imagery is licensed for non-commercial use only, which neither the reference host nor the SDK carries. The six ask for no more than their credit text. Colorful stays in the SDK for other hosts, and the site makes no request to the VersaTiles server that Colorful uses. A saved or linked id the catalogue does not hold, such as colorful or the retired maptoolkit-dark, shows the default for the viewer's theme. The WebMCP set-map-basemap tool offers the basemaps of the host's catalogue (useBasemaps()), so it never offers one the picker does not show; a basemap marked nonCommercial is left out (basemapChoices), because an agent should not accept a provider's licence on a person's behalf, so the tool offers all six of the reference host's basemaps, and the filter stays for a host that defines a non-commercial one. In the e2e build only, the browser test seam can replace the catalogue, so a spec can run on a host that offers the SDK's whole list.

A definition's thumbnail is optional, and it is a root-relative path the host serves; if the image fails to load, the picker shows the swatch. A basemap without one shows the picker's plain swatch, because only a host that serves the files, and has the right to them, can offer a preview; so does a tile whose image fails to load. The SDK's own definitions name no preview, so a host that serves none (the example app, say) shows a swatch for every SDK basemap and never requests an image, and a test in core and one in map check both. The reference host adds its previews as data: BASEMAP_THUMBNAILS in packages/web/src/basemaps/basemapThumbnails.ts maps each basemap it offers to a file in packages/web/public/basemaps, hostBasemaps.ts sets thumbnail on a copy of each definition it offers, and a test in packages/web checks that every basemap the host offers has its file. The thumbnail script reads the same table. A host that wants another place for its files only changes the paths in its own table, so the SDK carries no base URL.

RoutingProvider, FileOpener, SuggestionProvider, FeatureSelection and FeatureQuery are the optional services: Services.routing, Services.fileOpener, Services.suggestions, Services.selection and Services.featureQuery may be absent, and the ui must work without them. Without a file opener the Shapes section has no Import control. route({ stops, mode, signal }) returns one GeoJSON line feature for each leg with its distance (metres) and duration (seconds), and reachableArea({ origin, minutes, mode, signal }) returns polygon features. Both reject only with a typed RoutingError (network, invalid, no-route, rate-limited, aborted, unsupported).

The reference host's ValhallaRoutingProvider (packages/web/src/adapters/routing) calls a public Valhalla server with GET /route and GET /isochrone, decodes the encoded polyline shape itself, maps HTTP and network failures to those kinds, starts at most one request a second through the shared RequestSpacer, and sends no cookies. It sends the site's origin, and nothing more, as the referrer (referrerPolicy: "strict-origin"), because the public server's terms ask for one. It reads an answer, and an error body, at most maxResponseBytes (2 MiB by default; the recorded answers in its fixtures are under a kilobyte) through the shared readJsonWithin, and an answer over the limit is invalid, the same error kind as a body that is not what the service documents. A route request asks for directions_type: "none", because the adapter reads only each leg's shape and summary, which keeps the answer small. The routing contract suite requires it: RoutingProviderControls has a required respondWithOversizeAnswer(), and the suite requires a route and an area over the limit to fail as invalid. packages/map holds only the generic Directions tool (tools/Directions): useDirections keeps the stops, mode and result and cancels superseded requests, DirectionsPanel is the interface, MapDirections draws the result through setShapeLayer and fits the map clear of the sheet, and DirectionsOverlay draws the lettered stops. None of them names a provider; the host passes the credit and the privacy note, and mounts the button only when services.routing exists.

Search suggestions. Services.suggestions is an optional SuggestionProvider (suggest(query, { limit, signal }), resolving SearchResults, so a suggestion carries its centre and optional extent and picking one needs no second lookup). It is a port of its own, apart from SearchProvider, because the two services have different terms: Nominatim's usage policy forbids a request on every keystroke, and a service built for typing makes different promises. A host without it keeps submit-only search; nothing else changes. The adapter rejects only with SearchError (offline, rate-limited, failed, where a timeout is failed) or PortAbortError. The reference host's PhotonSuggestionProvider (packages/web/src/adapters/search) calls GET /api/?q&limit&lang=en on the public Photon server (run by komoot on OpenStreetMap data), reads its GeoJSON (the centre is longitude then latitude, the extent west, north, east, south), starts at most one request every 250 ms through RequestSpacer, fails a request after four seconds, reads at most maxResponseBytes of an answer (256 KiB by default, through the shared readJsonWithin; an answer over it is failed), and sends no position, no cookies and no referrer. Everything that decides when to ask lives in one hook, useSuggestions in packages/map/src/tools/SearchPill: it waits for a pause in typing (SUGGEST_DEBOUNCE_MS, 275 ms), asks only for at least MIN_SUGGEST_LENGTH (3) characters that include a word of three or more letters, so a coordinate pair is never sent, not even while it is being typed, aborts the request before it whenever the text changes so an older answer is never shown, and announces the count politely. After SUGGEST_FAILURE_LIMIT (3) failures in a row, or one rate-limited answer, it stops asking for SUGGEST_COOLDOWN_MS (60 s) and announces once that suggestions are unavailable and Enter still searches. SearchPill shows the suggestions in its one listbox (named "Suggestions" until a search is submitted, then "Search results"), so a suggestion is an option exactly like a result, picked by the same keys and taps, and Enter with none highlighted still submits to Nominatim. The public Photon server states only that clients should be fair and gives no terms for commercial use, so a commercial host runs its own Photon server and passes it as the adapter's endpoint (see sites/docs/docs/guides/extending.md).

The other copy that names a provider works the same way. The Settings privacy statement (privacyNote on SheetContent and SettingsSection) and the note under the pin card's "Look up address" (lookupNote on PinCard) are props that take text or nodes, and each has a neutral default that names no provider. The reference host supplies its own as the catalogue keys host.notes.privacy, host.notes.pinLookup and host.notes.routing, in English and Afrikaans, so its visible text says what the privacy page and PRIVACY.md describe (src/i18n/hostNotes.test.tsx checks the facts they share), and an embedding host writes its own.

Pure helpers (layer templates, decoders and style evaluation, zoom conversion, metres per pixel, the surface state machine, sheet snapping, coordinate formatting, announcement messages, theme resolution, hash parsing) are plain functions in core. They are not wrapped in interfaces.

The feature selection. FeatureSelection (packages/core/src/ports/selection.ts) is the set of features a person has picked. Each FeatureRef is a layer id and a feature id, the pair a tap reports (MapFeatureHit). The store is synchronous (getState(), subscribe(listener), add, remove, replace, clear and a limit), because useSyncExternalStore needs a snapshot of stable identity, so it has no loading or failed state. A host that saves the set somewhere slow keeps a local copy, writes behind it, and calls its subscribers when the copy changes, when it hydrates or when it restores the copy after a failed save. The rules for every implementation are in contracts/featureSelection.contract.ts:

  • getState() returns the same array until a change, in selection order, and getState and subscribe work when taken off the object.
  • A duplicate is ignored, and a call that changes the set tells every subscriber once, while a call that changes nothing tells none.
  • A call that would take the total past limit changes nothing, so a batch is refused whole, as a shape file that would take the drawing past MAX_DRAWING_SHAPES is. The refusal is silent and the methods return nothing, so a caller compares getState() before and after to tell it from a batch of duplicates.
  • A store that hydrates with more than limit references shows them all and refuses every addition. Removing is always allowed.

MemoryFeatureSelection is the one class the SDK ships, as MemorySettingsStore is for settings: it is the store and its fake. Its limit defaults to DEFAULT_SELECTION_LIMIT (200), and replaceExternally(refs) scripts a change from outside, such as hydration or a failed save. Services.selection is optional and createServices() builds none (HOST_SUPPLIED_PORT_NAMES in contracts/portRegistry.ts), so the reference site offers no selection and a host that wants it supplies a store. featureRefKey(ref) (ports/selection.ts) is the one key for a set or map of references, which the memory store and the ui both use, so they cannot disagree on which references are the same. useSelectionStore() returns it. useFeatureSelection reads it for the ui (see "Data layers"), and the reference host and the example app call that hook. The highlights, the panel and select mode are planned in docs/plans/0007-multi-feature-selection.md and are not built. The set is not written to the permalink.

The feature query. FeatureQuery (packages/core/src/ports/featureQuery.ts) answers "which features lie inside this area", so the synchronous selection store never waits on it. within({ area, layerIds, limit, signal }) resolves SelectionHits, each a layer id and the LayerFeature itself, so the caller can show it without loading its layer. The area is a QueryArea polygon, and the polygon shapeGeometry gives for a drawn polygon or circle passes as it is. A caller that has room for n more asks for a limit of n + 1, so a result of that size tells it that more lie inside, and the host can stop looking once it has them. The rules for every implementation are in contracts/featureQuery.contract.ts: hits only from the layers named, a feature once, exactly limit hits when at least that many lie inside, no hits for no layers, and a rejection only with a typed FeatureQueryError (network, invalid, unsupported, aborted). invalid covers a limit that is not a whole number of at least 1 and an area that is not a polygon with at least one closed ring on the globe. The port does not check that a hole lies inside the outer ring, that no edge crosses another or how large a ring is, so a host guards against a very large ring itself. Services.featureQuery is optional and createServices() builds none (HOST_SUPPLIED_PORT_NAMES): the SDK ships no query and sends nothing itself, so a host whose query sends a shape to a server tells its visitors. FakeFeatureQuery is scripted with respondWith, failWith and hold, and useFeatureQuery() returns the port. Nothing in the ui reads it yet: the Shapes section's action to select the features inside a shape is planned in the same plan and is not built.