9ab5dc2da356683eef570143d4a797d70bb4deda
[yaffs-website] / web / core / modules / file / file.es6.js
1 /**
2  * @file
3  * Provides JavaScript additions to the managed file field type.
4  *
5  * This file provides progress bar support (if available), popup windows for
6  * file previews, and disabling of other file fields during Ajax uploads (which
7  * prevents separate file fields from accidentally uploading files).
8  */
9
10 (function ($, Drupal) {
11   /**
12    * Attach behaviors to the file fields passed in the settings.
13    *
14    * @type {Drupal~behavior}
15    *
16    * @prop {Drupal~behaviorAttach} attach
17    *   Attaches validation for file extensions.
18    * @prop {Drupal~behaviorDetach} detach
19    *   Detaches validation for file extensions.
20    */
21   Drupal.behaviors.fileValidateAutoAttach = {
22     attach(context, settings) {
23       const $context = $(context);
24       let elements;
25
26       function initFileValidation(selector) {
27         $context.find(selector)
28           .once('fileValidate')
29           .on('change.fileValidate', { extensions: elements[selector] }, Drupal.file.validateExtension);
30       }
31
32       if (settings.file && settings.file.elements) {
33         elements = settings.file.elements;
34         Object.keys(elements).forEach(initFileValidation);
35       }
36     },
37     detach(context, settings, trigger) {
38       const $context = $(context);
39       let elements;
40
41       function removeFileValidation(selector) {
42         $context.find(selector)
43           .removeOnce('fileValidate')
44           .off('change.fileValidate', Drupal.file.validateExtension);
45       }
46
47       if (trigger === 'unload' && settings.file && settings.file.elements) {
48         elements = settings.file.elements;
49         Object.keys(elements).forEach(removeFileValidation);
50       }
51     },
52   };
53
54   /**
55    * Attach behaviors to file element auto upload.
56    *
57    * @type {Drupal~behavior}
58    *
59    * @prop {Drupal~behaviorAttach} attach
60    *   Attaches triggers for the upload button.
61    * @prop {Drupal~behaviorDetach} detach
62    *   Detaches auto file upload trigger.
63    */
64   Drupal.behaviors.fileAutoUpload = {
65     attach(context) {
66       $(context).find('input[type="file"]').once('auto-file-upload').on('change.autoFileUpload', Drupal.file.triggerUploadButton);
67     },
68     detach(context, setting, trigger) {
69       if (trigger === 'unload') {
70         $(context).find('input[type="file"]').removeOnce('auto-file-upload').off('.autoFileUpload');
71       }
72     },
73   };
74
75   /**
76    * Attach behaviors to the file upload and remove buttons.
77    *
78    * @type {Drupal~behavior}
79    *
80    * @prop {Drupal~behaviorAttach} attach
81    *   Attaches form submit events.
82    * @prop {Drupal~behaviorDetach} detach
83    *   Detaches form submit events.
84    */
85   Drupal.behaviors.fileButtons = {
86     attach(context) {
87       const $context = $(context);
88       $context.find('.js-form-submit').on('mousedown', Drupal.file.disableFields);
89       $context.find('.js-form-managed-file .js-form-submit').on('mousedown', Drupal.file.progressBar);
90     },
91     detach(context) {
92       const $context = $(context);
93       $context.find('.js-form-submit').off('mousedown', Drupal.file.disableFields);
94       $context.find('.js-form-managed-file .js-form-submit').off('mousedown', Drupal.file.progressBar);
95     },
96   };
97
98   /**
99    * Attach behaviors to links within managed file elements for preview windows.
100    *
101    * @type {Drupal~behavior}
102    *
103    * @prop {Drupal~behaviorAttach} attach
104    *   Attaches triggers.
105    * @prop {Drupal~behaviorDetach} detach
106    *   Detaches triggers.
107    */
108   Drupal.behaviors.filePreviewLinks = {
109     attach(context) {
110       $(context).find('div.js-form-managed-file .file a').on('click', Drupal.file.openInNewWindow);
111     },
112     detach(context) {
113       $(context).find('div.js-form-managed-file .file a').off('click', Drupal.file.openInNewWindow);
114     },
115   };
116
117   /**
118    * File upload utility functions.
119    *
120    * @namespace
121    */
122   Drupal.file = Drupal.file || {
123
124     /**
125      * Client-side file input validation of file extensions.
126      *
127      * @name Drupal.file.validateExtension
128      *
129      * @param {jQuery.Event} event
130      *   The event triggered. For example `change.fileValidate`.
131      */
132     validateExtension(event) {
133       event.preventDefault();
134       // Remove any previous errors.
135       $('.file-upload-js-error').remove();
136
137       // Add client side validation for the input[type=file].
138       const extensionPattern = event.data.extensions.replace(/,\s*/g, '|');
139       if (extensionPattern.length > 1 && this.value.length > 0) {
140         const acceptableMatch = new RegExp(`\\.(${extensionPattern})$`, 'gi');
141         if (!acceptableMatch.test(this.value)) {
142           const error = Drupal.t('The selected file %filename cannot be uploaded. Only files with the following extensions are allowed: %extensions.', {
143             // According to the specifications of HTML5, a file upload control
144             // should not reveal the real local path to the file that a user
145             // has selected. Some web browsers implement this restriction by
146             // replacing the local path with "C:\fakepath\", which can cause
147             // confusion by leaving the user thinking perhaps Drupal could not
148             // find the file because it messed up the file path. To avoid this
149             // confusion, therefore, we strip out the bogus fakepath string.
150             '%filename': this.value.replace('C:\\fakepath\\', ''),
151             '%extensions': extensionPattern.replace(/\|/g, ', '),
152           });
153           $(this).closest('div.js-form-managed-file').prepend(`<div class="messages messages--error file-upload-js-error" aria-live="polite">${error}</div>`);
154           this.value = '';
155           // Cancel all other change event handlers.
156           event.stopImmediatePropagation();
157         }
158       }
159     },
160
161     /**
162      * Trigger the upload_button mouse event to auto-upload as a managed file.
163      *
164      * @name Drupal.file.triggerUploadButton
165      *
166      * @param {jQuery.Event} event
167      *   The event triggered. For example `change.autoFileUpload`.
168      */
169     triggerUploadButton(event) {
170       $(event.target).closest('.js-form-managed-file').find('.js-form-submit').trigger('mousedown');
171     },
172
173     /**
174      * Prevent file uploads when using buttons not intended to upload.
175      *
176      * @name Drupal.file.disableFields
177      *
178      * @param {jQuery.Event} event
179      *   The event triggered, most likely a `mousedown` event.
180      */
181     disableFields(event) {
182       const $clickedButton = $(this).findOnce('ajax');
183
184       // Only disable upload fields for Ajax buttons.
185       if (!$clickedButton.length) {
186         return;
187       }
188
189       // Check if we're working with an "Upload" button.
190       let $enabledFields = [];
191       if ($clickedButton.closest('div.js-form-managed-file').length > 0) {
192         $enabledFields = $clickedButton.closest('div.js-form-managed-file').find('input.js-form-file');
193       }
194
195       // Temporarily disable upload fields other than the one we're currently
196       // working with. Filter out fields that are already disabled so that they
197       // do not get enabled when we re-enable these fields at the end of
198       // behavior processing. Re-enable in a setTimeout set to a relatively
199       // short amount of time (1 second). All the other mousedown handlers
200       // (like Drupal's Ajax behaviors) are executed before any timeout
201       // functions are called, so we don't have to worry about the fields being
202       // re-enabled too soon. @todo If the previous sentence is true, why not
203       // set the timeout to 0?
204       const $fieldsToTemporarilyDisable = $('div.js-form-managed-file input.js-form-file').not($enabledFields).not(':disabled');
205       $fieldsToTemporarilyDisable.prop('disabled', true);
206       setTimeout(() => {
207         $fieldsToTemporarilyDisable.prop('disabled', false);
208       }, 1000);
209     },
210
211     /**
212      * Add progress bar support if possible.
213      *
214      * @name Drupal.file.progressBar
215      *
216      * @param {jQuery.Event} event
217      *   The event triggered, most likely a `mousedown` event.
218      */
219     progressBar(event) {
220       const $clickedButton = $(this);
221       const $progressId = $clickedButton.closest('div.js-form-managed-file').find('input.file-progress');
222       if ($progressId.length) {
223         const originalName = $progressId.attr('name');
224
225         // Replace the name with the required identifier.
226         $progressId.attr('name', originalName.match(/APC_UPLOAD_PROGRESS|UPLOAD_IDENTIFIER/)[0]);
227
228         // Restore the original name after the upload begins.
229         setTimeout(() => {
230           $progressId.attr('name', originalName);
231         }, 1000);
232       }
233       // Show the progress bar if the upload takes longer than half a second.
234       setTimeout(() => {
235         $clickedButton.closest('div.js-form-managed-file').find('div.ajax-progress-bar').slideDown();
236       }, 500);
237     },
238
239     /**
240      * Open links to files within forms in a new window.
241      *
242      * @name Drupal.file.openInNewWindow
243      *
244      * @param {jQuery.Event} event
245      *   The event triggered, most likely a `click` event.
246      */
247     openInNewWindow(event) {
248       event.preventDefault();
249       $(this).attr('target', '_blank');
250       window.open(this.href, 'filePreview', 'toolbar=0,scrollbars=1,location=1,statusbar=1,menubar=0,resizable=1,width=500,height=550');
251     },
252   };
253 }(jQuery, Drupal));