Making WordPress.org

Changeset 15011


Ignore:
Timestamp:
07/28/2026 08:06:48 AM (3 months ago)
Author:
thilinah
Message:

Plugin Directory: Improve screenshot lightbox captions

Props alexodiy, bor0, thilinah.
Closes ​https://github.com/WordPress/wordpress.org/pull/697.
Fixes #8289.

Location:
sites/trunk/wordpress.org/public_html/wp-content/plugins
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • sites/trunk/wordpress.org/public_html/wp-content/plugins/gallery-lightbox-enhancements/assets/lightbox-captions.css

    r14955 r15011  
    22 * Caption styling for the core image lightbox overlay.
    33 *
    4  * Polyfill for https://github.com/WordPress/gutenberg/pull/77477.
    5  *
    6  * Caption is mounted inside the visible `.lightbox-image-container`
    7  * (the JS picks the one whose <img> is on screen) so it pins to the
    8  * bottom edge of the picture frame, not the bottom of the viewport.
    9  * The visual treatment matches the PR #77477 reference exactly:
    10  * white text with a soft drop shadow on a barely-there bottom-up
    11  * scrim, anchored flush to the image.
     4 * The gallery keeps the core lightbox animation and navigation but
     5 * renders the caption as a dedicated bar beneath the active image.
     6 * This avoids competing with text-heavy screenshots while still keeping
     7 * short captions compact and visually centered.
    128 */
    139
    … …  
    2622
    2723/*
    28  * Do NOT set `.lightbox-image-container` to `position: relative`. Core
    29  * stacks its two containers (zoom-thumbnail + full-res) as absolutely
    30  * positioned, overlapping siblings; forcing them into normal flow stacks
    31  * the images vertically and renders the picture twice once both hold a
    32  * real image (e.g. plugin screenshots). The absolute container is already
    33  * the caption's containing block — no override needed.
     24 * The caption stays at the overlay level. Core already exposes the
     25 * active image dimensions through CSS custom properties on the overlay,
     26 * so the bar can align itself below the current image without changing
     27 * the lightbox container flow.
    3428 */
    3529
    36 .wp-lightbox-overlay .lightbox-image-container > figcaption.wp-lightbox-caption {
     30.wp-lightbox-overlay > figcaption.wp-lightbox-caption {
    3731        position: absolute;
    38         bottom: 0;
    39         left: 0;
    40         right: 0;
     32        top: var(--wporg-lightbox-caption-top, calc(50% + ( var(--wp--lightbox-container-height) / 2 ) + 0.5rem));
     33        left: 50%;
     34        transform: translateX(-50%);
    4135        z-index: 3000001;
     36        box-sizing: border-box;
     37        width: min(var(--wporg-lightbox-caption-width, var(--wp--lightbox-container-width)), calc(100% - 1rem));
     38        max-width: calc(100% - 1rem);
    4239        margin: 0;
    43         padding: 3.5em 1.25em 1em;
    44         color: #fff;
    45         text-align: start;
    46         font-size: 0.95rem;
    47         font-weight: 500;
    48         line-height: 1.45;
    49         letter-spacing: 0.005em;
    50         text-shadow: 0 1px 2px rgba(0, 0, 0, 0.55);
    51 
    52         /* Almost invisible scrim — present only to guarantee contrast on
    53            bright photos. The text-shadow does most of the legibility work. */
    54         background: linear-gradient(to top, rgba(0, 0, 0, 0.45) 0%, rgba(0, 0, 0, 0) 100%);
     40        padding: 0.75rem 1rem;
     41        color: #1e1e1e;
     42        text-align: center;
     43        font-size: 0.875rem;
     44        font-weight: 400;
     45        line-height: 1.4;
     46        letter-spacing: 0;
     47        text-shadow: none;
     48        background: rgba(255, 255, 255, 0.98);
     49        border: 0;
     50        border-radius: 12px;
     51        overflow-wrap: anywhere;
    5552        pointer-events: none;
    5653        opacity: 0;
    57         transition: opacity 160ms ease-in;
     54        transition: opacity 180ms ease-out;
    5855}
    5956
    60 .wp-lightbox-overlay.active .lightbox-image-container > figcaption.wp-lightbox-caption.has-caption {
     57.wp-lightbox-overlay.active > figcaption.wp-lightbox-caption.has-caption.is-ready {
    6158        opacity: 1;
    62         transition: opacity 220ms ease-out 200ms;
    6359}
    6460
    6561/* Hide the caption when there is no text to show. */
    66 .wp-lightbox-overlay .lightbox-image-container > figcaption.wp-lightbox-caption:not(.has-caption) {
     62.wp-lightbox-overlay > figcaption.wp-lightbox-caption:not(.has-caption) {
    6763        visibility: hidden;
     64}
     65
     66@media (min-width: 960px) {
     67
     68        .wp-lightbox-overlay > figcaption.wp-lightbox-caption {
     69                top: var(--wporg-lightbox-caption-top, calc(50% + ( var(--wp--lightbox-container-height) / 2 ) + 0.75rem));
     70                padding: 0.875rem 1.25rem;
     71                font-size: 0.95rem;
     72        }
     73}
     74
     75@media (max-width: 480px), (max-height: 700px) {
     76
     77        .wp-lightbox-overlay > figcaption.wp-lightbox-caption {
     78                top: var(--wporg-lightbox-caption-top, calc(50% + ( var(--wp--lightbox-container-height) / 2 ) + 0.375rem));
     79                padding: 0.625rem 0.875rem;
     80                font-size: 0.8125rem;
     81                border-radius: 10px;
     82        }
     83
    6884}
    6985
    7086@media (prefers-reduced-motion: reduce) {
    7187
    72         .wp-lightbox-overlay .lightbox-image-container > figcaption.wp-lightbox-caption,
    73         .wp-lightbox-overlay.active .lightbox-image-container > figcaption.wp-lightbox-caption.has-caption {
     88        .wp-lightbox-overlay > figcaption.wp-lightbox-caption,
     89        .wp-lightbox-overlay.active > figcaption.wp-lightbox-caption.has-caption {
    7490                transition: none;
    7591        }
  • sites/trunk/wordpress.org/public_html/wp-content/plugins/gallery-lightbox-enhancements/assets/lightbox-captions.js

    r14955 r15011  
    11/**
    2  * Augments the core lightbox overlay with a figcaption mounted inside
    3  * the *visible* enlarged-image container, so the caption sits flush
    4  * against the bottom edge of the picture frame — exactly the visual
    5  * contract of https://github.com/WordPress/gutenberg/pull/77477.
     2 * Augments the core lightbox overlay with a figcaption mounted at the
     3 * overlay level, beneath the active image.
    64 *
    7  * Why "visible": core renders two center-overlapping
    8  * `.lightbox-image-container` siblings. One holds the small thumbnail
    9  * used for the zoom animation hand-off, the other the full-resolution
    10  * image, which paints on top. We mount the caption into that top
    11  * container — the last one on screen — so it pins to the bottom of the
    12  * displayed picture and is not occluded by the enlarged image, then let
    13  * CSS anchor it to the absolutely-positioned container frame.
     5 * Core still owns the zoom animation, navigation buttons, and the
     6 * active image container geometry. This layer only reads the active
     7 * image's caption text, renders a dedicated caption bar below the
     8 * image, and switches the text alignment when the rendered caption
     9 * grows beyond a short-label treatment.
    1410 *
    1511 * `data-wp-text` / `data-wp-bind` attributes added after the
    … …  
    1915
    2016( function () {
     17        // Delay the first caption reveal until core's lightbox zoom sizing has settled.
     18        var CAPTION_REVEAL_DELAY = 430;
     19
     20        // Synthetic Plugin Directory screenshot IDs start here; ordinary images stay unmanaged.
     21        // Keep in sync with SYNTHETIC_ID_OFFSET in plugin-directory/shortcodes/class-screenshots.php.
     22        var SCREENSHOT_ID_OFFSET = 9000000;
     23
    2124        /**
    2225         * Whether the element overlaps the current viewport, even partially.
    … …  
    5861                        }
    5962                }
    60                 // Fallback: last container — wrong-spot caption beats no caption at all.
     63                // Fallback to the last container because a misplaced caption is better than none.
    6164                return containers[ containers.length - 1 ] || null;
    6265        }
    6366
    6467        /**
    65          * Moves the caption node into the target container if it isn't
    66          * already attached there.
    67          *
    68          * @param {HTMLElement|null} target  Container that should host the caption.
    69          * @param {HTMLElement}      caption The figcaption element to move.
    70          */
    71         function moveCaptionInto( target, caption ) {
    72                 if ( target && caption.parentNode !== target ) {
    73                         target.appendChild( caption );
    74                 }
     68         * Keeps the caption as a direct child of the overlay so it can sit in
     69         * a dedicated bar beneath the active image without disturbing core's
     70         * overlapping lightbox-image containers.
     71         *
     72         * @param {HTMLElement} overlay The `.wp-lightbox-overlay` element.
     73         * @param {HTMLElement} caption The figcaption element to move.
     74         */
     75        function moveCaptionIntoOverlay( overlay, caption ) {
     76                var insertBefore = overlay.querySelector( '.screen-reader-text, .scrim' );
     77                if ( caption.parentNode !== overlay ) {
     78                        overlay.insertBefore( caption, insertBefore || null );
     79                }
     80        }
     81
     82        /**
     83         * Extracts the attachment-style id from a lightbox image class.
     84         *
     85         * Screenshot gallery images use a high synthetic id range so they can be
     86         * distinguished from ordinary site images that should keep core behavior.
     87         *
     88         * @param {HTMLImageElement|null} img Lightbox image element.
     89         * @return {number}
     90         */
     91        function getImageBlockId( img ) {
     92                var match;
     93
     94                if ( ! img || ! img.className ) {
     95                        return 0;
     96                }
     97
     98                match = img.className.match( /\bwp-image-(\d+)\b/ );
     99
     100                if ( ! match ) {
     101                        return 0;
     102                }
     103
     104                return parseInt( match[1], 10 ) || 0;
     105        }
     106
     107        /**
     108         * Whether the current lightbox image belongs to the Plugin Directory
     109         * screenshots gallery rather than some other site lightbox.
     110         *
     111         * @param {HTMLImageElement|null} img Lightbox image element.
     112         * @return {boolean}
     113         */
     114        function isManagedImage( img ) {
     115                return getImageBlockId( img ) >= SCREENSHOT_ID_OFFSET;
     116        }
     117
     118        /**
     119         * Whether the active overlay currently shows a managed screenshot image.
     120         *
     121         * @param {HTMLElement} overlay The `.wp-lightbox-overlay` element.
     122         * @return {boolean}
     123         */
     124        function isManagedOverlay( overlay ) {
     125                var target = getVisibleContainer( overlay );
     126                var img    = target ? target.querySelector( 'img' ) : null;
     127
     128                return isManagedImage( img );
     129        }
     130
     131        /**
     132         * Returns a stable key for the active managed screenshot.
     133         *
     134         * @param {HTMLElement} overlay The `.wp-lightbox-overlay` element.
     135         * @return {string}
     136         */
     137        function getActiveImageKey( overlay ) {
     138                var target = getVisibleContainer( overlay );
     139                var img    = target ? target.querySelector( 'img' ) : null;
     140
     141                if ( ! isManagedImage( img ) ) {
     142                        return '';
     143                }
     144
     145                return [
     146                        getImageBlockId( img ),
     147                        img.currentSrc || img.src || img.getAttribute( 'src' ) || '',
     148                ].join( '|' );
     149        }
     150
     151        /**
     152         * Whether the lightbox overlay is currently active.
     153         *
     154         * @param {HTMLElement} overlay The `.wp-lightbox-overlay` element.
     155         * @return {boolean}
     156         */
     157        function isOverlayActive( overlay ) {
     158                return overlay.classList.contains( 'active' );
     159        }
     160
     161        /**
     162         * Whether the overlay has finished its current transition.
     163         *
     164         * @param {HTMLElement} overlay The `.wp-lightbox-overlay` element.
     165         * @return {boolean}
     166         */
     167        function isOverlaySettled( overlay ) {
     168                return overlay.dataset.wporgCaptionSettled === '1';
     169        }
     170
     171        /**
     172         * Marks the overlay as still transitioning.
     173         *
     174         * @param {HTMLElement} overlay The `.wp-lightbox-overlay` element.
     175         */
     176        function markOverlayUnsettled( overlay ) {
     177                overlay.dataset.wporgCaptionSettled = '0';
     178        }
     179
     180        /**
     181         * Marks the overlay as stable enough for geometry-sensitive caption work.
     182         *
     183         * @param {HTMLElement} overlay The `.wp-lightbox-overlay` element.
     184         */
     185        function markOverlaySettled( overlay ) {
     186                overlay.dataset.wporgCaptionSettled = '1';
     187        }
     188
     189        /**
     190         * Returns whether the first caption reveal is still waiting for core zoom.
     191         *
     192         * @param {HTMLElement} overlay The `.wp-lightbox-overlay` element.
     193         * @return {boolean}
     194         */
     195        function isCaptionRevealPending( overlay ) {
     196                return overlay.dataset.wporgCaptionRevealPending === '1';
     197        }
     198
     199        /**
     200         * Marks the caption as waiting for the first reveal.
     201         *
     202         * @param {HTMLElement} overlay The `.wp-lightbox-overlay` element.
     203         */
     204        function markCaptionRevealPending( overlay ) {
     205                overlay.dataset.wporgCaptionRevealPending = '1';
     206                overlay.dataset.wporgCaptionRevealKey     = getActiveImageKey( overlay );
     207        }
     208
     209        /**
     210         * Clears the first reveal waiting state.
     211         *
     212         * @param {HTMLElement} overlay The `.wp-lightbox-overlay` element.
     213         */
     214        function clearCaptionRevealPending( overlay ) {
     215                delete overlay.dataset.wporgCaptionRevealPending;
     216                delete overlay.dataset.wporgCaptionRevealKey;
     217        }
     218
     219        /**
     220         * Clears cached core lightbox dimensions so the next settled sync starts
     221         * from the current image rather than a stale transition frame.
     222         *
     223         * @param {HTMLElement} overlay The `.wp-lightbox-overlay` element.
     224         */
     225        function clearOverlayMetricCache( overlay ) {
     226                delete overlay.dataset.wporgLightboxBaseKey;
     227                delete overlay.dataset.wporgLightboxContainerWidth;
     228                delete overlay.dataset.wporgLightboxContainerHeight;
     229                delete overlay.dataset.wporgLightboxImageWidth;
     230                delete overlay.dataset.wporgLightboxImageHeight;
     231                delete overlay.dataset.wporgLightboxScale;
     232                delete overlay.dataset.wporgLightboxGeometryApplied;
     233        }
     234
     235        /**
     236         * Clears any pending deferred caption sync.
     237         *
     238         * @param {HTMLElement} overlay The `.wp-lightbox-overlay` element.
     239         */
     240        function clearDeferredSync( overlay ) {
     241                if ( overlay.wporgCaptionSyncTimer ) {
     242                        window.clearTimeout( overlay.wporgCaptionSyncTimer );
     243                        overlay.wporgCaptionSyncTimer = null;
     244                }
     245        }
     246
     247        /**
     248         * Clears any pending caption reveal.
     249         *
     250         * @param {HTMLElement} overlay The `.wp-lightbox-overlay` element.
     251         */
     252        function clearCaptionReveal( overlay ) {
     253                if ( overlay.wporgCaptionRevealTimer ) {
     254                        window.clearTimeout( overlay.wporgCaptionRevealTimer );
     255                        overlay.wporgCaptionRevealTimer = null;
     256                }
     257
     258                clearCaptionRevealPending( overlay );
     259        }
     260
     261        /**
     262         * Reveals the caption after layout-sensitive sizing has settled.
     263         *
     264         * Delaying the opacity flip avoids showing the caption while the
     265         * image and caption widths are still being recomputed.
     266         *
     267         * @param {HTMLElement} overlay The `.wp-lightbox-overlay` element.
     268         * @param {HTMLElement} caption The figcaption element.
     269         */
     270        function scheduleCaptionReveal( overlay, caption ) {
     271                clearCaptionReveal( overlay );
     272
     273                if ( ! isOverlayActive( overlay ) || ! caption.classList.contains( 'has-caption' ) ) {
     274                        return;
     275                }
     276
     277                markCaptionRevealPending( overlay );
     278
     279                overlay.wporgCaptionRevealTimer = window.setTimeout( function () {
     280                        overlay.wporgCaptionRevealTimer = null;
     281                        clearCaptionRevealPending( overlay );
     282
     283                        if ( ! isOverlayActive( overlay ) || ! caption.classList.contains( 'has-caption' ) ) {
     284                                return;
     285                        }
     286
     287                        caption.classList.add( 'is-ready' );
     288                }, 24 );
     289        }
     290
     291        /**
     292         * Hides the caption without touching the current lightbox geometry.
     293         *
     294         * We intentionally leave core sizing variables as-is during the close
     295         * animation so the zoom-back transition does not snap.
     296         *
     297         * @param {HTMLElement} overlay The `.wp-lightbox-overlay` element.
     298         * @param {HTMLElement} caption The figcaption element.
     299         */
     300        function hideCaption( overlay, caption ) {
     301                clearCaptionReveal( overlay );
     302                caption.classList.remove( 'has-caption', 'is-long-caption', 'is-ready' );
     303                caption.style.removeProperty( '--wporg-lightbox-caption-width' );
     304                caption.style.removeProperty( '--wporg-lightbox-caption-top' );
     305                caption.style.removeProperty( '--wporg-lightbox-caption-max-height' );
     306        }
     307
     308        /**
     309         * Returns the number of rendered text lines inside the caption.
     310         *
     311         * The CSS keeps a stable width for the caption bar, so the rendered
     312         * line count reflects the real lightbox layout on both desktop and
     313         * narrow mobile viewports.
     314         *
     315         * @param {HTMLElement} caption The figcaption element.
     316         * @return {number}
     317         */
     318        function getRenderedLineCount( caption ) {
     319                var styles = window.getComputedStyle( caption );
     320                var lineHeight = parseFloat( styles.lineHeight );
     321                var paddingTop = parseFloat( styles.paddingTop ) || 0;
     322                var paddingBottom = parseFloat( styles.paddingBottom ) || 0;
     323
     324                if ( ! lineHeight ) {
     325                        return 0;
     326                }
     327
     328                return Math.max(
     329                        0,
     330                        ( caption.getBoundingClientRect().height - paddingTop - paddingBottom ) / lineHeight
     331                );
     332        }
     333
     334        /**
     335         * Whether two rectangles overlap.
     336         *
     337         * @param {DOMRect} a First rectangle.
     338         * @param {DOMRect|null} b Second rectangle.
     339         * @return {boolean}
     340         */
     341        function rectsOverlap( a, b ) {
     342                return !! b && ! (
     343                        a.right <= b.left ||
     344                        a.left >= b.right ||
     345                        a.bottom <= b.top ||
     346                        a.top >= b.bottom
     347                );
     348        }
     349
     350        /**
     351         * Reads a numeric lightbox size variable off the overlay.
     352         *
     353         * @param {HTMLElement} overlay The `.wp-lightbox-overlay` element.
     354         * @param {string} variableName CSS custom property name.
     355         * @return {number}
     356         */
     357        function getOverlayMetric( overlay, variableName ) {
     358                var inlineValue = overlay.style.getPropertyValue( variableName );
     359                var computedValue = inlineValue || window.getComputedStyle( overlay ).getPropertyValue( variableName );
     360                var parsedValue = parseFloat( computedValue );
     361
     362                return Number.isFinite( parsedValue ) ? parsedValue : 0;
     363        }
     364
     365        /**
     366         * Stores the current lightbox image dimensions for the active image and viewport.
     367         *
     368         * Core recalculates these values when the user navigates between images or
     369         * resizes the viewport. We cache the current set so the caption logic can
     370         * temporarily shrink the visible image and still restore the original values
     371         * before the next measurement pass.
     372         *
     373         * @param {HTMLElement} overlay The `.wp-lightbox-overlay` element.
     374         * @param {HTMLImageElement|null} img The active lightbox image.
     375         */
     376        function cacheOverlayMetrics( overlay, img ) {
     377                var key = ( img ? img.getAttribute( 'src' ) || '' : '' ) +
     378                        '@' + window.innerWidth + 'x' + window.innerHeight;
     379
     380                if ( overlay.dataset.wporgLightboxBaseKey === key ) {
     381                        return;
     382                }
     383
     384                overlay.dataset.wporgLightboxBaseKey = key;
     385                overlay.dataset.wporgLightboxContainerWidth = String(
     386                        getOverlayMetric( overlay, '--wp--lightbox-container-width' )
     387                );
     388                overlay.dataset.wporgLightboxContainerHeight = String(
     389                        getOverlayMetric( overlay, '--wp--lightbox-container-height' )
     390                );
     391                overlay.dataset.wporgLightboxImageWidth = String(
     392                        getOverlayMetric( overlay, '--wp--lightbox-image-width' )
     393                );
     394                overlay.dataset.wporgLightboxImageHeight = String(
     395                        getOverlayMetric( overlay, '--wp--lightbox-image-height' )
     396                );
     397                overlay.dataset.wporgLightboxScale = String(
     398                        getOverlayMetric( overlay, '--wp--lightbox-scale' )
     399                );
     400        }
     401
     402        /**
     403         * Restores the lightbox image dimensions captured from core.
     404         *
     405         * @param {HTMLElement} overlay The `.wp-lightbox-overlay` element.
     406         */
     407        function resetOverlayMetrics( overlay ) {
     408                var metrics = {
     409                        '--wp--lightbox-container-width': overlay.dataset.wporgLightboxContainerWidth,
     410                        '--wp--lightbox-container-height': overlay.dataset.wporgLightboxContainerHeight,
     411                        '--wp--lightbox-image-width': overlay.dataset.wporgLightboxImageWidth,
     412                        '--wp--lightbox-image-height': overlay.dataset.wporgLightboxImageHeight,
     413                        '--wp--lightbox-scale': overlay.dataset.wporgLightboxScale,
     414                };
     415
     416                Object.keys( metrics ).forEach( function ( variableName ) {
     417                        if ( ! metrics[ variableName ] ) {
     418                                return;
     419                        }
     420
     421                        if ( variableName === '--wp--lightbox-scale' ) {
     422                                overlay.style.setProperty( variableName, metrics[ variableName ] );
     423                                return;
     424                        }
     425
     426                        overlay.style.setProperty( variableName, metrics[ variableName ] + 'px' );
     427                } );
     428        }
     429
     430        /**
     431         * Reads the rendered image dimensions from the active lightbox image.
     432         *
     433         * @param {HTMLElement} overlay The `.wp-lightbox-overlay` element.
     434         * @param {HTMLImageElement|null} img The active lightbox image.
     435         * @return {{width:number,height:number}}
     436         */
     437        function getRenderedImageMetrics( overlay, img ) {
     438                var overlayWidth = getOverlayMetric( overlay, '--wp--lightbox-image-width' );
     439                var overlayHeight = getOverlayMetric( overlay, '--wp--lightbox-image-height' );
     440                var imageRect = img ? img.getBoundingClientRect() : null;
     441
     442                if ( overlayWidth && overlayHeight ) {
     443                        return {
     444                                width: overlayWidth,
     445                                height: overlayHeight,
     446                        };
     447                }
     448
     449                return {
     450                        width: imageRect ? imageRect.width : getOverlayMetric( overlay, '--wp--lightbox-image-width' ),
     451                        height: imageRect ? imageRect.height : getOverlayMetric( overlay, '--wp--lightbox-image-height' ),
     452                };
     453        }
     454
     455        /**
     456         * Whether the active screenshot is portrait-shaped or otherwise very narrow.
     457         *
     458         * Those screenshots already get a wider caption bar and need the fitting
     459         * math to use the intended lightbox geometry, not the current animation
     460         * frame, otherwise the open transition can visibly jump mid-flight.
     461         *
     462         * @param {HTMLElement} overlay The `.wp-lightbox-overlay` element.
     463         * @param {HTMLImageElement|null} img The active lightbox image.
     464         * @return {boolean}
     465         */
     466        function isPortraitOrNarrowImage( overlay, img ) {
     467                var imageMetrics = getRenderedImageMetrics( overlay, img );
     468                var aspectRatio = imageMetrics.width ? imageMetrics.height / imageMetrics.width : 0;
     469
     470                return aspectRatio > 1.2 || ( imageMetrics.width > 0 && imageMetrics.width < 320 );
     471        }
     472
     473        /**
     474         * Shrinks the lightbox image proportionally when a below-image caption would
     475         * otherwise fall out of the viewport or into the navigation controls.
     476         *
     477         * @param {HTMLElement} overlay The `.wp-lightbox-overlay` element.
     478         * @param {HTMLElement} caption The figcaption element.
     479         * @param {HTMLImageElement|null} img The active lightbox image.
     480         */
     481        function fitCaptionWithinViewport( overlay, caption, img ) {
     482                var bottomPadding = 16;
     483                var attempt = 0;
     484                var minContainerScale = 0.5;
     485                var nextButton = overlay.querySelector( '.wp-lightbox-navigation-button-next' );
     486                var prevButton = overlay.querySelector( '.wp-lightbox-navigation-button-prev' );
     487                var maxCaptionBottom = window.innerHeight - bottomPadding;
     488                var nextRect = nextButton ? nextButton.getBoundingClientRect() : null;
     489                var prevRect = prevButton ? prevButton.getBoundingClientRect() : null;
     490                var isPortraitOrNarrow = isPortraitOrNarrowImage( overlay, img );
     491                var overflow;
     492
     493                if ( isPortraitOrNarrow ) {
     494                        if ( window.innerWidth <= 480 ) {
     495                                minContainerScale = 0.2;
     496                        } else if ( window.innerWidth <= 960 || window.innerHeight <= 700 ) {
     497                                minContainerScale = 0.24;
     498                        } else {
     499                                minContainerScale = 0.28;
     500                        }
     501                } else if ( window.innerWidth <= 480 ) {
     502                        minContainerScale = 0.28;
     503                } else if ( window.innerWidth <= 960 || window.innerHeight <= 700 ) {
     504                        minContainerScale = 0.35;
     505                }
     506
     507                overflow = Math.max(
     508                        0,
     509                        caption.getBoundingClientRect().bottom - maxCaptionBottom
     510                );
     511
     512                if ( rectsOverlap( caption.getBoundingClientRect(), nextRect ) ) {
     513                        overflow = Math.max(
     514                                overflow,
     515                                caption.getBoundingClientRect().bottom - ( nextRect.top - 12 )
     516                        );
     517                }
     518
     519                if ( rectsOverlap( caption.getBoundingClientRect(), prevRect ) ) {
     520                        overflow = Math.max(
     521                                overflow,
     522                                caption.getBoundingClientRect().bottom - ( prevRect.top - 12 )
     523                        );
     524                }
     525
     526                while ( overflow > 0 && attempt < 8 ) {
     527                        var currentContainerWidth = getOverlayMetric( overlay, '--wp--lightbox-container-width' );
     528                        var currentContainerHeight = getOverlayMetric( overlay, '--wp--lightbox-container-height' );
     529                        var currentImageWidth = getOverlayMetric( overlay, '--wp--lightbox-image-width' );
     530                        var currentImageHeight = getOverlayMetric( overlay, '--wp--lightbox-image-height' );
     531                        var currentLightboxScale = getOverlayMetric( overlay, '--wp--lightbox-scale' );
     532                        var minContainerHeight = parseFloat( overlay.dataset.wporgLightboxContainerHeight ) * minContainerScale;
     533                        var newContainerHeight = Math.max(
     534                                minContainerHeight,
     535                                currentContainerHeight - ( overflow * 2 )
     536                        );
     537                        var scale;
     538
     539                        if (
     540                                ! currentContainerWidth ||
     541                                ! currentContainerHeight ||
     542                                ! currentImageWidth ||
     543                                ! currentImageHeight ||
     544                                ! currentLightboxScale ||
     545                                newContainerHeight === currentContainerHeight
     546                        ) {
     547                                return;
     548                        }
     549
     550                        scale = newContainerHeight / currentContainerHeight;
     551
     552                        // These are core Image block lightbox internals set by setOverlayStyles().
     553                        // Core rewrites them whenever the lightbox opens, navigates, or resizes.
     554                        // See https://github.com/WordPress/gutenberg/blob/trunk/packages/block-library/src/image/view.js#L585-L597.
     555                        overlay.style.setProperty(
     556                                '--wp--lightbox-container-width',
     557                                ( currentContainerWidth * scale ) + 'px'
     558                        );
     559                        overlay.style.setProperty(
     560                                '--wp--lightbox-container-height',
     561                                newContainerHeight + 'px'
     562                        );
     563                        overlay.style.setProperty(
     564                                '--wp--lightbox-image-width',
     565                                ( currentImageWidth * scale ) + 'px'
     566                        );
     567                        overlay.style.setProperty(
     568                                '--wp--lightbox-image-height',
     569                                ( currentImageHeight * scale ) + 'px'
     570                        );
     571                        overlay.style.setProperty(
     572                                '--wp--lightbox-scale',
     573                                currentLightboxScale / scale
     574                        );
     575
     576                        overflow = Math.max(
     577                                0,
     578                                caption.getBoundingClientRect().bottom - maxCaptionBottom
     579                        );
     580
     581                        if ( rectsOverlap( caption.getBoundingClientRect(), nextRect ) ) {
     582                                overflow = Math.max(
     583                                        overflow,
     584                                        caption.getBoundingClientRect().bottom - ( nextRect.top - 12 )
     585                                );
     586                        }
     587
     588                        if ( rectsOverlap( caption.getBoundingClientRect(), prevRect ) ) {
     589                                overflow = Math.max(
     590                                        overflow,
     591                                        caption.getBoundingClientRect().bottom - ( prevRect.top - 12 )
     592                                );
     593                        }
     594
     595                        attempt++;
     596                }
     597        }
     598
     599        /**
     600         * Keeps portrait and very narrow screenshots readable by letting a
     601         * text-heavy caption grow wider than the rendered image.
     602         *
     603         * Short labels stay aligned to the image width. Longer copy can use a
     604         * wider bar when the screenshot itself is too narrow to carry a
     605         * paragraph-shaped caption comfortably.
     606         *
     607         * @param {HTMLElement} overlay The `.wp-lightbox-overlay` element.
     608         * @param {HTMLElement} caption The figcaption element.
     609         * @param {HTMLImageElement|null} img The active lightbox image.
     610         * @param {string} text The caption text.
     611         * @param {boolean} promoteForLongCaption Whether a measured paragraph
     612         *                                        caption should get extra width.
     613         */
     614        function applyCaptionWidth( overlay, caption, img, text, promoteForLongCaption ) {
     615                var imageMetrics = getRenderedImageMetrics( overlay, img );
     616                var imageWidth = imageMetrics.width;
     617                var viewportWidth = Math.max( 0, window.innerWidth - 16 );
     618                var isPortraitOrNarrow = isPortraitOrNarrowImage( overlay, img );
     619                var preferredWidth = imageWidth;
     620                var relaxedWidth;
     621
     622                if ( ! imageWidth || ! viewportWidth ) {
     623                        caption.style.removeProperty( '--wporg-lightbox-caption-width' );
     624                        return;
     625                }
     626
     627                if ( isPortraitOrNarrow && ( text.length > 60 || promoteForLongCaption ) ) {
     628                        relaxedWidth = Math.max(
     629                                imageWidth,
     630                                Math.min( 420, imageWidth * 2 ),
     631                                300
     632                        );
     633
     634                        if ( promoteForLongCaption ) {
     635                                relaxedWidth = Math.max(
     636                                        relaxedWidth,
     637                                        Math.min( 460, imageWidth * 2.3 ),
     638                                        340
     639                                );
     640                        }
     641
     642                        preferredWidth = Math.min( viewportWidth, relaxedWidth );
     643                }
     644
     645                caption.style.setProperty( '--wporg-lightbox-caption-width', preferredWidth + 'px' );
     646        }
     647
     648        /**
     649         * Syncs caption width and long-text detection against the current
     650         * rendered image size.
     651         *
     652         * The image may shrink after viewport-fitting, so this pass can be
     653         * repeated after geometry changes to keep the final caption width in
     654         * step with the visible screenshot.
     655         *
     656         * @param {HTMLElement} overlay The `.wp-lightbox-overlay` element.
     657         * @param {HTMLElement} caption The figcaption element.
     658         * @param {HTMLImageElement|null} img The active lightbox image.
     659         * @param {string} text The caption text.
     660         */
     661        function syncCaptionPresentation( overlay, caption, img, text ) {
     662                var isLongCaption;
     663
     664                caption.classList.remove( 'is-long-caption' );
     665                applyCaptionWidth( overlay, caption, img, text, false );
     666
     667                isLongCaption = isParagraphCaption( text, caption );
     668                if ( isLongCaption ) {
     669                        applyCaptionWidth( overlay, caption, img, text, true );
     670                        isLongCaption = isParagraphCaption( text, caption );
     671                }
     672
     673                caption.classList.toggle( 'is-long-caption', isLongCaption );
     674        }
     675
     676        /**
     677         * Decides whether the caption should be treated as long-form copy.
     678         *
     679         * Short product-style captions keep the same centered treatment even if a
     680         * narrow mobile viewport wraps them. Longer descriptions still keep that
     681         * centered treatment, but we track them separately for width heuristics.
     682         *
     683         * @param {string} text The caption text.
     684         * @param {HTMLElement} caption The figcaption element.
     685         * @return {boolean}
     686         */
     687        function isParagraphCaption( text, caption ) {
     688                var renderedLineCount = getRenderedLineCount( caption );
     689
     690                return renderedLineCount > 2.5 || ( text.length > 220 && renderedLineCount > 2 );
     691        }
     692
     693        /**
     694         * Reveals the caption after core's opening zoom has finished.
     695         *
     696         * Geometry is applied before the first visible zoom frame so the image
     697         * does not jump at the end of the animation. Text waits until the zoom
     698         * completes, keeping the opening motion focused on the screenshot.
     699         *
     700         * @param {HTMLElement} overlay The `.wp-lightbox-overlay` element.
     701         */
     702        function scheduleDeferredSync( overlay ) {
     703                clearDeferredSync( overlay );
     704
     705                if ( ! isOverlayActive( overlay ) ) {
     706                        return;
     707                }
     708
     709                markCaptionRevealPending( overlay );
     710
     711                overlay.wporgCaptionSyncTimer = window.setTimeout( function () {
     712                        overlay.wporgCaptionSyncTimer = null;
     713                        markOverlaySettled( overlay );
     714                        scheduleCaptionReveal( overlay, ensureCaption( overlay ) );
     715                }, CAPTION_REVEAL_DELAY );
     716        }
     717
     718        /**
     719         * Delays the caption reveal until core finishes the opening animation.
     720         *
     721         * @param {HTMLElement} overlay       The `.wp-lightbox-overlay` element.
     722         * @param {boolean}     forceGeometry Whether to recalculate during a pending reveal.
     723         */
     724        function requestSettledSync( overlay, forceGeometry ) {
     725                var shouldSyncImmediately = isOverlaySettled( overlay );
     726
     727                if ( ! isOverlayActive( overlay ) ) {
     728                        clearDeferredSync( overlay );
     729                        markOverlayUnsettled( overlay );
     730                        clearOverlayMetricCache( overlay );
     731                        hideCaption( overlay, ensureCaption( overlay ) );
     732                        return;
     733                }
     734
     735                if ( ! isManagedOverlay( overlay ) ) {
     736                        clearDeferredSync( overlay );
     737                        markOverlayUnsettled( overlay );
     738                        clearOverlayMetricCache( overlay );
     739
     740                        if ( overlay.querySelector( 'figcaption.wp-lightbox-caption' ) ) {
     741                                hideCaption( overlay, ensureCaption( overlay ) );
     742                        }
     743
     744                        return;
     745                }
     746
     747                if ( isCaptionRevealPending( overlay ) ) {
     748                        var pendingKey = overlay.dataset.wporgCaptionRevealKey || '';
     749                        var currentKey = getActiveImageKey( overlay );
     750
     751                        if ( currentKey === pendingKey && ! forceGeometry ) {
     752                                return;
     753                        }
     754
     755                        clearCaptionReveal( overlay );
     756                }
     757
     758                if ( shouldSyncImmediately ) {
     759                        clearDeferredSync( overlay );
     760                        clearCaptionReveal( overlay );
     761                        clearOverlayMetricCache( overlay );
     762                        syncCaption( overlay, true );
     763                        return;
     764                }
     765
     766                clearOverlayMetricCache( overlay );
     767                markOverlaySettled( overlay );
     768                syncCaption( overlay, false );
     769                markOverlayUnsettled( overlay );
     770                scheduleDeferredSync( overlay );
    75771        }
    76772
    … …  
    79775         *
    80776         * The caption lives at the overlay level so it survives container
    81          * shuffles between open / close. It is moved into whichever
    82          * container is visible at sync time.
     777         * shuffles between open / close and can be positioned outside the
     778         * image frame.
    83779         *
    84780         * @param {HTMLElement} overlay The `.wp-lightbox-overlay` element.
    … …  
    96792
    97793        /**
    98          * Reads the active image's alt text and writes it into the caption,
    99          * mounted under the visible container.
    100          *
    101          * @param {HTMLElement} overlay The `.wp-lightbox-overlay` element.
    102          */
    103         function syncCaption( overlay ) {
    104                 var caption = ensureCaption( overlay );
     794         * Reads the active image's alt text and writes it into the caption
     795         * bar below the visible image container.
     796         *
     797         * @param {HTMLElement} overlay The `.wp-lightbox-overlay` element.
     798         * @param {boolean} keepReady Whether an already-visible caption should stay visible.
     799         */
     800        function syncCaption( overlay, keepReady ) {
    105801                var target  = getVisibleContainer( overlay );
    106                 moveCaptionInto( target, caption );
    107 
    108802                // Read alt off the visible image (the off-screen sibling holds stale state).
    109803                var img  = target ? target.querySelector( 'img' ) : null;
    110804                var text = img ? img.getAttribute( 'alt' ) || '' : '';
     805                var caption;
     806
     807                if ( ! isOverlayActive( overlay ) ) {
     808                        clearDeferredSync( overlay );
     809                        markOverlayUnsettled( overlay );
     810                        clearOverlayMetricCache( overlay );
     811                        caption = overlay.querySelector( 'figcaption.wp-lightbox-caption' );
     812
     813                        if ( caption ) {
     814                                hideCaption( overlay, caption );
     815                        }
     816
     817                        return;
     818                }
     819
     820                if ( ! isManagedImage( img ) ) {
     821                        clearDeferredSync( overlay );
     822                        markOverlayUnsettled( overlay );
     823                        clearOverlayMetricCache( overlay );
     824                        caption = overlay.querySelector( 'figcaption.wp-lightbox-caption' );
     825
     826                        if ( caption ) {
     827                                hideCaption( overlay, caption );
     828                        }
     829
     830                        return;
     831                }
     832
     833                caption = ensureCaption( overlay );
     834
     835                if ( ! isOverlayActive( overlay ) ) {
     836                        clearDeferredSync( overlay );
     837                        markOverlayUnsettled( overlay );
     838                        clearOverlayMetricCache( overlay );
     839                        hideCaption( overlay, caption );
     840                        return;
     841                }
     842
     843                moveCaptionIntoOverlay( overlay, caption );
    111844                caption.textContent = text;
    112                 caption.classList.toggle( 'has-caption', text !== '' );
     845
     846                if ( text === '' ) {
     847                        hideCaption( overlay, caption );
     848                        return;
     849                }
     850
     851                caption.classList.add( 'has-caption' );
     852                if ( ! keepReady ) {
     853                        caption.classList.remove( 'is-ready' );
     854                }
     855
     856                if ( ! isOverlaySettled( overlay ) ) {
     857                        return;
     858                }
     859
     860                if ( overlay.dataset.wporgLightboxGeometryApplied !== '1' ) {
     861                        cacheOverlayMetrics( overlay, img );
     862                        resetOverlayMetrics( overlay );
     863                        syncCaptionPresentation( overlay, caption, img, text );
     864                        fitCaptionWithinViewport( overlay, caption, img );
     865                        syncCaptionPresentation( overlay, caption, img, text );
     866                        overlay.dataset.wporgLightboxGeometryApplied = '1';
     867                }
     868
     869                syncCaptionPresentation( overlay, caption, img, text );
     870
     871                if ( keepReady ) {
     872                        caption.classList.add( 'is-ready' );
     873                }
    113874        }
    114875
    … …  
    122883                }
    123884
    124                 syncCaption( overlay );
     885                markOverlayUnsettled( overlay );
     886                requestSettledSync( overlay );
    125887
    126888                /*
    … …  
    131893                imgs.forEach( function ( img ) {
    132894                        var observer = new MutationObserver( function () {
    133                                 syncCaption( overlay );
     895                                requestSettledSync( overlay );
    134896                        } );
    135897                        observer.observe( img, { attributes: true, attributeFilter: [ 'alt', 'src' ] } );
    … …  
    141903                 */
    142904                var classObserver = new MutationObserver( function () {
    143                         syncCaption( overlay );
     905                        requestSettledSync( overlay );
    144906                } );
    145907                classObserver.observe( overlay, { attributes: true, attributeFilter: [ 'class' ] } );
     908
     909                window.addEventListener( 'resize', function () {
     910                        requestSettledSync( overlay, true );
     911                } );
     912
     913                if ( window.visualViewport ) {
     914                        window.visualViewport.addEventListener( 'resize', function () {
     915                                requestSettledSync( overlay, true );
     916                        } );
     917                }
    146918        }
    147919
  • sites/trunk/wordpress.org/public_html/wp-content/plugins/plugin-directory/shortcodes/class-screenshots.php

    r14994 r15011  
    5555         * key in `state.metadata.{id}`, so we mint one from this offset plus the
    5656         * screenshot index.
     57         * Keep in sync with `SCREENSHOT_ID_OFFSET` in
     58         * `gallery-lightbox-enhancements/assets/lightbox-captions.js`.
    5759         *
    5860         * @var int
Note: See TracChangeset for help on using the changeset viewer.