You are here

function webform_shortcuts_preprocess_block in Webform 6.x

Same name and namespace in other branches
  1. 8.5 modules/webform_shortcuts/webform_shortcuts.module \webform_shortcuts_preprocess_block()

Implements hook_preprocess_block().

File

modules/webform_shortcuts/webform_shortcuts.module, line 32
Provides keyboard shortcuts to create and save webform elements.

Code

function webform_shortcuts_preprocess_block(&$variables) {
  if ($variables['plugin_id'] !== 'local_actions_block') {
    return;
  }
  if (\Drupal::routeMatch()
    ->getRouteName() !== 'entity.webform.edit_form') {
    return;
  }

  // Get shortcuts settings.
  $config = \Drupal::config('webform_shortcuts.settings');

  // Shortcuts.
  $shortcuts = [
    '--',
    'add_element' => t('Add element'),
    'add_page' => t('Add page'),
    'add_layout' => t('Add layout'),
    '--',
    'save_elements' => t('Save element or elements'),
    'reset_elements' => t('Reset elements'),
    '--',
    'toggle_weights' => t('Show/hide row weights'),
    '--',
  ];
  $items = [];
  $last_shortcut = '';
  foreach ($shortcuts as $name => $task) {
    if ($task === '--') {
      if ($last_shortcut !== $task) {
        $items[] = [
          '#markup' => '<hr/>',
        ];
      }
      $last_shortcut = $task;
    }
    else {
      $shortcut = $config
        ->get($name);
      if ($shortcut) {
        $t_args = [
          '@shortcut' => strtoupper($shortcut),
          '@task' => $task,
        ];
        $items[] = [
          '#markup' => t('@shortcut = @task', $t_args),
          '#suffix' => '<br/>',
        ];
        $last_shortcut = $name;
      }
    }
  }
  $variables['content']['help'] = [
    '#type' => 'webform_help',
    '#help_title' => t('Keyboard shortcuts'),
    '#help' => $items,
    '#weight' => 100,
  ];
  $variables['content']['help']['#attached']['library'][] = 'webform_shortcuts/webform_shortcuts';

  // Convert shortcuts PHP settings to camelCase JavaScript settings.
  $settings = [];
  $data = $config
    ->getRawData();
  foreach ($data as $name => $value) {
    $settings[WebformTextHelper::snakeToCamel($name)] = $value;
  }
  $variables['content']['help']['#attached']['drupalSettings']['webform']['shortcuts'] = $settings;

  // Add config to render array caching.
  $renderer = \Drupal::service('renderer');
  $renderer
    ->addCacheableDependency($variables['content']['help'], $config);
}