machine-name.es6.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. /**
  2. * @file
  3. * Machine name functionality.
  4. */
  5. (function ($, Drupal, drupalSettings) {
  6. /**
  7. * Attach the machine-readable name form element behavior.
  8. *
  9. * @type {Drupal~behavior}
  10. *
  11. * @prop {Drupal~behaviorAttach} attach
  12. * Attaches machine-name behaviors.
  13. */
  14. Drupal.behaviors.machineName = {
  15. /**
  16. * Attaches the behavior.
  17. *
  18. * @param {Element} context
  19. * The context for attaching the behavior.
  20. * @param {object} settings
  21. * Settings object.
  22. * @param {object} settings.machineName
  23. * A list of elements to process, keyed by the HTML ID of the form
  24. * element containing the human-readable value. Each element is an object
  25. * defining the following properties:
  26. * - target: The HTML ID of the machine name form element.
  27. * - suffix: The HTML ID of a container to show the machine name preview
  28. * in (usually a field suffix after the human-readable name
  29. * form element).
  30. * - label: The label to show for the machine name preview.
  31. * - replace_pattern: A regular expression (without modifiers) matching
  32. * disallowed characters in the machine name; e.g., '[^a-z0-9]+'.
  33. * - replace: A character to replace disallowed characters with; e.g.,
  34. * '_' or '-'.
  35. * - standalone: Whether the preview should stay in its own element
  36. * rather than the suffix of the source element.
  37. * - field_prefix: The #field_prefix of the form element.
  38. * - field_suffix: The #field_suffix of the form element.
  39. */
  40. attach(context, settings) {
  41. const self = this;
  42. const $context = $(context);
  43. let timeout = null;
  44. let xhr = null;
  45. function clickEditHandler(e) {
  46. const data = e.data;
  47. data.$wrapper.removeClass('visually-hidden');
  48. data.$target.trigger('focus');
  49. data.$suffix.hide();
  50. data.$source.off('.machineName');
  51. }
  52. function machineNameHandler(e) {
  53. const data = e.data;
  54. const options = data.options;
  55. const baseValue = $(e.target).val();
  56. const rx = new RegExp(options.replace_pattern, 'g');
  57. const expected = baseValue.toLowerCase().replace(rx, options.replace).substr(0, options.maxlength);
  58. // Abort the last pending request because the label has changed and it
  59. // is no longer valid.
  60. if (xhr && xhr.readystate !== 4) {
  61. xhr.abort();
  62. xhr = null;
  63. }
  64. // Wait 300 milliseconds for Ajax request since the last event to update
  65. // the machine name i.e., after the user has stopped typing.
  66. if (timeout) {
  67. clearTimeout(timeout);
  68. timeout = null;
  69. }
  70. if (baseValue.toLowerCase() !== expected) {
  71. timeout = setTimeout(() => {
  72. xhr = self.transliterate(baseValue, options).done((machine) => {
  73. self.showMachineName(machine.substr(0, options.maxlength), data);
  74. });
  75. }, 300);
  76. }
  77. else {
  78. self.showMachineName(expected, data);
  79. }
  80. }
  81. Object.keys(settings.machineName).forEach((source_id) => {
  82. let machine = '';
  83. let eventData;
  84. const options = settings.machineName[source_id];
  85. const $source = $context.find(source_id).addClass('machine-name-source').once('machine-name');
  86. const $target = $context.find(options.target).addClass('machine-name-target');
  87. const $suffix = $context.find(options.suffix);
  88. const $wrapper = $target.closest('.js-form-item');
  89. // All elements have to exist.
  90. if (!$source.length || !$target.length || !$suffix.length || !$wrapper.length) {
  91. return;
  92. }
  93. // Skip processing upon a form validation error on the machine name.
  94. if ($target.hasClass('error')) {
  95. return;
  96. }
  97. // Figure out the maximum length for the machine name.
  98. options.maxlength = $target.attr('maxlength');
  99. // Hide the form item container of the machine name form element.
  100. $wrapper.addClass('visually-hidden');
  101. // Determine the initial machine name value. Unless the machine name
  102. // form element is disabled or not empty, the initial default value is
  103. // based on the human-readable form element value.
  104. if ($target.is(':disabled') || $target.val() !== '') {
  105. machine = $target.val();
  106. }
  107. else if ($source.val() !== '') {
  108. machine = self.transliterate($source.val(), options);
  109. }
  110. // Append the machine name preview to the source field.
  111. const $preview = $(`<span class="machine-name-value">${options.field_prefix}${Drupal.checkPlain(machine)}${options.field_suffix}</span>`);
  112. $suffix.empty();
  113. if (options.label) {
  114. $suffix.append(`<span class="machine-name-label">${options.label}: </span>`);
  115. }
  116. $suffix.append($preview);
  117. // If the machine name cannot be edited, stop further processing.
  118. if ($target.is(':disabled')) {
  119. return;
  120. }
  121. eventData = {
  122. $source,
  123. $target,
  124. $suffix,
  125. $wrapper,
  126. $preview,
  127. options,
  128. };
  129. // If it is editable, append an edit link.
  130. const $link = $(`<span class="admin-link"><button type="button" class="link">${Drupal.t('Edit')}</button></span>`).on('click', eventData, clickEditHandler);
  131. $suffix.append($link);
  132. // Preview the machine name in realtime when the human-readable name
  133. // changes, but only if there is no machine name yet; i.e., only upon
  134. // initial creation, not when editing.
  135. if ($target.val() === '') {
  136. $source.on('formUpdated.machineName', eventData, machineNameHandler)
  137. // Initialize machine name preview.
  138. .trigger('formUpdated.machineName');
  139. }
  140. // Add a listener for an invalid event on the machine name input
  141. // to show its container and focus it.
  142. $target.on('invalid', eventData, clickEditHandler);
  143. });
  144. },
  145. showMachineName(machine, data) {
  146. const settings = data.options;
  147. // Set the machine name to the transliterated value.
  148. if (machine !== '') {
  149. if (machine !== settings.replace) {
  150. data.$target.val(machine);
  151. data.$preview.html(settings.field_prefix + Drupal.checkPlain(machine) + settings.field_suffix);
  152. }
  153. data.$suffix.show();
  154. }
  155. else {
  156. data.$suffix.hide();
  157. data.$target.val(machine);
  158. data.$preview.empty();
  159. }
  160. },
  161. /**
  162. * Transliterate a human-readable name to a machine name.
  163. *
  164. * @param {string} source
  165. * A string to transliterate.
  166. * @param {object} settings
  167. * The machine name settings for the corresponding field.
  168. * @param {string} settings.replace_pattern
  169. * A regular expression (without modifiers) matching disallowed characters
  170. * in the machine name; e.g., '[^a-z0-9]+'.
  171. * @param {string} settings.replace_token
  172. * A token to validate the regular expression.
  173. * @param {string} settings.replace
  174. * A character to replace disallowed characters with; e.g., '_' or '-'.
  175. * @param {number} settings.maxlength
  176. * The maximum length of the machine name.
  177. *
  178. * @return {jQuery}
  179. * The transliterated source string.
  180. */
  181. transliterate(source, settings) {
  182. return $.get(Drupal.url('machine_name/transliterate'), {
  183. text: source,
  184. langcode: drupalSettings.langcode,
  185. replace_pattern: settings.replace_pattern,
  186. replace_token: settings.replace_token,
  187. replace: settings.replace,
  188. lowercase: true,
  189. });
  190. },
  191. };
  192. }(jQuery, Drupal, drupalSettings));