optimize image blocks with responsive srcset and webp conversion

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
isUnknown 2026-03-23 22:08:04 +01:00
parent 31f1cd0ed5
commit 62144384ce
3 changed files with 48 additions and 3 deletions

View file

@ -28,4 +28,5 @@ return [
],
'moinframe.loop.language' => 'fr',
'thumbs' => require __DIR__ . '/thumbs.php',
];

44
site/config/thumbs.php Normal file
View file

@ -0,0 +1,44 @@
<?php
/**
* Génère un preset srcset Kirby à partir d'un tableau [label => largeur_px].
* Applique le multiplicateur et optionnellement un format (ex: 'webp').
*/
function srcsetPreset(array $widths, float $mult, ?string $format = null): array
{
$preset = [];
foreach ($widths as $label => $px) {
$entry = ['width' => (int) round($px * $mult)];
if ($format !== null) {
$entry['format'] = $format;
}
$preset[$label] = $entry;
}
return $preset;
}
/**
* Génère une paire de presets (original + webp) depuis un tableau de widths.
*/
function srcsetPair(string $name, array $widths, float $mult): array
{
return [
$name => srcsetPreset($widths, $mult),
$name . '-webp' => srcsetPreset($widths, $mult, 'webp'),
];
}
// Pas de multiplicateur supplémentaire : les tailles retina sont déjà dans les widths
$m = 1;
// Bloc image — desktop max 720px, retina x2 = 1440px, mobile 95vw
$widths = [
'block-image' => ['360w' => 360, '720w' => 720, '1080w' => 1080, '1440w' => 1440],
];
return [
'quality' => 80,
'srcsets' => array_merge(
srcsetPair('block-image', $widths['block-image'], $m),
),
];

View file

@ -14,7 +14,7 @@ if ($block->location() == 'web') {
} elseif ($image = $block->image()->toFile()) {
$alt = $alt->or($image->alt());
$src = $image->url();
$srcset = $image->srcset([300, 600, 900, 1200, 1800]);
$srcset = $image->srcset('block-image-webp');
}
?>
@ -22,10 +22,10 @@ if ($block->location() == 'web') {
<figure<?= Html::attr(['data-ratio' => $ratio, 'data-crop' => $crop], null, ' ') ?>>
<?php if ($link->isNotEmpty()): ?>
<a href="<?= Str::esc($link->toUrl()) ?>">
<img src="<?= $src ?>" alt="<?= $alt->esc() ?>"<?php if ($srcset): ?> srcset="<?= $srcset ?>" sizes="min(60vw, 45rem)"<?php endif ?> loading="lazy">
<img src="<?= $src ?>" alt="<?= $alt->esc() ?>"<?php if ($srcset): ?> srcset="<?= $srcset ?>" sizes="(min-width: 768px) 720px, 95vw"<?php endif ?> loading="lazy">
</a>
<?php else: ?>
<img src="<?= $src ?>" alt="<?= $alt->esc() ?>"<?php if ($srcset): ?> srcset="<?= $srcset ?>" sizes="min(60vw, 45rem)"<?php endif ?> loading="lazy">
<img src="<?= $src ?>" alt="<?= $alt->esc() ?>"<?php if ($srcset): ?> srcset="<?= $srcset ?>" sizes="(min-width: 768px) 720px, 95vw"<?php endif ?> loading="lazy">
<?php endif ?>
<?php if ($caption->isNotEmpty()): ?>