1<?php
2
3namespace Drupal\layout_builder\Controller;
4
5use Drupal\Core\Ajax\AjaxResponse;
6use Drupal\Core\Ajax\CloseDialogCommand;
7use Drupal\Core\Ajax\ReplaceCommand;
8use Drupal\layout_builder\SectionStorageInterface;
9
10/**
11 * Provides AJAX responses to rebuild the Layout Builder.
12 */
13trait LayoutRebuildTrait {
14
15  /**
16   * Rebuilds the layout.
17   *
18   * @param \Drupal\layout_builder\SectionStorageInterface $section_storage
19   *   The section storage.
20   *
21   * @return \Drupal\Core\Ajax\AjaxResponse
22   *   An AJAX response to either rebuild the layout and close the dialog, or
23   *   reload the page.
24   */
25  protected function rebuildAndClose(SectionStorageInterface $section_storage) {
26    $response = $this->rebuildLayout($section_storage);
27    $response->addCommand(new CloseDialogCommand('#drupal-off-canvas'));
28    return $response;
29  }
30
31  /**
32   * Rebuilds the layout.
33   *
34   * @param \Drupal\layout_builder\SectionStorageInterface $section_storage
35   *   The section storage.
36   *
37   * @return \Drupal\Core\Ajax\AjaxResponse
38   *   An AJAX response to either rebuild the layout and close the dialog, or
39   *   reload the page.
40   */
41  protected function rebuildLayout(SectionStorageInterface $section_storage) {
42    $response = new AjaxResponse();
43    $layout = [
44      '#type' => 'layout_builder',
45      '#section_storage' => $section_storage,
46    ];
47    $response->addCommand(new ReplaceCommand('#layout-builder', $layout));
48    return $response;
49  }
50
51}
52