nitro.erl 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. -module(nitro).
  2. -include_lib("nitro/include/cx.hrl").
  3. -include_lib("nitro/include/nitro.hrl").
  4. -compile(export_all).
  5. -behaviour(application).
  6. -export([start/2, stop/1, init/1]).
  7. q(Key) -> q(Key, []).
  8. q(Key, Default) ->
  9. case get(Key) of
  10. undefined -> Default;
  11. Value -> Value
  12. end.
  13. qc(Key) -> CX = get(context), qc(Key,CX#cx.req).
  14. qc(Key,Req) -> proplists:get_value(nitro:to_binary(Key),cowboy_req:parse_qs(Req)).
  15. start(_StartType, _StartArgs) -> supervisor:start_link({local, ?MODULE}, ?MODULE, []).
  16. stop(_State) -> ok.
  17. init([]) -> {ok, {{one_for_one, 5, 10}, []}}.
  18. f(S) -> f(S, []).
  19. f(S, Args) -> lists:flatten(io_lib:format(S, Args)).
  20. coalesce([]) -> undefined;
  21. coalesce([H]) -> H;
  22. coalesce([undefined|T]) -> coalesce(T);
  23. coalesce([[]|T]) -> coalesce(T);
  24. coalesce([H|_]) -> H.
  25. jse(X) -> js_escape(X).
  26. js_escape(undefined) -> [];
  27. js_escape(Value) when is_list(Value) -> binary_to_list(js_escape(iolist_to_binary(Value)));
  28. js_escape(Value) -> js_escape(Value, <<>>).
  29. js_escape(<<"\\", Rest/binary>>, Acc) -> js_escape(Rest, <<Acc/binary, "\\\\">>);
  30. js_escape(<<"\r", Rest/binary>>, Acc) -> js_escape(Rest, <<Acc/binary, "\\r">>);
  31. js_escape(<<"\n", Rest/binary>>, Acc) -> js_escape(Rest, <<Acc/binary, "\\n">>);
  32. js_escape(<<"\"", Rest/binary>>, Acc) -> js_escape(Rest, <<Acc/binary, "\\\"">>);
  33. js_escape(<<"'",Rest/binary>>,Acc) -> js_escape(Rest, <<Acc/binary, "\\'">>);
  34. js_escape(<<"<script", Rest/binary>>, Acc) -> js_escape(Rest, <<Acc/binary, "<scr\" + \"ipt">>);
  35. js_escape(<<"script>", Rest/binary>>, Acc) -> js_escape(Rest, <<Acc/binary, "scr\" + \"ipt>">>);
  36. js_escape(<<C, Rest/binary>>, Acc) -> js_escape(Rest, <<Acc/binary, C>>);
  37. js_escape(<<>>, Acc) -> Acc.
  38. -define(IS_STRING(Term), (is_list(Term) andalso Term /= [] andalso is_integer(hd(Term)))).
  39. to_list(L) when ?IS_STRING(L) -> L;
  40. to_list(L) when is_list(L) -> SubLists = [inner_to_list(X) || X <- L], lists:flatten(SubLists);
  41. to_list(A) -> inner_to_list(A).
  42. inner_to_list(A) when is_atom(A) -> atom_to_list(A);
  43. inner_to_list(B) when is_binary(B) -> binary_to_list(B);
  44. inner_to_list(I) when is_integer(I) -> integer_to_list(I);
  45. inner_to_list(L) when is_tuple(L) -> lists:flatten(io_lib:format("~p", [L]));
  46. inner_to_list(L) when is_list(L) -> L;
  47. inner_to_list(F) when is_float(F) -> float_to_list(F,[{decimals,9},compact]).
  48. to_atom(A) when is_atom(A) -> A;
  49. to_atom(B) when is_binary(B) -> to_atom(binary_to_list(B));
  50. to_atom(I) when is_integer(I) -> to_atom(integer_to_list(I));
  51. to_atom(F) when is_float(F) -> to_atom(float_to_list(F,[{decimals,9},compact]));
  52. to_atom(L) when is_list(L) -> list_to_atom(binary_to_list(list_to_binary(L))).
  53. to_binary(A) when is_atom(A) -> atom_to_binary(A,latin1);
  54. to_binary(B) when is_binary(B) -> B;
  55. to_binary(I) when is_integer(I) -> to_binary(integer_to_list(I));
  56. to_binary(F) when is_float(F) -> float_to_binary(F,[{decimals,9},compact]);
  57. to_binary(L) when is_list(L) -> iolist_to_binary(L).
  58. -ifndef(PICKLER).
  59. -define(PICKLER, (application:get_env(n2o,pickler,nitro_pickle))).
  60. -endif.
  61. pickle(Data) -> ?PICKLER:pickle(Data).
  62. depickle(SerializedData) -> ?PICKLER:depickle(SerializedData).
  63. depickle(SerializedData, TTLSeconds) -> ?PICKLER:depickle(SerializedData, TTLSeconds).
  64. render(X) -> wf_render:render(X).
  65. wire(Actions) -> action_wire:wire(Actions).
  66. unique_integer() -> erlang:unique_integer().
  67. temp_id() -> "auto" ++ integer_to_list(unique_integer() rem 1000000).
  68. html_encode(L,Fun) when is_function(Fun) -> Fun(L);
  69. html_encode(L,EncType) when is_atom(L) -> html_encode(nitro:to_list(L),EncType);
  70. html_encode(L,EncType) when is_integer(L) -> html_encode(integer_to_list(L),EncType);
  71. html_encode(L,EncType) when is_float(L) -> html_encode(float_to_list(L,[{decimals,9},compact]),EncType);
  72. html_encode(L, false) -> L;
  73. html_encode(L, true) -> L;
  74. html_encode(L, whites) -> html_encode_whites(nitro:to_list(lists:flatten([L]))).
  75. html_encode(<<>>) -> [];
  76. html_encode([]) -> [];
  77. html_encode([H|T]) ->
  78. case H of
  79. $< -> "&lt;" ++ html_encode(T);
  80. $> -> "&gt;" ++ html_encode(T);
  81. $" -> "&quot;" ++ html_encode(T);
  82. $' -> "&#39;" ++ html_encode(T);
  83. $& -> "&amp;" ++ html_encode(T);
  84. BigNum when is_integer(BigNum) andalso BigNum > 255 ->
  85. [$&,$# | nitro:to_list(BigNum)] ++ ";" ++ html_encode(T);
  86. Tup when is_tuple(Tup) -> throw({html_encode,encountered_tuple,Tup});
  87. _ -> [H|html_encode(T)]
  88. end.
  89. html_encode_whites([]) -> [];
  90. html_encode_whites([H|T]) ->
  91. case H of
  92. $\s -> "&nbsp;" ++ html_encode_whites(T);
  93. $\t -> "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" ++ html_encode_whites(T);
  94. $< -> "&lt;" ++ html_encode_whites(T);
  95. $> -> "&gt;" ++ html_encode_whites(T);
  96. $" -> "&quot;" ++ html_encode_whites(T);
  97. $' -> "&#39;" ++ html_encode_whites(T);
  98. $& -> "&amp;" ++ html_encode_whites(T);
  99. $\n -> "<br>" ++ html_encode_whites(T);
  100. _ -> [H|html_encode_whites(T)]
  101. end.
  102. script() -> get(script).
  103. script(Script) -> put(script,Script).
  104. % Update DOM nitro:update
  105. update(Target, Elements) ->
  106. nitro:wire(#jq{target=Target,property=outerHTML,right=Elements,format="'~s'"}).
  107. insert_top(Tag,Target, Elements) ->
  108. Pid = self(),
  109. Ref = make_ref(),
  110. spawn(fun() -> R = nitro:render(Elements), Pid ! {R,Ref,nitro:actions()} end),
  111. {Render,Ref,Actions} = receive {_, Ref, _} = A -> A end,
  112. nitro:wire(nitro:f(
  113. "qi('~s').insertBefore("
  114. "(function(){var div = qn('~s'); div.innerHTML = '~s'; return div.firstChild; })(),"
  115. "qi('~s').firstChild);",
  116. [Target,Tag,Render,Target])),
  117. nitro:wire(nitro:render(Actions)).
  118. insert_bottom(Tag, Target, Elements) ->
  119. Pid = self(),
  120. Ref = make_ref(),
  121. spawn(fun() -> R = nitro:render(Elements), Pid ! {R,Ref,nitro:actions()} end),
  122. {Render,Ref,Actions} = receive {_, Ref, _} = A -> A end,
  123. nitro:wire(nitro:f(
  124. "(function(){ var div = qn('~s'); div.innerHTML = '~s';"
  125. "qi('~s').appendChild(div.firstChild); })();",
  126. [Tag,Render,Target])),
  127. nitro:wire(nitro:render(Actions)).
  128. insert_adjacent(Command,Target, Elements) ->
  129. Pid = self(),
  130. Ref = make_ref(),
  131. spawn(fun() -> R = nitro:render(Elements), Pid ! {R,Ref,nitro:actions()} end),
  132. {Render,Ref,Actions} = receive {_, Ref, _} = A -> A end,
  133. nitro:wire(nitro:f("qi('~s').insertAdjacentHTML('~s', '~s');",[Target,Command,Render])),
  134. nitro:wire(nitro:render(Actions)).
  135. actions() -> get(actions).
  136. actions(Ac) -> put(actions,Ac).
  137. insert_top(Target, Elements) when element(1,Elements) == tr -> insert_top(tbody,Target, Elements);
  138. insert_top(Target, Elements) -> insert_top('div',Target, Elements).
  139. insert_bottom(Target, Elements) when element(1,Elements) == tr -> insert_bottom(tbody, Target, Elements);
  140. insert_bottom(Target, Elements) -> insert_bottom('div', Target, Elements).
  141. insert_before(Target, Elements) -> insert_adjacent(beforebegin,Target, Elements).
  142. insert_after(Target, Elements) -> insert_adjacent(afterend,Target, Elements).
  143. clear(Target) ->
  144. nitro:wire("var x = qi('"++nitro:to_list(Target)++"'); while (x.firstChild) x.removeChild(x.firstChild);").
  145. remove(Target) ->
  146. nitro:wire("var x=qi('"++nitro:to_list(Target)++"'); x && x.parentNode.removeChild(x);").
  147. % Wire JavaScript nitro:wire
  148. state(Key) -> erlang:get(Key).
  149. state(Key,Value) -> erlang:put(Key,Value).
  150. % Redirect and purge connection nitro:redirect
  151. redirect({http,Url}) -> n2o:header(<<"Location">>,nitro_conv:to_binary(Url)), nitro:state(status,302), [];
  152. redirect(Url) -> nitro:wire(#jq{target='window.top',property=location,args=simple,right=Url}).
  153. header(K,V) -> nitro:context((?CTX)#cx{req=cowboy_req:set_resp_header(K,V,?CTX#cx.req)}).
  154. % Convert and Utils API
  155. display(Element,Status) ->
  156. nitro:wire("{ var x = qi('"++
  157. nitro:to_list(Element)++"'); if (x) x.style.display = '"++nitro:to_list(Status)++"'; }").
  158. show(Element) -> display(Element,block).
  159. hide(Element) -> display(Element,none).