-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathWidget.php
471 lines (431 loc) · 15.7 KB
/
Widget.php
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
<?php
namespace vova07\fileapi;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\web\JsExpression;
use yii\widgets\InputWidget;
use Yii;
/**
* FileAPI Class
* Wrapper widget for {@link https://github.com/RubaXa/jquery.fileapi/ FileAPI} plugin.
* @todo Multiple files upload
*
* Usage:
* ```
* ...
* echo \vova07\fileapi\Widget::widget([
* 'name' => 'fileapi',
* 'settings' => [
* 'autoUpload' => true
* ]
* ]);
* ...
* ```
* or
* ```
* ...
* echo $form->field($model, 'file')->widget('vova07\fileapi\Widget', [
* 'settings' => [
* 'autoUpload' => true
* ]
* ]);
* ...
* ```
*/
class Widget extends InputWidget
{
/**
* @var string FileAPI selector
*/
public $selector;
/**
* @var string The parameter name for the file form data (the request argument name)
*/
public $paramName = 'file';
/**
* Widget settings.
*
* @var array {@link https://github.com/RubaXa/jquery.fileapi/ FileAPI options}
*/
public $settings = [];
/**
* @var string Widget template view
*
* @see \yii\base\Widget::render
*/
public $template;
/**
* @var array FileAPI events array
*/
public $callbacks = [];
/**
* @var boolean Enable/disable files preview
*/
public $preview = true;
/**
* @var boolean Enable/disable crop
*/
public $crop = false;
/**
* @var bool Show/Hide browse glyphicon
*/
public $browseGlyphicon = true;
/**
* @var array JCrop settings
*/
public $jcropSettings = [
'aspectRatio' => 1,
'bgColor' => '#ffffff',
'maxSize' => [568, 800],
'minSize' => [100, 100],
'keySupport' => false, // Important param to hide jCrop radio button.
'selection' => '100%'
];
/**
* @var integer|null Crop resize width
*/
public $cropResizeWidth;
/**
* @var integer|null Crop resize height
*/
public $cropResizeHeight;
/**
* @var integer|null Crop resize max width
*/
public $cropResizeMaxWidth;
/**
* @var integer|null Crop resize max height
*/
public $cropResizeMaxHeight;
/**
* @var string|null Real attribute name without any indexes in case this are setted
*/
protected $_attributeName;
/**
* @var array Default settings array
*/
private $_defaultSettings;
/**
* @var array Default settings array for single upload
*/
private $_defaultSingleSettings = [
'autoUpload' => true,
'elements' => [
'progress' => '[data-fileapi="progress"]',
'active' => [
'show' => '[data-fileapi="active.show"]',
'hide' => '[data-fileapi="active.hide"]'
],
'name' => '[data-fileapi="name"]',
'preview' => [
'el' => '[data-fileapi="preview"]',
'width' => 100,
'height' => 100
]
]
];
/**
* @var array Default settings array for multiple upload
*/
private $_defaultMultipleSettings = [
'autoUpload' => true,
'elements' => [
'list' => '.uploader-files',
'file' => [
'tpl' => '.uploader-file-tpl',
'progress' => '.uploader-file-progress-bar',
'preview' => [
'el' => '.uploader-file-preview',
'width' => 100,
'height' => 100
],
'upload' => [
'show' => '.uploader-file-progress'
],
'complete' => [
'hide' => '.uploader-file-progress'
]
],
'dnd' => [
'el' => '.uploader-dnd',
'hover' => 'uploader-dnd-hover',
'fallback' => '.uploader-dnd-not-supported'
]
]
];
/**
* Widget translation function.
*
* @param string $category the message category.
* @param string $message the message to be translated.
* @param array $params the parameters that will be used to replace the corresponding placeholders in the message.
* @param string $language the language code (e.g. `en-US`, `en`). If this is null, the current
* [[\yii\base\Application::language|application language]] will be used.
*
* @return string the translated message.
*/
public static function t($category, $message, $params = [], $language = null)
{
return Yii::t('vova07/' . $category, $message, $params, $language);
}
/**
* @inheritdoc
*/
public function init()
{
parent::init();
$request = Yii::$app->getRequest();
$this->registerTranslations();
if ($request->enableCsrfValidation === true) {
$this->settings['data'][$request->csrfParam] = $request->getCsrfToken();
}
if (!isset($this->settings['url'])) {
$this->settings['url'] = $request->getUrl();
} else {
$this->settings['url'] = Url::to($this->settings['url']);
}
if ($this->crop === true) {
$this->settings['autoUpload'] = false;
}
if (isset($this->settings['multiple']) && $this->settings['multiple'] === true) {
if ($this->template === null) {
$this->template = 'multiple';
}
if ($this->preview === false) {
unset($this->_defaultMultipleSettings['elements']['file']['preview']);
}
$this->_defaultSettings = $this->_defaultMultipleSettings;
} else {
if ($this->template === null) {
$this->template = 'single';
}
if ($this->preview === false) {
unset($this->_defaultSingleSettings['elements']['preview']);
}
$this->_defaultSettings = $this->_defaultSingleSettings;
}
$this->settings = ArrayHelper::merge($this->_defaultSettings, $this->settings);
}
/**
* Register widget translations.
*/
public function registerTranslations()
{
if (!isset(Yii::$app->i18n->translations['vova07/fileapi']) && !isset(Yii::$app->i18n->translations['vova07/*'])) {
Yii::$app->i18n->translations['vova07/fileapi'] = [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '@vova07/fileapi/messages',
'fileMap' => [
'vova07/fileapi' => 'fileapi.php'
],
'forceTranslation' => true
];
}
}
/**
* @inheritdoc
*/
public function run()
{
$this->registerFiles();
$this->register();
if ($this->selector === null) {
if (isset($this->settings['multiple']) && $this->settings['multiple'] === true) {
return $this->render(
$this->template,
[
'selector' => $this->options['id'],
'paramName' => $this->paramName
]
);
} else {
$input = $this->hasModel() ? Html::activeHiddenInput(
$this->model,
$this->attribute,
$this->options
) : Html::hiddenInput($this->name, $this->value, $this->options);
return $this->render(
$this->template,
[
'selector' => $this->getSelector(),
'input' => $input,
'paramName' => $this->paramName,
'value' => $this->hasModel() ? $this->model->{$this->attributeName} : $this->value,
'preview' => $this->preview,
'crop' => $this->crop,
'browseGlyphicon' => $this->browseGlyphicon
]
);
}
}
}
/**
* Registering already uploaded files.
*/
public function registerFiles()
{
if (!isset($this->settings['multiple']) || $this->settings['multiple'] === false) {
if ($this->hasModel() && $this->model->{$this->attributeName} && $this->model->fileExists($this->attributeName)) {
$this->settings['files'][] = [
'src' => $this->model->urlAttribute($this->attributeName),
'name' => $this->model->{$this->attributeName},
'type' => $this->model->getMimeType($this->attributeName)
];
}
}
}
/**
* Register all widget scripts and callbacks
*/
public function register()
{
$this->registerMainClientScript();
$this->registerClientScript();
$this->registerDefaultCallbacks();
$this->registerCallbacks();
}
/**
* Register widget main asset.
*/
protected function registerMainClientScript()
{
$selector = $this->getSelector();
$options = Json::encode($this->settings);
$view = $this->getView();
Asset::register($view);
$view->registerJs("jQuery('#$selector').fileapi($options);");
}
/**
* @return string Widget selector
*/
public function getSelector()
{
return $this->selector !== null ? $this->selector : 'uploader-' . $this->options['id'];
}
/**
* Register widget asset.
*/
public function registerClientScript()
{
$view = $this->getView();
$selector = $this->getSelector();
if (isset($this->settings['multiple']) && $this->settings['multiple'] === true) {
// MultipleAsset::register($view);
} else {
SingleAsset::register($view);
if ($this->preview === true) {
$view->registerJs(
"jQuery(document).on('click', '#$selector [data-fileapi=\"delete\"]', function(evt) {" .
"evt.preventDefault();" .
"var uploader = jQuery(this).closest('#$selector');" .
"uploader.fileapi('clear');" .
"uploader.find('[data-fileapi=\"browse-text\"]').removeClass('hidden');" .
"uploader.find('input[type=\"hidden\"]').val('');" .
"})"
);
}
}
if ($this->crop === true) {
CropAsset::register($view);
}
}
/**
* @return null|string Real attribute name without any indexes in case this are setted
*/
protected function getAttributeName()
{
if ($this->_attributeName === null) {
$this->_attributeName = preg_replace('/\[.\]/iu', '', $this->attribute);
}
return $this->_attributeName;
}
/**
* Register default widget callbacks
*/
protected function registerDefaultCallbacks()
{
// File complete handler
$this->callbacks['filecomplete'][] = new JsExpression('function (evt, uiEvt) {' .
'if (uiEvt.result.error) {' .
'alert(uiEvt.result.error);' .
'} else {' .
'jQuery(this).find("input[type=\"hidden\"]").val(uiEvt.result.name);' .
'jQuery(this).find("[data-fileapi=\"browse-text\"]").addClass("hidden");' .
'jQuery(this).find("[data-fileapi=\"delete\"]").attr("data-fileapi-uid", FileAPI.uid(uiEvt.file));' .
'}' .
'}');
if ($this->crop === true) {
$view = $this->getView();
$selector = $this->getSelector();
$jcropSettings = Json::encode($this->jcropSettings);
if ($this->cropResizeWidth !== null && $this->cropResizeHeight !== null) {
$cropResizeJs = "el.fileapi('resize', ufile, $this->cropResizeWidth, $this->cropResizeHeight);";
} elseif ($this->cropResizeWidth !== null && $this->cropResizeHeight == null) {
$cropResizeJs = "el.fileapi('resize', ufile, $this->cropResizeWidth, ((coordinates.h * $this->cropResizeWidth)/coordinates.w));";
} elseif ($this->cropResizeWidth == null && $this->cropResizeHeight !== null) {
$cropResizeJs = "el.fileapi('resize', ufile, ((coordinates.w * $this->cropResizeHeight)/coordinates.h), $this->cropResizeHeight);";
} elseif ($this->cropResizeMaxWidth !== null && $this->cropResizeMaxHeight !== null) {
$cropResizeJs = "if(coordinates.w > $this->cropResizeMaxWidth) el.fileapi('resize', ufile, $this->cropResizeMaxWidth, ((coordinates.h * $this->cropResizeMaxWidth)/coordinates.w));";
$cropResizeJs .= "else if(coordinates.h > $this->cropResizeMaxHeight) el.fileapi('resize', ufile, ((coordinates.w * $this->cropResizeMaxHeight)/coordinates.h), $this->cropResizeMaxHeight);";
} elseif ($this->cropResizeMaxWidth !== null && $this->cropResizeMaxHeight == null) {
$cropResizeJs = "if(coordinates.w > $this->cropResizeMaxWidth) el.fileapi('resize', ufile, $this->cropResizeMaxWidth, ((coordinates.h * $this->cropResizeMaxWidth)/coordinates.w));";
} elseif ($this->cropResizeMaxWidth == null && $this->cropResizeMaxHeight !== null) {
$cropResizeJs = "if(coordinates.h > $this->cropResizeMaxHeight) el.fileapi('resize', ufile, ((coordinates.w * $this->cropResizeMaxHeight)/coordinates.h), $this->cropResizeMaxHeight);";
} else {
$cropResizeJs = '';
}
// Add event handler for crop button
$view->registerJs('jQuery(document).on("click", "#modal-crop .crop", function() {' .
'$("#' . $selector . '").fileapi("upload");' .
'jQuery("#modal-crop").modal("hide");' .
'});');
// Crop event handler
$this->callbacks['select'] = new JsExpression('function (evt, ui) {' .
'var ufile = ui.files[0],' .
'jcropSettings = ' . $jcropSettings . ',' .
'el = jQuery(this);' .
'if (ufile) {' .
'jcropSettings.file = ufile;' .
'jcropSettings.onSelect = function (coordinates) {' .
'$("#' . $selector . '").fileapi("crop", ufile, coordinates);' .
$cropResizeJs .
'};' .
'FileAPI.getInfo (ufile, function (err, info) {' .
'if (!err) { var coordinates = { w: info.width, h: info.height }; ' . $cropResizeJs . '}' .
'});;' .
'jQuery("#modal-crop").modal("show");' .
'setTimeout(function () {' .
'$("#modal-preview").cropper(jcropSettings);' .
'}, 700);' .
'}' .
'}');
}
}
/**
* Register widget callbacks.
*/
protected function registerCallbacks()
{
if (!empty($this->callbacks)) {
$selector = $this->getSelector();
$view = $this->getView();
foreach ($this->callbacks as $event => $callback) {
if (is_array($callback)) {
foreach ($callback as $function) {
if (!$function instanceof JsExpression) {
$function = new JsExpression($function);
}
$view->registerJs("jQuery('#$selector').on('$event', $function);");
}
} else {
if (!$callback instanceof JsExpression) {
$callback = new JsExpression($callback);
}
$view->registerJs("jQuery('#$selector').on('$event', $callback);");
}
}
}
}
}