Actualizacion 7.1.2
This commit is contained in:
+37
@@ -15,6 +15,7 @@ use RankMath\Traits\Hooker;
|
||||
use RankMath\Admin\Page;
|
||||
use RankMath\Admin\Admin_Helper;
|
||||
use RankMath\Helpers\Param;
|
||||
use RankMath\AI_Visibility\Api\Brands_Controller;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
@@ -90,6 +91,10 @@ class Admin {
|
||||
'isSiteUrlValid' => Admin_Helper::is_site_url_valid(),
|
||||
'isPro' => defined( 'RANK_MATH_PRO_FILE' ),
|
||||
'plan' => Helper::get_content_ai_plan(),
|
||||
'languages' => Helper::get_content_ai_languages(),
|
||||
'defaultLanguage' => Helper::content_ai_default_language(),
|
||||
'platforms' => Platforms::all(),
|
||||
'maxPlatforms' => Platforms::max_selectable(),
|
||||
'locales' => array_values(
|
||||
array_filter(
|
||||
array_map(
|
||||
@@ -111,6 +116,7 @@ class Admin {
|
||||
)
|
||||
)
|
||||
),
|
||||
'intervals' => $this->get_intervals(),
|
||||
],
|
||||
],
|
||||
],
|
||||
@@ -118,6 +124,37 @@ class Admin {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the available intervals for AI Visibility.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
private function get_intervals() {
|
||||
$allowed = Brands_Controller::get_allowed_intervals();
|
||||
|
||||
$intervals = [
|
||||
[
|
||||
'label' => esc_html__( 'Daily', 'seo-by-rank-math' ),
|
||||
'value' => 'daily',
|
||||
],
|
||||
[
|
||||
'label' => esc_html__( 'Weekly', 'seo-by-rank-math' ),
|
||||
'value' => 'weekly',
|
||||
],
|
||||
[
|
||||
'label' => esc_html__( 'Monthly', 'seo-by-rank-math' ),
|
||||
'value' => 'monthly',
|
||||
],
|
||||
];
|
||||
|
||||
foreach ( $intervals as &$interval ) {
|
||||
$interval['disabled'] = ! in_array( $interval['value'], $allowed, true );
|
||||
}
|
||||
unset( $interval );
|
||||
|
||||
return $intervals;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enqueue Mixpanel script and inject tracking data for JS events on this page.
|
||||
*/
|
||||
|
||||
+1
-1
@@ -124,7 +124,7 @@ abstract class Base_Controller extends WP_REST_Controller {
|
||||
$args['body'] = wp_json_encode( $body );
|
||||
}
|
||||
|
||||
$url = 'https://ai-visibility.rankmath.com/' . ltrim( $path, '/' );
|
||||
$url = RANK_MATH_AIV_URL . '/' . ltrim( $path, '/' );
|
||||
$response = wp_remote_request( $url, $args );
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
|
||||
+207
-46
@@ -14,7 +14,9 @@ namespace RankMath\AI_Visibility\Api;
|
||||
|
||||
use WP_REST_Server;
|
||||
use WP_REST_Request;
|
||||
use RankMath\Helper;
|
||||
use RankMath\AI_Visibility\Cache;
|
||||
use RankMath\AI_Visibility\Platforms;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
@@ -28,6 +30,66 @@ class Brands_Controller extends Base_Controller {
|
||||
*/
|
||||
const BRAND_ID_PATTERN = '(?P<id>[a-zA-Z0-9\-]+)';
|
||||
|
||||
/**
|
||||
* Allowed values for the `language` request param.
|
||||
*
|
||||
* @param bool $allow_empty Whether '' (no value) is a valid choice.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function get_language_choices( bool $allow_empty = true ): array {
|
||||
$names = wp_list_pluck( Helper::get_content_ai_languages(), 'name' );
|
||||
return $allow_empty ? array_merge( [ '' ], $names ) : $names;
|
||||
}
|
||||
|
||||
/**
|
||||
* Allowed values for the `interval` request param.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function get_interval_choices(): array {
|
||||
return [ 'daily', 'weekly', 'monthly' ];
|
||||
}
|
||||
|
||||
/**
|
||||
* Cadences allowed for a given AI Visibility plan.
|
||||
*
|
||||
* @param string|null $plan Plan slug. Defaults to the current account's plan.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function get_allowed_intervals( ?string $plan = null ): array {
|
||||
$plan = $plan ?? Helper::get_content_ai_plan();
|
||||
|
||||
return 'expert' === $plan
|
||||
? [ 'daily', 'weekly', 'monthly' ]
|
||||
: [ 'weekly', 'monthly' ];
|
||||
}
|
||||
|
||||
/**
|
||||
* Reject an `interval` value the caller's plan does not allow.
|
||||
*
|
||||
* @param string $interval Requested cadence value.
|
||||
*
|
||||
* @return \WP_Error|true
|
||||
*/
|
||||
private function check_interval_allowed( string $interval ) {
|
||||
$allowed = self::get_allowed_intervals();
|
||||
if ( in_array( $interval, $allowed, true ) ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return $this->error(
|
||||
'aiv_frequency_not_allowed',
|
||||
sprintf(
|
||||
/* translators: %s: comma-separated list of allowed cadences. */
|
||||
__( 'The selected analysis frequency is not available on your plan. Allowed frequencies: %s. Upgrade your plan to unlock more frequency options.', 'seo-by-rank-math' ),
|
||||
implode( ', ', $allowed )
|
||||
),
|
||||
403
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register routes.
|
||||
*/
|
||||
@@ -114,6 +176,23 @@ class Brands_Controller extends Base_Controller {
|
||||
'required' => false,
|
||||
'sanitize_callback' => 'sanitize_text_field',
|
||||
],
|
||||
'language' => [
|
||||
'description' => esc_html__( 'Output language to use when analyzing/generating content for this brand. Independent of `locale` (target country). Required; immutable after creation.', 'seo-by-rank-math' ),
|
||||
'type' => 'string',
|
||||
'required' => true,
|
||||
'enum' => self::get_language_choices( false ),
|
||||
'sanitize_callback' => 'sanitize_text_field',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
],
|
||||
'interval' => [
|
||||
'description' => esc_html__( 'Analysis refresh cadence. Omitted → backend applies the account plan\'s default.', 'seo-by-rank-math' ),
|
||||
'type' => 'string',
|
||||
'required' => false,
|
||||
'enum' => self::get_interval_choices(),
|
||||
'sanitize_callback' => 'sanitize_text_field',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
],
|
||||
'platforms' => Platforms::rest_arg( true ),
|
||||
],
|
||||
]
|
||||
);
|
||||
@@ -149,20 +228,33 @@ class Brands_Controller extends Base_Controller {
|
||||
'required' => false,
|
||||
'sanitize_callback' => 'sanitize_text_field',
|
||||
],
|
||||
'language' => [
|
||||
'type' => 'string',
|
||||
'required' => false,
|
||||
'enum' => self::get_language_choices(),
|
||||
'sanitize_callback' => 'sanitize_text_field',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
],
|
||||
'status' => [
|
||||
'type' => 'string',
|
||||
'required' => false,
|
||||
'enum' => [ 'active', 'inactive' ],
|
||||
'sanitize_callback' => 'sanitize_text_field',
|
||||
],
|
||||
'interval' => [
|
||||
'type' => 'string',
|
||||
'required' => false,
|
||||
'enum' => self::get_interval_choices(),
|
||||
'sanitize_callback' => 'sanitize_text_field',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
],
|
||||
'platforms' => Platforms::rest_arg( false ),
|
||||
]
|
||||
),
|
||||
]
|
||||
);
|
||||
|
||||
// GET /brands/{id}/insights — full latest-analysis payload
|
||||
// (competitors + transcripts). Cache-first; the only proxy route that
|
||||
// may call the upstream analyses/results endpoint.
|
||||
// GET /brands/{id}/insights — full latest-analysis payload (competitors + transcripts).
|
||||
register_rest_route(
|
||||
$this->namespace,
|
||||
'/brands/' . self::BRAND_ID_PATTERN . '/insights',
|
||||
@@ -244,15 +336,12 @@ class Brands_Controller extends Base_Controller {
|
||||
return $this->overview_response( $cached, false, $search );
|
||||
}
|
||||
|
||||
// Stale-while-revalidate: serve stale immediately; the client
|
||||
// fires a background `refresh=1` request on seeing `is_stale`.
|
||||
return $this->overview_response( $cached, true, $search );
|
||||
}
|
||||
|
||||
$result = $this->remote_request( 'GET', '/api/v1/overview' );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
// Serve stale cache on upstream failure rather than erroring out.
|
||||
if ( null !== $cached ) {
|
||||
return $this->overview_response( $cached, true, $search );
|
||||
}
|
||||
@@ -276,9 +365,6 @@ class Brands_Controller extends Base_Controller {
|
||||
/**
|
||||
* Map an /overview brand item (API shape) to the UI row shape.
|
||||
*
|
||||
* Note: `description` is not returned by /overview — it is fetched
|
||||
* lazily and cached per brand via `get_brand()`.
|
||||
*
|
||||
* @param array $brand Raw brand item.
|
||||
*
|
||||
* @return array
|
||||
@@ -289,7 +375,10 @@ class Brands_Controller extends Base_Controller {
|
||||
'name' => $brand['name'] ?? '',
|
||||
'url' => $brand['url'] ?? '',
|
||||
'locale' => $brand['country_code'] ?? null,
|
||||
'language' => $brand['language'] ?? null,
|
||||
'status' => ! empty( $brand['active'] ) ? 'active' : 'inactive',
|
||||
'interval' => $brand['analysis_frequency'] ?? null,
|
||||
'platforms' => Platforms::sanitize( $brand['platforms'] ?? [] ),
|
||||
'score' => $brand['ai_visibility_score'] ?? null,
|
||||
'rank' => $brand['rank'] ?? null,
|
||||
'avg_sentiment' => $brand['avg_sentiment'] ?? null,
|
||||
@@ -303,9 +392,7 @@ class Brands_Controller extends Base_Controller {
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the dashboard response envelope, applying the optional search
|
||||
* filter (name/URL) against the stored rows. The filter never affects
|
||||
* what is cached — only what is returned.
|
||||
* Build the dashboard response envelope, applying the optional search filter.
|
||||
*
|
||||
* @param array $data Cached dashboard payload.
|
||||
* @param bool $is_stale Whether the payload is past its TTL.
|
||||
@@ -352,8 +439,7 @@ class Brands_Controller extends Base_Controller {
|
||||
return $this->success( [ 'brand' => $cached ] );
|
||||
}
|
||||
|
||||
// /overview omits `description`, so the single-brand endpoint is the
|
||||
// canonical source for full identity. Fetched once, then cached.
|
||||
// /overview omits `description`; fetch full identity once and cache it.
|
||||
$result = $this->remote_request( 'GET', '/api/v1/brands/' . $uuid );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
@@ -375,17 +461,48 @@ class Brands_Controller extends Base_Controller {
|
||||
* @return \WP_REST_Response|\WP_Error
|
||||
*/
|
||||
public function create_brand( $request ) {
|
||||
$locale = $request->get_param( 'locale' );
|
||||
$result = $this->remote_request(
|
||||
'POST',
|
||||
'/api/v1/brands',
|
||||
[
|
||||
'name' => sanitize_text_field( (string) $request->get_param( 'name' ) ),
|
||||
'url' => esc_url_raw( (string) $request->get_param( 'url' ) ),
|
||||
'description' => sanitize_textarea_field( (string) $request->get_param( 'description' ) ),
|
||||
'country_code' => $locale ? strtoupper( (string) $locale ) : '',
|
||||
]
|
||||
);
|
||||
$locale = $request->get_param( 'locale' );
|
||||
$language = $request->get_param( 'language' );
|
||||
$interval = $request->get_param( 'interval' );
|
||||
$platforms = $request->get_param( 'platforms' );
|
||||
|
||||
// Re-validate: the create-brand ability bypasses the REST arg constraints.
|
||||
$valid = Platforms::validate( $platforms );
|
||||
if ( is_wp_error( $valid ) ) {
|
||||
return $valid;
|
||||
}
|
||||
|
||||
$platforms = Platforms::sanitize( $platforms );
|
||||
|
||||
if ( ! $language ) {
|
||||
return $this->error(
|
||||
'aiv_bad_request',
|
||||
__( 'Please select a language for this brand.', 'seo-by-rank-math' ),
|
||||
400
|
||||
);
|
||||
}
|
||||
|
||||
$body = [
|
||||
'name' => sanitize_text_field( (string) $request->get_param( 'name' ) ),
|
||||
'url' => esc_url_raw( (string) $request->get_param( 'url' ) ),
|
||||
'description' => sanitize_textarea_field( (string) $request->get_param( 'description' ) ),
|
||||
'language' => (string) $language,
|
||||
'platforms' => $platforms,
|
||||
];
|
||||
|
||||
// Omit rather than send '' — the backend rejects an explicit empty string.
|
||||
if ( $locale ) {
|
||||
$body['country_code'] = strtoupper( (string) $locale );
|
||||
}
|
||||
if ( $interval ) {
|
||||
$allowed = $this->check_interval_allowed( $interval );
|
||||
if ( is_wp_error( $allowed ) ) {
|
||||
return $allowed;
|
||||
}
|
||||
$body['analysis_frequency'] = (string) $interval;
|
||||
}
|
||||
|
||||
$result = $this->remote_request( 'POST', '/api/v1/brands', $body );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return $result;
|
||||
@@ -394,9 +511,7 @@ class Brands_Controller extends Base_Controller {
|
||||
$brand = $this->map_brand( $result );
|
||||
$uuid = $brand['id'];
|
||||
|
||||
// Prime caches from the create response. Creation atomically seeds a
|
||||
// pending analysis, so the row starts as `pending` (no last_analyzed) —
|
||||
// this is what makes it eligible for the first-analysis poller.
|
||||
// Row starts as `pending` — creation atomically seeds the first analysis.
|
||||
Cache::append_brand_row(
|
||||
array_merge(
|
||||
$brand,
|
||||
@@ -421,8 +536,9 @@ class Brands_Controller extends Base_Controller {
|
||||
'AI Visibility Brand Created',
|
||||
[
|
||||
'locale' => $brand['locale'] ?? null,
|
||||
'interval' => 'weekly',
|
||||
'platforms' => [ 'chatgpt' ],
|
||||
'language' => $brand['language'] ?? null,
|
||||
'interval' => $brand['interval'] ?? null,
|
||||
'platforms' => $platforms,
|
||||
]
|
||||
);
|
||||
|
||||
@@ -460,6 +576,31 @@ class Brands_Controller extends Base_Controller {
|
||||
$body['country_code'] = strtoupper( sanitize_text_field( $locale ) );
|
||||
}
|
||||
|
||||
// Omit blank values — the backend rejects an explicit empty string.
|
||||
$language = $request->get_param( 'language' );
|
||||
if ( $language ) {
|
||||
$body['language'] = sanitize_text_field( $language );
|
||||
}
|
||||
|
||||
$interval = $request->get_param( 'interval' );
|
||||
if ( null !== $interval ) {
|
||||
$allowed = $this->check_interval_allowed( $interval );
|
||||
if ( is_wp_error( $allowed ) ) {
|
||||
return $allowed;
|
||||
}
|
||||
$body['analysis_frequency'] = sanitize_text_field( $interval );
|
||||
}
|
||||
|
||||
$platforms = $request->get_param( 'platforms' );
|
||||
if ( null !== $platforms ) {
|
||||
$valid = Platforms::validate( $platforms );
|
||||
if ( is_wp_error( $valid ) ) {
|
||||
return $valid;
|
||||
}
|
||||
|
||||
$body['platforms'] = Platforms::sanitize( $platforms );
|
||||
}
|
||||
|
||||
if ( empty( $body ) ) {
|
||||
return $this->error( 'aiv_bad_request', __( 'No fields to update.', 'seo-by-rank-math' ), 400 );
|
||||
}
|
||||
@@ -472,7 +613,6 @@ class Brands_Controller extends Base_Controller {
|
||||
|
||||
$brand = $this->map_brand( isset( $result['data'] ) ? $result['data'] : $result );
|
||||
|
||||
// Write-through: patch the dashboard row, replace the identity transient.
|
||||
Cache::patch_brand_row(
|
||||
$uuid,
|
||||
[
|
||||
@@ -480,7 +620,10 @@ class Brands_Controller extends Base_Controller {
|
||||
'url' => $brand['url'],
|
||||
'description' => $brand['description'],
|
||||
'locale' => $brand['locale'],
|
||||
'language' => $brand['language'],
|
||||
'status' => $brand['status'],
|
||||
'interval' => $brand['interval'],
|
||||
'platforms' => $brand['platforms'],
|
||||
]
|
||||
);
|
||||
Cache::set_brand( $uuid, $brand );
|
||||
@@ -492,6 +635,8 @@ class Brands_Controller extends Base_Controller {
|
||||
'fields_changed' => array_keys( $body ),
|
||||
'status_changed' => $status_changed,
|
||||
'new_status' => $status_changed ? $brand['status'] : null,
|
||||
'platforms' => $brand['platforms'],
|
||||
'language' => $brand['language'] ?? null,
|
||||
]
|
||||
);
|
||||
|
||||
@@ -512,9 +657,12 @@ class Brands_Controller extends Base_Controller {
|
||||
'url' => $brand['url'] ?? '',
|
||||
'description' => $brand['description'] ?? '',
|
||||
'locale' => $brand['country_code'] ?? null,
|
||||
'language' => $brand['language'] ?? null,
|
||||
'status' => $brand['status'] ?? 'active',
|
||||
'interval' => $brand['analysis_frequency'] ?? null,
|
||||
'last_analyzed' => $brand['last_analyzed_at'] ?? null,
|
||||
'created_at' => $brand['created_at'] ?? null,
|
||||
'platforms' => Platforms::sanitize( $brand['platforms'] ?? [] ),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -568,15 +716,22 @@ class Brands_Controller extends Base_Controller {
|
||||
);
|
||||
|
||||
// Keep the dashboard row's summary in sync (poller success path).
|
||||
$finished_ats = array_filter( array_column( $insights['analyses'], 'finished_at' ) );
|
||||
|
||||
// Resolve status here rather than relying on /overview, which can lag.
|
||||
$analysis_statuses = array_column( $insights['analyses'], 'status' );
|
||||
$analysis_status = in_array( 'error', $analysis_statuses, true ) ? 'error' : 'success';
|
||||
|
||||
Cache::patch_brand_row(
|
||||
$uuid,
|
||||
[
|
||||
'score' => $insights['score'],
|
||||
'rank' => $insights['rank'],
|
||||
'avg_sentiment' => $insights['avg_sentiment'],
|
||||
'mentions' => $insights['mentions'],
|
||||
'citations' => $insights['citations'],
|
||||
'last_analyzed' => $insights['analysis']['finished_at'],
|
||||
'score' => $insights['score'],
|
||||
'rank' => $insights['rank'],
|
||||
'avg_sentiment' => $insights['avg_sentiment'],
|
||||
'mentions' => $insights['mentions'],
|
||||
'citations' => $insights['citations'],
|
||||
'last_analyzed' => $finished_ats ? max( $finished_ats ) : null,
|
||||
'analysis_status' => $analysis_status,
|
||||
]
|
||||
);
|
||||
|
||||
@@ -591,7 +746,7 @@ class Brands_Controller extends Base_Controller {
|
||||
* @return array
|
||||
*/
|
||||
private function map_insights( $result ) {
|
||||
$analysis = isset( $result['analysis'] ) ? (array) $result['analysis'] : [];
|
||||
$analyses = isset( $result['analyses'] ) ? (array) $result['analyses'] : [];
|
||||
|
||||
return [
|
||||
'score' => $result['ai_visibility_score'] ?? null,
|
||||
@@ -599,14 +754,19 @@ class Brands_Controller extends Base_Controller {
|
||||
'avg_sentiment' => $result['avg_sentiment'] ?? null,
|
||||
'mentions' => $result['mentions'] ?? null,
|
||||
'citations' => $result['citations'] ?? null,
|
||||
'analysis' => [
|
||||
'id' => $analysis['uuid'] ?? null,
|
||||
// Map the API status vocabulary to the UI one (`success` → `done`).
|
||||
'status' => isset( $analysis['status'] ) && 'success' === $analysis['status'] ? 'done' : ( $analysis['status'] ?? null ),
|
||||
'started_at' => $analysis['started_at'] ?? null,
|
||||
'finished_at' => $analysis['finished_at'] ?? null,
|
||||
'duration_seconds' => $analysis['duration_seconds'] ?? null,
|
||||
],
|
||||
'analyses' => array_map(
|
||||
function ( $analysis ) {
|
||||
return [
|
||||
'id' => $analysis['uuid'] ?? null,
|
||||
'platform' => $analysis['platform'] ?? null,
|
||||
'status' => isset( $analysis['status'] ) && 'success' === $analysis['status'] ? 'done' : ( $analysis['status'] ?? null ),
|
||||
'started_at' => $analysis['started_at'] ?? null,
|
||||
'finished_at' => $analysis['finished_at'] ?? null,
|
||||
'duration_seconds' => $analysis['duration_seconds'] ?? null,
|
||||
];
|
||||
},
|
||||
$analyses
|
||||
),
|
||||
'competitors' => array_map(
|
||||
function ( $competitor ) {
|
||||
return [
|
||||
@@ -623,6 +783,7 @@ class Brands_Controller extends Base_Controller {
|
||||
return [
|
||||
'query_id' => $query_result['query_uuid'] ?? null,
|
||||
'query_text' => $query_result['query_text'] ?? '',
|
||||
'platform' => $query_result['platform'] ?? null,
|
||||
'found' => ! empty( $query_result['found'] ),
|
||||
'rank' => $query_result['rank_among_competitors'] ?? null,
|
||||
'sentiment' => $query_result['sentiment_score'] ?? null,
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
+10
-10
@@ -7,7 +7,7 @@
|
||||
/**
|
||||
* WordPress dependencies
|
||||
*/
|
||||
import { useMemo, useState, useEffect } from '@wordpress/element'
|
||||
import { useMemo, useState, useEffect, useRef } from '@wordpress/element'
|
||||
import { __ } from '@wordpress/i18n'
|
||||
import { SelectControl, SearchControl, Button } from '@wordpress/components'
|
||||
|
||||
@@ -43,28 +43,31 @@ const AnalysesFilterBar = ( {
|
||||
} ) => {
|
||||
const ns = 'rank-math-ai-visibility-analyses-filter-bar'
|
||||
|
||||
// Prepend "All Brands" option to the brand list.
|
||||
const brandSelectOptions = useMemo( () => [
|
||||
{ label: __( 'All Brands', 'seo-by-rank-math' ), value: '' },
|
||||
...brandOptions,
|
||||
], [ brandOptions ] )
|
||||
|
||||
// The hook stores brandIds as an array. For the single-select UI we store
|
||||
// the first item (or '') and convert back on change.
|
||||
// brandIds is an array; the single-select UI only needs the first item.
|
||||
const activeBrandId = ( filters.brandIds && filters.brandIds[ 0 ] )
|
||||
? String( filters.brandIds[ 0 ] )
|
||||
: ''
|
||||
|
||||
// Local search state — debounced 300 ms before propagating to the hook.
|
||||
// This prevents a new API request on every keystroke.
|
||||
const [ localSearch, setLocalSearch ] = useState( filters.search || '' )
|
||||
const isFirstSearchRender = useRef( true )
|
||||
|
||||
// Sync local state if the parent resets filters externally (e.g. "clear all").
|
||||
// Sync when the parent resets filters externally (e.g. "clear all").
|
||||
useEffect( () => {
|
||||
setLocalSearch( filters.search || '' )
|
||||
}, [ filters.search ] )
|
||||
|
||||
// Skip on mount — avoids a no-op filter change resetting pagination.
|
||||
useEffect( () => {
|
||||
if ( isFirstSearchRender.current ) {
|
||||
isFirstSearchRender.current = false
|
||||
return
|
||||
}
|
||||
|
||||
const timer = setTimeout( () => {
|
||||
onFilterChange( { search: localSearch } )
|
||||
}, 300 )
|
||||
@@ -82,7 +85,6 @@ const AnalysesFilterBar = ( {
|
||||
return (
|
||||
<div className={ ns }>
|
||||
|
||||
{ /* Brand — standard SelectControl, matches Status style */ }
|
||||
<SelectControl
|
||||
className={ `${ ns }__brand` }
|
||||
value={ activeBrandId }
|
||||
@@ -102,7 +104,6 @@ const AnalysesFilterBar = ( {
|
||||
__nextHasNoMarginBottom={ true }
|
||||
/>
|
||||
|
||||
{ /* Search — value bound to local state; propagation is debounced 300 ms */ }
|
||||
<SearchControl
|
||||
className={ `${ ns }__search` }
|
||||
placeholder={ __( 'Search', 'seo-by-rank-math' ) }
|
||||
@@ -123,7 +124,6 @@ const AnalysesFilterBar = ( {
|
||||
</Button>
|
||||
) }
|
||||
|
||||
{ /* Date range: [📅 From] - [📅 To] */ }
|
||||
<div className={ `${ ns }__dates` }>
|
||||
<div className={ `${ ns }__date-wrap` }>
|
||||
<DateInput
|
||||
|
||||
+27
-15
@@ -26,20 +26,28 @@ import './AnalysisRunDetail.scss'
|
||||
/**
|
||||
* Map an insights query result to the shape TranscriptModal expects.
|
||||
*
|
||||
* The id is qualified by platform — the backend reuses the same query_id
|
||||
* across platforms, so an unqualified id would collide.
|
||||
*
|
||||
* @param {Object} result Query result from the insights payload.
|
||||
* @param {number} index Fallback index.
|
||||
* @param {Object} analysis Parent analysis meta.
|
||||
* @param {Object} analysis Analysis run (matched by platform) this result belongs to.
|
||||
* @return {Object} Normalised entry.
|
||||
*/
|
||||
const normalise = ( result, index, analysis ) => ( {
|
||||
...result,
|
||||
id: result.query_id ?? index,
|
||||
query: result.query_text ?? '',
|
||||
response: result.response ?? '',
|
||||
created_at: analysis?.finished_at ?? null,
|
||||
duration_seconds: analysis?.duration_seconds ?? null,
|
||||
model: null,
|
||||
} )
|
||||
const normalise = ( result, index, analysis ) => {
|
||||
const baseId = result.query_id ?? index
|
||||
const platform = result.platform ?? 'default'
|
||||
|
||||
return {
|
||||
...result,
|
||||
id: `${ baseId }-${ platform }`,
|
||||
query: result.query_text ?? '',
|
||||
response: result.response ?? '',
|
||||
created_at: analysis?.finished_at ?? null,
|
||||
duration_seconds: analysis?.duration_seconds ?? null,
|
||||
model: null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* AnalysisRunDetail component.
|
||||
@@ -60,10 +68,14 @@ const AnalysisRunDetail = ( { row, onBack } ) => {
|
||||
const insights = insightsData?.insights ?? null
|
||||
const [ modalEntry, setModalEntry ] = useState( null )
|
||||
|
||||
const transcripts = ( insights?.query_results ?? [] ).map( ( result, i ) => normalise( result, i, insights?.analysis ) )
|
||||
const totalDuration = insights?.analysis?.duration_seconds ?? 0
|
||||
const analyses = insights?.analyses ?? []
|
||||
const findAnalysis = ( platform ) => analyses.find( ( analysis ) => analysis.platform === platform ) ?? analyses[ 0 ] ?? null
|
||||
|
||||
const transcripts = ( insights?.query_results ?? [] ).map( ( result, i ) => normalise( result, i, findAnalysis( result.platform ) ) )
|
||||
const totalDuration = analyses.reduce( ( sum, analysis ) => sum + ( analysis.duration_seconds ?? 0 ), 0 )
|
||||
const durationLabel = totalDuration ? `${ totalDuration }s` : '—'
|
||||
const startedAt = row?.started_at ?? insights?.analysis?.started_at
|
||||
const startedAts = analyses.map( ( analysis ) => analysis.started_at ).filter( Boolean ).sort()
|
||||
const startedAt = row?.started_at ?? startedAts[ 0 ]
|
||||
|
||||
const handleExportReport = () => navigateToReportsTab( row.id )
|
||||
|
||||
@@ -94,7 +106,7 @@ const AnalysisRunDetail = ( { row, onBack } ) => {
|
||||
value={ row?.brand_name || '—' }
|
||||
className="rank-math-ai-visibility-stat-card--target-brand"
|
||||
tooltip={ __( 'The brand this analysis run is for.', 'seo-by-rank-math' ) }
|
||||
analysis={ insights?.analysis }
|
||||
analysis={ analyses[ 0 ] ?? null }
|
||||
/>
|
||||
|
||||
<StatCard
|
||||
@@ -105,7 +117,7 @@ const AnalysisRunDetail = ( { row, onBack } ) => {
|
||||
sub={ formatShortDate( startedAt ) }
|
||||
className="rank-math-ai-visibility-stat-card--duration-timing"
|
||||
tooltip={ __( 'Total duration of all queries in this run, and the date it was started.', 'seo-by-rank-math' ) }
|
||||
analysis={ insights?.analysis }
|
||||
analysis={ analyses[ 0 ] ?? null }
|
||||
/>
|
||||
|
||||
</div>
|
||||
|
||||
+14
-25
@@ -20,6 +20,7 @@ import { addQueryArgs } from '@wordpress/url'
|
||||
* Internal dependencies
|
||||
*/
|
||||
import useDashboard from '../shared/hooks/useDashboard'
|
||||
import usePagination from '../shared/hooks/usePagination'
|
||||
import { getAnalysisState } from '../utils/analysisState'
|
||||
import { SectionHeader } from '../shared/components'
|
||||
import AnalysesFilterBar from './AnalysesFilterBar'
|
||||
@@ -36,20 +37,15 @@ const DEFAULT_FILTERS = {
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync filters + pagination into the URL without reloading.
|
||||
*
|
||||
* @param {Object} filters Active filter bag.
|
||||
* @param {Object} pagination Active pagination.
|
||||
* @param {Object} filters Active filter bag.
|
||||
*/
|
||||
const writeToUrl = ( filters, pagination ) => {
|
||||
const writeFiltersToUrl = ( filters ) => {
|
||||
const params = {
|
||||
aiv_brands: filters.brandIds.length ? filters.brandIds.join( ',' ) : undefined,
|
||||
aiv_status: filters.status || undefined,
|
||||
aiv_search: filters.search || undefined,
|
||||
aiv_from: filters.dateFrom || undefined,
|
||||
aiv_to: filters.dateTo || undefined,
|
||||
aiv_page: pagination.page > 1 ? pagination.page : undefined,
|
||||
aiv_per: pagination.perPage !== 10 ? pagination.perPage : undefined,
|
||||
}
|
||||
|
||||
const url = addQueryArgs( window.location.href, params )
|
||||
@@ -70,8 +66,7 @@ const toRunRow = ( brand ) => {
|
||||
brand_id: brand.id,
|
||||
brand_name: brand.name,
|
||||
started_at: brand.last_analyzed,
|
||||
// Display/filter bucket: running | error | done | none. Same icon
|
||||
// derivation as the Dashboard column, so the two tabs never disagree.
|
||||
// Matches the Dashboard column's derivation, so both tabs agree.
|
||||
status: state ?? ( brand.last_analyzed ? 'done' : 'none' ),
|
||||
}
|
||||
}
|
||||
@@ -85,7 +80,6 @@ const Analyses = () => {
|
||||
const { brands, loading, error } = useDashboard()
|
||||
|
||||
const [ filters, setFilters ] = useState( DEFAULT_FILTERS )
|
||||
const [ pagination, setPagination ] = useState( { page: 1, perPage: 10 } )
|
||||
const [ selectedRow, setSelectedRow ] = useState( null )
|
||||
|
||||
const brandOptions = useMemo(
|
||||
@@ -93,7 +87,6 @@ const Analyses = () => {
|
||||
[ brands ]
|
||||
)
|
||||
|
||||
// Derive + filter rows client-side.
|
||||
const filteredItems = useMemo( () => {
|
||||
return brands.map( toRunRow ).filter( ( item ) => {
|
||||
if ( filters.search && ! item.brand_name.toLowerCase().includes( filters.search.toLowerCase() ) ) {
|
||||
@@ -118,26 +111,22 @@ const Analyses = () => {
|
||||
} )
|
||||
}, [ brands, filters ] )
|
||||
|
||||
const total = filteredItems.length
|
||||
const pages = Math.max( 1, Math.ceil( total / pagination.perPage ) )
|
||||
const pageItems = useMemo( () => {
|
||||
const offset = ( pagination.page - 1 ) * pagination.perPage
|
||||
return filteredItems.slice( offset, offset + pagination.perPage )
|
||||
}, [ filteredItems, pagination ] )
|
||||
const { pagination, pageItems, total, pages, onPageChange, onPerPageChange, resetPage } =
|
||||
usePagination( filteredItems, { perPage: 10, syncUrl: true } )
|
||||
|
||||
const handleFilterChange = useCallback( ( patch ) => {
|
||||
setFilters( ( prev ) => ( { ...prev, ...patch } ) )
|
||||
setPagination( ( prev ) => ( { ...prev, page: 1 } ) )
|
||||
}, [] )
|
||||
resetPage()
|
||||
}, [ resetPage ] )
|
||||
|
||||
const handleClearFilters = useCallback( () => {
|
||||
setFilters( DEFAULT_FILTERS )
|
||||
setPagination( ( prev ) => ( { ...prev, page: 1 } ) )
|
||||
}, [] )
|
||||
resetPage()
|
||||
}, [ resetPage ] )
|
||||
|
||||
useEffect( () => {
|
||||
writeToUrl( filters, pagination )
|
||||
}, [ filters, pagination ] )
|
||||
writeFiltersToUrl( filters )
|
||||
}, [ filters ] )
|
||||
|
||||
if ( selectedRow ) {
|
||||
return (
|
||||
@@ -177,8 +166,8 @@ const Analyses = () => {
|
||||
loading={ loading }
|
||||
pagination={ { ...pagination, total, pages } }
|
||||
onViewDetail={ ( row ) => setSelectedRow( row ) }
|
||||
onPageChange={ ( page ) => setPagination( ( prev ) => ( { ...prev, page: Math.max( 1, page ) } ) ) }
|
||||
onPerPageChange={ ( perPage ) => setPagination( { page: 1, perPage: Math.max( 1, perPage ) } ) }
|
||||
onPageChange={ onPageChange }
|
||||
onPerPageChange={ onPerPageChange }
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
+2
-2
@@ -76,7 +76,7 @@ const App = ( { config = {} } ) => {
|
||||
setActiveTab( tabName )
|
||||
}
|
||||
|
||||
const { isSiteConnected, isPro, plan, locales = [] } = rankMath.aiVisibility
|
||||
const { isSiteConnected, isPro, plan, locales = [], languages = [], defaultLanguage = '', intervals = [], platforms = {}, maxPlatforms = 1 } = rankMath.aiVisibility
|
||||
|
||||
// Access gate — Free Content AI plan: PRO users get the trial flow,
|
||||
// free plugin users get the upgrade modal.
|
||||
@@ -100,7 +100,7 @@ const App = ( { config = {} } ) => {
|
||||
<div className={ 'rank-math-ai-visibility__tab rank-math-ai-visibility__tab--' + tab.name }>
|
||||
{ ! isSiteConnected && <Connect config={ config } /> }
|
||||
{ isSiteConnected && (
|
||||
isPlanGated ? <GatedPreview /> : createElement( tab.view, { locales, onBrandCreated: showSnackbar } )
|
||||
isPlanGated ? <GatedPreview /> : createElement( tab.view, { locales, languages, defaultLanguage, intervals, platforms, maxPlatforms, onBrandCreated: showSnackbar } )
|
||||
) }
|
||||
</div>
|
||||
) }
|
||||
|
||||
+5
@@ -72,6 +72,11 @@ const BrandHeader = ( {
|
||||
{ brand.url }
|
||||
</a>
|
||||
{ brand.locale && <CountryFlag locale={ brand.locale } /> }
|
||||
{ brand.language && (
|
||||
<span className={ `${ ns }__language` }>
|
||||
{ brand.language }
|
||||
</span>
|
||||
) }
|
||||
<a
|
||||
className={ `${ ns }__external` }
|
||||
href={ getBrandUrl( brand.url ) }
|
||||
|
||||
+10
@@ -81,6 +81,16 @@
|
||||
}
|
||||
}
|
||||
|
||||
&__language {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 2px 8px;
|
||||
border-radius: 20px;
|
||||
font-size: 11px;
|
||||
color: $color-text-muted;
|
||||
border: 1px solid $color-border;
|
||||
}
|
||||
|
||||
&__external {
|
||||
color: #757575;
|
||||
display: inline-flex;
|
||||
|
||||
+3
-3
@@ -50,7 +50,7 @@ const BrandOverview = ( { brand, insights = null, loading = false } ) => {
|
||||
: placeholder
|
||||
}
|
||||
tooltip={ __( 'AI Visibility Score for this brand across AI platforms.', 'seo-by-rank-math' ) }
|
||||
analysis={ insights?.analysis }
|
||||
analysis={ insights?.analyses?.[ 0 ] }
|
||||
/>
|
||||
|
||||
<StatCard
|
||||
@@ -71,7 +71,7 @@ const BrandOverview = ( { brand, insights = null, loading = false } ) => {
|
||||
: placeholder
|
||||
}
|
||||
tooltip={ __( 'Average sentiment score across all AI mentions of this brand.', 'seo-by-rank-math' ) }
|
||||
analysis={ insights?.analysis }
|
||||
analysis={ insights?.analyses?.[ 0 ] }
|
||||
/>
|
||||
|
||||
<StatCard
|
||||
@@ -98,7 +98,7 @@ const BrandOverview = ( { brand, insights = null, loading = false } ) => {
|
||||
label={ __( 'Top Competitor', 'seo-by-rank-math' ) }
|
||||
value={ topCompetitor || placeholder }
|
||||
tooltip={ __( 'The competitor brand with the highest share of voice in AI mentions.', 'seo-by-rank-math' ) }
|
||||
analysis={ insights?.analysis }
|
||||
analysis={ insights?.analyses?.[ 0 ] }
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
+25
-12
@@ -20,21 +20,29 @@ import './RunDetail.scss'
|
||||
/**
|
||||
* Map an insights query result to the shape TranscriptViewer expects.
|
||||
*
|
||||
* The id is qualified by platform — the backend reuses the same query_id
|
||||
* across platforms, so an unqualified id would collide.
|
||||
*
|
||||
* @param {Object} result Query result from the insights payload.
|
||||
* @param {number} index Fallback index.
|
||||
* @param {Object} analysis Parent analysis meta.
|
||||
* @param {Object} analysis Analysis run (matched by platform) this result belongs to.
|
||||
* @return {Object} Normalised entry.
|
||||
*/
|
||||
const toEntry = ( result, index, analysis ) => ( {
|
||||
...result,
|
||||
id: result.query_id ?? index,
|
||||
query: result.query_text ?? '',
|
||||
response: result.response ?? '',
|
||||
created_at: analysis?.finished_at ?? null,
|
||||
duration_seconds: analysis?.duration_seconds ?? null,
|
||||
status: result.found ? 'success' : 'partial',
|
||||
model: null,
|
||||
} )
|
||||
const toEntry = ( result, index, analysis ) => {
|
||||
const baseId = result.query_id ?? index
|
||||
const platform = result.platform ?? 'default'
|
||||
|
||||
return {
|
||||
...result,
|
||||
id: `${ baseId }-${ platform }`,
|
||||
query: result.query_text ?? '',
|
||||
response: result.response ?? '',
|
||||
created_at: analysis?.finished_at ?? null,
|
||||
duration_seconds: analysis?.duration_seconds ?? null,
|
||||
status: result.found ? 'success' : 'partial',
|
||||
model: null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} props
|
||||
@@ -44,7 +52,12 @@ const toEntry = ( result, index, analysis ) => ( {
|
||||
*/
|
||||
const RunDetail = ( { insights = null, loading = false } ) => {
|
||||
const entries = useMemo(
|
||||
() => ( insights?.query_results ?? [] ).map( ( result, i ) => toEntry( result, i, insights?.analysis ) ),
|
||||
() => {
|
||||
const analyses = insights?.analyses ?? []
|
||||
const findAnalysis = ( platform ) => analyses.find( ( analysis ) => analysis.platform === platform ) ?? analyses[ 0 ] ?? null
|
||||
|
||||
return ( insights?.query_results ?? [] ).map( ( result, i ) => toEntry( result, i, findAnalysis( result.platform ) ) )
|
||||
},
|
||||
[ insights ]
|
||||
)
|
||||
|
||||
|
||||
+11
-1
@@ -55,9 +55,14 @@ const SUB_TABS = [
|
||||
* @param {number} props.brandId
|
||||
* @param {Function} [props.onBack]
|
||||
* @param {Array} [props.locales]
|
||||
* @param {Array} [props.languages]
|
||||
* @param {string} [props.defaultLanguage] Default language for new brands (site language).
|
||||
* @param {Array} [props.intervals]
|
||||
* @param {Object} [props.platforms] AI platform registry from PHP.
|
||||
* @param {number} [props.maxPlatforms] Platforms selectable on the current plan.
|
||||
* @return {JSX.Element} Rendered component.
|
||||
*/
|
||||
const BrandDetail = ( { brandId, onBack, locales = [] } ) => {
|
||||
const BrandDetail = ( { brandId, onBack, locales = [], languages = [], defaultLanguage = '', intervals = [], platforms = {}, maxPlatforms = 1 } ) => {
|
||||
const handleBack = onBack || navigateBackToDashboard
|
||||
const { data: brandData, loading, error, setData: setBrandData } = useFetch(
|
||||
() => getBrand( brandId ),
|
||||
@@ -165,6 +170,11 @@ const BrandDetail = ( { brandId, onBack, locales = [] } ) => {
|
||||
isSaving={ isSaving }
|
||||
apiError={ saveError }
|
||||
locales={ locales }
|
||||
languages={ languages }
|
||||
defaultLanguage={ defaultLanguage }
|
||||
intervals={ intervals }
|
||||
platforms={ platforms }
|
||||
maxPlatforms={ maxPlatforms }
|
||||
/>
|
||||
) }
|
||||
|
||||
|
||||
+1
-1
@@ -52,7 +52,7 @@ const GatedPreview = () => {
|
||||
<StatCard
|
||||
className="rank-math-ai-visibility-stat-card--analyses"
|
||||
icon={ trendingUp }
|
||||
label={ __( 'Analyses in last 24h', 'seo-by-rank-math' ) }
|
||||
label={ __( 'Analyses in the last 7 days', 'seo-by-rank-math' ) }
|
||||
value={ 0 }
|
||||
/>
|
||||
<StatCard
|
||||
|
||||
+36
-15
@@ -21,6 +21,7 @@ import { trendingUp, store } from '@wordpress/icons'
|
||||
* Internal dependencies
|
||||
*/
|
||||
import useDashboard from '../shared/hooks/useDashboard'
|
||||
import usePagination from '../shared/hooks/usePagination'
|
||||
import { getBrand } from '../shared/services/api/aiVisibilityApi'
|
||||
import { StatCard, EmptyState } from '../shared/components'
|
||||
import { ConfirmModal, AddBrandModal, UpgradePlanModal } from '../shared/Modals'
|
||||
@@ -67,11 +68,11 @@ const getConfirmMessage = ( confirmBrand, confirmAction ) => {
|
||||
/**
|
||||
* Resolve the display value for a summary StatCard.
|
||||
*
|
||||
* @param {Object} options
|
||||
* @param {boolean} options.loading Whether the dashboard is still loading.
|
||||
* @param {boolean} options.hasBrands Whether any brands are tracked.
|
||||
* @param {*} options.raw Raw summary value (may be null/undefined).
|
||||
* @param {Function} [options.format] Optional formatter for a present value.
|
||||
* @param {Object} options
|
||||
* @param {boolean} options.loading Whether the dashboard is still loading.
|
||||
* @param {boolean} options.hasBrands Whether any brands are tracked.
|
||||
* @param {*} options.raw Raw summary value (may be null/undefined).
|
||||
* @param {Function} [options.format] Optional formatter for a present value.
|
||||
* @return {string|number|null} Placeholder, null (empty), 0 (missing) or formatted value.
|
||||
*/
|
||||
const getStatValue = ( { loading, hasBrands, raw, format } ) => {
|
||||
@@ -89,11 +90,16 @@ const getStatValue = ( { loading, hasBrands, raw, format } ) => {
|
||||
|
||||
/**
|
||||
* @param {Object} props
|
||||
* @param {Array} [props.locales] Locale options for the brand modals.
|
||||
* @param {Function} [props.onBrandCreated] Callback when a new brand is successfully created.
|
||||
* @param {Array} [props.locales] Locale options for the brand modals.
|
||||
* @param {Array} [props.languages] Output language options for the brand modals.
|
||||
* @param {string} [props.defaultLanguage] Default language for new brands (site language).
|
||||
* @param {Object} [props.platforms] AI platform registry from PHP.
|
||||
* @param {number} [props.maxPlatforms] Platforms selectable on the current plan.
|
||||
* @param {Function} [props.onBrandCreated] Callback when a new brand is successfully created.
|
||||
* @param {Array} [props.intervals] Interval options for the brand modals.
|
||||
* @return {JSX.Element} Rendered component.
|
||||
*/
|
||||
const Dashboard = ( { locales = [], onBrandCreated = () => {} } ) => {
|
||||
const Dashboard = ( { locales = [], languages = [], defaultLanguage = '', platforms = {}, maxPlatforms = 1, onBrandCreated = () => {}, intervals = [] } ) => {
|
||||
const [ activeBrandId, setActiveBrandId ] = useState( getActiveBrandId )
|
||||
|
||||
useEffect( () => {
|
||||
@@ -114,13 +120,11 @@ const Dashboard = ( { locales = [], onBrandCreated = () => {} } ) => {
|
||||
handleEnableBrand,
|
||||
} = useDashboard()
|
||||
|
||||
// Modal state
|
||||
const [ isAddModalOpen, setAddModalOpen ] = useState( false )
|
||||
const [ editBrand, setEditBrand ] = useState( null )
|
||||
const [ isSaving, setIsSaving ] = useState( false )
|
||||
const [ saveError, setSaveError ] = useState( null )
|
||||
|
||||
// ConfirmModal state
|
||||
const [ confirmBrand, setConfirmBrand ] = useState( null )
|
||||
const [ confirmAction, setConfirmAction ] = useState( 'delete' )
|
||||
const [ isProcessing, setIsProcessing ] = useState( false )
|
||||
@@ -128,10 +132,13 @@ const Dashboard = ( { locales = [], onBrandCreated = () => {} } ) => {
|
||||
|
||||
const [ isUpgradeModalOpen, setUpgradeModalOpen ] = useState( false )
|
||||
|
||||
// Search: debounced 300 ms, proxy filters cached rows server-side.
|
||||
// Search is debounced 300ms.
|
||||
const [ searchQuery, setSearchQuery ] = useState( '' )
|
||||
const isFirstSearchRender = useRef( true )
|
||||
|
||||
const { pagination, pageItems, total, pages, onPageChange, onPerPageChange, resetPage } =
|
||||
usePagination( brands, { perPage: 10, syncUrl: true } )
|
||||
|
||||
useEffect( () => {
|
||||
if ( isFirstSearchRender.current ) {
|
||||
isFirstSearchRender.current = false
|
||||
@@ -140,9 +147,10 @@ const Dashboard = ( { locales = [], onBrandCreated = () => {} } ) => {
|
||||
|
||||
const timer = setTimeout( () => {
|
||||
handleSearch( searchQuery.trim() )
|
||||
resetPage()
|
||||
}, 300 )
|
||||
return () => clearTimeout( timer )
|
||||
}, [ searchQuery, handleSearch ] )
|
||||
}, [ searchQuery, handleSearch, resetPage ] )
|
||||
|
||||
const hasActiveSearch = !! searchQuery.trim()
|
||||
const isEmpty = ! loading && brands.length === 0 && ! hasActiveSearch
|
||||
@@ -234,6 +242,11 @@ const Dashboard = ( { locales = [], onBrandCreated = () => {} } ) => {
|
||||
brandId={ activeBrandId }
|
||||
onBack={ handleBackToDashboard }
|
||||
locales={ locales }
|
||||
languages={ languages }
|
||||
defaultLanguage={ defaultLanguage }
|
||||
intervals={ intervals }
|
||||
platforms={ platforms }
|
||||
maxPlatforms={ maxPlatforms }
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -260,8 +273,8 @@ const Dashboard = ( { locales = [], onBrandCreated = () => {} } ) => {
|
||||
<StatCard
|
||||
className="rank-math-ai-visibility-stat-card--analyses"
|
||||
icon={ trendingUp }
|
||||
label={ __( 'Analyses in last 24h', 'seo-by-rank-math' ) }
|
||||
value={ getStatValue( { loading, hasBrands: brands.length > 0, raw: summary?.analyses_last_24h } ) }
|
||||
label={ __( 'Analyses in the last 7 days', 'seo-by-rank-math' ) }
|
||||
value={ getStatValue( { loading, hasBrands: brands.length > 0, raw: summary?.analyses_last_7d } ) }
|
||||
tooltip={ __( 'Total analysis runs completed in the past 24 hours.', 'seo-by-rank-math' ) }
|
||||
/>
|
||||
<StatCard
|
||||
@@ -297,8 +310,9 @@ const Dashboard = ( { locales = [], onBrandCreated = () => {} } ) => {
|
||||
/>
|
||||
|
||||
<BrandsTable
|
||||
brands={ brands }
|
||||
brands={ pageItems }
|
||||
loading={ loading }
|
||||
pagination={ { ...pagination, total, pages } }
|
||||
onView={ handleViewBrand }
|
||||
onEdit={ async ( brand ) => {
|
||||
setEditBrand( brand )
|
||||
@@ -313,6 +327,8 @@ const Dashboard = ( { locales = [], onBrandCreated = () => {} } ) => {
|
||||
}
|
||||
} }
|
||||
onDisable={ ( brand ) => openDisableConfirm( brand ) }
|
||||
onPageChange={ onPageChange }
|
||||
onPerPageChange={ onPerPageChange }
|
||||
/>
|
||||
</div>
|
||||
) }
|
||||
@@ -325,6 +341,11 @@ const Dashboard = ( { locales = [], onBrandCreated = () => {} } ) => {
|
||||
isSaving={ isSaving }
|
||||
apiError={ saveError }
|
||||
locales={ locales }
|
||||
languages={ languages }
|
||||
defaultLanguage={ defaultLanguage }
|
||||
intervals={ intervals }
|
||||
platforms={ platforms }
|
||||
maxPlatforms={ maxPlatforms }
|
||||
/>
|
||||
) }
|
||||
|
||||
|
||||
+4
@@ -136,7 +136,11 @@ const Reports = () => {
|
||||
rows[ 0 ].competitors = ( data?.insights?.competitors ?? [] ).map( ( c ) => c.name )
|
||||
rows[ 0 ].queries = ( data?.insights?.query_results ?? [] ).map( ( q ) => ( {
|
||||
query: q.query_text ?? '',
|
||||
platform: q.platform ?? null,
|
||||
response: q.response ?? '',
|
||||
found: q.found ?? null,
|
||||
sentiment_score: q.sentiment ?? null,
|
||||
citations_count: q.citations ?? null,
|
||||
} ) )
|
||||
} catch {
|
||||
// Competitors and queries are nice-to-have in the report — ignore.
|
||||
|
||||
+120
-77
@@ -7,7 +7,7 @@
|
||||
/**
|
||||
* WordPress dependencies
|
||||
*/
|
||||
import { __ } from '@wordpress/i18n'
|
||||
import { __, _n, sprintf } from '@wordpress/i18n'
|
||||
import { useState, useEffect, useMemo, useRef } from '@wordpress/element'
|
||||
import { Modal, TextControl, TextareaControl, SelectControl, CheckboxControl, Icon } from '@wordpress/components'
|
||||
import { close } from '@wordpress/icons'
|
||||
@@ -19,54 +19,31 @@ import { SelectWithSearch } from '@rank-math/components'
|
||||
import Button from '../components/Button'
|
||||
import LoadingButton from '../components/LoadingButton'
|
||||
import getLink from '@helpers/getLink'
|
||||
import { toPlatformList, getDefaultPlatforms, getEnabledPlatformIds } from '../services/platforms'
|
||||
import './AddBrandModal.scss'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Constants
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const EMPTY_FORM = {
|
||||
/**
|
||||
* Blank form state.
|
||||
*
|
||||
* @param {Array} platformList Available platforms.
|
||||
* @param {string} [defaultLanguage=''] Default language for a new brand (site language).
|
||||
* @return {Object} Empty form values.
|
||||
*/
|
||||
const emptyForm = ( platformList, defaultLanguage = '' ) => ( {
|
||||
name: '',
|
||||
url: '',
|
||||
description: '',
|
||||
locale: '',
|
||||
interval: 'weekly',
|
||||
platforms: [ 'chatgpt' ],
|
||||
}
|
||||
language: defaultLanguage,
|
||||
interval: 'monthly',
|
||||
platforms: getDefaultPlatforms( platformList ),
|
||||
} )
|
||||
|
||||
/**
|
||||
* Order in which fields are validated / scrolled to.
|
||||
* Used to focus the first errored field on a failed save.
|
||||
*/
|
||||
const FIELD_ORDER = [ 'name', 'url', 'description' ]
|
||||
|
||||
/**
|
||||
* Analysis interval options.
|
||||
*/
|
||||
const INTERVAL_OPTIONS = [
|
||||
{ label: __( 'Weekly', 'seo-by-rank-math' ), value: 'weekly', disabled: false },
|
||||
{ label: __( 'Monthly (Coming Soon)', 'seo-by-rank-math' ), value: 'monthly', disabled: true },
|
||||
{ label: __( 'Daily (Coming Soon)', 'seo-by-rank-math' ), value: 'daily', disabled: true },
|
||||
]
|
||||
|
||||
/**
|
||||
* AI Platform definitions.
|
||||
*
|
||||
* `enabled` — whether the platform is available for selection.
|
||||
* Disabled platforms show a "Coming Soon" badge.
|
||||
*
|
||||
* Layout: left column = index 0–2, right column = index 3–4.
|
||||
*/
|
||||
const AI_PLATFORMS = [
|
||||
{ id: 'chatgpt', label: 'ChatGPT', enabled: true },
|
||||
{ id: 'perplexity', label: 'Perplexity', enabled: false },
|
||||
{ id: 'google_ai_overview', label: 'Google AI Overview', enabled: false },
|
||||
{ id: 'gemini', label: 'Gemini', enabled: false },
|
||||
{ id: 'claude', label: 'Claude', enabled: false },
|
||||
]
|
||||
|
||||
const LEFT_PLATFORMS = AI_PLATFORMS.slice( 0, 3 )
|
||||
const RIGHT_PLATFORMS = AI_PLATFORMS.slice( 3 )
|
||||
const FIELD_ORDER = [ 'name', 'url', 'description', 'language' ]
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Sub-components
|
||||
@@ -114,12 +91,17 @@ const PlatformRow = ( { platform, checked, onChange, disabled } ) => {
|
||||
* AddBrandModal component.
|
||||
*
|
||||
* @param {Object} props
|
||||
* @param {Object|null} [props.brand=null] null = add mode, object = edit (pre-fills form).
|
||||
* @param {Function} props.onSave Called with the validated form payload.
|
||||
* @param {Function} props.onClose Called when the modal should close.
|
||||
* @param {boolean} [props.isSaving=false] Shows spinner + disables all fields.
|
||||
* @param {string | null} props.apiError API error message to display.
|
||||
* @param {Array} [props.locales=[]] Locale options injected from PHP via wp_localize_script.
|
||||
* @param {Object|null} [props.brand=null] null = add mode, object = edit (pre-fills form).
|
||||
* @param {Function} props.onSave Called with the validated form payload.
|
||||
* @param {Function} props.onClose Called when the modal should close.
|
||||
* @param {boolean} [props.isSaving=false] Shows spinner + disables all fields.
|
||||
* @param {string | null} props.apiError API error message to display.
|
||||
* @param {Array} [props.locales=[]] Locale options injected from PHP via wp_localize_script.
|
||||
* @param {Array} [props.languages=[]] Output language options injected from PHP via wp_localize_script.
|
||||
* @param {string} [props.defaultLanguage=''] Default language for a new brand (site language), injected from PHP.
|
||||
* @param {Array} [props.intervals=[]] { label, value, disabled } options injected from PHP via wp_localize_script.
|
||||
* @param {Object} [props.platforms={}] AI platform registry injected from PHP.
|
||||
* @param {number} [props.maxPlatforms=1] Platforms selectable on the current plan.
|
||||
* @return {JSX.Element} Brand add/edit dialog.
|
||||
*/
|
||||
const AddBrandModal = ( {
|
||||
@@ -129,8 +111,16 @@ const AddBrandModal = ( {
|
||||
isSaving = false,
|
||||
apiError = null,
|
||||
locales = [],
|
||||
languages = [],
|
||||
defaultLanguage = '',
|
||||
intervals = [],
|
||||
platforms = {},
|
||||
maxPlatforms = 1,
|
||||
} ) => {
|
||||
const [ form, setForm ] = useState( EMPTY_FORM )
|
||||
const platformList = useMemo( () => toPlatformList( platforms ), [ platforms ] )
|
||||
const enabledPlatformCount = useMemo( () => getEnabledPlatformIds( platformList ).length, [ platformList ] )
|
||||
|
||||
const [ form, setForm ] = useState( () => emptyForm( platformList, defaultLanguage ) )
|
||||
const [ errors, setErrors ] = useState( {} )
|
||||
|
||||
const ns = 'rank-math-ai-visibility-add-brand-modal'
|
||||
@@ -140,6 +130,7 @@ const AddBrandModal = ( {
|
||||
name: useRef( null ),
|
||||
url: useRef( null ),
|
||||
description: useRef( null ),
|
||||
language: useRef( null ),
|
||||
}
|
||||
|
||||
// Locale options — object map expected by SelectWithSearch: { value: label, … }
|
||||
@@ -152,6 +143,14 @@ const AddBrandModal = ( {
|
||||
[ locales ]
|
||||
)
|
||||
|
||||
const languageOptions = useMemo(
|
||||
() => languages.reduce( ( acc, { name, icon } ) => {
|
||||
acc[ name ] = icon ? `${ icon } ${ name }` : name
|
||||
return acc
|
||||
}, {} ),
|
||||
[ languages ]
|
||||
)
|
||||
|
||||
// Pre-fill when editing.
|
||||
useEffect( () => {
|
||||
if ( brand ) {
|
||||
@@ -161,12 +160,17 @@ const AddBrandModal = ( {
|
||||
url: brand.url ?? '',
|
||||
description: brand.description ?? '',
|
||||
locale: brand.locale ?? '',
|
||||
interval: brand.interval ?? 'weekly',
|
||||
platforms: brand.platforms ?? [ 'chatgpt' ],
|
||||
// Legacy brands predate the language field.
|
||||
language: brand.language ?? 'US English',
|
||||
interval: brand.interval ?? 'monthly',
|
||||
platforms: brand.platforms?.length
|
||||
? brand.platforms.slice( 0, maxPlatforms )
|
||||
: getDefaultPlatforms( platformList ),
|
||||
} )
|
||||
} else {
|
||||
setForm( EMPTY_FORM )
|
||||
setForm( emptyForm( platformList, defaultLanguage ) )
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [ brand ] )
|
||||
|
||||
// ── Field helpers ────────────────────────────────────────────────────────
|
||||
@@ -184,18 +188,24 @@ const AddBrandModal = ( {
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle a platform ID in the platforms array.
|
||||
* Toggle a platform. Selecting past the plan cap evicts the oldest pick.
|
||||
*
|
||||
* @param {string} id Platform id to toggle.
|
||||
*/
|
||||
const togglePlatform = ( id ) => {
|
||||
setForm( ( prev ) => {
|
||||
const exists = prev.platforms.includes( id )
|
||||
if ( prev.platforms.includes( id ) ) {
|
||||
return {
|
||||
...prev,
|
||||
platforms: prev.platforms.filter( ( p ) => p !== id ),
|
||||
}
|
||||
}
|
||||
|
||||
const next = [ ...prev.platforms, id ]
|
||||
|
||||
return {
|
||||
...prev,
|
||||
platforms: exists
|
||||
? prev.platforms.filter( ( p ) => p !== id )
|
||||
: [ ...prev.platforms, id ],
|
||||
platforms: next.slice( Math.max( 0, next.length - maxPlatforms ) ),
|
||||
}
|
||||
} )
|
||||
}
|
||||
@@ -229,6 +239,9 @@ const AddBrandModal = ( {
|
||||
if ( ! form.description.trim() ) {
|
||||
newErrors.description = __( 'Description is required.', 'seo-by-rank-math' )
|
||||
}
|
||||
if ( ! form.language ) {
|
||||
newErrors.language = __( 'Language is required.', 'seo-by-rank-math' )
|
||||
}
|
||||
|
||||
setErrors( newErrors )
|
||||
return newErrors
|
||||
@@ -266,13 +279,14 @@ const AddBrandModal = ( {
|
||||
url: form.url.trim(),
|
||||
description: form.description.trim(),
|
||||
locale: form.locale,
|
||||
language: form.language,
|
||||
interval: form.interval,
|
||||
platforms: form.platforms,
|
||||
} )
|
||||
}
|
||||
|
||||
const isEditMode = Boolean( brand )
|
||||
const isActionDisabled = isSaving || form?.platforms?.length === 0 || Object.keys( errors ).length > 0
|
||||
const isActionDisabled = isSaving || form?.platforms?.length === 0 || ! form?.language || Object.keys( errors ).length > 0
|
||||
|
||||
return (
|
||||
<Modal
|
||||
@@ -370,12 +384,35 @@ const AddBrandModal = ( {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={ `${ ns }__field` } ref={ fieldRefs.language }>
|
||||
<span className={ `${ ns }__label` }>
|
||||
{ __( 'Output Language', 'seo-by-rank-math' ) }
|
||||
</span>
|
||||
<SelectWithSearch
|
||||
value={ form.language }
|
||||
options={ languageOptions }
|
||||
onChange={ set( 'language' ) }
|
||||
disabled={ isSaving || isEditMode }
|
||||
className={ errors.language ? `${ ns }__field--error` : '' }
|
||||
/>
|
||||
{ errors.language && (
|
||||
<p className={ `${ ns }__field-note ${ ns }__field-note--error` }>
|
||||
{ errors.language }
|
||||
</p>
|
||||
) }
|
||||
{ isEditMode && (
|
||||
<p className={ `${ ns }__field-note` }>
|
||||
{ __( 'Language can\'t be changed after a brand is created.', 'seo-by-rank-math' ) }
|
||||
</p>
|
||||
) }
|
||||
</div>
|
||||
|
||||
{ /* Interval */ }
|
||||
<div className={ `${ ns }__field` }>
|
||||
<SelectControl
|
||||
label={ __( 'Frequency of analyses', 'seo-by-rank-math' ) }
|
||||
value={ form.interval }
|
||||
options={ INTERVAL_OPTIONS }
|
||||
options={ intervals }
|
||||
onChange={ set( 'interval' ) }
|
||||
disabled={ isSaving }
|
||||
__next40pxDefaultSize={ true }
|
||||
@@ -388,29 +425,35 @@ const AddBrandModal = ( {
|
||||
<span className={ `${ ns }__label` }>
|
||||
{ __( 'AI Platforms', 'seo-by-rank-math' ) }
|
||||
</span>
|
||||
{ maxPlatforms < enabledPlatformCount && (
|
||||
<p className={ `${ ns }__field-note` }>
|
||||
{ sprintf(
|
||||
/* translators: %d: number of AI platforms selectable on the current plan. */
|
||||
_n(
|
||||
'Your plan lets you track %d platform per brand. Upgrade to Expert to track them all at once.',
|
||||
'Your plan lets you track %d platforms per brand. Upgrade to Expert to track them all at once.',
|
||||
maxPlatforms,
|
||||
'seo-by-rank-math'
|
||||
),
|
||||
maxPlatforms
|
||||
) }
|
||||
</p>
|
||||
) }
|
||||
{ form.platforms.length === 0 && (
|
||||
<p className={ `${ ns }__field-note ${ ns }__field-note--error` }>
|
||||
{ __( 'Select at least one AI platform.', 'seo-by-rank-math' ) }
|
||||
</p>
|
||||
) }
|
||||
<div className={ `${ ns }__platforms` }>
|
||||
<div className={ `${ ns }__platforms-col` }>
|
||||
{ LEFT_PLATFORMS.map( ( platform ) => (
|
||||
<PlatformRow
|
||||
key={ platform.id }
|
||||
platform={ platform }
|
||||
checked={ form.platforms.includes( platform.id ) }
|
||||
onChange={ () => togglePlatform( platform.id ) }
|
||||
disabled={ isSaving }
|
||||
/>
|
||||
) ) }
|
||||
</div>
|
||||
<div className={ `${ ns }__platforms-col` }>
|
||||
{ RIGHT_PLATFORMS.map( ( platform ) => (
|
||||
<PlatformRow
|
||||
key={ platform.id }
|
||||
platform={ platform }
|
||||
checked={ form.platforms.includes( platform.id ) }
|
||||
onChange={ () => togglePlatform( platform.id ) }
|
||||
disabled={ isSaving }
|
||||
/>
|
||||
) ) }
|
||||
</div>
|
||||
{ platformList.map( ( platform ) => (
|
||||
<PlatformRow
|
||||
key={ platform.id }
|
||||
platform={ platform }
|
||||
checked={ form.platforms.includes( platform.id ) }
|
||||
onChange={ () => togglePlatform( platform.id ) }
|
||||
disabled={ isSaving }
|
||||
/>
|
||||
) ) }
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
+11
-6
@@ -132,6 +132,16 @@
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
&__field-note {
|
||||
margin: 4px 0 0;
|
||||
font-size: 12px;
|
||||
color: $color-text-muted;
|
||||
|
||||
&--error {
|
||||
color: $color-trend-down;
|
||||
}
|
||||
}
|
||||
|
||||
.components-base-control__label,
|
||||
.components-input-control__label {
|
||||
font-size: 11px;
|
||||
@@ -186,16 +196,11 @@
|
||||
&__platforms {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
grid-auto-flow: row;
|
||||
gap: 10px 16px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
&__platforms-col {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
&__platform-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
+1
-1
@@ -34,7 +34,7 @@ import './StatCard.scss'
|
||||
* @return {JSX.Element} Stat card with icon, label, value, and optional trend.
|
||||
*/
|
||||
const StatCard = ( { icon, label, value, tooltip, sub, compact = false, className = '', analysis = null } ) => {
|
||||
const hasData = ( analysis?.status && analysis?.status === 'done' ) ?? ( value !== null && value !== undefined && value !== '' && value !== '—' )
|
||||
const hasData = ( analysis?.status && ( analysis?.status === 'done' || analysis?.status === 'partial' ) ) ?? ( value !== null && value !== undefined && value !== '' && value !== '—' )
|
||||
|
||||
const ns = 'rank-math-ai-visibility-stat-card'
|
||||
|
||||
|
||||
+4
@@ -173,6 +173,10 @@ const TranscriptViewer = ( {
|
||||
if ( e.query ) {
|
||||
label = e.query.length > 60 ? e.query.slice( 0, 60 ) + '…' : e.query
|
||||
}
|
||||
// Append platform — multiple platforms can share the same query text.
|
||||
if ( e.platform ) {
|
||||
label += ` — ${ e.platform }`
|
||||
}
|
||||
return { label, value: String( e.id ) }
|
||||
} ),
|
||||
], [ entries ] )
|
||||
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* usePagination — client-side pagination over an in-memory array.
|
||||
*
|
||||
* @since 1.0.274
|
||||
*/
|
||||
|
||||
/**
|
||||
* WordPress dependencies
|
||||
*/
|
||||
import { useState, useMemo, useCallback, useEffect, useRef } from '@wordpress/element'
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import { getPageFromUrl, getPerPageFromUrl, writePaginationToUrl } from '../../utils/urlState'
|
||||
|
||||
const DEFAULT_PER_PAGE = 10
|
||||
|
||||
/**
|
||||
* @param {Array} items Full, already-filtered item list to paginate.
|
||||
* @param {Object} [options]
|
||||
* @param {number} [options.perPage=10] Default/initial page size.
|
||||
* @param {boolean} [options.syncUrl=false] Read the initial page from the URL and keep it updated.
|
||||
* @return {Object} `{ pagination, pageItems, total, pages, onPageChange, onPerPageChange, resetPage }`
|
||||
*/
|
||||
const usePagination = ( items = [], { perPage = DEFAULT_PER_PAGE, syncUrl = false } = {} ) => {
|
||||
const [ pagination, setPagination ] = useState( () => ( {
|
||||
page: syncUrl ? getPageFromUrl( 1 ) : 1,
|
||||
perPage: syncUrl ? getPerPageFromUrl( perPage ) : perPage,
|
||||
} ) )
|
||||
|
||||
const total = items.length
|
||||
const pages = Math.max( 1, Math.ceil( total / pagination.perPage ) )
|
||||
|
||||
const pageItems = useMemo( () => {
|
||||
const offset = ( pagination.page - 1 ) * pagination.perPage
|
||||
return items.slice( offset, offset + pagination.perPage )
|
||||
}, [ items, pagination ] )
|
||||
|
||||
// Clamp out-of-range pages, but not on mount (would clobber a URL-provided page).
|
||||
const isFirstRun = useRef( true )
|
||||
useEffect( () => {
|
||||
if ( isFirstRun.current ) {
|
||||
isFirstRun.current = false
|
||||
return
|
||||
}
|
||||
setPagination( ( prev ) => ( prev.page > pages ? { ...prev, page: pages } : prev ) )
|
||||
}, [ pages ] )
|
||||
|
||||
useEffect( () => {
|
||||
if ( syncUrl ) {
|
||||
writePaginationToUrl( pagination, perPage )
|
||||
}
|
||||
}, [ pagination, syncUrl, perPage ] )
|
||||
|
||||
const onPageChange = useCallback(
|
||||
( page ) => setPagination( ( prev ) => ( { ...prev, page: Math.max( 1, page ) } ) ),
|
||||
[]
|
||||
)
|
||||
|
||||
const onPerPageChange = useCallback(
|
||||
( newPerPage ) => setPagination( { page: 1, perPage: Math.max( 1, newPerPage ) } ),
|
||||
[]
|
||||
)
|
||||
|
||||
const resetPage = useCallback(
|
||||
() => setPagination( ( prev ) => ( prev.page === 1 ? prev : { ...prev, page: 1 } ) ),
|
||||
[]
|
||||
)
|
||||
|
||||
return { pagination, pageItems, total, pages, onPageChange, onPerPageChange, resetPage }
|
||||
}
|
||||
|
||||
export default usePagination
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* AI platform registry helpers — mirrors `Platforms` in PHP.
|
||||
*
|
||||
* @since 1.0.275
|
||||
*/
|
||||
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { map, filter } from 'lodash'
|
||||
|
||||
/**
|
||||
* Convert the localized registry map into a list, preserving key order.
|
||||
*
|
||||
* @param {Object} platforms Registry keyed by platform ID.
|
||||
* @return {Array<{id: string, label: string, enabled: boolean}>} Platform list.
|
||||
*/
|
||||
export const toPlatformList = ( platforms = {} ) =>
|
||||
map( platforms, ( platform, id ) => ( {
|
||||
id,
|
||||
label: platform?.label ?? id,
|
||||
enabled: Boolean( platform?.enabled ),
|
||||
} ) )
|
||||
|
||||
/**
|
||||
* Platform IDs available for selection.
|
||||
*
|
||||
* @param {Array} platformList Output of toPlatformList().
|
||||
* @return {string[]} Enabled platform IDs.
|
||||
*/
|
||||
export const getEnabledPlatformIds = ( platformList = [] ) =>
|
||||
map( filter( platformList, 'enabled' ), 'id' )
|
||||
|
||||
/**
|
||||
* Default selection for a new brand — the first enabled platform.
|
||||
*
|
||||
* @param {Array} platformList Output of toPlatformList().
|
||||
* @return {string[]} Default platform IDs.
|
||||
*/
|
||||
export const getDefaultPlatforms = ( platformList = [] ) =>
|
||||
getEnabledPlatformIds( platformList ).slice( 0, 1 )
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
* Derive a brand's display analysis state from its `analysis_status`.
|
||||
*
|
||||
* API status semantics:
|
||||
* success → ran successfully (a future weekly run is masked as success)
|
||||
* success → ran successfully (a future monthly run is masked as success)
|
||||
* partial → last run completed partially
|
||||
* pending → awaiting first run, or an overdue run is due
|
||||
* running → a run is currently in progress
|
||||
|
||||
+30
@@ -110,3 +110,33 @@ export const navigateToReportsTab = ( brandId ) => {
|
||||
window.history.pushState( {}, '', url )
|
||||
window.dispatchEvent( new window.PopStateEvent( 'popstate' ) )
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} [fallback=1] Fallback when `aiv_page` is absent/invalid.
|
||||
* @return {number} Page number from the URL.
|
||||
*/
|
||||
export const getPageFromUrl = ( fallback = 1 ) => {
|
||||
const raw = parseInt( getQueryArg( window.location.href, 'aiv_page' ), 10 )
|
||||
return raw > 0 ? raw : fallback
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} [fallback=10] Fallback when `aiv_per` is absent/invalid.
|
||||
* @return {number} Page size from the URL.
|
||||
*/
|
||||
export const getPerPageFromUrl = ( fallback = 10 ) => {
|
||||
const raw = parseInt( getQueryArg( window.location.href, 'aiv_per' ), 10 )
|
||||
return raw > 0 ? raw : fallback
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} pagination `{ page, perPage }`.
|
||||
* @param {number} [defaultPerPage=10] Omitted from the URL when matched.
|
||||
*/
|
||||
export const writePaginationToUrl = ( pagination, defaultPerPage = 10 ) => {
|
||||
const url = addQueryArgs( window.location.href, {
|
||||
aiv_page: pagination.page > 1 ? pagination.page : undefined,
|
||||
aiv_per: pagination.perPage !== defaultPerPage ? pagination.perPage : undefined,
|
||||
} )
|
||||
window.history.replaceState( {}, '', url )
|
||||
}
|
||||
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
<?php
|
||||
/**
|
||||
* AI platform registry.
|
||||
*
|
||||
* @since 1.0.275
|
||||
* @package RankMath
|
||||
* @subpackage RankMath\AI_Visibility
|
||||
* @author Rank Math <support@rankmath.com>
|
||||
*/
|
||||
|
||||
namespace RankMath\AI_Visibility;
|
||||
|
||||
use WP_Error;
|
||||
use RankMath\Helper;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Platforms class.
|
||||
*/
|
||||
final class Platforms {
|
||||
|
||||
/**
|
||||
* Plan that unlocks every supported platform.
|
||||
*/
|
||||
const UNLIMITED_PLAN = 'expert';
|
||||
|
||||
/**
|
||||
* Platform definitions. Key order drives the UI column split.
|
||||
*
|
||||
* @var array<string, array{label: string, enabled: bool}>
|
||||
*/
|
||||
private const PLATFORMS = [
|
||||
'chatgpt' => [
|
||||
'label' => 'ChatGPT',
|
||||
'enabled' => true,
|
||||
],
|
||||
'gemini' => [
|
||||
'label' => 'Google Gemini',
|
||||
'enabled' => true,
|
||||
],
|
||||
'perplexity' => [
|
||||
'label' => 'Perplexity',
|
||||
'enabled' => false,
|
||||
],
|
||||
'claude' => [
|
||||
'label' => 'Claude',
|
||||
'enabled' => false,
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* Every known platform, keyed by ID.
|
||||
*
|
||||
* @return array<string, array{label: string, enabled: bool}>
|
||||
*/
|
||||
public static function all() {
|
||||
return self::PLATFORMS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Platform IDs available for selection.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public static function supported() {
|
||||
return array_keys(
|
||||
array_filter(
|
||||
self::PLATFORMS,
|
||||
function ( $platform ) {
|
||||
return ! empty( $platform['enabled'] );
|
||||
}
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Platforms the current plan may track per brand.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public static function max_selectable() {
|
||||
return self::UNLIMITED_PLAN === Helper::get_content_ai_plan()
|
||||
? count( self::supported() )
|
||||
: 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Supported IDs as a quoted list, e.g. `"chatgpt", "gemini"`.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function supported_as_string() {
|
||||
return implode(
|
||||
', ',
|
||||
array_map(
|
||||
function ( $id ) {
|
||||
return '"' . $id . '"';
|
||||
},
|
||||
self::supported()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* REST route arg definition for a `platforms` param.
|
||||
*
|
||||
* @param bool $required Whether the param is mandatory.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function rest_arg( $required ) {
|
||||
return [
|
||||
'description' => sprintf(
|
||||
/* translators: %s: supported platform IDs. */
|
||||
esc_html__( 'AI platforms to track for this brand. Supported values: %s. Tracking more than one platform per brand requires the Expert plan.', 'seo-by-rank-math' ),
|
||||
self::supported_as_string()
|
||||
),
|
||||
'type' => 'array',
|
||||
'minItems' => 1,
|
||||
'items' => [
|
||||
'type' => 'string',
|
||||
'enum' => self::supported(),
|
||||
],
|
||||
'required' => $required,
|
||||
'validate_callback' => [ self::class, 'validate' ],
|
||||
'sanitize_callback' => [ self::class, 'sanitize' ],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize, dedupe and drop unsupported IDs.
|
||||
*
|
||||
* @param mixed $value Raw platforms value.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public static function sanitize( $value ) {
|
||||
return array_values(
|
||||
array_unique(
|
||||
array_intersect(
|
||||
array_map( 'sanitize_text_field', (array) $value ),
|
||||
self::supported()
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate against the registry and the plan limit.
|
||||
*
|
||||
* @param mixed $value Raw platforms value.
|
||||
*
|
||||
* @return true|WP_Error
|
||||
*/
|
||||
public static function validate( $value ) {
|
||||
if ( null === $value || '' === $value || [] === $value ) {
|
||||
return new WP_Error(
|
||||
'aiv_bad_request',
|
||||
sprintf(
|
||||
/* translators: %s: supported platform IDs. */
|
||||
esc_html__( 'Please specify which AI platforms to track. Supported values: %s.', 'seo-by-rank-math' ),
|
||||
self::supported_as_string()
|
||||
),
|
||||
[ 'status' => 400 ]
|
||||
);
|
||||
}
|
||||
|
||||
$platforms = self::sanitize( $value );
|
||||
|
||||
if ( empty( $platforms ) ) {
|
||||
return new WP_Error(
|
||||
'aiv_bad_request',
|
||||
sprintf(
|
||||
/* translators: %s: supported platform IDs. */
|
||||
esc_html__( 'No valid AI platforms were provided. Supported values: %s.', 'seo-by-rank-math' ),
|
||||
self::supported_as_string()
|
||||
),
|
||||
[ 'status' => 400 ]
|
||||
);
|
||||
}
|
||||
|
||||
$max = self::max_selectable();
|
||||
if ( count( $platforms ) > $max ) {
|
||||
return new WP_Error(
|
||||
'aiv_plan_limit',
|
||||
sprintf(
|
||||
/* translators: 1: platforms allowed on the current plan, 2: supported platform IDs. */
|
||||
esc_html__( 'Your plan allows tracking %1$d AI platform(s) per brand — upgrade to the Expert plan to track more. Supported values: %2$s.', 'seo-by-rank-math' ),
|
||||
$max,
|
||||
self::supported_as_string()
|
||||
),
|
||||
[ 'status' => 403 ]
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user