Server components

Say you are building a chart as a Lustre server component. You want to show fewer data points when the window gets narrow. The width lives in the browser, but your update function runs on the BEAM. How does the new width get there?

off_topic uses a small browser runtime for this. Your Gleam code still returns subscriptions from subscriptions. The server tells the browser which ones to start, and the browser sends their messages back to update. When a subscription disappears, the browser runs its cleanup.

Load the browser runtime

Use off_topic.application or off_topic.component as you would in a browser app. On the server, off_topic inserts an <ot-client-runtime> element into the rendered view. The host page also needs the off_topic JavaScript module, alongside Lustre’s server component runtime:

<script type="module" src="/off-topic.mjs"></script>

Serve off_topic’s priv/static/off-topic.mjs at /off-topic.mjs. There is also a minified version in the same directory. To get going quickly, there’s also off_topic.script().

Now the subscriptions callback looks familiar:

fn subscriptions(_model: Model) -> off_topic.Subscription(Msg) {
  off_topic.window_size(WindowResized)
}

The browser reports the current size as soon as this subscription starts, then reports each resize. off_topic sends those values to the BEAM as WindowResized(width, height) messages. You handle them in update as usual. There is no separate server version of window_size to call.

Most built-in subscriptions make that choice internally. The ones marked JS in the API reference, such as server_sent_events and websocket, only have a browser path.

Add a browser API of your own

Suppose a server component wants the device’s location. The BEAM cannot call navigator.geolocation, so we need a browser handler. remote gives that handler a name and describes how to decode the values it sends back:

import gleam/dynamic/decode
import off_topic

pub fn geolocation(
  send: fn(Float, Float) -> message,
) -> off_topic.Subscription(message) {
  let decoder = {
    use lat <- decode.field("lat", decode.float)
    use lng <- decode.field("lng", decode.float)
    decode.success(send(lat, lng))
  }

  off_topic.remote(name: "my-app/geolocation", with: [], run: decoder)
  |> off_topic.including(["lat", "lng"])
}

Register the matching handler in a JavaScript module loaded by the host page:

window.OffTopic ??= {};
window.OffTopic.subscriptions ??= {};

window.OffTopic.subscriptions["my-app/geolocation"] = (dispatch) => {
  const id = navigator.geolocation.watchPosition((position) => {
    dispatch({
      lat: position.coords.latitude,
      lng: position.coords.longitude,
    });
  });

  return () => navigator.geolocation.clearWatch(id);
};

The browser runtime looks up "my-app/geolocation", starts the watch, and calls its returned function when the subscription stops. The with: [] list is empty because this handler needs no parameters. If it did, the runtime would pass them before dispatch.

The including call matters here. The bridge only forwards object fields you name, so the decoder needs both lat and lng. Built-in DOM event subscriptions such as on_key_down already select the fields they use. Primitive values pass through without including.

This function is for server components. To offer the same subscription in a browser app, use lustre.is_browser() to choose a direct from subscription there and remote on the server. The subscriptions from scratch guide shows the browser side.

Keep frequent events in the browser

Pointer movement can produce many messages. In a server component, each one would otherwise cross the connection to the BEAM. throttle drops intermediate messages in the browser:

off_topic.on_pointer_move(MouseMoved)
|> off_topic.throttle(wait: duration.milliseconds(50))

Like Lustres event.throttle function, the first message goes through immediately, while delay would wait until the events have been quiet for the requested duration, then sends the last one.

One-shot browser actions

A custom subscription starts a browser listener and returns cleanup. For a one-shot browser action, register a function in window.OffTopic.commands and call it from an effect with off_topic.command(name, params). Built-in actions such as scroll_to already take care of this for you.

✨ Search Document