nitro.erl 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. -module(nitro).
  2. %%-author('Maxim Sokhatsky').
  3. -behaviour(application).
  4. -include_lib("nitro/include/cx.hrl").
  5. -include_lib("nitro/include/nitro.hrl").
  6. -include_lib("nitro/include/event.hrl").
  7. -export([start/2, stop/1, init/1]).
  8. -export([atom/1, q/1, q/2, qc/1, qc/2,
  9. jse/1, hte/1, config/3, pickle/1, depickle/1, unique_integer/0, temp_id/0,
  10. script/0, script/1, actions/0, actions/1, state/1, state/2,
  11. redirect/1, cookie_expire/1, cookie/2, cookie/3, cookies/0, cookie/1,
  12. f/1, f/2, coalesce/1,
  13. to_list/1, to_atom/1, to_binary/1, to_integer/1,
  14. join/2, replace/3, indexof/2, indexof/3, append/3, os_env/1, os_env/2,
  15. prolongate/0, authenticate/2,
  16. render/1, wire/1, hex/1, unhex/1, js_escape/1, js_escape/2,
  17. html_encode/1, html_encode/2, url_encode/1, url_decode/1,
  18. update/2, insert_top/2, insert_top/3, insert_bottom/2, insert_bottom/3,
  19. insert_before/2, insert_after/2, insert_adjacent/3, insert_adjacent/4,
  20. clear/1, remove/1, setAttr/3, style/2, style/3, display/2, show/1, hide/1,
  21. compact/1, meg/1, num/1 ]).
  22. atom(List) when erlang:is_list(List) ->
  23. string:join([ nitro:to_list(L) || L <- List], "_");
  24. atom(Scalar) -> nitro:to_list(Scalar).
  25. q(Key) -> q(Key, []). %% todo unwrap
  26. q(Key, Def) -> case get(Key) of undefined -> Def; Val -> Val end.
  27. qc(Key) -> CX = get(context), qc(Key,CX#cx.req).
  28. qc(Key, Req) -> proplists:get_value(nitro:to_binary(Key),cowboy_req:parse_qs(Req)).
  29. jse(X) -> js_escape(X). %% todo unwrap
  30. hte(X) when erlang:is_binary(X) -> nitro:to_binary(html_encode(X));
  31. hte(X) -> html_encode(X).
  32. config(App, Key, Default) -> application:get_env(App, Key, Default).
  33. %%js_escape(Value) -> nitro_conv:js_escape(Value). %% todo mv to this module
  34. start(_StartType, _StartArgs) -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). %% todo mv other module
  35. stop(_State) -> ok.
  36. init([]) -> {ok, {{one_for_one, 5, 10}, []}}.
  37. %% Convert and Utils API
  38. f(S) -> f(S, []).
  39. f(S, Args) -> lists:flatten(io_lib:format(S, Args)).
  40. coalesce({_, Y}) -> Y;
  41. coalesce(false) -> undefined;
  42. coalesce([]) -> undefined;
  43. coalesce([H]) -> H;
  44. coalesce([undefined|T]) -> coalesce(T);
  45. coalesce([[]|T]) -> coalesce(T);
  46. coalesce([H|_]) -> H.
  47. %% to_list to_atom to_binary to_integer
  48. -define(IS_STRING(Term),
  49. (erlang:is_list(Term) andalso Term /= [] andalso erlang:is_integer(hd(Term)))).
  50. to_list(L) when ?IS_STRING(L) -> L;
  51. to_list(L) when erlang:is_list(L) ->
  52. SubLists = [inner_to_list(X) || X <- L],
  53. lists:flatten(SubLists);
  54. to_list(A) -> inner_to_list(A).
  55. inner_to_list(A) when erlang:is_atom(A) -> erlang:atom_to_list(A);
  56. inner_to_list(B) when erlang:is_binary(B) -> erlang:binary_to_list(B);
  57. inner_to_list(I) when erlang:is_integer(I) -> erlang:integer_to_list(I);
  58. inner_to_list(L) when erlang:is_tuple(L) -> lists:flatten(io_lib:format("~p", [L]));
  59. inner_to_list(L) when erlang:is_list(L) -> L;
  60. inner_to_list(F) when erlang:is_float(F) -> erlang:float_to_list(F, [{decimals, 9}, compact]).
  61. to_atom(A) when erlang:is_atom(A) -> A;
  62. to_atom(B) when erlang:is_binary(B) -> erlang:binary_to_atom(B);
  63. to_atom(I) when erlang:is_integer(I) -> to_atom(erlang:integer_to_list(I));
  64. to_atom(F) when erlang:is_float(F) -> to_atom(erlang:float_to_list(F, [{decimals, 9}, compact]));
  65. to_atom(L) when erlang:is_list(L) -> erlang:list_to_atom(L).
  66. to_binary(A) when erlang:is_atom(A) -> erlang:atom_to_binary(A, latin1);
  67. to_binary(B) when erlang:is_binary(B) -> B;
  68. to_binary(I) when erlang:is_integer(I) -> erlang:integer_to_binary(I);
  69. to_binary(F) when erlang:is_float(F) -> erlang:float_to_binary(F, [{decimals, 9}, compact]);
  70. to_binary(L) when erlang:is_list(L) -> erlang:iolist_to_binary(L);
  71. to_binary(X) when erlang:is_tuple(X) -> erlang:term_to_binary(X).
  72. to_integer(A) when erlang:is_atom(A) -> to_integer(erlang:atom_to_list(A));
  73. to_integer(B) when erlang:is_binary(B) -> to_integer(erlang:binary_to_list(B));
  74. to_integer(I) when erlang:is_integer(I) -> I;
  75. to_integer([]) -> 0;
  76. to_integer(L) when erlang:is_list(L) -> erlang:list_to_integer(L);
  77. to_integer(F) when erlang:is_float(F) -> erlang:round(F).
  78. %% JOIN
  79. %% join(List, Delimiter)
  80. join([], _) -> [];
  81. join([Item], _Delim) -> [Item];
  82. join([Item|Items], Delim) ->
  83. [Item, Delim | join(Items, Delim)].
  84. %% replace(String, S1, S2)
  85. replace([], _, _) -> [];
  86. replace(String, S1, S2) when erlang:is_list(String), erlang:is_list(S1), erlang:is_list(S2) ->
  87. Length = erlang:length(S1),
  88. case string:substr(String, 1, Length) of
  89. S1 ->
  90. S2 ++ replace(string:substr(String, Length + 1), S1, S2);
  91. _ ->
  92. [erlang:hd(String) | replace(erlang:tl(String), S1, S2)]
  93. end.
  94. indexof(Key, Fields) -> indexof(Key, Fields, 2).
  95. indexof(_, [], _) -> undefined;
  96. indexof(Key, [Key|_], N) -> N;
  97. indexof(Key, [_|T], N) -> indexof(Key, T, N + 1).
  98. append(List, Key, Value) ->
  99. case Value of
  100. undefined -> List;
  101. _A -> [{Key, Value}|List]
  102. end.
  103. os_env(Key) -> os_env(Key, "").
  104. os_env(Key, Default) ->
  105. case os:getenv(Key) of
  106. false -> Default;
  107. V -> V
  108. end.
  109. -ifndef(PICKLER).
  110. -define(PICKLER, (application:get_env(n2o, pickler, nitro_pickle))).
  111. -endif.
  112. pickle(Data) -> ?PICKLER:pickle(Data).
  113. depickle(SerializedData) -> ?PICKLER:depickle(SerializedData).
  114. prolongate() ->
  115. case application:get_env(n2o, session) of
  116. {ok, M} -> M:prolongate();
  117. undefined -> false
  118. end.
  119. authenticate(I, Auth) ->
  120. (application:get_env(n2o, session, n2o_session)):authenticate(I, Auth).
  121. render(X) -> wf_render:render(X).
  122. % Wire JavaScript nitro:wire
  123. wire(Actions) -> action_wire:wire(Actions).
  124. unique_integer() -> erlang:unique_integer().
  125. temp_id() -> "auto" ++ integer_to_list(unique_integer() rem 1000000).
  126. %% Fast HEX
  127. %digit(0) -> $0;
  128. %digit(1) -> $1;
  129. %digit(2) -> $2;
  130. %digit(3) -> $3;
  131. %digit(4) -> $4;
  132. %digit(5) -> $5;
  133. %digit(6) -> $6;
  134. %digit(7) -> $7;
  135. %digit(8) -> $8;
  136. %digit(9) -> $9;
  137. %digit(10) -> $a;
  138. %digit(11) -> $b;
  139. %digit(12) -> $c;
  140. %digit(13) -> $d;
  141. %digit(14) -> $e;
  142. %digit(15) -> $f.
  143. digit(X) when X >= 0 andalso X =< 9 -> X + 48;
  144. digit(X) when X >= 10 andalso X =< 15 -> X + 87.
  145. hex(Bin) ->
  146. << << (digit(A1)), (digit(A2)) >> || <<A1:4, A2:4>> <= Bin >>.
  147. unhex(Hex) ->
  148. << << (erlang:list_to_integer([H1, H2], 16)) >> || <<H1, H2>> <= Hex >>.
  149. %% JavaScript escape
  150. js_escape(undefined) -> [];
  151. js_escape(Value) when erlang:is_list(Value) ->
  152. erlang:binary_to_list( js_escape( erlang:iolist_to_binary(Value) ) );
  153. js_escape(Value) -> js_escape(Value, <<>>).
  154. js_escape(<<"\\", Rest/binary>>, Acc) -> %"
  155. js_escape(Rest, <<Acc/binary, "\\\\">>); %"
  156. js_escape(<<"\r", Rest/binary>>, Acc) ->
  157. js_escape(Rest, <<Acc/binary, "\\r">>);
  158. js_escape(<<"\n", Rest/binary>>, Acc) ->
  159. js_escape(Rest, <<Acc/binary, "\\n">>);
  160. js_escape(<<"\"", Rest/binary>>, Acc) ->
  161. js_escape(Rest, <<Acc/binary, "\\\"">>);
  162. js_escape(<<"'", Rest/binary>>, Acc) ->
  163. js_escape(Rest, <<Acc/binary, "\\'">>);
  164. js_escape(<<"`", Rest/binary>>, Acc) ->
  165. js_escape(Rest, <<Acc/binary, "\\`">>);
  166. js_escape(<<"<script", Rest/binary>>, Acc) ->
  167. js_escape(Rest, <<Acc/binary, "<script">>);
  168. js_escape(<<"script>", Rest/binary>>, Acc) ->
  169. js_escape(Rest, <<Acc/binary, "script>">>);
  170. js_escape(<<C, Rest/binary>>, Acc) ->
  171. js_escape(Rest, <<Acc/binary, C>>);
  172. js_escape(<<>>, Acc) -> Acc.
  173. %% HTML encode/decode
  174. %% html_encode(B, normal)
  175. html_encode(L, Fun) when erlang:is_function(Fun) ->
  176. Fun(L);
  177. html_encode(L, EncType) when erlang:is_atom(L) ->
  178. html_encode(nitro:to_list(L), EncType);
  179. html_encode(L, EncType) when erlang:is_integer(L) ->
  180. html_encode(erlang:integer_to_list(L), EncType);
  181. html_encode(L, EncType) when erlang:is_float(L) ->
  182. html_encode(erlang:float_to_list(L, [{decimals, 9}, compact]), EncType);
  183. html_encode(L, false) ->
  184. L;
  185. html_encode(L, true) ->
  186. L;
  187. html_encode(L, whites) ->
  188. html_encode_whites(nitro:to_list(lists:flatten([L]))).
  189. html_encode(<<>>) ->
  190. [];
  191. html_encode([]) ->
  192. [];
  193. html_encode(B) when is_binary(B) ->
  194. nitro:to_binary(
  195. html_encode(erlang:binary_to_list(B))
  196. );
  197. html_encode([$\n |T]) ->
  198. "<br>" ++ html_encode(T);
  199. html_encode([H|T]) ->
  200. case H of
  201. $< -> "&lt;" ++ html_encode(T);
  202. $> -> "&gt;" ++ html_encode(T);
  203. $" -> "&quot;" ++ html_encode(T);
  204. $' -> "&#39;" ++ html_encode(T);
  205. $& -> "&amp;" ++ html_encode(T);
  206. $\\ -> "&#92;" ++ html_encode(T);
  207. BigNum when erlang:is_integer(BigNum) andalso BigNum > 255 ->
  208. %% Any integers above 255 are converted to their HTML encode equivalent
  209. %% Example: 7534 gets turned into &#7534;
  210. [$&, $# | nitro:to_list(BigNum)] ++ ";" ++ html_encode(T);
  211. Tup when erlang:is_tuple(Tup) ->
  212. erlang:throw({html_encode, encountered_tuple, Tup});
  213. _ ->
  214. [H|html_encode(T)]
  215. end.
  216. html_encode_whites([]) -> [];
  217. html_encode_whites([H|T]) ->
  218. case H of
  219. $\s -> "&nbsp;" ++ html_encode_whites(T);
  220. $\t -> "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" ++ html_encode_whites(T);
  221. $< -> "&lt;" ++ html_encode_whites(T);
  222. $> -> "&gt;" ++ html_encode_whites(T);
  223. $" -> "&quot;" ++ html_encode_whites(T);
  224. $' -> "&#39;" ++ html_encode_whites(T);
  225. $& -> "&amp;" ++ html_encode_whites(T);
  226. $\n -> "<br>" ++ html_encode_whites(T);
  227. $\\ -> "&#92;" ++ html_encode_whites(T);
  228. _ -> [H|html_encode_whites(T)]
  229. end.
  230. %% URL encode/decode
  231. -define(PERCENT, 37). % $\%
  232. -define(FULLSTOP, 46). % $\.
  233. -define(IS_HEX(C), ((C >= $0 andalso C =< $9) orelse
  234. (C >= $a andalso C =< $f) orelse
  235. (C >= $A andalso C =< $F))).
  236. -define(QS_SAFE(C), ((C >= $a andalso C =< $z) orelse
  237. (C >= $A andalso C =< $Z) orelse
  238. (C >= $0 andalso C =< $9) orelse
  239. (C =:= ?FULLSTOP orelse C =:= $- orelse
  240. C =:= $~ orelse C =:= $_))).
  241. url_encode(Atom) when erlang:is_atom(Atom) ->
  242. url_encode(erlang:atom_to_list(Atom));
  243. url_encode(Int) when erlang:is_integer(Int) ->
  244. url_encode(erlang:integer_to_list(Int));
  245. url_encode(Bin) when erlang:is_binary(Bin) ->
  246. url_encode(erlang:binary_to_list(Bin));
  247. url_encode(String) ->
  248. url_encode(String, []).
  249. url_encode([], Acc) ->
  250. lists:reverse(Acc);
  251. url_encode([C | Rest], Acc) when ?QS_SAFE(C) ->
  252. url_encode(Rest, [C | Acc]);
  253. url_encode([$\s | Rest], Acc) ->
  254. url_encode(Rest, [$+ | Acc]);
  255. url_encode([C | Rest], Acc) ->
  256. <<Hi:4, Lo:4>> = <<C>>,
  257. url_encode(Rest, [digit(Lo), digit(Hi), ?PERCENT | Acc]).
  258. url_decode(Binary) when erlang:is_binary(Binary) ->
  259. url_decode(erlang:binary_to_list(Binary));
  260. url_decode(String) -> url_decode_h(lists:reverse(String)).
  261. unhexdigit(C) when C >= $0, C =< $9 ->
  262. C - $0;
  263. unhexdigit(C) when C >= $a, C =< $f ->
  264. C - $a + 10;
  265. unhexdigit(C) when C >= $A, C =< $F ->
  266. C - $A + 10.
  267. url_decode_h(S) -> url_decode_h(S, []).
  268. url_decode_h([], Acc) -> Acc;
  269. url_decode_h([$+ | Rest], Acc) ->
  270. url_decode_h(Rest, [$\s | Acc]);
  271. url_decode_h([Lo, Hi, ?PERCENT | Rest], Acc) when ?IS_HEX(Lo), ?IS_HEX(Hi) ->
  272. url_decode_h(Rest, [(unhexdigit(Lo) bor (unhexdigit(Hi) bsl 4)) | Acc]);
  273. url_decode_h([C | Rest], Acc) -> url_decode_h(Rest, [C | Acc]).
  274. script() -> get(script).
  275. script(Script) -> put(script, Script).
  276. %% Update DOM nitro:update
  277. update(Target, Elements) ->
  278. nitro:wire(#jq{target = Target, property = outerHTML, right = Elements, format = "`~s`"}).
  279. insert_top(Tag, Target, Elements) ->
  280. {Render, _Ref, Actions} = render_html(Elements),
  281. nitro:wire(nitro:f(
  282. "qi('~s').insertBefore("
  283. "(function(){var div = qn('~s'); div.innerHTML = `~s`; return div.firstChild; })(),"
  284. "qi('~s').firstChild);",
  285. [Target, Tag, Render, Target])),
  286. nitro:wire(nitro:render(Actions)).
  287. insert_bottom(Tag, Target, Elements) ->
  288. {Render, _Ref, Actions} = render_html(Elements),
  289. nitro:wire(nitro:f(
  290. "(function(){ var div = qn('~s'); div.innerHTML = `~s`;"
  291. "qi('~s').appendChild(div.firstChild); })();",
  292. [Tag, Render, Target])),
  293. nitro:wire(nitro:render(Actions)).
  294. insert_before(Target, Elements) -> insert_adjacent(beforebegin, Target, Elements).
  295. insert_after(Target, Elements) -> insert_adjacent(afterend, Target, Elements).
  296. insert_adjacent(Command, Target, Elements) ->
  297. insert_adjacent(Command, Target, Elements, "qi").
  298. insert_adjacent(Command, Target, Elements, Q) ->
  299. {Render, _Ref, Actions} = render_html(Elements),
  300. nitro:wire(nitro:f("~s('~s').insertAdjacentHTML('~s', `~s`);", [Q, Target, Command, Render])),
  301. nitro:wire(nitro:render(Actions)).
  302. render_html(Elements) ->
  303. Pid = erlang:self(),
  304. Ref = erlang:make_ref(),
  305. erlang:spawn(fun() ->
  306. R = nitro:render(Elements),
  307. Pid ! {R, Ref, erlang:get(actions)}
  308. end),
  309. {Render, Ref, Actions} = receive {_, Ref, _} = A -> A end,
  310. {Render, Ref, Actions}.
  311. actions() -> get(actions).
  312. actions(Ac) -> put(actions, Ac).
  313. insert_top(Target, Elements) when erlang:element(1, Elements) == tr ->
  314. insert_top(tbody, Target, Elements);
  315. insert_top(Target, Elements) ->
  316. insert_top('div', Target, Elements).
  317. insert_bottom(Target, Elements) when erlang:element(1, Elements) == tr ->
  318. insert_bottom(tbody, Target, Elements);
  319. insert_bottom(Target, Elements) ->
  320. insert_bottom('div', Target, Elements).
  321. clear(Target) ->
  322. nitro:wire("var x = qi('" ++ nitro:to_list(Target) ++ "');"
  323. "while(x && x.firstChild) x.removeChild(x.firstChild);").
  324. remove(Target) ->
  325. nitro:wire("var x = qi('" ++ nitro:to_list(Target) ++ "');"
  326. "x && x.parentNode.removeChild(x);").
  327. %% Wire JavaScript nitro:wire
  328. state(Key) -> erlang:get(Key).
  329. state(Key,Value) -> erlang:put(Key, Value).
  330. %% Redirect and purge connection nitro:redirect
  331. redirect(Url) -> nitro:wire(#jq{target = 'window', property = location, args = simple, right = Url}).
  332. %header(K,V) -> nitro:context((?CTX)#cx{req = cowboy_req:set_resp_header(K, V, ?CTX#cx.req)}).
  333. setAttr(Element, Attr, Value) ->
  334. nitro:wire("{ var x = qi('" ++ nitro:to_list(Element) ++ "');"
  335. "if(x) x.setAttribute('" ++ nitro:to_list(Attr) ++ "', '" ++ nitro:to_list(Value) ++ "'); }").
  336. style(Element, Style) ->
  337. setAttr(Element, "style", Style).
  338. style(Element, Style, Value) ->
  339. nitro:wire("{ var x = qi('" ++ nitro:to_list(Element) ++ "');"
  340. "if(x) x.style." ++ nitro:to_list(Style) ++ " = '" ++ nitro:to_list(Value) ++ "'; }").
  341. display(Element, Status) -> style(Element, "display", Status).
  342. show(Element) -> display(Element, block).
  343. hide(Element) -> display(Element, none).
  344. compact([]) -> "[]";
  345. compact("\n") -> "[]";
  346. compact([X|_] = Y) when erlang:is_tuple(X) ->
  347. [ compact(F) || F <- Y ];
  348. compact(Bin) when erlang:is_binary(Bin) ->
  349. unicode:characters_to_binary(Bin);
  350. compact(Tuple) when erlang:is_tuple(Tuple) ->
  351. Min = erlang:min(9, erlang:size(Tuple)),
  352. Fields = lists:zip(lists:seq(1, Min),
  353. lists:sublist(erlang:tuple_to_list(Tuple), 1, Min)),
  354. "{" ++ string:join([ io_lib:format("~s", [compact(F)]) || {_, F} <- Fields ], ",") ++ "}";
  355. compact(T) ->
  356. nitro:js_escape(nitro:to_list(T)).
  357. meg(X) -> erlang:integer_to_list(X div 1000000) ++ "M".
  358. num(S) -> case lists:reverse(S) of
  359. [$K|K] -> erlang:list_to_integer(lists:reverse(K)) * 1000;
  360. [$M|M] -> erlang:list_to_integer(lists:reverse(M)) * 1000 * 1000;
  361. [$G|G] -> erlang:list_to_integer(lists:reverse(G)) * 1000 * 1000 * 1000;
  362. [$T|T] -> erlang:list_to_integer(lists:reverse(T)) * 1000 * 1000 * 1000 * 1000
  363. end.
  364. cookie_expire(SecondsToLive) ->
  365. Seconds = calendar:datetime_to_gregorian_seconds(calendar:local_time()),
  366. DateTime = calendar:gregorian_seconds_to_datetime(Seconds + SecondsToLive),
  367. cow_date:rfc2109(DateTime).
  368. cookie(Id, Value) -> cookie(Id, Value, 2147483647). %% expire never
  369. cookie(Id, Value, Expire) ->
  370. Format = "document.cookie='~s=~s; path=/; expires=~s';",
  371. nitro:wire(nitro:f(Format, [nitro:to_list(Id), nitro:to_list(Value), cookie_expire(Expire)])).
  372. cookies() -> cowboy_req:parse_cookies((erlang:get(context))#cx.req).
  373. cookie(Key) ->
  374. case lists:keyfind(Key, 1, cowboy_req:parse_cookies((erlang:get(context))#cx.req)) of
  375. false -> undefined;
  376. {_, Value} -> Value
  377. end.