layout-builder.es6.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. /**
  2. * @file
  3. * Attaches the behaviors for the Layout Builder module.
  4. */
  5. (($, Drupal, Sortable) => {
  6. const { ajax, behaviors, debounce, announce, formatPlural } = Drupal;
  7. /*
  8. * Boolean that tracks if block listing is currently being filtered. Declared
  9. * outside of behaviors so value is retained on rebuild.
  10. */
  11. let layoutBuilderBlocksFiltered = false;
  12. /**
  13. * Provides the ability to filter the block listing in "Add block" dialog.
  14. *
  15. * @type {Drupal~behavior}
  16. *
  17. * @prop {Drupal~behaviorAttach} attach
  18. * Attach block filtering behavior to "Add block" dialog.
  19. */
  20. behaviors.layoutBuilderBlockFilter = {
  21. attach(context) {
  22. const $categories = $('.js-layout-builder-categories', context);
  23. const $filterLinks = $categories.find('.js-layout-builder-block-link');
  24. /**
  25. * Filters the block list.
  26. *
  27. * @param {jQuery.Event} e
  28. * The jQuery event for the keyup event that triggered the filter.
  29. */
  30. const filterBlockList = e => {
  31. const query = $(e.target)
  32. .val()
  33. .toLowerCase();
  34. /**
  35. * Shows or hides the block entry based on the query.
  36. *
  37. * @param {number} index
  38. * The index in the loop, as provided by `jQuery.each`
  39. * @param {HTMLElement} link
  40. * The link to add the block.
  41. */
  42. const toggleBlockEntry = (index, link) => {
  43. const $link = $(link);
  44. const textMatch =
  45. $link
  46. .text()
  47. .toLowerCase()
  48. .indexOf(query) !== -1;
  49. $link.toggle(textMatch);
  50. };
  51. // Filter if the length of the query is at least 2 characters.
  52. if (query.length >= 2) {
  53. // Attribute to note which categories are closed before opening all.
  54. $categories
  55. .find('.js-layout-builder-category:not([open])')
  56. .attr('remember-closed', '');
  57. // Open all categories so every block is available to filtering.
  58. $categories.find('.js-layout-builder-category').attr('open', '');
  59. // Toggle visibility of links based on query.
  60. $filterLinks.each(toggleBlockEntry);
  61. // Only display categories containing visible links.
  62. $categories
  63. .find(
  64. '.js-layout-builder-category:not(:has(.js-layout-builder-block-link:visible))',
  65. )
  66. .hide();
  67. announce(
  68. formatPlural(
  69. $categories.find('.js-layout-builder-block-link:visible').length,
  70. '1 block is available in the modified list.',
  71. '@count blocks are available in the modified list.',
  72. ),
  73. );
  74. layoutBuilderBlocksFiltered = true;
  75. } else if (layoutBuilderBlocksFiltered) {
  76. layoutBuilderBlocksFiltered = false;
  77. // Remove "open" attr from categories that were closed pre-filtering.
  78. $categories
  79. .find('.js-layout-builder-category[remember-closed]')
  80. .removeAttr('open')
  81. .removeAttr('remember-closed');
  82. $categories.find('.js-layout-builder-category').show();
  83. $filterLinks.show();
  84. announce(Drupal.t('All available blocks are listed.'));
  85. }
  86. };
  87. $('input.js-layout-builder-filter', context)
  88. .once('block-filter-text')
  89. .on('keyup', debounce(filterBlockList, 200));
  90. },
  91. };
  92. /**
  93. * Callback used in {@link Drupal.behaviors.layoutBuilderBlockDrag}.
  94. *
  95. * @param {HTMLElement} item
  96. * The HTML element representing the repositioned block.
  97. * @param {HTMLElement} from
  98. * The HTML element representing the previous parent of item
  99. * @param {HTMLElement} to
  100. * The HTML element representing the current parent of item
  101. *
  102. * @internal This method is a callback for layoutBuilderBlockDrag and is used
  103. * in FunctionalJavascript tests. It may be renamed if the test changes.
  104. * @see https://www.drupal.org/node/3084730
  105. */
  106. Drupal.layoutBuilderBlockUpdate = function(item, from, to) {
  107. const $item = $(item);
  108. const $from = $(from);
  109. // Check if the region from the event and region for the item match.
  110. const itemRegion = $item.closest('.js-layout-builder-region');
  111. if (to === itemRegion[0]) {
  112. // Find the destination delta.
  113. const deltaTo = $item.closest('[data-layout-delta]').data('layout-delta');
  114. // If the block didn't leave the original delta use the destination.
  115. const deltaFrom = $from
  116. ? $from.closest('[data-layout-delta]').data('layout-delta')
  117. : deltaTo;
  118. ajax({
  119. url: [
  120. $item.closest('[data-layout-update-url]').data('layout-update-url'),
  121. deltaFrom,
  122. deltaTo,
  123. itemRegion.data('region'),
  124. $item.data('layout-block-uuid'),
  125. $item.prev('[data-layout-block-uuid]').data('layout-block-uuid'),
  126. ]
  127. .filter(element => element !== undefined)
  128. .join('/'),
  129. }).execute();
  130. }
  131. };
  132. /**
  133. * Provides the ability to drag blocks to new positions in the layout.
  134. *
  135. * @type {Drupal~behavior}
  136. *
  137. * @prop {Drupal~behaviorAttach} attach
  138. * Attach block drag behavior to the Layout Builder UI.
  139. */
  140. behaviors.layoutBuilderBlockDrag = {
  141. attach(context) {
  142. const regionSelector = '.js-layout-builder-region';
  143. Array.prototype.forEach.call(
  144. context.querySelectorAll(regionSelector),
  145. region => {
  146. Sortable.create(region, {
  147. draggable: '.js-layout-builder-block',
  148. ghostClass: 'ui-state-drop',
  149. group: 'builder-region',
  150. onEnd: event =>
  151. Drupal.layoutBuilderBlockUpdate(event.item, event.from, event.to),
  152. });
  153. },
  154. );
  155. },
  156. };
  157. /**
  158. * Disables interactive elements in previewed blocks.
  159. *
  160. * @type {Drupal~behavior}
  161. *
  162. * @prop {Drupal~behaviorAttach} attach
  163. * Attach disabling interactive elements behavior to the Layout Builder UI.
  164. */
  165. behaviors.layoutBuilderDisableInteractiveElements = {
  166. attach() {
  167. // Disable interactive elements inside preview blocks.
  168. const $blocks = $('#layout-builder [data-layout-block-uuid]');
  169. $blocks.find('input, textarea, select').prop('disabled', true);
  170. $blocks
  171. .find('a')
  172. // Don't disable contextual links.
  173. // @see \Drupal\contextual\Element\ContextualLinksPlaceholder
  174. .not(
  175. (index, element) =>
  176. $(element).closest('[data-contextual-id]').length > 0,
  177. )
  178. .on('click mouseup touchstart', e => {
  179. e.preventDefault();
  180. e.stopPropagation();
  181. });
  182. /*
  183. * In preview blocks, remove from the tabbing order all input elements
  184. * and elements specifically assigned a tab index, other than those
  185. * related to contextual links.
  186. */
  187. $blocks
  188. .find(
  189. 'button, [href], input, select, textarea, iframe, [tabindex]:not([tabindex="-1"]):not(.tabbable)',
  190. )
  191. .not(
  192. (index, element) =>
  193. $(element).closest('[data-contextual-id]').length > 0,
  194. )
  195. .attr('tabindex', -1);
  196. },
  197. };
  198. // After a dialog opens, highlight element that the dialog is acting on.
  199. $(window).on('dialog:aftercreate', (event, dialog, $element) => {
  200. if (Drupal.offCanvas.isOffCanvas($element)) {
  201. // Start by removing any existing highlighted elements.
  202. $('.is-layout-builder-highlighted').removeClass(
  203. 'is-layout-builder-highlighted',
  204. );
  205. /*
  206. * Every dialog has a single 'data-layout-builder-target-highlight-id'
  207. * attribute. Every dialog-opening element has a unique
  208. * 'data-layout-builder-highlight-id' attribute.
  209. *
  210. * When the value of data-layout-builder-target-highlight-id matches
  211. * an element's value of data-layout-builder-highlight-id, the class
  212. * 'is-layout-builder-highlighted' is added to element.
  213. */
  214. const id = $element
  215. .find('[data-layout-builder-target-highlight-id]')
  216. .attr('data-layout-builder-target-highlight-id');
  217. if (id) {
  218. $(`[data-layout-builder-highlight-id="${id}"]`).addClass(
  219. 'is-layout-builder-highlighted',
  220. );
  221. }
  222. // Remove wrapper class added by move block form.
  223. $('#layout-builder').removeClass('layout-builder--move-blocks-active');
  224. /**
  225. * If dialog has a data-add-layout-builder-wrapper attribute, get the
  226. * value and add it as a class to the Layout Builder UI wrapper.
  227. *
  228. * Currently, only the move block form uses
  229. * data-add-layout-builder-wrapper, but any dialog can use this attribute
  230. * to add a class to the Layout Builder UI while opened.
  231. */
  232. const layoutBuilderWrapperValue = $element
  233. .find('[data-add-layout-builder-wrapper]')
  234. .attr('data-add-layout-builder-wrapper');
  235. if (layoutBuilderWrapperValue) {
  236. $('#layout-builder').addClass(layoutBuilderWrapperValue);
  237. }
  238. }
  239. });
  240. /*
  241. * When a Layout Builder dialog is triggered, the main canvas resizes. After
  242. * the resize transition is complete, see if the target element is still
  243. * visible in viewport. If not, scroll page so the target element is again
  244. * visible.
  245. *
  246. * @todo Replace this custom solution when a general solution is made
  247. * available with https://www.drupal.org/node/3033410
  248. */
  249. if (document.querySelector('[data-off-canvas-main-canvas]')) {
  250. const mainCanvas = document.querySelector('[data-off-canvas-main-canvas]');
  251. // This event fires when canvas CSS transitions are complete.
  252. mainCanvas.addEventListener('transitionend', () => {
  253. const $target = $('.is-layout-builder-highlighted');
  254. if ($target.length > 0) {
  255. // These four variables are used to determine if the element is in the
  256. // viewport.
  257. const targetTop = $target.offset().top;
  258. const targetBottom = targetTop + $target.outerHeight();
  259. const viewportTop = $(window).scrollTop();
  260. const viewportBottom = viewportTop + $(window).height();
  261. // If the element is not in the viewport, scroll it into view.
  262. if (targetBottom < viewportTop || targetTop > viewportBottom) {
  263. const viewportMiddle = (viewportBottom + viewportTop) / 2;
  264. const scrollAmount = targetTop - viewportMiddle;
  265. // Check whether the browser supports scrollBy(options). If it does
  266. // not, use scrollBy(x-coord, y-coord) instead.
  267. if ('scrollBehavior' in document.documentElement.style) {
  268. window.scrollBy({
  269. top: scrollAmount,
  270. left: 0,
  271. behavior: 'smooth',
  272. });
  273. } else {
  274. window.scrollBy(0, scrollAmount);
  275. }
  276. }
  277. }
  278. });
  279. }
  280. $(window).on('dialog:afterclose', (event, dialog, $element) => {
  281. if (Drupal.offCanvas.isOffCanvas($element)) {
  282. // Remove the highlight from all elements.
  283. $('.is-layout-builder-highlighted').removeClass(
  284. 'is-layout-builder-highlighted',
  285. );
  286. // Remove wrapper class added by move block form.
  287. $('#layout-builder').removeClass('layout-builder--move-blocks-active');
  288. }
  289. });
  290. /**
  291. * Toggles content preview in the Layout Builder UI.
  292. *
  293. * @type {Drupal~behavior}
  294. *
  295. * @prop {Drupal~behaviorAttach} attach
  296. * Attach content preview toggle to the Layout Builder UI.
  297. */
  298. behaviors.layoutBuilderToggleContentPreview = {
  299. attach(context) {
  300. const $layoutBuilder = $('#layout-builder');
  301. // The content preview toggle.
  302. const $layoutBuilderContentPreview = $('#layout-builder-content-preview');
  303. // data-content-preview-id specifies the layout being edited.
  304. const contentPreviewId = $layoutBuilderContentPreview.data(
  305. 'content-preview-id',
  306. );
  307. /**
  308. * Tracks if content preview is enabled for this layout. Defaults to true
  309. * if no value has previously been set.
  310. */
  311. const isContentPreview =
  312. JSON.parse(localStorage.getItem(contentPreviewId)) !== false;
  313. /**
  314. * Disables content preview in the Layout Builder UI.
  315. *
  316. * Disabling content preview hides block content. It is replaced with the
  317. * value of the block's data-layout-content-preview-placeholder-label
  318. * attribute.
  319. *
  320. * @todo Revisit in https://www.drupal.org/node/3043215, it may be
  321. * possible to remove all but the first line of this function.
  322. */
  323. const disableContentPreview = () => {
  324. $layoutBuilder.addClass('layout-builder--content-preview-disabled');
  325. /**
  326. * Iterate over all Layout Builder blocks to hide their content and add
  327. * placeholder labels.
  328. */
  329. $('[data-layout-content-preview-placeholder-label]', context).each(
  330. (i, element) => {
  331. const $element = $(element);
  332. // Hide everything in block that isn't contextual link related.
  333. $element.children(':not([data-contextual-id])').hide(0);
  334. const contentPreviewPlaceholderText = $element.attr(
  335. 'data-layout-content-preview-placeholder-label',
  336. );
  337. const contentPreviewPlaceholderLabel = Drupal.theme(
  338. 'layoutBuilderPrependContentPreviewPlaceholderLabel',
  339. contentPreviewPlaceholderText,
  340. );
  341. $element.prepend(contentPreviewPlaceholderLabel);
  342. },
  343. );
  344. };
  345. /**
  346. * Enables content preview in the Layout Builder UI.
  347. *
  348. * When content preview is enabled, the Layout Builder UI returns to its
  349. * default experience. This is accomplished by removing placeholder
  350. * labels and un-hiding block content.
  351. *
  352. * @todo Revisit in https://www.drupal.org/node/3043215, it may be
  353. * possible to remove all but the first line of this function.
  354. */
  355. const enableContentPreview = () => {
  356. $layoutBuilder.removeClass('layout-builder--content-preview-disabled');
  357. // Remove all placeholder labels.
  358. $('.js-layout-builder-content-preview-placeholder-label').remove();
  359. // Iterate over all blocks.
  360. $('[data-layout-content-preview-placeholder-label]').each(
  361. (i, element) => {
  362. $(element)
  363. .children()
  364. .show();
  365. },
  366. );
  367. };
  368. $('#layout-builder-content-preview', context).on('change', event => {
  369. const isChecked = $(event.currentTarget).is(':checked');
  370. localStorage.setItem(contentPreviewId, JSON.stringify(isChecked));
  371. if (isChecked) {
  372. enableContentPreview();
  373. announce(
  374. Drupal.t('Block previews are visible. Block labels are hidden.'),
  375. );
  376. } else {
  377. disableContentPreview();
  378. announce(
  379. Drupal.t('Block previews are hidden. Block labels are visible.'),
  380. );
  381. }
  382. });
  383. /**
  384. * On rebuild, see if content preview has been set to disabled. If yes,
  385. * disable content preview in the Layout Builder UI.
  386. */
  387. if (!isContentPreview) {
  388. $layoutBuilderContentPreview.attr('checked', false);
  389. disableContentPreview();
  390. }
  391. },
  392. };
  393. /**
  394. * Creates content preview placeholder label markup.
  395. *
  396. * @param {string} contentPreviewPlaceholderText
  397. * The text content of the placeholder label
  398. *
  399. * @return {string}
  400. * A HTML string of the placeholder label.
  401. */
  402. Drupal.theme.layoutBuilderPrependContentPreviewPlaceholderLabel = contentPreviewPlaceholderText => {
  403. const contentPreviewPlaceholderLabel = document.createElement('div');
  404. contentPreviewPlaceholderLabel.className =
  405. 'layout-builder-block__content-preview-placeholder-label js-layout-builder-content-preview-placeholder-label';
  406. contentPreviewPlaceholderLabel.innerHTML = contentPreviewPlaceholderText;
  407. return `<div class="layout-builder-block__content-preview-placeholder-label js-layout-builder-content-preview-placeholder-label">${contentPreviewPlaceholderText}</div>`;
  408. };
  409. })(jQuery, Drupal, Sortable);