Completed
Push — master ( 4fbf71...b6fccf )
by Evgenii
03:05
created

assets/yii2-floor12-files.js (1 issue)

1
console.log('Yii2 files model init.');
2
3
4
var currentCroppingImageId;
5
var currentRenamingFileId;
6
var cropper;
7
var removeFileOnCropCancel;
8
var yii2CropperRoute;
9
10
$(document).on('change', '.yii2-files-upload-field', function () {
11
12
    obj = $(this);
13
14
    var formData = new FormData();
15
    formData.append('file', obj[0].files[0]);
16
    formData.append('modelClass', obj.data('modelclass'));
17
    formData.append('attribute', obj.data('attribute'));
18
    formData.append('mode', obj.data('mode'));
19
    formData.append('ratio', obj.data('ratio'));
20
    formData.append('_fileFormToken', yii2FileFormToken);
21
22
23
    $.ajax({
24
        url: yii2UploadRoute,
25
        type: 'POST',
26
        data: formData,
27
        processData: false,  // tell jQuery not to process the data
28
        contentType: false,  // tell jQuery not to set contentType
29
        success: function (response) {
30
            id = '#files-widget-block_' + obj.data('block');
31
            $(response).appendTo(id).find('div.floor12-files-widget-list');
32
        }
33
    });
34
});
35
36
37
function clipboard(text) {
38
    //based on https://stackoverflow.com/a/12693636
39
    document.oncopy = function (event) {
40
        event.clipboardData.setData("Text", text);
41
        event.preventDefault();
42
    };
43
    document.execCommand("Copy");
44
    document.oncopy = undefined;
45
    f12notification.info(text, 1);
46
}
47
48
function updateProgressCircle(val, btnGroup) {
49
    result = 169.646 * (1 - val / 100);
50
    btnGroup.querySelector('svg #progress-circle').setAttribute('stroke-dashoffset', result);
51
    btnGroup.querySelector('.floor12-file-percents').innerHTML = val + '%';
52
    // setAttribute('stroke-dashoffset', result);
53
}
54
55
var observer = new MutationObserver(function (mutations) {
56
    percent = mutations[0].target.style.width.replace('%', '');
57
    btnGroup = mutations[0].target.parentElement.parentElement;
58
    updateProgressCircle(percent, btnGroup);
59
});
60
61
function Yii2FilesUploaderSet(id, className, attribute, scenario) {
62
63
    var mode = 'multi';
64
    var blockName = "#" + id;
65
    var block = $(blockName);
66
    var uploadButton = block.find('button.btn-upload')[0];
67
    var filesList = block.find('.floor12-files-widget-list')[0];
68
    var ratio = 0;
69
70
    var csrf = block.parents('form').find('input[name=' + yii2CsrfParam + ']').val();
71
72
    if (block.data('ratio'))
73
        ratio = block.data('ratio');
74
75
    if (block.hasClass('floor12-files-widget-single-block')) {
76
        mode = 'single';
77
        toggleSingleUploadButton(block);
78
    }
79
80
    var data = {
81
        modelClass: className,
82
        attribute: attribute,
83
        scenario: scenario,
84
        mode: mode,
85
        ratio: ratio,
86
        _fileFormToken: yii2FileFormToken
87
    }
88
    data[yii2CsrfParam] = csrf
89
90
    var uploader = new ss.SimpleUpload({
91
        button: uploadButton,
92
        url: yii2UploadRoute,
93
        name: 'file',
94
        dropzone: block,
95
        dragClass: 'floor12-files-widget-block-drug-over',
96
        multiple: true,
97
        multipleSelect: true,
98
        data: data,
99
        onSubmit:
100
            function (filename, extension, data) {
101
                var svg = '\t<svg width="60" height="60" viewBox="0 0 60 60">\n' +
102
                    '\t\t<circle cx="30" cy="30" r="27" fill="none" stroke="#ccc" stroke-width="5" />\n' +
103
                    '\t\t<circle id="progress-circle" cx="30" cy="30" r="27" fill="none" stroke="#666" stroke-width="5" stroke-dasharray="169.646" stroke-dashoffset="169.646" />\n' +
104
                    '\t</svg>';
105
106
                var id = generateId(filename);
107
                var btnGroup = document.createElement('div');
108
                var fileObject = document.createElement('div');
109
                var bar = document.createElement('div');
110
                var percents = document.createElement('div');
111
                btnGroup.setAttribute('id', id);
112
                btnGroup.className = 'btn-group files-btn-group';
113
                fileObject.className = 'floor12-file-object';
114
                percents.className = 'floor12-file-percents';
115
116
                this.setProgressBar(bar);
117
118
                fileObject.innerHTML = svg;
119
120
                observer.observe(bar, {
121
                    attributes: true
122
                });
123
124
                fileObject.appendChild(bar);
125
                fileObject.appendChild(percents);
126
                btnGroup.appendChild(fileObject);
127
128
129
                if (mode == 'single') {
130
                    $(filesList).html('');
131
                }
132
                $(filesList).append(btnGroup);
133
134
135
            },
136
        onComplete: function (filename, response) {
137
            if (!response) {
138
                console.log(filename + 'upload failed');
139
                return false;
140
            }
141
            f12notification.info(FileUploadedText, 1);
142
            idName = "#" + generateId(filename);
143
            $(idName).replaceWith($(response));
144
145
            if (mode == 'single')
146
                toggleSingleUploadButton(block);
147
        },
148
        onError: function (filename, errorType, status, statusText, response, uploadBtn, fileSize) {
149
            data = {
150
                responseText: response,
151
                status: status,
152
                statusText: statusText,
153
            };
154
            processError(data);
155
            idName = "#" + generateId(filename);
156
            $(idName).remove();
157
        }
158
159
        //     progressUrl: 'uploadProgress.php', // enables cross-browser progress support (more info below)
160
        //     responseType: 'json',
161
        //    allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
162
        //   maxSize: 1024, // kilobytes
163
        //     hoverClass: 'ui-state-hover',
164
        //     focusClass: 'ui-state-focus',
165
        //     disabledClass: 'ui-state-disabled',
166
    });
167
168
}
169
170
function generateId(filename) {
171
    return 'id-' + filename.replace(/[^0-9a-zA-Z]/g, "");
172
}
173
174
function showUploadButton(event) {
175
    obj = $(event.target);
176
    console.log(obj);
177
    obj.parents('div.floor12-files-widget-single-block').find('button').show();
178
}
179
180
function toggleSingleUploadButton(block) {
181
    if (block.find('div.floor12-single-file-object').length > 0)
182
        block.find('button').hide();
183
    else
184
        block.find('button').show();
185
}
186
187
function sortableFiles() {
188
    $(".floor12-files-widget-list-multi").sortable({
189
        opacity: 0.5,
190
        revert: 1,
191
        items: "div.files-btn-group",
192
    });
193
}
194
195
function removeFile(id) {
196
    id = "#yii2-file-object-" + id;
197
198
    $(id).parents('div.files-btn-group').fadeOut(200, function () {
199
        $(this).remove();
200
        f12notification.info(FileRemovedText, 1);
201
    });
202
    return false;
203
}
204
205
function removeAllFiles(event) {
206
    console.log('removeAllFiles');
207
    $(event.target).parents('div.floor12-files-widget-list').find('div.files-btn-group').fadeOut(200, function () {
208
        $(this).remove();
209
    });
210
    f12notification.info(FilesRemovedText, 1);
211
    return false;
212
}
213
214
function initCropperLayout() {
215
    if (yii2CropperRoute.length > 0)
216
        $.get(yii2CropperRoute, function (response) {
217
            $('body').append(response);
218
219
            $('#yii2-file-title-editor input').on('keyup', function (e) {
220
                if (e.keyCode == 13) {
221
                    saveFileTitle()
222
                }
223
            });
224
        })
225
}
226
227
function initCropper(id, url, ratio, remove) {
228
    $('#cropperModal').modal();
229
230
    currentCroppingImageId = id;
231
232
    removeFileOnCropCancel = false;
233
    if (remove)
234
        removeFileOnCropCancel = true;
235
236
    currentCropImage = $('<img>').attr('src', url);
237
    $('#cropperArea').html("");
238
    $('#cropperArea').append(currentCropImage);
239
240
    autoCrop = false;
241
    aspectRatio = NaN;
0 ignored issues
show
Comprehensibility Best Practice introduced by
You seem to be aliasing the built-in name NaN as aspectRatio. This makes your code very difficult to follow, consider using the built-in name directly.
Loading history...
242
243
    if (ratio) {
244
        autoCrop = true;
245
        aspectRatio = ratio;
246
        $('.cropper-ratio-btn-group').hide();
247
    }
248
249
    setTimeout(function () {
250
        cropper = currentCropImage.cropper({
251
            viewMode: 1,
252
            background: false,
253
            zoomable: false,
254
            autoCrop: autoCrop,
255
            aspectRatio: aspectRatio,
256
        });
257
    }, 1000)
258
}
259
260
function stopCrop(id) {
261
    $('#cropperModal').modal('hide');
262
    if (removeFileOnCropCancel)
263
        removeFile(currentCroppingImageId);
264
}
265
266
function cropImage() {
267
    сropBoxData = cropper.cropper('getCropBoxData');
268
    imageData = cropper.cropper('getImageData');
269
    canvasData = cropper.cropper('getCanvasData');
270
    ratio = imageData.height / imageData.naturalHeight;
271
    cropLeft = (сropBoxData.left - canvasData.left) / ratio;
272
    cropTop = (сropBoxData.top - canvasData.top) / ratio;
273
    cropWidth = сropBoxData.width / ratio;
274
    cropHeight = сropBoxData.height / ratio;
275
    rotated = imageData.rotate;
276
277
    data = {
278
        id: currentCroppingImageId,
279
        width: cropWidth,
280
        height: cropHeight,
281
        top: cropTop,
282
        left: cropLeft,
283
        rotated: rotated,
284
        _fileFormToken: yii2FileFormToken
285
    };
286
287
    removeFileOnCropCancel = false;
288
289
    $.ajax({
290
        url: yii2CropRoute,
291
        'method': 'POST',
292
        data: data,
293
        success: function (response) {
294
            id = '#yii2-file-object-' + currentCroppingImageId;
295
            if ($(id).find('img').length)
296
                $(id).find('img').attr('src', response);
297
            else {
298
                $(id).css('background-image', 'none');
299
                $(id).css('background-image', 'url(' + response + ')');
300
            }
301
            stopCrop();
302
            f12notification.info(FileSavedText, 1);
303
        },
304
        error: function (response) {
305
            processError(response);
306
        }
307
    })
308
}
309
310
function showRenameFileForm(id, event) {
311
    var blockId = '#yii2-file-object-' + id;
312
    var title = $(blockId).attr('title');
313
    currentRenamingFileId = id;
314
    $('#yii2-file-title-editor').css('top', event.clientY).css('left', event.clientX - 70).fadeIn(100);
315
    $('#yii2-file-title-editor input').val(title).focus();
316
}
317
318
function hideYii2FileTitleEditor() {
319
    $('#yii2-file-title-editor').fadeOut(100);
320
    currentRenamingFileId = null;
321
}
322
323
function saveFileTitle() {
324
    $('#yii2-file-title-editor').fadeOut(100);
325
    val = $('#yii2-file-title-editor input').val();
326
    blockId = '#yii2-file-object-' + currentRenamingFileId;
327
    $(blockId).attr('title', val);
328
    $(blockId).attr('data-title', val);
329
330
    $.ajax({
331
            url: yii2RenameRoute,
332
            method: 'POST',
333
            data: {id: currentRenamingFileId, title: val, _fileFormToken: yii2FileFormToken},
334
            success: function () {
335
                f12notification.info(FileRenamedText, 1);
336
            },
337
            error: function (response) {
338
                processError(response);
339
            }
340
        }
341
    );
342
    currentRenamingFileId = null;
343
}
344
345
$(document).ready(function () {
346
    setInterval(function () {
347
        sortableFiles()
348
    }, 2000);
349
350
    sortableFiles();
351
352
    initCropperLayout();
353
354
});
355
356
357