# Registering JavaScript

Some of what MapLibre takes is code, not data. A protocol for `pmtiles://`
URLs is a function. A custom WebGL layer and a control of your own are objects
with methods. A request transform and a resolver for missing images are
functions MapLibre calls back. None of them can travel through a component
prop, which carries JSON.

So the application provides that JavaScript once, under a name, and refers to
the name from Elixir.

## Registering

Push a callback onto `window.HoloMap.registry`. It is called with the
`register` functions:

```javascript
window.HoloMap = window.HoloMap || {};
(window.HoloMap.registry ||= []).push((register) => {
  register.protocol("cached", cachedLoad);
  register.function("signedRequests", signRequest);
});
```

| Function | Registers | Used by |
| -------- | --------- | ------- |
| `register.layer(name, factory)` | A function that builds a custom WebGL layer | `HoloMap.Layer.Custom`'s `factory` |
| `register.control(name, factory)` | A function that builds a control | `HoloMap.Control.Custom`'s `factory` |
| `register.protocol(scheme, load)` | A load function for URLs starting with `scheme://` | Any source, sprite or glyph URL with that scheme |
| `register.function(name, fn)` | A function MapLibre calls back | `HoloMap.Map`'s `transform_request` and `missing_image_resolver` |

Each kind has names of its own. A registration without a name, or without a
function, is ignored with a console warning, and so is anything pushed that is
not a function. A callback that throws is logged, and the others still run.

The registry works before the runtime has loaded. Until then
`window.HoloMap.registry` is a plain list that your script fills. The runtime
runs every callback in it once it loads, and puts in its place a registry
whose `push` runs a callback at once, so the same line works whichever comes
first.

Registrations last for the page: they survive Hologram's navigations, and
nothing unregisters them.

Once the runtime has loaded, `window.HoloMap` also holds `map`, `cids` and
`destroy` (see the [Imperative API guide](imperative-api.html#from-javascript)).
Before then it may hold `registry` alone, so code that waits for a map asks
`window.HoloMap?.map?.(cid)`.

### A name registered twice

The second registration replaces the first, and the browser console warns
about it once for each name. A protocol takes effect from MapLibre's next
request, and a function from MapLibre's next call. A layer or a control
already built by the first factory stays as it is until it is built again,
for an `options` change it has no `update` for, and the new factory builds
it then. Registering the same function again under the same name does nothing.

### A name registered late

A component or a prop can name something before it is registered. The
browser console warns once for each name on each map, and the map goes on
without it: a custom layer or control stays off the map, and a prop is as if
it were not set. Once the name is registered, the layer or control is added
in its place, and the function is used from MapLibre's next call, with no
reload.

## Loading your script

Put the script in your layout's `<head>`, as a plain `<script>` before
Hologram's `<Runtime />`:

```elixir
def template do
  ~HOLO"""
  <!DOCTYPE html>
  <html>
    <head>
      <link rel="stylesheet" href="/assets/maplibre-gl.css" />
      <script src="/assets/holo_map_extensions.js"></script>
      <Runtime />
    </head>
    <body>
      <slot />
    </body>
  </html>
  """
end
```

and serve the file from your `Plug.Static`, as the
[Installation guide](installation.html) does for MapLibre's worker. The
browser runs a plain script in `<head>` before it goes on reading the page,
and `<Runtime />` loads Hologram's runtime and the page's bundle with `async`,
so your registrations are in place before the first map boots.

The script cannot `import`: it is a classic script, not a module. A library it
needs, such as three.js, comes from its own `<script>` tag before it, or is
bundled into the file with your own tooling.

Hologram keeps a script element with the same `src` through its navigations,
and does not run it again. A page that uses another layout without the script
removes it, and a page that brings it back runs it again: the names are then
registered a second time, which replaces them, with a warning (see above).

### Why not `js_import`

A module imported with `Hologram.JS`'s `js_import` would run too, but
Hologram builds one bundle per page, and each bundle carries its own copy of
the module. It runs again for every page the browser loads, and registers
every name again each time. Keep registrations in one script the layout
loads.

The same holds for `HoloMap`'s own runtime and for MapLibre: each page bundle
carries a copy. The registry belongs to the page rather than to a copy, so a
copy a later page brings finds every name registered before it.

## Protocols

```javascript
(window.HoloMap.registry ||= []).push((register) => {
  register.protocol("cached", async (params, abortController) => {
    const response = await fetch(params.url.replace("cached://", "https://"), {
      signal: abortController.signal,
    });
    return { data: await response.arrayBuffer() };
  });
});
```

The load function is MapLibre's `addProtocol` load function: it receives the
request parameters, `url` among them, and an `AbortController`, and returns
a promise of `{data}`. MapLibre calls it for every URL with that scheme,
whichever source, sprite or glyph request it is for: a source written as

```elixir
<HoloMap.Source.Vector id="area" url="cached://tiles.example.com/area.json" />
```

loads through it.

MapLibre keeps protocols for the whole page, not per map. Each copy of
MapLibre does, and as each page bundle carries its own copy, the runtime adds
every registered protocol to each copy as it loads, and a protocol registered
later to every copy already loaded. A protocol is never removed.

A request MapLibre made before its protocol was registered has already failed,
and MapLibre reported it through `on_error`. It is not made again: register
protocols before the first map boots, as the layout script does.

MapLibre's report of such a request is a failed fetch, which does not say
that a protocol is missing. So a source component whose `url`, `tiles` or
`data` names a scheme other than `http`, `https` or `file`, with no protocol
registered for it when the source is added, is warned about in the browser
console, once for each scheme on each map. The warning names the source and
the scheme, not the URL.

### PMTiles

PMTiles' protocol is a protocol like any other. With `pmtiles.js`, the
`pmtiles` package's browser build, loaded by its own `<script>` tag before
your script (the [Installation guide](installation.html#pmtiles-archives)
has the steps):

```javascript
(window.HoloMap.registry ||= []).push((register) => {
  register.protocol("pmtiles", new pmtiles.Protocol().tile);
});
```

```elixir
<HoloMap.Source.Vector id="zones" url="pmtiles://https://cdn.example.com/zones.pmtiles" />
```

`tile` is the protocol's load function, which takes MapLibre's request and
`AbortController` as MapLibre 6 hands them, and needs no binding. The one
`Protocol` serves every map on the page, and every copy of MapLibre the
page's bundles carry, so each archive is opened once. Its own callback
keeps the other registrations in place when `pmtiles.js` did not load: the
callback throws a `ReferenceError`, which the console shows.

PMTiles reads the archive with requests of its own, so `request_rules` and
`transform_request` do not reach them. For an archive that needs a header or
a cookie, give the protocol the archive with a `FetchSource` that sends it.
This example is not run by the test suites; it follows the `FetchSource`
constructor of `pmtiles` 4.5.0, which takes the URL, the headers and the
credentials:

```javascript
(window.HoloMap.registry ||= []).push((register) => {
  const protocol = new pmtiles.Protocol();
  const archive = "https://tiles.example.com/zones.pmtiles";

  protocol.add(new pmtiles.PMTiles(new pmtiles.FetchSource(
    archive,
    new Headers({ Authorization: `Bearer ${window.tileToken}` }),
    "include",
  )));
  register.protocol("pmtiles", protocol.tile);
});
```

The protocol finds the archive by the URL after `pmtiles://`, so the source
names it as `"pmtiles://https://tiles.example.com/zones.pmtiles"`. As with a
rule, what the browser holds anyone who opens the page can read.

## Custom layers

`register.layer` takes a factory: a function that receives the component's
`options` and `{map, cid, id}`, and returns a layer as MapLibre takes it, a
`CustomLayerInterface`. MapLibre calls its `render(gl, frame)` on every
frame, with the WebGL2 context, and its `onAdd(map, gl)` and
`onRemove(map, gl)` as it goes on and off the map. `prerender` and
`renderingMode` (`"2d"` or `"3d"`) are optional. MapLibre sees the layer as
the component's `id`, of type `"custom"`, whatever the object holds; the
object itself is not changed.

This one draws a translucent quad over the area its options give, in raw
WebGL. The demo's JavaScript page runs a layer like it:

```javascript
// Web Mercator coordinates in [0, 1], as the frame's matrix takes them.
const mercator = ([lng, lat]) => [
  (180 + lng) / 360,
  (180 - (180 / Math.PI) * Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI) / 360))) / 360,
];

(window.HoloMap.registry ||= []).push((register) => {
  register.layer("area", (options) => ({
    options,
    onAdd(map, gl) {
      const shader = (type, source) => {
        const made = gl.createShader(type);
        gl.shaderSource(made, source);
        gl.compileShader(made);
        return made;
      };

      this.program = gl.createProgram();
      gl.attachShader(this.program, shader(gl.VERTEX_SHADER, `#version 300 es
        uniform mat4 u_matrix;
        in vec2 a_position;
        void main() { gl_Position = u_matrix * vec4(a_position, 0.0, 1.0); }`));
      gl.attachShader(this.program, shader(gl.FRAGMENT_SHADER, `#version 300 es
        precision mediump float;
        uniform vec4 u_color;
        out vec4 color;
        void main() { color = u_color; }`));
      gl.linkProgram(this.program);

      const [[west, south], [east, north]] = this.options.bounds;
      const [x0, y0] = mercator([west, north]);
      const [x1, y1] = mercator([east, south]);
      this.buffer = gl.createBuffer();
      gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer);
      gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([x0, y0, x1, y0, x0, y1, x0, y1, x1, y0, x1, y1]), gl.STATIC_DRAW);
    },
    update(options) {
      this.options = options;
    },
    render(gl, frame) {
      gl.useProgram(this.program);
      gl.uniformMatrix4fv(gl.getUniformLocation(this.program, "u_matrix"), false, frame.defaultProjectionData.mainMatrix);
      gl.uniform4fv(gl.getUniformLocation(this.program, "u_color"), this.options.color);
      const position = gl.getAttribLocation(this.program, "a_position");
      gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer);
      gl.enableVertexAttribArray(position);
      gl.vertexAttribPointer(position, 2, gl.FLOAT, false, 0, 0);
      gl.enable(gl.BLEND);
      gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
      gl.drawArrays(gl.TRIANGLES, 0, 6);
    },
    onRemove(map, gl) {
      gl.deleteBuffer(this.buffer);
      gl.deleteProgram(this.program);
    },
  }));
});
```

```elixir
<HoloMap.Map cid="explorer" style={@style}>
  <HoloMap.Layer.Custom id="area" factory="area" before_id="labels"
                        options={%{bounds: [[-72, 17.5], [-68.3, 20]], color: [0.06, 0.46, 0.43, 0.6]}} />
</HoloMap.Map>
```

`frame.defaultProjectionData.mainMatrix` maps Web Mercator coordinates in
`[0, 1]` to the screen on a mercator map. A layer that should also draw on a
globe uses MapLibre's projection shader code from `frame.shaderData` instead;
MapLibre's custom layer examples show how.

The layer is a style layer like the others: it stacks in template order, and
`before_id` places it. It survives every style change, and comes back after a
WebGL context loss, where MapLibre logs that it cannot restore a custom
layer: the runtime adds it again. Each `onAdd` is followed by one `onRemove`,
so the object can set up its WebGL resources in one and free them in the
other. An `options` change calls `update(options)` and has the map draw
again; an object without `update` is built again. `HoloMap.Layer.Custom`
has the details.

### three.js

This example is not run by the test suites. It follows MapLibre's three.js
example, with three.js loaded by its own `<script>` tag before the
registration script, which makes `window.THREE`, and `mercator` from the
example above. three.js draws on MapLibre's canvas, with MapLibre's WebGL
context:

```javascript
(window.HoloMap.registry ||= []).push((register) => {
  register.layer("box3d", ({ lngLat: [lng, lat], size, color }) => {
    const [x, y] = mercator([lng, lat]);
    const metre = 1 / (2 * Math.PI * 6378137 * Math.cos((lat * Math.PI) / 180));
    const camera = new THREE.Camera();
    const scene = new THREE.Scene();
    let renderer = null;

    return {
      renderingMode: "3d",
      onAdd(map, gl) {
        scene.add(new THREE.AmbientLight(0xffffff, 1.5));
        const box = new THREE.Mesh(
          new THREE.BoxGeometry(size, size, size),
          new THREE.MeshStandardMaterial({ color }),
        );
        box.position.z = size / 2;
        scene.add(box);
        renderer = new THREE.WebGLRenderer({ canvas: map.getCanvas(), context: gl });
        renderer.autoClear = false;
      },
      render(gl, frame) {
        const place = new THREE.Matrix4()
          .makeTranslation(x, y, 0)
          .scale(new THREE.Vector3(metre, -metre, metre));
        camera.projectionMatrix = new THREE.Matrix4()
          .fromArray(frame.defaultProjectionData.mainMatrix)
          .multiply(place);
        renderer.resetState();
        renderer.render(scene, camera);
      },
      onRemove() {
        renderer.dispose();
      },
    };
  });
});
```

```elixir
<HoloMap.Layer.Custom id="box" factory="box3d"
                      options={%{lngLat: [-69.93, 18.47], size: 200, color: "#f97316"}} />
```

### deck.gl

This example is not run by the test suites either. deck.gl's
`MapboxOverlay` is a control, which draws its layers into MapLibre's stack
when it is `interleaved`, so it goes in a `HoloMap.Control.Custom`, with
deck.gl loaded by its own `<script>` tag, which makes `window.deck`:

```javascript
(window.HoloMap.registry ||= []).push((register) => {
  const layersFor = ({ points }) => [
    new deck.ScatterplotLayer({
      id: "points",
      data: points,
      getPosition: (point) => point.position,
      getRadius: 300,
      getFillColor: [249, 115, 22],
    }),
  ];

  register.control("deck", (options) => {
    const overlay = new deck.MapboxOverlay({ interleaved: true, layers: layersFor(options) });
    overlay.update = (next) => overlay.setProps({ layers: layersFor(next) });
    return overlay;
  });
});
```

```elixir
<HoloMap.Control.Custom factory="deck" options={%{points: @points}} />
```

## Custom controls

`register.control` takes a factory: a function that receives the
component's `options` and `{map, cid, id}`, and returns a control as MapLibre
takes it, an object with `onAdd(map)`, which returns the control's element,
and `onRemove(map)`:

```javascript
(window.HoloMap.registry ||= []).push((register) => {
  register.control("legend", (options) => ({
    onAdd() {
      this.element = document.createElement("div");
      this.element.className = "maplibregl-ctrl maplibregl-ctrl-group legend";
      this.render(options);
      return this.element;
    },
    update(options) {
      this.render(options);
    },
    render({ title, items }) {
      this.element.replaceChildren(
        Object.assign(document.createElement("strong"), { textContent: title }),
        ...items.map((item) => Object.assign(document.createElement("div"), { textContent: item })),
      );
    },
    onRemove() {
      this.element.remove();
    },
  }));
});
```

```elixir
<HoloMap.Map cid="explorer" style={@style}>
  <HoloMap.Control.Custom factory="legend" position="bottom-left"
                          options={%{title: "Zones", items: @zones}} />
</HoloMap.Map>
```

The control is added and removed with its component, and keeps its place in
its corner among the built-in controls. An `options` change calls its
`update(options)` when it has one, and otherwise builds the control again.
Its `onRemove` is called when the component goes, or the map does, and the
element it returned leaves the page even if `onRemove` leaves it.
`HoloMap.Control.Custom` has the details.

## Errors in your JavaScript

What the application's JavaScript throws does not stop the rest of the map.
An error a factory throws, a factory that returns nothing, and an error from
a layer's or a control's `onAdd`, `update` or `onRemove` are reported through
the map's `on_error`, as MapLibre reports its own errors, with a message that
names the layer or the control and the method, and the error itself as its
`cause`. A map without `on_error` logs them to the browser console. The
layer or control is then left off the map, or taken off it, and every other
component is applied as usual.

A custom layer's `render`, `prerender` and `renderToTerrainTile` run on every
frame, inside MapLibre's own drawing: the first error each of them throws is
reported, the rest are not, and the frame goes on. A layer object without
`render` is refused by MapLibre, which reports it through `on_error` as
well.

## Request transform

A header or a cookie on the requests to a tile server needs no JavaScript:
`HoloMap.Map`'s `request_rules` adds them by the start of the URL (see
"Request rules" in `HoloMap.Map`). A transform is for what rules cannot
say, such as a signature computed for each URL, or a token the browser
fetches and renews itself.

`HoloMap.Map`'s `transform_request` names a function MapLibre calls just
before each request it makes. It receives MapLibre's two arguments, the URL
and the kind of resource (`"Style"`, `"Source"`, `"Tile"`, `"Glyphs"`,
`"SpriteImage"`, `"SpriteJSON"`, `"Image"`), and a third, `{map, cid,
request}`. It answers the request to make instead, with `url`, `headers` and
`credentials`, or a promise of one, which MapLibre awaits, or nothing to
leave the request as it is:

```javascript
(window.HoloMap.registry ||= []).push((register) => {
  register.function("signedRequests", (url, resourceType, { cid }) => {
    if (url.startsWith("https://tiles.example.com/")) {
      return { url, headers: { Authorization: `Bearer ${window.tileToken}` } };
    }
  });
});
```

```elixir
<HoloMap.Map cid="explorer" style={@style} transform_request="signedRequests" />
```

The map is built with it, so the style's own request goes through it: `map`
is `null` for that one, as MapLibre makes it while it builds the map. A
change to the prop applies with MapLibre's `setTransformRequest`, and `nil`
takes the transform away.

An error the function throws fails the request MapLibre was making, which
MapLibre reports through the map's `error` event, and so `on_error`: a
request the function was to sign does not go out unsigned.

### With request rules

A map can have both. The rules apply first, and `request` is the request
they made: the URL with the headers and credentials of the rule that
matched, or `{url}` alone when none did. The function signs it, or answers
another, and what it answers is the request MapLibre makes. Nothing, or a
promise of nothing, leaves the rules' request as it is:

```javascript
(window.HoloMap.registry ||= []).push((register) => {
  register.function("signTiles", async (url, resourceType, { request }) => {
    if (!url.startsWith("https://tiles.example.com/")) return;

    const signature = await window.signUrl(url, request.headers);
    return { ...request, headers: { ...request.headers, "X-Signature": signature } };
  });
});
```

```elixir
<HoloMap.Map cid="explorer" style={@style} transform_request="signTiles"
             request_rules={[%{url_prefix: "https://tiles.example.com/", headers: %{"X-Client" => "web"}}]} />
```

`request` is the function's own copy, which it may change. While no function
is registered under the name, the rules' requests go out as they made them.
An error the function throws still fails the request, whatever the rules
added.

## Missing images

`missing_image_resolver` names a function MapLibre calls for each image a
tile needs that the style lacks, with the image's id and `{map, cid}`.
MapLibre waits for the promise it returns before it reports the image as
missing, so the function can fetch or draw the image and add it:

```javascript
(window.HoloMap.registry ||= []).push((register) => {
  register.function("drawDots", (id, { map }) => {
    const match = /^dot-([0-9a-f]{6})$/.exec(id);
    if (!match) return;

    const size = 24;
    const canvas = new OffscreenCanvas(size, size);
    const context = canvas.getContext("2d");
    context.fillStyle = `#${match[1]}`;
    context.beginPath();
    context.arc(size / 2, size / 2, size / 2 - 1, 0, Math.PI * 2);
    context.fill();
    map.addImage(id, context.getImageData(0, 0, size, size));
  });
});
```

```elixir
<HoloMap.Map cid="explorer" style={@style} missing_image_resolver="drawDots">
  <HoloMap.Layer.Symbol id="stops" source="stops" layout={%{icon_image: "dot-0f766e"}} />
</HoloMap.Map>
```

The map keeps the resolver through every style change, and a style built
from scratch, which starts without the images it added, asks for them again.

The function is not asked for an image a `HoloMap.Image` declares, even while
the image is still loading: the component adds it. `on_style_image_missing`
fires only for an image still missing once the function is done. An error it
throws, or a promise of its that rejects, is reported through `on_error`,
and the image stays missing.
