machine-name.es6.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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((sourceId) => {
  82. let machine = '';
  83. const options = settings.machineName[sourceId];
  84. const $source = $context.find(sourceId).addClass('machine-name-source').once('machine-name');
  85. const $target = $context.find(options.target).addClass('machine-name-target');
  86. const $suffix = $context.find(options.suffix);
  87. const $wrapper = $target.closest('.js-form-item');
  88. // All elements have to exist.
  89. if (!$source.length || !$target.length || !$suffix.length || !$wrapper.length) {
  90. return;
  91. }
  92. // Skip processing upon a form validation error on the machine name.
  93. if ($target.hasClass('error')) {
  94. return;
  95. }
  96. // Figure out the maximum length for the machine name.
  97. options.maxlength = $target.attr('maxlength');
  98. // Hide the form item container of the machine name form element.
  99. $wrapper.addClass('visually-hidden');
  100. // Determine the initial machine name value. Unless the machine name
  101. // form element is disabled or not empty, the initial default value is
  102. // based on the human-readable form element value.
  103. if ($target.is(':disabled') || $target.val() !== '') {
  104. machine = $target.val();
  105. }
  106. else if ($source.val() !== '') {
  107. machine = self.transliterate($source.val(), options);
  108. }
  109. // Append the machine name preview to the source field.
  110. const $preview = $(`<span class="machine-name-value">${options.field_prefix}${Drupal.checkPlain(machine)}${options.field_suffix}</span>`);
  111. $suffix.empty();
  112. if (options.label) {
  113. $suffix.append(`<span class="machine-name-label">${options.label}: </span>`);
  114. }
  115. $suffix.append($preview);
  116. // If the machine name cannot be edited, stop further processing.
  117. if ($target.is(':disabled')) {
  118. return;
  119. }
  120. const eventData = {
  121. $source,
  122. $target,
  123. $suffix,
  124. $wrapper,
  125. $preview,
  126. options,
  127. };
  128. // If it is editable, append an edit link.
  129. const $link = $(`<span class="admin-link"><button type="button" class="link">${Drupal.t('Edit')}</button></span>`).on('click', eventData, clickEditHandler);
  130. $suffix.append($link);
  131. // Preview the machine name in realtime when the human-readable name
  132. // changes, but only if there is no machine name yet; i.e., only upon
  133. // initial creation, not when editing.
  134. if ($target.val() === '') {
  135. $source.on('formUpdated.machineName', eventData, machineNameHandler)
  136. // Initialize machine name preview.
  137. .trigger('formUpdated.machineName');
  138. }
  139. // Add a listener for an invalid event on the machine name input
  140. // to show its container and focus it.
  141. $target.on('invalid', eventData, clickEditHandler);
  142. });
  143. },
  144. showMachineName(machine, data) {
  145. const settings = data.options;
  146. // Set the machine name to the transliterated value.
  147. if (machine !== '') {
  148. if (machine !== settings.replace) {
  149. data.$target.val(machine);
  150. data.$preview.html(settings.field_prefix + Drupal.checkPlain(machine) + settings.field_suffix);
  151. }
  152. data.$suffix.show();
  153. }
  154. else {
  155. data.$suffix.hide();
  156. data.$target.val(machine);
  157. data.$preview.empty();
  158. }
  159. },
  160. /**
  161. * Transliterate a human-readable name to a machine name.
  162. *
  163. * @param {string} source
  164. * A string to transliterate.
  165. * @param {object} settings
  166. * The machine name settings for the corresponding field.
  167. * @param {string} settings.replace_pattern
  168. * A regular expression (without modifiers) matching disallowed characters
  169. * in the machine name; e.g., '[^a-z0-9]+'.
  170. * @param {string} settings.replace_token
  171. * A token to validate the regular expression.
  172. * @param {string} settings.replace
  173. * A character to replace disallowed characters with; e.g., '_' or '-'.
  174. * @param {number} settings.maxlength
  175. * The maximum length of the machine name.
  176. *
  177. * @return {jQuery}
  178. * The transliterated source string.
  179. */
  180. transliterate(source, settings) {
  181. return $.get(Drupal.url('machine_name/transliterate'), {
  182. text: source,
  183. langcode: drupalSettings.langcode,
  184. replace_pattern: settings.replace_pattern,
  185. replace_token: settings.replace_token,
  186. replace: settings.replace,
  187. lowercase: true,
  188. });
  189. },
  190. };
  191. }(jQuery, Drupal, drupalSettings));