-
Notifications
You must be signed in to change notification settings - Fork 43
/
drab.ex
700 lines (563 loc) · 22.2 KB
/
drab.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
defmodule Drab do
@moduledoc """
Drab allows to query and manipulate the User Interface directly from the Phoenix server backend.
Drab operates on top of the Phoenix application, to run it you must already have it configured.
In case you operate the app under an umbrella, all Drab configuration and installation should
be done in the Web application (in most cases the one ending with `_web`).
All Drab functions (callbacks and event handlers) should be placed in a module called
a 'commander'. It is very similar to controller, but it does not render any pages - it works
with the live page instead. For example, pages generated by `DrabExample.PageController` are
handled by commander with the corresponding name, in this case `DrabExample.PageCommander`:
defmodule DrabExample.PageCommander do
use Drab.Commander
onload :page_loaded
# Drab Callbacks
def page_loaded(socket) do
set_prop socket, "div.jumbotron h2", innerHTML: "This page has been DRABBED"
end
# Drab Events
defhandler button_clicked(socket, sender) do
set_prop socket, this(sender), innerText: "already clicked"
end
end
More on commander is in `Drab.Commander` documentation.
Drab handler are launched from the client (browser) side by running javascript function
[`Drab.exec_elixir()`](Drab.Client.html#module-drab-exec_elixir-elixir_function_name-argument),
or defining the handler function name directly in the html:
<button drab-click="button_clicked">Clickety click</button>
More on event handlers in `Drab.Core` documentation.
## Debugging Drab in IEx
When started with iex (`iex -S mix phx.server`) Drab shows the helpful message on how to
debug its functions:
Started Drab for /drab/docs, handling events in DrabPoc.DocsCommander
You may debug Drab functions in IEx by copy/paste the following:
import Drab.{Core, Query, Modal, Waiter}
socket = Drab.get_socket(pid("0.443.0"))
Examples:
socket |> select(:htmls, from: "h4")
socket |> exec_js("alert('hello from IEx!')")
socket |> alert("Title", "Sure?", buttons: [ok: "Azaliż", cancel: "Poniechaj"])
All you need to do is to copy/paste the line with `socket = ...` and now you can run Drab function
directly from IEx, observing the results on the running browser in the realtime.
## Modules
Drab is modular. You may choose which modules to use in the specific Commander by using `:module`
option in `use Drab.Commander` directive or set it globally by `:default_modules` config option.
By default, `Drab.Live`, `Drab.Element` and `Drab.Modal` are loaded.
Every module must have the corresponding javascript template, which is added to the client code
in case the module is loaded. This is why it is good to keep the modules list small, if you are
not using all modules.
`Drab.Core` module is always loaded.
### List of Drab Modules
#### `Drab.Core`
Contains core functions, like `exec_js`. It is always loaded, as it is essential for the rest of
Drab.
#### `Drab.Live`, the living assigns
This module is responsible for the living assigns. Contains function to push (`poke`) and pull
(`peek`) new assign values to the browser, live. Works only with pages compiled with
`Drab.Live.EExEngine` (pages with `.drab` extension).
#### `Drab.Element`, DOM element manipulation
Use functions from this module to get (`query`) or set (`set_prop`) properties or attributes
of DOM elements. All functions are based on CSS selectors.
#### `Drab.Modal`, Bootstrap modal window
This module contains only one function, `modal`, which shows synchronous modal windows. It
requires Bootstrap to work. Good to ask for a customer input.
#### `Drab.Waiter`, waits for the user input
This is an optional module, so must be listed in `:module` option in `use Drab.Commander`
directive or in `:default_modules` config option. Analogically to modal, waits for the user input.
#### `Drab.Query`, the jQuery module
This is an optional module, so must be listed in `:module` option in `use Drab.Commander`
directive or in `:default_modules` config option. Also, jQuery must be available as a global
(see "Manuall Installation" in `README`). `Drab.Query` has a number of useful functions, brings
jQuery to the server side.
#### `Drab.Browser`, browser related functions
This module is standalone (does not contain its own JS), so it does not have to be listed in
`use Drab.Commander` or in the setup. Contains browser related functions, like get the local
time, language or set the url in the browser bar.
## Handling Exceptions
Drab intercepts all exceptions from event handler function and let it die, but before it presents
the error message in the logs and an alert for a user on the page.
By default it is just an `alert()`, but you can easly override it by creating the template in the
`priv/templates/drab/drab.error_handler.js` folder with your own javascript presenting the
message. You may use the local variable `message` there to get the exception description, like:
alert(<%= message %>);
## Drab in production and behind a proxy
When using in production, an app is often behind an apache/nginx server for domain virtualization
or balancing, so the external port (80) is different from the actual app port (i.e. 4000).
The necessary mapping between the two ports is usually done by configuring a proxy,
but _a particularly care have to be taken to correctly handle_ `websocket` _calls_,
as they are at the core of Drab mechanism to communicate between the client browser and the backend server.
You can find more information and examples to how to configure your nxinx or apache environments
on the Drab wiki page at https://github.com/grych/drab/wiki/Drab-in-production-and-behind-a-proxy
## Learnig Drab
There is a [tutorial/demo page](https://tg.pl/drab).
The point to start reading docs should be `Drab.Core`.
"""
require Logger
use GenServer
@type t :: %Drab{
store: map,
commander: atom,
commanders: list,
controller: atom,
socket: Phoenix.Socket.t(),
topics: list,
priv: map
}
defstruct store: %{},
commander: nil,
commanders: [],
controller: nil,
socket: nil,
topics: [],
priv: %{}
@doc false
@spec start_link(Phoenix.Socket.t()) :: GenServer.on_start()
def start_link(socket) do
GenServer.start_link(__MODULE__, %Drab{
commander: Drab.get_commander(socket),
commanders: Drab.get_commanders(socket),
controller: Drab.get_controller(socket)
})
end
@doc false
@spec init(t) :: {:ok, t}
def init(state) do
Process.flag(:trap_exit, true)
{:ok, state}
end
@doc false
@spec terminate(any, t) :: {:noreply, t}
def terminate(_reason, %Drab{store: store, commander: commander, socket: socket} = state) do
if commander.__drab__().ondisconnect do
:ok =
apply(commander, commander_config(commander).ondisconnect, [
store,
socket.assigns[:__session]
])
end
{:noreply, state}
end
@doc false
@spec handle_info(tuple, t) :: {:noreply, t}
def handle_info({:EXIT, pid, :normal}, state) when pid != self() do
# ignore exits of the subprocesses
{:noreply, state}
end
@doc false
def handle_info({:EXIT, pid, :killed}, state) when pid != self() do
failed(state.socket, %RuntimeError{message: "Drab Process #{inspect(pid)} has been killed."})
{:noreply, state}
end
@doc false
def handle_info({:EXIT, pid, {reason, stack}}, state) when pid != self() do
# subprocess died
Logger.error("""
Drab Process #{inspect(pid)} died because of #{inspect(reason)}
#{Exception.format_stacktrace(stack)}
""")
{:noreply, state}
end
@doc false
@spec handle_cast(tuple, t) :: {:noreply, t}
def handle_cast({:onconnect, socket, payload}, %Drab{commander: commander} = state) do
socket = transform_socket(payload["payload"], socket, state)
Drab.Core.save_store(socket, socket.assigns[:__store])
Drab.Core.save_socket(socket)
onconnect = commander_config(commander).onconnect
handle_callback(socket, commander, onconnect)
for shared_commander <- state.commanders do
onconnect = commander_config(shared_commander).onconnect
handle_callback(socket, shared_commander, onconnect)
end
if Drab.Config.get(:presence) do
Drab.Config.get(:presence, :module).start(socket, socket.topic)
end
{:noreply, state}
end
@doc false
def handle_cast({:onload, socket, payload}, %Drab{commander: commander} = state) do
socket = transform_socket(payload["payload"], socket, state)
onload = commander_config(commander).onload
handle_callback(socket, commander, onload)
for shared_commander <- state.commanders do
onload = commander_config(shared_commander).onload
handle_callback(socket, shared_commander, onload)
end
{:noreply, state}
end
# casts for update values from the state
Enum.each([:store, :socket, :priv, :topics], fn name ->
msg_name = String.to_atom("set_#{name}")
@doc false
def handle_cast({unquote(msg_name), value}, state) do
new_state = Map.put(state, unquote(name), value)
{:noreply, new_state}
end
end)
@doc false
# any other cast is an event handler
def handle_cast({event_name, socket, payload, event_handler_function, reply_to}, state) do
handle_event(socket, event_name, event_handler_function, payload, reply_to, state)
end
# calls for get values from the state
Enum.each([:store, :socket, :priv, :topics], fn name ->
msg_name = String.to_atom("get_#{name}")
@doc false
def handle_call(unquote(msg_name), _from, state) do
value = Map.get(state, unquote(name))
{:reply, value, state}
end
end)
@spec handle_callback(Phoenix.Socket.t(), atom, atom) :: Phoenix.Socket.t()
defp handle_callback(socket, commander, callback) do
if callback do
spawn_link(fn ->
try do
Process.put(:__drab_event_handler_or_callback, true)
apply(commander, callback, [socket])
rescue
e ->
failed(socket, e, Exception.format_stacktrace(System.stacktrace()))
end
end)
end
socket
end
@spec transform_payload(map, t) :: map
defp transform_payload(payload, state) do
all_modules = DrabModule.all_modules_for(state.commander.__drab__().modules)
# transform payload via callbacks in DrabModules
Enum.reduce(all_modules, payload, fn m, p ->
m.transform_payload(p, state)
end)
end
@spec transform_socket(map, Phoenix.Socket.t(), t) :: Phoenix.Socket.t()
defp transform_socket(payload, socket, state) do
all_modules = DrabModule.all_modules_for(state.commander.__drab__().modules)
# transform socket via callbacks
Enum.reduce(all_modules, socket, fn m, s ->
m.transform_socket(s, payload, state)
end)
end
@spec handle_event(Phoenix.Socket.t(), any, atom, map, atom, t) :: {:noreply, t}
defp handle_event(
socket,
_event_name,
event_handler_function,
payload,
reply_to,
%Drab{commander: commander_module, controller: controller_module} = state
) do
spawn_link(fn ->
try do
Process.put(:__drab_event_handler_or_callback, true)
argument = payload["__additional_argument"]
payload = Map.delete(payload, "__additional_argument")
{commander_module, event_handler} =
event_handler(commander_module, event_handler_function)
raise_if_handler_is_not_public(commander_module, event_handler)
raise_if_commander_is_not_shared(commander_module, controller_module)
payload = transform_payload(payload, state)
socket = transform_socket(payload, socket, state)
commander_cfg = commander_config(commander_module)
# run before_handlers first
returns_from_befores =
Enum.map(
callbacks_for(event_handler, commander_cfg.before_handler),
fn callback_handler ->
apply(commander_module, callback_handler, [socket, payload])
end
)
# if ANY of them fail (return false or nil), do not proceed
unless Enum.any?(returns_from_befores, &(!&1)) do
# run actuall event handler
arguments =
if argument,
do: [socket, payload, argument],
else: [socket, payload]
returned_from_handler = apply(commander_module, event_handler, arguments)
Enum.map(
callbacks_for(event_handler, commander_cfg.after_handler),
fn callback_handler ->
apply(commander_module, callback_handler, [socket, payload, returned_from_handler])
end
)
end
rescue
e ->
failed(socket, e, Exception.format_stacktrace(System.stacktrace()))
after
# push reply to the browser, to re-enable controls
push_reply(socket, reply_to, commander_module, event_handler_function)
end
end)
{:noreply, state}
end
@spec event_handler(atom, String.t()) :: {atom | nil, atom}
defp event_handler(original_module, function_name) do
case String.split(function_name, ".") do
[function] ->
{original_module, String.to_existing_atom(function)}
module_and_function ->
module = module_and_function |> List.delete_at(-1) |> Module.safe_concat()
unless Code.ensure_loaded?(module) do
raise """
module #{inspect(module)} does not exist.
"""
end
function = module_and_function |> List.last() |> String.to_existing_atom()
{module, function}
end
end
@spec raise_if_handler_is_not_public(atom, atom) :: {atom, atom} | no_return
defp raise_if_handler_is_not_public(module, function) do
unless is_public?(module, function) do
raise Drab.ConfigurationError,
message: """
handler #{inspect(module)}.#{function} must be declared as public in the commander.
Please use Drab.Commander.public or Drab.Commander.defhandler macro as following:
defhandler #{function}(socket, sender) do
...
end
"""
end
{module, function}
end
@spec raise_if_commander_is_not_shared(atom, atom) :: {atom, atom} | no_return
defp raise_if_commander_is_not_shared(commander_module, controller_module) do
unless is_commander_declared?(commander_module, controller_module) do
raise Drab.ConfigurationError,
message: """
shared commander #{inspect(commander_module)} is not declared in #{
inspect(controller_module)
}
Please whitelist all shared commanders in the controller:
use Drab.Controller, commanders: [#{inspect(commander_module)}]
"""
end
{commander_module, controller_module}
end
@spec is_public?(atom, atom) :: boolean | no_return
defp is_public?(module, function) do
if {:__drab__, 0} in apply(module, :__info__, [:functions]) do
options = apply(module, :__drab__, [])
function in Map.get(options, :public_handlers, [])
else
raise Drab.ConfigurationError,
message: """
#{module} is not a Drab module.
"""
end
end
@spec is_commander_declared?(atom, atom) :: boolean
defp is_commander_declared?(commander, controller) do
cond do
commander in Drab.Config.drab_internal_commanders() ->
true
commander.__drab__().controller == controller ->
true
{:__drab__, 0} in apply(controller, :__info__, [:functions]) ->
commander in controller.__drab__().commanders
true ->
false
end
end
@spec failed(Phoenix.Socket.t(), Exception.t()) :: :ok
defp failed(socket, e, stacktrace \\ "") do
error = """
Drab Handler failed with the following exception:
#{Exception.format_banner(:error, e)}
#{stacktrace}
"""
Logger.error(error)
if socket do
js =
Drab.Template.render_template(
socket.endpoint,
"drab.error_handler.js",
message: Drab.Core.encode_js(error)
)
{:ok, _} = Drab.Core.exec_js(socket, js)
end
:ok
end
@spec push_reply(Phoenix.Socket.t(), atom, any, any) :: :ok
defp push_reply(socket, reply_to, _, _) do
Phoenix.Channel.push(socket, "event", %{
finished: reply_to
})
end
@doc false
# Returns the list of callbacks (before_handler, after_handler) defined in handler_config
@spec callbacks_for(atom, list) :: list
def callbacks_for(_, []) do
[]
end
@doc false
def callbacks_for(event_handler_function, handler_config) do
handler_config
|> Enum.map(fn {callback_name, callback_filter} ->
case callback_filter do
[] ->
callback_name
[only: handlers] ->
if event_handler_function in handlers, do: callback_name, else: false
[except: handlers] ->
if event_handler_function in handlers, do: false, else: callback_name
_ ->
false
end
end)
|> Enum.filter(& &1)
end
# setter and getter functions
Enum.each([:store, :socket, :priv, :topics], fn name ->
get_name = String.to_atom("get_#{name}")
update_name = String.to_atom("set_#{name}")
@doc false
def unquote(get_name)(pid) do
GenServer.call(pid, unquote(get_name))
end
@doc false
def unquote(update_name)(pid, new_value) do
GenServer.cast(pid, {unquote(update_name), new_value})
end
end)
@doc false
@spec push_and_wait_for_response(Phoenix.Socket.t(), pid, String.t(), Keyword.t(), Keyword.t()) ::
Drab.Core.result()
def push_and_wait_for_response(socket, pid, message, payload \\ [], options \\ []) do
if Process.alive?(Drab.pid(socket)) do
ref = make_ref()
push(socket, pid, ref, message, payload)
timeout = options[:timeout] || Drab.Config.get(socket.endpoint, :browser_response_timeout)
receive do
{:got_results_from_client, status, ^ref, reply} ->
{status, reply}
after
timeout ->
# TODO: message is still in a queue
{:error, :timeout}
end
else
{:error, :disconnected}
end
end
@doc false
@spec push_and_wait_forever(Phoenix.Socket.t(), pid, String.t(), Keyword.t()) ::
Drab.Core.result()
def push_and_wait_forever(socket, pid, message, payload \\ []) do
push(socket, pid, nil, message, payload)
receive do
{:got_results_from_client, status, _, reply} ->
{status, reply}
end
end
@doc false
@spec push(Phoenix.Socket.t(), pid, reference | nil, String.t(), Keyword.t()) :: :ok | no_return
def push(socket, pid, ref, message, payload \\ []) do
do_push_or_broadcast(socket, pid, ref, message, payload, &Phoenix.Channel.push/3)
end
@doc false
@spec broadcast(Drab.Core.subject(), pid | nil, String.t(), Keyword.t()) :: :ok | no_return
def broadcast(subject, pid, message, payload \\ [])
def broadcast(%Phoenix.Socket{} = socket, pid, message, payload) do
do_push_or_broadcast(socket, pid, nil, message, payload, &Phoenix.Channel.broadcast/3)
end
def broadcast({endpoint, subject}, _pid, message, payload)
when is_binary(subject) and is_atom(endpoint) do
Phoenix.Channel.Server.broadcast(
Drab.Config.pubsub(endpoint),
subject,
message,
Map.new(payload)
)
end
def broadcast(subject, _pid, message, payload) when is_binary(subject) do
Phoenix.Channel.Server.broadcast(
Drab.Config.default_pubsub(),
subject,
message,
Map.new(payload)
)
end
@doc false
def broadcast(topics, _pid, message, payload) when is_list(topics) do
for topic <- topics do
broadcast(topic, nil, message, payload)
end
:ok
end
@spec do_push_or_broadcast(
Phoenix.Socket.t() | Drab.Core.subject(),
pid | nil,
reference | nil,
String.t(),
Keyword.t(),
function
) :: :ok | no_return
defp do_push_or_broadcast(socket, pid, ref, message, payload, function) do
m = payload |> Enum.into(%{}) |> Map.merge(%{sender: tokenize(socket, {pid, ref})})
function.(socket, message, m)
end
@doc false
@spec tokenize(Phoenix.Socket.t() | Plug.Conn.t(), term(), String.t()) :: String.t()
def tokenize(socket, what, salt \\ "drab token") do
Phoenix.Token.sign(socket, salt, what)
end
@doc false
@spec detokenize(Phoenix.Socket.t() | Plug.Conn.t(), String.t(), String.t()) ::
term() | no_return
def detokenize(socket, token, salt \\ "drab token") do
max_age = Drab.Config.get(socket.endpoint, :browser_response_timeout) + 1000
case Phoenix.Token.verify(socket, salt, token, max_age: max_age) do
{:ok, detokenized} ->
detokenized
{:error, reason} ->
# let it die
raise "Can't verify the token `#{salt}`: #{inspect(reason)}"
end
end
# returns the commander name for the given controller (assigned in socket)
@doc false
@spec get_commander(Phoenix.Socket.t()) :: atom
def get_commander(socket) do
socket.assigns.__commander
end
# returns the list of shared commanders name for the given controller (assigned in socket)
@doc false
@spec get_commanders(Phoenix.Socket.t()) :: list
def get_commanders(socket) do
controller = get_controller(socket)
if controller && {:__drab__, 0} in apply(controller, :__info__, [:functions]) do
controller.__drab__().commanders
else
[]
end
# socket.assigns.__commanders
end
# returns the controller name used with the socket
@doc false
@spec get_controller(Phoenix.Socket.t()) :: atom
def get_controller(socket) do
socket.assigns.__controller
end
# returns the view name used with the socket
@doc false
@spec get_view(Phoenix.Socket.t()) :: atom
def get_view(socket) do
socket.assigns.__view
end
# returns the drab_pid from socket
@doc "Extract Drab PID from the socket"
@spec pid(Phoenix.Socket.t()) :: pid
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
@spec commander_config(atom) :: map
defp commander_config(module) do
module.__drab__()
end
end