diff --git a/assets/src/dashboard/parts/connected/settings/Watermark.js b/assets/src/dashboard/parts/connected/settings/Watermark.js
index e42000a24..7e0efb54b 100644
--- a/assets/src/dashboard/parts/connected/settings/Watermark.js
+++ b/assets/src/dashboard/parts/connected/settings/Watermark.js
@@ -63,7 +63,7 @@ const Watermark = () => {
className="border border-gray-300 text-gray-700 px-6 py-3 rounded-lg font-medium hover:bg-gray-50"
target="_blank"
rel="noopener noreferrer"
- href="https://docs.optimole.com/article/1475-adding-watermarks-to-your-images"
+ href={ optimoleDashboardApp.docs_links.watermark_settings }
>
{options_strings.learn_more}
diff --git a/assets/src/global.d.ts b/assets/src/global.d.ts
index 541e9aeac..1b1163189 100644
--- a/assets/src/global.d.ts
+++ b/assets/src/global.d.ts
@@ -27,6 +27,7 @@ export interface IOptimoleDashboardApp {
optimoleHome: string
optimoleDashHome: string
optimoleDashBilling: string
+ docs_links: DocsLinks
days_since_install: string
is_offload_media_available: string
auto_connect: string
@@ -38,6 +39,20 @@ export interface IOptimoleDashboardApp {
report_issue_url: string
}
+export interface DocsLinks {
+ home: string
+ visitors_count: string
+ plan_limits: string
+ visitors_plan: string
+ getting_started: string
+ webp: string
+ watermarks: string
+ cloud_library: string
+ exclusions: string
+ custom_integration: string
+ watermark_settings: string
+}
+
export interface Strings {
optimole: string
version: string
diff --git a/assets/src/media/__tests__/admin-page.test.js b/assets/src/media/__tests__/admin-page.test.js
new file mode 100644
index 000000000..fa041c329
--- /dev/null
+++ b/assets/src/media/__tests__/admin-page.test.js
@@ -0,0 +1,38 @@
+/**
+ * Tests for the Cloud Library admin page script.
+ */
+
+jest.mock( '../scss/admin-page.scss', () => ({}) );
+
+const SITE_URL = 'https://example.test';
+
+describe( 'Cloud Library admin page (issue #1211)', () => {
+ let iframe;
+ let loader;
+
+ beforeAll( () => {
+ window.optmlAdminPage = { siteUrl: SITE_URL };
+
+ // The script is printed in the head, before the iframe markup exists.
+ require( '../admin-page.js' );
+
+ document.body.innerHTML = '
';
+ iframe = document.getElementById( 'om-dam' );
+ loader = document.querySelector( '.om-dam-loader' );
+ });
+
+ test( 'reveals the iframe when it loads after the script ran', () => {
+ iframe.dispatchEvent( new Event( 'load' ) );
+
+ expect( loader.style.display ).toBe( 'none' );
+ expect( iframe.style.display ).toBe( '' );
+ });
+
+ test( 'answers getUrl from an iframe added after the script ran', () => {
+ const postMessage = jest.spyOn( iframe.contentWindow, 'postMessage' ).mockImplementation( () => {});
+
+ window.dispatchEvent( new MessageEvent( 'message', { data: { type: 'om-dam', action: 'getUrl' }}) );
+
+ expect( postMessage ).toHaveBeenCalledWith({ siteUrl: SITE_URL, type: 'om-dam', context: 'browse' }, '*' );
+ });
+});
diff --git a/assets/src/media/admin-page.js b/assets/src/media/admin-page.js
index f861a2fa1..2d7a6692b 100644
--- a/assets/src/media/admin-page.js
+++ b/assets/src/media/admin-page.js
@@ -3,12 +3,16 @@ import './scss/admin-page.scss';
const { optmlAdminPage } = window;
const { siteUrl } = optmlAdminPage;
-const iframe = document.getElementById( 'om-dam' );
-iframe.addEventListener( 'load', function() {
+// This runs in the head, before #om-dam exists: `load` does not bubble, so catch it in the capture phase.
+document.addEventListener( 'load', function( event ) {
+ if ( 'om-dam' !== event.target.id ) {
+ return;
+ }
+
document.querySelector( '.om-dam-loader' ).style.display = 'none';
- iframe.style.display = '';
-});
+ event.target.style.display = '';
+}, true );
window.addEventListener( 'message', function( event ) {
if ( ! event.data ) {
@@ -31,5 +35,5 @@ window.addEventListener( 'message', function( event ) {
return;
}
- iframe.contentWindow.postMessage({ siteUrl, type: 'om-dam', context: 'browse' }, '*' );
+ document.getElementById( 'om-dam' ).contentWindow.postMessage({ siteUrl, type: 'om-dam', context: 'browse' }, '*' );
});
diff --git a/inc/admin.php b/inc/admin.php
index 0641d2599..0ebf66c64 100755
--- a/inc/admin.php
+++ b/inc/admin.php
@@ -717,7 +717,7 @@ public function add_notice_upgrade() {
?>
-
@@ -772,6 +772,8 @@ public function should_show_upgrade() {
/**
* Build upgrade URL with current user's encoded email.
*
+ * The URL is already localized, so callers must not pass it through tsdk_translate_link() again.
+ *
* @return string Upgrade URL.
*/
public static function get_upgrade_base_link() {
@@ -786,6 +788,42 @@ public static function get_upgrade_base_link() {
return $base_url;
}
+ /**
+ * Build a docs.optimole.com link with UTMs.
+ *
+ * Links go to the final docs URL: the old /article/ URLs redirect, and the redirect drops the UTMs.
+ *
+ * @param string $path Docs page path, e.g. 'wordpress-plugin/best-format'.
+ * @param string $campaign The feature the link explains (utm_campaign).
+ * @param string $medium Where the link is shown (utm_medium).
+ *
+ * @return string Docs URL with UTMs.
+ */
+ public static function docs_url( $path, $campaign, $medium ) {
+ return tsdk_utmify( 'https://docs.optimole.com/' . ltrim( $path, '/' ), $campaign, $medium );
+ }
+
+ /**
+ * Get docs links used by the dashboard app.
+ *
+ * @return array Docs URLs with UTMs, by key.
+ */
+ public static function get_dashboard_docs_links() {
+ return [
+ 'home' => self::docs_url( '', 'documentation', 'help' ),
+ 'visitors_count' => self::docs_url( 'account/how-optimole-counts-the-number-of-visitors', 'visitors-count', 'help' ),
+ 'plan_limits' => self::docs_url( 'account/what-happens-if-i-exceed-plan-limits', 'plan-limits', 'help' ),
+ 'visitors_plan' => self::docs_url( 'account/visitors-based-plan', 'visitors-plan', 'help' ),
+ 'getting_started' => self::docs_url( 'wordpress-plugin/how-to-get-started-with-optimole-in-just-3-steps', 'getting-started', 'help' ),
+ 'webp' => self::docs_url( 'image-processing/how-optimole-can-serve-webp-images', 'webp', 'help' ),
+ 'watermarks' => self::docs_url( 'image-processing/adding-watermarks-to-your-images', 'watermark', 'help' ),
+ 'cloud_library' => self::docs_url( 'wordpress-plugin/cloud-library-browsing', 'cloud-library', 'help' ),
+ 'exclusions' => self::docs_url( 'wordpress-plugin/exclude-from-optimizing-or-lazy-loading', 'exclusions', 'help' ),
+ 'custom_integration' => self::docs_url( 'image-processing/how-to-use-the-custom-integration-in-optimole', 'custom-integration', 'help' ),
+ 'watermark_settings' => self::docs_url( 'image-processing/adding-watermarks-to-your-images', 'watermark', 'settings' ),
+ ];
+ }
+
/**
* Get contact URL.
*
@@ -1536,6 +1574,7 @@ private function localize_dashboard_app() {
'optimoleDashBilling' => tsdk_translate_link( 'https://dashboard.optimole.com/settings/billing', 'query' ),
'optimoleDashMetrics' => tsdk_translate_link( tsdk_utmify( 'https://dashboard.optimole.com/metrics', 'wp-plugin', 'shortcut' ) ),
'offload_upgrade_url' => tsdk_translate_link( tsdk_utmify( 'https://optimole.com/pricing/', 'offload' ) ),
+ 'docs_links' => self::get_dashboard_docs_links(),
'days_since_install' => round( ( time() - get_option( 'optimole_wp_install', 0 ) ) / DAY_IN_SECONDS ),
'is_offload_media_available' => $is_offload_media_available,
'auto_connect' => $auto_connect,
@@ -1741,7 +1780,7 @@ public function get_bf_notices( $user_plan ) {
'' . $promo_code . ' ',
'' . __( '25% discount', 'optimole-wp' ) . ' '
),
- 'cta_link' => esc_url_raw( tsdk_utmify( tsdk_translate_link( self::get_upgrade_base_link() ), 'bfcm', 'sidebarnotice' ) ),
+ 'cta_link' => esc_url_raw( tsdk_utmify( self::get_upgrade_base_link(), 'bfcm', 'sidebarnotice' ) ),
];
// The banner shares the SDK dismissal, which resets every year.
@@ -1864,13 +1903,13 @@ private function get_dashboard_strings() {
'',
' ',
number_format_i18n( 2000 ),
- '',
+ ' ',
' '
),
'account_needed_subtitle_3' => sprintf(
/* translators: 1 is the starting anchor tag for the docs link, 2 is the ending anchor tag. */
__( 'Need help? %1$sGetting Started with Optimole%2$s', 'optimole-wp' ),
- '',
+ ' ',
' '
),
'account_needed_subtitle_2' => sprintf(
@@ -1914,7 +1953,7 @@ private function get_dashboard_strings() {
'notice_disabled_account' => sprintf(
/* translators: 1 anchor tag to pricing, 2 is the ending endin anchor tag, 3 is the bold tag start, 4 ending bold tag, 5 new line tag */
__( '%3$sYour account has been disabled due to exceeding quota.%4$s All images are being redirected to the original unoptimized URL. %5$sPlease %1$supgrade%2$s to re-activate the account.', 'optimole-wp' ),
- '',
+ '',
' ',
'',
' ',
@@ -2014,7 +2053,7 @@ private function get_dashboard_strings() {
'best_format_desc' => sprintf(
/* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */
__( 'When enabled, Optimole chooses the best format for your images, balancing quality with speed. It tries options like AVIF and WebP to keep visuals sharp and pages fast, though uncached images may take a bit longer to process. %1$sLearn more%2$s.', 'optimole-wp' ),
- ' ',
+ ' ',
' '
),
'add_filter' => __( 'Add filter', 'optimole-wp' ),
@@ -2024,7 +2063,7 @@ private function get_dashboard_strings() {
'cache_desc' => sprintf(
/* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */
__( 'Clears all Optimole’s cached resources (images, JS, CSS). Useful if you made changes to your images and don\'t see those applying on your site. %1$sLearn more%2$s', 'optimole-wp' ),
- '',
+ ' ',
' '
),
'cache_title' => __( 'Clear Cached Resources', 'optimole-wp' ),
@@ -2032,7 +2071,7 @@ private function get_dashboard_strings() {
'image_size_notice' => sprintf(
/* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */
__( 'Use this option if you notice images are not cropped correctly after using Optimole. Add the affected image sizes here to automatically adjust and correct their cropping for optimal display. %1$sLearn more%2$s', 'optimole-wp' ),
- '',
+ ' ',
' '
),
'clear_cache_images' => __( 'Clear cached images', 'optimole-wp' ),
@@ -2046,13 +2085,13 @@ private function get_dashboard_strings() {
'enable_avif_desc' => sprintf(
/* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */
__( 'Enable this to automatically convert images to the AVIF format on browsers that support it. This format provides quality images with reduced file sizes, and faster webpage loading. %1$sLearn more%2$s', 'optimole-wp' ),
- '',
+ ' ',
' '
),
'enable_bg_lazyload_desc' => sprintf(
/* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */
__( 'Apply lazy loading to CSS background images. The toggle below enables it globally. The selector list is optional and only needed to extend coverage if certain elements are missed. %1$sLearn more%2$s', 'optimole-wp' ),
- '',
+ ' ',
' '
),
'enable_bg_lazyload_title' => __( 'CSS Background Lazy Load', 'optimole-wp' ),
@@ -2061,26 +2100,26 @@ private function get_dashboard_strings() {
'enable_noscript_desc' => sprintf(
/* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */
__( 'Enables fallback images for browsers that can\'t handle JavaScript-based lazy loading or related features. Disabling it may resolve conflicts with other plugins or configurations and decrease HTML page size. %1$sLearn more%2$s', 'optimole-wp' ),
- '',
+ ' ',
' '
),
// translators: %s is the name of the html tag (e.g: );
'enable_noscript_title' => sprintf( __( 'Enable %s fallback', 'optimole-wp' ), ' ' ),
'enable_gif_replace_title' => __( 'GIF to Video Conversion', 'optimole-wp' ),
'enable_offload_media_title' => __( 'Store Your Images in Optimole Cloud', 'optimole-wp' ),
- 'enable_offload_media_desc' => sprintf( /* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */ __( 'Free up space on your server by transferring your images to Optimole Cloud; you can transfer them back anytime. Once moved, the images will still be visible in the Media Library and can be used as before. %1$sLearn more%2$s', 'optimole-wp' ), '', ' ' ),
+ 'enable_offload_media_desc' => sprintf( /* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */ __( 'Free up space on your server by transferring your images to Optimole Cloud; you can transfer them back anytime. Once moved, the images will still be visible in the Media Library and can be used as before. %1$sLearn more%2$s', 'optimole-wp' ), '', ' ' ),
'enable_cloud_images_title' => __( 'Unified Image Access', 'optimole-wp' ),
'enable_cloud_images_desc' => sprintf(
/* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */
__( 'Enable this setting to access all your Optimole images, including those from other websites connected to your Optimole account, directly on this site. They will be available for browsing in the Cloud Library tab. %1$sLearn more%2$s', 'optimole-wp' ),
- '',
+ ' ',
' '
),
'enable_image_replace' => __( 'Enable Optimole Image Handling', 'optimole-wp' ),
'enable_lazyload_placeholder_desc' => sprintf(
/* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */
__( 'Enable this to use a generic transparent placeholder instead of the blurry images during lazy loading. %1$sLearn more%2$s', 'optimole-wp' ),
- '',
+ ' ',
' '
),
@@ -2088,7 +2127,7 @@ private function get_dashboard_strings() {
'lazyload_behaviour_desc' => sprintf(
/* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */
__( 'Choose how Optimole will handle lazy loading for images on your website. %1$sLearn more%2$s', 'optimole-wp' ),
- '',
+ ' ',
' '
),
'lazyload_behaviour_all' => __( 'Lazy Load All Images', 'optimole-wp' ),
@@ -2101,28 +2140,28 @@ private function get_dashboard_strings() {
'enable_network_opt_desc' => sprintf(
/* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */
__( 'When enabled, Optimole will automatically reduce the image quality when it detects a slower network, making your images load faster on low-speed internet connections. %1$sLearn more%2$s', 'optimole-wp' ),
- '',
+ ' ',
' '
),
'enable_network_opt_title' => __( 'Network-based Optimizations', 'optimole-wp' ),
'enable_resize_smart_desc' => sprintf(
/* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */
__( 'When enabled, Optimole automatically detects the most interesting or important part of your images. When pictures are resized or cropped, this feature ensures the focus stays on the most interesting part of the picture. %1$sLearn more%2$s', 'optimole-wp' ),
- '',
+ ' ',
' '
),
'enable_resize_smart_title' => __( 'Smart Cropping', 'optimole-wp' ),
'enable_retina_desc' => sprintf(
/* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */
__( 'Optimizes images for Retina (high-DPI) screens for sharper results. Always enabled for images under 150px wide. %1$sLearn more%2$s', 'optimole-wp' ),
- '',
+ ' ',
' '
),
'enable_retina_title' => __( 'Retina Quality', 'optimole-wp' ),
'enable_limit_dimensions_desc' => sprintf(
/* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */
__( 'Define the max width or height limits for images on your website. Larger images will be automatically adjusted to fit within these parameters while preserving their original aspect ratio. %1$sLearn more%2$s', 'optimole-wp' ),
- '',
+ ' ',
' '
),
'enable_limit_dimensions_title' => __( 'Limit Image Sizes', 'optimole-wp' ),
@@ -2136,7 +2175,7 @@ private function get_dashboard_strings() {
'enable_badge_description' => sprintf(
/* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */
__( 'Get 20.000 more visits for free by enabling the Optimole badge on your websites. %1$sLearn more%2$s', 'optimole-wp' ),
- '',
+ ' ',
' '
),
'image_sizes_title' => __( 'Your cropped image sizes', 'optimole-wp' ),
@@ -2161,14 +2200,14 @@ private function get_dashboard_strings() {
'exclude_desc_optimize' => sprintf(
/* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */
__( 'Here you can define exceptions, in case you don\'t want some images to be optimised. %1$sLearn more%2$s', 'optimole-wp' ),
- '',
+ ' ',
' '
),
'exclude_title_lazyload' => __( 'Don\'t lazy-load images if', 'optimole-wp' ),
'exclude_desc_lazyload' => sprintf(
/* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */
__( 'Define exceptions, in case you don\'t want the lazy-load to be active on certain images. %1$sLearn more%2$s', 'optimole-wp' ),
- '',
+ ' ',
' '
),
'exclude_title_optimize' => __( 'Don\'t optimize and don\'t lazy-load images if', 'optimole-wp' ),
@@ -2191,7 +2230,7 @@ private function get_dashboard_strings() {
'exclude_first' => __( 'Exclude first', 'optimole-wp' ),
'images' => __( 'images', 'optimole-wp' ),
'exclude_first_images_title' => __( 'Bypass Lazy Load for First Images', 'optimole-wp' ),
- 'exclude_first_images_desc' => sprintf( /* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */ __( 'Indicate how many images at the top of each page should bypass lazy loading, ensuring they’re instantly visible. Enter 0 to not exclude any images from the lazy loading process. %1$sLearn more%2$s', 'optimole-wp' ), '', ' ' ),
+ 'exclude_first_images_desc' => sprintf( /* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */ __( 'Indicate how many images at the top of each page should bypass lazy loading, ensuring they’re instantly visible. Enter 0 to not exclude any images from the lazy loading process. %1$sLearn more%2$s', 'optimole-wp' ), '', ' ' ),
'filter_class' => __( 'Image class', 'optimole-wp' ),
'filter_ext' => __( 'Image extension', 'optimole-wp' ),
'filter_filename' => __( 'Image filename', 'optimole-wp' ),
@@ -2200,7 +2239,7 @@ private function get_dashboard_strings() {
'filter_operator_is' => __( 'is', 'optimole-wp' ),
'filter_url' => __( 'Page URL', 'optimole-wp' ),
'filter_helper' => __( 'For homepage use `home` keyword.', 'optimole-wp' ),
- 'gif_replacer_desc' => sprintf( /* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */ __( 'Enable this to automatically convert GIF images to Video files (MP4 and WebM). %1$sLearn more%2$s', 'optimole-wp' ), '', ' ' ),
+ 'gif_replacer_desc' => sprintf( /* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */ __( 'Enable this to automatically convert GIF images to Video files (MP4 and WebM). %1$sLearn more%2$s', 'optimole-wp' ), '', ' ' ),
'height_field' => __( 'Height', 'optimole-wp' ),
'add_image_size_button' => __( 'Add size', 'optimole-wp' ),
'add_image_size_desc' => __( 'Add New Image Crop Size', 'optimole-wp' ),
@@ -2209,7 +2248,7 @@ private function get_dashboard_strings() {
'high_q_title' => __( 'High', 'optimole-wp' ),
'image_1_label' => __( 'Original', 'optimole-wp' ),
'image_2_label' => __( 'Optimized', 'optimole-wp' ),
- 'lazyload_desc' => sprintf( /* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */ __( 'Images load only when they\'re about to enter the viewport. %1$sLearn more%2$s', 'optimole-wp' ), '', ' ' ),
+ 'lazyload_desc' => sprintf( /* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */ __( 'Images load only when they\'re about to enter the viewport. %1$sLearn more%2$s', 'optimole-wp' ), '', ' ' ),
'filter_length_error' => __( 'The filter should be at least 3 characters long.', 'optimole-wp' ),
'scale_desc' => __( 'Automatically resize the images based on device and viewport', 'optimole-wp' ),
'low_q_title' => __( 'Low', 'optimole-wp' ),
@@ -2217,14 +2256,14 @@ private function get_dashboard_strings() {
'no_images_found' => __( 'You dont have any images in your Media Library. Add one and check how the Optimole will perform.', 'optimole-wp' ),
'native_desc' => __( 'Uses the browser\'s built-in lazy loading feature. Enabling this will disable the auto scale.', 'optimole-wp' ),
'option_saved' => __( 'Option saved.', 'optimole-wp' ),
- 'ml_quality_desc' => sprintf( /* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */ __( 'Optimole ML algorithms will predict the optimal image quality to get the smallest possible size with minimum perceived quality losses. When disabled, you can control the quality manually. %1$sLearn more%2$s', 'optimole-wp' ), '', ' ' ),
+ 'ml_quality_desc' => sprintf( /* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */ __( 'Optimole ML algorithms will predict the optimal image quality to get the smallest possible size with minimum perceived quality losses. When disabled, you can control the quality manually. %1$sLearn more%2$s', 'optimole-wp' ), '', ' ' ),
'quality_desc' => __( 'Lower image quality might boost your loading speed by lowering the size. However, the low image quality may negatively impact the visual appearance of the images. Try experimenting with the setting, then click the View sample image link to see what option works best for you.', 'optimole-wp' ),
'quality_selected_value' => __( 'Selected value', 'optimole-wp' ),
'quality_slider_desc' => __( 'See one sample image which will help you choose the right quality of the compression.', 'optimole-wp' ),
'quality_title' => __( 'Auto Quality Powered by ML(Machine Learning)', 'optimole-wp' ),
'strip_meta_title' => __( 'Strip Image Metadata', 'optimole-wp' ),
- 'strip_meta_desc' => sprintf( /* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */ __( 'Removes extra information from images, including EXIF and IPTC data (like camera settings and copyright info). This makes the pictures lighter and helps your website load faster. %1$sLearn more%2$s', 'optimole-wp' ), '', ' ' ),
- 'replacer_desc' => sprintf( /* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */ __( 'When enabled, Optimole will manage, optimize, and serve all the images on your website. If disabled, optimization, lazy loading, and other features will no longer be available. %1$sLearn more%2$s', 'optimole-wp' ), '', ' ' ),
+ 'strip_meta_desc' => sprintf( /* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */ __( 'Removes extra information from images, including EXIF and IPTC data (like camera settings and copyright info). This makes the pictures lighter and helps your website load faster. %1$sLearn more%2$s', 'optimole-wp' ), '', ' ' ),
+ 'replacer_desc' => sprintf( /* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */ __( 'When enabled, Optimole will manage, optimize, and serve all the images on your website. If disabled, optimization, lazy loading, and other features will no longer be available. %1$sLearn more%2$s', 'optimole-wp' ), '', ' ' ),
'sample_image_loading' => __( 'Loading a sample image.', 'optimole-wp' ),
'save_changes' => __( 'Save changes', 'optimole-wp' ),
'show' => __( 'Show', 'optimole-wp' ),
@@ -2262,7 +2301,7 @@ private function get_dashboard_strings() {
'width_field' => __( 'Width', 'optimole-wp' ),
'crop' => __( 'crop', 'optimole-wp' ),
'toggle_cdn' => __( 'Serve CSS & JS Through Optimole', 'optimole-wp' ),
- 'cdn_desc' => sprintf( /* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */ __( 'When enabled, Optimole will optimize your CSS and JS files and, if they contain images, the images as well, then deliver them via the CDN for faster webpage loading. %1$sLearn more%2$s', 'optimole-wp' ), '', ' ' ),
+ 'cdn_desc' => sprintf( /* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */ __( 'When enabled, Optimole will optimize your CSS and JS files and, if they contain images, the images as well, then deliver them via the CDN for faster webpage loading. %1$sLearn more%2$s', 'optimole-wp' ), '', ' ' ),
'enable_css_minify_title' => __( 'Minify CSS files', 'optimole-wp' ),
'css_minify_desc' => __( 'Once Optimole will serve your CSS files, it will also minify the files and serve them via CDN.', 'optimole-wp' ),
'enable_js_minify_title' => __( 'Minify JS files', 'optimole-wp' ),
@@ -2294,7 +2333,7 @@ private function get_dashboard_strings() {
'sync_media_error_desc' => __( 'You can try again to offload the rest of the images to Optimole.', 'optimole-wp' ),
'offload_disable_warning_title' => __( 'Important! Please read carefully', 'optimole-wp' ),
'offload_disable_warning_desc' => __( 'If you turn off this option, you will not be able to see the images in the Media Library without restoring the images first. Do you want to restore the images to your site upon turning off the option?', 'optimole-wp' ),
- 'offload_enable_info_desc' => sprintf( /* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */ __( 'You are not required to use the offload functionality for the plugin to work, use it if you want to save on hosting space. %1$s More details%2$s', 'optimole-wp' ), '', ' ' ),
+ 'offload_enable_info_desc' => sprintf( /* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */ __( 'You are not required to use the offload functionality for the plugin to work, use it if you want to save on hosting space. %1$s More details%2$s', 'optimole-wp' ), '', ' ' ),
'offload_conflicts_part_1' => __( 'We have detected the following plugins that conflict with the offload features:', 'optimole-wp' ),
'offload_conflicts_part_2' => __( 'Please disable those plugins temporarily in order for Optimole to rollback the images to your site.', 'optimole-wp' ),
'offloading_success' => sprintf( /* translators: 1 is the starting bold tag, 2 is the ending bold tag */ __( '%s Your images are now stored in Optimole Cloud.', 'optimole-wp' ), '' . __( 'Transfer Complete.', 'optimole-wp' ) . ' ' ),
@@ -2329,7 +2368,7 @@ private function get_dashboard_strings() {
'cloud_library_btn_text' => __( 'Go to Cloud Library', 'optimole-wp' ),
'cloud_library_btn_link' => add_query_arg( 'page', 'optimole-dam', admin_url( 'admin.php' ) ),
'exceed_plan_quota_notice_title' => __( 'Your site has already reached over 50% of your monthly visits limit within just two weeks.', 'optimole-wp' ),
- 'exceed_plan_quota_notice_description' => sprintf( /* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */ __( 'Based on this trend, you are likely to exceed your free quota before the month ends. To avoid any disruption in service, we strongly recommend %1$supgrading%2$s your plan or waiting until your traffic stabilizes before offloading your images. Do you still wish to proceed?', 'optimole-wp' ), '', ' ' ),
+ 'exceed_plan_quota_notice_description' => sprintf( /* translators: 1 is the starting anchor tag, 2 is the ending anchor tag */ __( 'Based on this trend, you are likely to exceed your free quota before the month ends. To avoid any disruption in service, we strongly recommend %1$supgrading%2$s your plan or waiting until your traffic stabilizes before offloading your images. Do you still wish to proceed?', 'optimole-wp' ), '', ' ' ),
'exceed_plan_quota_notice_start_action' => __( 'Yes, Transfer to Optimole Cloud', 'optimole-wp' ),
'exceed_plan_quota_notice_secondary_action' => __( 'No, keep images on my website', 'optimole-wp' ),
'plan_update_notice_title' => __( 'Plan Update', 'optimole-wp' ),
@@ -2450,7 +2489,7 @@ private function get_dashboard_strings() {
'optimization_tips' => sprintf(
/* translators: 1 is the opening anchor tag, 2 is the closing anchor tag */
__( '%1$sView all optimization tips%2$s', 'optimole-wp' ),
- ' ',
+ ' ',
' '
),
'contact_support' => [
diff --git a/inc/api.php b/inc/api.php
index da8e38758..25531f386 100644
--- a/inc/api.php
+++ b/inc/api.php
@@ -192,7 +192,7 @@ public function request( $path, $method = 'GET', $params = [], $extra_headers =
if ( intval( $response['code'] ) !== 200 ) {
if ( isset( $response['error'] ) && $response['error'] === 'domain_not_accessible' ) {
- return new WP_Error( 'domain_not_accessible', sprintf( /* translators: 1 start of the italic tag, 2 is the end of italic tag, 3 is starting anchor tag, 4 is the ending anchor tag. */ __( 'It seems Optimole is having trouble reaching your website. This issue often occurs if your website is private, local, or protected by a firewall. But don\'t stress – it\'s an easy fix! Ensure your website is live and accessible to the public. If a firewall is in place, just tweak the settings to allow the %1$sOptimole(1.0)%2$s user agent access to your website. %3$sLearn More%4$s', 'optimole-wp' ), '', ' ', '', ' ' ) );
+ return new WP_Error( 'domain_not_accessible', sprintf( /* translators: 1 start of the italic tag, 2 is the end of italic tag, 3 is starting anchor tag, 4 is the ending anchor tag. */ __( 'It seems Optimole is having trouble reaching your website. This issue often occurs if your website is private, local, or protected by a firewall. But don\'t stress – it\'s an easy fix! Ensure your website is live and accessible to the public. If a firewall is in place, just tweak the settings to allow the %1$sOptimole(1.0)%2$s user agent access to your website. %3$sLearn More%4$s', 'optimole-wp' ), '', ' ', '', ' ' ) );
}
if ( $path === 'optml/v2/account/complete_register_remote' && isset( $response['error'] ) ) {
if ( strpos( $response['error'], 'This email address is already registered.' ) !== false ) {
diff --git a/inc/dam.php b/inc/dam.php
index 8bbeb4c99..5744e5a39 100644
--- a/inc/dam.php
+++ b/inc/dam.php
@@ -429,12 +429,12 @@ public function render_dashboard_page() {
display: none !important;
}
-
...
+
' . self::IFRAME_PLACEHOLDER_CLASS . '';
const SVG_PLACEHOLDER = 'data:image/svg+xml,%3Csvg%20viewBox%3D%220%200%20#width#%20#height#%22%20width%3D%22#width#%22%20height%3D%22#height#%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Crect%20width%3D%22#width#%22%20height%3D%22#height#%22%20fill%3D%22#fill#%22%2F%3E%3C%2Fsvg%3E';
+ /**
+ * What precedes a start tag attribute: whitespace or, as browsers allow, directly a quoted value.
+ */
+ private const TAG_ATTRIBUTE_SEPARATOR = '(?:\s+|(?<=["\']))';
+ /**
+ * One start tag attribute with its separator.
+ *
+ * A quoted value is matched whole, so text inside it is never read as an attribute. An iframe whose
+ * attribute value starts with a backslash is not matched, so JSON-escaped iframe markup is left as written.
+ */
+ private const TAG_ATTRIBUTE = self::TAG_ATTRIBUTE_SEPARATOR . '[^\s"\'>\/=]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|[^\s"\'>\\\\][^\s>]*))?';
/**
* If frame lazyload is present on page.
*
@@ -374,14 +385,16 @@ public function lazyload_video_replace( $content ) {
$video_tags = [];
$iframes = [];
$videos = [];
- preg_match_all( '#(?:\s*)?(?:\s* )?#is', $content, $iframes );
+ // Only iframes with no fallback content; one with fallback text is left as written.
+ preg_match_all( '#(?:\s*)?(?:\s* )?#i', $content, $iframes );
preg_match_all( '#(?:\s*)?.*? (?:\s* )?#is', $content, $videos );
+ $iframe_count = count( $iframes[0] );
$video_tags = array_merge( $iframes[0], $videos[0] );
$search = [];
$replace = [];
- foreach ( $video_tags as $video_tag ) {
+ foreach ( $video_tags as $index => $video_tag ) {
if ( ! $this->should_lazyload_iframe( $video_tag ) ) {
continue;
@@ -389,23 +402,12 @@ public function lazyload_video_replace( $content ) {
if ( preg_match( "/ data-opt-src=['\"]/is", $video_tag ) ) {
continue;
}
- $should_add_noscript = true;
$original_tag = $video_tag;
- // replace the src and add the data-opt-src attribute
- if ( strpos( $video_tag, 'iframe' ) !== false ) {
- $video_tag = preg_replace( '/iframe(.*?)src=/is', 'iframe$1 src="about:blank" data-opt-src=', $video_tag );
- } elseif ( strpos( $video_tag, 'video' ) !== false ) {
- if ( strpos( $video_tag, 'source' ) !== false ) {
- if ( strpos( $video_tag, 'preload' ) === false ) {
- $video_tag = preg_replace( '/video(.*?)>/is', 'video$1 preload="metadata">', $video_tag, 1 );
- $should_add_noscript = false;
- } else {
- continue;
- }
- } else {
- $video_tag = preg_replace( '/video(.*?)src=/is', 'video$1 data-opt-src=', $video_tag );
- }
+ $lazyloaded = $this->lazyload_media_element( $video_tag, $index < $iframe_count );
+ if ( null === $lazyloaded ) {
+ continue;
}
+ list( $video_tag, $should_add_noscript ) = $lazyloaded;
if ( $this->should_add_noscript( $video_tag ) && $should_add_noscript ) {
$video_tag .= '' . $original_tag . ' ';
}
@@ -419,6 +421,46 @@ public function lazyload_video_replace( $content ) {
return $content;
}
+ /**
+ * Move the src of a matched iframe or video to data-opt-src, or ask a sourced video to preload metadata only.
+ *
+ * @param string $element The iframe or video element.
+ * @param bool $is_iframe Whether the element was matched as an iframe.
+ *
+ * @return array{0: string, 1: bool}|null The element and whether it gets a noscript copy, or null to leave it untouched.
+ */
+ private function lazyload_media_element( string $element, bool $is_iframe ): ?array {
+ if ( $is_iframe && strpos( $element, 'iframe' ) !== false ) {
+ return [ $this->replace_start_tag_src( $element, 'iframe', ' src="about:blank" data-opt-src' ), true ];
+ }
+ if ( $is_iframe || strpos( $element, 'video' ) === false ) {
+ return [ $element, true ];
+ }
+ if ( strpos( $element, 'source' ) === false ) {
+ return [ $this->replace_start_tag_src( $element, 'video', ' data-opt-src' ), true ];
+ }
+ if ( strpos( $element, 'preload' ) !== false ) {
+ return null;
+ }
+
+ return [ preg_replace( '#^((?:\s*)?(?:' . self::TAG_ATTRIBUTE . ')*)\s*/?)>#i', '$1 preload="metadata">', $element, 1 ) ?? $element, false ];
+ }
+
+ /**
+ * Replace the name of the src attribute in the element's start tag.
+ *
+ * @param string $element Element markup, starting with its start tag.
+ * @param string $tag_name The element's tag name.
+ * @param string $replacement Markup written in place of the attribute name, before its `=`.
+ *
+ * @return string The element, unchanged when its start tag has no src attribute.
+ */
+ private function replace_start_tag_src( string $element, string $tag_name, string $replacement ): string {
+ $pattern = '#^((?:\s*)?<' . $tag_name . '(?>(?:(?!\s*src\s*=)' . self::TAG_ATTRIBUTE . ')*)' . self::TAG_ATTRIBUTE_SEPARATOR . ')src(?=\s*=)#i';
+
+ return preg_replace( $pattern, '$1' . $replacement, $element, 1 ) ?? $element;
+ }
+
/**
* Check if the lazyload is allowed for this url.
*
diff --git a/inc/manager.php b/inc/manager.php
index b55c2de33..3adb2f2f2 100644
--- a/inc/manager.php
+++ b/inc/manager.php
@@ -564,7 +564,7 @@ public function replace_content( $html, $partial = false ) {
}
$marker = Lazyload::get_marker();
- if ( ! empty( $personalized_bg_css ) && ( $start_pos = strpos( $html, $marker ) ) !== false ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.Found
+ if ( null !== $personalized_bg_css && ( $start_pos = strpos( $html, $marker ) ) !== false ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.Found
// We replace the general bg css with the personalized one.
if ( ( $end_pos = strpos( $html, $marker, $start_pos + strlen( $marker ) ) ) !== false ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.Found
$html = substr_replace(
diff --git a/inc/rest.php b/inc/rest.php
index 50e086529..c719d432a 100644
--- a/inc/rest.php
+++ b/inc/rest.php
@@ -9,6 +9,7 @@
use Optimole\Sdk\Resource\ImageProperty\ResizeTypeProperty;
use Optimole\Sdk\ValueObject\Position;
+use OptimoleWP\BgOptimizer\Lazyload;
use OptimoleWP\PageProfiler\Profile;
/**
@@ -1013,7 +1014,7 @@ public function optimizations( WP_REST_Request $request ) {
// save just the first 6 images, see https://github.com/Codeinwp/optimole-service/issues/1588#issuecomment-3357110865
$above_fold_images = array_slice( $above_fold_images, 0, 6 );
$above_fold_images = array_values( array_map( 'intval', array_filter( $above_fold_images, 'is_numeric' ) ) );
- if ( count( $bg_selectors ) > 100 ) {
+ if ( count( $bg_selectors ) > Lazyload::MAX_WATCHERS ) {
return $this->response( 'Background selectors limit exceeded', 'error' );
}
if ( $url === Profile::PLACEHOLDER ) {
@@ -1026,7 +1027,7 @@ public function optimizations( WP_REST_Request $request ) {
if ( ! in_array( $selector, $current_selectors, true ) ) {
return $this->response( 'Invalid background selector', 'error' );
}
- if ( count( $above_fold_bg_selectors ) > 100 ) {
+ if ( count( $above_fold_bg_selectors ) > Lazyload::MAX_ABOVE_FOLD_SELECTORS ) {
return $this->response( 'Above fold background selectors limit exceeded', 'error' );
}
$selector = strip_tags( $selector );
diff --git a/inc/v2/BgOptimizer/Lazyload.php b/inc/v2/BgOptimizer/Lazyload.php
index 0c57a65e2..15f8081f1 100644
--- a/inc/v2/BgOptimizer/Lazyload.php
+++ b/inc/v2/BgOptimizer/Lazyload.php
@@ -18,6 +18,21 @@ class Lazyload {
*/
const SAFE_SELECTOR_PATTERN = '/^(?:[\w\-#. >\x{00A0}-\x{10FFFF}]|:nth-of-type\(\d+\))+$/u';
+ /**
+ * Most watchers the profiler reports per device; the frontend cuts the rest.
+ */
+ const MAX_WATCHERS = 100;
+
+ /**
+ * Most above-fold selectors the profiler reports per watcher; the frontend cuts the rest.
+ */
+ const MAX_ABOVE_FOLD_SELECTORS = 100;
+
+ /**
+ * Widest viewport in px the profiler counts as mobile (MOBILE_BREAKPOINT in device.js).
+ */
+ private const DEVICE_BREAKPOINT = 600;
+
/**
* Check whether a client-reported selector is a plain selector safe to embed in the stylesheet as-is.
*
@@ -46,9 +61,9 @@ public static function get_marker(): string {
/**
* Get the current personalized CSS for lazy loading.
*
- * @return string The personalized CSS.
+ * @return string|null The personalized CSS, or null when the general CSS must stay.
*/
- public static function get_current_personalized_css() {
+ public static function get_current_personalized_css(): ?string {
return self::get_personalized_css( Profile::get_current_profile_data() );
}
/**
@@ -56,9 +71,9 @@ public static function get_current_personalized_css() {
*
* @param array $data Profile data.
*
- * @return string The personalized CSS.
+ * @return string|null The personalized CSS ('' hides nothing), or null when every device was voided and the general CSS must stay.
*/
- public static function get_personalized_css( $data ) {
+ public static function get_personalized_css( $data ): ?string {
$lazyload_selectors = array_values( Optml_Lazyload_Replacer::get_background_lazyload_selectors() );
$lazyload_selectors = array_fill_keys( $lazyload_selectors, true );
$css_selectors = [];
@@ -94,35 +109,27 @@ public static function get_personalized_css( $data ) {
Links::add_link( [ 'url' => $url, 'priority' => 'high' ] );
}
- $hide_rule = ' { background-image: none !important; }';
- $mobile = $css_selectors[ Profile::DEVICE_TYPE_MOBILE ];
- $desktop = $css_selectors[ Profile::DEVICE_TYPE_DESKTOP ];
-
- // Keep the surviving rule scoped when the other device was voided.
- if ( $tainted[ Profile::DEVICE_TYPE_MOBILE ] !== $tainted[ Profile::DEVICE_TYPE_DESKTOP ] ) {
- if ( $tainted[ Profile::DEVICE_TYPE_MOBILE ] ) {
- return empty( $desktop ) ? '' : '@media (min-width: 600px) { ' . implode( ',', $desktop ) . $hide_rule . ' }';
- }
- return empty( $mobile ) ? '' : '@media (max-width: 600px) { ' . implode( ',', $mobile ) . $hide_rule . ' }';
+ if ( ! in_array( false, $tainted, true ) ) {
+ return null;
}
- $mobile_selectors = implode( ',', $mobile );
- $desktop_selectors = implode( ',', $desktop );
+ $hide_rule = ' { background-image: none !important; }';
+ $mobile_selectors = implode( ',', $css_selectors[ Profile::DEVICE_TYPE_MOBILE ] );
+ $desktop_selectors = implode( ',', $css_selectors[ Profile::DEVICE_TYPE_DESKTOP ] );
if ( $mobile_selectors === $desktop_selectors ) {
- return empty( $mobile_selectors ) ? '' : $mobile_selectors . $hide_rule;
+ return $mobile_selectors === '' ? '' : $mobile_selectors . $hide_rule;
}
- // if any of those are empty, return the other one
- if ( empty( $mobile_selectors ) ) {
- return $desktop_selectors . $hide_rule;
+
+ // A device without selectors hides nothing on purpose (voided or capped), so the other rule stays in its media query.
+ $media_queries = [];
+ if ( $mobile_selectors !== '' ) {
+ $media_queries[] = '@media (max-width: ' . self::DEVICE_BREAKPOINT . 'px) { ' . $mobile_selectors . $hide_rule . ' }';
}
- if ( empty( $desktop_selectors ) ) {
- return $mobile_selectors . $hide_rule;
+ if ( $desktop_selectors !== '' ) {
+ $media_queries[] = '@media (min-width: ' . ( self::DEVICE_BREAKPOINT + 1 ) . 'px) { ' . $desktop_selectors . $hide_rule . ' }';
}
-
- // generate media query for desktop and mobile
- $media_query = '@media (max-width: 600px) { ' . $mobile_selectors . $hide_rule . ' } @media (min-width: 600px) { ' . $desktop_selectors . $hide_rule . ' }';
- return $media_query;
+ return implode( ' ', $media_queries );
}
/**
* Build the background-hide selectors for one device.
@@ -139,15 +146,25 @@ private static function collect_device_selectors( array $personalized_selectors,
if ( ! isset( $lazyload_selectors[ $selector ] ) ) {
continue;
}
- if ( empty( $above_fold_selectors ) ) {
- $css_selectors[] = 'html ' . strip_tags( $selector ) . ':not(.optml-bg-lazyloaded)';
+ // A full list may have been cut, so hiding the watcher could delay unlisted above-fold elements.
+ if ( count( $above_fold_selectors ) >= self::MAX_ABOVE_FOLD_SELECTORS ) {
continue;
}
+ // One rule per watcher: a separate rule per element would still hide the watcher's other above-fold elements.
+ $exemptions = '';
foreach ( $above_fold_selectors as $above_fold_selector => $bg_urls ) {
if ( ! self::is_safe_selector( $above_fold_selector ) ) {
return null;
}
- $css_selectors[] = 'html ' . strip_tags( $selector ) . ':not(' . $above_fold_selector . '):not(.optml-bg-lazyloaded)';
+ $exemptions .= ':not(' . $above_fold_selector . ')';
+ }
+ $css_selectors[] = 'html ' . strip_tags( $selector ) . $exemptions . ':not(.optml-bg-lazyloaded)';
+ }
+
+ // This CSS replaces the generic one, so unlisted watchers keep it unless the watcher list may have been cut.
+ if ( count( $personalized_selectors ) < self::MAX_WATCHERS ) {
+ foreach ( array_keys( array_diff_key( $lazyload_selectors, $personalized_selectors ) ) as $selector ) {
+ $css_selectors[] = 'html ' . strip_tags( $selector ) . ':not(.optml-bg-lazyloaded)';
}
}
diff --git a/package-lock.json b/package-lock.json
index 0c0a8ae61..62826add8 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -14,7 +14,7 @@
"usehooks-ts": "^2.9.1"
},
"devDependencies": {
- "@playwright/test": "^1.50.1",
+ "@playwright/test": "^1.61.1",
"@semantic-release/changelog": "^5.0.1",
"@semantic-release/exec": "^5.0.0",
"@semantic-release/git": "^9.0.0",
@@ -3285,13 +3285,13 @@
}
},
"node_modules/@playwright/test": {
- "version": "1.50.1",
- "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.50.1.tgz",
- "integrity": "sha512-Jii3aBg+CEDpgnuDxEp/h7BimHcUTDlpEtce89xEumlJ5ef2hqepZ+PWp1DDpYC/VO9fmWVI1IlEaoI5fK9FXQ==",
+ "version": "1.61.1",
+ "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.61.1.tgz",
+ "integrity": "sha512-8nKv6+0RJSL9FE4jYOEGXnPeM/Hg12qZpmqzZjRh3qM0Y7c3z1mrOTfFLids72RDQYVh9WpLEfR5WdpNX4fkig==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
- "playwright": "1.50.1"
+ "playwright": "1.61.1"
},
"bin": {
"playwright": "cli.js"
@@ -22408,13 +22408,13 @@
}
},
"node_modules/playwright": {
- "version": "1.50.1",
- "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.50.1.tgz",
- "integrity": "sha512-G8rwsOQJ63XG6BbKj2w5rHeavFjy5zynBA9zsJMMtBoe/Uf757oG12NXz6e6OirF7RCrTVAKFXbLmn1RbL7Qaw==",
+ "version": "1.61.1",
+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.61.1.tgz",
+ "integrity": "sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
- "playwright-core": "1.50.1"
+ "playwright-core": "1.61.1"
},
"bin": {
"playwright": "cli.js"
@@ -22439,9 +22439,9 @@
}
},
"node_modules/playwright/node_modules/playwright-core": {
- "version": "1.50.1",
- "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.50.1.tgz",
- "integrity": "sha512-ra9fsNWayuYumt+NiM069M6OkcRb1FZSK8bgi66AtpFoWkg2+y0bJSNmkFrWhMbEBbVKC/EruAHH3g0zmtwGmQ==",
+ "version": "1.61.1",
+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.61.1.tgz",
+ "integrity": "sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg==",
"dev": true,
"license": "Apache-2.0",
"bin": {
@@ -32765,12 +32765,12 @@
"dev": true
},
"@playwright/test": {
- "version": "1.50.1",
- "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.50.1.tgz",
- "integrity": "sha512-Jii3aBg+CEDpgnuDxEp/h7BimHcUTDlpEtce89xEumlJ5ef2hqepZ+PWp1DDpYC/VO9fmWVI1IlEaoI5fK9FXQ==",
+ "version": "1.61.1",
+ "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.61.1.tgz",
+ "integrity": "sha512-8nKv6+0RJSL9FE4jYOEGXnPeM/Hg12qZpmqzZjRh3qM0Y7c3z1mrOTfFLids72RDQYVh9WpLEfR5WdpNX4fkig==",
"dev": true,
"requires": {
- "playwright": "1.50.1"
+ "playwright": "1.61.1"
}
},
"@pmmmwh/react-refresh-webpack-plugin": {
@@ -47090,19 +47090,19 @@
}
},
"playwright": {
- "version": "1.50.1",
- "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.50.1.tgz",
- "integrity": "sha512-G8rwsOQJ63XG6BbKj2w5rHeavFjy5zynBA9zsJMMtBoe/Uf757oG12NXz6e6OirF7RCrTVAKFXbLmn1RbL7Qaw==",
+ "version": "1.61.1",
+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.61.1.tgz",
+ "integrity": "sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ==",
"dev": true,
"requires": {
"fsevents": "2.3.2",
- "playwright-core": "1.50.1"
+ "playwright-core": "1.61.1"
},
"dependencies": {
"playwright-core": {
- "version": "1.50.1",
- "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.50.1.tgz",
- "integrity": "sha512-ra9fsNWayuYumt+NiM069M6OkcRb1FZSK8bgi66AtpFoWkg2+y0bJSNmkFrWhMbEBbVKC/EruAHH3g0zmtwGmQ==",
+ "version": "1.61.1",
+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.61.1.tgz",
+ "integrity": "sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg==",
"dev": true
}
}
diff --git a/package.json b/package.json
index 7ae2996a0..f4ac7b606 100755
--- a/package.json
+++ b/package.json
@@ -49,7 +49,7 @@
"make-pot": "docker run --user root --rm --volume $(pwd):/var/www/html/optimole-wp wordpress:cli bash -c 'php -d memory_limit=512M $(which wp) --version --allow-root && wp i18n make-pot optimole-wp ./optimole-wp/languages/optimole-wp.pot --include=inc,assets/src --allow-root --domain=optimole-wp'"
},
"devDependencies": {
- "@playwright/test": "^1.50.1",
+ "@playwright/test": "^1.61.1",
"@semantic-release/changelog": "^5.0.1",
"@semantic-release/exec": "^5.0.0",
"@semantic-release/git": "^9.0.0",
diff --git a/tests/test-bg-selector.php b/tests/test-bg-selector.php
index f03680e2e..f1cb2a3bc 100644
--- a/tests/test-bg-selector.php
+++ b/tests/test-bg-selector.php
@@ -127,9 +127,153 @@ public function test_personalized_css_drops_injected_selectors(): void {
]
);
- $this->assertStringNotContainsString( 'background:red', $css );
- $this->assertStringNotContainsString( self::PAYLOAD, $css );
- $this->assertSame( '', $css );
+ $this->assertNull( $css );
+ }
+
+ /**
+ * Issue 1216: all above-fold elements of a watcher are exempted in one rule, since a separate
+ * rule per element would still hide the other elements.
+ */
+ public function test_personalized_css_exempts_all_above_fold_elements_in_one_rule(): void {
+ $device_data = [ 'bg' => [ self::WATCHER => [ '#hero-a' => [], '#hero-b' => [] ] ] ];
+
+ $css = Lazyload::get_personalized_css(
+ [
+ Profile::DEVICE_TYPE_MOBILE => $device_data,
+ Profile::DEVICE_TYPE_DESKTOP => $device_data,
+ ]
+ );
+
+ $this->assertStringContainsString( 'html ' . self::WATCHER . ':not(#hero-a):not(#hero-b):not(.optml-bg-lazyloaded)', $css );
+ $this->assertStringNotContainsString( 'html ' . self::WATCHER . ':not(#hero-a):not(.optml-bg-lazyloaded)', $css );
+ $this->assertStringNotContainsString( 'html ' . self::WATCHER . ':not(#hero-b):not(.optml-bg-lazyloaded)', $css );
+ }
+
+ /**
+ * A watcher the profile does not list keeps its generic hide rule while the watcher list is below the cap.
+ */
+ public function test_personalized_css_keeps_generic_rule_for_unlisted_watchers(): void {
+ $device_data = [ 'bg' => [ '.bg-0' => [ '#hero' => [] ] ] ];
+
+ $css = $this->get_css_with_watchers( 1, $device_data );
+
+ $this->assertStringContainsString( 'html ' . self::WATCHER . ':not(.optml-bg-lazyloaded)', $css );
+ $this->assertStringContainsString( 'html .bg-0:not(#hero):not(.optml-bg-lazyloaded)', $css );
+ }
+
+ /**
+ * When the profile lists the maximum number of watchers, the client may have cut others, so unlisted
+ * watchers get no hide rule.
+ */
+ public function test_personalized_css_skips_unlisted_watchers_when_watcher_list_is_full(): void {
+ $watchers = array_map(
+ static function ( int $index ): string {
+ return '.bg-' . $index;
+ },
+ range( 0, Lazyload::MAX_WATCHERS )
+ );
+ $bg = array_fill_keys( array_slice( $watchers, 0, Lazyload::MAX_WATCHERS ), [] );
+ $bg['.bg-0'] = [ '#hero' => [] ];
+
+ $css = $this->get_css_with_watchers( Lazyload::MAX_WATCHERS + 1, [ 'bg' => $bg ] );
+
+ $this->assertStringNotContainsString( 'html .bg-' . Lazyload::MAX_WATCHERS . ':', $css );
+ $this->assertStringNotContainsString( 'html ' . self::WATCHER . ':', $css );
+ $this->assertStringContainsString( 'html .bg-0:not(#hero):not(.optml-bg-lazyloaded)', $css );
+ $this->assertStringContainsString( 'html .bg-1:not(.optml-bg-lazyloaded)', $css );
+ }
+
+ /**
+ * A watcher whose above-fold list hit the cap may be missing above-fold elements, so it gets no hide rule.
+ */
+ public function test_personalized_css_skips_watcher_with_full_above_fold_list(): void {
+ $above_fold = [];
+ foreach ( range( 1, Lazyload::MAX_ABOVE_FOLD_SELECTORS ) as $index ) {
+ $above_fold[ '#hero-' . $index ] = [];
+ }
+ $device_data = [
+ 'bg' => [
+ '.bg-0' => $above_fold,
+ '.bg-1' => array_slice( $above_fold, 0, Lazyload::MAX_ABOVE_FOLD_SELECTORS - 1 ),
+ ],
+ ];
+
+ $css = $this->get_css_with_watchers( 2, $device_data );
+
+ $this->assertStringNotContainsString( 'html .bg-0:', $css );
+ $this->assertStringContainsString( 'html .bg-1:not(#hero-1)', $css );
+ }
+
+ /**
+ * When one device's watcher hit the above-fold cap, the other device's hide rule stays in its media query.
+ */
+ public function test_personalized_css_scopes_other_device_rule_when_one_device_is_capped(): void {
+ $above_fold = [];
+ foreach ( range( 1, Lazyload::MAX_ABOVE_FOLD_SELECTORS ) as $index ) {
+ $above_fold[ '#hero-' . $index ] = [];
+ }
+ $only_watcher = static function (): array {
+ return [ '.bg-0' ];
+ };
+ add_filter( 'optml_lazyload_bg_selectors', $only_watcher );
+ $this->reset_background_selectors();
+
+ $css = Lazyload::get_personalized_css(
+ [
+ Profile::DEVICE_TYPE_MOBILE => [ 'bg' => [ '.bg-0' => $above_fold ] ],
+ Profile::DEVICE_TYPE_DESKTOP => [ 'bg' => [ '.bg-0' => array_slice( $above_fold, 0, Lazyload::MAX_ABOVE_FOLD_SELECTORS - 1 ) ] ],
+ ]
+ );
+ remove_filter( 'optml_lazyload_bg_selectors', $only_watcher );
+
+ $this->assertIsString( $css );
+ $this->assertStringStartsWith( '@media (min-width: 601px) { html .bg-0:not(#hero-1)', $css );
+ $this->assertStringNotContainsString( 'max-width', $css );
+ }
+
+ /**
+ * The profiler counts a 600px viewport as mobile, so only the mobile rule applies there.
+ */
+ public function test_personalized_css_device_media_queries_do_not_overlap(): void {
+ $css = Lazyload::get_personalized_css(
+ [
+ Profile::DEVICE_TYPE_MOBILE => [ 'bg' => [ self::WATCHER => [ '#hero-mobile' => [] ] ] ],
+ Profile::DEVICE_TYPE_DESKTOP => [ 'bg' => [ self::WATCHER => [ '#hero-desktop' => [] ] ] ],
+ ]
+ );
+
+ $this->assertIsString( $css );
+ $this->assertStringContainsString( '@media (max-width: 600px) { html ' . self::WATCHER . ':not(#hero-mobile)', $css );
+ $this->assertStringContainsString( '@media (min-width: 601px) { html ' . self::WATCHER . ':not(#hero-desktop)', $css );
+ }
+
+ /**
+ * Build the personalized CSS for both devices with extra watchers .bg-0 … .bg-{count-1} registered.
+ *
+ * @param int $count Number of extra watchers to register.
+ * @param array $device_data Profile data used for both devices.
+ *
+ * @return string Personalized CSS.
+ */
+ private function get_css_with_watchers( int $count, array $device_data ): string {
+ $add_watchers = static function ( array $selectors ) use ( $count ): array {
+ foreach ( range( 0, $count - 1 ) as $index ) {
+ $selectors[] = '.bg-' . $index;
+ }
+ return $selectors;
+ };
+ add_filter( 'optml_lazyload_bg_selectors', $add_watchers );
+ $this->reset_background_selectors();
+
+ $css = Lazyload::get_personalized_css(
+ [
+ Profile::DEVICE_TYPE_MOBILE => $device_data,
+ Profile::DEVICE_TYPE_DESKTOP => $device_data,
+ ]
+ );
+ remove_filter( 'optml_lazyload_bg_selectors', $add_watchers );
+
+ return $css;
}
/**
@@ -151,8 +295,7 @@ public function test_personalized_css_drops_injected_lcp_selector(): void {
]
);
- $this->assertStringNotContainsString( 'background:red', $css );
- $this->assertSame( '', $css );
+ $this->assertNull( $css );
}
/**
@@ -175,8 +318,7 @@ public function test_personalized_css_drops_rule_when_any_selector_unsafe(): voi
]
);
- $this->assertStringNotContainsString( 'background:red', $css );
- $this->assertSame( '', $css );
+ $this->assertNull( $css );
}
/**
@@ -200,7 +342,7 @@ public function test_personalized_css_scopes_surviving_device_to_media_query():
$this->assertStringNotContainsString( 'background:red', $css );
$this->assertStringNotContainsString( self::PAYLOAD, $css );
// The surviving desktop rule must stay desktop-scoped and not apply on phones.
- $this->assertStringStartsWith( '@media (min-width: 600px) {', $css );
+ $this->assertStringStartsWith( '@media (min-width: 601px) {', $css );
$this->assertStringNotContainsString( '@media (max-width: 600px)', $css );
// The safe above-fold and LCP selectors are still rendered (the gating must not over-reject them).
$this->assertStringContainsString( ':not(#hero):not(.optml-bg-lazyloaded)', $css );
diff --git a/tests/test-dam.php b/tests/test-dam.php
index 6313bca56..94bbc17bf 100644
--- a/tests/test-dam.php
+++ b/tests/test-dam.php
@@ -136,6 +136,19 @@ public function test_iframe_url_all_cloud_sites_enabled() {
$this->assertEmpty( $data['sites'] );
}
+ public function test_dashboard_page_renders_loader_before_iframe_issue_1211() {
+ ob_start();
+ $this->dam->render_dashboard_page();
+ $html = ob_get_clean();
+
+ $loader = strpos( $html, 'class="om-dam-loader"' );
+ $iframe = strpos( $html, 'id="om-dam"' );
+
+ $this->assertNotFalse( $loader );
+ $this->assertNotFalse( $iframe );
+ $this->assertLessThan( $iframe, $loader );
+ }
+
public function test_insert_attachments() {
foreach ( $this->inserted_ids as $index => $id ) {
$this->assertIsInt( $id );
diff --git a/tests/test-docs-links.php b/tests/test-docs-links.php
new file mode 100644
index 000000000..84146f9be
--- /dev/null
+++ b/tests/test-docs-links.php
@@ -0,0 +1,89 @@
+assertSame(
+ 'https://docs.optimole.com/wordpress-plugin/best-format?utm_source=wpadmin&utm_medium=settings&utm_campaign=best-format&utm_content=docsoptimolecomwordpress-pluginbest-format',
+ Optml_Admin::docs_url( 'wordpress-plugin/best-format', 'best-format', 'settings' )
+ );
+ }
+
+ /**
+ * A settings description links to its current docs page with UTMs.
+ */
+ public function test_settings_description_links_to_current_page() {
+ $strings = $this->get_dashboard_strings();
+
+ $this->assertStringContainsString(
+ 'href="https://docs.optimole.com/wordpress-plugin/best-format?utm_source=wpadmin&utm_medium=settings&utm_campaign=best-format&utm_content=docsoptimolecomwordpress-pluginbest-format"',
+ $strings['options_strings']['best_format_desc']
+ );
+ }
+
+ /**
+ * No dashboard string links to an old /article/ URL, and every docs link has UTMs.
+ */
+ public function test_no_string_uses_old_article_urls() {
+ $strings = wp_json_encode( $this->get_dashboard_strings(), JSON_UNESCAPED_SLASHES );
+
+ $this->assertStringNotContainsString( 'docs.optimole.com/article/', $strings );
+ // Curly quotes make the browser read the target as a window named ”_blank”, so every click reuses one tab.
+ $this->assertStringNotContainsString( 'target=\u201d', $strings );
+ preg_match_all( '#href=\\\\"(https://docs\.optimole\.com/[^"\\\\]*)#', $strings, $links );
+ $this->assertNotEmpty( $links[1] );
+ foreach ( $links[1] as $link ) {
+ $this->assertStringContainsString( 'utm_source=wpadmin', $link );
+ }
+ }
+
+ /**
+ * The dashboard app gets the Help tab and Watermark docs links with UTMs.
+ *
+ * @covers Optml_Admin::get_dashboard_docs_links
+ */
+ public function test_dashboard_docs_links() {
+ $links = Optml_Admin::get_dashboard_docs_links();
+
+ $this->assertSame(
+ 'https://docs.optimole.com/image-processing/how-to-use-the-custom-integration-in-optimole?utm_source=wpadmin&utm_medium=help&utm_campaign=custom-integration&utm_content=docsoptimolecomimage-processinghow-to-use-the-custom-integration-in-optimole',
+ $links['custom_integration']
+ );
+ $this->assertStringContainsString( 'utm_medium=settings&utm_campaign=watermark', $links['watermark_settings'] );
+ foreach ( $links as $link ) {
+ $this->assertStringStartsWith( 'https://docs.optimole.com/', $link );
+ $this->assertStringNotContainsString( '/article/', $link );
+ $this->assertStringContainsString( 'utm_source=wpadmin', $link );
+ }
+ }
+
+ /**
+ * Get the dashboard strings.
+ *
+ * @return array Dashboard strings.
+ */
+ private function get_dashboard_strings() {
+ $method = new ReflectionMethod( Optml_Admin::class, 'get_dashboard_strings' );
+ $method->setAccessible( true );
+
+ return $method->invoke( new Optml_Admin() );
+ }
+}
diff --git a/tests/test-lazyload.php b/tests/test-lazyload.php
index a7bded325..df06e0b05 100644
--- a/tests/test-lazyload.php
+++ b/tests/test-lazyload.php
@@ -516,6 +516,58 @@ public function test_lazyload_iframe_exclusion() {
$this->assertStringNotContainsString( '', $replaced_content );
}
+ public function test_lazyload_iframe_leaves_content_after_fallback_text_unchanged() {
+ $form = '';
+ $comment = 'One more thing, the details are here.
';
+ $map = '';
+
+ $replaced_content = Optml_Manager::instance()->replace_content( $form . $comment . $map );
+
+ $this->assertStringContainsString( $form . $comment, $replaced_content );
+ $this->assertStringContainsString( '' . $map . ' ', $replaced_content );
+ }
+
+ public function test_lazyload_iframe_rewrites_only_its_src_attribute() {
+ $iframe = 'VIDEO ';
+
+ $replaced_content = Optml_Manager::instance()->replace_content( $iframe );
+
+ $this->assertStringContainsString( '' . $iframe . ' ', $replaced_content );
+ }
+
+ /**
+ * @dataProvider video_titles_with_src_text
+ */
+ public function test_lazyload_video_rewrites_only_its_src_attribute( string $title ) {
+ $video = ' ';
+
+ $replaced_content = Optml_Manager::instance()->replace_content( $video );
+
+ $this->assertStringContainsString( '' . $video . ' ', $replaced_content );
+ }
+
+ public function video_titles_with_src_text(): array {
+ return [
+ 'iframe text' => [ 'iframe src=x onloadstart=alert(1) y=' ],
+ 'video text' => [ 'video src=x onloadstart=alert(1) y=' ],
+ ];
+ }
+
+ public function test_lazyload_video_with_source_preload_ignores_quoted_attribute_text() {
+ $replaced_content = Optml_Manager::instance()->replace_content( ' ' );
+
+ $this->assertStringContainsString( '', $replaced_content );
+ $this->assertStringNotContainsString( '', $replaced_content );
+ }
+
+ public function test_lazyload_iframe_leaves_json_escaped_markup_unchanged() {
+ $iframe = 'VIDEO ';
+
+ $replaced_content = Optml_Manager::instance()->replace_content( json_encode( [ 'html' => $iframe ], JSON_UNESCAPED_SLASHES ) );
+
+ $this->assertSame( [ 'html' => $iframe ], json_decode( $replaced_content, true ) );
+ }
+
public function test_generic_placeholder() {
$settings = new Optml_Settings();
diff --git a/tests/test-upgrade-link.php b/tests/test-upgrade-link.php
new file mode 100644
index 000000000..f713f59ae
--- /dev/null
+++ b/tests/test-upgrade-link.php
@@ -0,0 +1,229 @@
+initial_service_data = $settings->get( 'service_data' );
+
+ $settings->update(
+ 'service_data',
+ [
+ 'cdn_key' => 'example',
+ 'cdn_secret' => 'test',
+ 'whitelist' => [ 'example.org' ],
+ 'user_email' => self::ACCOUNT_EMAIL,
+ 'plan' => 'free',
+ 'visitors_limit' => 2000,
+ 'visitors_left' => 100,
+ ]
+ );
+ }
+
+ /**
+ * Restore the settings, which outlive the database rollback because they are cached statically.
+ */
+ public function tearDown(): void {
+ ( new Optml_Settings() )->update( 'service_data', $this->initial_service_data );
+
+ remove_all_filters( 'themeisle_sdk_is_black_friday_sale' );
+ remove_all_filters( 'themeisle_sdk_current_date' );
+ set_current_screen( 'front' );
+
+ parent::tearDown();
+ }
+
+ /**
+ * Locales for which the SDK adds a language code to a link, with that code.
+ *
+ * @return array
+ */
+ public function localized_locales(): array {
+ return [
+ 'de_DE' => [ 'de_DE', 'de' ],
+ 'de_DE_formal' => [ 'de_DE_formal', 'de' ],
+ 'es_ES' => [ 'es_ES', 'es' ],
+ 'fr_FR' => [ 'fr_FR', 'fr' ],
+ 'it_IT' => [ 'it_IT', 'it' ],
+ 'ja' => [ 'ja', 'ja' ],
+ 'nl_NL' => [ 'nl_NL', 'nl' ],
+ 'nl_NL_formal' => [ 'nl_NL_formal', 'nl' ],
+ 'ro_RO' => [ 'ro_RO', 'ro' ],
+ ];
+ }
+
+ /**
+ * Log in an administrator who uses the given locale, and check how the SDK localizes links for them.
+ *
+ * @param string $locale User locale.
+ * @param string $code Language code the SDK uses for that locale, empty when it uses none.
+ */
+ private function login_admin_with_locale( string $locale = 'de_DE', string $code = 'de' ): void {
+ wp_set_current_user(
+ self::factory()->user->create(
+ [
+ 'role' => 'administrator',
+ 'locale' => $locale,
+ ]
+ )
+ );
+
+ $this->assertSame( $locale, get_user_locale() );
+ $this->assertSame(
+ '' === $code ? 'https://example.org/page/' : "https://example.org/$code/page/",
+ tsdk_translate_link( 'https://example.org/page/' )
+ );
+ }
+
+ /**
+ * Assert a link is the upgrade page with the language code once, carrying the encoded account email.
+ *
+ * @param string $link Link to check.
+ * @param string $code Expected language code, empty for none.
+ * @param string $message Failure message.
+ */
+ private function assert_upgrade_link( string $link, string $code = 'de', string $message = '' ): void {
+ $path = '' === $code ? '/upgrade' : "/$code/upgrade";
+
+ $this->assertStringStartsWith( "https://optimole.com$path?email=", $link, $message );
+
+ parse_str( (string) wp_parse_url( $link, PHP_URL_QUERY ), $query );
+ $this->assertSame( self::ACCOUNT_EMAIL, base64_decode( $query['email'] ), $message );
+ }
+
+ /**
+ * Get the optimole.com links of some markup.
+ *
+ * @param string $html Markup.
+ *
+ * @return string[]
+ */
+ private function get_optimole_links( string $html ): array {
+ preg_match_all( '~href="(https://optimole\.com/[^"]*)"~', $html, $matches );
+
+ return array_map( 'html_entity_decode', $matches[1] );
+ }
+
+ /**
+ * The upgrade link has the language code of the user once, and keeps the account email.
+ *
+ * @dataProvider localized_locales
+ *
+ * @param string $locale User locale.
+ * @param string $code Language code the SDK uses for that locale.
+ */
+ public function test_upgrade_link_has_the_language_code_once( string $locale, string $code ): void {
+ $this->login_admin_with_locale( $locale, $code );
+
+ $this->assert_upgrade_link( Optml_Admin::get_upgrade_base_link(), $code );
+ }
+
+ /**
+ * A locale the SDK does not localize gets the upgrade link without a language code.
+ */
+ public function test_upgrade_link_has_no_language_code_for_other_locales(): void {
+ $this->login_admin_with_locale( 'en_US', '' );
+
+ $this->assert_upgrade_link( Optml_Admin::get_upgrade_base_link(), '' );
+ }
+
+ /**
+ * The Media Library upgrade notice does not add the language code a second time.
+ */
+ public function test_upgrade_notice_link_has_the_language_code_once(): void {
+ $this->login_admin_with_locale();
+ set_current_screen( 'upload' );
+
+ ob_start();
+ ( new Optml_Admin() )->add_notice_upgrade();
+ $output = (string) ob_get_clean();
+
+ $links = $this->get_optimole_links( $output );
+
+ $this->assertCount( 1, $links );
+ $this->assert_upgrade_link( $links[0] );
+ }
+
+ /**
+ * Neither Black Friday notice adds the language code a second time.
+ */
+ public function test_black_friday_links_have_the_language_code_once(): void {
+ $this->login_admin_with_locale();
+ add_filter( 'themeisle_sdk_is_black_friday_sale', '__return_true' );
+ add_filter(
+ 'themeisle_sdk_current_date',
+ static function () {
+ return new DateTime( 'last Friday of November ' . gmdate( 'Y' ) );
+ }
+ );
+
+ $notices = ( new Optml_Admin() )->get_bf_notices( 'free' );
+
+ foreach ( [ 'sidebar', 'banner' ] as $notice ) {
+ $this->assertArrayHasKey( $notice, $notices );
+ $this->assert_upgrade_link( $notices[ $notice ]['cta_link'], 'de', "Wrong upgrade link in the $notice notice." );
+ }
+ }
+
+ /**
+ * Nothing the dashboard app receives links to optimole.com with two language codes.
+ */
+ public function test_dashboard_data_has_no_doubled_language_code(): void {
+ $this->login_admin_with_locale();
+
+ $localize = new ReflectionMethod( Optml_Admin::class, 'localize_dashboard_app' );
+ $localize->setAccessible( true );
+ $data = $localize->invoke( new Optml_Admin() );
+
+ $this->assert_upgrade_link( $data['upgrade_url'] );
+
+ $disabled_account_links = $this->get_optimole_links( $data['strings']['notice_disabled_account'] );
+ $this->assertCount( 1, $disabled_account_links );
+ $this->assert_upgrade_link( $disabled_account_links[0] );
+
+ array_walk_recursive(
+ $data,
+ function ( $value, $key ) {
+ if ( is_string( $value ) ) {
+ $this->assertDoesNotMatchRegularExpression( self::DOUBLED_LANGUAGE_PATTERN, $value, "Doubled language code in '$key'." );
+ }
+ }
+ );
+ }
+}
diff --git a/tests/test-viewport-bg-css.php b/tests/test-viewport-bg-css.php
index ea3140999..3932f20c3 100644
--- a/tests/test-viewport-bg-css.php
+++ b/tests/test-viewport-bg-css.php
@@ -50,7 +50,7 @@ public function setUp(): void {
add_filter( 'optml_page_profile_id', [ self::class, 'profile_id' ] );
foreach ( [ Profile::DEVICE_TYPE_MOBILE, Profile::DEVICE_TYPE_DESKTOP ] as $device ) {
- Optml_Manager::instance()->page_profiler->store( self::PROFILE_ID, $device, [], [ self::WATCHER => [] ] );
+ Optml_Manager::instance()->page_profiler->store( self::PROFILE_ID, $device, [], [ self::WATCHER => [ '#hero' => [] ] ] );
}
}
@@ -98,8 +98,11 @@ private function comment(): string {
return 'x ';
}
+ /**
+ * A rule only the personalized CSS contains: the generic CSS has no above-fold exemption.
+ */
private function personalized_rule(): string {
- return 'html ' . self::WATCHER . ':not(.optml-bg-lazyloaded) { background-image: none !important; }';
+ return 'html ' . self::WATCHER . ':not(#hero):not(.optml-bg-lazyloaded)';
}
public function test_marker_carries_a_random_token(): void {
@@ -211,4 +214,36 @@ public function test_marker_printed_before_the_plugin_style_is_not_paired_with_i
$this->assertStringContainsString( $title, $replaced );
$this->assertStringContainsString( $this->personalized_rule(), $replaced );
}
+
+ public function test_general_css_is_removed_when_every_device_hides_nothing(): void {
+ $only_watcher = static function (): array {
+ return [ self::WATCHER ];
+ };
+ add_filter( 'optml_lazyload_bg_selectors', $only_watcher );
+ $this->reset_background_selectors();
+ $above_fold = [];
+ foreach ( range( 1, Lazyload::MAX_ABOVE_FOLD_SELECTORS ) as $index ) {
+ $above_fold[ '#hero-' . $index ] = [];
+ }
+ foreach ( [ Profile::DEVICE_TYPE_MOBILE, Profile::DEVICE_TYPE_DESKTOP ] as $device ) {
+ Optml_Manager::instance()->page_profiler->store( self::PROFILE_ID, $device, [], [ self::WATCHER => $above_fold ] );
+ }
+ $html = '' . $this->plugin_style() . 'Body.
';
+
+ $replaced = Optml_Manager::instance()->replace_content( $html );
+ remove_filter( 'optml_lazyload_bg_selectors', $only_watcher );
+ $this->reset_background_selectors();
+
+ $this->assertStringContainsString( 'optml_no_js', $replaced );
+ $this->assertStringNotContainsString( 'html ' . self::WATCHER . ':not(.optml-bg-lazyloaded)', $replaced );
+ }
+
+ /**
+ * Reset the cached background lazyload selectors.
+ */
+ private function reset_background_selectors(): void {
+ $property = new ReflectionProperty( Optml_Lazyload_Replacer::class, 'background_lazyload_selectors' );
+ $property->setAccessible( true );
+ $property->setValue( null, null );
+ }
}