nitro.erl 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. -module(nitro).
  2. -include_lib("nitro/include/cx.hrl").
  3. -include_lib("nitro/include/nitro.hrl").
  4. -include_lib("nitro/include/event.hrl").
  5. -compile([export_all, nowarn_export_all]). % todo export
  6. atom(List) when erlang:is_list(List) ->
  7. string:join([ nitro:to_list(L) || L <- List], "_");
  8. atom(Scalar) -> nitro:to_list(Scalar).
  9. q(Key) -> q(Key, []).
  10. q(Key, Def) ->
  11. case erlang:get(Key) of
  12. undefined -> Def;
  13. Val -> Val
  14. end.
  15. qc(Key) ->
  16. CX = erlang:get(context),
  17. qc(Key,CX#cx.req).
  18. qc(Key, Req) ->
  19. proplists:get_value(nitro:to_binary(Key), cowboy_req:parse_qs(Req)).
  20. f(S) -> f(S, []).
  21. f(S, Args) -> lists:flatten(io_lib:format(S, Args)).
  22. coalesce([]) -> undefined;
  23. coalesce([H]) -> H;
  24. coalesce([undefined|T]) -> coalesce(T);
  25. coalesce([[]|T]) -> coalesce(T);
  26. coalesce([H|_]) -> H.
  27. jse(X) -> js_escape(X).
  28. hte(X) when erlang:is_binary(X) ->
  29. nitro:to_binary(nitro_conv:html_encode(X));
  30. hte(X) -> nitro_conv:html_encode(X).
  31. js_escape(Value) ->
  32. nitro_conv:js_escape(Value).
  33. -define(IS_STRING(Term),
  34. (erlang:is_list(Term) andalso Term /= [] andalso erlang:is_integer(erlang:hd(Term)))).
  35. to_list(L) when ?IS_STRING(L) -> L;
  36. to_list(L) when erlang:is_list(L) ->
  37. SubLists = [inner_to_list(X) || X <- L],
  38. lists:flatten(SubLists);
  39. to_list(A) -> inner_to_list(A).
  40. inner_to_list(A) when erlang:is_atom(A) -> erlang:atom_to_list(A);
  41. inner_to_list(B) when erlang:is_binary(B) -> erlang:binary_to_list(B);
  42. inner_to_list(I) when erlang:is_integer(I) -> erlang:integer_to_list(I);
  43. inner_to_list(L) when erlang:is_tuple(L) -> lists:flatten(io_lib:format("~p", [L]));
  44. inner_to_list(L) when erlang:is_list(L) -> L;
  45. inner_to_list(F) when erlang:is_float(F) -> erlang:float_to_list(F, [{decimals, 9}, compact]).
  46. to_atom(A) when erlang:is_atom(A) -> A;
  47. to_atom(B) when erlang:is_binary(B) -> to_atom(erlang:binary_to_list(B));
  48. to_atom(I) when erlang:is_integer(I) -> to_atom(erlang:integer_to_list(I));
  49. to_atom(F) when erlang:is_float(F) -> to_atom(erlang:float_to_list(F, [{decimals, 9}, compact]));
  50. to_atom(L) when erlang:is_list(L) -> erlang:list_to_atom(erlang:binary_to_list(erlang:list_to_binary(L))).
  51. to_binary(A) when erlang:is_atom(A) -> erlang:atom_to_binary(A, latin1);
  52. to_binary(B) when erlang:is_binary(B) -> B;
  53. to_binary(I) when erlang:is_integer(I) -> to_binary(erlang:integer_to_list(I));
  54. to_binary(F) when erlang:is_float(F) -> erlang:float_to_binary(F, [{decimals, 9}, compact]);
  55. to_binary(L) when erlang:is_list(L) -> erlang:iolist_to_binary(L);
  56. to_binary(X) when erlang:is_tuple(X) -> erlang:term_to_binary(X).
  57. -ifndef(PICKLER).
  58. -define(PICKLER, (application:get_env(n2z, pickler, nitro_conv))).
  59. -endif.
  60. pickle(Data) -> ?PICKLER:pickle(Data).
  61. depickle(SerializedData) -> ?PICKLER:depickle(SerializedData).
  62. prolongate() ->
  63. case application:get_env(n2z, session) of
  64. {ok, M} -> M:prolongate();
  65. undefined -> false
  66. end.
  67. authenticate(I, Auth) ->
  68. (application:get_env(n2z, session, n2z_session)):authenticate(I, Auth).
  69. render(X) -> wf_render:render(X).
  70. wire(Actions) -> action_wire:wire(Actions).
  71. unique_integer() -> erlang:unique_integer().
  72. temp_id() ->
  73. "auto" ++ integer_to_list(unique_integer() rem 1000000).
  74. html_encode(L, Fun) when erlang:is_function(Fun) ->
  75. Fun(L);
  76. html_encode(L, EncType) when erlang:is_atom(L) ->
  77. html_encode(nitro:to_list(L), EncType);
  78. html_encode(L, EncType) when erlang:is_integer(L) ->
  79. html_encode(erlang:integer_to_list(L),EncType);
  80. html_encode(L, EncType) when erlang:is_float(L) ->
  81. html_encode(erlang:float_to_list(L, [{decimals, 9}, compact]), EncType);
  82. html_encode(L, false) ->
  83. L;
  84. html_encode(L, true) ->
  85. L;
  86. html_encode(L, whites) ->
  87. html_encode_whites(nitro:to_list(lists:flatten([L]))).
  88. html_encode(<<>>) ->
  89. [];
  90. html_encode([]) ->
  91. [];
  92. html_encode([H|T]) ->
  93. case H of
  94. $< -> "&lt;" ++ html_encode(T);
  95. $> -> "&gt;" ++ html_encode(T);
  96. $" -> "&quot;" ++ html_encode(T);
  97. $' -> "&#39;" ++ html_encode(T);
  98. $& -> "&amp;" ++ html_encode(T);
  99. BigNum when erlang:is_integer(BigNum) andalso BigNum > 255 ->
  100. [$&,$# | nitro:to_list(BigNum)] ++ ";" ++ html_encode(T);
  101. Tup when erlang:is_tuple(Tup) ->
  102. erlang:throw({html_encode, encountered_tuple, Tup});
  103. _ ->
  104. [H|html_encode(T)]
  105. end.
  106. html_encode_whites([]) -> [];
  107. html_encode_whites([H|T]) ->
  108. case H of
  109. $\s -> "&nbsp;" ++ html_encode_whites(T);
  110. $\t -> "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" ++ html_encode_whites(T);
  111. $< -> "&lt;" ++ html_encode_whites(T);
  112. $> -> "&gt;" ++ html_encode_whites(T);
  113. $" -> "&quot;" ++ html_encode_whites(T);
  114. $' -> "&#39;" ++ html_encode_whites(T);
  115. $& -> "&amp;" ++ html_encode_whites(T);
  116. $\n -> "<br>" ++ html_encode_whites(T);
  117. _ -> [H|html_encode_whites(T)]
  118. end.
  119. script() -> erlang:get(script).
  120. script(Script) -> erlang:put(script, Script).
  121. % Update DOM nitro:update
  122. update(Target, Elements) ->
  123. nitro:wire(#jq{target=Target, property=outerHTML, right=Elements, format="`~s`"}).
  124. insert_top(Tag, Target, Elements) ->
  125. {Render, _Ref, Actions} = render_html(Elements),
  126. nitro:wire(nitro:f(
  127. "qi('~s').insertBefore("
  128. "(function(){var div = qn('~s'); div.innerHTML = `~s`; return div.firstChild; })(),"
  129. "qi('~s').firstChild);",
  130. [Target, Tag, Render, Target])),
  131. nitro:wire(nitro:render(Actions)).
  132. insert_bottom(Tag, Target, Elements) ->
  133. {Render, _Ref, Actions} = render_html(Elements),
  134. nitro:wire(nitro:f(
  135. "(function(){ var div = qn('~s'); div.innerHTML = `~s`;"
  136. "qi('~s').appendChild(div.firstChild); })();",
  137. [Tag, Render, Target])),
  138. nitro:wire(nitro:render(Actions)).
  139. insert_before(Target, Elements) -> insert_adjacent(beforebegin, Target, Elements).
  140. insert_after(Target, Elements) -> insert_adjacent(afterend, Target, Elements).
  141. insert_adjacent(Command, Target, Elements) ->
  142. insert_adjacent(Command, Target, Elements, "qi").
  143. insert_adjacent(Command, Target, Elements, Q) ->
  144. {Render, _Ref, Actions} = render_html(Elements),
  145. nitro:wire(nitro:f("~s('~s').insertAdjacentHTML('~s', `~s`);", [Q, Target, Command, Render])),
  146. nitro:wire(nitro:render(Actions)).
  147. render_html(Elements) ->
  148. Pid = erlang:self(),
  149. Ref = erlang:make_ref(),
  150. erlang:spawn(fun() -> % todo : remove spawn
  151. R = nitro:render(Elements),
  152. Pid ! {R, Ref, nitro:actions()}
  153. end),
  154. {Render, Ref, Actions} = receive {_, Ref, _} = A -> A end,
  155. {Render, Ref, Actions}.
  156. actions() -> erlang:get(actions).
  157. actions(Ac) -> erlang:put(actions, Ac).
  158. insert_top(Target, Elements) when erlang:element(1, Elements) == tr ->
  159. insert_top(tbody, Target, Elements);
  160. insert_top(Target, Elements) ->
  161. insert_top('div', Target, Elements).
  162. insert_bottom(Target, Elements) when erlang:element(1, Elements) == tr ->
  163. insert_bottom(tbody, Target, Elements);
  164. insert_bottom(Target, Elements) ->
  165. insert_bottom('div', Target, Elements).
  166. clear(Target) ->
  167. nitro:wire("var x = qi('" ++ nitro:to_list(Target) ++ "');"
  168. "while(x && x.firstChild) x.removeChild(x.firstChild);").
  169. remove(Target) ->
  170. nitro:wire("var x = qi('" ++ nitro:to_list(Target) ++ "');"
  171. "x && x.parentNode.removeChild(x);").
  172. % Wire JavaScript nitro:wire
  173. state(Key) -> erlang:get(Key).
  174. state(Key, Value) -> erlang:put(Key, Value).
  175. % Redirect and purge connection nitro:redirect
  176. redirect(Url) -> nitro:wire(#jq{target='window', property=location, args=simple, right=Url}).
  177. %header(K, V) -> nitro:context((?CTX)#cx{req=cowboy_req:set_resp_header(K, V, ?CTX#cx.req)}).
  178. setAttr(Element, Attr, Value) ->
  179. nitro:wire("{ var x = qi('" ++ nitro:to_list(Element) ++ "');"
  180. "if(x) x.setAttribute('" ++ nitro:to_list(Attr) ++ "', '" ++ nitro:to_list(Value) ++ "'); }").
  181. style(Element, Style) ->
  182. setAttr(Element, "style", Style).
  183. style(Element, Style, Value) ->
  184. nitro:wire("{ var x = qi('" ++ nitro:to_list(Element) ++ "');"
  185. "if(x) x.style." ++ nitro:to_list(Style) ++ " = '" ++ nitro:to_list(Value) ++ "'; }").
  186. display(Element, Status) -> style(Element, "display", Status).
  187. show(Element) -> display(Element, block).
  188. hide(Element) -> display(Element, none).
  189. compact([]) -> "[]";
  190. compact("\n") -> "[]";
  191. compact([X|_]=Y) when erlang:is_tuple(X) ->
  192. [ compact(F) || F <- Y ];
  193. compact(Bin) when erlang:is_binary(Bin) ->
  194. unicode:characters_to_binary(Bin);
  195. compact(Tuple) when erlang:is_tuple(Tuple) ->
  196. Min = erlang:min(9, erlang:size(Tuple)),
  197. Fields = lists:zip(lists:seq(1, Min),
  198. lists:sublist(erlang:tuple_to_list(Tuple), 1, Min)),
  199. "{" ++ string:join([ io_lib:format("~s", [compact(F)]) || {_, F} <- Fields ], ",") ++ "}";
  200. compact(T) ->
  201. nitro:jse(nitro:to_list(T)).
  202. meg(X) -> erlang:integer_to_list(X div 1000000) ++ "M".
  203. rev(X) -> lists:reverse(X).
  204. num(S) -> case rev(S) of
  205. [$K|K] -> erlang:list_to_integer(rev(K)) * 1000;
  206. [$M|M] -> erlang:list_to_integer(rev(M)) * 1000 * 1000;
  207. [$G|G] -> erlang:list_to_integer(rev(G)) * 1000 * 1000 * 1000;
  208. [$T|T] -> erlang:list_to_integer(rev(T)) * 1000 * 1000 * 1000 * 1000
  209. end.
  210. cookie_expire(SecondsToLive) ->
  211. Seconds = calendar:datetime_to_gregorian_seconds(calendar:local_time()),
  212. DateTime = calendar:gregorian_seconds_to_datetime(Seconds + SecondsToLive),
  213. cow_date:rfc2109(DateTime).
  214. cookie(Id, Value) -> cookie(Id, Value, 2147483647). % expire never
  215. cookie(Id, Value, Expire) ->
  216. Format = "document.cookie='~s=~s; path=/; expires=~s';",
  217. nitro:wire(nitro:f(Format, [nitro:to_list(Id), nitro:to_list(Value), cookie_expire(Expire)])).
  218. cookies() ->
  219. cowboy_req:parse_cookies((erlang:get(context))#cx.req).
  220. cookie(Key) ->
  221. case lists:keyfind(Key, 1, cowboy_req:parse_cookies((erlang:get(context))#cx.req)) of
  222. false -> undefined;
  223. {_, Value} -> Value
  224. end.