annotate core/modules/layout_builder/js/layout-builder.es6.js @ 19:fa3358dc1485 tip

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