Current section

Files

Jump to
drab lib drab.ex
Raw

lib/drab.ex

defmodule Drab do
require Logger
@moduledoc """
Drab allows to query and manipulate the User Interface directly from the Phoenix server backend.
To enable it on the specific page you must find its controller and
enable Drab by `use Drab.Controller` there:
defmodule DrabExample.PageController do
use Example.Web, :controller
use Drab.Controller
def index(conn, _params) do
render conn, "index.html"
end
end
Notice that it will enable Drab on all the pages generated by `DrabExample.PageController`.
All Drab functions (callbacks and event handlers) should be placed in a module called 'commander'. It is very
similar to controller, but it does not render any pages - it works with the live page instead. Each controller with
enabled Drab should have the corresponding commander.
defmodule DrabExample.PageCommander do
use Drab.Commander, onload: :page_loaded
# Drab Callbacks
def page_loaded(socket) do
socket |> update(:html, set: "Welcome to Phoenix+Drab!", on: "div.jumbotron h2")
socket |> update(:html,
set: "Please visit <a href='https://tg.pl/drab'>Drab</a> page for more examples and description",
on: "div.jumbotron p.lead")
end
# Drab Events
def button_clicked(socket, dom_sender) do
socket |> update(:text, set: "alread clicked", on: this(dom_sender))
end
end
Drab treats browser page as a database, allows you to read and change the data there. Please refer to `Drab.Query` documentation to
find out how `Drab.Query.select/2` or `Drab.Query.update/2` works.
## Modules
Drab is modular. You my choose which modules to use in the specific Commander by using `:module` option
in `use Drab.Commander` directive. By default, `Drab.Query` and `Drab.Modal` are loaded, but you may override it using
options with `use Drab.Commander` directive.
Every module must have the corresponding javascript template, which is added to the client code in case the module is loaded.
"""
use GenServer
@doc false
def start_link(socket) do
GenServer.start_link(__MODULE__, socket)
end
@doc false
def init(socket) do
{:ok, socket}
end
@doc false
def handle_cast({:onload, socket}, _) do
# socket is coming from the first request from the client
cmdr = commander(socket)
onload = drab_config(cmdr).onload
if onload do # only if onload exists
apply(cmdr, onload, [socket])
end
{:noreply, socket}
end
@doc false
# any other cast is an event handler
def handle_cast({_, socket, payload, event_handler_function, reply_to}, _) do
do_handle_cast(socket, event_handler_function, payload, reply_to)
end
defp do_handle_cast(socket, event_handler_function, payload, reply_to) do
commander_module = commander(socket)
# raise a friendly exception when misspelled the function handler name
unless function_exists?(commander_module, event_handler_function) do
raise "Drab can't find the event handler function \"#{commander_module}.#{event_handler_function}/2\"."
end
# TODO: rethink the subprocess strategies - now it is just spawn_link
spawn_link fn ->
dom_sender = Map.delete(payload, "event_handler_function")
returned_socket = apply(
commander_module,
String.to_existing_atom(event_handler_function),
[socket, dom_sender]
)
# check if the handler return socket, if not - ignore
# TODO: change the warning to exception
updated_session = case returned_socket do
%Phoenix.Socket{assigns: returned_assigns} ->
returned_assigns.drab_session
ret ->
Logger.warn("Event Handler should return `socket`. It returned: `#{inspect(ret)}` instead. The session will not be updated.")
socket.assigns.drab_session
end
drab_session_token = Phoenix.Token.sign(socket, "drab_session_token", updated_session)
# Send a message to browser to run the "after event" callback
# eg. for enabling the buttons after handling events
Phoenix.Channel.push(socket, "event", %{
finished: reply_to,
drab_session_token: drab_session_token,
})
end
{:noreply, socket}
end
defp function_exists?(module_name, function_name) do
module_name.__info__(:functions)
|> Enum.map(fn {f, _} -> Atom.to_string(f) end)
|> Enum.member?(function_name)
end
@doc false
def push_and_wait_for_response(socket, pid, message, options \\ []) do
push(socket, pid, message, options)
receive do
{:got_results_from_client, reply} ->
reply
end
end
@doc false
def push(socket, pid, message, options \\ []) do
do_push_or_broadcast(socket, pid, message, options, &Phoenix.Channel.push/3)
end
@doc false
def broadcast(socket, pid, message, options \\ []) do
do_push_or_broadcast(socket, pid, message, options, &Phoenix.Channel.broadcast/3)
end
defp do_push_or_broadcast(socket, pid, message, options, function) do
m = options |> Enum.into(%{}) |> Map.merge(%{sender: tokenize(socket, pid)})
function.(socket, message, m)
end
@doc false
def tokenize(socket, pid) do
myself = :erlang.term_to_binary(pid)
Phoenix.Token.sign(socket, "sender", myself)
end
# returns the commander name for the given controller (assigned in token)
defp commander(socket) do
# Logger.debug "**** ASSIGNS: #{inspect(socket.assigns)}"
controller = socket.assigns.controller
controller.__drab__()[:commander]
end
# if module is commander or controller with drab enabled, it has __drab__/0 function with Drab configuration
defp drab_config(module) do
module.__drab__()
end
@doc """
Returns map of Drab configuration options.
All the config values may be override in `config.exs`, for example:
config :drab, disable_controls_while_processing: false
Configuration options:
* `disable_controls_while_processing` (default: `true`) - after sending request to the server, sender will be
disabled until get the answer; warning: this behaviour is not broadcasted, so only the control in the current
browers will be disabled
* `events_to_disable_while_processing` (default: `["click"]`) - list of events which will be disabled when
waiting for server response
* `disable_controls_when_disconnected` (default: `true`) - disables control when there is no connectivity
between the browser and the server
* `socket` (default: `"/drab/socket"`) - path to Drab socket
"""
def config() do
%{
disable_controls_while_processing: Application.get_env(:drab, :disable_controls_while_processing, true),
events_to_disable_while_processing: Application.get_env(:drab, :events_to_disable_while_processing, ["click"]),
disable_controls_when_disconnected: Application.get_env(:drab, :disable_controls_when_disconnected, true),
socket: Application.get_env(:drab, :socket, "/drab/socket")
}
end
end