You are here

class FocalPointImageWidget in Focal Point 8

Plugin implementation of the 'image_focal_point' widget.

Plugin annotation


@FieldWidget(
  id = "image_focal_point",
  label = @Translation("Image (Focal Point)"),
  field_types = {
    "image"
  }
)

Hierarchy

Expanded class hierarchy of FocalPointImageWidget

2 files declare their use of FocalPointImageWidget
FocalPointFieldWidgetTest.php in tests/src/Unit/FieldWidgets/FocalPointFieldWidgetTest.php
FocalPointPreviewController.php in src/Controller/FocalPointPreviewController.php

File

src/Plugin/Field/FieldWidget/FocalPointImageWidget.php, line 23

Namespace

Drupal\focal_point\Plugin\Field\FieldWidget
View source
class FocalPointImageWidget extends ImageWidget {
  const PREVIEW_TOKEN_NAME = 'focal_point_preview';

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return [
      'progress_indicator' => 'throbber',
      'preview_image_style' => 'thumbnail',
      'preview_link' => TRUE,
      'offsets' => '50,50',
    ] + parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $form = parent::settingsForm($form, $form_state);

    // We need a preview image for this widget.
    $form['preview_image_style']['#required'] = TRUE;
    unset($form['preview_image_style']['#empty_option']);

    // @todo Implement https://www.drupal.org/node/2872960
    //   The preview image should not be generated using a focal point effect
    //   and should maintain the aspect ratio of the original image.
    $form['preview_image_style']['#description'] = t($form['preview_image_style']['#description']
      ->getUntranslatedString() . "<br/>Do not choose an image style that alters the aspect ratio of the original image nor an image style that uses a focal point effect.", $form['preview_image_style']['#description']
      ->getArguments(), $form['preview_image_style']['#description']
      ->getOptions());
    $form['preview_link'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Display preview link'),
      '#default_value' => $this
        ->getSetting('preview_link'),
      '#weight' => 30,
    ];
    $form['offsets'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Default focal point value'),
      '#default_value' => $this
        ->getSetting('offsets'),
      '#description' => $this
        ->t('Specify the default focal point of this widget in the form "leftoffset,topoffset" where offsets are in percentages. Ex: 25,75.'),
      '#size' => 7,
      '#maxlength' => 7,
      '#element_validate' => [
        [
          $this,
          'validateFocalPointWidget',
        ],
      ],
      '#required' => TRUE,
      '#weight' => 35,
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = parent::settingsSummary();
    $status = $this
      ->getSetting('preview_link') ? $this
      ->t('Yes') : $this
      ->t('No');
    $summary[] = $this
      ->t('Preview link: @status', [
      '@status' => $status,
    ]);
    $offsets = $this
      ->getSetting('offsets');
    $summary[] = $this
      ->t('Default focal point: @offsets', [
      '@offsets' => $offsets,
    ]);
    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element = parent::formElement($items, $delta, $element, $form, $form_state);
    $element['#focal_point'] = [
      'preview_link' => $this
        ->getSetting('preview_link'),
      'offsets' => $this
        ->getSetting('offsets'),
    ];
    return $element;
  }

  /**
   * {@inheritdoc}
   *
   * Processes an image_focal_point field Widget.
   *
   * Expands the image_focal_point Widget to include the focal_point field.
   * This method is assigned as a #process callback in formElement() method.
   *
   * @todo Implement https://www.drupal.org/node/2657592
   *   Convert focal point selector tool into a standalone form element.
   * @todo Implement https://www.drupal.org/node/2848511
   *   Focal Point offsets not accessible by keyboard.
   */
  public static function process($element, FormStateInterface $form_state, $form) {
    $element = parent::process($element, $form_state, $form);
    $item = $element['#value'];
    $item['fids'] = $element['fids']['#value'];
    $element_selectors = [
      'focal_point' => 'focal-point-' . implode('-', $element['#parents']),
    ];
    $default_focal_point_value = isset($item['focal_point']) ? $item['focal_point'] : $element['#focal_point']['offsets'];

    // Override the default Image Widget template when using the Media Library
    // module so we can use the image field's preview rather than the preview
    // provided by Media Library.
    if ($form['#form_id'] == 'media_library_upload_form' || $form['#form_id'] == 'media_library_add_form') {
      $element['#theme'] = 'focal_point_media_library_image_widget';
      unset($form['media'][0]['preview']);
    }

    // Add the focal point indicator to preview.
    if (isset($element['preview'])) {
      $preview = [
        'indicator' => self::createFocalPointIndicator($element['#delta'], $element_selectors),
        'thumbnail' => $element['preview'],
      ];

      // Even for image fields with a cardinality higher than 1 the correct fid
      // can always be found in $item['fids'][0].
      $fid = isset($item['fids'][0]) ? $item['fids'][0] : '';
      if ($element['#focal_point']['preview_link'] && !empty($fid)) {
        $preview['preview_link'] = self::createPreviewLink($fid, $element['#field_name'], $element_selectors, $default_focal_point_value);
      }

      // Use the existing preview weight value so that the focal point indicator
      // and thumbnail appear in the correct order.
      $preview['#weight'] = isset($element['preview']['#weight']) ? $element['preview']['#weight'] : 0;
      unset($preview['thumbnail']['#weight']);
      $element['preview'] = $preview;
    }

    // Add the focal point field.
    $element['focal_point'] = self::createFocalPointField($element['#field_name'], $element_selectors, $default_focal_point_value);
    return $element;
  }

  /**
   * {@inheritdoc}
   *
   * Form API callback. Retrieves the value for the file_generic field element.
   *
   * This method is assigned as a #value_callback in formElement() method.
   */
  public static function value($element, $input, FormStateInterface $form_state) {
    $return = parent::value($element, $input, $form_state);

    // When an element is loaded, focal_point needs to be set. During a form
    // submission the value will already be there.
    if (isset($return['target_id']) && !isset($return['focal_point'])) {

      /** @var \Drupal\file\FileInterface $file */
      $file = \Drupal::service('entity_type.manager')
        ->getStorage('file')
        ->load($return['target_id']);
      if ($file) {
        $crop_type = \Drupal::config('focal_point.settings')
          ->get('crop_type');
        $crop = Crop::findCrop($file
          ->getFileUri(), $crop_type);
        if ($crop) {
          $anchor = \Drupal::service('focal_point.manager')
            ->absoluteToRelative($crop->x->value, $crop->y->value, $return['width'], $return['height']);
          $return['focal_point'] = "{$anchor['x']},{$anchor['y']}";
        }
      }
      else {
        \Drupal::logger('focal_point')
          ->notice("Attempted to get a focal point value for an invalid or temporary file.");
        $return['focal_point'] = $element['#focal_point']['offsets'];
      }
    }
    return $return;
  }

  /**
   * {@inheritdoc}
   *
   * Validation Callback; Focal Point process field.
   */
  public static function validateFocalPoint($element, FormStateInterface $form_state) {
    if (empty($element['#value']) || FALSE === \Drupal::service('focal_point.manager')
      ->validateFocalPoint($element['#value'])) {
      $replacements = [
        '@title' => strtolower($element['#title']),
      ];
      $form_state
        ->setError($element, new TranslatableMarkup('The @title field should be in the form "leftoffset,topoffset" where offsets are in percentages. Ex: 25,75.', $replacements));
    }
  }

  /**
   * {@inheritdoc}
   *
   * Validation Callback; Focal Point widget setting.
   */
  public function validateFocalPointWidget(array &$element, FormStateInterface $form_state) {
    static::validateFocalPoint($element, $form_state);
  }

  /**
   * Create and return a token to use for accessing the preview page.
   *
   * @return string
   *   A valid token.
   *
   * @codeCoverageIgnore
   */
  public static function getPreviewToken() {
    return \Drupal::csrfToken()
      ->get(self::PREVIEW_TOKEN_NAME);
  }

  /**
   * Validate a preview token.
   *
   * @param string $token
   *   A drupal generated token.
   *
   * @return bool
   *   True if the token is valid.
   *
   * @codeCoverageIgnore
   */
  public static function validatePreviewToken($token) {
    return \Drupal::csrfToken()
      ->validate($token, self::PREVIEW_TOKEN_NAME);
  }

  /**
   * Create the focal point form element.
   *
   * @param string $field_name
   *   The name of the field element for the image field.
   * @param array $element_selectors
   *   The element selectors to ultimately be used by javascript.
   * @param string $default_focal_point_value
   *   The default focal point value in the form x,y.
   *
   * @return array
   *   The preview link form element.
   */
  private static function createFocalPointField($field_name, array $element_selectors, $default_focal_point_value) {
    $field = [
      '#type' => 'textfield',
      '#title' => new TranslatableMarkup('Focal point'),
      '#description' => new TranslatableMarkup('Specify the focus of this image in the form "leftoffset,topoffset" where offsets are in percents. Ex: 25,75'),
      '#default_value' => $default_focal_point_value,
      '#element_validate' => [
        [
          static::class,
          'validateFocalPoint',
        ],
      ],
      '#attributes' => [
        'class' => [
          'focal-point',
          $element_selectors['focal_point'],
        ],
        'data-selector' => $element_selectors['focal_point'],
        'data-field-name' => $field_name,
      ],
      '#wrapper_attributes' => [
        'class' => [
          'focal-point-wrapper',
        ],
      ],
      '#attached' => [
        'library' => [
          'focal_point/drupal.focal_point',
        ],
      ],
    ];
    return $field;
  }

  /**
   * Create the focal point form element.
   *
   * @param int $delta
   *   The delta of the image field widget.
   * @param array $element_selectors
   *   The element selectors to ultimately be used by javascript.
   *
   * @return array
   *   The focal point field form element.
   */
  private static function createFocalPointIndicator($delta, array $element_selectors) {
    $indicator = [
      '#type' => 'html_tag',
      '#tag' => 'div',
      '#attributes' => [
        'class' => [
          'focal-point-indicator',
        ],
        'data-selector' => $element_selectors['focal_point'],
        'data-delta' => $delta,
      ],
    ];
    return $indicator;
  }

  /**
   * Create the preview link form element.
   *
   * @param int $fid
   *   The fid of the image file.
   * @param string $field_name
   *   The name of the field element for the image field.
   * @param array $element_selectors
   *   The element selectors to ultimately be used by javascript.
   * @param string $default_focal_point_value
   *   The default focal point value in the form x,y.
   *
   * @return array
   *   The preview link form element.
   */
  private static function createPreviewLink($fid, $field_name, array $element_selectors, $default_focal_point_value) {

    // Replace comma (,) with an x to make javascript handling easier.
    $preview_focal_point_value = str_replace(',', 'x', $default_focal_point_value);

    // Create a token to be used during an access check on the preview page.
    $token = self::getPreviewToken();
    $preview_link = [
      '#type' => 'link',
      '#title' => new TranslatableMarkup('Preview'),
      '#url' => new Url('focal_point.preview', [
        'fid' => $fid,
        'focal_point_value' => $preview_focal_point_value,
      ], [
        'query' => [
          'focal_point_token' => $token,
        ],
      ]),
      '#attached' => [
        'library' => [
          'core/drupal.dialog.ajax',
        ],
      ],
      '#attributes' => [
        'class' => [
          'focal-point-preview-link',
          'use-ajax',
        ],
        'data-selector' => $element_selectors['focal_point'],
        'data-field-name' => $field_name,
        'data-dialog-type' => 'modal',
        'target' => '_blank',
      ],
    ];
    return $preview_link;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AllowedTagsXssTrait::allowedTags public function Returns a list of tags allowed by AllowedTagsXssTrait::fieldFilterXss().
AllowedTagsXssTrait::displayAllowedTags public function Returns a human-readable list of allowed tags for display in help texts.
AllowedTagsXssTrait::fieldFilterXss public function Filters an HTML string to prevent XSS vulnerabilities.
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
FileWidget::create public static function Creates an instance of the plugin. Overrides WidgetBase::create
FileWidget::extractFormValues public function Extracts field values from submitted form values. Overrides WidgetBase::extractFormValues
FileWidget::flagErrors public function Reports field-level validation errors against actual form elements. Overrides WidgetBase::flagErrors
FileWidget::getDescriptionFromElement protected static function Retrieves the file description from a field field element.
FileWidget::massageFormValues public function Massages the form values into the format expected for field values. Overrides WidgetBase::massageFormValues
FileWidget::processMultiple public static function Form API callback: Processes a group of file_generic field elements.
FileWidget::submit public static function Form submission handler for upload/remove button of formElement().
FileWidget::validateMultipleCount public static function Form element validation callback for upload element on file widget. Checks if user has uploaded more files than allowed.
FocalPointImageWidget::createFocalPointField private static function Create the focal point form element.
FocalPointImageWidget::createFocalPointIndicator private static function Create the focal point form element.
FocalPointImageWidget::createPreviewLink private static function Create the preview link form element.
FocalPointImageWidget::defaultSettings public static function Defines the default settings for this plugin. Overrides ImageWidget::defaultSettings
FocalPointImageWidget::formElement public function Returns the form for a single field widget. Overrides ImageWidget::formElement
FocalPointImageWidget::getPreviewToken public static function Create and return a token to use for accessing the preview page.
FocalPointImageWidget::PREVIEW_TOKEN_NAME constant
FocalPointImageWidget::process public static function Processes an image_focal_point field Widget. Overrides ImageWidget::process
FocalPointImageWidget::settingsForm public function Returns a form to configure settings for the widget. Overrides ImageWidget::settingsForm
FocalPointImageWidget::settingsSummary public function Returns a short summary for the current widget settings. Overrides ImageWidget::settingsSummary
FocalPointImageWidget::validateFocalPoint public static function Validation Callback; Focal Point process field.
FocalPointImageWidget::validateFocalPointWidget public function Validation Callback; Focal Point widget setting.
FocalPointImageWidget::validatePreviewToken public static function Validate a preview token.
FocalPointImageWidget::value public static function Form API callback. Retrieves the value for the file_generic field element. Overrides FileWidget::value
ImageWidget::$imageFactory protected property The image factory service.
ImageWidget::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides PluginSettingsBase::calculateDependencies
ImageWidget::formMultipleElements protected function Overrides \Drupal\file\Plugin\Field\FieldWidget\FileWidget::formMultipleElements(). Overrides FileWidget::formMultipleElements
ImageWidget::onDependencyRemoval public function Informs the plugin that some configuration it depends on will be deleted. Overrides PluginSettingsBase::onDependencyRemoval
ImageWidget::validateRequiredFields public static function Validate callback for alt and title field, if the user wants them required.
ImageWidget::__construct public function Constructs an ImageWidget object. Overrides FileWidget::__construct
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
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.
PluginSettingsBase::$defaultSettingsMerged protected property Whether default settings have been merged into the current $settings.
PluginSettingsBase::$thirdPartySettings protected property The plugin settings injected by third party modules.
PluginSettingsBase::getSetting public function Returns the value of a setting, or its default value if absent. Overrides PluginSettingsInterface::getSetting
PluginSettingsBase::getSettings public function Returns the array of settings, including defaults for missing settings. Overrides PluginSettingsInterface::getSettings
PluginSettingsBase::getThirdPartyProviders public function Gets the list of third parties that store information. Overrides ThirdPartySettingsInterface::getThirdPartyProviders
PluginSettingsBase::getThirdPartySetting public function Gets the value of a third-party setting. Overrides ThirdPartySettingsInterface::getThirdPartySetting
PluginSettingsBase::getThirdPartySettings public function Gets all third-party settings of a given module. Overrides ThirdPartySettingsInterface::getThirdPartySettings
PluginSettingsBase::mergeDefaults protected function Merges default settings values into $settings.
PluginSettingsBase::setSetting public function Sets the value of a setting for the plugin. Overrides PluginSettingsInterface::setSetting
PluginSettingsBase::setSettings public function Sets the settings for the plugin. Overrides PluginSettingsInterface::setSettings
PluginSettingsBase::setThirdPartySetting public function Sets the value of a third-party setting. Overrides ThirdPartySettingsInterface::setThirdPartySetting
PluginSettingsBase::unsetThirdPartySetting public function Unsets a third-party setting. Overrides ThirdPartySettingsInterface::unsetThirdPartySetting
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.
WidgetBase::$fieldDefinition protected property The field definition.
WidgetBase::$settings protected property The widget settings. Overrides PluginSettingsBase::$settings
WidgetBase::addMoreAjax public static function Ajax callback for the "Add another item" button.
WidgetBase::addMoreSubmit public static function Submission handler for the "Add another item" button.
WidgetBase::afterBuild public static function After-build handler for field elements in a form.
WidgetBase::errorElement public function Assigns a field-level validation error to the right widget sub-element. Overrides WidgetInterface::errorElement 8
WidgetBase::form public function Creates a form element for a field. Overrides WidgetBaseInterface::form 3
WidgetBase::formSingleElement protected function Generates the form element for a single copy of the widget.
WidgetBase::getFieldSetting protected function Returns the value of a field setting.
WidgetBase::getFieldSettings protected function Returns the array of field settings.
WidgetBase::getFilteredDescription protected function Returns the filtered field description.
WidgetBase::getWidgetState public static function Retrieves processing information about the widget from $form_state. Overrides WidgetBaseInterface::getWidgetState
WidgetBase::getWidgetStateParents protected static function Returns the location of processing information within $form_state.
WidgetBase::handlesMultipleValues protected function Returns whether the widget handles multiple values.
WidgetBase::isApplicable public static function Returns if the widget can be used for the provided field. Overrides WidgetInterface::isApplicable 4
WidgetBase::isDefaultValueWidget protected function Returns whether the widget used for default value form.
WidgetBase::setWidgetState public static function Stores processing information about the widget in $form_state. Overrides WidgetBaseInterface::setWidgetState