api.tex 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. \section{API}
  2. \subsection{Update DOM \bf{wf:update}}
  3. You can update part of the page or DOM element with a given
  4. element or even raw HTML. N2O comes with NITRO template engine
  5. based on Erlang records syntax and optimized to be as fast as DTL or EEX template engines.
  6. You may use them with {\bf \#dtl} and {\bf \#eex} template NITRO elements.
  7. N2O Review application provides a sample how to use DTL templates.
  8. For using Nitrogen like DSL first you should include {\bf nitro} application to your
  9. rebar.config
  10. \vspace{1\baselineskip}
  11. \begin{lstlisting}
  12. {nitro,".*",{git,"git://github.com/synrc/nitro",{tag,"2.9"}}},
  13. \end{lstlisting}
  14. \vspace{1\baselineskip}
  15. And also plug it in headers to your erlang page module:
  16. \vspace{1\baselineskip}
  17. \begin{lstlisting}
  18. -include("nitro/include/nitro.hrl").
  19. \end{lstlisting}
  20. \vspace{1\baselineskip}
  21. Here is an example of simple {\bf \#span} NITRO element with an HTML counterpart.
  22. \vspace{1\baselineskip}
  23. \begin{lstlisting}
  24. wf:update(history,[#span{body="Hello"}]).
  25. \end{lstlisting}
  26. \vspace{1\baselineskip}
  27. It generates DOM update script and sends it to
  28. WebSocket channel for evaluation:
  29. \vspace{1\baselineskip}
  30. \begin{lstlisting}
  31. document.querySelector('#history')
  32. .outerHTML = '<span>Hello</span>';
  33. \end{lstlisting}
  34. \vspace{1\baselineskip}
  35. Companions are also provided for updating head and tail
  36. of the elements list: {\bf wf:insert\_top/2} and
  37. {\bf wf:insert\_bottom/2}. These are translated to appropriate
  38. JavaScript methods {\bf insertBefore} and {\bf appendChild} during rendering.
  39. \vspace{1\baselineskip}
  40. \begin{lstlisting}
  41. wf:insert_top(history,
  42. #panel{id=banner, body= [
  43. #span{ id=text,
  44. body = wf:f("User ~s logged in.",[wf:user()]) },
  45. #button{id=logout, body="Logout", postback=logout },
  46. #br{} ]}),
  47. \end{lstlisting}
  48. \vspace{1\baselineskip}
  49. Remember to envelop all elements in common root element before inserts.
  50. \paragraph{}
  51. For relative updates use {\bf wf:insert\_before/2} and {\bf wf:insert\_after/2}.
  52. To remove an element use {\bf wf:remove/2}.
  53. \paragraph{\bf Element Naming}
  54. You can specify element's id with Erlang atoms,
  55. lists or binaries. During rendering the value will be converted
  56. with {\bf wf:to\_list}. Conversion will be consistent only if you use atoms.
  57. Otherwise you need to care about illegal symbols for element accessors.
  58. \paragraph{}
  59. During page updates you can create additional elements with
  60. runtime generated event handlers, perform HTML rendering for
  61. template elements or even use distributed map/reduce to calculate view.
  62. You have to be aware that heavy operations will consume
  63. more power in the browser, but you can save it by rendering
  64. HTML on server-side. All DOM updates API works both using
  65. JavaScript/OTP and server pages.
  66. \paragraph{}
  67. List of elements you can use is given in {\bf Chapter 9}. You can also create
  68. your own elements with a custom render function.
  69. If you want to see how custom element are being implemented you may refer
  70. to {\bf synrc/extra} packages where some useful controls may be found like
  71. file uploader, calendar, autocompletion textboxlist and HTML editor.
  72. \newpage
  73. \subsection{Wire JavaScript \bf{wf:wire}}
  74. Just like HTML is generated from Elements, Actions are rendered into
  75. JavaScript to handle events raised in the browser. Actions are always
  76. transformed into JavaScript and sent through WebSockets pipe.
  77. \subsection*{Direct Wiring}
  78. There are two types of actions. First class are direct JavaScript
  79. strings provided directly as Erlang lists or via JavaScript/OTP
  80. transformations.
  81. \vspace{1\baselineskip}
  82. \begin{lstlisting}
  83. wf:wire("window.location='http://synrc.com'").
  84. \end{lstlisting}
  85. \subsection*{Actions Render}
  86. Second class actions are in fact Erlang records
  87. rendered during page load, server events or client events.
  88. \vspace{1\baselineskip}
  89. \begin{lstlisting}
  90. wf:wire(#alert{text="Hello!"}).
  91. \end{lstlisting}
  92. \vspace{1\baselineskip}
  93. However basic N2O actions that are part of N2O API, {\bf wf:update} and {\bf wf:redirect},
  94. are implemented as Erlang records as given in the example. If you need deferred
  95. rendering of JavaScript, you can use Erlang records instead of direct wiring with
  96. Erlang lists or JavaScript/OTP.
  97. \paragraph{}
  98. Any action, wired with {\bf wf:wire}, is enveloped in {\bf \#wire\{actions=[]\}},
  99. which is also an action capable of polymorphic rendering of custom or built-in actions, specified in the list.
  100. Following nested action embedding is also valid:
  101. \vspace{1\baselineskip}
  102. \begin{lstlisting}
  103. wf:wire(#wire{actions=[#alert{text="N2O"}]}).
  104. \end{lstlisting}
  105. \vspace{1\baselineskip}
  106. You may try to see how internally wiring is working:
  107. \begin{lstlisting}
  108. > wf:actions().
  109. []
  110. > wf:wire(#alert{text="N2O"}).
  111. [#wire{ancestor = action,trigger = undefined,
  112. target = undefined,module = action_wire,
  113. actions = #alert{ancestor = action,
  114. trigger = undefined,
  115. target = undefined,
  116. module = action_alert,
  117. actions = undefined,
  118. source = [], text = "N2O"},
  119. source = []}]
  120. > iolist_to_binary(wf:render(wf:actions())).
  121. <<"alert(\"N2O\");">>
  122. \end{lstlisting}
  123. Consider wiring {\bf \#event} if you want to add listener to
  124. existed element on page:
  125. \vspace{1\baselineskip}
  126. \begin{lstlisting}
  127. > wf:wire(#event{target=btn,postback=evt,type=click}),
  128. []
  129. > rp(iolist_to_binary(wf:render(wf:actions()))).
  130. <<"{var x=qi('element_id'); x && x.addEventListener('cl
  131. ick',function (event){{ if (validateSources([])) ws.sen
  132. d(enc(tuple(atom('pickle'),bin('element_id'),bin('g2gCa
  133. AVkAAJldmQABWluZGV4ZAADZXZ0awAKZWxlbWVudF9pZGQABWV2ZW50
  134. aANiAAAFoWIAB8kuYgAOvJA='),[tuple(tuple(utf8_toByteArra
  135. y('element_id'),bin('detail')),event.detail)])));else c
  136. onsole.log('Validation Error'); }});};">>
  137. \end{lstlisting}
  138. \newpage
  139. \subsection{Message Bus {\bf wf:reg} and {\bf wf:send}}
  140. N2O uses {\bf gproc} process registry for managing async processes pools.
  141. It is used as a PubSub message bus for N2O communications.
  142. You can associate a process with the pool with {\bf wf:reg}
  143. and send a message to the pool with {\bf wf:send}.
  144. \vspace{1\baselineskip}
  145. \begin{lstlisting}
  146. loop() ->
  147. receive M ->
  148. wf:info(?MODULE, "P: ~p, M: ~p",[self(),M]) end, loop().
  149. \end{lstlisting}
  150. Now you can test it
  151. \begin{lstlisting}
  152. > spawn(fun() -> wf:reg(topic), loop() end).
  153. > spawn(fun() -> wf:reg(topic), loop() end).
  154. > wf:send(topic,"Hello").
  155. \end{lstlisting}
  156. It should print in REPL something like:
  157. \begin{lstlisting}
  158. > [info] P: <0.2012.0>, M: "Hello"
  159. > [info] P: <0.2015.0>, M: "Hello"
  160. \end{lstlisting}
  161. \paragraph{\bf Custom Registrator}
  162. You may want to replace built-in {\bf gproc} based PubSub registrator
  163. with something more robust like MQTT and AMQP or something more
  164. internal like {\bf pg2}. All you need is to implement following API:
  165. \vspace{1\baselineskip}
  166. \begin{lstlisting}
  167. -module(mqtt_mq).
  168. -compile(export_all).
  169. send(Topic, Message) -> mqtt:publish(Topic, Message).
  170. reg(Topic) -> mqtt:subscribe(Topic, Message).
  171. reg(Topic,Tag) -> mqtt:subscribe(Topic, Tag, Message).
  172. unreg(Topic) -> mqtt:unsubscribe(Topic).
  173. \end{lstlisting}
  174. \vspace{1\baselineskip}
  175. And set it in runtime:
  176. \vspace{1\baselineskip}
  177. \begin{lstlisting}
  178. > application:set_env(n2o,mq,mqtt_mq).
  179. \end{lstlisting}
  180. \subsection{Async Processes {\bf wf:async} and {\bf wf:flush}}
  181. Function {\bf wf:async/2} creates Erlang process, which communicate with the primary page
  182. process by sending messages. {\bf wf:flush/0} should be called to redirect all updates and
  183. wire actions back to the page process from its async counterpart. But function {\bf wf:flush/1}
  184. has completly another meaning, it uses pubsub to deliver a rendered actions in async worker to
  185. any process, previously registered with {\bf wf:reg/1}, by its topic.
  186. Usually you send messages to async processes over N2O
  187. message bus {\bf wf:send/2} which is similar to how {\bf wf:flush/1} works.
  188. But you can use also {\bf n2o\_async:send/2} selectively to async worker what reminds
  189. {\bf wf:flush/0}. In following
  190. example different variants are gives, both incrementing counter by 2. Also notice
  191. the async process initialization through {\bf init} message. It is not nessesary
  192. to include init clause to async looper.
  193. \vspace{1\baselineskip}
  194. \begin{lstlisting}
  195. body() -> [ #span { id=display, body="0"},
  196. #button { id=send, body="Inc",
  197. postback=inc} ].
  198. event(init) -> wf:async("counter",fun loop/1);
  199. event(inc) -> wf:send(counter,up),
  200. n2o_async:send("counter",up).
  201. loop(init) -> wf:reg(counter), put(counter,0);
  202. loop(up) -> C = get(counter) + 1,
  203. put(counter,C),
  204. wf:update(display,
  205. #span{id=display,body=wf:to_binary(C)}),
  206. wf:flush().
  207. \end{lstlisting}
  208. \vspace{1\baselineskip}
  209. \paragraph{\bf Process Naming}
  210. The name of async process is globally unique. There are two
  211. versions, {\bf wf:async/1} and {\bf wf:async/2}. In the given example
  212. the name of async process is specified as ``counter'', otherwise,
  213. if the first parameter was not specified, the default name ``looper''
  214. will be used. Internally each async process includes custom key which
  215. is settled by default to session id.
  216. \newpage
  217. So let's mimic {\bf session\_id} and {\bf \#cx} in the shell:
  218. \vspace{1\baselineskip}
  219. \begin{lstlisting}
  220. > put(session_id,<<"d43adcc79dd64393a1eb559227a2d3fd">>).
  221. undefined
  222. > wf:context(wf:init_context(undefined)).
  223. {cx,[{query,n2o_query},
  224. {session,n2o_session},
  225. {route,routes}],
  226. [],[],index,undefined,[],
  227. undefined,[],undefined,[]}
  228. > wf:async("ho!",
  229. fun(X) -> io:format("Received: ~p~n",[X]) end).
  230. index:Received: init
  231. {<0.507.0>,{async,
  232. {"ho!",<<"d43adcc79dd64393a1eb559227a2d3fd">>}}}
  233. > supervisor:which_children(n2o_sup).
  234. [{{async,
  235. {"counter",<<"d43adcc79dd64393a1eb559227a2d3fd">>}},
  236. <0.11564.0>,worker,
  237. [n2o_async]}]
  238. \end{lstlisting}
  239. \vspace{1\baselineskip}
  240. Async workers suppors both sync and async messages, you may use {\bf gen\_server}
  241. for calling by pid, {\bf n2o\_async} for named or even built-in erlang way of
  242. sending messages. All types of handlilng like info, cast and call are supported.
  243. \vspace{1\baselineskip}
  244. \begin{lstlisting}
  245. > pid(0,507,0) ! "hey".
  246. Received: "hey"
  247. ok
  248. > n2o_async:send("ho!","hola").
  249. Received: "hola"
  250. ok
  251. > gen_server:call(pid(0,507,0),"sync").
  252. Received: "sync"
  253. ok
  254. \end{lstlisting}
  255. \vspace{1\baselineskip}
  256. \subsection{Parse URL and Context parameters {\bf wf:q} and {\bf wf:qp}}
  257. These are used to extract URL parameters or read from the process context.
  258. {\bf wf:q} extracts variables from the context stored by controls postbacks.
  259. {\bf wf:qp} extracts variables from URL params provieded by cowboy bridge.
  260. {\bf wf:qc} extracts variables from {\bf \#cx.params} context parsed with
  261. custom query handler during endpoint initialization usually performed
  262. inside N2O with something like.
  263. \vspace{1\baselineskip}
  264. \begin{lstlisting}
  265. Ctx = wf:init_context(Req),
  266. NewCtx = wf:fold(init,Ctx#cx.handlers,Ctx),
  267. wf:context(NewCtx),
  268. \end{lstlisting}
  269. \vspace{1\baselineskip}
  270. \newpage
  271. \subsection{Render {\bf wf:render} or {\bf nitro:render}}
  272. Render elements or actions with common render. Rendering is usually
  273. done automatically inside N2O, when you use DOM or Wiring API, but sometime you may
  274. need manual render, e.g. in static site generators and other NITRO applications
  275. which couldn't be even dependent from N2O. For that purposes you may use NITRO API
  276. \vspace{1\baselineskip}
  277. \begin{lstlisting}
  278. > nitro:render(#button{id=id,postback=signal}).
  279. <<"<button id=\"id\" type=\"button\"></button>">>
  280. \end{lstlisting}
  281. \vspace{1\baselineskip}
  282. \paragraph{}
  283. This is simple sample you may use in static site generators, but in N2O context
  284. you also may need to manual render JavaScript actions produced during HTML rendering.
  285. First of all you should know that process in which you want to render should be
  286. initialized with N2O {\bf \#cx} context. Here is example of JavaScript
  287. produced during previous {\bf \#button} rendering:
  288. \vspace{1\baselineskip}
  289. \begin{lstlisting}
  290. > wf:context(wf:init_context([])).
  291. undefined
  292. > rp(iolist_to_binary(nitro:render(wf:actions()))).
  293. <<"{var x=qi('id'); x && x.addEventListener('click',
  294. function (event){{ if (validateSources([])) ws.send(
  295. enc(tuple(atom('pickle'),bin('id'),bin('g2gCaAVkAAJl
  296. dmQABWluZGV4ZAAGc2lnbmFsawACaWRkAAVldmVudGgDYgAABaFi
  297. AAbo0GIACnB4'),[tuple(tuple(utf8_toByteArray('id'),b
  298. in('detail')),event.detail)])));else console.log('Va
  299. lidation Error'); }});};">>
  300. \end{lstlisting}
  301. \vspace{1\baselineskip}
  302. \newpage
  303. \paragraph{}
  304. Here is another more complex example of menu rendering using NITRO DSL:
  305. \vspace{1\baselineskip}
  306. \begin{lstlisting}
  307. menu(Files,Author) ->
  308. #panel{id=navcontainer,body=[#ul{id=nav,body=[
  309. #li{body=[#link{href="#",body="Navigation"},#ul{body=[
  310. #li{body=#link{href="/1.htm",body="Root"}},
  311. #li{body=#link{href="../1.htm",body="Parent"}},
  312. #li{body=#link{href="1.htm",body="This"}}]}]},
  313. #li{body=[#link{href="#",body="Download"},#ul{body=[
  314. #li{body=#link{href=F,body=F}}|| F <- Files ] }]},
  315. #li{body=[#link{href="#",body="Translations"},#ul{body=[
  316. #li{body=#link{href="#",body=Author}}]}]}]}]}.
  317. \end{lstlisting}
  318. \vspace{1\baselineskip}
  319. \vspace{1\baselineskip}
  320. \begin{lstlisting}
  321. > rp(iolist_to_binary(wf:render(menu(["1","2"],"5HT")))).
  322. <<"<div id=\"navcontainer\"><ul id=\"nav\"><li>
  323. <a href=\"#\">Navigation</a><ul><li><a href=\"/
  324. 1.htm\">Root</a></li><li><a href=\"../1.htm\">P
  325. arent</a></li><li><a href=\"1.htm\">This</a></l
  326. i></ul></li><li><a href=\"#\">Download</a><ul><
  327. li><a href=\"1\">1</a></li><li><a href=\"2\">2<
  328. /a></li></ul></li><li><a href=\"#\">Translation
  329. s</a><ul><li><a href=\"#\">5HT</a></li></ul></l
  330. i></ul></div>">>
  331. \end{lstlisting}
  332. \vspace{1\baselineskip}
  333. \paragraph{}
  334. Also notice some helpful functions to preprocess HTML and JavaScript
  335. escaping to avois XSS attacks:
  336. \vspace{1\baselineskip}
  337. \begin{lstlisting}
  338. > wf:html_encode(wf:js_escape("alert('N2O');")).
  339. "alert(\\&#39;N2O\\&#39;);"
  340. \end{lstlisting}
  341. \vspace{1\baselineskip}
  342. \subsection{Redirects {\bf wf:redirect}}
  343. Redirects are implemented not with HTTP headers, but with JavaScript action modifying {\bf window.location}.
  344. This saves login context information which is sent in the first packet upon establishing a WebSocket connection.
  345. \subsection{Session Information {\bf wf:session}}
  346. Store any session information in ETS tables. Use {\bf wf:user}, {\bf wf:role} for
  347. login and authorization. Consult {\bf AVZ} library documentation.
  348. \newpage
  349. \subsection{Bridge information {\bf wf:header} and {\bf wf:cookie}}
  350. You can read and issue cookie and headers information using internal Web-Server routines.
  351. You can also read peer IP with {\bf wf:peer}. Usually you do Bridge operations
  352. inside handlers or endpoints.
  353. \begin{lstlisting}
  354. wf:cookies_req(?REQ),
  355. wf:cookie_req(Name,Value,Path,TTL,Req)
  356. \end{lstlisting}
  357. You can set cookies for the page using public cookies API during initial page rendering.
  358. \begin{lstlisting}
  359. body() -> wf:cookie("user","Joe"), [].
  360. \end{lstlisting}
  361. You should use wiring inside WebSocket events:
  362. \begin{lstlisting}
  363. event(_) ->
  364. wf:wire(wf:f("document.cookie='~s=~s'",["user","Joe"])).
  365. \end{lstlisting}