Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion js/gallery-block.asset.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@
'wp-element',
'wp-i18n'
),
'version' => 'f4dd3a6a83f3bee704eb'
'version' => '2c1d097420ba8c1ff297'
);
2 changes: 1 addition & 1 deletion js/gallery-block.js

Large diffs are not rendered by default.

89 changes: 67 additions & 22 deletions php/media/class-gallery.php
Original file line number Diff line number Diff line change
Expand Up @@ -183,24 +183,69 @@ public function enqueue_gallery_library() {
return;
}

$this->enqueue_library_script();

// Add the config once, even if the library was already enqueued
// without it (e.g. for the editor canvas on `enqueue_block_assets`).
if ( ! $this->has_inline_config() ) {
$json_config = wp_json_encode( $this->get_config() );
wp_add_inline_script( self::GALLERY_LIBRARY_HANDLE, "var CLD_GALLERY_CONFIG = {$json_config};" );
}

wp_enqueue_script(
'cloudinary-gallery-init',
$this->plugin->dir_url . 'js/gallery-init.js',
array( self::GALLERY_LIBRARY_HANDLE ),
$this->plugin->version,
true
);
}

/**
* Enqueue the Product Gallery library script.
*/
private function enqueue_library_script() {
wp_enqueue_script(
self::GALLERY_LIBRARY_HANDLE,
CLOUDINARY_ENDPOINTS_GALLERY,
array(),
$this->plugin->version,
true
);
}

$json_config = wp_json_encode( $this->get_config() );
wp_add_inline_script( self::GALLERY_LIBRARY_HANDLE, "var CLD_GALLERY_CONFIG = {$json_config};" );
/**
* Check whether the gallery config has been added to the library script.
*
* @return bool
*/
private function has_inline_config() {
$inline = wp_scripts()->get_data( self::GALLERY_LIBRARY_HANDLE, 'after' );

wp_enqueue_script(
'cloudinary-gallery-init',
$this->plugin->dir_url . 'js/gallery-init.js',
array( self::GALLERY_LIBRARY_HANDLE ),
$this->plugin->version,
true
return is_array( $inline ) && false !== strpos( implode( '', $inline ), 'var CLD_GALLERY_CONFIG' );
}

/**
* Get the delivery settings of the connected account for rendering galleries.
*
* Used both on the front end and for the block editor preview, so that
* both render with the same cloud name and custom domain settings.
*
* @return array
*/
protected function get_delivery_config() {
$config = array(
'cloudName' => $this->plugin->components['connect']->get_cloud_name(),
);

$credentials = $this->plugin->components['connect']->get_credentials();

if ( ! empty( $credentials['cname'] ) ) {
$config['secureDistribution'] = $credentials['cname'];
$config['privateCdn'] = true;
}

return $config;
}

/**
Expand Down Expand Up @@ -285,10 +330,13 @@ public function block_editor_scripts_styles() {
);

wp_add_inline_script( 'cloudinary-gallery-block-js', 'var CLD_REST_ENDPOINT = "/' . REST_API::BASE . '";', 'before' );

$delivery_config = wp_json_encode( $this->get_delivery_config() );
wp_add_inline_script( 'cloudinary-gallery-block-js', "var CLD_GALLERY_DELIVERY = {$delivery_config};", 'before' );
}

/**
* Enqueue the gallery block editor styles.
* Enqueue the gallery block editor styles and the gallery library for the editor canvas.
*
* Registered on `enqueue_block_assets` so the styles are injected into the
* iframed block editor correctly. As of WordPress 7.1 the post editor is
Expand All @@ -300,6 +348,15 @@ public function block_editor_styles() {
return;
}

// The gallery block preview is rendered inside the editor canvas, which
// is an iframe in the iframed block editor. The Product Gallery library
// must be loaded in that document too, since the widget looks up its
// container in its own document and validates its config against its
// own frame's globals.
if ( $this->maybe_enqueue_scripts() ) {
$this->enqueue_library_script();
}
Comment on lines +356 to +358

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (non-blocking): maybe_enqueue_scripts() and enqueue_gallery_library() both stop when wp_script_is( 'cld-gallery' ) is true. If enqueue_block_assets enqueues the library in the outer admin document before enqueue_block_editor_assets runs, CLD_GALLERY_CONFIG and gallery-init are not added. Then dot.dot( CLD_GALLERY_CONFIG ) throws for new blocks.

No core screen does this now (the post, site and widgets editors all fire enqueue_block_editor_assets before admin-header.php), so only a plugin that fires the hook early can cause it. Adding the inline config one time, independent of wp_script_is(), removes this coupling.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in cc6c808. enqueue_gallery_library() now adds CLD_GALLERY_CONFIG once, based on whether the script's inline data already contains it (has_inline_config()), instead of relying on wp_script_is(). I removed the "already enqueued" check from maybe_enqueue_scripts() as well. Enqueueing again is a no-op and the config is only added once, so enqueuing the library for the canvas first can no longer drop the config or gallery-init.


wp_enqueue_style(
'cloudinary-gallery-block-css',
$this->plugin->dir_url . 'css/gallery-block.css',
Expand Down Expand Up @@ -513,14 +570,7 @@ public function prepare_block_render( $content, $block ) {
$attributes['mediaAssets'][] = $attachment;
}

$attributes['cloudName'] = $this->plugin->components['connect']->get_cloud_name();

$credentials = $this->plugin->components['connect']->get_credentials();

if ( ! empty( $credentials['cname'] ) ) {
$attributes['secureDistribution'] = $credentials['cname'];
$attributes['privateCdn'] = true;
}
$attributes = array_merge( $attributes, $this->get_delivery_config() );

if ( ! empty( $attributes['customSettings'] ) ) {
if ( is_string( $attributes['customSettings'] ) && ! is_admin() ) {
Expand Down Expand Up @@ -595,11 +645,6 @@ function_exists( 'has_block' ) && has_block( 'cloudinary/gallery' )
}
}

// Bail enqueuing the script several times.
if ( wp_script_is( self::GALLERY_LIBRARY_HANDLE ) ) {
$can = false;
}

/**
* Filter the enqueue of gallery script.
*
Expand Down
147 changes: 127 additions & 20 deletions src/js/gallery-block/edit.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/* global cloudinaryGalleryApi CLD_GALLERY_CONFIG CLD_REST_ENDPOINT */
/* global CLD_GALLERY_CONFIG CLD_GALLERY_DELIVERY CLD_REST_ENDPOINT */

/**
* External dependencies
Expand All @@ -12,7 +12,7 @@ import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { Spinner } from '@wordpress/components';
import '@wordpress/components/build-style/style.css';
import { useEffect, useMemo, useState } from '@wordpress/element';
import { useEffect, useMemo, useRef, useState } from '@wordpress/element';
import {
InspectorControls,
MediaPlaceholder,
Expand All @@ -25,7 +25,12 @@ import {
import '../../css/gallery.scss';
import Controls from './controls';
import { ALLOWED_MEDIA_TYPES } from './options';
import { generateId, setupAttributesForRendering, showNotice } from './utils';
import {
generateId,
parseCustomSettings,
setupAttributesForRendering,
showNotice,
} from './utils';

const dot = new Dot( '_' );

Expand All @@ -40,6 +45,40 @@ const galleryWidgetConfig = ( config, container ) => ( {
zoom: false,
} );

/**
* Get the Product Gallery widget factory of a given window.
*
* @param {Window} win The window to look the widget up in.
* @return {((config: Object) => Object)|undefined} The `galleryWidget` factory, if loaded.
*/
const getGalleryWidget = ( win ) => win?.cloudinary?.galleryWidget;

/**
* Get the delivery settings of the connected Cloudinary account.
*
* The front end always applies them over the block attributes when it
* renders a gallery, so the preview does too. Blocks may have no cloud name
* saved (e.g. created outside the editor) or a stale one, and the custom
* domain settings are not block attributes at all.
*
* `CLD_GALLERY_DELIVERY` is built by the same PHP method the front end uses
* (`Gallery::get_delivery_config()`), so both render with the same values.
*
* @return {Object} The cloud name and custom domain settings.
*/
const getDeliveryConfig = () =>
'undefined' === typeof CLD_GALLERY_DELIVERY ? {} : CLD_GALLERY_DELIVERY;

/**
* Log that the gallery library is missing from the frame holding the
* preview, which otherwise leaves the block blank without any message.
*/
const warnLibraryMissing = () => {
console.warn(
'Cloudinary Gallery: the gallery library is not loaded in the editor canvas.'
);
};

// Prefix for the generated gallery container class. A literal prefix keeps
// the value a valid, unique CSS selector. Prior to the Block API v2 upgrade
// the block's `className` prop was used, but that prop is no longer passed to
Expand All @@ -49,6 +88,7 @@ const CONTAINER_PREFIX = 'cld-gallery-';
const Edit = ( { setAttributes, attributes, isSelected } ) => {
const [ errorMessage, setErrorMessage ] = useState( null );
const [ loading, setLoading ] = useState( false );
const containerRef = useRef( null );

const preparedAttributes = useMemo( () => {
// Do not override block settings with defaults on existing ones.
Expand Down Expand Up @@ -108,30 +148,94 @@ const Edit = ( { setAttributes, attributes, isSelected } ) => {
setErrorMessage( null );
}

if ( attributes.selectedImages.length ) {
let gallery;
const container = containerRef.current;

if ( ! attributes.selectedImages.length || ! container ) {
return;
}

// In the iframed block editor the container lives in the editor
// canvas iframe, so the widget of that frame has to be used: it looks
// the container up in its own document and validates its config with
// checks bound to its own frame.
const win = container.ownerDocument.defaultView || window;

// Recreate the config in the target frame, so that its objects pass
// the widget's validation there.
const toFrame = ( config ) =>
win === window
? config
: win.JSON.parse( JSON.stringify( config ) );

const { customSettings, ...attributesConfig } =
setupAttributesForRendering( attributes );
const config = { ...attributesConfig, ...getDeliveryConfig() };
const custom = parseCustomSettings( customSettings );

let gallery;
let cancelled = false;

const render = () => {
if ( cancelled ) {
return;
}

const { customSettings, ...config } =
setupAttributesForRendering( attributes );
const galleryWidget = getGalleryWidget( win );

// The library failed to load in this frame.
if ( ! galleryWidget ) {
warnLibraryMissing();
setLoading( false );
return;
}

try {
gallery = cloudinary.galleryWidget(
galleryWidgetConfig(
{ ...config, ...customSettings },
attributes.container
)
);
} catch {
gallery = cloudinary.galleryWidget(
galleryWidgetConfig( config, attributes.container )
// Shallow merge, matching how the front end applies Custom
// Settings over the block attributes. Fall back to the config
// without them if the widget rejects the merged one.
try {
gallery = galleryWidget(
toFrame(
galleryWidgetConfig(
{ ...config, ...custom },
attributes.container
)
)
);
} catch {
gallery = galleryWidget(
toFrame(
galleryWidgetConfig( config, attributes.container )
)
);
}

gallery.render();
} catch ( error ) {
console.error(
'Cloudinary Gallery: could not render the preview.',
error
);
} finally {
setLoading( false );
}
};

gallery.render();
if ( getGalleryWidget( win ) ) {
render();
} else if ( 'complete' !== win.document.readyState ) {
// The library may still be loading in the editor canvas.
win.addEventListener( 'load', render, { once: true } );
} else {
warnLibraryMissing();
setLoading( false );

return () => gallery.destroy();
}
Comment on lines +226 to 232

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (non-blocking): Gutenberg mounts the blocks in the canvas only after the iframe load event, so when the library fails to load in the canvas, the else branch is the one that runs. The preview then stays blank with no console message, which is the symptom this PR fixes. A console.warn here makes that case easy to find:

} else {
	// eslint-disable-next-line no-console
	console.warn( 'Cloudinary Gallery: the gallery library is not loaded in the editor canvas.' );
	setLoading( false );
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, a blank preview with no message is exactly what made this hard to track down. Added in cc6c808. The warning is in a small helper used in both places the library can turn out to be missing: this else branch, and inside render() when it runs from the load listener.


return () => {
cancelled = true;
win.removeEventListener( 'load', render );
gallery?.destroy();
};
}, [ errorMessage, attributes, setAttributes ] );

const hasImages = !! attributes.selectedImages.length;
Expand All @@ -157,7 +261,10 @@ const Edit = ( { setAttributes, attributes, isSelected } ) => {
return (
<div { ...blockProps }>
<>
<div className={ attributes.container }></div>
<div
ref={ containerRef }
className={ attributes.container }
></div>
<div className="wp-block-cloudinary-gallery">
<MediaPlaceholder
labels={ {
Expand Down
28 changes: 28 additions & 0 deletions src/js/gallery-block/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,31 @@ export const setupAttributesForRendering = ( attributes ) => {

return config;
};

/**
* Parse the block's Custom Settings into an object.
*
* The `customSettings` attribute is stored as JSON text. It is decoded the
* same way the front end does before being merged over the gallery config.
* Invalid JSON, or JSON that is not an object, is ignored.
*
* @param {string|Object} customSettings The Custom Settings attribute value.
* @return {Object} The parsed settings, or an empty object.
*/
export const parseCustomSettings = ( customSettings ) => {
let parsed = customSettings;

if ( 'string' === typeof customSettings ) {
try {
parsed = JSON.parse( customSettings );
} catch {
return {};
}
}

if ( ! parsed || 'object' !== typeof parsed || Array.isArray( parsed ) ) {
return {};
}

return parsed;
};
Loading
Loading