annotate core/modules/layout_builder/js/layout-builder.es6.js @ 5:12f9dff5fda9 tip

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