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