3 * Provides JavaScript additions to the managed file field type.
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).
10 (function($, Drupal) {
12 * Attach behaviors to the file fields passed in the settings.
14 * @type {Drupal~behavior}
16 * @prop {Drupal~behaviorAttach} attach
17 * Attaches validation for file extensions.
18 * @prop {Drupal~behaviorDetach} detach
19 * Detaches validation for file extensions.
21 Drupal.behaviors.fileValidateAutoAttach = {
22 attach(context, settings) {
23 const $context = $(context);
26 function initFileValidation(selector) {
31 'change.fileValidate',
32 { extensions: elements[selector] },
33 Drupal.file.validateExtension,
37 if (settings.file && settings.file.elements) {
38 elements = settings.file.elements;
39 Object.keys(elements).forEach(initFileValidation);
42 detach(context, settings, trigger) {
43 const $context = $(context);
46 function removeFileValidation(selector) {
49 .removeOnce('fileValidate')
50 .off('change.fileValidate', Drupal.file.validateExtension);
53 if (trigger === 'unload' && settings.file && settings.file.elements) {
54 elements = settings.file.elements;
55 Object.keys(elements).forEach(removeFileValidation);
61 * Attach behaviors to file element auto upload.
63 * @type {Drupal~behavior}
65 * @prop {Drupal~behaviorAttach} attach
66 * Attaches triggers for the upload button.
67 * @prop {Drupal~behaviorDetach} detach
68 * Detaches auto file upload trigger.
70 Drupal.behaviors.fileAutoUpload = {
73 .find('input[type="file"]')
74 .once('auto-file-upload')
75 .on('change.autoFileUpload', Drupal.file.triggerUploadButton);
77 detach(context, settings, trigger) {
78 if (trigger === 'unload') {
80 .find('input[type="file"]')
81 .removeOnce('auto-file-upload')
82 .off('.autoFileUpload');
88 * Attach behaviors to the file upload and remove buttons.
90 * @type {Drupal~behavior}
92 * @prop {Drupal~behaviorAttach} attach
93 * Attaches form submit events.
94 * @prop {Drupal~behaviorDetach} detach
95 * Detaches form submit events.
97 Drupal.behaviors.fileButtons = {
99 const $context = $(context);
101 .find('.js-form-submit')
102 .on('mousedown', Drupal.file.disableFields);
104 .find('.js-form-managed-file .js-form-submit')
105 .on('mousedown', Drupal.file.progressBar);
107 detach(context, settings, trigger) {
108 if (trigger === 'unload') {
109 const $context = $(context);
111 .find('.js-form-submit')
112 .off('mousedown', Drupal.file.disableFields);
114 .find('.js-form-managed-file .js-form-submit')
115 .off('mousedown', Drupal.file.progressBar);
121 * Attach behaviors to links within managed file elements for preview windows.
123 * @type {Drupal~behavior}
125 * @prop {Drupal~behaviorAttach} attach
127 * @prop {Drupal~behaviorDetach} detach
130 Drupal.behaviors.filePreviewLinks = {
133 .find('div.js-form-managed-file .file a')
134 .on('click', Drupal.file.openInNewWindow);
138 .find('div.js-form-managed-file .file a')
139 .off('click', Drupal.file.openInNewWindow);
144 * File upload utility functions.
148 Drupal.file = Drupal.file || {
150 * Client-side file input validation of file extensions.
152 * @name Drupal.file.validateExtension
154 * @param {jQuery.Event} event
155 * The event triggered. For example `change.fileValidate`.
157 validateExtension(event) {
158 event.preventDefault();
159 // Remove any previous errors.
160 $('.file-upload-js-error').remove();
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.',
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, ', '),
182 .closest('div.js-form-managed-file')
184 `<div class="messages messages--error file-upload-js-error" aria-live="polite">${error}</div>`,
187 // Cancel all other change event handlers.
188 event.stopImmediatePropagation();
194 * Trigger the upload_button mouse event to auto-upload as a managed file.
196 * @name Drupal.file.triggerUploadButton
198 * @param {jQuery.Event} event
199 * The event triggered. For example `change.autoFileUpload`.
201 triggerUploadButton(event) {
203 .closest('.js-form-managed-file')
204 .find('.js-form-submit')
205 .trigger('mousedown');
209 * Prevent file uploads when using buttons not intended to upload.
211 * @name Drupal.file.disableFields
213 * @param {jQuery.Event} event
214 * The event triggered, most likely a `mousedown` event.
216 disableFields(event) {
217 const $clickedButton = $(this);
218 $clickedButton.trigger('formUpdated');
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');
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',
242 $fieldsToTemporarilyDisable.prop('disabled', true);
244 $fieldsToTemporarilyDisable.prop('disabled', false);
249 * Add progress bar support if possible.
251 * @name Drupal.file.progressBar
253 * @param {jQuery.Event} event
254 * The event triggered, most likely a `mousedown` 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');
264 // Replace the name with the required identifier.
267 originalName.match(/APC_UPLOAD_PROGRESS|UPLOAD_IDENTIFIER/)[0],
270 // Restore the original name after the upload begins.
272 $progressId.attr('name', originalName);
275 // Show the progress bar if the upload takes longer than half a second.
278 .closest('div.js-form-managed-file')
279 .find('div.ajax-progress-bar')
282 $clickedButton.trigger('fileUpload');
286 * Open links to files within forms in a new window.
288 * @name Drupal.file.openInNewWindow
290 * @param {jQuery.Event} event
291 * The event triggered, most likely a `click` event.
293 openInNewWindow(event) {
294 event.preventDefault();
295 $(this).attr('target', '_blank');
299 'toolbar=0,scrollbars=1,location=1,statusbar=1,menubar=0,resizable=1,width=500,height=550',