lustre_pipes/server_component

Values

pub fn element() -> #(String, List(Attribute(a)))

Render the server component custom element. This element acts as the thin client runtime for a server component running remotely. There are a handful of attributes you should provide to configure the client runtime:

  • route is the URL your server component should connect to. This must be provided before the client runtime will do anything. The route can be a relative URL, in which case it will be resolved against the current page URL.

  • method is the transport method the client runtime should use. This defaults to WebSocket enabling duplex communication between the client and server runtime. Other options include ServerSentEvents and Polling which are unidirectional transports.

Note: the server component runtime bundle must be included and sent to the client for this to work correctly. You can do this by including the JavaScript bundle found in Lustre’s priv/static directory or by inlining the script source directly with the script element below.

pub fn include(
  scaffold: #(String, List(Attribute(a))),
  event: Attribute(a),
  properties: List(String),
) -> #(String, List(Attribute(a)))

Properties of a JavaScript event object are typically not serialisable. This means if we want to send them to the server we need to make a copy of any fields we want to decode first.

This attribute tells Lustre what properties to include from an event. Properties can come from nested fields by using dot notation. For example, you could include the id of the target element by passing ["target.id"].

import gleam/dynamic/decode
import lustre/element.{type Element}
import lustre/element/html
import lustre/event
import lustre/server_component

pub fn custom_button(on_click: fn(String) -> msg) -> Element(msg) {
  let handler = fn(event) {
    use id <- decode.at(["target", "id"], decode.string)
    decode.success(on_click(id))
  }

  html.button(
    [server_component.include(["target.id"]), event.on_click(handler)],
    [html.text("Click me!")],
  )
}
pub fn method(
  scaffold: #(String, List(Attribute(a))),
  value: TransportMethod,
) -> #(String, List(Attribute(a)))
pub fn route(
  scaffold: #(String, List(Attribute(a))),
  path: String,
) -> #(String, List(Attribute(a)))

The route attribute tells the client runtime what route it should use to set up the WebSocket connection to the server. Whenever this attribute is changed (by a clientside Lustre app, for example), the client runtime will destroy the current connection and set up a new one.

pub fn script() -> Element(a)

Inline the server component client runtime as a <script> tag. Where possible you should prefer serving the pre-built client runtime from Lustre’s priv/static directory, but this inline script can be useful for development or scenarios where you don’t control the HTML document.

Search Document