file.js 9.2 KB

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