Packages
drab
0.2.5
0.10.5
0.10.4
0.10.3
0.10.2
0.10.1
0.10.0
0.9.3
0.9.2
0.9.1
0.9.0
0.8.3
0.8.2
0.8.1
0.8.0
0.7.7
0.7.6
0.7.5
0.7.4
0.7.3
0.7.2
0.7.1
0.7.0
0.6.3
0.6.2
0.6.1
0.6.0
0.6.0-pre.1
0.5.6
0.5.5
0.5.4
0.5.3
0.5.2
0.5.1
0.5.0
0.4.1
0.4.0
0.3.5
0.3.4
0.3.3
0.3.2
0.3.1
0.3.0
0.2.6
0.2.5
0.2.4
0.2.3
0.2.2
0.2.1
0.2.0
0.1.1
0.1.0
Remote controlled frontend framework for Phoenix.
Current section
Files
Jump to
Current section
Files
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({store, session, commander}) do
GenServer.start_link(__MODULE__, {store, session, commander})
end
@doc false
def init({store, session, commander}) do
Process.flag(:trap_exit, true)
{:ok, {store, session, commander}}
end
@doc false
def terminate(_reason, {store, session, commander}) do
if commander.__drab__().ondisconnect do
# TODO: timeout
:ok = apply(commander,
drab_config(commander).ondisconnect,
[store, session])
end
{:noreply, {store, session, commander}}
end
@doc false
def handle_info({:EXIT, pid, :normal}, state) when pid != self() do
# ignore exits of the subprocesses
{:noreply, state}
end
@doc false
def handle_cast({:onconnect, socket}, {store, session, commander}) do
tasks = [Task.async(fn -> Drab.Core.save_session(socket, Drab.Core.session(socket)) end),
Task.async(fn -> Drab.Core.save_store(socket, Drab.Core.store(socket)) end)]
Enum.each(tasks, fn(task) -> Task.await(task) end)
onconnect = drab_config(commander).onconnect
handle_callback(socket, commander, onconnect) #returns socket
{:noreply, {store, session, commander}}
end
@doc false
def handle_cast({:onload, socket}, {store, session, commander}) do
onload = drab_config(commander).onload
handle_callback(socket, commander, onload) #returns socket
{:noreply, {store, session, commander}}
end
@doc false
def handle_cast({:update_store, store}, {_store, session, commander}) do
{:noreply, {store, session, commander}}
end
@doc false
def handle_cast({:update_session, session}, {store, _session, commander}) do
{:noreply, {store, session, commander}}
end
@doc false
# any other cast is an event handler
def handle_cast({_, socket, payload, event_handler_function, reply_to}, {store, session, commander}) do
handle_event(socket, event_handler_function, payload, reply_to, store, session, commander)
end
@doc false
def handle_call(:get_store, _from, {store, session, commander}) do
{:reply, store, {store, session, commander}}
end
@doc false
def handle_call(:get_session, _from, {store, session, commander}) do
{:reply, session, {store, session, commander}}
end
defp handle_callback(socket, commander, callback) do
if callback do
# TODO: rethink the subprocess strategies - now it is just spawn_link
spawn_link fn ->
apply(commander, callback, [socket])
end
end
socket
end
defp handle_event(socket, event_handler_function, payload, reply_to, store, session, commander) do
commander_module = commander
# 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]
)
#TODO: check if handler returned real socket, otherwise push will crash
Phoenix.Channel.push(returned_socket, "event", %{
finished: reply_to
# drab_store_token: drab_store_token(socket, returned_socket)
})
# Drab.update_store(returned_socket.assigns.drab_pid, returned_socket.assigns.drab_store)
end
{:noreply, {store, session, commander}}
end
@doc false
def get_store(pid) do
GenServer.call(pid, :get_store)
end
@doc false
def update_store(pid, new_store) do
GenServer.cast(pid, {:update_store, new_store})
end
@doc false
def get_session(pid) do
GenServer.call(pid, :get_session)
end
@doc false
def update_session(pid, new_session) do
GenServer.cast(pid, {:update_session, new_session})
end
# defp drab_store_token(socket, returned_socket) do
# # check if the handler return socket, if not - ignore
# # TODO: change the warning to exception
# updated_store = case returned_socket do
# %Phoenix.Socket{assigns: returned_assigns} ->
# returned_assigns.drab_store
# ret ->
# Logger.warn("Event Handler should return `socket`. It returned: `#{inspect(ret)}` instead. Drab Store will not be updated.")
# socket.assigns.drab_store
# end
# tokenize_store(socket, updated_store)
# 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
# TODO: timeout
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)
@doc false
def get_commander(socket) do
controller = socket.assigns.controller
controller.__drab__()[:commander]
end
# returns the drab_pid from socket
@doc false
def pid(socket) do
socket.assigns.drab_pid
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
* `drab_store_storage` (default: :session_storage) - where to keep the Drab Strore, :memory, :local_storage or
:session_storage; data in memory is kept to the next page load, session storage persist until browser is
closed, and local storage is kept forever
"""
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"),
drab_store_storage: Application.get_env(:drab, :drab_store_storage, :session_storage)
}
end
end