nitro.erl 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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. q(Key) -> q(Key, []).
  9. q(Key, Def) -> case get(Key) of undefined -> Def; Val -> Val end.
  10. qc(Key) -> CX = get(context), qc(Key,CX#cx.req).
  11. qc(Key,Req) -> proplists:get_value(nitro:to_binary(Key),cowboy_req:parse_qs(Req)).
  12. start(_StartType, _StartArgs) -> supervisor:start_link({local, ?MODULE}, ?MODULE, []).
  13. stop(_State) -> ok.
  14. init([]) -> {ok, {{one_for_one, 5, 10}, []}}.
  15. f(S) -> f(S, []).
  16. f(S, Args) -> lists:flatten(io_lib:format(S, Args)).
  17. coalesce([]) -> undefined;
  18. coalesce([H]) -> H;
  19. coalesce([undefined|T]) -> coalesce(T);
  20. coalesce([[]|T]) -> coalesce(T);
  21. coalesce([H|_]) -> H.
  22. jse(X) -> js_escape(X).
  23. hte(X) when is_binary(X) -> nitro:to_binary(nitro_conv:html_encode(X));
  24. hte(X) -> nitro_conv:html_encode(X).
  25. js_escape(undefined) -> [];
  26. js_escape(Value) when is_list(Value) -> binary_to_list(js_escape(iolist_to_binary(Value)));
  27. js_escape(Value) -> js_escape(Value, <<>>).
  28. js_escape(<<"\\", Rest/binary>>, Acc) -> js_escape(Rest, <<Acc/binary, "\\\\">>);
  29. js_escape(<<"\r", Rest/binary>>, Acc) -> js_escape(Rest, <<Acc/binary, "\\r">>);
  30. js_escape(<<"\n", Rest/binary>>, Acc) -> js_escape(Rest, <<Acc/binary, "\\n">>);
  31. js_escape(<<"\"", Rest/binary>>, Acc) -> js_escape(Rest, <<Acc/binary, "\\\"">>);
  32. js_escape(<<"'",Rest/binary>>,Acc) -> js_escape(Rest, <<Acc/binary, "\\'">>);
  33. js_escape(<<"<script", Rest/binary>>, Acc) -> js_escape(Rest, <<Acc/binary, "<scr\" + \"ipt">>);
  34. js_escape(<<"script>", Rest/binary>>, Acc) -> js_escape(Rest, <<Acc/binary, "scr\" + \"ipt>">>);
  35. js_escape(<<C, Rest/binary>>, Acc) -> js_escape(Rest, <<Acc/binary, C>>);
  36. js_escape(<<>>, Acc) -> Acc.
  37. -define(IS_STRING(Term), (is_list(Term) andalso Term /= [] andalso is_integer(hd(Term)))).
  38. to_list(L) when ?IS_STRING(L) -> L;
  39. to_list(L) when is_list(L) -> SubLists = [inner_to_list(X) || X <- L], lists:flatten(SubLists);
  40. to_list(A) -> inner_to_list(A).
  41. inner_to_list(A) when is_atom(A) -> atom_to_list(A);
  42. inner_to_list(B) when is_binary(B) -> binary_to_list(B);
  43. inner_to_list(I) when is_integer(I) -> integer_to_list(I);
  44. inner_to_list(L) when is_tuple(L) -> lists:flatten(io_lib:format("~p", [L]));
  45. inner_to_list(L) when is_list(L) -> L;
  46. inner_to_list(F) when is_float(F) -> float_to_list(F,[{decimals,9},compact]).
  47. to_atom(A) when is_atom(A) -> A;
  48. to_atom(B) when is_binary(B) -> to_atom(binary_to_list(B));
  49. to_atom(I) when is_integer(I) -> to_atom(integer_to_list(I));
  50. to_atom(F) when is_float(F) -> to_atom(float_to_list(F,[{decimals,9},compact]));
  51. to_atom(L) when is_list(L) -> list_to_atom(binary_to_list(list_to_binary(L))).
  52. to_binary(A) when is_atom(A) -> atom_to_binary(A,latin1);
  53. to_binary(B) when is_binary(B) -> B;
  54. to_binary(I) when is_integer(I) -> to_binary(integer_to_list(I));
  55. to_binary(F) when is_float(F) -> float_to_binary(F,[{decimals,9},compact]);
  56. to_binary(L) when is_list(L) -> iolist_to_binary(L);
  57. to_binary(X) when is_tuple(X) -> term_to_binary(X).
  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. {Render, _Ref, Actions} = render_html(Elements),
  109. nitro:wire(nitro:f(
  110. "qi('~s').insertBefore("
  111. "(function(){var div = qn('~s'); div.innerHTML = `~s`; return div.firstChild; })(),"
  112. "qi('~s').firstChild);",
  113. [Target,Tag,Render,Target])),
  114. nitro:wire(nitro:render(Actions)).
  115. insert_bottom(Tag, Target, Elements) ->
  116. {Render, _Ref, Actions} = render_html(Elements),
  117. nitro:wire(nitro:f(
  118. "(function(){ var div = qn('~s'); div.innerHTML = `~s`;"
  119. "qi('~s').appendChild(div.firstChild); })();",
  120. [Tag,Render,Target])),
  121. nitro:wire(nitro:render(Actions)).
  122. insert_before(Target, Elements) -> insert_adjacent(beforebegin, Target, Elements).
  123. insert_after(Target, Elements) -> insert_adjacent(afterend, Target, Elements).
  124. insert_adjacent(Command, Target, Elements) -> insert_adjacent(Command, Target, Elements, "qi").
  125. insert_adjacent(Command, Target, Elements, Q) ->
  126. {Render, _Ref, Actions} = render_html(Elements),
  127. nitro:wire(nitro:f("~s('~s').insertAdjacentHTML('~s', `~s`);",[Q,Target,Command,Render])),
  128. nitro:wire(nitro:render(Actions)).
  129. render_html(Elements) ->
  130. Pid = self(),
  131. Ref = make_ref(),
  132. spawn(fun() -> R = nitro:render(Elements), Pid ! {R, Ref, nitro:actions()} end),
  133. {Render, Ref, Actions} = receive {_, Ref, _} = A -> A end,
  134. {Render, Ref, 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. clear(Target) ->
  142. nitro:wire("var x = qi('"++nitro:to_list(Target)++"'); while (x.firstChild) x.removeChild(x.firstChild);").
  143. remove(Target) ->
  144. nitro:wire("var x=qi('"++nitro:to_list(Target)++"'); x && x.parentNode.removeChild(x);").
  145. % Wire JavaScript nitro:wire
  146. state(Key) -> erlang:get(Key).
  147. state(Key,Value) -> erlang:put(Key,Value).
  148. % Redirect and purge connection nitro:redirect
  149. redirect({http,Url}) -> n2o:header(<<"Location">>,nitro_conv:to_binary(Url)), nitro:state(status,302), [];
  150. redirect(Url) -> nitro:wire(#jq{target='window.top',property=location,args=simple,right=Url}).
  151. %header(K,V) -> nitro:context((?CTX)#cx{req=cowboy_req:set_resp_header(K,V,?CTX#cx.req)}).
  152. setAttr(Element, Attr, Value) ->
  153. nitro:wire("{ var x = qi('"++
  154. nitro:to_list(Element)++"'); if (x) x.setAttribute('"++nitro:to_list(Attr)++"', '"++nitro:to_list(Value)++"'); }").
  155. style(Element, Style) -> setAttr(Element, "style", Style).
  156. style(Element, Style, Value) ->
  157. nitro:wire("{ var x = qi('"++
  158. nitro:to_list(Element)++"'); if (x) x.style."++nitro:to_list(Style)++" = '"++nitro:to_list(Value)++"'; }").
  159. display(Element,Status) -> style(Element, "display", Status).
  160. show(Element) -> display(Element,block).
  161. hide(Element) -> display(Element,none).
  162. compact([]) -> "[]";
  163. compact("\n") -> "[]";
  164. compact([X|_]=Y) when is_tuple(X) -> [ compact(F) || F <- Y ];
  165. compact(Tuple) when is_binary(Tuple) -> unicode:characters_to_binary(Tuple);
  166. compact(Tuple) when is_tuple(Tuple) ->
  167. Min = erlang:min(9,size(Tuple)),
  168. Fields = lists:zip(lists:seq(1,Min),lists:sublist(tuple_to_list(Tuple),1,Min)),
  169. "{" ++ string:join([ io_lib:format("~s",[compact(F)]) || {_,F}<- Fields ],",") ++ "}";
  170. compact(Tuple) -> nitro:jse(nitro:to_list(Tuple)).
  171. meg(X) -> integer_to_list(X div 1000000) ++ "M".
  172. rev(X) -> lists:reverse(X).
  173. num(S) -> case rev(S) of
  174. [$K|K] -> list_to_integer(rev(K)) * 1000;
  175. [$M|M] -> list_to_integer(rev(M)) * 1000 * 1000;
  176. [$G|G] -> list_to_integer(rev(G)) * 1000 * 1000 * 1000;
  177. [$T|T] -> list_to_integer(rev(T)) * 1000 * 1000 * 1000 * 1000 end.
  178. cookie_expire(SecondsToLive) ->
  179. Seconds = calendar:datetime_to_gregorian_seconds(calendar:local_time()),
  180. DateTime = calendar:gregorian_seconds_to_datetime(Seconds + SecondsToLive),
  181. cow_date:rfc2109(DateTime).
  182. cookie(Id, Value) -> cookie(Id, Value, 2147483647). % expire never
  183. cookie(Id, Value, Expire) ->
  184. Format = "document.cookie='~s=~s; path=/; expires=~s';",
  185. nitro:wire(nitro:f(Format,[nitro:to_list(Id),nitro:to_list(Value), cookie_expire(Expire)])).
  186. cookies() -> cowboy_req:parse_cookies((get(context))#cx.req).
  187. cookie(Key) -> case lists:keyfind(Key, 1, cowboy_req:parse_cookies((get(context))#cx.req)) of false -> undefined; {_, Value} -> Value end.