Plugin Directory

Changeset 3814342


Ignore:
Timestamp:
11/20/2026 06:52:48 PM (10 hours ago)
Author:
jesusinica
Message:

Release 0.3.18

Location:
empirical-responsive-images
Files:
24 edited
1 copied

Legend:

Unmodified
Added
Removed
  • empirical-responsive-images/tags/0.3.18/assets/js/visitor-gap-observer.js

    r3706969 r3814342  
    238238        }
    239239
    240         function queueGap(target, targetWidth, targetMaximumWidth, nativeWidth, viewportWidth, slotWidth, critical) {
     240        function queueGap(target, targetWidth, targetMaximumWidth, nativeWidth, viewportWidth, slotWidth, critical, cover) {
    241241                var width = critical
    242242                        ? criticalWidth(targetWidth, Math.min(maximumWidth, targetMaximumWidth || maximumWidth))
    … …  
    270270                        gap.viewport = Math.min(5120, Math.ceil(viewportWidth / 128) * 128);
    271271                        gap.slot = Math.min(5120, Math.ceil(slotWidth / 16) * 16);
     272
     273                        if (cover) {
     274                                gap.cover = true;
     275                        }
    272276                }
    273277
    … …  
    391395                        return a - b;
    392396                });
     397        }
     398
     399        // object-fit: cover scales the image until it fills the box, so a photo
     400        // wider than its box needs box height x aspect ratio CSS pixels, not the
     401        // box width. Browsers size srcset choices (and sizes="auto") by the box.
     402        function coverLayoutWidth(image, renderedWidth, renderedHeight) {
     403                if (renderedWidth < 1 || renderedHeight < 1 || typeof window.getComputedStyle !== 'function') {
     404                        return renderedWidth;
     405                }
     406
     407                var style = null;
     408
     409                try {
     410                        style = window.getComputedStyle(image);
     411                } catch (error) {
     412                        return renderedWidth;
     413                }
     414
     415                if (!style || String(style.objectFit || '').trim() !== 'cover') {
     416                        return renderedWidth;
     417                }
     418
     419                var intrinsicWidth = Number(image.naturalWidth) || Number(image.getAttribute('width'));
     420                var intrinsicHeight = Number(image.naturalHeight) || Number(image.getAttribute('height'));
     421
     422                if (!(intrinsicWidth > 0) || !(intrinsicHeight > 0)) {
     423                        return renderedWidth;
     424                }
     425
     426                return Math.max(
     427                        renderedWidth,
     428                        Math.min(renderedWidth * 4, Math.ceil(renderedHeight * intrinsicWidth / intrinsicHeight))
     429                );
    393430        }
    394431
    … …  
    418455                }
    419456
     457                var layoutWidth = coverLayoutWidth(image, renderedWidth, renderedHeight);
    420458                var targetWidth = Math.min(
    421459                        targetMaximumWidth,
    422                         Math.ceil(renderedWidth * dpr)
     460                        Math.ceil(layoutWidth * dpr)
    423461                );
    424462                var candidateWidths = getCandidateWidths(image, renderedWidth);
    … …  
    489527                                nativeWidth,
    490528                                learnsLayout ? Number(window.innerWidth || 0) : 0,
    491                                 learnsLayout ? renderedWidth : 0,
    492                         useCriticalCoverage
     529                                learnsLayout ? layoutWidth : 0,
     530                                useCriticalCoverage,
     531                                'attachment' === targetKind && layoutWidth > renderedWidth
    493532                        );
    494533                }
  • empirical-responsive-images/tags/0.3.18/changelog.txt

    r3780732 r3814342  
     1= 0.3.18 - 2026-11-20 =
     2* Fixed - Theme and plugin images (assets) got a WebP or AVIF source that listed only the widths generated so far, while the image also listed its original width. Browsers chose from that subset, so a slot needing about 1300px got a 531px file. A format source for an asset now lists every width or is left out, as for media library images since 0.3.17.
     3* Fixed - The background job that makes one learned asset width now also makes the original asset in each enabled format, so its format sources become complete instead of staying out.
     4* Changed - Checking format support no longer loads wp-admin/includes/image.php; the check is a core media function.
     5
     6= 0.3.17 - 2026-11-11 =
     7* Fixed - Learned sizes hints are now kept per placement instead of per attachment. The signed visitor target carries a short context derived from the image's class list (ignoring wp-image-N and plugin classes), and layout evidence is stored under the attachment and that context. A photo used both as a large featured image and as a small card no longer gets the card's sizes value everywhere. Evidence recorded before this release has no context and is no longer used for sizes.
     8* Fixed - Images cropped with object-fit: cover are measured by the width the crop needs (box height x intrinsic aspect ratio, at most four times the box), not the box width. Such reports carry a cover flag, may exceed the viewport by up to three times, and stop the plugin from adding sizes="auto" for that placement, because browsers resolve auto to the box width.
     9* Fixed - A sizes hint learned only at viewports narrower than 1024px no longer extends its widest slot to every larger viewport. The image's original sizes value covers wider viewports until desktop layouts are learned.
     10* Fixed - A format source now lists every candidate width or is left out. A partial srcset made the browser choose from that subset, so a 150px slot could get a 32px file. When a sanitizer such as Elementor's wp_kses drops the picture wrapper but keeps the image, the final HTML pass removes the stale picture-child marker and wraps the image again.
     11* Fixed - Cache purges delete Elementor's cached element HTML when Elementor is active, so pages show new picture sources after regeneration. Generated CSS is left alone.
     12* Performance - AVIF is encoded at quality 65 by default. At 82 it was barely smaller than the source JPEG; at 65 it matches the distortion of WebP at 82 and is 15-20% smaller than WebP on photo samples. Other formats keep 82, and the output quality filter still overrides both.
     13
    114= 0.3.16 - 2026-11-02 =
    215* Performance - While the visitor gap queue is full (50 qualified jobs or 256 jobs in total), the visitor observer samples 10% of anonymous visitors instead of all of them. Reports then only add confirmations to waiting jobs, and each one starts an uncached WordPress request. The rate is kept in a small autoloaded option, updated only when it changes, and returns to 100% once the queue drains. Trusted editor reports are not sampled.
  • empirical-responsive-images/tags/0.3.18/empirical-responsive-images.php

    r3780732 r3814342  
    44 * Plugin URI: https://github.com/gsusI/empirical-responsive-images
    55 * Description: Fix oversized images with zero setup. Automatically creates the image sizes, thumbnails, WebP and AVIF your pages need, in the background.
    6  * Version: 0.3.16
     6 * Version: 0.3.18
    77 * Requires at least: 6.9
    88 * Requires PHP: 7.4
    … …  
    2121}
    2222
    23 define( 'EMPIRICAL_RESPONSIVE_IMAGES_VERSION', '0.3.16' );
     23define( 'EMPIRICAL_RESPONSIVE_IMAGES_VERSION', '0.3.18' );
    2424define( 'EMPIRICAL_RESPONSIVE_IMAGES_FILE', __FILE__ );
    2525define( 'EMPIRICAL_RESPONSIVE_IMAGES_DIR', plugin_dir_path( __FILE__ ) );
  • empirical-responsive-images/tags/0.3.18/includes/class-asset-manager.php

    r3780410 r3814342  
    1616 */
    1717final class Asset_Manager {
     18        /**
     19         * Narrowest viewport bucket treated as a desktop layout.
     20         */
     21        private const DESKTOP_VIEWPORT = 1024;
     22
    1823        private const VARIANT_DIRECTORY = 'empirical-responsive-images/assets';
    1924        private const MAX_SOURCE_BYTES  = 20971520;
    … …  
    380385                        }
    381386
    382                         if ( ! empty( $format_candidates ) ) {
     387                        // A source that lists only some widths makes the browser pick from that
     388                        // subset, so a wide slot could get a narrow file. List every width or none.
     389                        if ( ! empty( $format_candidates ) && count( $format_candidates ) === count( $candidates ) ) {
    383390                                $formats[ $format ] = $this->build_srcset_from_candidates( $format_candidates );
    384391                        }
    … …  
    486493         *
    487494         * Unlike full/manual asset generation, this does not add the original source
    488          * width unless the requested width itself is capped to that width.
     495         * width unless the requested width itself is capped to that width. It does
     496         * make the original's alternate formats: front-end sources always list the
     497         * original width, and a format source is left out until every width has it.
    489498         *
    490499         * @param string $url   Image URL.
    … …  
    494503         */
    495504        public function generate_for_asset_width( string $url, int $width, bool $force = false ): array {
    496                 $result = $this->build_sources( $url, array( $width ), array(), true, $force, false );
    497 
    498                 return $this->summarize_generation_result( $result );
     505                $result   = $this->summarize_generation_result( $this->build_sources( $url, array( $width ), array(), true, $force, false ) );
     506                $original = $this->ensure_source_format_variants( $url, $force );
     507
     508                return array(
     509                        'generated' => $result['generated'] + $original['generated'],
     510                        'skipped'   => $result['skipped'] + $original['skipped'],
     511                        'errors'    => array_slice( array_unique( array_merge( $result['errors'], $original['errors'] ) ), 0, 10 ),
     512                );
     513        }
     514
     515        /**
     516         * Make the enabled alternate formats of the original asset at its own width.
     517         *
     518         * @param string $url   Image URL.
     519         * @param bool   $force Force rebuild.
     520         * @return array Generation counters and errors.
     521         */
     522        private function ensure_source_format_variants( string $url, bool $force ): array {
     523                $counts = array(
     524                        'generated' => 0,
     525                        'skipped'   => 0,
     526                        'errors'    => array(),
     527                );
     528                $source = $this->resolve_source( $url );
     529
     530                if ( empty( $source ) ) {
     531                        return $counts;
     532                }
     533
     534                foreach ( $this->settings->get_enabled_formats() as $format ) {
     535                        if ( ! $this->supports_format( $format ) || ! Alpha_Compat::can_use_format_for_source( $source['path'], $format ) ) {
     536                                continue;
     537                        }
     538
     539                        $result = $this->ensure_format_variant( $source['path'], $source, absint( $source['width'] ), $format, $force );
     540
     541                        if ( is_wp_error( $result ) ) {
     542                                $counts['errors'][] = $result->get_error_message();
     543                        } elseif ( ! empty( $result['generated'] ) ) {
     544                                ++$counts['generated'];
     545                        } else {
     546                                ++$counts['skipped'];
     547                        }
     548                }
     549
     550                return $counts;
    499551        }
    500552
    … …  
    741793
    742794                if ( method_exists( $editor, 'set_quality' ) ) {
    743                         $editor->set_quality( (int) apply_filters( 'empirical_responsive_images_output_quality', 82, $source['extension'], $source['path'] ) );
     795                        $editor->set_quality( (int) apply_filters( 'empirical_responsive_images_output_quality', Format_Generator::default_quality( $source['extension'] ), $source['extension'], $source['path'] ) );
    744796                }
    745797
    … …  
    797849
    798850                if ( method_exists( $editor, 'set_quality' ) ) {
    799                         $editor->set_quality( (int) apply_filters( 'empirical_responsive_images_output_quality', 82, $format, $candidate_path ) );
     851                        $editor->set_quality( (int) apply_filters( 'empirical_responsive_images_output_quality', Format_Generator::default_quality( $format ), $format, $candidate_path ) );
    800852                }
    801853
    … …  
    866918
    867919        /**
    868          * Build an empirical sizes attribute from observed CSS slots.
    869          *
    870          * @param array $slot_widths Slot width map.
     920         * Build a sizes value from viewport-bucketed slot widths.
     921         *
     922         * Viewports wider than any learned bucket would otherwise reuse the widest
     923         * learned slot. When only small viewports have been seen, a fallback (the
     924         * image's original sizes value) covers the rest instead of assuming a phone
     925         * layout on desktop.
     926         *
     927         * @param array  $slot_widths Slot widths keyed by viewport bucket.
     928         * @param string $fallback    Sizes value for viewports wider than every learned bucket.
    871929         * @return string
    872930         */
    873         public function build_empirical_sizes( array $slot_widths ): string {
     931        public function build_empirical_sizes( array $slot_widths, string $fallback = '' ): string {
    874932                $slots = array();
    875933
    … …  
    884942
    885943                if ( empty( $slots ) ) {
    886                         return '100vw';
     944                        return '' !== trim( $fallback ) ? trim( $fallback ) : '100vw';
    887945                }
    888946
    … …  
    895953                }
    896954
    897                 $parts[] = max( $slots ) . 'px';
     955                $fallback = trim( preg_replace( '/^auto\s*,\s*/i', '', trim( $fallback ) ) );
     956                $parts[]  = '' !== $fallback && max( array_keys( $slots ) ) < self::DESKTOP_VIEWPORT
     957                        ? $fallback
     958                        : max( $slots ) . 'px';
    898959
    899960                return implode( ', ', array_unique( $parts ) );
    … …  
    907968         */
    908969        private function supports_format( string $format ): bool {
    909                 require_once ABSPATH . 'wp-admin/includes/image.php';
     970                if ( ! function_exists( 'wp_image_editor_supports' ) ) {
     971                        require_once ABSPATH . 'wp-includes/media.php';
     972                }
    910973
    911974                return (bool) wp_image_editor_supports(
  • empirical-responsive-images/tags/0.3.18/includes/class-background-optimizer.php

    r3780410 r3814342  
    362362                $slot_width     = absint( $job['slot_width'] ?? 0 );
    363363                $creates_width  = ! empty( $job['creates_width'] );
     364                $cover          = ! empty( $job['cover'] );
    364365
    365366                if ( '' === $token || $width < 1 || '' === $lease ) {
    … …  
    392393                        }
    393394
    394                         $result = $this->process_attachment( $target, $width, $viewport_width, $slot_width, $creates_width );
     395                        $result = $this->process_attachment( $target, $width, $viewport_width, $slot_width, $creates_width, $cover );
    395396                } elseif ( 'asset' === (string) ( $target['type'] ?? '' ) ) {
    396397                        if ( ! $this->settings->is_asset_processing_enabled() ) {
    … …  
    502503         * @param int   $slot_width     Coarse CSS slot bucket.
    503504         * @param bool  $creates_width  Whether evidence requested a new exact width.
     505         * @param bool  $cover          Whether the image is cropped to cover its box.
    504506         * @return array
    505507         */
    506         private function process_attachment( array $target, int $width, int $viewport_width, int $slot_width, bool $creates_width ): array {
     508        private function process_attachment( array $target, int $width, int $viewport_width, int $slot_width, bool $creates_width, bool $cover = false ): array {
    507509                $attachment_id    = absint( $target['attachment_id'] ?? 0 );
    508510                $required_formats = Visitor_Gap_Target::get_applicable_formats(
    … …  
    613615                        $viewport_width > 0
    614616                        && $slot_width > 0
    615                         && ! $this->observation_store->record_automatic_attachment_slot( $attachment_id, $viewport_width, $slot_width )
     617                        && ! $this->observation_store->record_automatic_attachment_slot(
     618                                $attachment_id,
     619                                $viewport_width,
     620                                $slot_width,
     621                                (string) ( $target['context'] ?? '' ),
     622                                $cover
     623                        )
    616624                ) {
    617625                        return array(
    … …  
    681689                if ( method_exists( $editor, 'set_quality' ) ) {
    682690                        $extension = strtolower( (string) pathinfo( $file, PATHINFO_EXTENSION ) );
    683                         $editor->set_quality( (int) apply_filters( 'empirical_responsive_images_output_quality', 82, $extension, $file ) );
     691                        $editor->set_quality( (int) apply_filters( 'empirical_responsive_images_output_quality', Format_Generator::default_quality( $extension ), $extension, $file ) );
    684692                }
    685693
  • empirical-responsive-images/tags/0.3.18/includes/class-cache-compat.php

    r3626416 r3814342  
    6969                }
    7070
     71                self::purge_elementor_element_cache();
     72
    7173                // phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Third-party cache hooks must use their documented names.
    7274                do_action( 'litespeed_purge_url', $url );
    … …  
    102104                }
    103105
     106                self::purge_elementor_element_cache();
     107
    104108                // phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Third-party cache hooks must use their documented names.
    105109                do_action( 'litespeed_purge_all' );
    … …  
    108112                do_action( 'empirical_responsive_images_purge_all' );
    109113        }
     114
     115        /**
     116         * Drop Elementor's cached widget HTML so new picture markup is rendered.
     117         *
     118         * Elementor caches rendered elements in post meta for a day, which would keep
     119         * serving images without their new picture sources. Header and footer
     120         * templates are separate posts, so the whole cache is cleared; generated CSS
     121         * files are left alone.
     122         *
     123         * @return void
     124         */
     125        private static function purge_elementor_element_cache(): void {
     126                if ( ! defined( 'ELEMENTOR_VERSION' ) ) {
     127                        return;
     128                }
     129
     130                delete_post_meta_by_key( '_elementor_element_cache' );
     131        }
    110132}
  • empirical-responsive-images/tags/0.3.18/includes/class-format-generator.php

    r3780410 r3814342  
    4242        public function __construct( Settings $settings ) {
    4343                $this->settings = $settings;
     44        }
     45
     46        /**
     47         * Default encoder quality for an output format or file extension.
     48         *
     49         * AVIF at 65 matches the visual distortion of WebP at 82 while staying
     50         * markedly smaller; AVIF at 82 can be larger than the JPEG it replaces.
     51         *
     52         * @param string $format Format or file extension.
     53         * @return int
     54         */
     55        public static function default_quality( string $format ): int {
     56                return 'avif' === strtolower( $format ) ? 65 : 82;
    4457        }
    4558
    … …  
    466479
    467480                if ( method_exists( $editor, 'set_quality' ) ) {
    468                         $editor->set_quality( (int) apply_filters( 'empirical_responsive_images_output_quality', 82, $format, $source_path ) );
     481                        $editor->set_quality( (int) apply_filters( 'empirical_responsive_images_output_quality', self::default_quality( $format ), $format, $source_path ) );
    469482                }
    470483
  • empirical-responsive-images/tags/0.3.18/includes/class-observation-store.php

    r3780410 r3814342  
    312312
    313313        /**
    314          * Get bounded visitor-learned CSS slot widths for one attachment.
    315          *
    316          * @param int $attachment_id Attachment ID.
    317          * @return array
    318          */
    319         public function get_attachment_slot_widths( int $attachment_id ): array {
     314         * Get bounded visitor-learned CSS slot widths for one attachment placement.
     315         *
     316         * @param int    $attachment_id Attachment ID.
     317         * @param string $context       Placement context.
     318         * @return array
     319         */
     320        public function get_attachment_slot_widths( int $attachment_id, string $context = '' ): array {
     321                return $this->get_attachment_layout( $attachment_id, $context )['slot_widths'];
     322        }
     323
     324        /**
     325         * Get visitor-learned layout evidence for one attachment placement.
     326         *
     327         * Records learned before placements were tracked carry no context and are
     328         * only returned for an empty context, so they never resize other slots.
     329         *
     330         * @param int    $attachment_id Attachment ID.
     331         * @param string $context       Placement context.
     332         * @return array{slot_widths: array, cover: bool}
     333         */
     334        public function get_attachment_layout( int $attachment_id, string $context = '' ): array {
     335                $empty = array(
     336                        'slot_widths' => array(),
     337                        'cover'       => false,
     338                );
     339
    320340                if ( $attachment_id < 1 ) {
    321                         return array();
     341                        return $empty;
    322342                }
    323343
    324344                $data  = $this->get_data();
    325                 $key   = (string) $attachment_id;
     345                $key   = self::attachment_slot_key( $attachment_id, $context );
    326346                $entry = isset( $data['attachment_slots'][ $key ] ) && is_array( $data['attachment_slots'][ $key ] )
    327347                        ? $data['attachment_slots'][ $key ]
    328348                        : array();
    329349
    330                 return isset( $entry['slot_widths'] ) && is_array( $entry['slot_widths'] )
    331                         ? $this->sanitize_slot_width_map( $entry['slot_widths'] )
    332                         : array();
     350                return array(
     351                        'slot_widths' => isset( $entry['slot_widths'] ) && is_array( $entry['slot_widths'] )
     352                                ? $this->sanitize_slot_width_map( $entry['slot_widths'] )
     353                                : array(),
     354                        'cover'       => ! empty( $entry['cover'] ),
     355                );
     356        }
     357
     358        /**
     359         * Build the storage key for one attachment placement.
     360         *
     361         * @param int    $attachment_id Attachment ID.
     362         * @param string $context       Placement context.
     363         * @return string
     364         */
     365        public static function attachment_slot_key( int $attachment_id, string $context = '' ): string {
     366                $context = Visitor_Gap_Target::sanitize_context( $context );
     367
     368                return (string) absint( $attachment_id ) . ( '' !== $context ? '|' . $context : '' );
    333369        }
    334370
    … …  
    336372         * Check whether an attachment layout report would leave stored slots unchanged.
    337373         *
    338          * @param int $attachment_id  Attachment ID.
    339          * @param int $viewport_width Coarse viewport bucket.
    340          * @param int $slot_width     Coarse rendered slot bucket.
     374         * @param int    $attachment_id  Attachment ID.
     375         * @param int    $viewport_width Coarse viewport bucket.
     376         * @param int    $slot_width     Coarse rendered slot bucket.
     377         * @param string $context        Placement context.
     378         * @param bool   $cover          Whether the image is cropped to cover its box.
    341379         * @return bool
    342380         */
    343         public function attachment_layout_is_recorded( int $attachment_id, int $viewport_width, int $slot_width ): bool {
    344                 return $this->slot_map_covers( $this->get_attachment_slot_widths( $attachment_id ), $viewport_width, $slot_width );
     381        public function attachment_layout_is_recorded( int $attachment_id, int $viewport_width, int $slot_width, string $context = '', bool $cover = false ): bool {
     382                $layout = $this->get_attachment_layout( $attachment_id, $context );
     383
     384                return ( ! $cover || $layout['cover'] )
     385                        && $this->slot_map_covers( $layout['slot_widths'], $viewport_width, $slot_width );
    345386        }
    346387
    … …  
    533574         * Record one bounded visitor-learned attachment layout.
    534575         *
    535          * @param int $attachment_id Attachment ID.
    536          * @param int $viewport_width Coarse viewport bucket.
    537          * @param int $slot_width Coarse rendered slot bucket.
     576         * @param int    $attachment_id  Attachment ID.
     577         * @param int    $viewport_width Coarse viewport bucket.
     578         * @param int    $slot_width     Coarse rendered slot bucket.
     579         * @param string $context        Placement context.
     580         * @param bool   $cover          Whether the image is cropped to cover its box.
    538581         * @return bool Whether the exact layout record is durable.
    539582         */
    540         public function record_automatic_attachment_slot( int $attachment_id, int $viewport_width, int $slot_width ): bool {
     583        public function record_automatic_attachment_slot( int $attachment_id, int $viewport_width, int $slot_width, string $context = '', bool $cover = false ): bool {
    541584                $attachment_id  = absint( $attachment_id );
    542585                $viewport_width = min( 5120, absint( $viewport_width ) );
    … …  
    554597                        $data  = $this->get_data();
    555598                        $now   = time();
    556                         $key   = (string) $attachment_id;
     599                        $key   = self::attachment_slot_key( $attachment_id, $context );
    557600                        $entry = isset( $data['attachment_slots'][ $key ] ) && is_array( $data['attachment_slots'][ $key ] )
    558601                                ? $data['attachment_slots'][ $key ]
    … …  
    573616                        $entry['last_seen']   = $now;
    574617
     618                        if ( $cover ) {
     619                                $entry['cover'] = true;
     620                        }
     621
    575622                        $data['attachment_slots'][ $key ] = $entry;
    576623                        $data['attachment_slots']         = $this->trim_attachment_slots(
    … …  
    601648
    602649                try {
    603                         $data = $this->get_data();
    604 
    605                         if ( ! isset( $data['attachment_slots'][ $key ] ) ) {
     650                        $data    = $this->get_data();
     651                        $removed = false;
     652
     653                        foreach ( array_keys( $data['attachment_slots'] ) as $slot_key ) {
     654                                $slot_key = (string) $slot_key;
     655
     656                                if ( $slot_key === $key || 0 === strpos( $slot_key, $key . '|' ) ) {
     657                                        unset( $data['attachment_slots'][ $slot_key ] );
     658                                        $removed = true;
     659                                }
     660                        }
     661
     662                        if ( ! $removed ) {
    606663                                return;
    607664                        }
    608665
    609                         unset( $data['attachment_slots'][ $key ] );
    610666                        $data['updated_at'] = time();
    611667                        $this->persist_locked_data( $data );
  • empirical-responsive-images/tags/0.3.18/includes/class-renderer.php

    r3780702 r3814342  
    252252
    253253                if ( false !== strpos( $html, 'data-empirical-responsive-images-picture-child' ) ) {
    254                         return $html;
     254                        if ( $in_picture ) {
     255                                return $html;
     256                        }
     257
     258                        // A sanitizer (Elementor prints image widgets through wp_kses) dropped the
     259                        // PICTURE wrapper but kept the IMG, so wrap it again.
     260                        $html = $this->unmark_picture_child_html( $html );
    255261                }
    256262
    … …  
    569575                }
    570576
     577                $context = Visitor_Gap_Target::attachment_context( $this->image_class_from_html( $html ) );
     578
    571579                if ( $apply_empirical_sizes ) {
    572                         $html = $this->apply_attachment_empirical_sizes_html( $html, $attachment_id );
     580                        $html = $this->apply_attachment_empirical_sizes_html( $html, $attachment_id, $context );
    573581                }
    574582
    … …  
    593601                }
    594602
    595                 $target = Visitor_Gap_Target::token_for_attachment( $attachment_id );
     603                $target = Visitor_Gap_Target::token_for_attachment( $attachment_id, $context );
    596604
    597605                if ( '' === $target ) {
    … …  
    674682         * Lazy images retain the standards-based auto keyword, which lets supporting
    675683         * browsers use the actual layout slot even when CSS uses %, vh, or calc().
     684         * Cover-cropped images drop it: auto describes the box, and the crop needs
     685         * a wider image than the box.
    676686         *
    677687         * @param string $html          Image HTML.
    678688         * @param int    $attachment_id Attachment ID.
    679          * @return string
    680          */
    681         private function apply_attachment_empirical_sizes_html( string $html, int $attachment_id ): string {
    682                 $slot_widths = $this->store->get_attachment_slot_widths( $attachment_id );
    683 
    684                 if ( empty( $slot_widths ) || ! class_exists( 'WP_HTML_Tag_Processor' ) ) {
     689         * @param string $context       Placement context.
     690         * @return string
     691         */
     692        private function apply_attachment_empirical_sizes_html( string $html, int $attachment_id, string $context = '' ): string {
     693                $layout = $this->store->get_attachment_layout( $attachment_id, $context );
     694
     695                if ( empty( $layout['slot_widths'] ) || ! class_exists( 'WP_HTML_Tag_Processor' ) ) {
    685696                        return $html;
    686697                }
    … …  
    688699                $processor = new \WP_HTML_Tag_Processor( $html );
    689700
    690                 if ( ! $processor->next_tag( array( 'tag_name' => 'IMG' ) ) || ! $this->responsive_sizes_are_plugin_manageable( $processor ) ) {
    691                         return $html;
    692                 }
    693 
    694                 $sizes   = $this->asset_manager->build_empirical_sizes( $slot_widths );
     701                if (
     702                        ! $processor->next_tag( array( 'tag_name' => 'IMG' ) )
     703                        || 'empirical' === (string) $processor->get_attribute( 'data-empirical-responsive-images-sizes' )
     704                        || ! $this->responsive_sizes_are_plugin_manageable( $processor )
     705                ) {
     706                        return $html;
     707                }
     708
     709                $sizes   = $this->asset_manager->build_empirical_sizes( $layout['slot_widths'], (string) $processor->get_attribute( 'sizes' ) );
    695710                $loading = strtolower( (string) $processor->get_attribute( 'loading' ) );
    696711
    697                 if ( 'lazy' === $loading && 0 !== strpos( ltrim( $sizes ), 'auto,' ) ) {
     712                if ( 'lazy' === $loading && ! $layout['cover'] && 0 !== strpos( ltrim( $sizes ), 'auto,' ) ) {
    698713                        $sizes = 'auto, ' . $sizes;
    699714                }
    … …  
    749764
    750765                $processor->set_attribute( 'data-empirical-responsive-images-picture-child', '1' );
     766
     767                return $processor->get_updated_html();
     768        }
     769
     770        /**
     771         * Remove the picture-child marker from an image that lost its wrapper.
     772         *
     773         * @param string $html Image HTML.
     774         * @return string
     775         */
     776        private function unmark_picture_child_html( string $html ): string {
     777                $processor = new \WP_HTML_Tag_Processor( $html );
     778
     779                if ( ! $processor->next_tag( array( 'tag_name' => 'IMG' ) ) ) {
     780                        return $html;
     781                }
     782
     783                $processor->remove_attribute( 'data-empirical-responsive-images-picture-child' );
    751784
    752785                return $processor->get_updated_html();
    … …  
    922955         * Build one alternate srcset.
    923956         *
     957         * Returns an empty string unless every candidate has an alternate: a source
     958         * that lists only some widths makes the browser pick from that subset, so an
     959         * image could be served from a far smaller file than its slot needs.
     960         *
    924961         * @param array  $image    Image attributes.
    925962         * @param array  $metadata Attachment metadata.
    … …  
    946983
    947984                        if ( '' === $alternate_url ) {
    948                                 continue;
     985                                return '';
    949986                        }
    950987
  • empirical-responsive-images/tags/0.3.18/includes/class-visitor-gap-store.php

    r3780732 r3814342  
    498498                                                'viewport_width'       => $normalized['viewport_width'],
    499499                                                'slot_width'           => $normalized['slot_width'],
     500                                                'cover'                => ! empty( $normalized['cover'] ),
    500501                                                'creates_width'        => $normalized['creates_width'],
    501502                                                'confirmations'        => 0,
    … …  
    523524                                                $job[ $metric ] = absint( $normalized[ $metric ] );
    524525                                        }
     526                                }
     527
     528                                if ( ! empty( $normalized['cover'] ) ) {
     529                                        $job['cover'] = true;
    525530                                }
    526531
    … …  
    10801085                $viewport_width   = $this->normalize_metric( $gap['viewport'] ?? 0, 128, 5120 );
    10811086                $slot_width       = $this->normalize_metric( $gap['slot'] ?? 0, 16, 5120 );
    1082 
    1083                 if ( ! $this->layout_metrics_are_plausible( $reported_width, $viewport_width, $slot_width ) ) {
     1087                $cover            = 'attachment' === $type && true === ( $gap['cover'] ?? false );
     1088
     1089                if ( ! $this->layout_metrics_are_plausible( $reported_width, $viewport_width, $slot_width, $cover, $maximum ) ) {
    10841090                        $viewport_width = 0;
    10851091                        $slot_width     = 0;
    … …  
    10871093
    10881094                $has_layout_hint   = $viewport_width > 0 && $slot_width > 0;
     1095                $cover             = $cover && $has_layout_hint;
    10891096                $already_optimized = $is_current_protocol
    10901097                        ? (
    … …  
    11011108
    11021109                // A job that would change nothing still spends daily work and purges pages.
    1103                 if ( $files_ready && ( ! $has_layout_hint || $this->layout_is_recorded( $target, $work_width, $viewport_width, $slot_width ) ) ) {
     1110                if ( $files_ready && ( ! $has_layout_hint || $this->layout_is_recorded( $target, $work_width, $viewport_width, $slot_width, $cover ) ) ) {
    11041111                        return array();
    11051112                }
    … …  
    11181125                        'viewport_width'       => $viewport_width,
    11191126                        'slot_width'           => $slot_width,
     1127                        'cover'                => $cover,
    11201128                        'creates_width'        => 0 === $native_width,
    11211129                        'managed_widths'       => Visitor_Gap_Target::get_managed_widths( $target, $this->get_asset_manager() ),
    … …  
    11311139         * @param int   $viewport_width Coarse viewport bucket.
    11321140         * @param int   $slot_width     Coarse rendered slot bucket.
     1141         * @param bool  $cover          Whether the image is cropped to cover its box.
    11331142         * @return bool
    11341143         */
    1135         private function layout_is_recorded( array $target, int $width, int $viewport_width, int $slot_width ): bool {
     1144        private function layout_is_recorded( array $target, int $width, int $viewport_width, int $slot_width, bool $cover = false ): bool {
    11361145                if ( 'attachment' === (string) ( $target['type'] ?? '' ) ) {
    1137                         return $this->get_observation_store()->attachment_layout_is_recorded( absint( $target['attachment_id'] ?? 0 ), $viewport_width, $slot_width );
     1146                        return $this->get_observation_store()->attachment_layout_is_recorded(
     1147                                absint( $target['attachment_id'] ?? 0 ),
     1148                                $viewport_width,
     1149                                $slot_width,
     1150                                (string) ( $target['context'] ?? '' ),
     1151                                $cover
     1152                        );
    11381153                }
    11391154
    … …  
    11731188         * Reject anonymous layout hints that cannot describe the reported image.
    11741189         *
    1175          * @param int $physical_width Coarse physical-pixel target.
    1176          * @param int $viewport_width Coarse CSS viewport width.
    1177          * @param int $slot_width     Coarse CSS slot width.
     1190         * A cover-cropped image needs more width than its box, so its slot may
     1191         * exceed the viewport. A physical width capped by the source still counts.
     1192         *
     1193         * @param int  $physical_width Coarse physical-pixel target.
     1194         * @param int  $viewport_width Coarse CSS viewport width.
     1195         * @param int  $slot_width     Coarse CSS slot width.
     1196         * @param bool $cover          Whether the image is cropped to cover its box.
     1197         * @param int  $maximum        Largest width the target can reach.
    11781198         * @return bool
    11791199         */
    1180         private function layout_metrics_are_plausible( int $physical_width, int $viewport_width, int $slot_width ): bool {
     1200        private function layout_metrics_are_plausible( int $physical_width, int $viewport_width, int $slot_width, bool $cover = false, int $maximum = 0 ): bool {
    11811201                if ( $viewport_width < 1 || $slot_width < 1 || $physical_width < 1 ) {
    11821202                        return false;
    11831203                }
    11841204
    1185                 if ( $slot_width > $viewport_width + 32 ) {
     1205                if ( $slot_width > ( $cover ? $viewport_width * 3 : $viewport_width ) + 32 ) {
    11861206                        return false;
    11871207                }
    11881208
    1189                 return $physical_width >= (int) floor( $slot_width * 0.8 )
     1209                return (
     1210                        $physical_width >= (int) floor( $slot_width * 0.8 )
     1211                        || ( $maximum > 0 && $physical_width >= $maximum )
     1212                )
    11901213                        && $physical_width <= (int) ceil( $slot_width * 4.8 );
    11911214        }
  • empirical-responsive-images/tags/0.3.18/includes/class-visitor-gap-target.php

    r3780410 r3814342  
    5151         * Create a signed target for one image attachment.
    5252         *
    53          * @param int $attachment_id Attachment ID.
     53         * The optional placement context keeps layout evidence for one image
     54         * apart from the same image shown elsewhere at another size.
     55         *
     56         * @param int    $attachment_id Attachment ID.
     57         * @param string $context       Placement context from attachment_context().
    5458         * @return string
    5559         */
    56         public static function token_for_attachment( int $attachment_id ): string {
     60        public static function token_for_attachment( int $attachment_id, string $context = '' ): string {
    5761                $attachment_id = absint( $attachment_id );
     62                $context       = self::sanitize_context( $context );
    5863
    5964                if ( $attachment_id < 1 ) {
    … …  
    6166                }
    6267
    63                 if ( isset( self::$attachment_tokens[ $attachment_id ] ) ) {
    64                         return self::$attachment_tokens[ $attachment_id ];
     68                $cache_key = $attachment_id . '|' . $context;
     69
     70                if ( isset( self::$attachment_tokens[ $cache_key ] ) ) {
     71                        return self::$attachment_tokens[ $cache_key ];
    6572                }
    6673
    … …  
    6875
    6976                if ( ! wp_attachment_is_image( $attachment_id ) || ! self::dimensions_are_safe( $dimensions ) ) {
    70                         self::$attachment_tokens[ $attachment_id ] = '';
     77                        self::$attachment_tokens[ $cache_key ] = '';
    7178                        return '';
    7279                }
    7380
    74                 $token                                     = self::sign_payload( 'attachment:' . $attachment_id );
    75                 self::$attachment_tokens[ $attachment_id ] = $token;
     81                $token                                 = self::sign_payload( 'attachment:' . $attachment_id . ( '' !== $context ? '|' . $context : '' ) );
     82                self::$attachment_tokens[ $cache_key ] = $token;
    7683
    7784                return $token;
     85        }
     86
     87        /**
     88         * Derive a placement context from an image tag's class list.
     89         *
     90         * Per-attachment and plugin-owned classes are ignored, so the same layout
     91         * slot maps to the same context on every page and for every attachment.
     92         *
     93         * @param string $classes Image class attribute.
     94         * @return string Twelve hex characters.
     95         */
     96        public static function attachment_context( string $classes ): string {
     97                $tokens = preg_split( '/\s+/', strtolower( trim( $classes ) ) );
     98                $tokens = array_filter(
     99                        is_array( $tokens ) ? $tokens : array(),
     100                        static function ( string $token ): bool {
     101                                return '' !== $token
     102                                        && 1 !== preg_match( '/^wp-image-[0-9]+$/', $token )
     103                                        && 0 !== strpos( $token, 'empirical-responsive-image' );
     104                        }
     105                );
     106                $tokens = array_values( array_unique( $tokens ) );
     107                sort( $tokens );
     108
     109                return substr( hash( 'sha256', implode( ' ', $tokens ) ), 0, 12 );
     110        }
     111
     112        /**
     113         * Validate one placement context.
     114         *
     115         * @param string $context Context.
     116         * @return string
     117         */
     118        public static function sanitize_context( string $context ): string {
     119                return 1 === preg_match( '/^[a-f0-9]{12}$/', $context ) ? $context : '';
    78120        }
    79121
    … …  
    503545         */
    504546        private static function resolve_attachment( string $raw_id ): array {
     547                $context = '';
     548
     549                if ( false !== strpos( $raw_id, '|' ) ) {
     550                        list( $raw_id, $context ) = explode( '|', $raw_id, 2 );
     551
     552                        if ( '' === self::sanitize_context( $context ) ) {
     553                                return array();
     554                        }
     555                }
     556
    505557                if ( ! preg_match( '/^[1-9][0-9]*$/', $raw_id ) ) {
    506558                        return array();
    … …  
    524576                        'key'              => 'attachment:' . $attachment_id,
    525577                        'attachment_id'    => $attachment_id,
     578                        'context'          => $context,
    526579                        'url'              => '',
    527580                        'source_width'     => absint( $dimensions['width'] ?? 0 ),
  • empirical-responsive-images/tags/0.3.18/readme.txt

    r3780732 r3814342  
    55Tested up to: 7.1
    66Requires PHP: 7.4
    7 Stable tag: 0.3.16
     7Stable tag: 0.3.18
    88License: GPLv2 or later
    99License URI: https://www.gnu.org/licenses/gpl-2.0.html
    … …  
    168168== Changelog ==
    169169
     170= 0.3.18 =
     171* Sharper theme and plugin images in modern formats: a WebP or AVIF source now lists every width the image offers or is left out, so a wide slot no longer gets a narrow file. The background job also makes the original image in each format, so the source fills in on its own.
     172
     173= 0.3.17 =
     174* Sharper images where the same photo appears at different sizes, such as a large featured image that also shows as a small card thumbnail. Each placement now learns its own size instead of sharing one, so a thumbnail no longer makes the large image blurry.
     175* Sharper cropped images: photos cropped to fill their box (object-fit: cover) now get a file wide enough for the crop, not just for the box.
     176* Sizes learned on phones no longer apply to desktop screens until desktop visits have been measured.
     177* Image format sources always list every available width, so browsers no longer pick a tiny file from an incomplete list.
     178* Pages built with Elementor show new image formats right after they are generated.
     179* AVIF files are 15-20% smaller at the same visual quality.
     180
    170181= 0.3.16 =
    171182* Fewer server requests from visitors while the image queue is full: only one visitor in ten reports missing image sizes until the queue has room again. Logged-in editors still report every time.
  • empirical-responsive-images/trunk/assets/js/visitor-gap-observer.js

    r3706969 r3814342  
    238238        }
    239239
    240         function queueGap(target, targetWidth, targetMaximumWidth, nativeWidth, viewportWidth, slotWidth, critical) {
     240        function queueGap(target, targetWidth, targetMaximumWidth, nativeWidth, viewportWidth, slotWidth, critical, cover) {
    241241                var width = critical
    242242                        ? criticalWidth(targetWidth, Math.min(maximumWidth, targetMaximumWidth || maximumWidth))
    … …  
    270270                        gap.viewport = Math.min(5120, Math.ceil(viewportWidth / 128) * 128);
    271271                        gap.slot = Math.min(5120, Math.ceil(slotWidth / 16) * 16);
     272
     273                        if (cover) {
     274                                gap.cover = true;
     275                        }
    272276                }
    273277
    … …  
    391395                        return a - b;
    392396                });
     397        }
     398
     399        // object-fit: cover scales the image until it fills the box, so a photo
     400        // wider than its box needs box height x aspect ratio CSS pixels, not the
     401        // box width. Browsers size srcset choices (and sizes="auto") by the box.
     402        function coverLayoutWidth(image, renderedWidth, renderedHeight) {
     403                if (renderedWidth < 1 || renderedHeight < 1 || typeof window.getComputedStyle !== 'function') {
     404                        return renderedWidth;
     405                }
     406
     407                var style = null;
     408
     409                try {
     410                        style = window.getComputedStyle(image);
     411                } catch (error) {
     412                        return renderedWidth;
     413                }
     414
     415                if (!style || String(style.objectFit || '').trim() !== 'cover') {
     416                        return renderedWidth;
     417                }
     418
     419                var intrinsicWidth = Number(image.naturalWidth) || Number(image.getAttribute('width'));
     420                var intrinsicHeight = Number(image.naturalHeight) || Number(image.getAttribute('height'));
     421
     422                if (!(intrinsicWidth > 0) || !(intrinsicHeight > 0)) {
     423                        return renderedWidth;
     424                }
     425
     426                return Math.max(
     427                        renderedWidth,
     428                        Math.min(renderedWidth * 4, Math.ceil(renderedHeight * intrinsicWidth / intrinsicHeight))
     429                );
    393430        }
    394431
    … …  
    418455                }
    419456
     457                var layoutWidth = coverLayoutWidth(image, renderedWidth, renderedHeight);
    420458                var targetWidth = Math.min(
    421459                        targetMaximumWidth,
    422                         Math.ceil(renderedWidth * dpr)
     460                        Math.ceil(layoutWidth * dpr)
    423461                );
    424462                var candidateWidths = getCandidateWidths(image, renderedWidth);
    … …  
    489527                                nativeWidth,
    490528                                learnsLayout ? Number(window.innerWidth || 0) : 0,
    491                                 learnsLayout ? renderedWidth : 0,
    492                         useCriticalCoverage
     529                                learnsLayout ? layoutWidth : 0,
     530                                useCriticalCoverage,
     531                                'attachment' === targetKind && layoutWidth > renderedWidth
    493532                        );
    494533                }
  • empirical-responsive-images/trunk/changelog.txt

    r3780732 r3814342  
     1= 0.3.18 - 2026-11-20 =
     2* Fixed - Theme and plugin images (assets) got a WebP or AVIF source that listed only the widths generated so far, while the image also listed its original width. Browsers chose from that subset, so a slot needing about 1300px got a 531px file. A format source for an asset now lists every width or is left out, as for media library images since 0.3.17.
     3* Fixed - The background job that makes one learned asset width now also makes the original asset in each enabled format, so its format sources become complete instead of staying out.
     4* Changed - Checking format support no longer loads wp-admin/includes/image.php; the check is a core media function.
     5
     6= 0.3.17 - 2026-11-11 =
     7* Fixed - Learned sizes hints are now kept per placement instead of per attachment. The signed visitor target carries a short context derived from the image's class list (ignoring wp-image-N and plugin classes), and layout evidence is stored under the attachment and that context. A photo used both as a large featured image and as a small card no longer gets the card's sizes value everywhere. Evidence recorded before this release has no context and is no longer used for sizes.
     8* Fixed - Images cropped with object-fit: cover are measured by the width the crop needs (box height x intrinsic aspect ratio, at most four times the box), not the box width. Such reports carry a cover flag, may exceed the viewport by up to three times, and stop the plugin from adding sizes="auto" for that placement, because browsers resolve auto to the box width.
     9* Fixed - A sizes hint learned only at viewports narrower than 1024px no longer extends its widest slot to every larger viewport. The image's original sizes value covers wider viewports until desktop layouts are learned.
     10* Fixed - A format source now lists every candidate width or is left out. A partial srcset made the browser choose from that subset, so a 150px slot could get a 32px file. When a sanitizer such as Elementor's wp_kses drops the picture wrapper but keeps the image, the final HTML pass removes the stale picture-child marker and wraps the image again.
     11* Fixed - Cache purges delete Elementor's cached element HTML when Elementor is active, so pages show new picture sources after regeneration. Generated CSS is left alone.
     12* Performance - AVIF is encoded at quality 65 by default. At 82 it was barely smaller than the source JPEG; at 65 it matches the distortion of WebP at 82 and is 15-20% smaller than WebP on photo samples. Other formats keep 82, and the output quality filter still overrides both.
     13
    114= 0.3.16 - 2026-11-02 =
    215* Performance - While the visitor gap queue is full (50 qualified jobs or 256 jobs in total), the visitor observer samples 10% of anonymous visitors instead of all of them. Reports then only add confirmations to waiting jobs, and each one starts an uncached WordPress request. The rate is kept in a small autoloaded option, updated only when it changes, and returns to 100% once the queue drains. Trusted editor reports are not sampled.
  • empirical-responsive-images/trunk/empirical-responsive-images.php

    r3780732 r3814342  
    44 * Plugin URI: https://github.com/gsusI/empirical-responsive-images
    55 * Description: Fix oversized images with zero setup. Automatically creates the image sizes, thumbnails, WebP and AVIF your pages need, in the background.
    6  * Version: 0.3.16
     6 * Version: 0.3.18
    77 * Requires at least: 6.9
    88 * Requires PHP: 7.4
    … …  
    2121}
    2222
    23 define( 'EMPIRICAL_RESPONSIVE_IMAGES_VERSION', '0.3.16' );
     23define( 'EMPIRICAL_RESPONSIVE_IMAGES_VERSION', '0.3.18' );
    2424define( 'EMPIRICAL_RESPONSIVE_IMAGES_FILE', __FILE__ );
    2525define( 'EMPIRICAL_RESPONSIVE_IMAGES_DIR', plugin_dir_path( __FILE__ ) );
  • empirical-responsive-images/trunk/includes/class-asset-manager.php

    r3780410 r3814342  
    1616 */
    1717final class Asset_Manager {
     18        /**
     19         * Narrowest viewport bucket treated as a desktop layout.
     20         */
     21        private const DESKTOP_VIEWPORT = 1024;
     22
    1823        private const VARIANT_DIRECTORY = 'empirical-responsive-images/assets';
    1924        private const MAX_SOURCE_BYTES  = 20971520;
    … …  
    380385                        }
    381386
    382                         if ( ! empty( $format_candidates ) ) {
     387                        // A source that lists only some widths makes the browser pick from that
     388                        // subset, so a wide slot could get a narrow file. List every width or none.
     389                        if ( ! empty( $format_candidates ) && count( $format_candidates ) === count( $candidates ) ) {
    383390                                $formats[ $format ] = $this->build_srcset_from_candidates( $format_candidates );
    384391                        }
    … …  
    486493         *
    487494         * Unlike full/manual asset generation, this does not add the original source
    488          * width unless the requested width itself is capped to that width.
     495         * width unless the requested width itself is capped to that width. It does
     496         * make the original's alternate formats: front-end sources always list the
     497         * original width, and a format source is left out until every width has it.
    489498         *
    490499         * @param string $url   Image URL.
    … …  
    494503         */
    495504        public function generate_for_asset_width( string $url, int $width, bool $force = false ): array {
    496                 $result = $this->build_sources( $url, array( $width ), array(), true, $force, false );
    497 
    498                 return $this->summarize_generation_result( $result );
     505                $result   = $this->summarize_generation_result( $this->build_sources( $url, array( $width ), array(), true, $force, false ) );
     506                $original = $this->ensure_source_format_variants( $url, $force );
     507
     508                return array(
     509                        'generated' => $result['generated'] + $original['generated'],
     510                        'skipped'   => $result['skipped'] + $original['skipped'],
     511                        'errors'    => array_slice( array_unique( array_merge( $result['errors'], $original['errors'] ) ), 0, 10 ),
     512                );
     513        }
     514
     515        /**
     516         * Make the enabled alternate formats of the original asset at its own width.
     517         *
     518         * @param string $url   Image URL.
     519         * @param bool   $force Force rebuild.
     520         * @return array Generation counters and errors.
     521         */
     522        private function ensure_source_format_variants( string $url, bool $force ): array {
     523                $counts = array(
     524                        'generated' => 0,
     525                        'skipped'   => 0,
     526                        'errors'    => array(),
     527                );
     528                $source = $this->resolve_source( $url );
     529
     530                if ( empty( $source ) ) {
     531                        return $counts;
     532                }
     533
     534                foreach ( $this->settings->get_enabled_formats() as $format ) {
     535                        if ( ! $this->supports_format( $format ) || ! Alpha_Compat::can_use_format_for_source( $source['path'], $format ) ) {
     536                                continue;
     537                        }
     538
     539                        $result = $this->ensure_format_variant( $source['path'], $source, absint( $source['width'] ), $format, $force );
     540
     541                        if ( is_wp_error( $result ) ) {
     542                                $counts['errors'][] = $result->get_error_message();
     543                        } elseif ( ! empty( $result['generated'] ) ) {
     544                                ++$counts['generated'];
     545                        } else {
     546                                ++$counts['skipped'];
     547                        }
     548                }
     549
     550                return $counts;
    499551        }
    500552
    … …  
    741793
    742794                if ( method_exists( $editor, 'set_quality' ) ) {
    743                         $editor->set_quality( (int) apply_filters( 'empirical_responsive_images_output_quality', 82, $source['extension'], $source['path'] ) );
     795                        $editor->set_quality( (int) apply_filters( 'empirical_responsive_images_output_quality', Format_Generator::default_quality( $source['extension'] ), $source['extension'], $source['path'] ) );
    744796                }
    745797
    … …  
    797849
    798850                if ( method_exists( $editor, 'set_quality' ) ) {
    799                         $editor->set_quality( (int) apply_filters( 'empirical_responsive_images_output_quality', 82, $format, $candidate_path ) );
     851                        $editor->set_quality( (int) apply_filters( 'empirical_responsive_images_output_quality', Format_Generator::default_quality( $format ), $format, $candidate_path ) );
    800852                }
    801853
    … …  
    866918
    867919        /**
    868          * Build an empirical sizes attribute from observed CSS slots.
    869          *
    870          * @param array $slot_widths Slot width map.
     920         * Build a sizes value from viewport-bucketed slot widths.
     921         *
     922         * Viewports wider than any learned bucket would otherwise reuse the widest
     923         * learned slot. When only small viewports have been seen, a fallback (the
     924         * image's original sizes value) covers the rest instead of assuming a phone
     925         * layout on desktop.
     926         *
     927         * @param array  $slot_widths Slot widths keyed by viewport bucket.
     928         * @param string $fallback    Sizes value for viewports wider than every learned bucket.
    871929         * @return string
    872930         */
    873         public function build_empirical_sizes( array $slot_widths ): string {
     931        public function build_empirical_sizes( array $slot_widths, string $fallback = '' ): string {
    874932                $slots = array();
    875933
    … …  
    884942
    885943                if ( empty( $slots ) ) {
    886                         return '100vw';
     944                        return '' !== trim( $fallback ) ? trim( $fallback ) : '100vw';
    887945                }
    888946
    … …  
    895953                }
    896954
    897                 $parts[] = max( $slots ) . 'px';
     955                $fallback = trim( preg_replace( '/^auto\s*,\s*/i', '', trim( $fallback ) ) );
     956                $parts[]  = '' !== $fallback && max( array_keys( $slots ) ) < self::DESKTOP_VIEWPORT
     957                        ? $fallback
     958                        : max( $slots ) . 'px';
    898959
    899960                return implode( ', ', array_unique( $parts ) );
    … …  
    907968         */
    908969        private function supports_format( string $format ): bool {
    909                 require_once ABSPATH . 'wp-admin/includes/image.php';
     970                if ( ! function_exists( 'wp_image_editor_supports' ) ) {
     971                        require_once ABSPATH . 'wp-includes/media.php';
     972                }
    910973
    911974                return (bool) wp_image_editor_supports(
  • empirical-responsive-images/trunk/includes/class-background-optimizer.php

    r3780410 r3814342  
    362362                $slot_width     = absint( $job['slot_width'] ?? 0 );
    363363                $creates_width  = ! empty( $job['creates_width'] );
     364                $cover          = ! empty( $job['cover'] );
    364365
    365366                if ( '' === $token || $width < 1 || '' === $lease ) {
    … …  
    392393                        }
    393394
    394                         $result = $this->process_attachment( $target, $width, $viewport_width, $slot_width, $creates_width );
     395                        $result = $this->process_attachment( $target, $width, $viewport_width, $slot_width, $creates_width, $cover );
    395396                } elseif ( 'asset' === (string) ( $target['type'] ?? '' ) ) {
    396397                        if ( ! $this->settings->is_asset_processing_enabled() ) {
    … …  
    502503         * @param int   $slot_width     Coarse CSS slot bucket.
    503504         * @param bool  $creates_width  Whether evidence requested a new exact width.
     505         * @param bool  $cover          Whether the image is cropped to cover its box.
    504506         * @return array
    505507         */
    506         private function process_attachment( array $target, int $width, int $viewport_width, int $slot_width, bool $creates_width ): array {
     508        private function process_attachment( array $target, int $width, int $viewport_width, int $slot_width, bool $creates_width, bool $cover = false ): array {
    507509                $attachment_id    = absint( $target['attachment_id'] ?? 0 );
    508510                $required_formats = Visitor_Gap_Target::get_applicable_formats(
    … …  
    613615                        $viewport_width > 0
    614616                        && $slot_width > 0
    615                         && ! $this->observation_store->record_automatic_attachment_slot( $attachment_id, $viewport_width, $slot_width )
     617                        && ! $this->observation_store->record_automatic_attachment_slot(
     618                                $attachment_id,
     619                                $viewport_width,
     620                                $slot_width,
     621                                (string) ( $target['context'] ?? '' ),
     622                                $cover
     623                        )
    616624                ) {
    617625                        return array(
    … …  
    681689                if ( method_exists( $editor, 'set_quality' ) ) {
    682690                        $extension = strtolower( (string) pathinfo( $file, PATHINFO_EXTENSION ) );
    683                         $editor->set_quality( (int) apply_filters( 'empirical_responsive_images_output_quality', 82, $extension, $file ) );
     691                        $editor->set_quality( (int) apply_filters( 'empirical_responsive_images_output_quality', Format_Generator::default_quality( $extension ), $extension, $file ) );
    684692                }
    685693
  • empirical-responsive-images/trunk/includes/class-cache-compat.php

    r3626416 r3814342  
    6969                }
    7070
     71                self::purge_elementor_element_cache();
     72
    7173                // phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Third-party cache hooks must use their documented names.
    7274                do_action( 'litespeed_purge_url', $url );
    … …  
    102104                }
    103105
     106                self::purge_elementor_element_cache();
     107
    104108                // phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Third-party cache hooks must use their documented names.
    105109                do_action( 'litespeed_purge_all' );
    … …  
    108112                do_action( 'empirical_responsive_images_purge_all' );
    109113        }
     114
     115        /**
     116         * Drop Elementor's cached widget HTML so new picture markup is rendered.
     117         *
     118         * Elementor caches rendered elements in post meta for a day, which would keep
     119         * serving images without their new picture sources. Header and footer
     120         * templates are separate posts, so the whole cache is cleared; generated CSS
     121         * files are left alone.
     122         *
     123         * @return void
     124         */
     125        private static function purge_elementor_element_cache(): void {
     126                if ( ! defined( 'ELEMENTOR_VERSION' ) ) {
     127                        return;
     128                }
     129
     130                delete_post_meta_by_key( '_elementor_element_cache' );
     131        }
    110132}
  • empirical-responsive-images/trunk/includes/class-format-generator.php

    r3780410 r3814342  
    4242        public function __construct( Settings $settings ) {
    4343                $this->settings = $settings;
     44        }
     45
     46        /**
     47         * Default encoder quality for an output format or file extension.
     48         *
     49         * AVIF at 65 matches the visual distortion of WebP at 82 while staying
     50         * markedly smaller; AVIF at 82 can be larger than the JPEG it replaces.
     51         *
     52         * @param string $format Format or file extension.
     53         * @return int
     54         */
     55        public static function default_quality( string $format ): int {
     56                return 'avif' === strtolower( $format ) ? 65 : 82;
    4457        }
    4558
    … …  
    466479
    467480                if ( method_exists( $editor, 'set_quality' ) ) {
    468                         $editor->set_quality( (int) apply_filters( 'empirical_responsive_images_output_quality', 82, $format, $source_path ) );
     481                        $editor->set_quality( (int) apply_filters( 'empirical_responsive_images_output_quality', self::default_quality( $format ), $format, $source_path ) );
    469482                }
    470483
  • empirical-responsive-images/trunk/includes/class-observation-store.php

    r3780410 r3814342  
    312312
    313313        /**
    314          * Get bounded visitor-learned CSS slot widths for one attachment.
    315          *
    316          * @param int $attachment_id Attachment ID.
    317          * @return array
    318          */
    319         public function get_attachment_slot_widths( int $attachment_id ): array {
     314         * Get bounded visitor-learned CSS slot widths for one attachment placement.
     315         *
     316         * @param int    $attachment_id Attachment ID.
     317         * @param string $context       Placement context.
     318         * @return array
     319         */
     320        public function get_attachment_slot_widths( int $attachment_id, string $context = '' ): array {
     321                return $this->get_attachment_layout( $attachment_id, $context )['slot_widths'];
     322        }
     323
     324        /**
     325         * Get visitor-learned layout evidence for one attachment placement.
     326         *
     327         * Records learned before placements were tracked carry no context and are
     328         * only returned for an empty context, so they never resize other slots.
     329         *
     330         * @param int    $attachment_id Attachment ID.
     331         * @param string $context       Placement context.
     332         * @return array{slot_widths: array, cover: bool}
     333         */
     334        public function get_attachment_layout( int $attachment_id, string $context = '' ): array {
     335                $empty = array(
     336                        'slot_widths' => array(),
     337                        'cover'       => false,
     338                );
     339
    320340                if ( $attachment_id < 1 ) {
    321                         return array();
     341                        return $empty;
    322342                }
    323343
    324344                $data  = $this->get_data();
    325                 $key   = (string) $attachment_id;
     345                $key   = self::attachment_slot_key( $attachment_id, $context );
    326346                $entry = isset( $data['attachment_slots'][ $key ] ) && is_array( $data['attachment_slots'][ $key ] )
    327347                        ? $data['attachment_slots'][ $key ]
    328348                        : array();
    329349
    330                 return isset( $entry['slot_widths'] ) && is_array( $entry['slot_widths'] )
    331                         ? $this->sanitize_slot_width_map( $entry['slot_widths'] )
    332                         : array();
     350                return array(
     351                        'slot_widths' => isset( $entry['slot_widths'] ) && is_array( $entry['slot_widths'] )
     352                                ? $this->sanitize_slot_width_map( $entry['slot_widths'] )
     353                                : array(),
     354                        'cover'       => ! empty( $entry['cover'] ),
     355                );
     356        }
     357
     358        /**
     359         * Build the storage key for one attachment placement.
     360         *
     361         * @param int    $attachment_id Attachment ID.
     362         * @param string $context       Placement context.
     363         * @return string
     364         */
     365        public static function attachment_slot_key( int $attachment_id, string $context = '' ): string {
     366                $context = Visitor_Gap_Target::sanitize_context( $context );
     367
     368                return (string) absint( $attachment_id ) . ( '' !== $context ? '|' . $context : '' );
    333369        }
    334370
    … …  
    336372         * Check whether an attachment layout report would leave stored slots unchanged.
    337373         *
    338          * @param int $attachment_id  Attachment ID.
    339          * @param int $viewport_width Coarse viewport bucket.
    340          * @param int $slot_width     Coarse rendered slot bucket.
     374         * @param int    $attachment_id  Attachment ID.
     375         * @param int    $viewport_width Coarse viewport bucket.
     376         * @param int    $slot_width     Coarse rendered slot bucket.
     377         * @param string $context        Placement context.
     378         * @param bool   $cover          Whether the image is cropped to cover its box.
    341379         * @return bool
    342380         */
    343         public function attachment_layout_is_recorded( int $attachment_id, int $viewport_width, int $slot_width ): bool {
    344                 return $this->slot_map_covers( $this->get_attachment_slot_widths( $attachment_id ), $viewport_width, $slot_width );
     381        public function attachment_layout_is_recorded( int $attachment_id, int $viewport_width, int $slot_width, string $context = '', bool $cover = false ): bool {
     382                $layout = $this->get_attachment_layout( $attachment_id, $context );
     383
     384                return ( ! $cover || $layout['cover'] )
     385                        && $this->slot_map_covers( $layout['slot_widths'], $viewport_width, $slot_width );
    345386        }
    346387
    … …  
    533574         * Record one bounded visitor-learned attachment layout.
    534575         *
    535          * @param int $attachment_id Attachment ID.
    536          * @param int $viewport_width Coarse viewport bucket.
    537          * @param int $slot_width Coarse rendered slot bucket.
     576         * @param int    $attachment_id  Attachment ID.
     577         * @param int    $viewport_width Coarse viewport bucket.
     578         * @param int    $slot_width     Coarse rendered slot bucket.
     579         * @param string $context        Placement context.
     580         * @param bool   $cover          Whether the image is cropped to cover its box.
    538581         * @return bool Whether the exact layout record is durable.
    539582         */
    540         public function record_automatic_attachment_slot( int $attachment_id, int $viewport_width, int $slot_width ): bool {
     583        public function record_automatic_attachment_slot( int $attachment_id, int $viewport_width, int $slot_width, string $context = '', bool $cover = false ): bool {
    541584                $attachment_id  = absint( $attachment_id );
    542585                $viewport_width = min( 5120, absint( $viewport_width ) );
    … …  
    554597                        $data  = $this->get_data();
    555598                        $now   = time();
    556                         $key   = (string) $attachment_id;
     599                        $key   = self::attachment_slot_key( $attachment_id, $context );
    557600                        $entry = isset( $data['attachment_slots'][ $key ] ) && is_array( $data['attachment_slots'][ $key ] )
    558601                                ? $data['attachment_slots'][ $key ]
    … …  
    573616                        $entry['last_seen']   = $now;
    574617
     618                        if ( $cover ) {
     619                                $entry['cover'] = true;
     620                        }
     621
    575622                        $data['attachment_slots'][ $key ] = $entry;
    576623                        $data['attachment_slots']         = $this->trim_attachment_slots(
    … …  
    601648
    602649                try {
    603                         $data = $this->get_data();
    604 
    605                         if ( ! isset( $data['attachment_slots'][ $key ] ) ) {
     650                        $data    = $this->get_data();
     651                        $removed = false;
     652
     653                        foreach ( array_keys( $data['attachment_slots'] ) as $slot_key ) {
     654                                $slot_key = (string) $slot_key;
     655
     656                                if ( $slot_key === $key || 0 === strpos( $slot_key, $key . '|' ) ) {
     657                                        unset( $data['attachment_slots'][ $slot_key ] );
     658                                        $removed = true;
     659                                }
     660                        }
     661
     662                        if ( ! $removed ) {
    606663                                return;
    607664                        }
    608665
    609                         unset( $data['attachment_slots'][ $key ] );
    610666                        $data['updated_at'] = time();
    611667                        $this->persist_locked_data( $data );
  • empirical-responsive-images/trunk/includes/class-renderer.php

    r3780702 r3814342  
    252252
    253253                if ( false !== strpos( $html, 'data-empirical-responsive-images-picture-child' ) ) {
    254                         return $html;
     254                        if ( $in_picture ) {
     255                                return $html;
     256                        }
     257
     258                        // A sanitizer (Elementor prints image widgets through wp_kses) dropped the
     259                        // PICTURE wrapper but kept the IMG, so wrap it again.
     260                        $html = $this->unmark_picture_child_html( $html );
    255261                }
    256262
    … …  
    569575                }
    570576
     577                $context = Visitor_Gap_Target::attachment_context( $this->image_class_from_html( $html ) );
     578
    571579                if ( $apply_empirical_sizes ) {
    572                         $html = $this->apply_attachment_empirical_sizes_html( $html, $attachment_id );
     580                        $html = $this->apply_attachment_empirical_sizes_html( $html, $attachment_id, $context );
    573581                }
    574582
    … …  
    593601                }
    594602
    595                 $target = Visitor_Gap_Target::token_for_attachment( $attachment_id );
     603                $target = Visitor_Gap_Target::token_for_attachment( $attachment_id, $context );
    596604
    597605                if ( '' === $target ) {
    … …  
    674682         * Lazy images retain the standards-based auto keyword, which lets supporting
    675683         * browsers use the actual layout slot even when CSS uses %, vh, or calc().
     684         * Cover-cropped images drop it: auto describes the box, and the crop needs
     685         * a wider image than the box.
    676686         *
    677687         * @param string $html          Image HTML.
    678688         * @param int    $attachment_id Attachment ID.
    679          * @return string
    680          */
    681         private function apply_attachment_empirical_sizes_html( string $html, int $attachment_id ): string {
    682                 $slot_widths = $this->store->get_attachment_slot_widths( $attachment_id );
    683 
    684                 if ( empty( $slot_widths ) || ! class_exists( 'WP_HTML_Tag_Processor' ) ) {
     689         * @param string $context       Placement context.
     690         * @return string
     691         */
     692        private function apply_attachment_empirical_sizes_html( string $html, int $attachment_id, string $context = '' ): string {
     693                $layout = $this->store->get_attachment_layout( $attachment_id, $context );
     694
     695                if ( empty( $layout['slot_widths'] ) || ! class_exists( 'WP_HTML_Tag_Processor' ) ) {
    685696                        return $html;
    686697                }
    … …  
    688699                $processor = new \WP_HTML_Tag_Processor( $html );
    689700
    690                 if ( ! $processor->next_tag( array( 'tag_name' => 'IMG' ) ) || ! $this->responsive_sizes_are_plugin_manageable( $processor ) ) {
    691                         return $html;
    692                 }
    693 
    694                 $sizes   = $this->asset_manager->build_empirical_sizes( $slot_widths );
     701                if (
     702                        ! $processor->next_tag( array( 'tag_name' => 'IMG' ) )
     703                        || 'empirical' === (string) $processor->get_attribute( 'data-empirical-responsive-images-sizes' )
     704                        || ! $this->responsive_sizes_are_plugin_manageable( $processor )
     705                ) {
     706                        return $html;
     707                }
     708
     709                $sizes   = $this->asset_manager->build_empirical_sizes( $layout['slot_widths'], (string) $processor->get_attribute( 'sizes' ) );
    695710                $loading = strtolower( (string) $processor->get_attribute( 'loading' ) );
    696711
    697                 if ( 'lazy' === $loading && 0 !== strpos( ltrim( $sizes ), 'auto,' ) ) {
     712                if ( 'lazy' === $loading && ! $layout['cover'] && 0 !== strpos( ltrim( $sizes ), 'auto,' ) ) {
    698713                        $sizes = 'auto, ' . $sizes;
    699714                }
    … …  
    749764
    750765                $processor->set_attribute( 'data-empirical-responsive-images-picture-child', '1' );
     766
     767                return $processor->get_updated_html();
     768        }
     769
     770        /**
     771         * Remove the picture-child marker from an image that lost its wrapper.
     772         *
     773         * @param string $html Image HTML.
     774         * @return string
     775         */
     776        private function unmark_picture_child_html( string $html ): string {
     777                $processor = new \WP_HTML_Tag_Processor( $html );
     778
     779                if ( ! $processor->next_tag( array( 'tag_name' => 'IMG' ) ) ) {
     780                        return $html;
     781                }
     782
     783                $processor->remove_attribute( 'data-empirical-responsive-images-picture-child' );
    751784
    752785                return $processor->get_updated_html();
    … …  
    922955         * Build one alternate srcset.
    923956         *
     957         * Returns an empty string unless every candidate has an alternate: a source
     958         * that lists only some widths makes the browser pick from that subset, so an
     959         * image could be served from a far smaller file than its slot needs.
     960         *
    924961         * @param array  $image    Image attributes.
    925962         * @param array  $metadata Attachment metadata.
    … …  
    946983
    947984                        if ( '' === $alternate_url ) {
    948                                 continue;
     985                                return '';
    949986                        }
    950987
  • empirical-responsive-images/trunk/includes/class-visitor-gap-store.php

    r3780732 r3814342  
    498498                                                'viewport_width'       => $normalized['viewport_width'],
    499499                                                'slot_width'           => $normalized['slot_width'],
     500                                                'cover'                => ! empty( $normalized['cover'] ),
    500501                                                'creates_width'        => $normalized['creates_width'],
    501502                                                'confirmations'        => 0,
    … …  
    523524                                                $job[ $metric ] = absint( $normalized[ $metric ] );
    524525                                        }
     526                                }
     527
     528                                if ( ! empty( $normalized['cover'] ) ) {
     529                                        $job['cover'] = true;
    525530                                }
    526531
    … …  
    10801085                $viewport_width   = $this->normalize_metric( $gap['viewport'] ?? 0, 128, 5120 );
    10811086                $slot_width       = $this->normalize_metric( $gap['slot'] ?? 0, 16, 5120 );
    1082 
    1083                 if ( ! $this->layout_metrics_are_plausible( $reported_width, $viewport_width, $slot_width ) ) {
     1087                $cover            = 'attachment' === $type && true === ( $gap['cover'] ?? false );
     1088
     1089                if ( ! $this->layout_metrics_are_plausible( $reported_width, $viewport_width, $slot_width, $cover, $maximum ) ) {
    10841090                        $viewport_width = 0;
    10851091                        $slot_width     = 0;
    … …  
    10871093
    10881094                $has_layout_hint   = $viewport_width > 0 && $slot_width > 0;
     1095                $cover             = $cover && $has_layout_hint;
    10891096                $already_optimized = $is_current_protocol
    10901097                        ? (
    … …  
    11011108
    11021109                // A job that would change nothing still spends daily work and purges pages.
    1103                 if ( $files_ready && ( ! $has_layout_hint || $this->layout_is_recorded( $target, $work_width, $viewport_width, $slot_width ) ) ) {
     1110                if ( $files_ready && ( ! $has_layout_hint || $this->layout_is_recorded( $target, $work_width, $viewport_width, $slot_width, $cover ) ) ) {
    11041111                        return array();
    11051112                }
    … …  
    11181125                        'viewport_width'       => $viewport_width,
    11191126                        'slot_width'           => $slot_width,
     1127                        'cover'                => $cover,
    11201128                        'creates_width'        => 0 === $native_width,
    11211129                        'managed_widths'       => Visitor_Gap_Target::get_managed_widths( $target, $this->get_asset_manager() ),
    … …  
    11311139         * @param int   $viewport_width Coarse viewport bucket.
    11321140         * @param int   $slot_width     Coarse rendered slot bucket.
     1141         * @param bool  $cover          Whether the image is cropped to cover its box.
    11331142         * @return bool
    11341143         */
    1135         private function layout_is_recorded( array $target, int $width, int $viewport_width, int $slot_width ): bool {
     1144        private function layout_is_recorded( array $target, int $width, int $viewport_width, int $slot_width, bool $cover = false ): bool {
    11361145                if ( 'attachment' === (string) ( $target['type'] ?? '' ) ) {
    1137                         return $this->get_observation_store()->attachment_layout_is_recorded( absint( $target['attachment_id'] ?? 0 ), $viewport_width, $slot_width );
     1146                        return $this->get_observation_store()->attachment_layout_is_recorded(
     1147                                absint( $target['attachment_id'] ?? 0 ),
     1148                                $viewport_width,
     1149                                $slot_width,
     1150                                (string) ( $target['context'] ?? '' ),
     1151                                $cover
     1152                        );
    11381153                }
    11391154
    … …  
    11731188         * Reject anonymous layout hints that cannot describe the reported image.
    11741189         *
    1175          * @param int $physical_width Coarse physical-pixel target.
    1176          * @param int $viewport_width Coarse CSS viewport width.
    1177          * @param int $slot_width     Coarse CSS slot width.
     1190         * A cover-cropped image needs more width than its box, so its slot may
     1191         * exceed the viewport. A physical width capped by the source still counts.
     1192         *
     1193         * @param int  $physical_width Coarse physical-pixel target.
     1194         * @param int  $viewport_width Coarse CSS viewport width.
     1195         * @param int  $slot_width     Coarse CSS slot width.
     1196         * @param bool $cover          Whether the image is cropped to cover its box.
     1197         * @param int  $maximum        Largest width the target can reach.
    11781198         * @return bool
    11791199         */
    1180         private function layout_metrics_are_plausible( int $physical_width, int $viewport_width, int $slot_width ): bool {
     1200        private function layout_metrics_are_plausible( int $physical_width, int $viewport_width, int $slot_width, bool $cover = false, int $maximum = 0 ): bool {
    11811201                if ( $viewport_width < 1 || $slot_width < 1 || $physical_width < 1 ) {
    11821202                        return false;
    11831203                }
    11841204
    1185                 if ( $slot_width > $viewport_width + 32 ) {
     1205                if ( $slot_width > ( $cover ? $viewport_width * 3 : $viewport_width ) + 32 ) {
    11861206                        return false;
    11871207                }
    11881208
    1189                 return $physical_width >= (int) floor( $slot_width * 0.8 )
     1209                return (
     1210                        $physical_width >= (int) floor( $slot_width * 0.8 )
     1211                        || ( $maximum > 0 && $physical_width >= $maximum )
     1212                )
    11901213                        && $physical_width <= (int) ceil( $slot_width * 4.8 );
    11911214        }
  • empirical-responsive-images/trunk/includes/class-visitor-gap-target.php

    r3780410 r3814342  
    5151         * Create a signed target for one image attachment.
    5252         *
    53          * @param int $attachment_id Attachment ID.
     53         * The optional placement context keeps layout evidence for one image
     54         * apart from the same image shown elsewhere at another size.
     55         *
     56         * @param int    $attachment_id Attachment ID.
     57         * @param string $context       Placement context from attachment_context().
    5458         * @return string
    5559         */
    56         public static function token_for_attachment( int $attachment_id ): string {
     60        public static function token_for_attachment( int $attachment_id, string $context = '' ): string {
    5761                $attachment_id = absint( $attachment_id );
     62                $context       = self::sanitize_context( $context );
    5863
    5964                if ( $attachment_id < 1 ) {
    … …  
    6166                }
    6267
    63                 if ( isset( self::$attachment_tokens[ $attachment_id ] ) ) {
    64                         return self::$attachment_tokens[ $attachment_id ];
     68                $cache_key = $attachment_id . '|' . $context;
     69
     70                if ( isset( self::$attachment_tokens[ $cache_key ] ) ) {
     71                        return self::$attachment_tokens[ $cache_key ];
    6572                }
    6673
    … …  
    6875
    6976                if ( ! wp_attachment_is_image( $attachment_id ) || ! self::dimensions_are_safe( $dimensions ) ) {
    70                         self::$attachment_tokens[ $attachment_id ] = '';
     77                        self::$attachment_tokens[ $cache_key ] = '';
    7178                        return '';
    7279                }
    7380
    74                 $token                                     = self::sign_payload( 'attachment:' . $attachment_id );
    75                 self::$attachment_tokens[ $attachment_id ] = $token;
     81                $token                                 = self::sign_payload( 'attachment:' . $attachment_id . ( '' !== $context ? '|' . $context : '' ) );
     82                self::$attachment_tokens[ $cache_key ] = $token;
    7683
    7784                return $token;
     85        }
     86
     87        /**
     88         * Derive a placement context from an image tag's class list.
     89         *
     90         * Per-attachment and plugin-owned classes are ignored, so the same layout
     91         * slot maps to the same context on every page and for every attachment.
     92         *
     93         * @param string $classes Image class attribute.
     94         * @return string Twelve hex characters.
     95         */
     96        public static function attachment_context( string $classes ): string {
     97                $tokens = preg_split( '/\s+/', strtolower( trim( $classes ) ) );
     98                $tokens = array_filter(
     99                        is_array( $tokens ) ? $tokens : array(),
     100                        static function ( string $token ): bool {
     101                                return '' !== $token
     102                                        && 1 !== preg_match( '/^wp-image-[0-9]+$/', $token )
     103                                        && 0 !== strpos( $token, 'empirical-responsive-image' );
     104                        }
     105                );
     106                $tokens = array_values( array_unique( $tokens ) );
     107                sort( $tokens );
     108
     109                return substr( hash( 'sha256', implode( ' ', $tokens ) ), 0, 12 );
     110        }
     111
     112        /**
     113         * Validate one placement context.
     114         *
     115         * @param string $context Context.
     116         * @return string
     117         */
     118        public static function sanitize_context( string $context ): string {
     119                return 1 === preg_match( '/^[a-f0-9]{12}$/', $context ) ? $context : '';
    78120        }
    79121
    … …  
    503545         */
    504546        private static function resolve_attachment( string $raw_id ): array {
     547                $context = '';
     548
     549                if ( false !== strpos( $raw_id, '|' ) ) {
     550                        list( $raw_id, $context ) = explode( '|', $raw_id, 2 );
     551
     552                        if ( '' === self::sanitize_context( $context ) ) {
     553                                return array();
     554                        }
     555                }
     556
    505557                if ( ! preg_match( '/^[1-9][0-9]*$/', $raw_id ) ) {
    506558                        return array();
    … …  
    524576                        'key'              => 'attachment:' . $attachment_id,
    525577                        'attachment_id'    => $attachment_id,
     578                        'context'          => $context,
    526579                        'url'              => '',
    527580                        'source_width'     => absint( $dimensions['width'] ?? 0 ),
  • empirical-responsive-images/trunk/readme.txt

    r3780732 r3814342  
    55Tested up to: 7.1
    66Requires PHP: 7.4
    7 Stable tag: 0.3.16
     7Stable tag: 0.3.18
    88License: GPLv2 or later
    99License URI: https://www.gnu.org/licenses/gpl-2.0.html
    … …  
    168168== Changelog ==
    169169
     170= 0.3.18 =
     171* Sharper theme and plugin images in modern formats: a WebP or AVIF source now lists every width the image offers or is left out, so a wide slot no longer gets a narrow file. The background job also makes the original image in each format, so the source fills in on its own.
     172
     173= 0.3.17 =
     174* Sharper images where the same photo appears at different sizes, such as a large featured image that also shows as a small card thumbnail. Each placement now learns its own size instead of sharing one, so a thumbnail no longer makes the large image blurry.
     175* Sharper cropped images: photos cropped to fill their box (object-fit: cover) now get a file wide enough for the crop, not just for the box.
     176* Sizes learned on phones no longer apply to desktop screens until desktop visits have been measured.
     177* Image format sources always list every available width, so browsers no longer pick a tiny file from an incomplete list.
     178* Pages built with Elementor show new image formats right after they are generated.
     179* AVIF files are 15-20% smaller at the same visual quality.
     180
    170181= 0.3.16 =
    171182* Fewer server requests from visitors while the image queue is full: only one visitor in ten reports missing image sizes until the queue has room again. Logged-in editors still report every time.
Note: See TracChangeset for help on using the changeset viewer.