HoloMap.JSON (HoloMap v0.1.0)

Copy Markdown View Source

A small JSON encoder that runs in the browser.

Every component specification travels from Elixir to MapLibre as a JSON string in a DOM attribute, and that string has to be produced during client-side re-renders as well as during server-side rendering. Hologram compiles a well-defined subset of Elixir to JavaScript, and Jason, which leans on Erlang primitives and protocols outside that subset, is not part of it. So HoloMap carries its own encoder, written only in constructs the Hologram client runtime supports.

It handles exactly what a MapLibre style specification contains: strings, integers, floats, booleans, nil, atoms, lists and maps. Anything else raises ArgumentError rather than being silently coerced. A struct or a tuple reaching this function means the calling component built a spec it did not intend to.

Examples

iex> HoloMap.JSON.encode(%{"fill-color" => "#f00", "fill-opacity" => 0.5})
~s({"fill-color":"#f00","fill-opacity":0.5})

iex> HoloMap.JSON.encode(["get", "name"])
~s(["get","name"])

iex> HoloMap.JSON.encode(nil)
"null"

Map keys are emitted in sorted order. That is not cosmetic: the reconciler compares the previous and current attribute strings to decide whether a MapLibre call is needed, and Erlang map iteration order is not stable across builds. Sorting makes an unchanged spec encode to an unchanged string.

Summary

Functions

Encodes value as a JSON string.

Functions

encode(value)

@spec encode(term()) :: String.t()

Encodes value as a JSON string.

Raises ArgumentError for terms with no JSON representation.