/
wing.vue.js
1235 lines (1135 loc) · 45.4 KB
/
wing.vue.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
/*
* Axios global settings
*/
// send session cookie
axios.defaults.withCredentials = true;
//disable IE ajax request caching
axios.defaults.headers.get['If-Modified-Since'] = 'Mon, 26 Jul 1997 05:00:00 GMT';
//more cache control
axios.defaults.headers.get['Cache-Control'] = 'no-cache';
axios.defaults.headers.get['Pragma'] = 'no-cache';
axios.defaults.paramsSerializer = function(params) {
return Qs.stringify(params, {arrayFormat: 'repeat'});
};
axios.interceptors.request.use(function (config) {
wing.throbber.working();
return config;
}, function (error) {
wing.throbber.done();
return Promise.reject(error);
});
axios.interceptors.response.use(function (response) {
wing.throbber.done();
if (response.headers['content-type'] === "application/json; charset=utf-8" && "_warnings" in response.data.result) {
for (var warning in response.data.result._warnings) {
document.dispatchEvent(new CustomEvent('wing_warn', { message : response.data.result._warnings[warning].message }));
wing.warn(response.data.result._warnings[warning].message);
}
}
return response;
}, function (error) {
wing.throbber.done();
var message = 'Error communicating with server.';
if (_.isObject(error.response) && _.isObject(error.response.headers) && error.response.headers['content-type'] === "application/json; charset=utf-8" && "error" in error.response.data) {
if (error.response.data.error.code == 401) {
var message =[
'div', {}, [
'You must ',
['a', {attrs : {href : '/account'}, class : 'btn btn-primary btn-sm'}, 'log in'],
' to do that.'
]
];
}
else {
message = error.response.data.error.message;
var matches = message.split(/ /);
var field = matches[0].toLowerCase();
var nodelist = document.querySelectorAll('label[for="'+field+'"]');
if (nodelist.length > 0) {
var label = nodelist[0].innerText;
if (label) {
message = message.replace(field,label);
}
}
}
}
document.dispatchEvent(new CustomEvent('wing_error', { message : message }));
wing.error(message);
return Promise.reject(error);
});
/*
* Throbber progress bar element
*/
var throbber = document.createElement('div');
throbber.innerHTML = `<div id="wingajaxprogress" style="z-index: 10000; position: fixed; top: 0px; width: 100%;">
<template v-if="counter > 0"><b-progress :value="counter" :max="max" height="10px" animated></b-progress></template>
</div>`;
document.body.appendChild(throbber);
/*
* Toast element used for rendering system messages. See wing.info, wing.success, wing.error, and wing.warn.
*/
var toastdiv = document.createElement('div');
toastdiv.id = 'wingtoast';
document.body.appendChild(toastdiv);
/*
* Format a date
*/
Vue.filter('moment', function(input, format, timezone){
if (typeof moment !== 'undefined') {
if (!_.isString(format)) {
format = 'MMMM D, YYYY';
}
return wing.parse_date(input, timezone).format(format);
}
return input;
});
/*
* Format a date into a relative time
*/
Vue.filter('timeago', function(input){
if (typeof moment !== 'undefined') {
return wing.parse_date(input).fromNow();
}
return input;
});
/*
* Round a decimal to some level of precision
*/
Vue.filter('round', function(number, precision){
number = parseFloat(number);
precision |= 0;
var shift = function (number, precision, reverseShift) {
if (reverseShift) {
precision = -precision;
}
numArray = ("" + number).split("e");
return +(numArray[0] + "e" + (numArray[1] ? (+numArray[1] + precision) : precision));
};
return shift(Math.round(shift(number, precision, false)), precision, true);
});
/*
* format a file size using common bytes multiples
*/
Vue.filter('bytes', function(bytes){
if (isNaN(parseFloat(bytes)) || !isFinite(bytes)) return '-';
if (typeof precision === 'undefined') precision = 1;
var units = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'],
number = Math.floor(Math.log(bytes) / Math.log(1024));
return (bytes / Math.pow(1024, Math.floor(number))).toFixed(precision) + ' ' + units[number];
});
/*
* Automatically save an input field.
*/
Vue.directive('autosave', {
inserted: function (el, binding, vnode) {
const index = _.findIndex(vnode.data.directives, {rawName : 'v-model'});
if (index == -1) {
console.log('Cannot use v-autosave unless on an element with a v-model.');
}
else {
var field_array = vnode.data.directives[index].expression.split(/\./);
const field = field_array[field_array.length - 1];
var timer;
var original_value = binding.value.properties[field];
const debounce = function(e) {
if (timer) {
clearTimeout(timer);
}
if (e.keyCode == 13 && el.tagName != 'TEXTAREA') {
binding.value.save(field);
}
else {
timer = setTimeout(function() {
if (original_value != binding.value.properties[field]) {
original_value = binding.value.properties[field];
binding.value.save(field);
}
}, 2000);
}
}
el.addEventListener('keyup', debounce, false);
el.addEventListener('change', debounce, false);
el.addEventListener('focus', debounce, false);
el.addEventListener('blur', function(){
if (original_value != binding.value.properties[field]) {
clearTimeout(timer);
original_value = binding.value.properties[field];
binding.value.save(field);
}
}, false);
}
},
});
/*
* A component to generate select lists from wing options.
*/
Vue.component('wing-select', {
template : `<select @change="object.save(property)" class="form-control custom-select" v-model="object.properties[property]">
<option v-for="option in options()" :value="option">{{_option(option)}}</option>
</select>`,
props: ['object','property'],
methods : {
options() {
if ('_options' in this.object.properties) {
return this.object.properties._options[this.property];
}
return [];
},
_option(option) {
return this.object.properties._options['_'+this.property][option];
},
},
});
/*
* A component to generate select lists from wing options.
*/
Vue.component('wing-select-new', {
template : `<select class="form-control custom-select" v-model="list.new[property]">
<option v-for="option in options()" :value="option">{{_option(option)}}</option>
</select>`,
props: ['list','property'],
methods : {
options() {
if (this.property in this.list.field_options) {
return this.list.field_options[this.property];
}
return [];
},
_option(option) {
return this.list.field_options['_'+this.property][option];
},
},
});
/*
* A component to count the characters remaining in a text area.
*/
Vue.component('characters-remaining', {
template : `<small v-bind:class="{'text-danger': toobig, 'text-warning': nearlyfull}" class="text-sm float-right form-text">Characters Remaining: {{remaining}} / {{max}}</small>`,
props: ['property','max'],
computed : {
remaining() {
if (_.isString(this.property)) {
return this.max - this.property.length;
}
return this.max;
},
toobig() {
return this.remaining <= 0;
},
nearlyfull() {
const fivepercent = this.max * 0.05;
return this.remaining < fivepercent && this.remaining > 0;
}
},
});
/*
* A button to toggle confirmations.
*/
Vue.component('confirmation-toggle', {
template : `<button v-if="wing.confirmations.enabled()" class="btn btn-danger" @click="wing.confirmations.toggle()"><i class="fas fa-minus-circle"></i> Disable Confirmations</button>
<button v-else class="btn btn-secondary" @click="wing.confirmations.toggle()"><i class="fas fa-check-circle"></i> Enable Confirmations</button>`,
});
/*
* Comments.
*/
Vue.component('comments', {
template : `<template>
<div class="table-responsive">
<table class="table table-striped">
<tr v-for="comment in comments.objects">
<td>
<textarea class="form-control" v-if="comment.stash('edit')" rows="5" v-model="comment.properties.comment" v-autosave="comment"></textarea>
<div v-if="!comment.stash('edit')" style="white-space: pre-wrap;">{{comment.properties.comment|truncate(comment.stash('comment_length')||200)}}</div>
<button class="btn btn-secondary btn-sm mt-3" v-if="comment.stash('comment_length') < 1000000 && comment.properties.comment.length > 200" @click="comment.stash('comment_length',1000000)">Read More</button>
</td>
<td style="width: 40%">
<a :href="comment.properties.user.profile_uri"><img v-if="comment.properties.user.avatar_uri" :src="comment.properties.user.avatar_uri" class="rounded" alt="avatar" style="height: 30px"> {{comment.properties.user.display_name}}</a>
<span class="badge badge-secondary" v-if="special_badge_user_id == comment.properties.user_id">{{special_badge_label}}</span>
<br>
{{comment.properties.date_created|timeago}}
<br>
<i class="far fa-heart" v-show="!comment.properties.i_like" @click="like_comment(comment)"></i>
<i class="fas fa-heart" v-show="comment.properties.i_like" @click="unlike_comment(comment)"></i>
({{comment.properties.like_count}} likes)
<br>
<button class="btn btn-primary btn-sm" @click="comment.stash('edit', !comment.stash('edit'))" v-if="!comment.stash('edit')" v-show="comment.properties.user_id == current_user_id || is_admin == 1"><i class="fas fa-edit"></i> Edit</button>
<button class="btn btn-success btn-sm" @click="comment.stash('edit', !comment.stash('edit'))" v-if="comment.stash('edit')" v-show="comment.properties.user_id == current_user_id || is_admin == 1"><i class="fas fa-edit"></i> Save</button>
<button class="btn btn-danger btn-sm" @click="comment.delete()" v-show="comment.properties.user_id == current_user_id || is_admin == 1"><i class="fas fa-trash-alt"></i> Delete</button>
</td>
</tr>
<tr>
<td>
<textarea class="form-control" rows="5" v-model="comments.new.comment"></textarea>
</td>
<td>
<button class="btn btn-success" @click="comments.create()"><i class="fas fa-edit"></i> Add Comment</button>
</td>
</tr>
</table>
</div>
</template>`,
props: ['comments','special_badge_label','special_badge_user_id', 'current_user_id', 'is_admin'],
data () {
return { }
},
methods : {
like_comment(comment) {
comment.call('POST', comment.properties._relationships.self+'/like', {});
},
unlike_comment(comment) {
comment.call('DELETE', comment.properties._relationships.self+'/like', {});
},
},
});
/*
* Wing Factories, Services, and Utilities
*/
const wing = {
/*
* get a cookie by name
*/
get_cookie(a) {
let b = document.cookie.match('(^|;)\\s*' + a + '\\s*=\\s*([^;]+)');
return b ? b.pop() : '';
},
/*
* scroll the window to an element
*/
scroll_to (el) {
var elbox = el.getBoundingClientRect();
var bodybox = document.body.getBoundingClientRect();
window.scroll(elbox.left - bodybox.left, elbox.top - bodybox.top);
},
/*
* base URI when you're working against a server that is not on your domain
*/
base_uri : '',
format_base_uri : function(uri_suffix) {
return wing.base_uri + uri_suffix;
},
/*
* format wing options as bootstrap-vue options
*/
format_field_options : function(wing_options) {
const bv_options = {};
for (const field in wing_options) {
if (!field.startsWith('_')) {
bv_options[field] = [];
for (const key in wing_options[field]) {
const value = wing_options[field][key];
bv_options[field].push({
value : value,
text : wing_options['_'+field][value],
});
}
}
}
return bv_options;
},
/*
* return field options for a particular field formatted as bootstrap-vue options
*/
get_field_options : function(field, wing_options) {
const bv_options = [];
for (const key in wing_options[field]) {
const value = wing_options[field][key];
bv_options.push({
value : value,
text : wing_options['_'+field][value],
});
}
return bv_options;
},
/*
* Manages the ajax progress bar
*/
throbber : new Vue({
el: '#wingajaxprogress',
data : { counter : 0, max: 100, workers : 0 },
methods : {
working () {
this.counter = 100;
this.workers++;
},
done () {
const self = this;
self.workers--;
if (self.workers < 1) {
self.counter = 1;
setTimeout(function() {
self.counter = 0;
}, 200)
}
},
}
}),
confirmations : {
_enabled : true,
enabled () {
return wing.confirmations._enabled;
},
disabled () {
return !wing.confirmations._enabled;
},
toggle () {
if (wing.confirmations._enabled == true) {
if (confirm('Are you sure you want to disable confirmations on deletes?')) {
wing.confirmations._enabled = false;
}
}
else {
wing.confirmations._enabled = true;
}
},
},
/*
* Manages a single wing database record via Ajax.
*/
format_post_data(params) {
var form = new FormData();
_.forEach(params, function(value, key) {
//console.log('--'+key+'--');
//console.dir(value)
if (typeof(value) == 'object') {
if (value instanceof File) { // handle file upload
//console.log(key+' is a file');
form.append(key, value);
}
else if (value == null) { // handle null
//console.log(key+' is null');
// skip it
}
else if (Array.isArray(value) && typeof(value[0]) == 'object') { // handle an array of objects as JSON
//console.log(key+' is an array of objects');
form.append(key, JSON.stringify(value));
}
else if (Array.isArray(value)) { // handle an array of values as individual key value pairs
//console.log(key+' is an array of key value pairs');
_.forEach(value, function(element) {
form.append(key, element);
});
}
else { // just a normal object hash
//console.log(key+' is an object hash');
form.append(key, JSON.stringify(value));
}
}
else { // handle values
//console.log(key+' is an normal value');
form.append(key, value);
}
});
return form;
},
object : (behavior) => ({
properties : behavior.properties || {},
params : _.defaultsDeep({}, behavior.params, { _include_relationships : 1}),
create_api : behavior.create_api,
fetch_api : behavior.fetch_api,
_stash : {},
stash(name,value) {
const self = this;
if (typeof(value) !== 'undefined') {
Vue.set(self._stash, name, value);
}
if (name in self._stash) {
return self._stash[name];
}
else {
return null;
}
},
fetch : function(options) {
const self = this;
const fetch_api = (typeof self.properties !== 'undefined' && typeof self.properties._relationships !== 'undefined' && self.properties._relationships.self) || self.fetch_api;
if (!fetch_api) {
console.error('wing.object fetch_api is empty');
}
const promise = axios({
method:'get',
url: wing.format_base_uri(fetch_api),
params : self.params,
withCredentials : behavior.with_credentials != null ? behavior.with_credentials : true,
});
promise.then(function (response) {
const data = response.data;
self.properties = data.result;
self.id = data.result.id;
if (typeof options !== 'undefined' && typeof options.on_success !== 'undefined') {
options.on_success(data.result);
}
if (typeof behavior.on_fetch !== 'undefined') {
behavior.on_fetch(data.result);
}
})
.catch( function (error) {
console.dir(error);
const data = error.response.data;
if (typeof options !== 'undefined' && typeof options.on_error !== 'undefined') {
options.on_error(data.result);
}
if (typeof behavior.on_error !== 'undefined') {
behavior.on_error(data.result);
}
return self;
});
return promise;
},
format_field_options : function() {
return wing.format_field_options(this.properties._options || {});
},
get_field_options : function(field) {
return wing.get_field_options(field, this.properties._options || {});
},
create : function(properties, options) {
const self = this;
if (!self.create_api) {
console.error('wing.object create_api is empty');
}
const params = wing.format_post_data(_.extend({}, self.params, properties));
const promise = axios({
method:'post',
url: wing.format_base_uri(self.create_api),
data : params,
withCredentials : behavior.with_credentials != null ? behavior.with_credentials : true,
});
promise.then(function (response) {
const data = response.data;
self.properties = data.result;
self.id = data.result.id;
if (typeof options !== 'undefined' && typeof options.on_success !== 'undefined') {
options.on_success(data.result);
}
if (typeof behavior.on_create !== 'undefined') {
behavior.on_create(data.result);
}
})
.catch( function (error) {
console.dir(error);
const data = error.response.data;
if (typeof options !== 'undefined' && typeof options.on_error !== 'undefined') {
options.on_error(data.result);
}
if (typeof behavior.on_error !== 'undefined') {
behavior.on_error(data.result);
}
});
return promise;
},
update : function(options) {
const self = this;
return self.partial_update(self.properties, options);
},
save : _.debounce(function(property, value) {
return this._save(property, value);
}, 200),
_save : function(property, value) {
const self = this;
const update = {};
update[property] = value || self.properties[property];
return self._partial_update(update);
},
call : function(method, uri, properties, options) {
const self = this;
const params = _.extend({}, self.params, properties);
const config = {
method: method.toLowerCase(),
url: wing.format_base_uri(uri),
params : params,
withCredentials : behavior.with_credentials != null ? behavior.with_credentials : true,
};
if (config.method == 'put' || config.method == 'post') {
config['data'] = wing.format_post_data(params);
}
else {
config['params'] = params;
}
const promise = axios(config);
promise.then(function (response) {
const data = response.data;
self.properties = data.result;
if (typeof options !== 'undefined' && typeof options.on_success !== 'undefined') {
options.on_success(data.result);
}
})
.catch( function (error) {
console.error('Problem with CALL: '+uri);
console.dir(error);
const data = error.response.data;
if (typeof options !== 'undefined' && typeof options.on_error !== 'undefined') {
options.on_error(data.result);
}
if (typeof behavior.on_error !== 'undefined') {
behavior.on_error(data.result);
}
});
return promise;
},
partial_update : _.debounce(function(properties, options) {
return this._partial_update(properties, options);
}, 200),
_partial_update : function(properties, options) {
const self = this;
const params = wing.format_post_data(_.extend({}, self.params, properties));
const promise = axios({
method: 'put',
url: wing.format_base_uri(self.properties._relationships.self),
data : params,
withCredentials : behavior.with_credentials != null ? behavior.with_credentials : true,
});
promise.then(function (response) {
const data = response.data;
self.properties = data.result;
if (typeof options !== 'undefined' && typeof options.on_success !== 'undefined') {
options.on_success(data.result);
}
if (typeof behavior.on_update !== 'undefined') {
behavior.on_update(data.result);
}
})
.catch( function (error) {
console.error(error);
const data = error.response.data;
if (typeof options !== 'undefined' && typeof options.on_error !== 'undefined') {
options.on_error(data.result);
}
if (typeof behavior.on_error !== 'undefined') {
behavior.on_error(data.result);
}
});
return promise;
},
delete : function(options) {
const self = this;
const object = self.properties;
if (_.isEmpty(object._relationships.self)) {
console.error('You need to specify an API URL to use the wing.delete method.');
}
let message = 'Are you sure?';
if ('name' in object) {
message = 'Are you sure you want to delete ' + object.name + '?';
}
if ((typeof options !== 'undefined' && typeof options.skip_confirm !== 'undefined' && options.skip_confirm == true) || wing.confirmations.disabled() || confirm(message)) {
const promise = axios({
method: 'delete',
url: wing.format_base_uri(object._relationships.self),
params : self.params,
withCredentials : behavior.with_credentials != null ? behavior.with_credentials : true,
});
promise.then(function (response) {
const data = response.data;
if (typeof options !== 'undefined' && typeof options.on_success !== 'undefined') {
options.on_success(object);
}
if (typeof behavior.on_delete !== 'undefined') {
behavior.on_delete(object);
}
self.properties = {};
})
.catch( function (error) {
console.dir(error);
const data = error.response.data;
if (typeof options !== 'undefined' && typeof options.on_error !== 'undefined') {
options.on_error(data.error);
}
if (typeof behavior.on_error !== 'undefined') {
behavior.on_error(data.error);
}
});
return promise;
}
},
}),
/*
* Manages wing lists of objects, like "users" rather than "user"
*/
object_list : (behavior) => ({
params : _.defaultsDeep({}, behavior.params, { _include_relationships : 1}),
objects : [],
paging : {},
new : _.defaultsDeep({}, behavior.new_defaults),
reset_new() { this.new = _.defaultsDeep({}, behavior.new_defaults) },
list_api : behavior.list_api,
create_api : behavior.create_api,
field_options : {},
items_per_page_options : [
{ value : 5, text : "5 per page" },
{ value : 10, text : "10 per page" },
{ value : 25, text : "25 per page" },
{ value : 50, text : "50 per page" },
{ value : 100, text : "100 per page" },
],
find_object_index : function(id) {
const self = this;
for (var i = 0, len = self.objects.length; i < len; i++) {
if (self.objects[i].properties.id === id) return i;
}
return -1;
},
find_object : function(id) {
const self = this;
const index = self.find_object_index(id);
if (index == -1) {
return null;
}
return self.objects[index];
},
_create_object : function(properties) {
const self = this;
return wing.object({
properties : properties,
params : self.params,
create_api : self.create_api,
on_create : behavior.on_create,
on_update : behavior.on_update,
on_delete : function(properties) {
const myself = this;
self.paging.total_items--;
if ('on_delete' in behavior) {
behavior.on_delete(properties);
}
self.remove(properties.id);
},
});
},
append : function(properties, options) {
const self = this;
const new_object = self._create_object(properties);
self.objects.push(new_object);
if (typeof options !== 'undefined' && typeof options.on_each !== 'undefined') {
options.on_each(properties, self.objects[self.objects.length -1]);
}
if (typeof behavior.on_each !== 'undefined') {
behavior.on_each(properties, self.objects[self.objects.length -1]);
}
return new_object;
},
search : _.debounce(function(options) {
return this._search(options);
}, 200),
_search : function(options) {
const self = this;
if (!self.list_api) {
console.error('wing.object_list list_api is empty');
}
let pagination = {
_page_number : self.paging.page_number || 1,
_items_per_page : self.paging.items_per_page || 10,
};
if (typeof options !== 'undefined' && typeof options.params !== 'undefined') {
pagination = _.extend({}, pagination, options.params);
}
const params = _.extend({}, pagination, self.params);
const promise = axios({
method: 'get',
url: wing.format_base_uri(self.list_api),
params : params,
withCredentials : behavior.with_credentials != null ? behavior.with_credentials : true,
});
promise.then(function (response) {
const data = response.data;
if (typeof options === 'undefined' || typeof options !== 'undefined' && options.accumulate != true) {
self.objects = [];
}
for (var index = 0; index < data.result.items.length; index++) {
self.append(data.result.items[index], options);
}
self.paging = data.result.paging;
const items = data.result.items;
if (typeof options !== 'undefined' && typeof options.prepend_item !== 'undefined') { // useful for typeahead
items.unshift(options.prepend_item);
}
if (typeof options !== 'undefined' && typeof options.on_success !== 'undefined') {
options.on_success(data.result);
}
if (typeof behavior.on_success !== 'undefined') {
behavior.on_success(data.result);
}
return items;
})
.catch(function (error) {console.error(error)});
return promise;
},
all : _.debounce(function(options, page_number) {
return this._all(options, page_number);
}, 200),
_all : function(options, page_number) {
const self = this;
if (!self.list_api) {
console.error('wing.object_list list_api is empty');
}
let params = _.extend({}, {
_page_number: page_number || 1,
_items_per_page: 10,
}, self.params);
if (typeof options !== 'undefined' && typeof options.params !== 'undefined') {
params = _.extend({}, params, options.params);
}
const promise = axios({
method: 'get',
url: wing.format_base_uri(self.list_api),
params : params,
withCredentials : behavior.with_credentials != null ? behavior.with_credentials : true,
});
promise.then(function (response) {
const data = response.data;
for (var index in data.result.items) {
self.append(data.result.items[index], options);
}
if (typeof options !== 'undefined' && typeof options.on_success !== 'undefined') {
options.on_success();
}
if (typeof behavior.on_success !== 'undefined') {
behavior.on_success();
}
if (data.result.paging.page_number < data.result.paging.total_pages) {
return self._all(options, data.result.paging.next_page_number);
}
else {
if (typeof options !== 'undefined' && typeof options.on_all_done !== 'undefined') {
options.on_all_done();
}
}
})
.catch(function (error) {console.error(error)});
return promise;
},
reset : function() {
const self = this;
self.objects = [];
return self;
},
call : function(method, uri, properties, options) {
const self = this;
const params = _.extend({}, params, self.params, properties);
const promise = axios({
method: method.toLowerCase(),
url: wing.format_base_uri(uri),
params : params,
withCredentials : behavior.with_credentials != null ? behavior.with_credentials : true,
});
promise.then(function (response) {
const data = response.data;
if (typeof options !== 'undefined' && typeof options.on_success !== 'undefined') {
options.on_success(data.result);
}
})
.catch(function (error) {
console.error(error);
const data = error.response.data;
if (typeof options !== 'undefined' && typeof options.on_error !== 'undefined') {
options.on_error(data.result);
}
if (typeof behavior.on_error !== 'undefined') {
behavior.on_error(data.result);
}
});
return promise;
},
options_api : function() {
const self = this;
if (behavior.options_api != null) {
return behavior.options_api;
}
return self.create_api + '/_options';
},
fetch_options : function(options) {
const self = this;
const promise = axios({
method: 'get',
url: wing.format_base_uri(self.options_api()),
withCredentials : behavior.with_credentials != null ? behavior.with_credentials : true,
});
promise.then(function (response) {
const data = response.data;
self.field_options = data.result;
if (typeof options !== 'undefined' && typeof options.on_success !== 'undefined') {
options.on_success(data.result);
}
})
.catch(function (error) {
console.error(error);
const data = error.response.data;
if (typeof options !== 'undefined' && typeof options.on_error !== 'undefined') {
options.on_error(data.result);
}
});
return promise;
},
format_field_options : function() {
return wing.format_field_options(this.field_options || {});
},
get_field_options : function(field) {
return wing.get_field_options(field, this.field_options || {});
},
format_objects_as_field_options : function(text_field) {
const self = this;
const bv_options = [];
for (const key in self.objects) {
bv_options.push({
text : self.objects[key].properties[text_field],
value : self.objects[key].properties.id,
});
}
return bv_options;
},
create : function(new_properties, options) {
const self = this;
if (!self.create_api) {
console.error('wing.object_list create_api is empty');
}
let properties = new_properties;
if (typeof properties === 'undefined') {
properties = self.new;
}
const new_object = self._create_object(properties);
const add_it = function() {
if ((typeof options !== 'undefined' && typeof options.unshift !== 'undefined' && options.unshift == true) || (typeof behavior.unshift_on_create !== 'undefined' && behavior.unshift_on_create)) {
self.objects.unshift(new_object);
}
else {
self.objects.push(new_object);
}
self.paging.total_items++;
self.reset_new();
};
if (typeof options !== 'undefined') {
if (typeof options.on_success !== 'undefined') {
const success = options.on_success;
options.on_success = function(properties) {
add_it();
success(properties, new_object);
};
}
else {
options['on_success'] = add_it;
}
}
else {
options = {on_success : add_it};
}
return new_object.create(properties, options);
},
update : function(index, options) {
const self = this;
return self.objects[index].update(options);
},
save : function(index, property) {
const self = this;
return self.objects[index].save(property);
},