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
- class \Drupal\Component\Plugin\PluginBase implements DerivativeInspectionInterface, PluginInspectionInterface
- class \Drupal\Core\Plugin\PluginBase uses DependencySerializationTrait, MessengerTrait, StringTranslationTrait
- class \Drupal\Core\Field\PluginSettingsBase implements DependentPluginInterface, PluginSettingsInterface
- class \Drupal\Core\Field\WidgetBase implements WidgetInterface, ContainerFactoryPluginInterface uses AllowedTagsXssTrait
- class \Drupal\file\Plugin\Field\FieldWidget\FileWidget implements ContainerFactoryPluginInterface
- class \Drupal\image\Plugin\Field\FieldWidget\ImageWidget
- class \Drupal\focal_point\Plugin\Field\FieldWidget\FocalPointImageWidget
- class \Drupal\image\Plugin\Field\FieldWidget\ImageWidget
- class \Drupal\file\Plugin\Field\FieldWidget\FileWidget implements ContainerFactoryPluginInterface
- class \Drupal\Core\Field\WidgetBase implements WidgetInterface, ContainerFactoryPluginInterface uses AllowedTagsXssTrait
- class \Drupal\Core\Field\PluginSettingsBase implements DependentPluginInterface, PluginSettingsInterface
- class \Drupal\Core\Plugin\PluginBase uses DependencySerializationTrait, MessengerTrait, StringTranslationTrait
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\FieldWidgetView 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
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
AllowedTagsXssTrait:: |
public | function | Returns a list of tags allowed by AllowedTagsXssTrait::fieldFilterXss(). | |
AllowedTagsXssTrait:: |
public | function | Returns a human-readable list of allowed tags for display in help texts. | |
AllowedTagsXssTrait:: |
public | function | Filters an HTML string to prevent XSS vulnerabilities. | |
DependencySerializationTrait:: |
protected | property | An array of entity type IDs keyed by the property name of their storages. | |
DependencySerializationTrait:: |
protected | property | An array of service IDs keyed by property name used for serialization. | |
DependencySerializationTrait:: |
public | function | 1 | |
DependencySerializationTrait:: |
public | function | 2 | |
FileWidget:: |
public static | function |
Creates an instance of the plugin. Overrides WidgetBase:: |
|
FileWidget:: |
public | function |
Extracts field values from submitted form values. Overrides WidgetBase:: |
|
FileWidget:: |
public | function |
Reports field-level validation errors against actual form elements. Overrides WidgetBase:: |
|
FileWidget:: |
protected static | function | Retrieves the file description from a field field element. | |
FileWidget:: |
public | function |
Massages the form values into the format expected for field values. Overrides WidgetBase:: |
|
FileWidget:: |
public static | function | Form API callback: Processes a group of file_generic field elements. | |
FileWidget:: |
public static | function | Form submission handler for upload/remove button of formElement(). | |
FileWidget:: |
public static | function | Form element validation callback for upload element on file widget. Checks if user has uploaded more files than allowed. | |
FocalPointImageWidget:: |
private static | function | Create the focal point form element. | |
FocalPointImageWidget:: |
private static | function | Create the focal point form element. | |
FocalPointImageWidget:: |
private static | function | Create the preview link form element. | |
FocalPointImageWidget:: |
public static | function |
Defines the default settings for this plugin. Overrides ImageWidget:: |
|
FocalPointImageWidget:: |
public | function |
Returns the form for a single field widget. Overrides ImageWidget:: |
|
FocalPointImageWidget:: |
public static | function | Create and return a token to use for accessing the preview page. | |
FocalPointImageWidget:: |
constant | |||
FocalPointImageWidget:: |
public static | function |
Processes an image_focal_point field Widget. Overrides ImageWidget:: |
|
FocalPointImageWidget:: |
public | function |
Returns a form to configure settings for the widget. Overrides ImageWidget:: |
|
FocalPointImageWidget:: |
public | function |
Returns a short summary for the current widget settings. Overrides ImageWidget:: |
|
FocalPointImageWidget:: |
public static | function | Validation Callback; Focal Point process field. | |
FocalPointImageWidget:: |
public | function | Validation Callback; Focal Point widget setting. | |
FocalPointImageWidget:: |
public static | function | Validate a preview token. | |
FocalPointImageWidget:: |
public static | function |
Form API callback. Retrieves the value for the file_generic field element. Overrides FileWidget:: |
|
ImageWidget:: |
protected | property | The image factory service. | |
ImageWidget:: |
public | function |
Calculates dependencies for the configured plugin. Overrides PluginSettingsBase:: |
|
ImageWidget:: |
protected | function |
Overrides \Drupal\file\Plugin\Field\FieldWidget\FileWidget::formMultipleElements(). Overrides FileWidget:: |
|
ImageWidget:: |
public | function |
Informs the plugin that some configuration it depends on will be deleted. Overrides PluginSettingsBase:: |
|
ImageWidget:: |
public static | function | Validate callback for alt and title field, if the user wants them required. | |
ImageWidget:: |
public | function |
Constructs an ImageWidget object. Overrides FileWidget:: |
|
MessengerTrait:: |
protected | property | The messenger. | 29 |
MessengerTrait:: |
public | function | Gets the messenger. | 29 |
MessengerTrait:: |
public | function | Sets the messenger. | |
PluginBase:: |
protected | property | Configuration information passed into the plugin. | 1 |
PluginBase:: |
protected | property | The plugin implementation definition. | 1 |
PluginBase:: |
protected | property | The plugin_id. | |
PluginBase:: |
constant | A string which is used to separate base plugin IDs from the derivative ID. | ||
PluginBase:: |
public | function |
Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface:: |
|
PluginBase:: |
public | function |
Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface:: |
|
PluginBase:: |
public | function |
Gets the definition of the plugin implementation. Overrides PluginInspectionInterface:: |
3 |
PluginBase:: |
public | function |
Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface:: |
|
PluginBase:: |
public | function | Determines if the plugin is configurable. | |
PluginSettingsBase:: |
protected | property | Whether default settings have been merged into the current $settings. | |
PluginSettingsBase:: |
protected | property | The plugin settings injected by third party modules. | |
PluginSettingsBase:: |
public | function |
Returns the value of a setting, or its default value if absent. Overrides PluginSettingsInterface:: |
|
PluginSettingsBase:: |
public | function |
Returns the array of settings, including defaults for missing settings. Overrides PluginSettingsInterface:: |
|
PluginSettingsBase:: |
public | function |
Gets the list of third parties that store information. Overrides ThirdPartySettingsInterface:: |
|
PluginSettingsBase:: |
public | function |
Gets the value of a third-party setting. Overrides ThirdPartySettingsInterface:: |
|
PluginSettingsBase:: |
public | function |
Gets all third-party settings of a given module. Overrides ThirdPartySettingsInterface:: |
|
PluginSettingsBase:: |
protected | function | Merges default settings values into $settings. | |
PluginSettingsBase:: |
public | function |
Sets the value of a setting for the plugin. Overrides PluginSettingsInterface:: |
|
PluginSettingsBase:: |
public | function |
Sets the settings for the plugin. Overrides PluginSettingsInterface:: |
|
PluginSettingsBase:: |
public | function |
Sets the value of a third-party setting. Overrides ThirdPartySettingsInterface:: |
|
PluginSettingsBase:: |
public | function |
Unsets a third-party setting. Overrides ThirdPartySettingsInterface:: |
|
StringTranslationTrait:: |
protected | property | The string translation service. | 1 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. | |
WidgetBase:: |
protected | property | The field definition. | |
WidgetBase:: |
protected | property |
The widget settings. Overrides PluginSettingsBase:: |
|
WidgetBase:: |
public static | function | Ajax callback for the "Add another item" button. | |
WidgetBase:: |
public static | function | Submission handler for the "Add another item" button. | |
WidgetBase:: |
public static | function | After-build handler for field elements in a form. | |
WidgetBase:: |
public | function |
Assigns a field-level validation error to the right widget sub-element. Overrides WidgetInterface:: |
8 |
WidgetBase:: |
public | function |
Creates a form element for a field. Overrides WidgetBaseInterface:: |
3 |
WidgetBase:: |
protected | function | Generates the form element for a single copy of the widget. | |
WidgetBase:: |
protected | function | Returns the value of a field setting. | |
WidgetBase:: |
protected | function | Returns the array of field settings. | |
WidgetBase:: |
protected | function | Returns the filtered field description. | |
WidgetBase:: |
public static | function |
Retrieves processing information about the widget from $form_state. Overrides WidgetBaseInterface:: |
|
WidgetBase:: |
protected static | function | Returns the location of processing information within $form_state. | |
WidgetBase:: |
protected | function | Returns whether the widget handles multiple values. | |
WidgetBase:: |
public static | function |
Returns if the widget can be used for the provided field. Overrides WidgetInterface:: |
4 |
WidgetBase:: |
protected | function | Returns whether the widget used for default value form. | |
WidgetBase:: |
public static | function |
Stores processing information about the widget in $form_state. Overrides WidgetBaseInterface:: |