Skip to content

Commit

Permalink
Closes #6432: Adds conditions to bail out from beacon
Browse files Browse the repository at this point in the history
  • Loading branch information
Miraeld committed Apr 10, 2024
1 parent ca50f74 commit 1308890
Show file tree
Hide file tree
Showing 8 changed files with 222 additions and 9 deletions.
27 changes: 26 additions & 1 deletion assets/js/lcp-beacon.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ function LCPCandidates(count) {
if (imageURL !== null) {
// Insert element into topCandidates in descending order of area
for (let i = 0; i < topCandidates.length; i++) {

if (area > topCandidates[i].area) {
topCandidates.splice(i, 0, { element, area, imageURL });
topCandidates.length = Math.min(
Expand Down Expand Up @@ -68,6 +68,31 @@ function getImageUrlFromElement(element) {
let performance_images = [];

async function main() {
// AJAX call to check if there are any records for the current URL
const response = await fetch(rocket_lcp_data.ajax_url, {
method: "POST",
credentials: 'same-origin',
body: new URLSearchParams({
action: 'rocket_check_lcp',
url: rocket_lcp_data.url,
rocket_lcp_nonce: rocket_lcp_data.nonce
})
});
const lcp_data = await response.json();
if ( true === lcp_data.success ) {
console.log('Bailing out because data is already available');
return;
}

// Check screen size
const screenWidth = window.innerWidth || document.documentElement.clientWidth;
const screenHeight = window.innerHeight || document.documentElement.clientHeight;
if (
( ( screenWidth < rocket_lcp_data.width_threshold || screenHeight < rocket_lcp_data.height_threshold ) ) ) {
console.log('Bailing out because screen size is not acceptable');
return;
}

// Filter the array based on the condition imageURL is not null
const filteredArray = LCPCandidates(1)
if (filteredArray.length !== 0) {
Expand Down
2 changes: 1 addition & 1 deletion assets/js/lcp-beacon.js.min.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion assets/js/lcp-beacon.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

30 changes: 30 additions & 0 deletions inc/Engine/Media/AboveTheFold/AJAX/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -91,4 +91,34 @@ public function add_lcp_data() {

wp_send_json_success( $item );
}

/**
* Checks if there is existing LCP data for the current URL and device type.
*
* This method is called via AJAX. It checks if there is existing LCP data for the current URL and device type.
* If the data exists, it returns a JSON success response with true. If the data does not exist, it returns a JSON success response with false.
* If the context is not allowed, it returns a JSON error response with false.
*
* @return void
*/
public function check_lcp_data() {
check_ajax_referer( 'rocket_lcp', 'rocket_lcp_nonce' );

if ( ! $this->context->is_allowed() ) {
wp_send_json_error( false );
return;
}

$url = isset( $_POST['url'] ) ? untrailingslashit( esc_url_raw( wp_unslash( $_POST['url'] ) ) ) : '';
$is_mobile = isset( $_POST['is_mobile'] ) ? filter_var( wp_unslash( $_POST['is_mobile'] ), FILTER_VALIDATE_BOOL ) : false;

$row = $this->query->get_row( $url, $is_mobile );

if ( ! empty( $row ) ) {
wp_send_json_success( 'data already exists' );
return;
}

wp_send_json_error( 'data does not exist' );
}
}
15 changes: 13 additions & 2 deletions inc/Engine/Media/AboveTheFold/AJAX/Subscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,10 @@ public function __construct( Controller $controller ) {
*/
public static function get_subscribed_events() {
return [
'wp_ajax_rocket_lcp' => 'add_lcp_data',
'wp_ajax_nopriv_rocket_lcp' => 'add_lcp_data',
'wp_ajax_rocket_lcp' => 'add_lcp_data',
'wp_ajax_nopriv_rocket_lcp' => 'add_lcp_data',
'wp_ajax_rocket_check_lcp' => 'check_lcp_data',
'wp_ajax_nopriv_rocket_check_lcp' => 'check_lcp_data',
];
}

Expand All @@ -42,4 +44,13 @@ public static function get_subscribed_events() {
public function add_lcp_data() {
$this->controller->add_lcp_data();
}

/**
* Callback for checking lcp data
*
* @return void
*/
public function check_lcp_data() {
$this->controller->check_lcp_data();
}
}
32 changes: 28 additions & 4 deletions inc/Engine/Media/AboveTheFold/Frontend/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -350,11 +350,35 @@ public function inject_beacon( $html, $url, $is_mobile ): string {
return $html;
}

/**
* Filters the width threshold for the LCP beacon.
*
* @param int $width_threshold The width threshold. Default is 393 for mobile and 1920 for others.
* @param bool $is_mobile True if the current device is mobile, false otherwise.
* @param string $url The current URL.
*
* @return int The filtered width threshold.
*/
$width_threshold = apply_filters( 'rocket_lcp_width_threshold', ( $is_mobile ? 393 : 1920 ), $is_mobile, $url );

/**
* Filters the height threshold for the LCP beacon.
*
* @param int $height_threshold The height threshold. Default is 830 for mobile and 1080 for others.
* @param bool $is_mobile True if the current device is mobile, false otherwise.
* @param string $url The current URL.
*
* @return int The filtered height threshold.
*/
$height_threshold = apply_filters( 'rocket_lcp_height_threshold', ( $is_mobile ? 830 : 1080 ), $is_mobile, $url );

$data = [
'ajax_url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'rocket_lcp' ),
'url' => $url,
'is_mobile' => $is_mobile,
'ajax_url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'rocket_lcp' ),
'url' => $url,
'is_mobile' => $is_mobile,
'width_threshold' => $width_threshold,
'height_threshold' => $height_threshold,
];

$inline_script = '<script>var rocket_lcp_data = ' . wp_json_encode( $data ) . '</script>';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php

return [
'testShouldReturnErrorWhenNotAllowed' => [
'config' => [
'filter' => false,
'url' => 'http://example.org',
'is_mobile' => false,
'post' => [
'rocket_lcp_nonce' => wp_create_nonce( 'rocket_lcp' ),
'action' => 'rocket_check_lcp',
'url' => 'http://example.org',
'is_mobile' => false,
],
'row' => [],
],
'expected' => [
'result' => false,
],
],
'testShouldReturnExists' => [
'config' => [
'filter' => true,
'url' => 'http://example.org',
'is_mobile' => false,
'post' => [
'rocket_lcp_nonce' => wp_create_nonce( 'rocket_lcp' ),
'action' => 'rocket_check_lcp',
'url' => 'http://example.org',
'is_mobile' => false,
],
'row' => [
'status' => 'completed',
'url' => 'http://example.org',
'lcp' => json_encode( (object) [
'type' => 'img',
'src' => 'http://example.org/wp-content/uploads/image.jpg',
] ),
'viewport' => json_encode( [
0 => (object) [
'type' => 'img',
'src' => 'http://example.org/wp-content/uploads/image.jpg',
],
] ),
],
'row_exists' => true,
],
'expected' => [
'result' => true,
],
],
'testShouldReturnNotExists' => [
'config' => [
'filter' => true,
'url' => 'http://example.org',
'is_mobile' => false,
'post' => [
'rocket_lcp_nonce' => wp_create_nonce( 'rocket_lcp' ),
'action' => 'rocket_check_lcp',
'url' => 'http://example.org',
'is_mobile' => false,
],
'row' => [],
'row_exists' => false,
],
'expected' => [
'result' => false,
],
],
];
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

namespace WP_Rocket\Tests\Integration\Inc\Engine\Media\AboveTheFold\AJAX\Subscriber;

use WP_Rocket\Tests\Integration\AjaxTestCase;

/**
* @covers WP_Rocket\Engine\Media\AboveTheFold\AJAX\Subscriber::check_lcp_data
*
* @group AboveTheFold
*/
class Test_CheckLcpData extends AjaxTestCase {
private $allowed;

public function set_up() {
parent::set_up();

$this->action = 'rocket_check_lcp';
}

/**
* $_POST is cleared in parent method
*
* @return void
*/
public function tear_down() {
remove_filter( 'rocket_above_the_fold_optimization', [ $this, 'set_allowed' ] );

parent::tear_down();
}

/**
* @dataProvider configTestData
*/
public function testShouldReturnExpected( $config, $expected ) {
$_POST = $config['post'];

$this->allowed = $config['filter'];

add_filter( 'rocket_above_the_fold_optimization', [ $this, 'set_allowed' ] );

if ( ! empty( $config['row'] ) ) {
self::addLcp( $config['row'] );
}

$result = $this->callAjaxAction();

$this->assertSame( $expected['result'], $result->success );
}
public function set_allowed() {
return $this->allowed;
}
}

0 comments on commit 1308890

Please sign in to comment.