You are here

block_aria_landmark_roles.module in Block ARIA Landmark Roles 8

Add ARIA landmark roles to Drupal blocks.

File

block_aria_landmark_roles.module
View source
<?php

/**
 * @file
 * Add ARIA landmark roles to Drupal blocks.
 */
use Drupal\block\Entity\Block;
use Drupal\block_aria_landmark_roles\BlockAriaLandmarkRoles;
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function block_aria_landmark_roles_form_block_form_alter(&$form, FormStateInterface $form_state) {

  /** @var \Drupal\block\Entity\Block $block */
  $block = $form_state
    ->getFormObject()
    ->getEntity();
  $form['third_party_settings']['#tree'] = TRUE;
  $form['third_party_settings']['block_aria_landmark_roles'] = [
    '#title' => t('Block ARIA Landmark Roles settings'),
    '#type' => 'details',
    '#collapsible' => TRUE,
    '#open' => TRUE,
  ];
  $form['third_party_settings']['block_aria_landmark_roles']['role'] = [
    '#title' => t('Landmark role'),
    '#description' => t('Add an ARIA landmark role to this block.'),
    '#type' => 'select',
    '#options' => [
      '' => t('- None -'),
    ] + _block_aria_landmark_roles_get_roles(),
    '#default_value' => $block
      ->getThirdPartySetting('block_aria_landmark_roles', 'role'),
  ];
  $form['third_party_settings']['block_aria_landmark_roles']['label'] = [
    '#title' => t('Label'),
    '#description' => t('Add an ARIA label to this block.'),
    '#type' => 'textfield',
    '#default_value' => $block
      ->getThirdPartySetting('block_aria_landmark_roles', 'label'),
  ];
}

/**
 * Implements hook_preprocess_HOOK().
 */
function block_aria_landmark_roles_preprocess_block(&$variables) {
  if (!empty($variables['elements']['#id'])) {
    $block = Block::load($variables['elements']['#id']);
    if ($role = $block
      ->getThirdPartySetting('block_aria_landmark_roles', 'role')) {
      $variables['attributes']['role'] = $role;
    }
    if ($label = $block
      ->getThirdPartySetting('block_aria_landmark_roles', 'label')) {
      $variables['attributes']['aria-label'] = $label;
    }
  }
}

/**
 * Return a list ARIA roles.
 *
 * @param bool $associative
 *   (optional) Whether to return an associative array. Defaults to TRUE.
 *
 * @return array
 */
function _block_aria_landmark_roles_get_roles($associative = TRUE) {
  return $associative ? BlockAriaLandmarkRoles::getAssociative() : BlockAriaLandmarkRoles::get();
}