-
Notifications
You must be signed in to change notification settings - Fork 203
/
zotonic-wired.js
1804 lines (1578 loc) · 52.7 KB
/
zotonic-wired.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Zotonic basic Javascript library
----------------------------------------------------------
@package: Zotonic 2009
@Author: Tim Benniks <tim@timbenniks.nl>
@Author: Marc Worrell <marc@worrell.nl>
Copyright 2009-2021 Tim Benniks, Marc Worrell
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Based on nitrogen.js which is copyright 2008-2009 Rusty Klophaus
---------------------------------------------------------- */
// Client state
var z_language = "en";
// var z_userid;
var z_editor;
var z_default_form_postback;
var z_init_postback_forms_timeout = false;
// Misc state
var z_input_updater = false;
var z_drag_tag = [];
var z_registered_events = {};
var z_on_visible_checks = [];
var z_on_visible_timer;
var z_unique_id_counter = 0;
var z_transport_queue = [];
/* Startup
---------------------------------------------------------- */
cotonic.ready.then(function() { zotonic_startup() });
// Lazy css loading - set the correct media on load.
window.addEventListener('load',
function() {
const elts = document.querySelectorAll("link[media='none']");
elts.forEach(function(e) {
if (e.hasAttribute('media-onload')) {
e.setAttribute('media', e.getAttribute('media-onload'));
e.removeAttribute('media-onload');
}
});
}, false);
function zotonic_startup() {
// Initialize the wires if the bridge is starting up
// cotonic.broker.subscribe("$bridge/origin/status", function() {
// cotonic.broker.unsubscribe("$bridge/origin/status", { wid: 'zotonicjs' });
// if (typeof window.zotonicPageInit == 'function') {
// window.zotonicPageInit();
// }
// }, { wid: 'zotonicjs'});
// Handle data sent by the server
cotonic.broker.subscribe("zotonic-transport/eval", function(msg) {
try {
eval(msg.payload);
if (z_init_postback_forms_timeout) {
clearTimeout(z_init_postback_forms_timeout);
}
z_init_postback_forms_timeout = setTimeout(function() {
z_init_postback_forms_timeout = false;
z_init_postback_forms();
}, 10);
} catch(e) {
console.log("Error on eval", e, msg.payload);
}
}, { wid: 'zotonicjs'});
cotonic.broker.subscribe(
"zotonic-transport/progress",
function(msg) {
if (msg.payload.is_auto_unmask && msg.payload.percentage >= 100) {
z_unmask(msg.payload.form_id);
} else {
z_progress(msg.payload.form_id, msg.payload.percentage);
}
}, { wid: 'zotonicprogress'});
cotonic.broker.subscribe(
"model/alert/post",
function(msg) {
z_dialog_alert(msg.payload);
}, { wid: 'zotonicalert'});
// Register the client-id to reuse on subsequent pages
cotonic.broker.subscribe(
"$bridge/origin/status",
function(msg) {
if (msg.payload.is_connected) {
cotonic.broker.publish(
"model/sessionStorage/post/mqtt-origin-client-id",
msg.payload.client_id,
);
// Retain the client-id
cotonic.broker.publish(
"$bridge/origin/client-id",
msg.payload.client_id,
{ retain: true },
);
}
}, { wid: "zotonicjs" });
// Start the client-server bridge
cotonic.broker.call("model/sessionStorage/get/mqtt-origin-client-id")
.then(
function(msg) {
cotonic.mqtt_bridge.newBridge('origin', {
client_id: msg.payload || '',
clean_start: true
});
});
setInterval(function() { z_transport_queue_check(); }, 500);
}
/* Non modal dialogs
---------------------------------------------------------- */
function z_dialog_open(options)
{
$.dialogAdd(options);
}
function z_dialog_close()
{
$.dialogClose();
}
function z_dialog_confirm(options)
{
var html,
backdrop,
is_danger,
btn_class;
if (typeof options.backdrop == 'undefined') {
backdrop = options.backdrop
} else {
backdrop = true;
}
is_danger = options.is_danger || false;
btn_class = is_danger ? "btn-danger" : "btn-primary";
html = '<div class="confirm">' + options.text + '</div>'
+ '<div class="modal-footer">'
+ '<button class="btn btn-default z-dialog-cancel-button">'
+ (options.cancel||z_translate('Cancel'))
+ '</button>'
+ '<button class="btn '+btn_class+' z-dialog-ok-button">'
+ (options.ok||z_translate('OK'))
+ '</button>'
+ '</div>';
$.dialogAdd({
title: (options.title||z_translate('Confirm')),
text: html,
width: (options.width),
backdrop: backdrop
});
$(".z-dialog-cancel-button").click(function() {
z_dialog_close();
if (options.on_cancel) options.on_cancel();
});
$(".z-dialog-ok-button").click(function() {
z_dialog_close();
if (options.on_confirm) options.on_confirm();
});
}
function z_dialog_alert(options)
{
var html,
backdrop;
if (typeof options.backdrop == 'undefined') {
backdrop = options.backdrop
} else {
backdrop = true;
}
html = '<div class="confirm">' + options.text + '</div>'
+ '<div class="modal-footer">'
+ '<button class="btn btn-primary z-dialog-ok-button">'
+ (options.ok||z_translate('OK'))
+ '</button>'
+ '</div>';
$.dialogAdd({
title: (options.title||z_translate('Alert')),
text: html,
width: (options.width),
backdrop: backdrop
});
$(".z-dialog-ok-button").click(function() {
z_dialog_close();
if (options.on_confirm) options.on_confirm();
});
}
function z_dialog_overlay_open(options)
{
var overlay_id = 'modal-overlay';
if (typeof options.level !== 'undefined' && options.level > 0) {
overlay_id = overlay_id + "-level-" + options.level;
level = options.level;
} else {
level = 0;
}
var $overlay = $('#'+overlay_id);
if ($overlay.length > 0) {
$overlay
.html('<a href="#close" class="modal-overlay-close" onclick="return z_dialog_overlay_close(this)">×</a>' + options.html)
.attr('class', 'modal-overlay')
.show();
} else {
html = '<div class="modal-overlay modal-overlay-level-' + level + '" id="' + overlay_id + '">' +
'<a href="#close" class="modal-overlay-close" onclick="return z_dialog_overlay_close(this)">×</a>' +
options.html +
'</div>';
$('body').append(html);
$overlay = $('#'+overlay_id);
}
if (options.class) {
$overlay.addClass(options.class);
}
$('body').addClass('overlay-open');
if (typeof($.widgetManager) != 'undefined') {
$overlay.widgetManager();
}
z_editor_add($overlay);
}
function z_dialog_overlay_close( closeButton )
{
var $overlay;
if (typeof closeButton !== 'undefined') {
$overlay = $(closeButton).closest(".modal-overlay");
} else {
$overlay = $('.modal-overlay');
}
$overlay.remove();
if ($('.modal-overlay').length == 0) {
$('body').removeClass('overlay-open');
}
return false;
}
/* Growl messages
---------------------------------------------------------- */
function z_growl_add(message, stay, type)
{
stay = stay || false;
type = type || 'notice';
$.noticeAdd(
{
text: message,
stay: stay,
type: type
});
if(type == 'error' && window.console)
{
console.error(message);
}
}
function z_growl_close()
{
$.noticeRemove($('.notice-item-wrapper'), 400);
}
/* Registered events for javascript triggered actions/postbacks
---------------------------------------------------------- */
function z_event_register(name, func)
{
z_registered_events[name] = func;
}
function z_event(name, extraParams)
{
if (z_registered_events[name])
{
z_registered_events[name](ensure_name_value(extraParams));
}
else
{
$.misc.error("z_event: no registered event named: '"+name+"'");
}
}
/* Call the server side notifier for {postback_notify, Message, Context}
---------------------------------------------------------- */
function z_notify(message, extraParams)
{
var trigger_id = '';
var target_id;
var params = extraParams || [];
var delegate = params.z_delegate || 'notify';
if (typeof params == 'object') {
if (params.z_trigger_id !== undefined) {
trigger_id = params.z_trigger_id;
delete params.z_trigger_id;
}
target_id = params.z_target_id || undefined;
}
params = ensure_name_value(params);
var postbackAttr = document.body.getAttribute("data-wired-postback");
if (postbackAttr) {
params.push({ name: "z_postback_data", value: JSON.parse(postbackAttr) });
}
var notify = {
_type: "postback_notify",
message: message,
trigger: trigger_id,
target: target_id,
data: {
q: params
}
};
var options = {
trigger_id: trigger_id
};
if (trigger_id) {
options.ack = function(_ack_msg, _options) {
z_unmask(trigger_id);
};
}
z_transport_queue_add(delegate, 'ubf', notify, options);
z_transport_queue_check();
}
/* Session handling and restarts
---------------------------------------------------------- */
// - checks pubzub registry for the local "session" topic
// - if any handlers then publish the new user to the topic
// - if no handlers then the default reload dialog is shown
//
// if (typeof pubzub == "object" && pubzub.subscribers("~pagesession/session").length > 0) {
// z_session_valid = true;
// pubzub.publish("~pagesession/session", status);
// z_stream_restart();
// }
/* Transport between user-agent and server
---------------------------------------------------------- */
// Queue any data to be transported to the server
function z_transport(delegate, content_type, data, options)
{
options = options || {};
if (options.transport == 'fileuploader' && cotonic.whereis("fileuploader")) {
// Post via the fileuploader worker
let fileInputs = $('input:file', options.post_form);
let files = [];
fileInputs.each(function() {
let fs = $(this).get(0).files;
for (let i = 0; i < fs.length; i++) {
files.push({
name: $(this).attr('name'),
file: fs[i]
})
}
});
// TODO: fill in failure topic and progress
data.data.q = data.data.q.concat($(options.post_form).formToArray());
let msg = {
files: files,
ready_msg: data,
ready_topic: "$promised/bridge/origin/zotonic-transport/" + delegate,
progress_topic: "zotonic-transport/progress",
progress_msg: { form_id: data.trigger },
failure_topic: "model/alert/post",
failure_msg: { text: "Error during upload" }
}
cotonic.broker.publish("model/fileuploader/post/new", msg);
} else if (options.transport == 'form' || options.transport == 'fileuploader') {
cotonic.broker.call("$promised/bridge/origin/model/mqtt_ticket/post/new")
.then( function(msg) {
if (msg.payload.status == 'ok') {
const ticket = msg.payload.result;
z_transport_form({
url: "/mqtt-transport/" + ticket + "/zotonic-transport/" + delegate,
postback: data,
options: options,
progress_topic: "~client/zotonic-transport/progress",
reply_topic: "~client/zotonic-transport/eval"
});
} else {
console.error("z_transport: could not obtain MQTT ticket for form post", [ msg.payload ]);
z_transport_queue_add(delegate, content_type, data, options);
}
});
} else {
cotonic.broker.publish(
"$promised/bridge/origin/zotonic-transport/" + delegate,
data,
{ qos: 1 });
}
}
function z_transport_queue_add( delegate, content_type, data, options )
{
z_transport_queue.push({
delegate: delegate,
content_type: content_type,
data: data,
options: options
});
}
function z_transport_queue_check()
{
const html = document.body.parentElement;
if(!html) return;
const authState = html.dataset.uiStateAuthAuth;
// Make sure the auth worker is ready so the postbacks are
// either authenticated, or not... Not something in between
// when the auth worker is still starting.
if ( z_transport_queue.length > 0
&& html.classList.contains('ui-state-bridge-connected')
&& (authState === 'anonymous' || authState === 'user')) {
let trans = z_transport_queue.shift();
z_transport(trans.delegate, trans.content_type, trans.data, trans.options);
}
}
// Queue form data to be transported to the server
// This is called by the server generated javascript and jquery triggered postback events.
// 'transport' is one of: '', 'form', 'fileuploader'
function z_queue_postback(trigger_id, postback, extraParams, noTriggerValue, transport, optPostForm)
{
var triggervalue = '';
var trigger;
var target_id;
if (typeof extraParams == 'object') {
target_id = extraParams.z_target_id || undefined;
}
if (transport === true) {
transport = '';
}
if (trigger_id) {
trigger = $('#'+trigger_id).get(0);
}
if (trigger && !noTriggerValue) {
if ($(trigger).is(":checkbox") || $(trigger).is(":radio")) {
if ($(trigger).is(":checked")) {
triggervalue = $(trigger).val() || 'on';
}
} else {
var nodeName = trigger.nodeName.toLowerCase();
if (nodeName == 'input' || nodeName == 'button' || nodeName == 'textarea' || nodeName == 'select') {
triggervalue = $(trigger).val() || '';
}
}
}
params = extraParams || [];
params = ensure_name_value(params);
var postbackAttr = document.body.getAttribute("data-wired-postback");
if (postbackAttr) {
params.push({ name: "z_postback_data", value: JSON.parse(postbackAttr) });
}
var pb_event = {
_type: "postback_event",
postback: postback,
trigger: trigger_id,
target: target_id,
triggervalue: triggervalue,
data: {
q: params
}
};
// if (!transport) {
// if ((trigger_id == "logon_form") || (trigger && $(trigger).hasClass("setcookie"))) {
// transport = 'ajax';
// }
// }
// logon_form and .setcookie forms are always posted, as they will set cookies.
var options = {
transport: transport,
trigger_id: trigger_id,
post_form: optPostForm
};
z_transport_queue_add('postback', 'ubf', pb_event, options);
z_transport_queue_check();
}
// function z_postback_opt_qs(extraParams)
// {
// if (typeof extraParams == 'object' && extraParams instanceof Array) {
// return {
// _type: "q",
// q: ensure_name_value(extraParams)
// };
// } else {
// return extraParams;
// }
// }
function z_mask(id)
{
if (id && typeof id == "string")
{
var trigger;
if (id.charAt(0) == ' ') {
trigger = $(id);
} else {
trigger = $('#'+id);
}
trigger.each(function() { try { $(this).mask(); } catch (e) {}});
}
}
function z_unmask(id)
{
if (id && typeof id == "string")
{
var trigger;
if (id == "body" || id.charAt(0) == ' ') {
trigger = $(id);
} else {
trigger = $('#'+id);
}
trigger.each(function() { try { $(this).unmask(); } catch (e) {}});
trigger.each(function() { $(this).removeClass("z_error_upload"); });
}
}
function z_unmask_error(id)
{
if (id && typeof id == "string")
{
var trigger;
if (id == "body" || id.charAt(0) == ' ') {
trigger = $(id);
} else {
trigger = $('#'+id);
}
trigger.each(function() { try { $(this).unmask(); } catch (e) {}});
trigger.each(function() { $(this).addClass("z_error_upload"); });
}
}
function z_progress(id, value)
{
if (id)
{
var trigger;
if (id == "body" || id.charAt(0) == ' ') {
trigger = $(id);
} else {
trigger = $('#'+id);
}
trigger = trigger.get(0);
if (trigger) {
switch (trigger.nodeName.toLowerCase()) {
case 'input':
case 'button':
break;
case 'form':
case 'body':
case 'div':
try { $(trigger).maskProgress(value); } catch (e) {};
break;
default:
break;
}
}
}
}
function z_reload(args)
{
var page = $('#logon_form input[name="page"]'),
qs = ensure_name_value(args),
rewriteUrl,
newLanguage,
href,
re,
pathname,
parts;
if (page.length > 0 && page.val() !== "" && page.val() !== '#reload') {
window.location.href = window.location.protocol
+ "//"
+ window.location.host
+ page.val();
} else {
if (typeof args === "undefined") {
window.location.reload(true);
return;
}
newLanguage = args.z_language;
if (typeof newLanguage === "string") {
rewriteUrl = Boolean(args["z_rewrite_url"]);
// Add or remove language from URL:
pathname = window.location.pathname.substring(1);
if (z_language) {
// Remove current language
re = new RegExp("^" + z_language);
pathname = pathname.replace(re, "");
}
// Get path parts
parts = pathname.split("/")
.filter(function(p) {
return p !== "";
});
if (rewriteUrl) {
// Add language to start
parts.unshift(newLanguage);
}
href = window.location.protocol
+ "//"
+ window.location.host
+ "/"
+ parts.join("/")
+ ((rewriteUrl && (pathname === "" || pathname === "/")) ? "/" : "")
} else {
href = window.location.protocol
+ "//"
+ window.location.host
+ window.location.pathname;
}
if (window.location.search == "") {
window.location.href = href;
} else {
// remove z_language and z_rewrite_url, keep other query params
var kvs;
kvs = window.location.search.substring(1)
.split(/[&;]/)
.map(function(kv) {
return (kv.match("^z_language") || kv.match("^z_rewrite_url"))
? ""
: kv;
})
.filter(function(kv) {
return kv !== "";
});
if (kvs === "") {
window.location.href = href;
} else {
window.location.href = href + "?" + kvs.join("&");
}
}
}
}
/* translations
---------------------------------------------------------- */
function z_translate(text)
{
if (typeof z_translations != "undefined" && typeof z_translations[text] != "undefined")
return z_translations[text];
return text;
}
/* Render text as html nodes
---------------------------------------------------------- */
function z_text_to_nodes(text)
{
var text1 = $.trim(text);
if (text1 === "") {
return $("");
} else {
var $ns;
if (text1.charAt(0) == "<" && text1.charAt(text1.length-1) == ">") {
$ns = $(text);
} else {
$ns = $("<span></span>"+text+"<span></span>").slice(1,-1);
}
return $ns.filter(function(i) { return $ns[i].nodeType != 3 || $ns[i].nodeValue.trim() !== ""; });
}
}
/* WYSYWIG editor
---------------------------------------------------------- */
function z_editor_init()
{
if (z_editor !== undefined) {
z_editor.init();
}
}
function z_editor_add(element)
{
if (z_editor !== undefined) {
var $element = (typeof element == "string") ? $(element) : element;
z_editor.add($element);
}
}
function z_editor_save(element)
{
if (z_editor !== undefined) {
var $element = (typeof element == "string") ? $(element) : element;
z_editor.save($element);
}
}
function z_editor_remove(element)
{
if (z_editor !== undefined) {
var $element = (typeof element == "string") ? $(element) : element;
z_editor.remove($element);
}
}
/* Support legacy code */
function z_tinymce_init()
{
z_editor_init();
}
function z_tinymce_add($element)
{
z_editor_add($element);
}
function z_tinymce_save($element)
{
z_editor_save($element);
}
function z_tinymce_remove($element)
{
z_editor_remove($element);
}
/* Utility functions
---------------------------------------------------------- */
// Should an event be canceled or passed through.
function z_opt_cancel(obj)
{
if(typeof obj.nodeName == 'undefined')
return false;
var nodeName = obj.nodeName.toLowerCase();
var nodeType = $(obj).attr("type");
if (nodeName == 'input' && (nodeType == 'checkbox' || nodeType == 'radio'))
{
return true;
}
else
{
return false;
}
}
function z_is_enter_key(event)
{
return (event && event.keyCode == 13);
}
function z_ensure_id(elt)
{
var id = $(elt).attr('id');
if (id === undefined || id === "") {
id = z_unique_id();
$(elt).attr('id', id);
}
return id;
}
function z_unique_id(no_dom_check)
{
var id;
do {
id = '-z-' + z_unique_id_counter++;
} while (!no_dom_check && $('#'+id).length > 0);
return id;
}
/* Drag & drop interface to the postback
---------------------------------------------------------- */
function z_draggable(dragObj, dragOptions, dragTag)
{
dragObj.draggable(dragOptions).data("z_drag_tag", dragTag);
z_drag_tag[dragObj.attr('id')] = dragTag;
}
function z_droppable(dropObj, dropOptions, dropPostbackInfo)
{
dropOptions.greedy = true;
dropOptions.drop = function(ev, ui)
{
var dragTag = $(ui.draggable[0]).data("z_drag_tag");
var dragItem = new Array({name: 'drag_item', value: dragTag});
z_queue_postback(this.id, dropPostbackInfo, dragItem, true);
};
$(dropObj).droppable(dropOptions);
}
/* Sorter and sortables interface to the postback
---------------------------------------------------------- */
function z_sortable(sortableObj, sortTag)
{
sortableObj.data("z_sort_tag", sortTag);
}
function z_sorter(sortBlock, sortOptions, sortPostbackInfo)
{
sortOptions.update = function()
{
var sortItems = "";
for (var i = 0; i < this.childNodes.length; i++)
{
var sortTag = $(this.childNodes[i]).data("z_sort_tag");
if (sortTag)
{
if (sortItems !== "")
{
sortItems += ",";
}
sortItems += sortTag;
}
}
var sortItem = new Array({name: 'sort_items', value: sortItems});
z_queue_postback(this.id, sortPostbackInfo, sortItem, true);
};
sortOptions.receive = function (ev, ui) {
var $target = $(this).data().uiSortable.element;
var $source = $(ui.sender);
$target.data('z_sort_tag', $source.data('z_drag_tag'));
};
sortOptions.helper = 'clone';
$(sortBlock).sortable(sortOptions);
}
/* typeselect input field
---------------------------------------------------------- */
function z_typeselect(ElementId, postbackInfo)
{
if (z_input_updater)
{
clearTimeout(z_input_updater);
z_input_updater = false;
}
z_input_updater = setTimeout(function()
{
var obj = $('#'+ElementId);
if(obj.val().length >= 2)
{
obj.addClass('loading');
z_queue_postback(ElementId, postbackInfo);
}
}, 400);
}
/* Lazy loading of content, based on visibility of an element
---------------------------------------------------------- */
function z_on_visible(CssSelector, Func)
{
z_on_visible_checks.push({selector: CssSelector, func: Func});
if (z_on_visible_timer == undefined) {
z_on_visible_timer = setInterval(function() {
z_on_visible_check();
}, 350);
}
}
function z_on_visible_check()
{
for (var i = 0; i < z_on_visible_checks.length; i++) {
var elt = $(z_on_visible_checks[i].selector).get(0);
if (elt != undefined) {
if ($(elt).is(":visible") && isScrolledIntoView(elt)) {
z_on_visible_checks[i].func.call(elt);
z_on_visible_checks.splice(i, 1);
}
}
}
if (z_on_visible_checks.length == 0) {
clearInterval(z_on_visible_timer);
z_on_visible_timer = undefined;
}
}
function isScrolledIntoView(elem)
{
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return (elemBottom >= docViewTop) && (elemTop <= docViewBottom);
// && (elemBottom <= docViewBottom) && (elemTop >= docViewTop);
}
/* Error handling
----------------------------------------------------------
Fetch the error event and log it to the server.
Which should log it in a separate ui error log.
---------------------------------------------------------- */
var oldOnError = window.onerror;
var z_page_unloading = false;
window.addEventListener("unload", function(event) {
z_page_unloading = true;
});
window.addEventListener("beforeunload", function(event) {
z_page_unloading = true;
setTimeout(function() { z_page_unloading = false }, 5000);
});
window.onerror = function(message, file, line, col, error) {
if (!z_page_unloading) {
let payload = {
type: 'error',
message: message,
file: file,
line: line,
col: col,
stack: error ? error.stack : null,
user_agent: navigator.userAgent,
url: window.location.href
};
let xhr = new XMLHttpRequest();
xhr.open('POST', '/log-client-event', true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(payload));
if ($("form.masked").length > 0 || (payload.stack && payload.stack.match(/(submitFunction|doValidations)/))) {
alert("Sorry, something went wrong.\n\n(" + message + ")");
try { $("form.masked").unmask(); } catch (e) {}
}
}