Skip to content

Commit

Permalink
Merge branch 'release/1.2.1'
Browse files Browse the repository at this point in the history
  • Loading branch information
khalwat committed Sep 10, 2017
2 parents 1afe08f + 96e8674 commit 3282d16
Show file tree
Hide file tree
Showing 9 changed files with 378 additions and 299 deletions.
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# ImageOptimize Changelog

## 1.2.1 - 2017.09.10
### Changed
* Fixed an issue that could leave stale image variants around
* Ensure that the optimized image variants are re-created if the image is edited
* Added logging to show the savings for image variants
* Fixed the way the Settings page is rendered
* Updated `README.md`

## 1.2.0 - 2017.09.08
### Added
* Added `OptimzedImages` Field
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "nystudio107/craft3-imageoptimize",
"description": "Automatically create & optimize responsive image transforms",
"type": "craft-plugin",
"version": "1.2.0",
"version": "1.2.1",
"keywords": [
"craft",
"cms",
Expand Down
24 changes: 23 additions & 1 deletion src/ImageOptimize.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,14 @@
use craft\events\VolumeEvent;
use craft\models\FieldLayout;
use craft\services\AssetTransforms;
use craft\services\Elements;
use craft\services\Fields;
use craft\services\Volumes;
use craft\web\Controller;

use yii\base\Event;

/** @noinspection MissingPropertyAnnotationsInspection */

/**
* Class ImageOptimize
*
Expand Down Expand Up @@ -168,6 +170,26 @@ function (GenerateTransformEvent $event) {
);
}

/**
* @inheritdoc
*/
public function getSettingsResponse()
{
$view = Craft::$app->getView();
$namespace = $view->getNamespace();
$view->setNamespace('settings');
$settingsHtml = $this->settingsHtml();
$view->setNamespace($namespace);

/** @var Controller $controller */
$controller = Craft::$app->controller;

return $controller->renderTemplate('image-optimize/_settings', [
'plugin' => $this,
'settingsHtml' => $settingsHtml
]);
}

/**
* @inheritdoc
*/
Expand Down
162 changes: 83 additions & 79 deletions src/fields/OptimizedImages.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
namespace nystudio107\imageoptimize\fields;

use craft\models\AssetTransform;
use nystudio107\imageoptimize\ImageOptimize;
use nystudio107\imageoptimize\assetbundles\optimizedimagesfield\OptimizedImagesFieldAsset;
use nystudio107\imageoptimize\models\OptimizedImage;

Expand All @@ -24,6 +23,8 @@

use yii\db\Schema;

/** @noinspection MissingPropertyAnnotationsInspection */

/**
* @author nystudio107
* @package ImageOptimize
Expand Down Expand Up @@ -124,10 +125,10 @@ public function beforeElementSave(ElementInterface $element, bool $isNew): bool
*/
public function afterElementSave(ElementInterface $element, bool $isNew)
{
// If this is a new element, resave it so that it as an id for our asset transforms
if ($isNew) {
/** @var Asset $element */
if ($element instanceof Asset) {
/** @var Asset $element */
if ($element instanceof Asset) {
// If this is a new element, resave it so that it as an id for our asset transforms
if ($isNew) {
// Initialize our field with defaults
$this->currentAsset = $element;
$defaultData = $this->normalizeValue(null, $element);
Expand All @@ -138,23 +139,19 @@ public function afterElementSave(ElementInterface $element, bool $isNew)

$success = Craft::$app->getElements()->saveElement($element, false);
Craft::info(
print_r('Re-saved new asset ' . $success, true),
print_r('Re-saved new asset '.$success, true),
__METHOD__
);
} else {
// Otherwise create a dummy model, and populate it, to recreate any asset transforms
$model = new OptimizedImage();
$this->populateOptimizedImageModel($element, $model);
}
}

parent::afterElementSave($element, $isNew);
}

/**
* @inheritdoc
*/
public function getContentColumnType(): string
{
return Schema::TYPE_TEXT;
}

/**
* @inheritdoc
*/
Expand All @@ -173,6 +170,50 @@ public function normalizeValue($value, ElementInterface $element = null)
return $model;
}

/**
* @param Asset $element
* @param OptimizedImage $model
*/
protected function populateOptimizedImageModel(Asset $element, OptimizedImage $model)
{
// Empty our the optimized image URLs
$model->optimizedImageUrls = [];
$model->optimizedWebPImageUrls = [];

/** @var AssetTransform $transform */
$transform = new AssetTransform();

foreach ($this->variants as $variant) {
// Create the transform based on the variant
$aspectRatio = $variant['aspectRatioX'] / $variant['aspectRatioY'];
$width = $variant['width'];
$transform->width = $width;
$transform->height = intval($width / $aspectRatio);
$transform->quality = $variant['quality'];
$transform->format = $variant['format'];

// Force generateTransformsBeforePageLoad = true to generate the images now
$generalConfig = Craft::$app->getConfig()->getGeneral();
$oldSetting = $generalConfig->generateTransformsBeforePageLoad;
$generalConfig->generateTransformsBeforePageLoad = true;
// Generate the URLs to the optimized images
$url = $element->getUrl($transform);
$generalConfig->generateTransformsBeforePageLoad = $oldSetting;

// Update the model
$model->optimizedImageUrls[$width] = $url;
$model->optimizedWebPImageUrls[$width] = $url.'.webp';
$model->focalPoint = $element->focalPoint;
$model->originalImageWidth = $element->width;
$model->originalImageHeight = $element->height;

Craft::info(
'Created transforms for variant: '.print_r($variant, true),
__METHOD__
);
}
}

/**
* @inheritdoc
*/
Expand All @@ -181,6 +222,14 @@ public function serializeValue($value, ElementInterface $element = null)
return parent::serializeValue($value, $element);
}

/**
* @inheritdoc
*/
public function getContentColumnType(): string
{
return Schema::TYPE_TEXT;
}

/**
* @inheritdoc
*/
Expand All @@ -192,22 +241,25 @@ public function getSettingsHtml()
$namespacedId = Craft::$app->getView()->namespaceInputId($id);
$namespacePrefix = Craft::$app->getView()->namespaceInputName($thisId);
Craft::$app->getView()->registerJs('new Craft.OptimizedImagesInput('.
'"'. $namespacedId .'", '.
'"'. $namespacePrefix .'"'.
'"'.$namespacedId.'", '.
'"'.$namespacePrefix.'"'.
');');

// Render the settings template
return Craft::$app->getView()->renderTemplate(
'image-optimize/_components/fields/OptimizedImages_settings',
[
'field' => $this,
'id' => $id,
'name' => $this->handle,
'field' => $this,
'id' => $id,
'name' => $this->handle,
'namespace' => $namespacedId,
]
);
}

// Protected Methods
// =========================================================================

/**
* @inheritdoc
*/
Expand All @@ -218,77 +270,29 @@ public function getInputHtml($value, ElementInterface $element = null): string

// Get our id and namespace
$id = Craft::$app->getView()->formatInputId($this->handle);
$namespacedId = Craft::$app->getView()->namespaceInputId($id);
$nameSpaceId = Craft::$app->getView()->namespaceInputId($id);

// Variables to pass down to our field JavaScript to let it namespace properly
$jsonVars = [
'id' => $id,
'name' => $this->handle,
'namespace' => $namespacedId,
'prefix' => Craft::$app->getView()->namespaceInputId(''),
'id' => $id,
'name' => $this->handle,
'namespace' => $nameSpaceId,
'prefix' => Craft::$app->getView()->namespaceInputId(''),
];
$jsonVars = Json::encode($jsonVars);
Craft::$app->getView()->registerJs("$('#{$namespacedId}-field').ImageOptimizeOptimizedImages(" . $jsonVars . ");");
Craft::$app->getView()->registerJs("$('#{$nameSpaceId}-field').ImageOptimizeOptimizedImages(".$jsonVars.");");

// Render the input template
return Craft::$app->getView()->renderTemplate(
'image-optimize/_components/fields/OptimizedImages_input',
[
'name' => $this->handle,
'value' => $value,
'variants' => $this->variants,
'field' => $this,
'id' => $id,
'namespacedId' => $namespacedId,
'name' => $this->handle,
'value' => $value,
'variants' => $this->variants,
'field' => $this,
'id' => $id,
'nameSpaceId' => $nameSpaceId,
]
);
}

// Protected Methods
// =========================================================================

/**
* @param Asset $element
* @param OptimizedImage $model
*/
protected function populateOptimizedImageModel(Asset $element, OptimizedImage $model)
{
// Empty our the optimized image URLs
$model->optimizedImageUrls = [];
$model->optimizedWebPImageUrls = [];

/** @var AssetTransform $transform */
$transform = new AssetTransform();

foreach ($this->variants as $variant) {
// Create the transform based on the variant
$aspectRatio = $variant['aspectRatioX'] / $variant['aspectRatioY'];
$width = $variant['width'];
$transform->width = $width;
$transform->height = intval($width / $aspectRatio);
$transform->quality = $variant['quality'];
$transform->format = $variant['format'];

// Force generateTransformsBeforePageLoad = true to generate the images now
$generalConfig = Craft::$app->getConfig()->getGeneral();
$oldSetting = $generalConfig->generateTransformsBeforePageLoad;
$generalConfig->generateTransformsBeforePageLoad = true;
// Generate the URLs to the optimized images
$url = $element->getUrl($transform);
$generalConfig->generateTransformsBeforePageLoad = $oldSetting;

// Update the model
$model->optimizedImageUrls[$width] = $url;
$model->optimizedWebPImageUrls[$width] = $url . '.webp';
$model->focalPoint = $element->focalPoint;
$model->originalImageWidth = $element->width;
$model->originalImageHeight = $element->height;

Craft::info(
'Created transforms for variant: ' . print_r($variant, true),
__METHOD__
);
}
}

}
1 change: 0 additions & 1 deletion src/models/OptimizedImage.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@

use nystudio107\imageoptimize\ImageOptimize;

use Craft;
use craft\helpers\UrlHelper;
use craft\base\Model;
use craft\validators\ArrayValidator;
Expand Down
Loading

0 comments on commit 3282d16

Please sign in to comment.