You are here

class GridStackLayoutDeprecated in GridStack 8

Provides a GridStack class for Layout plugins.

@todo: Remove for Drupal 8.x-3.

Hierarchy

Expanded class hierarchy of GridStackLayoutDeprecated

File

src/Layout/GridStackLayoutDeprecated.php, line 23

Namespace

Drupal\gridstack\Layout
View source
class GridStackLayoutDeprecated extends LayoutBase implements ContainerFactoryPluginInterface, LayoutInterface, PluginFormInterface {
  use GridStackLayoutTrait;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, AccountInterface $current_user, GridStackManagerInterface $manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->currentUser = $current_user;
    $this->manager = $manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('current_user'), $container
      ->get('gridstack.manager'));
  }

  /**
   * {@inheritdoc}
   */
  public function build(array $regions) {
    $config = $this
      ->getConfiguration();
    $definition = $this
      ->getPluginDefinition();
    $id = $definition['id'];
    $item_id = 'box';
    $name = $definition['optionset'];
    $optionset = GridStack::load($name);
    $grids = $optionset
      ->getEndBreakpointGrids();
    $ipe_exists = $this->manager
      ->getModuleHandler()
      ->moduleExists('panels_ipe');

    // Only check that Panels IPE is granted. Further access check is not here.
    // @see \Drupal\gridstack\GridStackManager::preRenderGridStack()
    $config['_ipe'] = FALSE;
    if ($ipe_exists && $this->currentUser
      ->hasPermission('access panels in-place editing')) {
      $config['_ipe'] = TRUE;
    }

    // Converts string to array.
    $config['extras'] = empty($config['extras']) ? [] : Json::decode($config['extras']);

    // Defines settings.
    $settings = [
      'id' => $id,
      'item_id' => $item_id,
      'namespace' => 'gridstack',
      'optionset' => $name,
    ] + $config;

    // Converts gridstack breakpoint grids from stored JSON into array.
    $optionset
      ->gridsJsonToArray($settings);
    $items = [];
    foreach ($grids as $delta => $grid) {
      $region = 'gridstack_' . $delta;
      $box = [];
      $box_settings = $settings;
      unset($box_settings['attributes'], $box_settings['wrapper'], $box_settings['wrapper_classes']);
      $box['settings'] = $box_settings;
      $nested_grids = $optionset
        ->getNestedGridsByDelta($delta);
      $is_nested = array_filter($nested_grids);
      if (!empty($is_nested)) {
        foreach ($nested_grids as $key => $nested_grid) {
          $nested_id = $delta . '_' . $key;
          $region = 'gridstack_' . $nested_id;

          // Preserves indices even if empty.
          $box[$item_id][$key][$item_id] = isset($regions[$region]) && !Element::isEmpty($regions[$region]) ? $regions[$region] : [];
        }
      }
      else {

        // Preserves indices even if empty.
        $box[$item_id] = isset($regions[$region]) && !Element::isEmpty($regions[$region]) ? $regions[$region] : [];
      }
      $items[] = $box;
      unset($box);
    }
    $build = [
      'items' => $items,
      'optionset' => $optionset,
      'settings' => $settings,
    ];
    return empty($items) ? [] : $this->manager
      ->build($build);
  }

  /**
   * Implements hook_layout_alter().
   */
  public static function layoutAlter(&$definitions) {
    $manager = \Drupal::service('gridstack.manager');
    $optionsets = $manager
      ->entityLoadMultiple('gridstack');
    $framework = $manager
      ->configLoad('framework', 'gridstack.settings');
    $path = drupal_get_path('module', 'gridstack');
    foreach ($optionsets as $key => $optionset) {
      if ($key == 'default') {
        continue;
      }
      $static = !empty($framework) && $optionset
        ->getOption('use_framework');
      $id = $optionset
        ->id();
      $layout_id = 'gridstack_' . $id;
      $regions = self::prepareRegions($optionset);
      $default = isset($regions['gridstack_0']) ? 'gridstack_0' : 'gridstack_0_0';
      $region_names = [];
      foreach ($regions as $region => $info) {
        $region_names[$region] = $info['label'];
      }

      // Defines the layout.
      $definition = [
        'label' => strip_tags($optionset
          ->label()),
        'category' => $static ? 'GridStack ' . ucwords($framework) : 'GridStack JS',
        'class' => 'Drupal\\gridstack\\Layout\\GridStackLayoutDeprecated',
        'default_region' => $default,
        'icon' => $optionset
          ->getIconUrl(),
        'id' => $layout_id,
        'optionset' => $id,
        'provider' => 'gridstack',
        'regions' => $regions,
        'region_names' => $region_names,
        'theme' => 'gridstack',
        'path' => $path,
        'template_path' => $path . '/templates',
        'library' => 'gridstack/layout',
        'config_dependencies' => [
          'config' => [
            'gridstack.optionset.' . $id,
          ],
          'module' => [
            'gridstack',
          ],
        ],
      ];
      $definitions[$layout_id] = $definition;
    }
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {

    // This form may be loaded as a subform by Field Layout, Panels, etc.
    // @see https://www.drupal.org/node/2536646
    // @see https://www.drupal.org/node/2798261
    // @see https://www.drupal.org/node/2774077
    // @todo: Remove when no more issues with it.
    if ($form_state instanceof SubformStateInterface) {
      $form_state = $form_state
        ->getCompleteFormState();
    }
    $access = $this->currentUser
      ->hasPermission('administer gridstack');
    $config = $this
      ->getConfiguration();
    $definition = $this
      ->getPluginDefinition();
    $regions = $this
      ->getRegionDefinitions();
    $name = $definition['optionset'];
    $optionset = GridStack::load($name);
    $regions_all = self::prepareRegions($optionset, FALSE);
    $extras = [];

    /** @var \Drupal\field_ui\Form\EntityViewDisplayEditForm $entity_form */
    $entity_form = $form_state
      ->getFormObject();

    /* @var \Drupal\Core\Entity\Display\EntityDisplayInterface $display */
    if (method_exists($entity_form, 'getEntity') && ($display = $entity_form
      ->getEntity())) {
      $extras = [
        'bundle' => $display
          ->getTargetBundle(),
        'entity_type' => $display
          ->getTargetEntityTypeId(),
        'view_mode' => $display
          ->getMode(),
      ];
    }
    $settings = [];
    foreach ([
      'attributes',
      'wrapper_classes',
      'skin',
      'wrapper',
    ] as $key) {
      $default = $key == 'wrapper' ? 'div' : '';
      $default = isset($config[$key]) ? $config[$key] : $default;
      $settings[$key] = $form_state
        ->getValue([
        'settings',
        $key,
      ], $default);
    }
    $prefix = '<h3>';
    if ($this->manager
      ->getModuleHandler()
      ->moduleExists('gridstack_ui') && $access) {
      $prefix .= $this
        ->t('Outer wrapper settings [<small><a href=":url">Edit @id</a></small>]', [
        ':url' => $optionset
          ->toUrl('edit-form')
          ->toString(),
        '@id' => strip_tags($optionset
          ->label()),
      ]);
    }
    else {
      $prefix .= $this
        ->t('Outer wrapper settings');
    }
    $prefix .= '</h3>';
    $form['settings'] = [
      '#type' => 'container',
      '#tree' => TRUE,
      '#weight' => 20,
      '#prefix' => $prefix,
    ];
    $form['settings']['skin'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Skin'),
      '#options' => $this->manager
        ->getSkinOptions(),
      '#empty_option' => $this
        ->t('- None -'),
      '#description' => $this
        ->t('Choose a skin to load for this layout. Check out, or clone, gridstack_example.module to register skins here. Leave empty to disable.'),
      '#default_value' => $settings['skin'],
      '#prefix' => '<div class="form-wrapper form-wrapper--inline form-wrapper--left">',
    ];
    $form['settings']['extras'] = [
      '#type' => 'hidden',
      '#value' => empty($extras) ? '' : Json::encode($extras),
    ];
    $form['settings'] += $this
      ->buildFormElements($settings);
    $closing = '</div><div class="form-wrapper form-wrapper--inline form-wrapper--icon form-wrapper--right">';
    if ($uri = $optionset
      ->getIconUri()) {
      $image = [
        '#theme' => 'image',
        '#uri' => $uri,
        '#alt' => $this
          ->t('Thumbnail'),
      ];
      $closing .= $this->manager
        ->getRenderer()
        ->render($image);
    }
    $closing .= '</div>';
    $form['settings']['attributes']['#suffix'] = $closing;
    $form['regions'] = [
      '#type' => 'container',
      '#tree' => TRUE,
      '#prefix' => '<p>' . $this
        ->t('A region has direct contents. A container contains a single, or multiple regions, grouped by their container index.') . '</p>',
    ];
    $settings = [];
    foreach ($regions_all as $region => $info) {
      foreach ([
        'attributes',
        'wrapper_classes',
        'wrapper',
      ] as $key) {
        $default = $key == 'wrapper' ? 'div' : '';
        $default = isset($config['regions'][$region][$key]) ? $config['regions'][$region][$key] : $default;
        $default = $form_state
          ->getValue([
          'regions',
          $region,
          $key,
        ], $default);
        $settings['regions'][$region][$key] = $default;
      }
      $prefix = !array_key_exists($region, $regions) ? 'Container' : 'Region';
      $form['regions'][$region] = [
        '#type' => 'details',
        '#title' => $this
          ->t('@prefix: <em>@label</em>', [
          '@prefix' => $prefix,
          '@label' => $info['label'],
        ]),
        '#open' => TRUE,
        '#tree' => TRUE,
        '#attributes' => [
          'class' => [
            'form-wrapper',
            'form-wrapper--inline',
          ],
        ],
      ];
      $form['regions'][$region] += $this
        ->buildFormElements($settings['regions'][$region]);
    }
    $form['#attached']['library'][] = 'gridstack/admin_base';
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    $dependencies = parent::calculateDependencies();
    $dependencies['module'][] = 'gridstack';
    return $dependencies;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
GridStackLayoutDeprecated::build public function Build a render array for layout with regions. Overrides LayoutBase::build
GridStackLayoutDeprecated::buildConfigurationForm public function Form constructor. Overrides LayoutBase::buildConfigurationForm
GridStackLayoutDeprecated::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides LayoutBase::calculateDependencies
GridStackLayoutDeprecated::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
GridStackLayoutDeprecated::layoutAlter public static function Implements hook_layout_alter().
GridStackLayoutDeprecated::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides PluginBase::__construct
GridStackLayoutTrait::$currentUser protected property The current user.
GridStackLayoutTrait::$manager protected property The gridstack manager service.
GridStackLayoutTrait::buildFormElements public function
GridStackLayoutTrait::defaultConfiguration public function
GridStackLayoutTrait::prepareRegions public static function Returns regions based on available grids.
GridStackLayoutTrait::submitConfigurationForm public function
GridStackLayoutTrait::validateConfigurationForm public function
LayoutBase::$configuration protected property The layout configuration. Overrides PluginBase::$configuration
LayoutBase::getBasePath public function Gets the path to resources like icon or template.
LayoutBase::getCategory public function Gets the human-readable category.
LayoutBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurablePluginInterface::getConfiguration
LayoutBase::getDescription public function Gets the optional description for advanced layouts.
LayoutBase::getIconFilename public function Gets the path to the preview image.
LayoutBase::getLabel public function Gets the human-readable name.
LayoutBase::getLibrary public function Get the asset library.
LayoutBase::getRegionDefinitions public function Gets information on regions keyed by machine name.
LayoutBase::getRegionNames public function Gets human-readable list of regions keyed by machine name.
LayoutBase::getThemeHook public function Gets the theme hook used to render this layout.
LayoutBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurablePluginInterface::setConfiguration
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.