View source
<?php
namespace Drupal\juicebox\Plugin\Field\FieldFormatter;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\image\Plugin\Field\FieldFormatter\ImageFormatterBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\field\FieldConfigInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Utility\LinkGeneratorInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\RendererInterface;
use Drupal\juicebox\JuiceboxFormatterInterface;
use Drupal\juicebox\JuiceboxGalleryInterface;
use Drupal\Core\Url;
class JuiceboxFieldFormatter extends ImageFormatterBase implements ContainerFactoryPluginInterface {
protected $juicebox;
protected $entityTypeManager;
protected $linkGenerator;
protected $request;
protected $renderer;
public function __construct(array $configuration, $plugin_id, array $plugin_definition, EntityTypeManagerInterface $entity_type_manager, LinkGeneratorInterface $link_generator, RequestStack $request_stack, JuiceboxFormatterInterface $juicebox, RendererInterface $renderer) {
parent::__construct($plugin_id, $plugin_definition, $configuration['field_definition'], $configuration['settings'], $configuration['label'], $configuration['view_mode'], $configuration['third_party_settings']);
$this->entityTypeManager = $entity_type_manager;
$this->linkGenerator = $link_generator;
$this->request = $request_stack
->getCurrentRequest();
$this->juicebox = $juicebox;
$this->renderer = $renderer;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('entity.manager'), $container
->get('link_generator'), $container
->get('request_stack'), $container
->get('juicebox.formatter'), $container
->get('renderer'));
}
public static function defaultSettings() {
$juicebox = \Drupal::service('juicebox.formatter');
$library = $juicebox
->getLibrary();
return [
'image_style' => !empty($library['version']) && !in_array('juicebox_multisize_image_style', $library['disallowed_conf']) ? 'juicebox_multisize' : 'juicebox_medium',
'thumb_style' => 'juicebox_square_thumb',
'caption_source' => '',
'title_source' => '',
] + $juicebox
->confBaseOptions() + parent::defaultSettings();
}
public function settingsForm(array $form, FormStateInterface $form_state) {
if ($this
->isPseudoInstance()) {
$element['instance_warning'] = [
'#prefix' => '<div class="messages messages--warning">',
'#markup' => $this
->t('<strong>WARNING:</strong> You appear to be using the Juicebox field formatter with a field instance that is not directly attached to an entity. Support for this configuration is currently experimental. Please test your final gallery output thoroughly.'),
'#suffix' => '</div>',
];
}
$text_sources = $this
->getFieldTextSources();
$element['image_style'] = [
'#type' => 'select',
'#title' => $this
->t('Main Image Style'),
'#default_value' => $this
->getSetting('image_style'),
'#description' => $this
->t('The style formatter for the main image.'),
'#options' => $this->juicebox
->confBaseStylePresets(),
'#empty_option' => $this
->t('None (original image)'),
];
$element['thumb_style'] = [
'#type' => 'select',
'#title' => $this
->t('Thumbnail Style'),
'#default_value' => $this
->getSetting('thumb_style'),
'#description' => $this
->t('The style formatter for the thumbnail.'),
'#options' => $this->juicebox
->confBaseStylePresets(FALSE),
'#empty_option' => $this
->t('None (original image)'),
];
$element['caption_source'] = [
'#type' => 'select',
'#title' => $this
->t('Caption Source'),
'#default_value' => $this
->getSetting('caption_source'),
'#description' => $this
->t('The image value that should be used for the caption.'),
'#options' => $text_sources,
'#empty_option' => $this
->t('No caption'),
];
$element['title_source'] = [
'#type' => 'select',
'#title' => $this
->t('Title Source'),
'#default_value' => $this
->getSetting('title_source'),
'#description' => $this
->t('The image value that should be used for the title.'),
'#options' => $text_sources,
'#empty_option' => $this
->t('No title'),
];
$element = $this->juicebox
->confBaseForm($element, $this
->getSettings());
return $element;
}
public function settingsSummary() {
$settings = $this
->getSettings();
$presets = $this->juicebox
->confBaseStylePresets();
$settings_display = [];
if (!empty($settings['image_style']) && isset($presets[$settings['image_style']])) {
$style = $presets[$settings['image_style']];
}
else {
$style = $this
->t('Original Image');
}
$settings_display[] = $this
->t("Image style: @style", [
'@style' => $style,
]);
if (!empty($settings['thumb_style']) && isset($presets[$settings['thumb_style']])) {
$style = $presets[$settings['thumb_style']];
}
else {
$style = $this
->t('Original Image');
}
$settings_display[] = $this
->t("Thumbnail style: @style", [
'@style' => $style,
]);
$text_sources = $this
->getFieldTextSources();
if (!empty($text_sources[$settings['caption_source']])) {
$source = $text_sources[$settings['caption_source']];
}
else {
$source = $this
->t('None');
}
$settings_display[] = $this
->t("Caption source: @source", [
'@source' => $source,
]);
if (!empty($text_sources[$settings['title_source']])) {
$source = $text_sources[$settings['title_source']];
}
else {
$source = $this
->t('None');
}
$settings_display[] = $this
->t("Title source: @source", [
'@source' => $source,
]);
$settings_display[] = $this
->t("Additional Juicebox library configuration options may also be set.");
return $settings_display;
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$element = [];
if ($items
->isEmpty()) {
return [];
}
$entity = $items
->getEntity();
$field_instance = $items
->getFieldDefinition();
$entity_type_id = $entity
->getEntityTypeId();
$entity_id = $entity
->id();
$field_name = $field_instance
->getName();
$display_name = $this->viewMode;
$add_js = TRUE;
if ($display_name == 'search_result' || $display_name == 'search_index') {
$add_js = FALSE;
}
if (!empty($entity->in_preview)) {
$this
->messenger()
->addWarning($this
->t('Juicebox galleries may not display correctly in preview mode. Any edits made to gallery data will only be visible after all changes are saved.'), FALSE);
}
$xml_route_info = [
'route_name' => 'juicebox.xml_field',
'route_parameters' => [
'entityType' => $entity_type_id,
'entityId' => $entity_id,
'fieldName' => $field_name,
'displayName' => $display_name,
],
'options' => [
'query' => $this->request->query
->all(),
],
];
try {
$gallery = $this->juicebox
->newGallery($xml_route_info['route_parameters']);
$this
->buildGallery($gallery, $items);
$contextual = $this
->buildContextualLinks($xml_route_info, $entity_type_id);
$element[0] = $this->juicebox
->buildEmbed($gallery, $this
->getSettings(), $xml_route_info, $add_js, $this
->isPseudoInstance(), $contextual);
} catch (\Exception $e) {
$message = 'Exception building Juicebox embed code for field: !message in %function (line %line of %file).';
watchdog_exception('juicebox', $e, $message);
}
return $element;
}
protected function buildGallery(JuiceboxGalleryInterface $gallery, FieldItemListInterface $items) {
$settings = $this
->getSettings();
foreach ($items as $delta => $item) {
if ($item
->isDisplayed() && !empty($item->target_id)) {
$src_data = $this->juicebox
->styleImageSrcData($item->entity, $settings['image_style'], $item->entity, $settings['thumb_style'], $settings);
if (!$src_data['juicebox_compatible'] && $settings['incompatible_file_action'] == 'skip') {
continue;
}
if (!$src_data['juicebox_compatible'] && $settings['incompatible_file_action'] == 'show_icon_and_link') {
$anchor = !empty($item->description) ? $item->description : $item->entity
->get('filename')->value;
$title = $this->linkGenerator
->generate($anchor, Url::fromUri($src_data['linkURL']));
}
else {
$title = $this
->getFieldText($item, $settings['title_source']);
}
$caption = $this
->getFieldText($item, $settings['caption_source']);
$gallery
->addImage($src_data, $title, $caption);
}
}
$this->juicebox
->runCommonBuild($gallery, $settings, $items);
}
protected function buildContextualLinks(array $xml_route_info, $entity_type_id) {
$contextual = [];
if (!$this
->isPseudoInstance()) {
$xml_query = !empty($xml_route_info['options']['query']) ? $xml_route_info['options']['query'] : [];
$contextual['juicebox_xml_field'] = [
'route_parameters' => $xml_route_info['route_parameters'] + $xml_query,
];
$bundle = $this->fieldDefinition
->getTargetBundle();
$display_entity = entity_get_display($entity_type_id, $bundle, $this->viewMode);
$contextual['juicebox_conf_field_' . $entity_type_id] = [
'route_parameters' => [
'view_mode_name' => !$display_entity
->status() || $display_entity
->isNew() ? 'default' : $this->viewMode,
],
];
$entity_types = $this->entityTypeManager
->getDefinitions();
$bundle_entity_type = $entity_types[$entity_type_id]
->getBundleEntityType();
if (!empty($bundle_entity_type)) {
$contextual['juicebox_conf_field_' . $entity_type_id]['route_parameters'][$bundle_entity_type] = $bundle;
}
}
return $contextual;
}
protected function getFieldTextSources() {
$text_source_options['filename'] = $this
->t('File - Filename (processed by fallback text format)');
$field_settings = $this
->getFieldSettings();
if ($this
->isPseudoInstance()) {
foreach ([
'alt_field',
'title_field',
'description_field',
] as $value) {
$field_settings[$value] = TRUE;
}
}
if (!empty($field_settings)) {
if (!empty($field_settings['alt_field'])) {
$text_source_options['alt'] = $this
->t('Image - Alt text (processed by fallback text format)');
}
if (!empty($field_settings['title_field'])) {
$text_source_options['title'] = $this
->t('Image - Title text (processed by fallback text format)');
}
if (!empty($field_settings['description_field'])) {
$text_source_options['description'] = $this
->t('File - Description text (processed by fallback text format)');
}
}
return $text_source_options;
}
protected function getFieldText(FieldItemInterface $item, $source) {
if ($source == 'filename' && isset($item->entity)) {
$entity = $item->entity;
$entity_properties = $item->entity
->toArray();
if (isset($entity_properties[$source])) {
$text_to_build = [
'#type' => 'processed_text',
'#text' => $item->entity
->get($source)->value,
];
return $this->renderer
->render($text_to_build);
}
}
if (isset($item->{$source}) && is_string($item->{$source})) {
$text_to_build = [
'#type' => 'processed_text',
'#text' => $item->{$source},
];
return $this->renderer
->render($text_to_build);
}
return '';
}
protected function isPseudoInstance() {
if (isset($this->fieldDefinition) && $this->fieldDefinition instanceof FieldConfigInterface && (isset($this->viewMode) && $this->viewMode != '_custom')) {
return FALSE;
}
return TRUE;
}
}