Skip to content

Fix the Cloudinary Gallery block preview in the iframed editor - #1368

Open
gabrielcld2 wants to merge 5 commits into
developfrom
fix/WPP-1246-1247-gallery-editor-preview
Open

gabrielcld2 wants to merge 5 commits into
developfrom
fix/WPP-1246-1247-gallery-editor-preview

Conversation

@gabrielcld2

@gabrielcld2 gabrielcld2 commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes two issues with the Cloudinary Gallery block preview in the block editor.

The issues

The preview stays blank in the iframed editor. With the editor canvas rendered in an iframe (always the case as of WordPress 7.1), images picked for a Cloudinary Gallery block are saved and the published page shows the gallery, but the block in the editor stays on the empty Upload / Media Library placeholder, with no console error.

  • The Product Gallery library (cld-gallery) was only enqueued in the outer admin document.
  • The block's container is rendered inside the editor-canvas iframe, so the widget looked the selector up in the wrong document and silently drew nothing.
  • Passing the container element itself doesn't work either: the widget validates its config with checks bound to its own frame and rejects objects created in another one.

The preview ignores the block's Custom Settings. Custom Settings applied on the published page but never in the editor preview.

  • customSettings is stored as JSON text, and the editor spread that string into the config, adding one numbered key per character.
  • The widget rejected that config, and the fallback rendered without the custom settings.
  • The front end decodes the JSON before merging it, so only the page got them.

The solution

  • Gallery::block_editor_styles() already runs on enqueue_block_assets, which WordPress uses to collect the editor canvas assets. It now also enqueues the gallery library there, using the existing maybe_enqueue_scripts() check and cloudinary_enqueue_gallery_script filter. CLD_GALLERY_CONFIG is now added once based on the script's inline data, rather than skipped whenever the library is already enqueued, so enqueuing the library for the canvas first can't drop it. As a result, maybe_enqueue_scripts() no longer returns false just because the library is already enqueued.
  • The block's Edit takes a ref on the container and renders with the galleryWidget of the window that holds it. When that is another frame, the config is rebuilt with that frame's JSON.parse so it passes the widget's validation. The container stays a CSS selector, resolved in the widget's own document. If the library is still loading in the canvas, rendering waits for the frame's load event.
  • The preview now always uses the connected account's cloud name and custom domain settings, as the front end does in prepare_block_render(). Both now get them from one method, Gallery::get_delivery_config(), passed to the editor as CLD_GALLERY_DELIVERY. Before, they were only set on new blocks: a block with no or a stale cloudName (e.g. created outside the editor) previewed broken images, and existing blocks ignored the custom domain. This only affects what is rendered; the saved block is unchanged.
  • In a non-iframed editor the container's window is the main window, so the behaviour is unchanged.
  • A new parseCustomSettings() util decodes Custom Settings (invalid JSON, or JSON that isn't an object, is ignored). They are merged one level deep over the config, matching wp_parse_args() on the front end: a transformation in Custom Settings replaces the block's own crop and background, as on the page.

Behaviour changes

  • The editor preview now applies Custom Settings, so mistakes in saved Custom Settings that were silently dropped in the editor now show there, as they already did on the published page.
  • The preview of existing blocks now loads images through the site's custom domain when one is set, and always from the connected cloud.
  • Other editor iframes now render the gallery too: the Tablet/Mobile device preview, the site editor, and inserter/pattern previews. They were blank before.
  • On WordPress 6.3 to 7.0, the post editor isn't iframed for this block (block API v2), so the preview takes the same path as before.

QA notes

  1. On WordPress 7.1, connect the plugin and create a post with a Cloudinary Gallery block.
  2. Click Media Library, pick two or more images and Update gallery.
    • The gallery preview renders in the block.
  3. In the block's Custom Settings, enter {"transformation":{"effect":"grayscale"}}.
    • The preview turns black and white (image URLs contain e_grayscale).
  4. Save and view the post.
    • The published gallery matches the editor preview.

A new e2e test in cloudinary-gallery-delivery.spec.js opens a gallery post in the editor and checks the preview renders inside the editor canvas, with every image carrying the Custom Settings transformation. Its block markup has no cloudName, so it also covers the delivery settings fallback. It fails on develop on each of the two issues.

The Product Gallery library was only loaded in the outer admin document,
while the block container lives in the editor canvas iframe, so the
widget never found it and the preview stayed blank.

Load the library in the editor canvas through enqueue_block_assets and
render with the widget of the window that holds the container, with the
config rebuilt in that frame so it passes the widget's validation.

Also parse the block's Custom Settings JSON before merging it over the
config, as the front end does, so the preview matches the published
gallery.
The front end always renders a gallery with the connected cloud name and
custom domain settings. The editor preview only got them on new blocks,
so blocks with no or a stale cloud name showed broken images, and
existing blocks ignored the custom domain.

@utkarshcloudinary utkarshcloudinary left a comment

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.

Looks good! Left some non blocking suggestions reviewed with help of LLM.

Comment thread src/js/gallery-block/edit.js Outdated
Comment on lines 192 to 210
try {
gallery = cloudinary.galleryWidget(
galleryWidgetConfig(
{ ...config, ...customSettings },
attributes.container
gallery = galleryWidget(
toFrame(
galleryWidgetConfig(
{ ...config, ...custom },
attributes.container
)
)
);
} catch {
gallery = cloudinary.galleryWidget(
galleryWidgetConfig( config, attributes.container )
gallery = galleryWidget(
toFrame(
galleryWidgetConfig( config, attributes.container )
)
);
}

gallery.render();
setLoading( false );

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.

nitpick (non-blocking): The fallback galleryWidget( ... ) call and gallery.render() are outside the try. If one of them throws, setLoading( false ) does not run and the spinner stays. When render runs from the load listener, the error goes to the canvas window.onerror, so it is hard to see.

try {
	try {
		gallery = galleryWidget( toFrame( galleryWidgetConfig( { ...config, ...custom }, attributes.container ) ) );
	} catch {
		gallery = galleryWidget( toFrame( galleryWidgetConfig( config, attributes.container ) ) );
	}
	gallery.render();
} catch ( error ) {
	// eslint-disable-next-line no-console
	console.error( 'Cloudinary Gallery: could not render the preview.', error );
} finally {
	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.

Good catch, thanks. Applied in cc6c808: the whole render, fallback included, is now wrapped in try/catch/finally. The spinner always stops, and a failure is logged with console.error instead of ending up unnoticed in the canvas window.onerror.

Comment on lines +215 to 220
} else if ( 'complete' !== win.document.readyState ) {
// The library may still be loading in the editor canvas.
win.addEventListener( 'load', render, { once: true } );
} else {
setLoading( false );
}

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.

Comment on lines +308 to +316
if ( $this->maybe_enqueue_scripts() ) {
wp_enqueue_script(
self::GALLERY_LIBRARY_HANDLE,
CLOUDINARY_ENDPOINTS_GALLERY,
array(),
$this->plugin->version,
true
);
}

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.

Comment thread php/media/class-gallery.php Outdated
Comment on lines +309 to +315
wp_enqueue_script(
self::GALLERY_LIBRARY_HANDLE,
CLOUDINARY_ENDPOINTS_GALLERY,
array(),
$this->plugin->version,
true
);

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.

nitpick (non-blocking): These arguments are the same as in enqueue_gallery_library(). A small private helper (or wp_register_script() one time) keeps the two calls the same if the version or the in_footer value changes.

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.

Done in cc6c808: both call sites now use a private enqueue_library_script() helper.

Comment thread src/js/gallery-block/edit.js Outdated
Comment on lines +66 to +78
const getDeliveryConfig = () => {
if ( 'undefined' === typeof CLD_GALLERY_CONFIG ) {
return {};
}

const { cloudName, secureDistribution, privateCdn } = CLD_GALLERY_CONFIG;

return Object.fromEntries(
Object.entries( { cloudName, secureDistribution, privateCdn } ).filter(
( [ , value ] ) => undefined !== value
)
);
};

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.

note (non-blocking): CLD_GALLERY_CONFIG goes through the cloudinary_gallery_config filter, but prepare_block_render() reads cloudName and cname directly from connect. If a site changes these values with that filter, the preview and the front end use different values. Write this in the doc comment, or use the same source on both sides.

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.

Good point. I went with the same source on both sides rather than a doc comment. A new Gallery::get_delivery_config() builds the cloud name and custom domain settings, prepare_block_render() uses it, and the editor gets its output as CLD_GALLERY_DELIVERY instead of reading them from the filtered CLD_GALLERY_CONFIG. The front-end output is unchanged; the custom-domain e2e spec still passes.

Comment on lines +290 to +293
// Relies on the iframed editor (WordPress 7.1+, or blocks on API v3):
// the editor canvas is an iframe, and the widget has to render inside
// it, not in the outer admin document.
const gallery = editor.canvas.locator(

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, test): If the editor is not iframed (WordPress < 7.1, block apiVersion: 2), editor.canvas does not find the iframe and the test fails after WIDGET_TIMEOUT. .wp-env.json pins 7.1, so CI is fine now. To protect a later change to the matrix, skip when iframe[name="editor-canvas"] is not found, or say in the comment that the test needs 7.1+.

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.

Applied in cc6c808. The test waits for the editor canvas, iframed or not, then calls test.skip() when there's no iframe[name="editor-canvas"], so a later change to the WordPress versions CI runs on won't turn it into a timeout.

- Always stop the spinner and log an error when the preview fails to
  render, and warn when the library is missing from the editor canvas.
- Add CLD_GALLERY_CONFIG once based on the script's inline data rather
  than on whether the library is already enqueued, so enqueuing it for
  the canvas first can't drop the config.
- Share the library enqueue arguments in a helper.
- Build the delivery settings in one method used by both the front end
  and the editor preview, instead of reading them from the filtered
  gallery config in the editor.
- Skip the editor preview e2e test when the editor is not iframed.

@utkarshcloudinary utkarshcloudinary left a comment

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.

Looks good ✅

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants