Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/performance optimizations #8

Merged
merged 6 commits into from
Oct 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,13 @@ To allow the images to change on resize, add this include to your head in the la
@include('statamic-glide-directive::partials.head')
```

We recommend to generate your presets by using `php please assets:generate-presets`.

To combat performance issues we recommend using redis for your queue connection, if you keep this on sync the images will be generated on the fly impacting page load.

When using redis the images will also be made on the fly, while working the jobs on the queue. If an image doesn't have a glide preset ready we will use the original image url for the first page load.


## Config

The package has some default config. By default it will use the presets defined in the config of this addon. If you've defined you're asset presets in the Statamic config, that will be used.
Expand Down
32 changes: 16 additions & 16 deletions resources/views/image.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,29 +11,29 @@ class="{{ $class }}"
@else
@isset($presets['webp'])
<source
srcset="{{ $presets['webp'] }}"
sizes="32px"
type="image/webp"
srcset="{{ $presets['webp'] }}"
sizes="32px"
type="image/webp"
>
@endisset
@isset($presets[$image->mimeType()])
<source
srcset="{{ $presets[$image->mimeType()] }}"
sizes="32px"
type="{{ $image->mimeType() }}"
srcset="{{ $presets[$image->mimeType()] }}"
sizes="32px"
type="{{ $image->mimeType() }}"
>
@endisset
<img
{!! $attributes ?? '' !!}
class="{{ $class }}"
src="{{ $presets['placeholder'] ?? $image->url() }}"
alt="{{ $alt ?? $image->alt() }}"
width="{{ $width }}"
height="{{ $height }}"
onload="
this.onload=null;
window.responsiveResizeObserver.observe(this);
"
{!! $attributes ?? '' !!}
class="{{ $class }}"
src="{{ $presets['placeholder'] ?? $image->url() }}"
alt="{{ $alt ?? $image->alt() }}"
width="{{ $width }}"
height="{{ $height }}"
onload="
this.onload=null;
window.responsiveResizeObserver.observe(this);
"
>
@endif
</picture>
Expand Down
41 changes: 41 additions & 0 deletions src/Jobs/GenerateGlideImageJob.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

namespace JustBetter\GlideDirective\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Statamic\Assets\Asset;
use Illuminate\Bus\Batchable;
use Statamic\Statamic;

class GenerateGlideImageJob implements ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use Batchable;

public function __construct(
public Asset $asset,
public string $preset = '',
public string $fit = '',
public ?string $format = null,
) {
}

public function handle(): void
{
Statamic::tag(
$this->preset === 'placeholder' ? 'glide:data_url' : 'glide'
)->params(
[
'preset' => $this->preset,
'src' => $this->asset->url(),
'format' => $this->format,
'fit' => $this->fit
]
)->fetch();
}
}
110 changes: 86 additions & 24 deletions src/Responsive.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,42 @@

namespace JustBetter\GlideDirective;

use JustBetter\GlideDirective\Jobs\GenerateGlideImageJob;
use Statamic\Contracts\Imaging\ImageManipulator;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Statamic\Facades\Glide;
use Statamic\Facades\Image;
use Statamic\Facades\URL;
use Statamic\Assets\Asset;
use Statamic\Fields\Value;
use Statamic\Support\Str;
use Statamic\Statamic;

class Responsive
{
public static function handle(mixed ...$arguments): Factory|View|string
{
$image = $arguments[0];
$image = $image instanceof Value ? $image->value() : $image;
$asset = $arguments[0];
$asset = $asset instanceof Value ? $asset->value() : $asset;
$arguments = $arguments[1] ?? [];

if (! $image || ! ($image instanceof Asset)) {
if (! $asset || ! ($asset instanceof Asset)) {
return '';
}

return view('statamic-glide-directive::image', [
'image' => $image,
'presets' => self::getPresets($image),
'image' => $asset,
'presets' => self::getPresets($asset),
'attributes' => self::getAttributeBag($arguments),
'class' => $arguments['class'] ?? '',
'alt' => $arguments['alt'] ?? '',
'width' => $arguments['width'] ?? $image->width(),
'height' => $arguments['height'] ?? $image->height(),
'width' => $arguments['width'] ?? $asset->width(),
'height' => $arguments['height'] ?? $asset->height(),
]);
}

public static function getPresets(Asset $image): array
public static function getPresets(Asset $asset): array
{
$config = config('statamic.assets.image_manipulation.presets');

Expand All @@ -46,13 +52,17 @@ public static function getPresets(Asset $image): array
}

if (self::canUseMimeTypeSource()) {
$presets[$image->mimeType()] = '';
$presets[$asset->mimeType()] = '';
}

$configPresets = self::getPresetsByRatio($image, $config);
$imageMeta = $image->meta();
$fit = isset($imageMeta['data']['focus']) ? sprintf('crop-%s', $imageMeta['data']['focus']) : null;
$configPresets = self::getPresetsByRatio($asset, $config);
$assetMeta = $asset->meta();
$fit = isset($assetMeta['data']['focus']) ? sprintf('crop-%s', $assetMeta['data']['focus']) : null;

$webpSourceFound = false;
$mimeTypeSourceFound = false;
$index = 0;

foreach ($configPresets as $preset => $data) {
$size = $data['w'].'w';

Expand All @@ -61,43 +71,95 @@ public static function getPresets(Asset $image): array
}

if (self::canUseWebpSource()) {
$glideUrl = Statamic::tag($preset === 'placeholder' ? 'glide:data_url' : 'glide')->params(['preset' => $preset, 'src' => $image->url(), 'format' => 'webp', 'fit' => $fit ?? $data['fit']])->fetch();
if ($glideUrl) {
if ($glideUrl = self::getGlideUrl($asset, $preset, $fit ?? $data['fit'], 'webp')) {
$presets['webp'] .= $glideUrl.' '.$size;

if ($preset !== 'placeholder') {
$webpSourceFound = true;
}
}
}

if (self::canUseMimeTypeSource()) {
$glideUrl = Statamic::tag($preset === 'placeholder' ? 'glide:data_url' : 'glide')->params(['preset' => $preset, 'src' => $image->url(), 'fit' => $fit ?? $data['fit']])->fetch();
if ($glideUrl) {
$presets[$image->mimeType()] .= $glideUrl.' '.$size;
if($glideUrl = self::getGlideUrl($asset, $fit ?? $data['fit'], $preset)) {
$presets[$asset->mimeType()] .= $glideUrl.' '.$size;

if ($preset !== 'placeholder') {
$mimeTypeSourceFound = true;
}
}
}

if ($preset === 'placeholder') {
$glideUrl = Statamic::tag('glide:data_url')->params(['preset' => 'placeholder', 'src' => $image->url(), 'fit' => $fit ?? $data['fit']])->fetch();
if ($glideUrl) {
if ($glideUrl = Statamic::tag('glide:data_url')->params(['preset' => 'placeholder', 'src' => $asset->url(), 'fit' => $fit ?? $data['fit']])->fetch()) {
$presets['placeholder'] = $glideUrl;
}
}

$index++;
}

if (!$webpSourceFound && !$mimeTypeSourceFound) {
$presets = ['placeholder' => $asset->url()];
}

if (! isset($presets['placeholder'])) {
$glideUrl = Statamic::tag('glide:data_url')->params(['preset' => collect($configPresets)->keys()->first(), 'src' => $image->url(), 'fit' => 'crop_focal'])->fetch();
$presets['placeholder'] = $glideUrl;
$presets['placeholder'] = Statamic::tag('glide:data_url')->params([
'preset' => collect($configPresets)->keys()->first(),
'src' => $asset->url(),
'fit' => 'crop_focal'
])->fetch();
}

return array_filter($presets);
}

protected static function getGlideUrl(Asset $asset, string $preset, string $fit, ?string $format = null): ?string
{
if ($preset === 'placeholder') {
return Statamic::tag('glide:data_url')->params([
'preset' => $preset,
'src' => $asset->url(),
'format' => $format,
'fit' => $fit
])->fetch();
}

$manipulator = self::getManipulator($asset, $preset, $fit, $format);

if (is_string($manipulator)) {
return null;
}

$params = $manipulator->getParams();

$manipulationCacheKey = 'asset::' . $asset->id() . '::' . md5(json_encode($params) ? json_encode($params) : '');

if ($cachedUrl = Glide::cacheStore()->get($manipulationCacheKey)) {
$url = Str::ensureLeft(config('statamic.assets.image_manipulation.route'), '/') . '/' . $cachedUrl;
return URL::encode($url);
}

return $presets;
GenerateGlideImageJob::dispatch($asset, $preset, $fit, $format);

return null;
}

protected static function getManipulator(Asset $item, string $preset, string $fit, ?string $format = null): ImageManipulator|string
{
$manipulator = Image::manipulate($item);

collect(['p' => $preset, 'fm' => $format, 'fit' => $fit])->each(fn ($value, $param) => $manipulator->$param($value));

return $manipulator;
}

protected static function getPresetsByRatio(Asset $image, array $config): array
protected static function getPresetsByRatio(Asset $asset, array $config): array
{
$presets = collect($config);

// filter config based on aspect ratio
$vertical = $image->height() > $image->width();
$vertical = $asset->height() > $asset->width();
$presets = $presets->filter(fn ($preset, $key) => $key === 'placeholder' || (($preset['h'] > $preset['w']) === $vertical));

return $presets->isNotEmpty() ? $presets->toArray() : $config;
Expand Down