# JavaScript API

MaplibreX's components create MapLibre maps in the browser and keep
sources, layers, markers and controls on them. Your own JavaScript can work
with those maps too: listen to MapLibre events, set feature state, drive a
map from a client-side store. This guide lists what the `maplibrex` package
exports for that, and the rules for touching what the components manage.

## What is public

These exports of `maplibrex` are public, and covered by the version number
as the components are: a change that breaks one of them is a breaking
change, listed under "Breaking" in the changelog (while MaplibreX is below
1.0, in a new minor version).

* `MapHooks`, also the default export: the hooks to give `LiveSocket` (see
  the README).
* `MapManager`, the registry of the maps on the page, with its methods
  `whenReady`, `whenNextRegistered`, `get` and `isRegistered`.
* `useMap`, `requireMap` and `followMap`.
* For TypeScript, the types of their callbacks: `MapReadyCallback`,
  `MapAttach` and `MapDetach`.
* For tests of application code only, three more methods of `MapManager`:
  `register`, `unregister` and `clear`; see
  [Methods for tests](#methods-for-tests).
* `maplibrex/map-manager`, which exports the same `MapManager`, `useMap`,
  `requireMap` and `followMap`, and their types, and nothing else: no
  hooks, and so no maplibre-gl. Code that imports them from there loads in
  Node; see [Testing code that follows a map](#testing-code-that-follows-a-map).
* `maplibrex/draw`, which exports `DrawHooks`, and nothing else: the hook
  of `<.draw>`, `DrawHook`, to give `LiveSocket` next to `MapHooks` (see the
  README). It is apart from `MapHooks` because it imports Terra Draw, which
  only an application that draws installs.

The rest of what the package exports is internal; see
[Internal exports](#internal-exports).

Import them from the same `maplibrex` as `MapHooks`:

```javascript
import { MapManager, followMap, useMap, requireMap } from "maplibrex"
```

There is one registry of maps on the page, the one the hooks register
them in: `maplibrex`, `maplibrex/map-manager` and `maplibrex/draw` keep
their maps in it, and so does a second copy of the same version of
MaplibreX, imported by another path. The same holds for the style changes
the map hook makes, which the drawing of `maplibrex/draw` waits for, and
for the cursor over a map's canvas, which its layers and drawings share.

The signatures below are TypeScript, with MapLibre's map type:
`import type { Map } from "maplibre-gl"`.

## The maps on the page

The map hook registers each map under the `id` of its `<.map>` as soon as
MapLibre creates it, before its style has loaded, and unregisters it just
before it removes it, when its element goes. Code given a map can listen to
its events at once; MapLibre refuses changes to the style (a source or a
layer added, feature state set) until the style has loaded.

A `<.map>` can be rendered again under the same id: behind `:if`, say, or
by a patch that replaces its element. That makes a new map: the old one is
removed, with every listener, source and layer on it, and the new one is
registered under the same id. `followMap` follows the map from one to the
next; the other functions deal with one map.

### `MapManager.whenReady(mapId, callback)`

```typescript
whenReady(mapId: string, callback: (map: Map) => void): () => void
```

Calls `callback` with the map registered under `mapId`: right away, before
`whenReady` returns, if there is one, and otherwise once one is registered.
It is called at most once, and only for a map registered under `mapId`:
other maps coming and going leave it waiting. If no such map ever comes, it
is never called, and waits until the function `whenReady` returns cancels
it (that function does nothing once the callback has run). A callback that
throws is logged in the console and does not stop the others.

```javascript
import { MapManager } from "maplibrex"

// Runs now if the map is registered, or once it is.
const cancel = MapManager.whenReady("map", map => {
  map.on("moveend", onMove)
})
```

It runs once: a map rendered again under the same id does not call it
again. `followMap` does.

### `MapManager.whenNextRegistered(mapId, callback)`

```typescript
whenNextRegistered(mapId: string, callback: (map: Map) => void): () => void
```

As `whenReady`, except that it always waits for the next map registered
under `mapId`, even when one is registered now.

### `MapManager.get(mapId)`

```typescript
get(mapId: string): Map | undefined
```

The map registered under `mapId` now, or `undefined`. It logs nothing
either way, so it is the way to ask whether a map exists:
`MapManager.get(mapId) !== undefined`. Code that needs the map and has
none uses `requireMap`, which complains; code that can wait for it uses
`whenReady` or `followMap`.

### `MapManager.isRegistered(mapId, map)`

```typescript
isRegistered(mapId: string, map: Map): boolean
```

Whether `map` is the map registered under `mapId` now: false once it has
been unregistered, or another map has been registered in its place.

### `useMap(mapId)`

```typescript
useMap(mapId: string): Map | undefined
```

The same as `MapManager.get(mapId)`.

### `requireMap(mapId)`

```typescript
requireMap(mapId: string): Map
```

The map registered under `mapId`. With none, it warns in the console, then
throws an `Error`; both name `mapId`.

### `followMap(mapId, attach)`

```typescript
followMap(mapId: string, attach: (map: Map) => (mapRemoved: boolean) => void): () => void
```

Follows the map registered under `mapId`, from one map to the next. It
calls `attach` with the map as soon as there is one, right away if there
is. `attach` returns a cleanup function. When the map is removed (its
`remove` event), `followMap` calls the cleanup with `true`, then `attach`
again with the map registered under `mapId` in its place: the one already
registered, when a patch replaced the map's element, or else the next one
registered.

With `true`, the map is gone, and the listeners on it with it: there is
nothing to undo on it. The cleanup is called before any `remove` listener
that `attach` added to the map.

The function `followMap` returns stops following. With a map attached, it
calls the cleanup with `false`: the map stays, and the cleanup undoes what
`attach` did to it. Otherwise it stops waiting. Calling it again does
nothing.

An `attach` that throws is logged in the console, and the next map is
followed all the same. A cleanup that throws when its map is removed is
logged and does not stop the map's other `remove` listeners; one that
throws when the function `followMap` returned calls it throws from that
function.

```javascript
import { followMap } from "maplibrex"

const stop = followMap("map", map => {
  map.on("click", onClick)
  // true: the map was removed, listeners and all; false: stop() was called.
  return mapRemoved => {
    if (!mapRemoved) map.off("click", onClick)
  }
})
```

The types `MapAttach` and `MapDetach` name `attach` and its cleanup, and
`MapReadyCallback` the callback of `whenReady` and `whenNextRegistered`.

## What the components own

Each component keeps these on the map registered under its `map_id`;
`<id>` is the component's `id`:

| Component | On the map |
| --- | --- |
| `map` | the map, registered under `<id>` |
| `geojson_layer` | a GeoJSON source `<id>-source`, and a layer `<id>` that draws it |
| `trail` | a GeoJSON source `<id>-source`, and a line layer `<id>` that draws it |
| `circle_layer`, `line_layer`, `fill_layer`, `symbol_layer`, `heatmap_layer`, `fill_extrusion_layer`, `hillshade_layer`, `raster_layer` | a layer `<id>`, which draws the source `source_id` (not its own) |
| `background_layer` | a layer `<id>` |
| `vector_tile_source`, `raster_tile_source`, `raster_dem_source`, `image_source`, `video_source` | a source `<id>` |
| `custom_layer`, `flow_layer` | a custom layer `<id>` |
| `image` | an image `<id>` (`map.addImage`), which symbol layers name in `icon-image`: no source or layer |
| `deckgl_layer` | a deck.gl layer `<id>`, in a deck.gl overlay that the map's `deckgl_layer`s share; deck.gl adds MapLibre layers of its own for it, under ids of its own |
| `draw` | Terra Draw's GeoJSON sources `<id>-polygon`, `<id>-linestring` and `<id>-point`, and its layers `<id>-polygon`, `<id>-polygon-outline`, `<id>-linestring`, `<id>-point` and `<id>-point-marker`, which draw them |
| `terrain` | the map's terrain, from the source `source_id`: no source or layer |
| `sky` | the map's sky: no source or layer |
| `marker`, `popup` | a MapLibre `Marker` or `Popup`: no source or layer |
| the control components | a control: no source or layer |
| `zoom_range` | nothing: it listens to the map's zoom |

A component whose layer, source or image id is already on the map, from the
map's style or from your code, takes that layer, source or image over: it
changes it, and leaves it on the map when it goes.

## Working with what the components manage

### Paint, layout, filter and data

A component applies its attributes. It changes a property of its layer when
the rendered value of that property changes (to MapLibre's default when
the attribute leaves it out), and `geojson_layer` gives its source new data
when `data` changes (only what changed, when its features have ids: see
"Updating part of the data" in `MaplibreX.Components.GeoJSONLayer`). After a style change, and on a map rendered again
under its id, it puts its layer and source back from its attributes (and,
for `geojson_layer`, from the commands it was given).

So a value your code sets on a component's layer or source, with
`setPaintProperty`, `setLayoutProperty`, `setFilter` or `setData`, lasts
until the next render that changes that property, or the next style
change. Data your code gives a `geojson_layer`'s source (`setData` or
`updateData`) leaves the layer not knowing what the source holds, so its
next new data goes whole, not as a difference. A change that has to last belongs in the attributes, or, for
`geojson_layer`, in its commands (see `MaplibreX.Components.GeoJSONLayer`),
which your JavaScript can dispatch too, and which last through style
changes. To take a component's layer or source off the map, remove the
component.

### Feature state

Feature state is your application's: no component sets it, and none puts
it back. MapLibre keeps it with the source. New data, which `geojson_layer`
gives its source with `setData`, or, for features with ids, as what changed
with `updateData`, keeps the state of each feature id; a source added again
starts with none. A component's source is added again:

* on each style change made through the map
  (`MaplibreX.Components.Map.set_style/2`, `map:set_style`, a new `style`
  attribute): MapLibre diffs the new style in, which
  removes the sources it does not have, the components' among them, and
  the components add theirs back; or, when it cannot diff (with terrain on,
  say), it rebuilds the style from scratch;
* when it changes in a way the source cannot take in place: for
  `geojson_layer`, turning `cluster` off, or a new `cluster_properties`,
  `generate_id` or `promote_id`;
* on a map rendered again under its id, which is a new map.

A source of the map's style that the new style has too, unchanged, keeps
its state through a diff, but not through a rebuild.

So set the state again on each new source object. Feature state needs
feature ids, from one of:

* an `id` on each GeoJSON feature;
* a property named by `promote_id`: with `promote_id="uuid"`, each
  feature's `uuid` property is its id, string or number, so
  `setFeatureState({ source: "<id>-source", id: feature.properties.uuid }, ...)`
  addresses it, whatever the order of the data;
* `generate_id={true}`, which numbers the features in the order of the
  data, so that a feature's id changes when a feature before it comes or
  goes. It excludes `promote_id`.

Here the layer is `<.geojson_layer id="quakes" ...>`, whose source is
`quakes-source`; when the user selects a quake, the application adds its
id to `selected` and sets its state as usual.

```javascript
import { followMap } from "maplibrex"

// The ids of the quakes the user selected: the application keeps them.
const selected = new Set()

followMap("map", map => {
  let source
  // A source added again has no feature state: set it on each new one.
  const restore = () => {
    const current = map.getSource("quakes-source")
    if (!current || current === source) return
    source = current
    for (const id of selected) {
      map.setFeatureState({ source: "quakes-source", id }, { selected: true })
    }
  }
  const onSourceData = event => {
    if (event.sourceId === "quakes-source") restore()
  }
  map.on("sourcedata", onSourceData)
  restore()
  return mapRemoved => {
    if (!mapRemoved) map.off("sourcedata", onSourceData)
  }
})
```

For the pointer over features your code selects this way, give the layer
component `cursor="pointer"` (or any CSS cursor) rather than an event it
does not need: it shows that cursor over the layer's features and pushes
nothing. The layers show their cursors on the map's canvas, and when the
pointer leaves their features the canvas gets back the cursor it had
before, one your code set included.

### Sources and layers of your own

A source or layer your code adds goes with each style change made through
the map: a diff keeps only what the new style has, and a rebuild keeps
nothing. A custom layer is the exception on a diff, which does not see
custom layers and leaves them where they are, under the new style's
layers; a rebuild drops it too. All of them go with the map. For a source
or layer that has to stay, use a component; otherwise add yours again after
each style change, and on each new map, which `followMap` gives you.

## Testing code that follows a map

Code that imports `MapManager`, `followMap`, `useMap` or `requireMap` from
`maplibrex` loads maplibre-gl with them, which needs a DOM and WebGL.
Imported from `maplibrex/map-manager`, they come without it, so the code
loads in Node, and its tests can run there against the real `followMap`.
In the browser, nothing changes: both keep their maps in the registry the
hooks register them in.

In place of each map, a test gives a plain object with what the code under
test calls on the map, and what `followMap` calls: `on` and `off`, for its
`remove` listener, and `remove`, which calls that listener. The test plays
the part of the map hook with the [methods for tests](#methods-for-tests):
it registers a map with `MapManager.register(mapId, map)`, and, when the
map's element goes, unregisters it with `MapManager.unregister(mapId, map)`,
then removes it.

The registry is one for the Node process, as for the page: a map a test
leaves registered is there for the next test. Unregister it at the end of
the test, or call `MapManager.clear()` between tests.

```javascript
import { MapManager, followMap } from "maplibrex/map-manager"

// A map, as far as followMap needs one: remove() calls the "remove" listeners.
function fakeMap() {
  const listeners = { remove: new Set() }
  return {
    on: (type, listener) => (listeners[type] ??= new Set()).add(listener),
    off: (type, listener) => listeners[type]?.delete(listener),
    remove: () => [...listeners.remove].forEach(listener => listener({ type: "remove" }))
  }
}

// The code under test follows the map "map".
const seen = []
const stop = followMap("map", map => {
  seen.push("attached")
  return mapRemoved => seen.push(mapRemoved ? "map removed" : "stopped")
})

// As the map hook does: register a map; when its element goes, unregister
// it, then remove it. The next map is followed in its place.
const first = fakeMap()
MapManager.register("map", first)
MapManager.unregister("map", first)
first.remove()
const second = fakeMap()
MapManager.register("map", second)
stop()
MapManager.unregister("map", second)
// seen: ["attached", "map removed", "attached", "stopped"]
```

## Methods for tests

`MapManager` has three more methods, with which a test of application code
stands in for the map hook. They are stable for that use, and covered by
the version number as the API above is. Application code must not call
them at runtime: on the page, the map hook owns registration, and the
components follow what it registers.

### `MapManager.register(mapId, map)`

```typescript
register(mapId: string, map: Map): void
```

Registers `map` under `mapId`, as the map hook does once MapLibre creates
the map, then calls the callbacks waiting for `mapId`: those of
`whenReady`, `whenNextRegistered` and `followMap`. A map already registered
under `mapId` is replaced, with a warning in the console.

### `MapManager.unregister(mapId, map)`

```typescript
unregister(mapId: string, map?: Map): boolean
```

Unregisters the map registered under `mapId`, as the map hook does just
before it removes the map; with `map`, only if `map` is the one registered.
It does not remove the map: call its `remove()` after, as the hook does.
Returns whether a map was unregistered.

### `MapManager.clear()`

```typescript
clear(): void
```

Removes every registered map, calling its `remove()`, empties the registry,
and drops every pending wait (of `whenReady`, `whenNextRegistered` and
`followMap`) without calling it. Called between tests, it leaves nothing
for the next one; a `followMap` not stopped before it follows nothing
after it.

## Internal exports

The package exports more than this guide documents. The rest is
MaplibreX's own, and may change in any release:

* the other methods of `MapManager`: `getOrThrow`, `has`, `getAll`,
  `getAllIds`, `count` and `setDebug`;
* `EventDispatcher` and `createEventDispatcher`, which connect a map to the
  LiveView of its hook;
* the hooks one by one (`MapHook`, `MarkerHook` and the others), the
  objects `MapHooks` holds, under the same names: register `MapHooks`,
  which has every hook the components name;
* the types `LiveViewHook`, `HookContext`, `MapConfig`, `MarkerConfig`,
  `PopupConfig`, `LayerConfig`, `GeoJSONSourceConfig`, `ControlConfig`,
  `NavigationControlConfig`, `ScaleControlConfig`,
  `FullscreenControlConfig`, `GeolocateControlConfig`, `MapEventPayload`,
  `MapMoveEventPayload`, `MapClickEventPayload`, `MarkerDragEventPayload`,
  `Position` and `Bounds`.
