lib/runbox/ui.ex

defmodule Runbox.Ui do
  @moduledoc """
  Set of utility functions for working with UI.
  """

  @doc """
  Returns a URL path to the specific asset in the Network tab.

  ## Examples

      iex> network_asset_path("/assets/cameras", "main")
      "/network/asset/%2Fassets%2Fcameras/main"

      iex> network_asset_path("/assets/strange type", "strange#id")
      "/network/asset/%2Fassets%2Fstrange%20type/strange%23id"
  """
  def network_asset_path(type, id) do
    "/network/asset/#{uri_encode(type)}/#{uri_encode(id)}"
  end

  @doc """
  Returns a URL path to the specific incident in the Network tab.

  ## Examples

      iex> network_incident_path("fire", "big")
      "/network/incident/fire/big"

      iex> network_incident_path("bad fire&", "strange#/id")
      "/network/incident/bad%20fire%26/strange%23%2Fid"
  """
  def network_incident_path(type, id) do
    "/network/incident/#{uri_encode(type)}/#{uri_encode(id)}"
  end

  # Note that `URI.encode_www_form/1` is NOT compatible with JS `decodeURIComponent`.
  defp uri_encode(segment), do: URI.encode(segment, &URI.char_unreserved?/1)
end