Passed
Push — master ( b733e9...2da5d3 )
by Vasyl
07:47 queued 03:37
created

resources/js/dashboard.js   F

Complexity

Total Complexity 103
Complexity/F 1.58

Size

Lines of Code 627
Function Count 65

Duplication

Duplicated Lines 627
Ratio 100 %

Importance

Changes 0
Metric Value
wmc 103
eloc 430
mnd 38
bc 38
fnc 65
dl 627
loc 627
rs 2
bpm 0.5846
cpm 1.5846
noi 30
c 0
b 0
f 0

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complexity

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like resources/js/dashboard.js often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
var initFieldMoreItemsSortable = function () {},
2
    initFieldSelect2Static = function () {},
3
    initJsVerificationSlugField = function () {};
4
5
$(function () {
6
7
    'use strict';
8
9
    const LANGUAGE = $('html').attr('lang') || 'ru';
10
11
    $(document).ajaxStart(function () {
12
        Pace.restart()
13
    });
14
    
15
    $.ajaxSetup({
16
        headers: {
17
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
18
        }
19
    });
20
21
    $('.field-checkbox-ajax').each(function(){
22
        var $base = $(this),
23
            url = $base.data('url'),
24
            method = $base.data('method') || 'POST',
25
            $input = $base.find('input.checkbox'),
26
            fieldName = $input.attr('name'),
27
            rawFieldName = $input.data('raw-name'),
28
            format = $base.data('format');
29
30
        $input.on('change', function () {
31
            var value = this.checked ? 1 : 0,
32
                data = format === 'name,value' ? {name: rawFieldName, value: value} : {[rawFieldName] : value};
33
            $.ajax({
34
                method: method,
35
                url: url,
36
                dataType: 'json',
37
                data: data,
38
                success: function (data) {
39
                    if (data.message) {
40
                        $base.append('<div class="text-success">' + data.message + '</div>')
41
                        $base.find('.text-success').delay(2000).fadeOut(500, 'linear', function () {
42
                            $(this).remove()
43
                        })
44
                    }
45
                },
46
                error: function () {
47
                    console.log('Error Ajax!')
48
                    $base.append('<div class="text-danger">Error Ajax</div>')
49
                    $base.find('.text-danger').delay(2000).fadeOut(500, 'linear', function () {
50
                        $(this).remove()
51
                    })
52
                },
53
                complete: function () {
54
                    $base.find('.overlay').addClass('hidden')
55
                }
56
            })
57
        });
58
    });
59
60
    $('.field-select2-change-status-ajax').each(function () {
61
        var $base = $(this),
62
            $select = $base.find('.select2-change-status-ajax'),
63
            url = $base.data('url'),
64
            fieldName = $base.find('select').attr('name'),
65
            method = $base.data('method') || 'GET',
66
            $select2 = $select.select2({
67
                language: LANGUAGE,
68
                tags: false
69
            });
70
71
        $select2.on("select2:select", function (e) {
72
            $base.find('.overlay').removeClass('hidden');
73
74
            $.ajax({
75
                method: method,
76
                url: url,
77
                dataType: 'json',
78
                data: {name: fieldName, value: e.params.data.id},
79
                success: function (data) {
80
                    if (data.message) {
81
                        $base.append('<div class="text-success">' + data.message + '</div>')
82
                        $base.find('.text-success').delay(2000).fadeOut(500, 'linear', function () {
83
                            $(this).remove()
84
                        })
85
                    }
86
                },
87
                error: function () {
88
                    console.log('Error Ajax!')
89
                    $base.append('<div class="text-danger">Error Ajax</div>')
90
                    $base.find('.text-danger').delay(2000).fadeOut(500, 'linear', function () {
91
                        $(this).remove()
92
                    })
93
                },
94
                complete: function () {
95
                    $base.find('.overlay').addClass('hidden')
96
                }
97
            })
98
        })
99
    })
100
101
    $('.field-select2-tree-ajax').each(function () {
102
        var $base = $(this),
103
            $select = $base.find('.select2-tree'),
104
            url = $base.data('url'),
105
            valFld = $base.data('valFld') ? $base.data('valFld') : 'id',
106
            labelFld = $base.data('labelFld') ? $base.data('labelFld') : 'name',
107
            incFld = $base.data('incFld') ? $base.data('incFld') : 'children'
108
109
        $.ajax({
110
            method: 'GET',
111
            url: url,
112
            dataType: 'json',
113
            data: {data: ''},
114
            success: function (data) {
115
                $select.select2ToTree({
116
                    treeData: {
117
                        dataArr: data.data,
118
                        dftVal: data.default,
119
                        valFld: valFld,
120
                        labelFld: labelFld,
121
                        'incFld': incFld
122
                    }
123
                })
124
            },
125
            error: function () {
126
                console.log('Error Ajax!')
127
            },
128
            complete: function () {
129
                $base.find('.overlay').fadeOut(200)
130
            }
131
        })
132
    })
133
134
    $('.field-tree').each(function () {
135
        var $base = $(this),
136
            $tree = $base.find('.field-tree-data'),
137
            url = $base.data('url'),
138
            showCheckbox = $base.data('showCheckbox') === undefined ? true : $base.data('showCheckbox'),
139
            showIcon = $base.data('showIcon') === undefined ? false : $base.data('showIcon'),
140
            fieldName = $base.data('field-name'),
141
            $inputs = $base.find('.field-tree-inputs'),
142
            getCheckedIds = function (obj) {
143
                $inputs.html('')
144
                var array = []
145
                obj.forEach(element => {
146
                    $inputs.append('<input type="hidden" name="' + fieldName + '[]" value="' + element.id + '" />')
147
                })
148
                return array
149
            }
150
151
        $.ajax({
152
            method: 'GET',
153
            url: url,
154
            dataType: 'json',
155
            data: {data: ''},
156
            success: function (data) {
157
                $tree.treeview({
158
                    data: data,
159
                    showIcon: showIcon,
160
                    showCheckbox: showCheckbox,
161
                })
162
163
                getCheckedIds($tree.treeview('getChecked'))
164
165
                $tree.on('nodeChecked', function (event, data) {
166
                    // console.log($(this).treeview('getChecked'))
167
                    getCheckedIds($(this).treeview('getChecked'))
168
                })
169
                $tree.on('nodeUnchecked', function (event, data) {
170
                    // console.log($(this).treeview('getChecked'))
171
                    getCheckedIds($(this).treeview('getChecked'))
172
                })
173
            },
174
            error: function () {
175
                console.log('Error Ajax!')
176
            },
177
            complete: function () {
178
                $base.find('.overlay').fadeOut(200)
179
            }
180
        })
181
182
    })
183
184
    if ($('textarea.ck-editor.ck-mini').length) {
185
        $('textarea.ck-editor.ck-mini').ckeditor(ckMini || {})
186
    }
187
188
    if ($('textarea.ck-editor.ck-small').length) {
189
        $('textarea.ck-editor.ck-small').ckeditor(ckSmall || {})
190
    }
191
192
    if ($('textarea.ck-editor.ck-full').length) {
193
        $('textarea.ck-editor.ck-full').ckeditor(ckFull || {})
194
    }
195
196
    if ($('.field-x-editable').length) {
197
        $('.field-x-editable').editable(xEditable || {});
198
    }
199
200
    if ($('.field-colorpicker').length) {
201
        $('.field-colorpicker').colorpicker(colorpickerOptions || {});
202
    }
203
204
    if ($('.field-datetimepicker').length) {
205
        $('.field-datetimepicker').datetimepicker(datetimepickerOptions || {
206
            format: 'Y/m/d H:i:s'
207
        });
208
    }
209
210
    if ($('.field-datepicker').length) {
211
        $('.field-datepicker').datetimepicker(datepickerOptions || {
212
            timepicker:false,
213
            format:'d/m/Y'
214
        });
215
    }
216
217
    if ($('.field-timepicker').length) {
218
        $('.field-timepicker').datetimepicker(timepickerOptions || {
219
            datepicker:false,
220
            format: 'H:i'
221
        });
222
    }
223
224
    initJsVerificationSlugField = function () {
225
        if ($('.js-verification-slug-field').length) {
226
            if ($('input.js-slug-field-change').is(':checked')) {
227
                $('.js-verification-slug-field input.js-slug-field-input')
228
                    .prop('readonly', false)
229
                    .prop('disabled', false)
230
            }
231
            $(document).on('change', '.js-verification-slug-field [type="checkbox"]', function () {
232
                var $wrap = $(this).closest('.js-verification-slug-field');
233
                if(this.checked) {
234
                    $wrap.find('input.js-slug-field-input')
235
                        .prop('readonly', false)
236
                        .prop('disabled', false)
237
                } else {
238
                    $wrap.find('input.js-slug-field-input')
239
                        .prop('readonly', true)
240
                        .prop('disabled', true)
241
                }
242
            })
243
        }
244
    }
245
    initJsVerificationSlugField();
246
247
    $(document).on('click', '.js-action-form', function (e) {
248
        e.preventDefault()
249
        var $form = $('#js-action-form'),
250
            $this = $(this),
251
            method = $this.data('method') || 'POST',
252
            strConfirm = $this.data('confirm') ? confirm($this.data('confirm')) : true,
253
            destination = $(this).data('destination'),
254
            url = $(this).data('url');
255
        
256
        if (url && $form && strConfirm) {
257
            $form.find('input[name="_method"]').val(method)
258
            if (destination) {
259
                $form.find('input.js-destination-val').val(destination)
260
            }
261
            $form.attr('action', url).submit()
262
        }
263
        return false
264
    });
265
266
    // 10000 -> 10 000
267
    $('.js-num-format').each(function (index, value) {
268
        var number = parseFloat(value.textContent);
269
        value.textContent = numberWithSpaces(number);
270
    });
271
    function numberWithSpaces(x) {
272
        return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ");
273
    }
274
    
275
    initFieldSelect2Static = function () {
276
        $('.field-select2-static').each(function () {
277
            var $base = $(this),
278
                $select = $base.find('.select2-static'),
279
                urlSave = $base.data('url-save');
280
281
            // Autosave after change
282
            if (urlSave) {
283
                var fieldName = $base.find('select').data('name'),
284
                    method = $base.data('method-save') || 'POST',
285
                    $select2 = $select.select2({
286
                        language: LANGUAGE,
287
                        tags: false
288
                    });
289
290
                $select2.on('change', function (e) {
291
                    var values = $select.first(':selected').val();
292
                    $base.find('.overlay').removeClass('hidden');
293
                    $.ajax({
294
                        method: method,
295
                        url: urlSave,
296
                        dataType: 'json',
297
                        data: {name: fieldName, value: values},
298
                        success: function (data) {
299
                            if (data.message) {
300
                                $base.append('<div class="text-success">' + data.message + '</div>')
301
                                $base.find('.text-success').delay(2000).fadeOut(500, 'linear', function () {
302
                                    $(this).remove()
303
                                })
304
                            }
305
                        },
306
                        error: function () {
307
                            console.log('Error Ajax!')
308
                            $base.append('<div class="text-danger">Error Ajax</div>')
309
                            $base.find('.text-danger').delay(2000).fadeOut(500, 'linear', function () {
310
                                $(this).remove()
311
                            })
312
                        },
313
                        complete: function () {
314
                            $base.find('.overlay').addClass('hidden')
315
                        }
316
                    });
317
                });
318
            } else {
319
                $select.select2({
320
                    language: LANGUAGE,
321
                    tags: false
322
                });
323
            }
324
        });
325
    }
326
    initFieldSelect2Static();
327
328
    if ($('.select2.select2-tags').length) {
329
        $('.select2.select2-tags').each(function (index) {
330
            var url = $(this).data('url') || $(this).data('route'),
331
                maximumSelection = $(this).data('max') || -1,
332
                tokenSeparators = $(this).data('separators') || [',', ';'],
333
                newTagLabel = $(this).data('new-tag-label') || ' (new tag)';
334
335
            $(this).select2({
336
                language: LANGUAGE,
337
                tags: true,
338
                tokenSeparators: tokenSeparators,
339
340
                ajax: url ? {
341
                    delay: 250,
342
                    url: url,
343
                    dataType: 'json',
344
                    processResults: function(data) {
345
                        return {
346
                            results: data.results
347
                        }
348
                    }
349
                } : undefined,
350
351
                // Some nice improvements:
352
353
                // max tags is 3
354
                maximumSelectionLength: maximumSelection,
355
356
                // add "(new tag)" for new tags
357
                createTag: function (params) {
358
                    var term = $.trim(params.term);
359
360
                    if (term === '') {
361
                        return null;
362
                    }
363
364
                    return {
365
                        id: term,
366
                        text: term + newTagLabel
367
                    };
368
                },
369
            });
370
        });
371
    }
372
373
    if ($('.select2.sortable').length) {
374
        $('.select2.sortable').select2({
375
            language: LANGUAGE,
376
            tags: true
377
        })
378
379
        $('.select2.sortable').on("select2:select", function (evt) {
380
            var element = evt.params.data.element
381
            var $element = $(element)
382
383
            $element.detach()
384
            $(this).append($element)
385
            $(this).trigger("change")
386
        })
387
    }
388
389
    if ($('.select2.field-select-ajax').length) {
390
        $('.select2.field-select-ajax').each(function (index) {
391
            var url = $(this).data('url') || $(this).data('route')
392
393
            $(this).select2({
394
                language: LANGUAGE,
395
                tags: false,
396
                ajax: {
397
                    delay: 250,
398
                    url: url,
399
                    dataType: 'json'
400
                }
401
            });
402
        });
403
    }
404
405
    $('.lte-daterangepicker').each(function () {
406
        $(this).on('apply.daterangepicker', function (ev, picker) {
407
            var $inputNameStart = $(this).data('input-name-start'),
408
                $inputNameEnd = $(this).data('input-name-end'),
409
                $format = $(this).data('format') || 'MM/DD/YYYY'
410
            $(this).val(picker.startDate.format($format) + ' - ' + picker.endDate.format($format))
411
            $(this).siblings('input[name="' + $inputNameStart + '"]').val(picker.startDate.format($format))
412
            $(this).siblings('input[name="' + $inputNameEnd + '"]').val(picker.endDate.format($format))
413
        })
414
415
        $(this).on('cancel.daterangepicker', function (ev, picker) {
416
            $(this).val('')
417
        })
418
419
        $(this).daterangepicker({
420
            autoUpdateInput: false,
421
            "locale": translates.localeDateRangePicker || {
422
                "format": "MM/DD/YYYY",
423
                "separator": " - ",
424
                "applyLabel": "Apply",
425
                "cancelLabel": "Cancel",
426
                "fromLabel": "From",
427
                "toLabel": "To",
428
                "customRangeLabel": "Custom",
429
                "weekLabel": "W",
430
                "daysOfWeek": [
431
                    "Su",
432
                    "Mo",
433
                    "Tu",
434
                    "We",
435
                    "Th",
436
                    "Fr",
437
                    "Sa"
438
                ],
439
                "monthNames": [
440
                    "January",
441
                    "February",
442
                    "March",
443
                    "April",
444
                    "May",
445
                    "June",
446
                    "July",
447
                    "August",
448
                    "September",
449
                    "October",
450
                    "November",
451
                    "December"
452
                ],
453
                "firstDay": 1
454
            }
455
        })
456
    })
457
458
    $('[data-toggle="tooltip"]').tooltip()
459
460
    $(document).on('click', '.js-fill-modal', function (e) {
461
        e.preventDefault()
462
        var $this = $(this),
463
            url = $this.data('url'),
464
            dataFields = $this.data('fields'),
465
            modal = $($this.data('target'));
466
467
        console.log(modal);
468
469
        if (url) {
470
            modal.find('form').attr('action', url)
471
        }
472
        for (var field in dataFields) {
473
            modal.find('[name="' + field + '"]').val(dataFields[field]);
474
        }
475
476
        modal.modal() // Bootstrap!
477
    })
478
479
    var treeSortable = {}
480
481
    if ($('.tree-sortable').length) {
482
        $('.tree-sortable').each(function () {
483
            treeSortable[$(this).data('entity-name')] = $(this).sortable({
484
                group: 'serialization',
485
                delay: 500,
486
                handle: '.handle',
487
                onDrop: function ($item, container, _super) {
488
                    _super($item, container);
489
                }
490
            })
491
        })
492
    }
493
494
    $(document).on('click', '.post-tree-sortaple', function (e) {
495
        e.preventDefault()
496
        e.stopPropagation()
497
        var $base = $(this),
498
            data = treeSortable[$(this).data('entity-name')].sortable("serialize").get(),
499
            url = $base.data('url');
500
501
        $.ajax({
502
            method: 'POST',
503
            url: url,
504
            dataType: 'json',
505
            data: {'data': data},
506
            beforeSend: function () {
507
                $base.attr('disabled', true)
508
                    .find('.fa')
509
                    .toggleClass('fa-spin')
510
                    .toggleClass('fa-refresh')
511
            },
512
            success: function (data) {
513
                console.log(data)
514
            },
515
            error: function () {
516
                console.log('Error Ajax!')
517
            },
518
            complete: function () {
519
                $base.attr('disabled', false)
520
                    .find('.fa')
521
                    .toggleClass('fa-spin')
522
                    .toggleClass('fa-refresh')
523
            }
524
        })
525
    })
526
527
    if ($('.field-links').length) {
528
        $('.field-links').on('click', '.btn-info', function (e) {
529
            e.preventDefault()
530
            var n = $(this).parents('.field-links').find('.btn-info').index(this),
531
                length = $(this).parents('.field-links').find('.btn-info').length,
532
                fieldName = $(this).parents('.field-links').data('field-name'),
533
                keyKey = $(this).parents('.field-links').data('key'),
534
                keyValue = $(this).parents('.field-links').data('value'),
535
                placeholderKey = $(this).parents('.field-links').data('placeholder-key'),
536
                placeholderValue = $(this).parents('.field-links').data('placeholder-value'),
537
                item = '<tr class="item">'
538
                    + '<td>'
539
                    + '<div class="input-group input-group-md">'
540
                    + '<input type="text" name="' + fieldName + '[' + (length) + '][' + keyKey + ']" class="form-control" placeholder="' + placeholderKey + '">'
541
                    + '<span class="input-group-btn" style="width: 40%">'
542
                    + '<input type="text" name="' + fieldName + '[' + (length) + '][' + keyValue + ']" class="form-control" placeholder="' + placeholderValue + '">'
543
                    + '</span>'
544
                    + '<span class="input-group-btn">'
545
                    + '<button type="button" class="btn btn-info btn-flat">'
546
                    + '<i class="fa fa-plus"></i>'
547
                    + '</button>'
548
                    + '<button type="button" class="btn btn-danger btn-flat">'
549
                    + '<i class="fa fa-remove"></i>'
550
                    + '</button>'
551
                    + '</span>'
552
                    + '</div>'
553
                    + '</td>'
554
                    + '</tr>"'
555
556
            $(this).parents('.field-links').find('.item').eq(n).after(item)
557
        })
558
559
        $('.field-links').on('click', '.btn-danger', function (e) {
560
            e.preventDefault()
561
            var n = $(this).parents('.field-links').find('.btn-danger:not(.first)').index(this)
562
563
            $(this).parents('.field-links').find('.item').eq(n).remove()
564
        })
565
    }
566
567
    if ($('.field-linear-list').length) {
568
        $('.field-linear-list').on('click', '.btn-info', function (e) {
569
            e.preventDefault()
570
            var n = $(this).parents('.field-linear-list').find('.btn-info').index(this),
571
                length = $(this).parents('.field-linear-list').find('.btn-info').length,
572
                fieldName = $(this).parents('.field-linear-list').data('field-name'),
573
                placeholderValue = $(this).parents('.field-linear-list').data('placeholder-value'),
574
                item = '<tr class="item">'
575
                    + '<td>'
576
                    + '<div class="input-group input-group-md">'
577
                    + '<span class="input-group-btn" style="width: 100%">'
578
                    + '<input type="text" name="' + fieldName + '[' + (length) + ']" class="form-control" placeholder="' + placeholderValue + ' ' + (parseInt(length) + 1) + '">'
579
                    + '</span>'
580
                    + '<span class="input-group-btn">'
581
                    + '<button type="button" class="btn btn-info btn-flat">'
582
                    + '<i class="fa fa-plus"></i>'
583
                    + '</button>'
584
                    + '<button type="button" class="btn btn-danger btn-flat">'
585
                    + '<i class="fa fa-remove"></i>'
586
                    + '</button>'
587
                    + '</span>'
588
                    + '</div>'
589
                    + '</td>'
590
                    + '</tr>"'
591
            $(this).parents('.field-linear-list').find('.item').eq(n).after(item)
592
        })
593
594
        $('.field-linear-list').on('click', '.btn-danger', function (e) {
595
            e.preventDefault()
596
            var n = $(this).parents('.field-linear-list').find('.btn-danger:not(.first)').index(this)
597
598
            $(this).parents('.field-linear-list').find('.item').eq(n).remove()
599
        })
600
    }
601
602
    initFieldMoreItemsSortable = function () {
603
        if ($('.field-more-items-sortable').length) {
604
            $('.field-more-items-sortable .todo-list').sortable({
605
                handle: '.handle',
606
                onDrop: function ($item, container, _super) {
607
                    _super($item, container);
608
                    $(container.target[0]).find('li').each(function (index) {
609
                        $(this).find('.field-weight-item').val(index)
610
                    })
611
                }
612
            });
613
614
            $('.field-more-items-sortable').on('click', '.filed-remove', function (e) {
615
                e.preventDefault()
616
                $(this).parents('li').hide().find('.field-delete-item').val($(this).data('id'))
617
            })
618
        }
619
    }
620
    initFieldMoreItemsSortable();
621
622
    if ($('.field-more-items').length) {
623
        $('.field-more-items').on('click', '.filed-remove', function (e) {
624
            e.preventDefault()
625
            $(this).parents('tr').hide().find('.field-delete-item').val($(this).data('id'))
626
        })
627
    }
628
629
    $('.js-copy-to-clipboard').on('click', function (e) {
630
        e.preventDefault()
631
        var $tmp = $("<textarea>"),
632
            $text = $(this).data('text');
633
        $("body").append($tmp);
634
        $tmp.val($text).select();
635
        document.execCommand("copy");
636
        $tmp.remove();
637
        $(this).hide().show(100);
638
    });
639
640
641
    /**
642
     * Add cropper editor for input type file
643
     */
644
    $.fn.addCropperToFiled = function (options) {
645
        this.each(function () {
646
            var _self = $(this),
647
                settings = $.extend({
648
                    width: _self?.data('size-width') ? +_self.data('size-width') : (options?.width ? +options.width : 150),
649
                    height: _self?.data('size-height') ? +_self.data('size-height') : (options?.height ? +options.height : 100),
650
                    show_preview: _self?.data('show-preview') ? _self.data('show-preview') : false
651
                }, options),
652
                field_name = _self?.data('field-name') ? _self?.data('field-name') : 'field_cropper_'+settings.width+'x'+settings.height;
653
654
            // Cahnge variables
655
            var timeOut,
656
                // Function for read file from field and convert to base64
657
                toBase64Fn = file => new Promise(function (resolve, reject) {
658
                    var reader = new FileReader();
659
660
                    reader.readAsDataURL(file);
661
                    reader.onload = function () { return resolve(reader.result) };
662
                    reader.onerror = function (error) { return reject(error) };
663
                });
664
665
            // Event change file and cropped to size
666
            _self.on('change', async function (e) {
667
                if (_self.parents('.field-cropper').length) {
668
                    _self.parents('.field-cropper').find('.field-cropper-container').remove();
669
                    _self.removeClass('.field-cropper');
670
                } else {
671
                    _self.wrap('<div class="field-cropper"></div>');
672
                }
673
674
                _self.after(`<div class="field-cropper-container">
675
                            <div class="field-cropper-container__editor"><img style="max-width: 100%;"/></div>`
676
                    +(settings.show_preview ? `<h3 class="field-cropper-container__title">${settings.width}x${settings.height}</h3>
677
                            <div class="field-cropper-container__preview"><img width="${settings.width}" height="${settings.height}"/></div>` : ``)
678
                    +`<input class="field-cropper-container__input" type="hidden" name="${field_name}"/>
679
                        </div>`);
680
681
                //<input class="field-cropper-container__input" type="hidden" name="field_cropper_${settings.width}x${settings.height}"/>
682
683
                var data = await toBase64Fn(e.target.files[0]),
684
                    $parent = _self.parents('.field-cropper'),
685
                    $container = $parent.find('.field-cropper-container'),
686
                    $editor = $container.find('.field-cropper-container__editor img'),
687
                    $input = $container.find('.field-cropper-container__input'),
688
                    $preview = $container.find('.field-cropper-container__preview img');
689
690
                $editor.attr('src', data);
691
692
                if(Object.keys($editor.cropper('getData')).length) {
693
                    $editor.cropper('destroy');
694
                }
695
696
                $editor.cropper({
697
                    aspectRatio: settings.width / settings.height,
698
                    crop: function (event) {
699
                        clearTimeout(timeOut);
700
                        timeOut = setTimeout(function () {
701
                            var cropper = event.target.cropper,
702
                                prevData = cropper.getCroppedCanvas({ width: settings.width, height: settings.height }).toDataURL('image/jpeg');
703
704
                            // Insert base64 to preview
705
                            $preview.attr('src', prevData);
706
                            // Insert base64 to input
707
                            $input.val(prevData);
708
                        }, 200);
709
                    }
710
                });
711
            });
712
        });
713
714
        return this;
715
    };
716
717
    if ($('.field-image-cropper-uploaded').length) {
718
        $('.field-image-cropper-uploaded input.field-input-cropper').addCropperToFiled();
719
720
        $('.field-image-cropper-uploaded').on('click', '.filed-remove', function (e) {
721
            e.preventDefault()
722
            $(this).parents('tr').hide().find('.field-delete-item').val($(this).data('id'))
723
        });
724
    }
725
726
727
    // Displaying blocks depending on the selection in the selection
728
    $('.js-select-blocks').each(function () {
729
        if ($(this).find(':selected')) {
730
            toggleSelectableBlocks($(this).find(':selected').val(), $(this).data('map'))
731
        }
732
    })
733
    $('.js-select-blocks').on('change', function () {
734
        if ($(this).data('map')) {
735
            toggleSelectableBlocks($(this).val(), $(this).data('map'))
736
        }
737
    })
738
    function toggleSelectableBlocks($val, selectBlocksMap) {
739
        for (var key in selectBlocksMap) {
740
            Pace.restart()
741
            if ($val === key) {
742
                for (var id in selectBlocksMap[key]) {
743
                    $(selectBlocksMap[key][id]).show()
744
                }
745
            } else {
746
                for (var id in selectBlocksMap[key]) {
747
                    $(selectBlocksMap[key][id]).hide()
748
                }
749
            }
750
        }
751
    }
752
753
754
    // Set active class LTE menu item
755
    if ($('.sidebar-menu.js-activeable').length) {
756
        var pathnameUrl = window.location.pathname,
757
            url = window.location.href,
758
            path = url.split('?')[0];
759
760
        $('.sidebar-menu.js-activeable li>a').each(function () {
761
            var aHref = $(this).attr("href"),
762
                regexp = $(this).data('pat') ? new RegExp($(this).data('pat')) : false;
763
764
            if (path === aHref || pathnameUrl === aHref || regexp && regexp.test(url)) {
765
                $(this).closest('li').addClass('active');
766
                $(this).closest('li.treeview').addClass('active');
767
            }
768
        });
769
    }
770
771
    // LTE template
772
    $('.js-check-skin').on('click', function (e) {
773
        e.preventDefault();
774
        var skin = $(this).data('skin');
775
        $('body').removeClass($('#lte_default_skin').val()).addClass(skin);
776
        $('#lte_default_skin').val(skin);
777
    });
778
    $('.js-set-body-class').change(function () {
779
        var bodyClass = $(this).data('bodyClass');
780
        this.checked ? $('body').addClass(bodyClass) : $('body').removeClass(bodyClass);
781
    })
782
});
783