Need to see an Image Preview while creating an image

Things to do:

  • Get preview functionality working (w/o SESSION variable)
  • Style the "image preview" link
  • Add original image to preview page
  • Create a template for the preview page
  • Add unit tests for new methods

Comments

VinayLondhe created an issue. See original summary.

VinayLondhe’s picture

VinayLondhe’s picture

Status: Active » Needs work
VinayLondhe’s picture

StatusFileSize
new13.18 KB
bleen’s picture

  1. +++ b/focal_point.routing.yml
    @@ -0,0 +1,6 @@
    +    _permission: 'access content'
    

    prob should be "edit content" or at least "access admin pages". I don't remember the real perm names but we should restrict public access.

  2. +++ b/src/Controller/FocalPointController.php
    @@ -0,0 +1,132 @@
    +  public function showImageStylePreview($fid, $focal_point, $show_original = TRUE) {
    

    missing docblock

  3. +++ b/src/Controller/FocalPointController.php
    @@ -0,0 +1,132 @@
    +  function focal_point_image_effect_info() {
    +    $effects = array(
    +        'focal_point_scale_and_crop' => array(
    +            'label' => t('Focal Point Scale And Crop'),
    +            'help' => t('Scale and crop based on data provided by <em>Focal Point</em>.'),
    +            'effect callback' => 'focal_point_scale_and_crop_effect',
    +            'dimensions callback' => 'image_resize_dimensions',
    +            'form callback' => 'focal_point_crop_form',
    +            'summary theme' => 'focal_point_image_resize_summary',
    +        ),
    +        'focal_point_crop' => array(
    +            'label' => t('Focal Point Crop'),
    +            'help' => t('Crop based on data provided by <em>Focal Point</em>.'),
    +            'effect callback' => 'focal_point_crop_effect',
    +            'dimensions callback' => 'image_resize_dimensions',
    +            'form callback' => 'focal_point_crop_form',
    +            'summary theme' => 'focal_point_image_crop_summary',
    +        ),
    +    );
    +
    +    return $effects;
    +  }
    

    - Missing docblock
    - camelCase method name
    - this needs to be replaced with a method that dynamically checks the effects defined in src/FocalPointEffectBase.php rather than hard coding here.

  4. +++ b/src/Plugin/Field/FieldWidget/FocalPointImageWidget.php
    @@ -36,45 +37,55 @@ class FocalPointImageWidget extends ImageWidget {
    +        '#element_validate' => array('Drupal\focal_point\Plugin\Field\FieldWidget\FocalPointImageWidget::validateFocalPoint'),
    

    you removed the initial "\" .... was that intentional?

  5. +++ b/src/Plugin/Field/FieldWidget/FocalPointImageWidget.php
    @@ -36,45 +37,55 @@ class FocalPointImageWidget extends ImageWidget {
    +            'class' => array('focal-point', 'focal-point-' . $element['#field_name'] . '-' . $element['#delta']),
    +            'data-delta' => $element['#delta'],
    +            'data-field-name' => $element['#field_name'],
    ...
    +            'library' => array('focal_point/drupal.focal_point'),
    

    nit: white space

  6. +++ b/src/Plugin/ImageEffect/FocalPointCropImageEffect.php
    @@ -28,7 +28,13 @@ class FocalPointCropImageEffect extends FocalPointEffectBase {
    +    $real_uri = $_SERVER['HTTP_REFERER'];
    
    +++ b/src/Plugin/ImageEffect/FocalPointScaleAndCropImageEffect.php
    @@ -30,15 +30,21 @@ class FocalPointScaleAndCropImageEffect extends FocalPointEffectBase {
    +    $real_uri = $_SERVER['HTTP_REFERER'];
    

    AHHHHHHHHH!!!! ... Need to find a better way ;) Using $_SERVER['HTTP_REFERER'] is bad

jfrederick’s picture

StatusFileSize
new14.29 KB

There was an improvement to this patch in #2615332: Changing the focal point indicator does not change the focal point image in the Image Preview, so I am moving that improved patch over here to keep the related work in one place. It incorporates all the work from #4 above, and improves upon that.

jfrederick’s picture

StatusFileSize
new14.32 KB

A slight improvement to the above patch.

- 'focal_point' => isset($item['focal_point']) ? $item['focal_point'] : FocalPoint::DEFAULT_VALUE));
+ 'focal_point' => (isset($item['focal_point']) && !empty($item['focal_point'])) ? $item['focal_point'] : FocalPoint::DEFAULT_VALUE));

FocalPointImageWidget::value() is called early in form processing, and it calls getFocalPoint(). getFocalPoint() might set $this->focalPoint to an empty string.

Later in form processing, FocalPointImageWidget::process() checks if $this->focalPoint is null, but we also need to check for an empty string to account for the work above in FocalPointImageWidget::value().

This also helps out if $this->focal_point was an empty string at the beginning of FocalPointImageWidget::value(), in which case the code in that method does not run, and the value remains an empty string.

bleen’s picture

Title: Can't see Image Preview while creating an image » Add image preview functionality
StatusFileSize
new12.75 KB

This patch goes in a slightly different direction. It creates the image preview by adding a query parameter to the image style URL. There is still work to do:

  • This breaks unit tests
  • There should be a template for the preview page
  • Add the original image to the preview page
  • Style the "image preview" link
ericduran’s picture

+++ b/src/FocalPointEffectBase.php

@@ -190,9 +196,20 @@ abstract class FocalPointEffectBase extends ResizeImageEffect implements Contain
+    $preview_value = \Drupal::request()->query->get('focal_point_preview_value'); // @todo: unit tests break because of this.

if you move this to $this->getRequest()

then in your unitTest you can easily replace the getRequest with any fake value to test the test.

In the real class you can have return \Drupal::request()->query->get(...)

ericduran’s picture

If you want to be real fancy move `\Drupal::request()` to be DI in the constructor.

bleen’s picture

StatusFileSize
new14.29 KB
new2.86 KB

This patch fixes the existing unit tests

I went with a test class...

bleen’s picture

Status: Needs work » Needs review
StatusFileSize
new3.42 KB
new16.16 KB

This patch styles the image preview link more betterer ...

Still todo:

  • Add original image to preview page
  • Create a template for the preview page
  • Add unit tests for new methods
  • Go through "@todo"s in code
bleen’s picture

Issue summary: View changes
bleen’s picture

bleen’s picture

Issue summary: View changes
StatusFileSize
new90.1 KB
new2.82 MB
new7.85 KB
new22.34 KB

This patch adds the original image to the preview page and styles it to be *much* more usable...

bleen’s picture

StatusFileSize
new22.39 KB
new2.81 KB

A few white space fixes and implemented the string translation trait instead of using the t() function

bleen’s picture

Issue summary: View changes
StatusFileSize
new24.85 KB
new3.8 KB

fixing/adding some unit tests

bleen’s picture

Issue summary: View changes
StatusFileSize
new25.32 KB

Ok ... I think this is good to go. The only changes in this patch were to a couple of comments.

Anyone want to review?

bleen’s picture

StatusFileSize
new27.03 KB
new2.24 KB

This throws an exception if the fid passed into the URL on the preview page is not an image file

bleen’s picture

StatusFileSize
new26.47 KB
new543 bytes

I managed to break the preview link ... this fixes it

bleen’s picture

StatusFileSize
new27.3 KB

Chasing HEAD

bleen’s picture

StatusFileSize
new27.21 KB
new406 bytes

According to #2758495: Remove @file tag docblock there are some docblocks that should not be added ... adjusting this appropriately

bleen’s picture

StatusFileSize
new28.5 KB
new3.02 KB

Making the preview link configurable. To display, or not to display; that is the question...

slashrsm’s picture

Looks great. It seems to me that the preview page is something we could potentially show in a dialog. Maybe a follow-up?

Few things that I noticed while reading through the patch:

  1. +++ b/config/install/focal_point.preview.yml
    @@ -0,0 +1 @@
    +display_link: true
    

    I don't see any reason for this configuration not to live in focal_point.settings.yml

  2. +++ b/focal_point.routing.yml
    @@ -0,0 +1,7 @@
    +    _permission: 'access content'
    

    I am not sure of this is the best permission to use. Could we check if the current user is the author of the file or has access to edit any of the entities that use this file?

  3. +++ b/src/Controller/FocalPointPreviewController.php
    @@ -0,0 +1,128 @@
    +    // Since we are about to create a new preview of this image, we first must
    +    // flush the old one. This should not be a performance hit since there is
    +    // no good reason for anyone to preview an image unless they are changing
    +    // the focal point value.
    +    image_path_flush($image->getSource());
    

    Since the route uses "access content" permission this could allow for DDoS attacks. Another reason to figure out better access control.

  4. +++ b/src/FocalPointEffectBase.php
    @@ -191,18 +204,26 @@ abstract class FocalPointEffectBase extends ResizeImageEffect implements Contain
        * @return array
        *   Array with two keys (x, y) and anchor coordinates as values.
        */
    -  protected function calculateAnchor(ImageInterface $image, CropInterface $crop) {
    -    // @todo Create a focalPointCrop class and override the "anchor" method.
     
    +  protected function calculateAnchor(ImageInterface $image, CropInterface $crop) {
    

    Extra newline between comment and the function implementation.

  5. +++ b/src/FocalPointEffectBase.php
    @@ -241,4 +262,15 @@ abstract class FocalPointEffectBase extends ResizeImageEffect implements Contain
    +    return \Drupal::request()->query->get('focal_point_preview_value');
    

    Could we inject this?

  6. +++ b/src/Plugin/Field/FieldWidget/FocalPointImageWidget.php
    @@ -34,21 +35,50 @@ class FocalPointImageWidget extends ImageWidget {
    +      $display_preview_link = \Drupal::config('focal_point.preview')->get('display_link');
    

    Inject?

bleen’s picture

StatusFileSize
new30.83 KB
new2.61 KB

Some good points in #24.. thanks!!

This fixes the permission issue (and the whitespace nit). I will inject the drupal services shortly.

Modal window is definitely on the table, but as a follow-up.

As for the separate config file, I prefer it separated and there doesn't seem to be a well-defined rule-of-thumb on that one :)

Thanks for the review!!

slashrsm’s picture

Great!

As for the separate config file, I prefer it separated and there doesn't seem to be a well-defined rule-of-thumb on that one :)

Sure. I didn't find a rule like that either. It comes down to personal preference. :)

realityloop’s picture

Status: Needs review » Needs work
The following updates are pending:

focal_point module : 
  8003 -   Install preview config. 

Do you wish to run all pending updates? (y/n): y
Can not save immutable configuration focal_point.settings. Use \Drupal\Core\Config\ConfigFactoryInterface::getEditable() to         [error]
retrieve a mutable configuration object
Performing focal_point_update_8003                                                                                                     [ok]
Failed: Can not save immutable configuration focal_point.settings. Use \Drupal\Core\Config\ConfigFactoryInterface::getEditable()    [error]
to retrieve a mutable configuration object
Cache rebuild complete.                                                                                                                [ok]
Strict warning: Drupal\Core\Controller\ControllerBase and Drupal\Core\StringTranslation\StringTranslationTrait define the same      [error]
property ($stringTranslation) in the composition of Drupal\focal_point\Controller\FocalPointPreviewController. This might be
incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed in include()
(line 168 of /var/beetbox/modules/contrib/focal_point/src/Controller/FocalPointPreviewController.php).
include(&#039;/var/beetbox/modules/contrib/focal_point/src/Controller/FocalPointPreviewController.php&#039;) (Line: 412)
Composer\Autoload\includeFile(&#039;/var/beetbox/docroot/profiles/zesty/modules/contrib/focal_point/src/Controller/FocalPointPreviewController.php&#039;)
(Line: 301)
Composer\Autoload\ClassLoader-&gt;loadClass(&#039;Drupal\focal_point\Controller\FocalPointPreviewController&#039;)
spl_autoload_call(&#039;Drupal\focal_point\Controller\FocalPointPreviewController&#039;)
ReflectionMethod-&gt;__construct(&#039;\Drupal\focal_point\Controller\FocalPointPreviewController&#039;, &#039;content&#039;)
(Line: 123)
Drupal\Core\Entity\EntityResolverManager-&gt;setParametersFromReflection(Array, Object) (Line: 205)
Drupal\Core\Entity\EntityResolverManager-&gt;setRouteOptions(Object) (Line: 48)
Drupal\Core\EventSubscriber\EntityRouteAlterSubscriber-&gt;onRoutingRouteAlterSetType(Object, &#039;routing.route_alter&#039;,
Object) (Line: 111)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher-&gt;dispatch(&#039;routing.route_alter&#039;, Object) (Line: 184)
Drupal\Core\Routing\RouteBuilder-&gt;rebuild() (Line: 83)
Drupal\Core\ProxyClass\Routing\RouteBuilder-&gt;rebuild() (Line: 1141)
drupal_flush_all_caches() (Line: 51)
drupal_rebuild(Object, Object) (Line: 291)
drush_cache_rebuild()
call_user_func_array(&#039;drush_cache_rebuild&#039;, Array) (Line: 366)
_drush_invoke_hooks(Array, Array) (Line: 217)
drush_command()
call_user_func_array(&#039;drush_command&#039;, Array) (Line: 185)
drush_dispatch(Array) (Line: 67)
Drush\Boot\BaseBoot-&gt;bootstrap_and_dispatch() (Line: 66)
drush_main() (Line: 12)

Finished performing updates.                                                                                                           [ok]

realityloop’s picture

On clean install:

Strict warning: Drupal\Core\Controller\ControllerBase and Drupal\Core\StringTranslation\StringTranslationTrait define the same property ($stringTranslation) in the composition of Drupal\focal_point\Controller\FocalPointPreviewController. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed in include() (line 168 of /var/beetbox/modules/contrib/focal_point/src/Controller/FocalPointPreviewController.php).

include('/var/beetbox/modules/contrib/focal_point/src/Controller/FocalPointPreviewController.php') (Line: 412)
Composer\Autoload\includeFile('/var/beetbox/docroot/profiles/zesty/modules/contrib/focal_point/src/Controller/FocalPointPreviewController.php') (Line: 301)
Composer\Autoload\ClassLoader->loadClass('Drupal\focal_point\Controller\FocalPointPreviewController')
spl_autoload_call('Drupal\focal_point\Controller\FocalPointPreviewController')
ReflectionMethod->__construct('\Drupal\focal_point\Controller\FocalPointPreviewController', 'content') (Line: 123)
Drupal\Core\Entity\EntityResolverManager->setParametersFromReflection(Array, Object) (Line: 205)
Drupal\Core\Entity\EntityResolverManager->setRouteOptions(Object) (Line: 48)
Drupal\Core\EventSubscriber\EntityRouteAlterSubscriber->onRoutingRouteAlterSetType(Object, 'routing.route_alter', Object) (Line: 111)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('routing.route_alter', Object) (Line: 184)
Drupal\Core\Routing\RouteBuilder->rebuild() (Line: 83)
Drupal\Core\ProxyClass\Routing\RouteBuilder->rebuild() (Line: 302)
Drupal\Core\Extension\ModuleInstaller->install(Array, 1) (Line: 83)
Drupal\Core\ProxyClass\Extension\ModuleInstaller->install(Array) (Line: 171)
Drupal\system\Form\ModulesListConfirmForm->submitForm(Array, Object)
call_user_func_array(Array, Array) (Line: 111)
Drupal\Core\Form\FormSubmitter->executeSubmitHandlers(Array, Object) (Line: 51)
Drupal\Core\Form\FormSubmitter->doSubmitForm(Array, Object) (Line: 583)
Drupal\Core\Form\FormBuilder->processForm('system_modules_confirm_form', Array, Object) (Line: 314)
Drupal\Core\Form\FormBuilder->buildForm(Object, Object) (Line: 74)
Drupal\Core\Controller\FormController->getContentResult(Object, Object)
call_user_func_array(Array, Array) (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 574)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 124)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
call_user_func_array(Object, Array) (Line: 139)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 62)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 628)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)
bleen’s picture

Status: Needs work » Needs review
StatusFileSize
new34.21 KB
new11.42 KB

This patch does the following:

  1. Adds some dependency injection based on #24.5
  2. DOES NOT: inject anything based on #24.6 ... I'm not sure how to do that in a static method where I cannot access $this. Happy to have someone take a swing at it... otherwise it can be a followup.
  3. Fixes the update in 8003 (#27)
  4. Fixes the clean install warning (#28)
  5. Adds a warning when someone visits the preview page but hasnt defined any image styles with a focal point effect
bleen’s picture

The patch in #29 also handles permissions better as per #24.3 by adding a custom access function here: \Drupal\focal_point\Controller\FocalPointPreviewController::access. Not sure why it's not in the interdiff, but it goes something like this:


/**
   * Deny users access to the preview page unless they have permission to edit
   * an entity (any entity) that references the current image being previewed.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The current user.
   * @param $fid
   *   The file id for the image being previewed from the URL.
   *
   * @return \Drupal\Core\Access\AccessResult
   */
  public function access(AccountInterface $account, $fid) {
    $access = AccessResult::forbidden();

    // @todo: I should be able to use "magic args" to load the file directly.
    $file = File::load($fid);
    $image = \Drupal::service('image.factory')->get($file->getFileUri());
   if (!$image->isValid()) {
      throw new InvalidArgumentException('The file with id = $fid is not an image.');
    }

    if (function_exists('file_get_file_references')) {
      $references = file_get_file_references($file, NULL, EntityStorageInterface::FIELD_LOAD_REVISION, '');
      foreach ($references as $field_name => $data) {
        foreach (array_keys($data) as $entity_type_id) {
          if ($account->hasPermission($entity_type_id . ".edit")) {
            $access = AccessResult::allowed();
            break;
          }
        }
      }

    }

    return $access;
  }

I thin its time to commit this thing ... any final thoughts?

  • bleen committed c329a0e on 8.x-1.x
    Issue #2615164 by bleen, VinayLondhe, jfrederick, slashrsm: Add image...
bleen’s picture

Committed... Wooooot!!!

bleen’s picture

Status: Needs review » Fixed

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.