wf_event.erl 1.5 KB

1234567891011121314151617181920212223242526272829303132
  1. -module(wf_event).
  2. -author('Maxim Sokhatsky').
  3. -author('Andrey Martemyanov').
  4. -include_lib("nitro/include/cx.hrl").
  5. -include_lib("nitro/include/nitro.hrl").
  6. -compile(export_all).
  7. -record(ev, { module, msg, trigger, name }).
  8. -define(B(E), nitro:to_binary(E)).
  9. -define(L(E), nitro:to_list(E)).
  10. target({ps,Id,Ps}) ->
  11. T = target(Id), P = nitro:js_escape(Ps),
  12. ["var ts=",T,",ps = '",P,"'.split('.').reduce((a,p)=>(a&&a[p]?a[p]:null),ts);","ps&&ps"];
  13. target({qs,S}) -> ["qs('",nitro:js_escape(?L(S)), "')"];
  14. target({g,T}) -> nitro:js_escape(?L(T));
  15. target(Id) -> ["qi('",nitro:js_escape(?L(Id)),"')"].
  16. new(P,E,D,N,Data,Source) -> new(P,E,D,N,Data,Source,<<>>).
  17. new(bin,Data) -> <<"ws.send(enc(tuple(atom('bin'),bin('",(nitro:pickle(Data))/binary,"'))));">>.
  18. new([], _, _, _, _, _, _) -> <<>>;
  19. new(undefined, _, _, _, _, _, _) -> <<>>;
  20. new(Postback, Element, Delegate, Name, Data, Source, Validation) ->
  21. Module = nitro:coalesce([Delegate, ?CTX#cx.module]),
  22. Join=fun([]) -> [];
  23. ([E]) -> [$'|E]++[$'];
  24. ([H|T]) -> [[$'|H]++[$']] ++ [ [$,,$'|E]++[$'] || E <- T ] end,
  25. Event = #ev{name=Name, module=Module, msg=Postback, trigger=Element},
  26. list_to_binary(["{ if (validateSources([",Join([ nitro:to_list(S) || S <- Source, S =/= []]),
  27. "])) { ",?B(Validation)," ws.send(enc(tuple(atom('",?B(application:get_env(n2o,event,pickle)),"'),bin('",
  28. Element,"'),bin('",nitro:pickle(Event),"'),",Data,"))); } else console.log('Validation Error'); }"]).