Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
// This file is part of Moodle - http://moodle.org/
2
//
3
// Moodle is free software: you can redistribute it and/or modify
4
// it under the terms of the GNU General Public License as published by
5
// the Free Software Foundation, either version 3 of the License, or
6
// (at your option) any later version.
7
//
8
// Moodle is distributed in the hope that it will be useful,
9
// but WITHOUT ANY WARRANTY; without even the implied warranty of
10
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
// GNU General Public License for more details.
12
//
13
// You should have received a copy of the GNU General Public License
14
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
15
 
16
/*
17
 * @package    atto_image
18
 * @copyright  2013 Damyon Wiese  <damyon@moodle.com>
19
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
20
 */
21
 
22
/**
23
 * @module moodle-atto_image_alignment-button
24
 */
25
 
26
/**
27
 * Atto image selection tool.
28
 *
29
 * @namespace M.atto_image
30
 * @class Button
31
 * @extends M.editor_atto.EditorPlugin
32
 */
33
 
34
var CSS = {
35
        RESPONSIVE: 'img-fluid',
36
        INPUTALIGNMENT: 'atto_image_alignment',
37
        INPUTALT: 'atto_image_altentry',
38
        INPUTHEIGHT: 'atto_image_heightentry',
39
        INPUTSUBMIT: 'atto_image_urlentrysubmit',
40
        INPUTURL: 'atto_image_urlentry',
41
        INPUTSIZE: 'atto_image_size',
42
        INPUTWIDTH: 'atto_image_widthentry',
43
        IMAGEALTWARNING: 'atto_image_altwarning',
44
        IMAGEURLWARNING: 'atto_image_urlwarning',
45
        IMAGEBROWSER: 'openimagebrowser',
46
        IMAGEPRESENTATION: 'atto_image_presentation',
47
        INPUTCONSTRAIN: 'atto_image_constrain',
48
        INPUTCUSTOMSTYLE: 'atto_image_customstyle',
49
        IMAGEPREVIEW: 'atto_image_preview',
50
        IMAGEPREVIEWBOX: 'atto_image_preview_box',
51
        ALIGNSETTINGS: 'atto_image_button'
52
    },
53
    FORMNAMES = {
54
        URL: 'urlentry',
55
        ALT: 'altentry'
56
    },
57
    SELECTORS = {
58
        INPUTURL: '.' + CSS.INPUTURL
59
    },
60
    ALIGNMENTS = [
61
        // Vertical alignment.
62
        {
63
            name: 'verticalAlign',
64
            str: 'alignment_top',
65
            value: 'text-top',
66
            margin: '0 0.5em'
67
        }, {
68
            name: 'verticalAlign',
69
            str: 'alignment_middle',
70
            value: 'middle',
71
            margin: '0 0.5em'
72
        }, {
73
            name: 'verticalAlign',
74
            str: 'alignment_bottom',
75
            value: 'text-bottom',
76
            margin: '0 0.5em',
77
            isDefault: true
78
        },
79
 
80
        // Floats.
81
        {
82
            name: 'float',
83
            str: 'alignment_left',
84
            value: 'left',
85
            margin: '0 0.5em 0 0'
86
        }, {
87
            name: 'float',
88
            str: 'alignment_right',
89
            value: 'right',
90
            margin: '0 0 0 0.5em'
91
        }
92
    ],
93
    DEFAULTS = {
94
        WIDTH: 160,
95
        HEIGHT: 160,
96
    },
97
    REGEX = {
98
        ISPERCENT: /\d+%/
99
    },
100
 
101
    COMPONENTNAME = 'atto_image',
102
 
103
    TEMPLATE = '' +
104
            '<form class="atto_form">' +
105
                // Add the repository browser button.
106
                '<div style="display:none" role="alert" class="alert alert-warning mb-1 {{CSS.IMAGEURLWARNING}}">' +
107
                    '<label for="{{elementid}}_{{CSS.INPUTURL}}">' +
108
                    '{{get_string "imageurlrequired" component}}' +
109
                    '</label>' +
110
                '</div>' +
111
                '{{#if showFilepicker}}' +
112
                    '<div class="mb-1">' +
113
                        '<label for="{{elementid}}_{{CSS.INPUTURL}}">{{get_string "enterurl" component}}</label>' +
114
                        '<div class="input-group input-append w-100">' +
115
                            '<input name="{{FORMNAMES.URL}}" class="form-control {{CSS.INPUTURL}}" type="url" ' +
116
                            'id="{{elementid}}_{{CSS.INPUTURL}}" size="32"/>' +
117
                            '<span class="input-group-append">' +
118
                                '<button class="btn btn-secondary {{CSS.IMAGEBROWSER}}" type="button">' +
119
                                '{{get_string "browserepositories" component}}</button>' +
120
                            '</span>' +
121
                        '</div>' +
122
                    '</div>' +
123
                '{{else}}' +
124
                    '<div class="mb-1">' +
125
                        '<label for="{{elementid}}_{{CSS.INPUTURL}}">{{get_string "enterurl" component}}</label>' +
126
                        '<input name="{{FORMNAMES.URL}}" class="form-control fullwidth {{CSS.INPUTURL}}" type="url" ' +
127
                        'id="{{elementid}}_{{CSS.INPUTURL}}" size="32"/>' +
128
                    '</div>' +
129
                '{{/if}}' +
130
 
131
                '<div style="display:none" role="alert" class="alert alert-warning mb-1 {{CSS.IMAGEALTWARNING}}">' +
132
                    '<label for="{{elementid}}_{{CSS.INPUTALT}}">' +
133
                    '{{get_string "presentationoraltrequired" component}}' +
134
                    '</label>' +
135
                '</div>' +
136
                // Add the Alt box.
137
                '<div class="mb-1">' +
138
                '<label for="{{elementid}}_{{CSS.INPUTALT}}">{{get_string "enteralt" component}}</label>' +
139
                '<textarea class="form-control fullwidth {{CSS.INPUTALT}}" ' +
140
                'id="{{elementid}}_{{CSS.INPUTALT}}" name="{{FORMNAMES.ALT}}" maxlength="125"></textarea>' +
141
 
142
                // Add the character count.
143
                '<div id="the-count" class="d-flex justify-content-end small">' +
144
                '<span id="currentcount">0</span>' +
145
                '<span id="maximumcount"> / 125</span>' +
146
                '</div>' +
147
 
148
                // Add the presentation select box.
149
                '<div class="form-check">' +
150
                '<input type="checkbox" class="form-check-input {{CSS.IMAGEPRESENTATION}}" ' +
151
                    'id="{{elementid}}_{{CSS.IMAGEPRESENTATION}}"/>' +
152
                '<label class="form-check-label" for="{{elementid}}_{{CSS.IMAGEPRESENTATION}}">' +
153
                    '{{get_string "presentation" component}}' +
154
                '</label>' +
155
                '</div>' +
156
                '</div>' +
157
 
158
                // Add the size entry boxes.
159
                '<div class="mb-1">' +
160
                '<label class="" for="{{elementid}}_{{CSS.INPUTSIZE}}">{{get_string "size" component}}</label>' +
161
                '<div id="{{elementid}}_{{CSS.INPUTSIZE}}" class="d-flex flex-wrap align-items-center {{CSS.INPUTSIZE}}">' +
162
                '<label class="accesshide" for="{{elementid}}_{{CSS.INPUTWIDTH}}">{{get_string "width" component}}</label>' +
163
                '<input type="text" class="form-control w-auto mr-1 input-mini {{CSS.INPUTWIDTH}}" ' +
164
                'id="{{elementid}}_{{CSS.INPUTWIDTH}}" size="4"/> x' +
165
 
166
                // Add the height entry box.
167
                '<label class="accesshide" for="{{elementid}}_{{CSS.INPUTHEIGHT}}">{{get_string "height" component}}</label>' +
168
                '<input type="text" class="form-control w-auto ml-1 input-mini {{CSS.INPUTHEIGHT}}" ' +
169
                'id="{{elementid}}_{{CSS.INPUTHEIGHT}}" size="4"/>' +
170
 
171
                // Add the constrain checkbox.
172
                '<div class="form-check ml-2">' +
173
                '<input type="checkbox" class="form-check-input {{CSS.INPUTCONSTRAIN}}" ' +
174
                'id="{{elementid}}_{{CSS.INPUTCONSTRAIN}}"/>' +
175
                '<label class="form-check-label" for="{{elementid}}_{{CSS.INPUTCONSTRAIN}}">' +
176
                '{{get_string "constrain" component}}</label>' +
177
                '</div>' +
178
                '</div>' +
179
                '</div>' +
180
 
181
                // Add the alignment selector.
182
                '<div class="d-flex flex-wrap align-items-center mb-1">' +
183
                '<label class="mb-0" for="{{elementid}}_{{CSS.INPUTALIGNMENT}}">{{get_string "alignment" component}}</label>' +
184
                '<select class="custom-select ml-2 {{CSS.INPUTALIGNMENT}}" id="{{elementid}}_{{CSS.INPUTALIGNMENT}}">' +
185
                    '{{#each alignments}}' +
186
                        '<option value="{{value}}">{{get_string str ../component}}</option>' +
187
                    '{{/each}}' +
188
                '</select>' +
189
                '</div>' +
190
                // Hidden input to store custom styles.
191
                '<input type="hidden" class="{{CSS.INPUTCUSTOMSTYLE}}"/>' +
192
                '<br/>' +
193
 
194
                // Add the image preview.
195
                '<div class="mdl-align">' +
196
                '<div class="{{CSS.IMAGEPREVIEWBOX}}">' +
197
                    '<img class="{{CSS.IMAGEPREVIEW}}" alt="" style="display: none;"/>' +
198
                '</div>' +
199
 
200
                // Add the submit button and close the form.
201
                '<button class="btn btn-secondary {{CSS.INPUTSUBMIT}}" type="submit">' + '' +
202
                    '{{get_string "saveimage" component}}</button>' +
203
                '</div>' +
204
            '</form>',
205
 
206
        IMAGETEMPLATE = '' +
207
            '<img src="{{url}}" alt="{{alt}}" ' +
208
                '{{#if width}}width="{{width}}" {{/if}}' +
209
                '{{#if height}}height="{{height}}" {{/if}}' +
210
                '{{#if presentation}}role="presentation" {{/if}}' +
211
                '{{#if customstyle}}style="{{customstyle}}" {{/if}}' +
212
                '{{#if classlist}}class="{{classlist}}" {{/if}}' +
213
                '{{#if id}}id="{{id}}" {{/if}}' +
214
                '/>';
215
 
216
Y.namespace('M.atto_image').Button = Y.Base.create('button', Y.M.editor_atto.EditorPlugin, [], {
217
    /**
218
     * A reference to the current selection at the time that the dialogue
219
     * was opened.
220
     *
221
     * @property _currentSelection
222
     * @type Range
223
     * @private
224
     */
225
    _currentSelection: null,
226
 
227
    /**
228
     * The most recently selected image.
229
     *
230
     * @param _selectedImage
231
     * @type Node
232
     * @private
233
     */
234
    _selectedImage: null,
235
 
236
    /**
237
     * A reference to the currently open form.
238
     *
239
     * @param _form
240
     * @type Node
241
     * @private
242
     */
243
    _form: null,
244
 
245
    /**
246
     * The dimensions of the raw image before we manipulate it.
247
     *
248
     * @param _rawImageDimensions
249
     * @type Object
250
     * @private
251
     */
252
    _rawImageDimensions: null,
253
 
254
    initializer: function() {
255
 
256
        this.addButton({
257
            icon: 'e/insert_edit_image',
258
            callback: this._displayDialogue,
259
            tags: 'img',
260
            tagMatchRequiresAll: false
261
        });
262
        this.editor.delegate('dblclick', this._displayDialogue, 'img', this);
263
        this.editor.delegate('click', this._handleClick, 'img', this);
264
        this.editor.on('paste', this._handlePaste, this);
265
        this.editor.on('drop', this._handleDragDrop, this);
266
 
267
        // ...e.preventDefault needed to stop the default event from clobbering the desired behaviour in some browsers.
268
        this.editor.on('dragover', function(e) {
269
            e.preventDefault();
270
        }, this);
271
        this.editor.on('dragenter', function(e) {
272
            e.preventDefault();
273
        }, this);
274
    },
275
 
276
    /**
277
     * Handle a drag and drop event with an image.
278
     *
279
     * @method _handleDragDrop
280
     * @param {EventFacade} e
281
     * @private
282
     */
283
    _handleDragDrop: function(e) {
284
        if (!e._event || !e._event.dataTransfer) {
285
            // Drop not fully supported in this browser.
286
            return;
287
        }
288
 
289
        this._handlePasteOrDropHelper(e, e._event.dataTransfer);
290
    },
291
 
292
    /**
293
     * Handles paste events where - if the thing being pasted is an image.
294
     *
295
     * @method _handlePaste
296
     * @param {EventFacade} e
297
     * @return {boolean} false if we handled the event, else true.
298
     * @private
299
     */
300
    _handlePaste: function(e) {
301
        if (!e._event || !e._event.clipboardData) {
302
            // Paste not fully supported in this browser.
303
            return true;
304
        }
305
 
306
        return this._handlePasteOrDropHelper(e, e._event.clipboardData);
307
    },
308
 
309
    /**
310
     * Handle a drag and drop event with an image.
311
     *
312
     * @method _handleDragDrop
313
     * @param {EventFacade} e
314
     * @param {DataTransfer} dataTransfer
315
     * @return {boolean} false if we handled the event, else true.
316
     * @private
317
     */
318
    _handlePasteOrDropHelper: function(e, dataTransfer) {
319
 
320
        var items = dataTransfer.items,
321
            didUpload = false;
322
        for (var i = 0; i < items.length; i++) {
323
            var item = items[i];
324
            if (item.kind !== 'file') {
325
                continue;
326
            }
327
            if (!this._isImage(item.type)) {
328
                continue;
329
            }
330
            this._uploadImage(item.getAsFile());
331
            didUpload = true;
332
        }
333
 
334
        if (didUpload) {
335
            e.preventDefault();
336
        }
337
    },
338
 
339
    /**
340
     * Is this file an image?
341
     *
342
     * @method _isImage
343
     * @param {string} mimeType the file's mime type.
344
     * @return {boolean} true if the file has an image mimeType.
345
     * @private
346
     */
347
    _isImage: function(mimeType) {
348
        return mimeType.indexOf('image/') === 0;
349
    },
350
 
351
    /**
352
     * Used by _handleDragDrop and _handlePaste to upload an image and insert it.
353
     *
354
     * @method _uploadImage
355
     * @param {File} fileToSave
356
     * @private
357
     */
358
    _uploadImage: function(fileToSave) {
359
 
360
        var self = this,
361
            host = this.get('host'),
362
            template = Y.Handlebars.compile(IMAGETEMPLATE);
363
 
364
        host.saveSelection();
365
 
366
        // Trigger form upload start events.
367
        require(['core_form/events'], function(FormEvent) {
368
            FormEvent.notifyUploadStarted(self.editor.get('id'));
369
        });
370
 
371
        var options = host.get('filepickeroptions').image,
372
            savepath = (options.savepath === undefined) ? '/' : options.savepath,
373
            formData = new FormData(),
374
            timestamp = 0,
375
            uploadid = "",
376
            xhr = new XMLHttpRequest(),
377
            imagehtml = "",
378
            keys = Object.keys(options.repositories);
379
 
380
        formData.append('repo_upload_file', fileToSave);
381
        formData.append('itemid', options.itemid);
382
 
383
        // List of repositories is an object rather than an array.  This makes iteration more awkward.
384
        for (var i = 0; i < keys.length; i++) {
385
            if (options.repositories[keys[i]].type === 'upload') {
386
                formData.append('repo_id', options.repositories[keys[i]].id);
387
                break;
388
            }
389
        }
390
        formData.append('env', options.env);
391
        formData.append('sesskey', M.cfg.sesskey);
392
        formData.append('client_id', options.client_id);
393
        formData.append('savepath', savepath);
394
        formData.append('ctx_id', options.context.id);
395
 
396
        // Insert spinner as a placeholder.
397
        timestamp = new Date().getTime();
398
        uploadid = 'moodleimage_' + Math.round(Math.random() * 100000) + '-' + timestamp;
399
        host.focus();
400
        host.restoreSelection();
401
        imagehtml = template({
402
            url: M.util.image_url("i/loading_small", 'moodle'),
403
            alt: M.util.get_string('uploading', COMPONENTNAME),
404
            id: uploadid
405
        });
406
        host.insertContentAtFocusPoint(imagehtml);
407
        self.markUpdated();
408
 
409
        // Kick off a XMLHttpRequest.
410
        xhr.onreadystatechange = function() {
411
            var placeholder = self.editor.one('#' + uploadid),
412
                result,
413
                file,
414
                newhtml,
415
                newimage;
416
 
417
            if (xhr.readyState === 4) {
418
                if (xhr.status === 200) {
419
                    result = JSON.parse(xhr.responseText);
420
                    if (result) {
421
                        if (result.error) {
422
                            if (placeholder) {
423
                                placeholder.remove(true);
424
                            }
425
                            // Trigger form upload complete events.
426
                            require(['core_form/events'], function(FormEvent) {
427
                                FormEvent.notifyUploadCompleted(self.editor.get('id'));
428
                            });
429
                            throw new M.core.ajaxException(result);
430
                        }
431
 
432
                        file = result;
433
                        if (result.event && result.event === 'fileexists') {
434
                            // A file with this name is already in use here - rename to avoid conflict.
435
                            // Chances are, it's a different image (stored in a different folder on the user's computer).
436
                            // If the user wants to reuse an existing image, they can copy/paste it within the editor.
437
                            file = result.newfile;
438
                        }
439
 
440
                        // Replace placeholder with actual image.
441
                        newhtml = template({
442
                            url: file.url,
443
                            presentation: true,
444
                            classlist: CSS.RESPONSIVE
445
                        });
446
                        newimage = Y.Node.create(newhtml);
447
                        if (placeholder) {
448
                            placeholder.replace(newimage);
449
                        } else {
450
                            self.editor.appendChild(newimage);
451
                        }
452
                        self.markUpdated();
453
                    }
454
                } else {
455
                    Y.use('moodle-core-notification-alert', function() {
456
                        // Trigger form upload complete events.
457
                        require(['core_form/events'], function(FormEvent) {
458
                            FormEvent.notifyUploadCompleted(self.editor.get('id'));
459
                        });
460
                        new M.core.alert({message: M.util.get_string('servererror', 'moodle')});
461
                    });
462
                    if (placeholder) {
463
                        placeholder.remove(true);
464
                    }
465
                }
466
                // Trigger form upload complete events.
467
                require(['core_form/events'], function(FormEvent) {
468
                    FormEvent.notifyUploadCompleted(self.editor.get('id'));
469
                });
470
            }
471
        };
472
        xhr.open("POST", M.cfg.wwwroot + '/repository/repository_ajax.php?action=upload', true);
473
        xhr.send(formData);
474
    },
475
 
476
    /**
477
     * Handle a click on an image.
478
     *
479
     * @method _handleClick
480
     * @param {EventFacade} e
481
     * @private
482
     */
483
    _handleClick: function(e) {
484
        var image = e.target;
485
 
486
        var selection = this.get('host').getSelectionFromNode(image);
487
        if (this.get('host').getSelection() !== selection) {
488
            this.get('host').setSelection(selection);
489
        }
490
    },
491
 
492
    /**
493
     * Display the image editing tool.
494
     *
495
     * @method _displayDialogue
496
     * @private
497
     */
498
    _displayDialogue: function() {
499
        // Store the current selection.
500
        this._currentSelection = this.get('host').getSelection();
501
        if (this._currentSelection === false) {
502
            return;
503
        }
504
 
505
        // Reset the image dimensions.
506
        this._rawImageDimensions = null;
507
 
508
        var dialogue = this.getDialogue({
509
            headerContent: M.util.get_string('imageproperties', COMPONENTNAME),
510
            width: 'auto',
511
            focusAfterHide: true,
512
            focusOnShowSelector: SELECTORS.INPUTURL
513
        });
514
        // Set a maximum width for the dialog. This will prevent the dialog width to extend beyond the screen width
515
        // in cases when the uploaded image has larger width.
516
        dialogue.get('boundingBox').setStyle('maxWidth', '90%');
517
        // Set the dialogue content, and then show the dialogue.
518
        dialogue.set('bodyContent', this._getDialogueContent())
519
                .show();
520
    },
521
 
522
    /**
523
     * Set the inputs for width and height if they are not set, and calculate
524
     * if the constrain checkbox should be checked or not.
525
     *
526
     * @method _loadPreviewImage
527
     * @param {String} url
528
     * @private
529
     */
530
    _loadPreviewImage: function(url) {
531
        var image = new Image();
532
        var self = this;
533
 
534
        image.onerror = function() {
535
            var preview = self._form.one('.' + CSS.IMAGEPREVIEW);
536
            preview.setStyles({
537
                'display': 'none'
538
            });
539
 
540
            // Centre the dialogue when clearing the image preview.
541
            self.getDialogue().centerDialogue();
542
        };
543
 
544
        image.onload = function() {
545
            var input, currentwidth, currentheight, widthRatio, heightRatio;
546
 
547
            // Store dimensions of the raw image, falling back to defaults for images without dimensions (e.g. SVG).
548
            self._rawImageDimensions = {
549
                width: this.width || DEFAULTS.WIDTH,
550
                height: this.height || DEFAULTS.HEIGHT,
551
            };
552
 
553
            input = self._form.one('.' + CSS.INPUTWIDTH);
554
            currentwidth = input.get('value');
555
            if (currentwidth === '') {
556
                input.set('value', self._rawImageDimensions.width);
557
                currentwidth = "" + self._rawImageDimensions.width;
558
            }
559
            input = self._form.one('.' + CSS.INPUTHEIGHT);
560
            currentheight = input.get('value');
561
            if (currentheight === '') {
562
                input.set('value', self._rawImageDimensions.height);
563
                currentheight = "" + self._rawImageDimensions.height;
564
            }
565
            input = self._form.one('.' + CSS.IMAGEPREVIEW);
566
            input.setAttribute('src', this.src);
567
            input.setStyles({
568
                'display': 'inline'
569
            });
570
 
571
            input = self._form.one('.' + CSS.INPUTCONSTRAIN);
572
            if (currentwidth.match(REGEX.ISPERCENT) && currentheight.match(REGEX.ISPERCENT)) {
573
                input.set('checked', currentwidth === currentheight);
574
            } else if (this.width === 0 || this.height === 0) {
575
                // If we don't have both dimensions of the image, we can't auto-size it, so disable control.
576
                input.set('disabled', 'disabled');
577
            } else {
578
                // This is the same as comparing to 3 decimal places.
579
                widthRatio = Math.round(1000 * parseInt(currentwidth, 10) / this.width);
580
                heightRatio = Math.round(1000 * parseInt(currentheight, 10) / this.height);
581
                input.set('checked', widthRatio === heightRatio);
582
            }
583
 
584
            // Apply the image sizing.
585
            self._autoAdjustSize(self);
586
 
587
            // Centre the dialogue once the preview image has loaded.
588
            self.getDialogue().centerDialogue();
589
        };
590
 
591
        image.src = url;
592
    },
593
 
594
    /**
595
     * Return the dialogue content for the tool, attaching any required
596
     * events.
597
     *
598
     * @method _getDialogueContent
599
     * @return {Node} The content to place in the dialogue.
600
     * @private
601
     */
602
    _getDialogueContent: function() {
603
        var template = Y.Handlebars.compile(TEMPLATE),
604
            canShowFilepicker = this.get('host').canShowFilepicker('image'),
605
            content = Y.Node.create(template({
606
                elementid: this.get('host').get('elementid'),
607
                CSS: CSS,
608
                FORMNAMES: FORMNAMES,
609
                component: COMPONENTNAME,
610
                showFilepicker: canShowFilepicker,
611
                alignments: ALIGNMENTS
612
            }));
613
 
614
        this._form = content;
615
 
616
        // Configure the view of the current image.
617
        this._applyImageProperties(this._form);
618
 
619
        this._form.one('.' + CSS.INPUTURL).on('blur', this._urlChanged, this);
620
        this._form.one('.' + CSS.INPUTURL).on('change', this._hasErrorUrlField, this);
621
        this._form.one('.' + CSS.IMAGEPRESENTATION).on('change', this._hasErrorAltField, this);
622
        this._form.one('.' + CSS.INPUTALT).on('blur', this._hasErrorAltField, this);
623
        this._form.one('.' + CSS.INPUTWIDTH).on('blur', this._autoAdjustSize, this);
624
        this._form.one('.' + CSS.INPUTHEIGHT).on('blur', this._autoAdjustSize, this, true);
625
        this._form.one('.' + CSS.INPUTCONSTRAIN).on('change', function(event) {
626
            if (event.target.get('checked')) {
627
                this._autoAdjustSize(event);
628
            }
629
        }, this);
630
        this._form.one('.' + CSS.INPUTSUBMIT).on('click', this._setImage, this);
631
 
632
        if (canShowFilepicker) {
633
            this._form.one('.' + CSS.IMAGEBROWSER).on('click', function() {
634
                    this.get('host').showFilepicker('image', this._filepickerCallback, this);
635
            }, this);
636
        }
637
 
638
        // Character count.
639
        this._form.one('.' + CSS.INPUTALT).on('keyup', this._handleKeyup, this);
640
 
641
        return content;
642
    },
643
 
644
    _autoAdjustSize: function(e, forceHeight) {
645
        forceHeight = forceHeight || false;
646
 
647
        var keyField = this._form.one('.' + CSS.INPUTWIDTH),
648
            keyFieldType = 'width',
649
            subField = this._form.one('.' + CSS.INPUTHEIGHT),
650
            subFieldType = 'height',
651
            constrainField = this._form.one('.' + CSS.INPUTCONSTRAIN),
652
            keyFieldValue = keyField.get('value'),
653
            subFieldValue = subField.get('value'),
654
            imagePreview = this._form.one('.' + CSS.IMAGEPREVIEW),
655
            rawPercentage,
656
            rawSize;
657
 
658
        // If we do not know the image size, do not do anything.
659
        if (!this._rawImageDimensions) {
660
            return;
661
        }
662
 
663
        // Set the width back to default if it is empty.
664
        if (keyFieldValue === '') {
665
            keyFieldValue = this._rawImageDimensions[keyFieldType];
666
            keyField.set('value', keyFieldValue);
667
            keyFieldValue = keyField.get('value');
668
        }
669
 
670
        // Clear the existing preview sizes.
671
        imagePreview.setStyles({
672
            width: null,
673
            height: null
674
        });
675
 
676
        // Now update with the new values.
677
        if (!constrainField.get('checked')) {
678
            // We are not keeping the image proportion - update the preview accordingly.
679
 
680
            // Width.
681
            if (keyFieldValue.match(REGEX.ISPERCENT)) {
682
                rawPercentage = parseInt(keyFieldValue, 10);
683
                rawSize = this._rawImageDimensions.width / 100 * rawPercentage;
684
                imagePreview.setStyle('width', rawSize + 'px');
685
            } else {
686
                imagePreview.setStyle('width', keyFieldValue + 'px');
687
            }
688
 
689
            // Height.
690
            if (subFieldValue.match(REGEX.ISPERCENT)) {
691
                rawPercentage = parseInt(subFieldValue, 10);
692
                rawSize = this._rawImageDimensions.height / 100 * rawPercentage;
693
                imagePreview.setStyle('height', rawSize + 'px');
694
            } else {
695
                imagePreview.setStyle('height', subFieldValue + 'px');
696
            }
697
        } else {
698
            // We are keeping the image in proportion.
699
            if (forceHeight) {
700
                // By default we update based on width. Swap the key and sub fields around to achieve a height-based scale.
701
                var _temporaryValue;
702
                _temporaryValue = keyField;
703
                keyField = subField;
704
                subField = _temporaryValue;
705
 
706
                _temporaryValue = keyFieldType;
707
                keyFieldType = subFieldType;
708
                subFieldType = _temporaryValue;
709
 
710
                _temporaryValue = keyFieldValue;
711
                keyFieldValue = subFieldValue;
712
                subFieldValue = _temporaryValue;
713
            }
714
 
715
            if (keyFieldValue.match(REGEX.ISPERCENT)) {
716
                // This is a percentage based change. Copy it verbatim.
717
                subFieldValue = keyFieldValue;
718
 
719
                // Set the width to the calculated pixel width.
720
                rawPercentage = parseInt(keyFieldValue, 10);
721
                rawSize = this._rawImageDimensions.width / 100 * rawPercentage;
722
 
723
                // And apply the width/height to the container.
724
                imagePreview.setStyle('width', rawSize);
725
                rawSize = this._rawImageDimensions.height / 100 * rawPercentage;
726
                imagePreview.setStyle('height', rawSize);
727
            } else {
728
                // Calculate the scaled subFieldValue from the keyFieldValue.
729
                subFieldValue = Math.round((keyFieldValue / this._rawImageDimensions[keyFieldType]) *
730
                        this._rawImageDimensions[subFieldType]);
731
 
732
                if (forceHeight) {
733
                    imagePreview.setStyles({
734
                        'width': subFieldValue,
735
                        'height': keyFieldValue
736
                    });
737
                } else {
738
                    imagePreview.setStyles({
739
                        'width': keyFieldValue,
740
                        'height': subFieldValue
741
                    });
742
                }
743
            }
744
 
745
            // Update the subField's value within the form to reflect the changes.
746
            subField.set('value', subFieldValue);
747
        }
748
    },
749
 
750
    /**
751
     * Update the dialogue after an image was selected in the File Picker.
752
     *
753
     * @method _filepickerCallback
754
     * @param {object} params The parameters provided by the filepicker
755
     * containing information about the image.
756
     * @private
757
     */
758
    _filepickerCallback: function(params) {
759
        if (params.url !== '') {
760
            var input = this._form.one('.' + CSS.INPUTURL);
761
            input.set('value', params.url);
762
 
763
            // Auto set the width and height.
764
            this._form.one('.' + CSS.INPUTWIDTH).set('value', '');
765
            this._form.one('.' + CSS.INPUTHEIGHT).set('value', '');
766
 
767
            // Load the preview image.
768
            this._loadPreviewImage(params.url);
769
        }
770
    },
771
 
772
    /**
773
     * Applies properties of an existing image to the image dialogue for editing.
774
     *
775
     * @method _applyImageProperties
776
     * @param {Node} form
777
     * @private
778
     */
779
    _applyImageProperties: function(form) {
780
        var properties = this._getSelectedImageProperties(),
781
            img = form.one('.' + CSS.IMAGEPREVIEW);
782
 
783
        if (properties === false) {
784
            img.setStyle('display', 'none');
785
            // Set the default alignment.
786
            ALIGNMENTS.some(function(alignment) {
787
                if (alignment.isDefault) {
788
                    form.one('.' + CSS.INPUTALIGNMENT).set('value', alignment.value);
789
                    return true;
790
                }
791
 
792
                return false;
793
            }, this);
794
 
795
            return;
796
        }
797
 
798
        if (properties.align) {
799
            form.one('.' + CSS.INPUTALIGNMENT).set('value', properties.align);
800
        }
801
        if (properties.customstyle) {
802
            form.one('.' + CSS.INPUTCUSTOMSTYLE).set('value', properties.customstyle);
803
        }
804
        if (properties.width) {
805
            form.one('.' + CSS.INPUTWIDTH).set('value', properties.width);
806
        }
807
        if (properties.height) {
808
            form.one('.' + CSS.INPUTHEIGHT).set('value', properties.height);
809
        }
810
        if (properties.alt) {
811
            form.one('.' + CSS.INPUTALT).set('value', properties.alt);
812
        }
813
        if (properties.src) {
814
            form.one('.' + CSS.INPUTURL).set('value', properties.src);
815
            this._loadPreviewImage(properties.src);
816
        }
817
        if (properties.presentation) {
818
            form.one('.' + CSS.IMAGEPRESENTATION).set('checked', 'checked');
819
        }
820
 
821
        // Update the image preview based on the form properties.
822
        this._autoAdjustSize();
823
    },
824
 
825
    /**
826
     * Gets the properties of the currently selected image.
827
     *
828
     * The first image only if multiple images are selected.
829
     *
830
     * @method _getSelectedImageProperties
831
     * @return {object}
832
     * @private
833
     */
834
    _getSelectedImageProperties: function() {
835
        var properties = {
836
                src: null,
837
                alt: null,
838
                width: null,
839
                height: null,
840
                align: '',
841
                presentation: false
842
            },
843
 
844
            // Get the current selection.
845
            images = this.get('host').getSelectedNodes(),
846
            width,
847
            height,
848
            style,
849
            image;
850
 
851
        if (images) {
852
            images = images.filter('img');
853
        }
854
 
855
        if (images && images.size()) {
856
            image = this._removeLegacyAlignment(images.item(0));
857
            this._selectedImage = image;
858
 
859
            style = image.getAttribute('style');
860
            properties.customstyle = style;
861
 
862
            width = image.getAttribute('width');
863
            if (!width.match(REGEX.ISPERCENT)) {
864
                width = parseInt(width, 10);
865
            }
866
            height = image.getAttribute('height');
867
            if (!height.match(REGEX.ISPERCENT)) {
868
                height = parseInt(height, 10);
869
            }
870
 
871
            if (width !== 0) {
872
                properties.width = width;
873
            }
874
            if (height !== 0) {
875
                properties.height = height;
876
            }
877
            this._getAlignmentPropeties(image, properties);
878
            properties.src = image.getAttribute('src');
879
            properties.alt = image.getAttribute('alt') || '';
880
            properties.presentation = (image.get('role') === 'presentation');
881
            return properties;
882
        }
883
 
884
        // No image selected - clean up.
885
        this._selectedImage = null;
886
        return false;
887
    },
888
 
889
    /**
890
     * Sets the alignment of a properties object.
891
     *
892
     * @method _getAlignmentPropeties
893
     * @param {Node} image The image that the alignment properties should be found for
894
     * @param {Object} properties The properties object that is created in _getSelectedImageProperties()
895
     * @private
896
     */
897
    _getAlignmentPropeties: function(image, properties) {
898
        var complete = false,
899
            defaultAlignment;
900
 
901
        // Check for an alignment value.
902
        complete = ALIGNMENTS.some(function(alignment) {
903
            var classname = this._getAlignmentClass(alignment.value);
904
            if (image.hasClass(classname)) {
905
                properties.align = alignment.value;
906
                Y.log('Found alignment ' + alignment.value, 'debug', 'atto_image-button');
907
 
908
                return true;
909
            }
910
 
911
            if (alignment.isDefault) {
912
                defaultAlignment = alignment.value;
913
            }
914
 
915
            return false;
916
        }, this);
917
 
918
        if (!complete && defaultAlignment) {
919
            properties.align = defaultAlignment;
920
        }
921
    },
922
 
923
    /**
924
     * Update the form when the URL was changed. This includes updating the
925
     * height, width, and image preview.
926
     *
927
     * @method _urlChanged
928
     * @private
929
     */
930
    _urlChanged: function() {
931
        var input = this._form.one('.' + CSS.INPUTURL);
932
 
933
        if (input.get('value') !== '') {
934
            // Load the preview image.
935
            this._loadPreviewImage(input.get('value'));
936
        }
937
    },
938
 
939
    /**
940
     * Update the image in the contenteditable.
941
     *
942
     * @method _setImage
943
     * @param {EventFacade} e
944
     * @private
945
     */
946
    _setImage: function(e) {
947
        var form = this._form,
948
            url = form.one('.' + CSS.INPUTURL).get('value'),
949
            alt = form.one('.' + CSS.INPUTALT).get('value'),
950
            width = form.one('.' + CSS.INPUTWIDTH).get('value'),
951
            height = form.one('.' + CSS.INPUTHEIGHT).get('value'),
952
            alignment = this._getAlignmentClass(form.one('.' + CSS.INPUTALIGNMENT).get('value')),
953
            presentation = form.one('.' + CSS.IMAGEPRESENTATION).get('checked'),
954
            constrain = form.one('.' + CSS.INPUTCONSTRAIN).get('checked'),
955
            imagehtml,
956
            customstyle = form.one('.' + CSS.INPUTCUSTOMSTYLE).get('value'),
957
            classlist = [],
958
            host = this.get('host');
959
 
960
        e.preventDefault();
961
 
962
        // Check if there are any accessibility issues.
963
        if (this._updateWarning()) {
964
            return;
965
        }
966
 
967
        // Focus on the editor in preparation for inserting the image.
968
        host.focus();
969
        if (url !== '') {
970
            if (this._selectedImage) {
971
                host.setSelection(host.getSelectionFromNode(this._selectedImage));
972
            } else {
973
                host.setSelection(this._currentSelection);
974
            }
975
 
976
            if (constrain) {
977
                classlist.push(CSS.RESPONSIVE);
978
            }
979
 
980
            // Add the alignment class for the image.
981
            classlist.push(alignment);
982
 
983
            if (!width.match(REGEX.ISPERCENT) && isNaN(parseInt(width, 10))) {
984
                form.one('.' + CSS.INPUTWIDTH).focus();
985
                return;
986
            }
987
            if (!height.match(REGEX.ISPERCENT) && isNaN(parseInt(height, 10))) {
988
                form.one('.' + CSS.INPUTHEIGHT).focus();
989
                return;
990
            }
991
 
992
            var template = Y.Handlebars.compile(IMAGETEMPLATE);
993
            imagehtml = template({
994
                url: url,
995
                alt: alt,
996
                width: width,
997
                height: height,
998
                presentation: presentation,
999
                customstyle: customstyle,
1000
                classlist: classlist.join(' ')
1001
            });
1002
 
1003
            this.get('host').insertContentAtFocusPoint(imagehtml);
1004
 
1005
            this.markUpdated();
1006
        }
1007
 
1008
        this.getDialogue({
1009
            focusAfterHide: null
1010
        }).hide();
1011
 
1012
    },
1013
 
1014
    /**
1015
     * Removes any legacy styles added by previous versions of the atto image button.
1016
     *
1017
     * @method _removeLegacyAlignment
1018
     * @param {Y.Node} imageNode
1019
     * @return {Y.Node}
1020
     * @private
1021
     */
1022
    _removeLegacyAlignment: function(imageNode) {
1023
        if (!imageNode.getStyle('margin')) {
1024
            // There is no margin therefore this cannot match any known alignments.
1025
            return imageNode;
1026
        }
1027
 
1028
        ALIGNMENTS.some(function(alignment) {
1029
            if (imageNode.getStyle(alignment.name) !== alignment.value) {
1030
                // The name/value do not match. Skip.
1031
                return false;
1032
            }
1033
 
1034
            var normalisedNode = Y.Node.create('<div>');
1035
            normalisedNode.setStyle('margin', alignment.margin);
1036
            if (imageNode.getStyle('margin') !== normalisedNode.getStyle('margin')) {
1037
                // The margin does not match.
1038
                return false;
1039
            }
1040
 
1041
            Y.log('Legacy alignment found and removed.', 'info', 'atto_image-button');
1042
            imageNode.addClass(this._getAlignmentClass(alignment.value));
1043
            imageNode.setStyle(alignment.name, null);
1044
            imageNode.setStyle('margin', null);
1045
 
1046
            return true;
1047
        }, this);
1048
 
1049
        return imageNode;
1050
    },
1051
 
1052
    _getAlignmentClass: function(alignment) {
1053
        return CSS.ALIGNSETTINGS + '_' + alignment;
1054
    },
1055
 
1056
    _toggleVisibility: function(selector, predicate) {
1057
        var form = this._form;
1058
        var element = form.all(selector);
1059
        element.setStyle('display', predicate ? 'block' : 'none');
1060
    },
1061
 
1062
    _toggleAriaInvalid: function(selectors, predicate) {
1063
        var form = this._form;
1064
        selectors.forEach(function(selector) {
1065
            var element = form.all(selector);
1066
            element.setAttribute('aria-invalid', predicate);
1067
        });
1068
    },
1069
 
1070
    _hasErrorUrlField: function() {
1071
        var form = this._form;
1072
        var url = form.one('.' + CSS.INPUTURL).get('value');
1073
        var urlerror = url === '';
1074
        this._toggleVisibility('.' + CSS.IMAGEURLWARNING, urlerror);
1075
        this._toggleAriaInvalid(['.' + CSS.INPUTURL], urlerror);
1076
        return urlerror;
1077
    },
1078
 
1079
    _hasErrorAltField: function() {
1080
        var form = this._form;
1081
        var alt = form.one('.' + CSS.INPUTALT).get('value');
1082
        var presentation = form.one('.' + CSS.IMAGEPRESENTATION).get('checked');
1083
        var imagealterror = alt === '' && !presentation;
1084
        this._toggleVisibility('.' + CSS.IMAGEALTWARNING, imagealterror);
1085
        this._toggleAriaInvalid(['.' + CSS.INPUTALT, '.' + CSS.IMAGEPRESENTATION], imagealterror);
1086
        return imagealterror;
1087
    },
1088
    /**
1089
     * Update the alt text warning live.
1090
     *
1091
     * @method _updateWarning
1092
     * @return {boolean} whether a warning should be displayed.
1093
     * @private
1094
     */
1095
    _updateWarning: function() {
1096
        var urlerror = this._hasErrorUrlField();
1097
        var imagealterror = this._hasErrorAltField();
1098
        var haserrors = urlerror || imagealterror;
1099
        this.getDialogue().centerDialogue();
1100
        return haserrors;
1101
    },
1102
 
1103
    /**
1104
     * Handle the keyup to update the character count.
1105
     */
1106
    _handleKeyup: function() {
1107
        var form = this._form,
1108
            alt = form.one('.' + CSS.INPUTALT).get('value'),
1109
            characterCount = alt.length,
1110
            current = form.one('#currentcount');
1111
        current.setHTML(characterCount);
1112
    }
1113
});