vvjh-1.0.4/vvjh.module

vvjh.module
<?php

/**
 * @file
 * Provides the module implementation for vvjh.
 *
 * Contains template preprocessing and theme definitions for Views.
 *
 * Filename:     vvjh.module
 * Website:      https://www.flashwebcenter.com
 * Description:  template.
 * Developer:    Alaa Haddad https://www.alaahaddad.com.
 */

declare(strict_types=1);

use Drupal\Component\Utility\Html;
use Drupal\Core\Render\Markup;
use Drupal\views\ViewExecutable;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Template\Attribute;
use Drupal\vvjh\Plugin\views\style\ViewsVanillaJavascriptHero;

/**
 * Implements hook_help().
 */
function vvjh_help(string $route_name, RouteMatchInterface $route_match): ?string {
  if ($route_name === 'help.page.vvjh') {
    return _vvjh_helper_render_readme();
  }
  return NULL;
}

/**
 * Helper function to render README.md.
 *
 * @return string
 *   The rendered content of README.md.
 */
function _vvjh_helper_render_readme(): string {
  $readme_path = __DIR__ . '/README.md';
  $text = file_get_contents($readme_path);

  if ($text === FALSE) {
    return (string) t('README.md file not found.');
  }

  if (!\Drupal::moduleHandler()->moduleExists('markdown')) {
    return '<pre>' . htmlspecialchars($text) . '</pre>';
  }

  $filter_manager = \Drupal::service('plugin.manager.filter');
  $settings = \Drupal::config('markdown.settings')->getRawData();
  $filter = $filter_manager->createInstance('markdown', ['settings' => $settings]);
  return $filter->process($text, 'en')->getProcessedText();
}

/**
 * Implements hook_theme().
 */
function vvjh_theme(array $existing, string $type, string $theme, string $path): array {
  return [
    'views_view_vvjh_fields' => [
      'variables' => [
        'view' => NULL,
        'options' => [],
        'row' => NULL,
        'field_alias' => NULL,
        'attributes' => [],
        'title_attributes' => [],
        'content_attributes' => [],
        'title_prefix' => [],
        'title_suffix' => [],
        'fields' => [],
      ],
      'template' => 'views-view-vvjh-fields',
      'path' => $path . '/templates',
    ],
    'views_view_vvjh' => [
      'variables' => [
        'view' => NULL,
        'rows' => [],
        'options' => [],
      ],
      'template' => 'views-view-vvjh',
      'path' => $path . '/templates',
    ],
  ];
}

/**
 * Implements hook_preprocess_HOOK() for views_view_vvjh.
 */
function template_preprocess_views_view_vvjh(array &$variables): void {
  static $views_theme_loaded = FALSE;
  if (!$views_theme_loaded) {
    \Drupal::moduleHandler()->loadInclude('views', 'inc', 'views.theme');
    $views_theme_loaded = TRUE;
  }

  /** @var \Drupal\vvjh\Plugin\views\style\ViewsVanillaJavascriptHero $handler */
  $handler = $variables['view']->style_plugin;

  $list_attributes = [];

  if (!empty($handler->options['overlay_position'])) {
    $list_attributes['data-overlay-position'] = $handler->options['overlay_position'];
  }

  if (!empty($handler->options['hero_style'])) {
    $list_attributes['data-hero-style'] = $handler->options['hero_style'];
  }

  if (!empty($handler->options['hero_speed'])) {
    $list_attributes['data-hero-speed'] = $handler->options['hero_speed'];
  }

  if (!empty($handler->options['animation_easing'])) {
    $list_attributes['data-animation-easing'] = $handler->options['animation_easing'];
  }

  if (!empty($handler->options['unique_id'])) {
    $list_attributes['data-unique-id'] = $handler->options['unique_id'];
  }

  if (!empty($handler->options['available_breakpoints'])) {
    $list_attributes['data-available-breakpoints'] = $handler->options['available_breakpoints'];
  }

  if (isset($handler->options['enable_css'])) {
    $list_attributes['data-enable-css'] = $handler->options['enable_css'] ? 'true' : 'false';
  }

  if (!empty($handler->options['min_height'])) {
    $list_attributes['data-min-height'] = $handler->options['min_height'];
  }

  if (!empty($handler->options['max_content_width'])) {
    $list_attributes['data-max-content-width'] = $handler->options['max_content_width'];
  }

  if (!empty($handler->options['max_width'])) {
    $list_attributes['data-max-width'] = $handler->options['max_width'];
  }

  if (!empty($handler->options['hero_item_width'])) {
    $list_attributes['data-hero-item-width'] = $handler->options['hero_item_width'];
  }

  if (!empty($handler->options['overlay_bg_color'])) {
    $rgb = _vvjh_hex_to_rgb($handler->options['overlay_bg_color']);
    $opacity = $handler->options['overlay_bg_opacity'] ?? 1;
    $background_rgb = "rgba({$rgb['r']}, {$rgb['g']}, {$rgb['b']}, $opacity)";
    $variables['background_rgb'] = $background_rgb;
  }
  else {
    $variables['background_rgb'] = NULL;
  }

  if (!empty($handler->options['min_height']['value']) && !empty($handler->options['min_height']['unit'])) {
    $unit = $handler->options['min_height']['unit'];
    $section_height = $handler->options['min_height']['value'] . $unit;
    $variables['min_height'] = $section_height;
  }
  else {
    $variables['min_height'] = '40vw';
  }

  $variables['list_attributes'] = new Attribute($list_attributes);

  $variables['options'] = $handler->options;

  $variables['settings'] = [
    'view_id' => $variables['view']->dom_id,
    'overlay_position' => $handler->options['overlay_position'],
    'hero_style' => $handler->options['hero_style'],
    'hero_speed' => $handler->options['hero_speed'],
    'animation_easing' => $handler->options['animation_easing'],
    'unique_id' => $handler->options['unique_id'],
    'available_breakpoints' => $handler->options['available_breakpoints'],
    'enable_css' => $handler->options['enable_css'],
    'min_height' => $handler->options['min_height'],
    'max_content_width' => $handler->options['max_content_width'],
    'max_width' => $handler->options['max_width'],
    'hero_item_width' => $handler->options['hero_item_width'],
  ];

  if (!empty($variables['rows'])) {
    foreach ($variables['rows'] as $key => $row) {
      if (isset($row['#theme']) && is_array($row['#theme'])) {
        foreach ($row['#theme'] as $idx => $theme_hook_suggestion) {
          $variables['rows'][$key]['#theme'][$idx] = str_replace('views_view_fields', 'views_view_vvjh_fields', $theme_hook_suggestion);
        }
      }
    }
  }

  template_preprocess_views_view_unformatted($variables);
}

/**
 * Prepares variables for views_view_vvjh_fields template.
 *
 * @param array $variables
 *   An associative array containing:
 *   - view: The view object.
 *   - options: Configuration options.
 *   - row: The result row object.
 *   - fields: An array of field render arrays.
 */
function template_preprocess_views_view_vvjh_fields(array &$variables): void {
  static $views_theme_loaded = FALSE;
  if (!$views_theme_loaded) {
    \Drupal::moduleHandler()->loadInclude('views', 'inc', 'views.theme');
    $views_theme_loaded = TRUE;
  }

  template_preprocess_views_view_fields($variables);
}

/**
 * Implements hook_preprocess_views_view().
 */
function vvjh_preprocess_views_view(array &$variables): void {
  if ($variables['view']->style_plugin instanceof ViewsVanillaJavascriptHero) {
    $variables['attributes']['class'][] = 'vvj-hero';
  }
}

/**
 * Helper function to convert hex color to RGB.
 *
 * @param string $hex
 *   The hex color code.
 *
 * @return array
 *   An associative array with 'r', 'g', 'b' values.
 */
function _vvjh_hex_to_rgb(string $hex): array {
  $hex = ltrim($hex, '#');

  if (strlen($hex) === 3) {
    $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
  }

  return [
    'r' => hexdec(substr($hex, 0, 2)),
    'g' => hexdec(substr($hex, 2, 2)),
    'b' => hexdec(substr($hex, 4, 2)),
  ];
}

/**
 * Implements hook_token_info().
 */
function vvjh_token_info(): array {
  return [
    'tokens' => [
      'view' => [
        'vvjh' => [
          'name' => t('VVJH field output'),
          'description' => t("Use these tokens when you enable 'Use replacement tokens from the first row' in Views text areas such as the header, footer, or empty text. Use [vvjh:field_name] for rendered output, or [vvjh:field_name:plain] to strip HTML and return plain text. These tokens pull values from the first row of the View result."),
        ],
      ],
    ],
  ];
}

/**
 * Implements hook_tokens().
 */
function vvjh_tokens(string $type, array $tokens, array $data = [], array $options = []): array {
  $replacements = [];

  if (!in_array($type, ['vvjh', 'global'])) {
    return $replacements;
  }

  if (!isset($data['view']) || !($data['view'] instanceof ViewExecutable)) {
    return $replacements;
  }

  $view = $data['view'];

  if (!($view->style_plugin instanceof ViewsVanillaJavascriptHero)) {
    return $replacements;
  }

  if (empty($view->result)) {
    return $replacements;
  }

  $first_row = $view->result[0];
  $field_handlers = $view->display_handler->getHandlers('field');

  /** @var \Drupal\Core\Render\RendererInterface $renderer */
  $renderer = \Drupal::service('renderer');

  foreach ($tokens as $token => $name) {
    if (!preg_match('/^[a-zA-Z0-9_]+(:plain)?$/', $token)) {
      \Drupal::logger('vvjh')->warning('Invalid token format: @token', ['@token' => $token]);
      continue;
    }

    $plain = FALSE;
    $field_id = $token;

    if (str_ends_with($token, ':plain')) {
      $plain = TRUE;
      $field_id = substr($token, 0, -6);
    }

    if (!isset($field_handlers[$field_id])) {
      continue;
    }

    try {
      $handler = $field_handlers[$field_id];
      $value = $plain && method_exists($handler, 'advancedRenderText')
        ? $handler->advancedRenderText($first_row)
        : $handler->advancedRender($first_row);

      if (is_array($value)) {
        $rendered = $renderer->renderPlain($value);
      }
      else {
        $rendered = (string) $value;
      }

      $replacements["[vvjh:$token]"] = $plain
        ? Html::decodeEntities(strip_tags($rendered))
        : Markup::create($rendered);
    }
    catch (\Throwable $e) {
      \Drupal::logger('vvjh')->error('Token replacement failed for @token: @message', [
        '@token' => $token,
        '@message' => $e->getMessage(),
      ]);
      $replacements["[vvjh:$token]"] = '';
    }
  }

  return $replacements;
}

/**
 * Implements hook_views_data_alter().
 */
function vvjh_views_data_alter(array &$data): void {
  $data['views_style_plugin']['views_vvjh'] = [
    'type' => 'views_style',
    'label' => t('Views Vanilla JavaScript Hero'),
    'mapping' => [
      'unique_id' => [
        'type' => 'string',
        'label' => t('Unique ID'),
        'description' => t('A unique numeric ID used to identify this view display.'),
      ],
      'hero_style' => [
        'type' => 'string',
        'label' => t('Hero Style'),
        'description' => t('The style of the hero animation (e.g., fade, zoom, slide from top, right, bottom, left).'),
      ],
      'max_width' => [
        'type' => 'numeric',
        'label' => t('Max Width Main Container'),
        'description' => t('The max width for the hero main container.'),
      ],
      'max_content_width' => [
        'type' => 'numeric',
        'label' => t('Max Width'),
        'description' => t('The max width for the hero content.'),
      ],
      'min_height' => [
        'type' => 'array',
        'label' => t('Min Height'),
        'description' => t('Define the height of the hero section.'),
      ],
      'overlay_position' => [
        'type' => 'string',
        'label' => t('Overlay Position'),
        'description' => t('The position of the overlay content (center, left, right, top, bottom).'),
      ],
      'overlay_bg_color' => [
        'type' => 'string',
        'label' => t('Overlay Background Color'),
        'description' => t('The background color for the overlay content.'),
      ],
      'overlay_bg_opacity' => [
        'type' => 'float',
        'label' => t('Overlay Background Opacity'),
        'description' => t('The opacity level for the overlay background color, ranging from 0 to 1.'),
      ],
      'hero_speed' => [
        'type' => 'numeric',
        'label' => t('Hero Animation Speed'),
        'description' => t('The speed of the hero animation (e.g., 0.9 for fast, 2 for slow).'),
      ],
      'animation_easing' => [
        'type' => 'string',
        'label' => t('Animation Easing'),
        'description' => t('The easing function applied to the hero animation (ease, linear, ease-in, ease-out, ease-in-out).'),
      ],
      'enable_css' => [
        'type' => 'boolean',
        'label' => t('Enable CSS Library'),
        'description' => t('Include the CSS library for styling the hero elements.'),
      ],
      'available_breakpoints' => [
        'type' => 'string',
        'label' => t('Responsive Breakpoints'),
        'description' => t('Defines the breakpoints at which the hero will be disabled (e.g., 576px, 768px, 992px, 1200px, 1400px).'),
      ],
      'hero_item_width' => [
        'type' => 'numeric',
        'label' => t('Hero Item Width'),
      ],
    ],
  ];
}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc