nitro.erl 9.1 KB

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