Commit inicial powerservice

This commit is contained in:
Gabriel
2026-10-19 12:45:45 -06:00
commit ad85486fe2
10158 changed files with 2736804 additions and 0 deletions
@@ -0,0 +1,112 @@
/**
* Analyses tab.
*/
@import '../scss/variables';
.rank-math-ai-visibility-analyses {
display: flex;
flex-direction: column;
gap: 24px;
// Error notice — same pattern as Dashboard.
&__error {
padding: $space-sm $space-md;
background: #fef0f0;
border: 1px solid $color-trend-down;
border-radius: $radius-sm;
color: $color-trend-down;
font-size: 14px;
}
&__card {
border-radius: 4px;
border: 1px solid #E0E0E0;
overflow: hidden;
}
// Override the table styling
.rank-math-table {
font-size: 13px;
&-card {
border-top: 1px solid #E0E0E0;
}
thead {
background: #FCFCFC;
border-color: #E0E0E0;
th {
padding: 13px 16px;
&:first-child {
padding: 13px 26px;
}
.rank-math-table-header-cell {
color: #1E1E1E;
font-size: 14px;
}
}
}
tbody {
tr {
td {
padding: 16px;
&:first-child {
padding: 16px 26px;
}
}
}
.rank-math-table-row {
&,
&:hover,
&:nth-child(odd) {
background: transparent;
}
}
}
&-footer {
justify-content: center;
padding: 20px 0;
&-nav {
justify-content: center;
align-items: center;
}
}
}
.rank-math-pagination {
&-page-info {
color: #666666;
}
&-separator {
color: #B2B2B2;
}
&-jump {
span {
color: #666666;
}
.rank-math-pagination-input {
width: 31px;
height: 28px;
border-radius: 2px;
min-height: 28px;
border-color: #C6C6C6;
color: #757575;
}
}
}
}
@@ -0,0 +1,153 @@
/**
* AnalysesFilterBar — filter controls above the analyses table.
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
import { useMemo, useState, useEffect, useRef } from '@wordpress/element'
import { __ } from '@wordpress/i18n'
import { SelectControl, SearchControl, Button } from '@wordpress/components'
/**
* Internal dependencies
*/
import './AnalysesFilterBar.scss'
import { DateInput } from '../shared/components'
// Status options — matches the states derived by `getAnalysisState`.
const STATUS_OPTIONS = [
{ label: __( 'All Statuses', 'seo-by-rank-math' ), value: '' },
{ label: __( 'Done', 'seo-by-rank-math' ), value: 'done' },
{ label: __( 'Running', 'seo-by-rank-math' ), value: 'running' },
{ label: __( 'Error', 'seo-by-rank-math' ), value: 'error' },
]
/**
* AnalysesFilterBar component.
*
* @param {Object} props
* @param {Object} props.filters Active filter bag.
* @param {Function} props.onFilterChange Receives a partial patch object.
* @param {Function} props.onClearFilters Resets all filters to defaults.
* @param {Array} [props.brandOptions=[]] `[{ label, value }]` for the brand dropdown.
* @return {JSX.Element} Single-row filter bar.
*/
const AnalysesFilterBar = ( {
filters,
onFilterChange,
onClearFilters,
brandOptions = [],
} ) => {
const ns = 'rank-math-ai-visibility-analyses-filter-bar'
const brandSelectOptions = useMemo( () => [
{ label: __( 'All Brands', 'seo-by-rank-math' ), value: '' },
...brandOptions,
], [ brandOptions ] )
// brandIds is an array; the single-select UI only needs the first item.
const activeBrandId = ( filters.brandIds && filters.brandIds[ 0 ] )
? String( filters.brandIds[ 0 ] )
: ''
const [ localSearch, setLocalSearch ] = useState( filters.search || '' )
const isFirstSearchRender = useRef( true )
// 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 )
return () => clearTimeout( timer )
}, [ localSearch, onFilterChange ] )
const hasActiveFilters = (
activeBrandId !== '' ||
filters.status !== '' ||
( filters.search || '' ) !== '' ||
( filters.dateFrom || '' ) !== '' ||
( filters.dateTo || '' ) !== ''
)
return (
<div className={ ns }>
<SelectControl
className={ `${ ns }__brand` }
value={ activeBrandId }
options={ brandSelectOptions }
onChange={ ( val ) => onFilterChange( { brandIds: val ? [ val ] : [] } ) }
__next40pxDefaultSize={ true }
__nextHasNoMarginBottom={ true }
/>
{ /* Status */ }
<SelectControl
className={ `${ ns }__status` }
value={ filters.status }
options={ STATUS_OPTIONS }
onChange={ ( value ) => onFilterChange( { status: value } ) }
__next40pxDefaultSize={ true }
__nextHasNoMarginBottom={ true }
/>
<SearchControl
className={ `${ ns }__search` }
placeholder={ __( 'Search', 'seo-by-rank-math' ) }
aria-label={ __( 'Search runs', 'seo-by-rank-math' ) }
value={ localSearch }
onChange={ ( value ) => setLocalSearch( value ) }
__nextHasNoMarginBottom={ true }
/>
{ hasActiveFilters && (
<Button
className={ `${ ns }__clear` }
variant="link"
isDestructive
onClick={ onClearFilters }
>
{ __( 'Clear filters', 'seo-by-rank-math' ) }
</Button>
) }
<div className={ `${ ns }__dates` }>
<div className={ `${ ns }__date-wrap` }>
<DateInput
value={ filters.dateFrom }
onChange={ ( e ) => onFilterChange( { dateFrom: e.target.value } ) }
ariaLabel={ __( 'From date', 'seo-by-rank-math' ) }
className={ `${ ns }__date-input` }
/>
</div>
<span className={ `${ ns }__date-sep` }>-</span>
<div className={ `${ ns }__date-wrap` }>
<DateInput
value={ filters.dateTo }
onChange={ ( e ) => onFilterChange( { dateTo: e.target.value } ) }
ariaLabel={ __( 'To date', 'seo-by-rank-math' ) }
className={ `${ ns }__date-input` }
/>
</div>
</div>
</div>
)
}
AnalysesFilterBar.displayName = 'AnalysesFilterBar'
export default AnalysesFilterBar
@@ -0,0 +1,121 @@
/**
* AnalysesFilterBar — single-row filter bar.
*
* [All Brands ▼] [All Statuses ▼] [Search 🔍 ........] [📅 dd/mm/yy] - [📅 dd/mm/yy]
*/
@import '../scss/variables';
.rank-math-ai-visibility-analyses-filter-bar {
display: flex;
align-items: center;
gap: $space-sm;
flex-wrap: nowrap;
padding: 15px 25px;
background-color: $color-surface;
// Remove WP base-control bottom margin.
.components-base-control {
margin-bottom: 0;
}
// Brand — fixed width, same style as Status
&__brand {
min-width: 150px;
flex-shrink: 0;
}
// Status — fixed width
&__status {
min-width: 140px;
flex-shrink: 0;
}
// Search — grows to fill available space between dropdowns and date range.
// Styled to match the Dashboard BrandsTableToolbar search:
// icon LEFT (default WP), 36px tall, border-radius 2px, border #949494.
&__search {
flex: 1;
min-width: 120px;
max-width: 260px;
// WP InputControl renders the visible border on .components-input-control__backdrop
// (a positioned <div>), NOT on the <input> element. The .is-focused class is
// toggled on the wrapper by WP on focus. WP admin also injects
// var(--wp-admin-theme-color) here, so !important is required to win.
.components-input-control.is-focused .components-input-control__backdrop {
@include input-focus-ring;
}
input[type='text'],
input[type='search'] {
height: 36px;
border-radius: 2px;
font-size: 13px;
// The visible ring lives on the backdrop — suppress any residual
// browser outline or box-shadow on the raw input element itself.
&:focus {
outline: none !important;
box-shadow: none !important;
}
}
input[type='text'] {
padding: 0 12px;
}
input[type='search'] {
padding: 0 5px;
}
}
// Date range wrapper: [📅 input] - [📅 input]
&__dates {
display: flex;
align-items: center;
gap: 6px;
flex-shrink: 0;
margin-left: auto;
}
&__date-sep {
font-size: 13px;
color: $color-text-muted;
flex-shrink: 0;
}
&__date-input {
border: none;
outline: none;
font-size: 12px;
color: $color-text-primary;
background: transparent;
width: 100px;
padding: 0;
}
// "Clear filters" link — appears only when filters are active.
&__clear {
flex-shrink: 0;
white-space: nowrap;
font-size: 12px;
}
@at-root #rank-math-ai-visibility-container {
.components-input-control__input,
.components-select-control__input {
height: 36px;
min-height: 36px;
}
.components-select-control__input {
color: #757575;
padding: 0 16px;
}
.components-input-control__backdrop {
border-color: $color-input-border;
}
}
}
@@ -0,0 +1,106 @@
/**
* AnalysesTable — paginated analyses runs table.
*
* @since 1.0.273
*/
/**
* External dependencies
*/
import { get } from 'lodash'
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n'
import { useMemo, memo } from '@wordpress/element'
/**
* Internal dependencies
*/
import { ListTable as Table, TableSkeleton } from '@rank-math/components'
import { Button, StartTime, StatusIcon } from '../shared/components'
import './AnalysesTable.scss'
/**
* AnalysesTable component.
*
* @param {Object} props
* @param {Array} [props.items=[]] Analysis run rows.
* @param {boolean} [props.loading=false] Show skeleton when true and items is empty.
* @param {Object} [props.pagination={}] `{ page, perPage, total, pages }`.
* @param {Function} [props.onViewDetail] Handler for "View Run Detail" — opens transcript.
* @param {Function} [props.onPageChange] Called with new page number.
* @param {Function} [props.onPerPageChange] Called with new per-page value.
* @return {JSX.Element} Paginated analyses runs table with section header.
*/
const AnalysesTable = ( {
items = [],
loading = false,
pagination = {},
onViewDetail = () => {},
onPageChange = () => {},
onPerPageChange = () => {},
} ) => {
const headers = useMemo( () => [
{
key: 'brand_name',
label: __( 'Brand', 'seo-by-rank-math' ),
},
{
key: 'started_at',
label: __( 'Last analyzed', 'seo-by-rank-math' ),
render: ( value, row ) => {
const hasStatus = row.status === 'error' || row.status === 'running'
return (
<span className="rank-math-ai-visibility-analyses-table__time-cell">
{ value ? <StartTime value={ value } /> : ( ! hasStatus && '−' ) }
{ hasStatus && <StatusIcon variant={ row.status } /> }
</span>
)
},
},
{
key: 'id',
label: __( 'Action', 'seo-by-rank-math' ),
render: ( _, row ) => {
// A completed run exists (and thus viewable transcripts) if
// last_analyzed is set. analysis_status can read `pending` for
// the next scheduled cycle even when prior data exists.
if ( ! row.started_at ) {
return null
}
return (
<Button
className="rank-math-ai-visibility-view-transcript"
iconLeft={ <span className="rm-icon-eye" /> }
onClick={ () => onViewDetail( row ) }
>
{ __( 'View Run Detail', 'seo-by-rank-math' ) }
</Button>
)
},
},
], [ onViewDetail ] )
if ( loading && ! items.length ) {
return <TableSkeleton columns={ 3 } rows={ 10 } />
}
return (
<Table
storageKey="ai-visibility-analyses"
headers={ headers }
rows={ items }
currentPage={ get( pagination, 'page', 1 ) }
rowsPerPage={ get( pagination, 'perPage', 10 ) }
totalItems={ get( pagination, 'total', items.length ) }
totalPages={ get( pagination, 'pages', 1 ) }
onPageChange={ onPageChange }
onRowsPerPageChange={ onPerPageChange }
/>
)
}
export default memo( AnalysesTable )
@@ -0,0 +1,36 @@
/**
* AnalysesTable — analyses runs table overrides.
*/
@import '../scss/variables';
.rank-math-ai-visibility-analyses {
// Suppress the ListTable's own toolbar row — we use AnalysesFilterBar instead.
.rank-math-table-header {
display: none !important;
}
// Explicit column widths — prevents table-layout:auto from giving
// Last Analyzed a disproportionately large share due to nowrap content.
table {
th:nth-child(1) { width: 45%; } // Brand
th:nth-child(2) { width: 35%; } // Last Analyzed
th:nth-child(3) { width: 20%; } // Action
}
}
// -------------------------------------------------------------------------
// Last analyzed cell — time + optional status icon.
// Mirrors the BrandsTable status icon pattern.
// -------------------------------------------------------------------------
.rank-math-ai-visibility-analyses-table {
&__time-cell {
display: flex;
align-items: center;
gap: 6px;
white-space: nowrap;
}
}
@@ -0,0 +1,201 @@
/**
* AnalysisRunDetail — full-page run detail view.
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
import { useState } from '@wordpress/element'
import { __ } from '@wordpress/i18n'
import { Notice, Tooltip } from '@wordpress/components'
/**
* Internal dependencies
*/
import { TableSkeleton } from '@rank-math/components'
import { getInsights } from '../shared/services/api/aiVisibilityApi'
import { Button, SentimentBadge, TranscriptModal, EmptyState, StatCard } from '../shared/components'
import PageTopbar from '../shared/components/PageTopbar'
import useFetch from '../shared/hooks/useFetch'
import { formatShortDate } from '../utils/formatDate'
import { navigateToReportsTab } from '../utils/urlState'
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 Analysis run (matched by platform) this result belongs to.
* @return {Object} Normalised entry.
*/
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.
*
* @param {Object} props
* @param {Object} props.row The analyses table row (brand_name, started_at, id).
* @param {Function} props.onBack Called when ← Back is clicked.
* @return {JSX.Element} Full-page analysis run detail.
*/
const AnalysisRunDetail = ( { row, onBack } ) => {
const ns = 'rank-math-ai-visibility-analysis-run-detail'
const { data: insightsData, loading, error } = useFetch(
() => getInsights( row.id ),
[ row?.id ],
{ skip: ! row?.id, errorMessage: __( 'Failed to load run detail.', 'seo-by-rank-math' ) }
)
const insights = insightsData?.insights ?? null
const [ modalEntry, setModalEntry ] = useState( null )
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 startedAts = analyses.map( ( analysis ) => analysis.started_at ).filter( Boolean ).sort()
const startedAt = row?.started_at ?? startedAts[ 0 ]
const handleExportReport = () => navigateToReportsTab( row.id )
return (
<div className={ ns }>
<PageTopbar
onBack={ onBack }
title={ __( 'Analysis Run Detail', 'seo-by-rank-math' ) }
actions={
<Button
variant="secondary"
onClick={ handleExportReport }
>
{ __( 'Export Report', 'seo-by-rank-math' ) }
</Button>
}
/>
<div className={ `${ ns }__content` }>
<div className={ `${ ns }__stat-cards` }>
<StatCard
compact
icon=" rm-icon-target"
label={ __( 'Target Brand', 'seo-by-rank-math' ) }
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={ analyses[ 0 ] ?? null }
/>
<StatCard
compact
icon="clock"
label={ __( 'Duration & Timing', 'seo-by-rank-math' ) }
value={ durationLabel }
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={ analyses[ 0 ] ?? null }
/>
</div>
{ error && (
<Notice status="error" isDismissible={ false }>{ error }</Notice>
) }
{ loading ? (
<TableSkeleton columns={ 3 } rows={ 3 } />
) : (
<div className={ `${ ns }__table` }>
<div className={ `${ ns }__table-row ${ ns }__table-row--header` }>
<div className={ `${ ns }__col ${ ns }__col--query` }>
{ __( 'Query text', 'seo-by-rank-math' ) }
</div>
<div className={ `${ ns }__col ${ ns }__col--sentiment` }>
{ __( 'Sentiment', 'seo-by-rank-math' ) }
</div>
<div className={ `${ ns }__col ${ ns }__col--action` }>
{ __( 'Action', 'seo-by-rank-math' ) }
</div>
</div>
{ transcripts.length === 0 ? (
<EmptyState
heading={ __( 'No queries found', 'seo-by-rank-math' ) }
description={ __( 'No queries were recorded for this analysis run.', 'seo-by-rank-math' ) }
/>
) : (
transcripts.map( ( entry ) => (
<div key={ entry.id } className={ `${ ns }__table-row` }>
<div className={ `${ ns }__col ${ ns }__col--query` }>
{ entry.query || '—' }
</div>
<div className={ `${ ns }__col ${ ns }__col--sentiment` }>
{ ( entry.avg_sentiment ?? entry.sentiment ) !== null && ( entry.avg_sentiment ?? entry.sentiment ) !== undefined ? (
<SentimentBadge score={ entry.avg_sentiment ?? entry.sentiment } />
) : (
<Tooltip text={ entry.found === false
? __( 'Sentiment unavailable - this brand was not detected in the AI response for this query.', 'seo-by-rank-math' )
: __( 'Sentiment data is not available for this query.', 'seo-by-rank-math' )
}>
<span>
<SentimentBadge score={ null } />
</span>
</Tooltip>
) }
</div>
<div className={ `${ ns }__col ${ ns }__col--action` }>
<Button
variant="secondary"
iconLeft={ <span className="rm-icon-eye" /> }
onClick={ () => setModalEntry( entry ) }
className="rank-math-ai-visibility-view-transcript"
>
{ __( 'View Transcript', 'seo-by-rank-math' ) }
</Button>
</div>
</div>
) )
) }
</div>
) }
{ modalEntry && (
<TranscriptModal
entry={ modalEntry }
onClose={ () => setModalEntry( null ) }
/>
) }
</div>
</div>
)
}
AnalysisRunDetail.displayName = 'AnalysisRunDetail'
export default AnalysisRunDetail
@@ -0,0 +1,75 @@
/**
* AnalysisRunDetail — full-page run detail view styles.
*/
@import '../scss/variables';
.rank-math-ai-visibility-analysis-run-detail {
// ── Stat cards ────────────────────────────────────────────────────────────
&__stat-cards {
display: flex;
gap: 28px;
margin-bottom: 26px;
margin-top: 24px;
}
// ── Query table ───────────────────────────────────────────────────────────
&__table {
background: $color-surface;
border: 1px solid $color-border;
border-radius: $radius-md;
overflow: hidden;
}
&__table-row {
display: grid;
grid-template-columns: 1fr 140px 160px;
align-items: center;
padding: 20px 35px;
border-bottom: 1px solid $color-border;
gap: 16px;
&:last-child {
border-bottom: none;
}
&--header {
background: #FCFCFC;
font-size: 12px;
font-weight: 600;
color: #1E1E1E;
text-transform: uppercase;
letter-spacing: 0.03em;
padding: 13px 35px;
}
}
&__col {
min-width: 0;
&--query {
font-size: 13px;
color: $color-text-primary;
line-height: 1.5;
}
&--sentiment {
display: flex;
align-items: center;
}
}
&__content {
background: #FFFFFF;
border-width: 0px 1px 1px 1px;
border-style: solid;
border-color: #E0E0E0;
border-radius: 0px 0px 4px 4px;
padding: 24px 34px 34px 34px;
margin: 24px 0 0 0;
}
}
@@ -0,0 +1,178 @@
/**
* Analyses & Transcripts tab container.
*
* Rows are derived from the cached dashboard data (one row per brand = its
* latest run); filtering, search, and pagination are client-side. No
* dedicated API endpoints.
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
import { useState, useEffect, useMemo, useCallback } from '@wordpress/element'
import { __ } from '@wordpress/i18n'
import { Notice } from '@wordpress/components'
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'
import AnalysesTable from './AnalysesTable'
import AnalysisRunDetail from './AnalysisRunDetail'
import './Analyses.scss'
const DEFAULT_FILTERS = {
brandIds: [],
status: '',
search: '',
dateFrom: '',
dateTo: '',
}
/**
* @param {Object} filters Active filter bag.
*/
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,
}
const url = addQueryArgs( window.location.href, params )
window.history.replaceState( {}, '', url )
}
/**
* Derive a run row from a brand's rollup data.
*
* @param {Object} brand Brand row.
* @return {Object} Analyses table row.
*/
const toRunRow = ( brand ) => {
const state = getAnalysisState( brand )
return {
id: brand.id,
brand_id: brand.id,
brand_name: brand.name,
started_at: brand.last_analyzed,
// Matches the Dashboard column's derivation, so both tabs agree.
status: state ?? ( brand.last_analyzed ? 'done' : 'none' ),
}
}
/**
* Analyses tab container component.
*
* @return {JSX.Element} Filter bar + derived runs table.
*/
const Analyses = () => {
const { brands, loading, error } = useDashboard()
const [ filters, setFilters ] = useState( DEFAULT_FILTERS )
const [ selectedRow, setSelectedRow ] = useState( null )
const brandOptions = useMemo(
() => brands.map( ( b ) => ( { label: b.name, value: b.id } ) ),
[ brands ]
)
const filteredItems = useMemo( () => {
return brands.map( toRunRow ).filter( ( item ) => {
if ( filters.search && ! item.brand_name.toLowerCase().includes( filters.search.toLowerCase() ) ) {
return false
}
if ( filters.status && item.status !== filters.status ) {
return false
}
if ( filters.brandIds.length && ! filters.brandIds.includes( item.brand_id ) ) {
return false
}
const itemDate = item.started_at ? item.started_at.slice( 0, 10 ) : ''
if ( filters.dateFrom && ( ! itemDate || itemDate < filters.dateFrom ) ) {
return false
}
if ( filters.dateTo && ( ! itemDate || itemDate > filters.dateTo ) ) {
return false
}
return true
} )
}, [ brands, filters ] )
const { pagination, pageItems, total, pages, onPageChange, onPerPageChange, resetPage } =
usePagination( filteredItems, { perPage: 10, syncUrl: true } )
const handleFilterChange = useCallback( ( patch ) => {
setFilters( ( prev ) => ( { ...prev, ...patch } ) )
resetPage()
}, [ resetPage ] )
const handleClearFilters = useCallback( () => {
setFilters( DEFAULT_FILTERS )
resetPage()
}, [ resetPage ] )
useEffect( () => {
writeFiltersToUrl( filters )
}, [ filters ] )
if ( selectedRow ) {
return (
<AnalysisRunDetail
row={ selectedRow }
onBack={ () => setSelectedRow( null ) }
/>
)
}
const ns = 'rank-math-ai-visibility-analyses'
return (
<div className={ ns }>
<SectionHeader
title={ __( 'Analyses & Transcripts', 'seo-by-rank-math' ) }
subtitle={ __( 'Global view of all runs with per-query detail.', 'seo-by-rank-math' ) }
/>
{ error && (
<Notice status="error" isDismissible={ false }>
{ error }
</Notice>
) }
<div className={ `${ ns }__card` }>
<AnalysesFilterBar
filters={ filters }
onFilterChange={ handleFilterChange }
onClearFilters={ handleClearFilters }
brandOptions={ brandOptions }
/>
<AnalysesTable
items={ pageItems }
loading={ loading }
pagination={ { ...pagination, total, pages } }
onViewDetail={ ( row ) => setSelectedRow( row ) }
onPageChange={ onPageChange }
onPerPageChange={ onPerPageChange }
/>
</div>
</div>
)
}
export default Analyses
@@ -0,0 +1,123 @@
/**
* AI Visibility — top-level app shell.
*
* @since 1.0.273
*/
/**
* External dependencies
*/
import { includes, toLower } from 'lodash'
/**
* WordPress dependencies
*/
import { useState, useEffect, createElement } from '@wordpress/element'
import { __ } from '@wordpress/i18n'
import { Snackbar } from '@wordpress/components'
/**
* Internal dependencies
*/
import { DashboardHeader, TabPanel } from '@rank-math/components'
import Dashboard from './Dashboard'
import Analyses from './Analyses'
import Reports from './Reports'
import { DEFAULT_TAB, getActiveTab, setTabInUrl } from './utils/urlState'
import { UpgradeToUnlockModal, ActivateTrialModal } from './shared/Modals'
import GatedPreview from './Dashboard/GatedPreview'
import Connect from './Connect'
/**
* Build the tabs array consumed by `@rank-math/components` TabPanel.
*
* @return {Array<Object>} Tab config objects.
*/
const getTabs = () => [
{
name: DEFAULT_TAB,
title: __( 'Dashboard', 'seo-by-rank-math' ),
className: 'rank-math-ai-visibility-dashboard-tab rank-math-tab',
view: Dashboard,
},
{
name: 'analyses',
title: __( 'Analyses & Transcripts', 'seo-by-rank-math' ),
className: 'rank-math-ai-visibility-analyses-tab rank-math-tab',
view: Analyses,
},
{
name: 'reports',
title: __( 'Reports & Export', 'seo-by-rank-math' ),
className: 'rank-math-ai-visibility-reports-tab rank-math-tab',
view: Reports,
},
]
const App = ( { config = {} } ) => {
const [ activeTab, setActiveTab ] = useState( getActiveTab( DEFAULT_TAB ) )
const [ snackbar, setSnackbar ] = useState( null )
const showSnackbar = ( message ) => setSnackbar( message )
const dismissSnackbar = () => setSnackbar( null )
// Sync with browser back/forward — pushState does NOT fire popstate.
useEffect( () => {
const handlePopState = () => {
setActiveTab( getActiveTab( DEFAULT_TAB ) )
}
window.addEventListener( 'popstate', handlePopState )
return () => window.removeEventListener( 'popstate', handlePopState )
}, [] )
const handleTabSelect = ( tabName ) => {
setTabInUrl( tabName )
setActiveTab( tabName )
}
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.
const isFreePlan = includes( [ '', 'free' ], toLower( plan ) )
const isPlanGated = isSiteConnected && isFreePlan
return (
<>
<DashboardHeader page={ __( 'AI Visibility', 'seo-by-rank-math' ) } />
<div className="wrap rank-math-wrap rank-math-ai-visibility">
<TabPanel
key={ activeTab }
className="rank-math-tabs"
activeClass="is-active"
initialTabName={ activeTab }
tabs={ getTabs() }
onSelect={ handleTabSelect }
>
{ ( tab ) => (
<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, languages, defaultLanguage, intervals, platforms, maxPlatforms, onBrandCreated: showSnackbar } )
) }
</div>
) }
</TabPanel>
{ isPlanGated && ( isPro ? <ActivateTrialModal /> : <UpgradeToUnlockModal /> ) }
</div>
{ snackbar && (
<Snackbar
onRemove={ dismissSnackbar }
>
{ snackbar }
</Snackbar>
) }
</>
)
}
export default App
@@ -0,0 +1,85 @@
/**
* AI Visibility — root app styles.
*/
@import './scss/variables';
.rank-math-ai-visibility {
margin: 0;
.rank-math-tabs {
margin-top: $space-md;
}
.rank-math-table tbody .rank-math-table-row:focus {
outline: none;
}
.components-checkbox-control__input[type=checkbox] {
&:checked,
&:indeterminate {
background: #017CBA;
border-color: #017CBA;
}
}
.components-input-control {
&__suffix svg,
&__suffix,
&__prefix {
color: #757575;
}
}
.rank-math-table-pagination-buttons {
display: inline-flex;
.rank-math-pagination-btn {
color: #757575;
border-radius: 2px;
&:first-child {
border-top-right-radius: 0;
margin-right: -1px;
border-bottom-right-radius: 0;
}
&:last-child {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
}
.rank-math-pagination-input {
width: auto;
padding: 0;
}
}
.rank-math-pagination-jump {
.rank-math-pagination-input {
width: auto;
min-height: 28px;
background: transparent;
}
span {
color: #666666;
}
}
.rank-math-pagination-page-info {
color: #666666;
}
.rank-math-table-footer {
padding: 20px 20px;
}
@media (min-width: 960px) {
.components-modal__frame {
max-height: 80%;
}
}
}
@@ -0,0 +1,74 @@
/**
* BrandDetail — brand detail page layout.
*/
@import '../scss/variables';
.rank-math-ai-visibility-brand-detail {
display: flex;
flex-direction: column;
gap: 20px;
&__content {
background: $color-surface;
border: 1px solid $color-border;
border-radius: $radius-sm;
}
&--loading {
display: flex;
justify-content: center;
padding: $space-lg;
}
&--error {
padding: $space-md;
text-align: center;
color: $color-trend-down;
}
&__tabs {
margin-top: $space-sm;
}
&__tab {
padding: 32px;
}
.rank-math-ai-visibility-brand-header__name {
font-weight: 400;
font-size: 30px;
line-height: 34px;
color: #1E1E1E;
margin: 0;
}
.rank-math-ai-visibility-brand-detail__tabs.rank-math-tabs {
margin: 0;
.components-tab-panel__tabs {
padding: 0 16px;
border-bottom: 1px solid $color-border;
}
.components-tab-panel__tabs-item {
height: 52px !important;
font-weight: 500;
color: #383838;
&.is-active {
color: $color-btn-primary;
&:after {
background: $color-btn-primary;
height: 2px;
}
}
}
.components-button:hover:not(:disabled,[aria-disabled=true]),
.components-button[aria-expanded=true] {
color: $color-btn-primary;
}
}
}
@@ -0,0 +1,124 @@
/**
* BrandHeader — brand detail page header.
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n'
import { external } from '@wordpress/icons'
import { Icon } from '@wordpress/components'
/**
* Internal dependencies
*/
import { Button, CountryFlag } from '../shared/components'
import { formatDateTime } from '../utils/formatDate'
import './BrandHeader.scss'
/**
* @param {string} url Brand URL from the API.
* @return {string} URL with https:// prepended if missing.
*/
const getBrandUrl = ( url ) => {
if ( ! url ) {
return '#'
}
return url.startsWith( 'http' ) ? url : `https://${ url }`
}
/**
* @param {Object} props
* @param {Object} props.brand
* @param {Function} [props.onEdit]
* @return {JSX.Element} Rendered component.
*/
const BrandHeader = ( {
brand,
onEdit = () => {},
} ) => {
const ns = 'rank-math-ai-visibility-brand-header'
const isActive = brand?.status === 'active'
return (
<div className={ ns }>
<div className={ `${ ns }__card` }>
<div className={ `${ ns }__content` }>
<div className={ `${ ns }__identity` }>
<div className={ `${ ns }__name-row` }>
<h1 className={ `${ ns }__name` }>{ brand.name }</h1>
<Button
variant="secondary"
onClick={ onEdit }
className={ `${ ns }__edit-btn` }
>
<span className="rm-icon rm-icon-edit" />
{ __( 'Edit Brand', 'seo-by-rank-math' ) }
</Button>
</div>
<div className={ `${ ns }__url-row` }>
<a
className={ `${ ns }__url` }
href={ getBrandUrl( brand.url ) }
target="_blank"
rel="noreferrer"
>
{ 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 ) }
target="_blank"
rel="noreferrer"
aria-label={ __( 'Open brand URL', 'seo-by-rank-math' ) }
>
<Icon icon={ external } size={ 14 } />
</a>
</div>
<div className={ `${ ns }__meta-row` }>
<span className={ `${ ns }__status ${ ns }__status--${ isActive ? 'active' : 'inactive' }` }>
{ isActive ? __( 'Active', 'seo-by-rank-math' ) : __( 'Inactive', 'seo-by-rank-math' ) }
</span>
{ brand.last_analyzed && (
<span className={ `${ ns }__last-analysis` }>
<span className="dashicons dashicons-clock" />
{ __( 'Last analysis:', 'seo-by-rank-math' ) }
{ ' ' }
{ formatDateTime( brand.last_analyzed ) }
</span>
) }
</div>
</div>
{ brand.description && (
<div className={ `${ ns }__description-panel` }>
<strong className={ `${ ns }__description-label` }>
{ __( 'Description', 'seo-by-rank-math' ) }
</strong>
<p className={ `${ ns }__description-text` }>
{ brand.description }
</p>
</div>
) }
</div>
</div>
</div>
)
}
export default BrandHeader
@@ -0,0 +1,181 @@
/**
* BrandHeader
*/
@import '../scss/variables';
.rank-math-ai-visibility-brand-header {
display: flex;
flex-direction: column;
gap: 0;
padding: 32px;
border-bottom: 1px solid $color-border;
// -------------------------------------------------------------------------
// Two-column content area.
// -------------------------------------------------------------------------
&__content {
display: flex;
align-items: flex-start;
justify-content: space-between;
}
&__identity {
display: flex;
flex-direction: column;
flex: 1;
}
// Brand name + inline Edit Brand button.
&__name-row {
display: flex;
align-items: center;
gap: 16px;
}
&__name {
margin: 0;
font-size: 26px;
font-weight: 600;
line-height: 1.2;
color: $color-text-primary;
}
&__edit-btn.rank-math-ai-visibility-btn.components-button {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 12px;
height: 24px;
padding: 0 8px;
border-color: #C6C6C6;
color: #757575;
background: #FCFCFC;
min-height: 24px;
.dashicons {
height: 12px;
width: 12px;
font-size: 12px;
margin: 0;
}
}
// URL + flag + external link row.
&__url-row {
display: flex;
align-items: center;
gap: 8px;
}
&__url {
text-decoration: none;
font-weight: 300;
font-size: 20px;
line-height: 28px;
color: #017CBA;
&:hover {
text-decoration: underline;
}
}
&__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;
align-items: center;
text-decoration: none;
&:hover {
color: $color-btn-primary;
}
// WP external icon uses fill
svg path {
fill: currentColor;
}
}
// Status badge + last analysis row.
&__meta-row {
display: flex;
align-items: center;
gap: 10px;
font-size: 13px;
margin: 12px 0 0 0;
}
&__status {
display: inline-flex;
align-items: center;
padding: 0 10px;
border-radius: 20px;
font-size: 11px;
font-weight: 400;
border: 1px solid #e0e0e0;
&--active {
color: #2e7d32;
border-color: #a5d6a7;
background: rgba( 46, 125, 50, 0.06 );
}
&--inactive {
color: $color-text-muted;
border-color: $color-border;
background: transparent;
}
}
&__last-analysis {
display: inline-flex;
align-items: center;
gap: 4px;
color: $color-text-muted;
font-size: 12px;
.dashicons {
height: 14px;
width: 14px;
font-size: 14px;
}
}
// -------------------------------------------------------------------------
// Description panel — right column.
// -------------------------------------------------------------------------
&__description-panel {
flex: 0 0 320px;
padding: 16px;
border: 1px solid $color-border;
border-radius: $radius-sm;
background: $color-surface;
}
&__description-label {
display: block;
font-size: 13px;
font-weight: 600;
color: $color-text-primary;
margin-bottom: 8px;
}
&__description-text {
margin: 0;
font-size: 13px;
line-height: 1.6;
color: $color-text-muted;
}
}
@@ -0,0 +1,109 @@
/**
* BrandOverview — Brand detail Overview sub-tab.
*
* @since 1.0.273
*/
/**
* External dependencies
*/
import { round } from 'lodash'
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n'
/**
* Internal dependencies
*/
import { StatCard } from '../shared/components'
import './BrandOverview.scss'
/**
* @param {Object} props
* @param {Object} props.brand
* @param {Object|null} props.insights
* @param {boolean} props.loading
* @return {JSX.Element|null} Rendered component, or null when brand is falsy.
*/
const BrandOverview = ( { brand, insights = null, loading = false } ) => {
if ( ! brand ) {
return null
}
const placeholder = loading ? '…' : '—'
const topCompetitor = insights?.competitors?.[ 0 ]?.name ?? null
const ns = 'rank-math-ai-visibility-brand-overview'
return (
<div className={ ns }>
<div className={ `${ ns }__stats` }>
<StatCard
className={ `${ ns }__stat-card ${ ns }__stat-card--score` }
icon=" rm-icon-ai-visibility"
label={ __( 'AI Visibility Score', 'seo-by-rank-math' ) }
value={ insights?.score !== null && insights?.score !== undefined
? `${ insights.score }/100`
: placeholder
}
tooltip={ __( 'AI Visibility Score for this brand across AI platforms.', 'seo-by-rank-math' ) }
analysis={ insights?.analyses?.[ 0 ] }
/>
<StatCard
className={ `${ ns }__stat-card ${ ns }__stat-card--rank` }
icon="chart-line"
label={ __( 'Avg Rank', 'seo-by-rank-math' ) }
value={ insights?.rank ?? placeholder }
tooltip={ __( 'Average rank of this brand across AI-generated mentions.', 'seo-by-rank-math' ) }
analysis={ insights?.analysis }
/>
<StatCard
className={ `${ ns }__stat-card ${ ns }__stat-card--sentiment` }
icon="smiley"
label={ __( 'Avg Sentiments', 'seo-by-rank-math' ) }
value={ insights?.avg_sentiment !== null && insights?.avg_sentiment !== undefined
? `${ round( insights.avg_sentiment ) }%`
: placeholder
}
tooltip={ __( 'Average sentiment score across all AI mentions of this brand.', 'seo-by-rank-math' ) }
analysis={ insights?.analyses?.[ 0 ] }
/>
<StatCard
className={ `${ ns }__stat-card ${ ns }__stat-card--mentions` }
icon=" rm-icon-comments"
label={ __( 'Recent Mentions', 'seo-by-rank-math' ) }
value={ insights?.mentions ?? placeholder }
tooltip={ __( 'Total brand mentions across AI-generated content.', 'seo-by-rank-math' ) }
analysis={ insights?.analysis }
/>
<StatCard
className={ `${ ns }__stat-card ${ ns }__stat-card--citations` }
icon=" rm-icon-misc"
label={ __( 'Citations', 'seo-by-rank-math' ) }
value={ insights?.citations ?? placeholder }
tooltip={ __( 'Total citations of this brand across AI-generated content.', 'seo-by-rank-math' ) }
analysis={ insights?.analysis }
/>
<StatCard
className={ `${ ns }__stat-card ${ ns }__stat-card--competitor` }
icon="awards"
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?.analyses?.[ 0 ] }
/>
</div>
</div>
)
}
export default BrandOverview
@@ -0,0 +1,69 @@
/**
* BrandOverview — stat cards row for the Overview sub-tab.
*/
@import '../scss/variables';
.rank-math-ai-visibility-brand-overview {
display: flex;
flex-direction: column;
gap: $space-md;
&__stats {
display: flex;
flex-wrap: wrap;
gap: $card-row-gap;
// Stack vertically on narrow viewports.
@media ( max-width: 782px ) {
flex-direction: column;
}
// Each card grows equally.
.rank-math-ai-visibility-stat-card {
flex: 0 1 calc(25% - 62px);
}
}
}
// -------------------------------------------------------------------------
// Per-card icon colour variants for the Overview sub-tab.
// -------------------------------------------------------------------------
.rank-math-ai-visibility-stat-card--overview {
// AI Visibility Score — blue
&-score {
--stat-icon-bg: rgba( 1, 124, 186, 0.12 );
--stat-icon-color: #{$color-btn-primary};
}
// Avg Rank — green
&-rank {
--stat-icon-bg: rgba( 45, 168, 116, 0.12 );
--stat-icon-color: #2DA874;
}
// Recent Mentions — amber
&-mentions {
--stat-icon-bg: rgba( 232, 166, 35, 0.12 );
--stat-icon-color: #E8A623;
}
// Avg Sentiments — purple/blue
&-sentiment {
--stat-icon-bg: rgba( 82, 96, 185, 0.12 );
--stat-icon-color: #5260B9;
}
// Citations — teal
&-citations {
--stat-icon-bg: rgba( 26, 155, 172, 0.12 );
--stat-icon-color: #1A9BAC;
}
// Top Competitor — red/pink
&-competitor {
--stat-icon-bg: rgba( 246, 98, 118, 0.12 );
--stat-icon-color: #F66276;
}
}
@@ -0,0 +1,39 @@
/**
* BrandTopbar — header section of the Brand Detail page.
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n'
/**
* Internal dependencies
*/
import { Button } from '../shared/components'
import PageTopbar from '../shared/components/PageTopbar'
/**
* @param {Object} props
* @param {Function} props.onBack
* @param {Function} [props.onExport]
* @return {JSX.Element} Rendered component.
*/
const BrandTopbar = ( {
onBack,
onExport = () => {},
} ) => (
<PageTopbar
onBack={ onBack }
title={ __( 'Brand detail', 'seo-by-rank-math' ) }
actions={
<Button variant="secondary" onClick={ onExport }>
{ __( 'Export Report', 'seo-by-rank-math' ) }
</Button>
}
/>
)
export default BrandTopbar
@@ -0,0 +1,106 @@
/**
* CompetitorsTable — Brand detail Competitors sub-tab.
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n'
/**
* Internal dependencies
*/
import { TableSkeleton } from '@rank-math/components'
import { SentimentBadge, EmptyState, CountBadge, DataTable } from '../shared/components'
import './CompetitorsTable.scss'
/**
* @param {string} name Competitor name.
* @return {string} Deterministic hex colour from the palette.
*/
const colorFromName = ( name ) => {
const palette = [ '#E60012', '#107C10', '#1A1A1A', '#1B2838', '#5260B9', '#017CBA', '#F59E0B', '#42B268' ]
let hash = 0
for ( let i = 0; i < ( name || '' ).length; i++ ) {
hash = ( ( hash * 31 ) + name.charCodeAt( i ) ) % palette.length
}
return palette[ hash ]
}
/**
* @param {Object} props
* @param {string} props.name
* @return {JSX.Element} Rendered component.
*/
const BrandAvatar = ( { name } ) => (
<span
className="rank-math-ai-visibility-competitors-table__avatar"
style={ { backgroundColor: colorFromName( name ) } }
aria-hidden="true"
>
{ name?.charAt( 0 )?.toUpperCase() ?? '?' }
</span>
)
/**
* @param {Object} props
* @param {Object|null} props.insights
* @param {boolean} props.loading
* @return {JSX.Element} Rendered component.
*/
const CompetitorsTable = ( { insights = null, loading = false } ) => {
const competitors = insights?.competitors ?? []
const ns = 'rank-math-ai-visibility-competitors-table'
if ( loading ) {
return <TableSkeleton columns={ 3 } rows={ 4 } />
}
if ( ! competitors.length ) {
return (
<div className={ ns }>
<EmptyState
heading={ __( 'No competitors detected yet', 'seo-by-rank-math' ) }
description={ __( 'Competitors are automatically identified during analysis runs.', 'seo-by-rank-math' ) }
/>
</div>
)
}
const columns = [
{
key: 'name',
label: __( 'Competitor', 'seo-by-rank-math' ),
width: '50%',
render: ( row ) => (
<>
<BrandAvatar name={ row.name } />
<span className={ `${ ns }__name` }>{ row.name }</span>
</>
),
},
{
key: 'avg_sentiment',
label: __( 'Avg sentiment', 'seo-by-rank-math' ),
render: ( row ) => <SentimentBadge score={ row.avg_sentiment } />,
},
{
key: 'mentions',
label: __( 'Mentions', 'seo-by-rank-math' ),
render: ( row ) => <CountBadge value={ row.mentions ?? null } variant="mentions" />,
},
]
return (
<div className={ ns }>
<DataTable columns={ columns } rows={ competitors } rowKey="name" />
</div>
)
}
CompetitorsTable.displayName = 'CompetitorsTable'
export default CompetitorsTable
@@ -0,0 +1,48 @@
/**
* CompetitorsTable — Brand detail Competitors sub-tab styles.
*/
@import '../scss/variables';
.rank-math-ai-visibility-competitors-table {
max-width: 1146px;
margin: 0 auto;
&--loading {
display: flex;
justify-content: center;
padding: $space-lg;
}
&--error {
p {
@include error-state;
}
}
.rank-math-ai-visibility-data-table__td:first-child {
display: flex;
align-items: center;
gap: 10px;
}
&__avatar {
display: inline-flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
border-radius: 4px;
font-size: 12px;
font-weight: 600;
color: $color-btn-primary-text;
flex-shrink: 0;
line-height: 1;
}
&__name {
font-size: 13px;
color: $color-text-primary;
font-weight: 400;
}
}
@@ -0,0 +1,189 @@
/**
* QueriesTable — Brand detail Queries sub-tab.
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n'
import { useState, useEffect, useCallback } from '@wordpress/element'
/**
* Internal dependencies
*/
import { TableSkeleton } from '@rank-math/components'
import { getQueries, updateQuery, generateQueries } from '../shared/services/api/aiVisibilityApi'
import { LoadingButton, StatusToggle, EmptyState, DataTable } from '../shared/components'
import { ConfirmModal } from '../shared/Modals'
import { formatLongDate } from '../utils/formatDate'
import './QueriesTable.scss'
/**
* @param {Object} props
* @param {number} props.brandId
* @return {JSX.Element} Queries sub-tab content.
*/
const QueriesTable = ( { brandId } ) => {
const ns = 'rank-math-ai-visibility-queries-table'
const [ queries, setQueries ] = useState( [] )
const [ queryOrder, setQueryOrder ] = useState( [] )
const [ loading, setLoading ] = useState( true )
const [ togglingId, setTogglingId ] = useState( null )
const [ regenConfirm, setRegenConfirm ] = useState( false )
const [ isRegenerating, setIsRegenerating ] = useState( false )
const fetchQueries = useCallback( async () => {
if ( ! brandId ) {
setQueries( [] )
setLoading( false )
return
}
setLoading( true )
try {
const data = await getQueries( brandId )
const fetched = Array.isArray( data?.queries ) ? data.queries : []
setQueryOrder( fetched.map( ( q ) => q.id ) )
setQueries( fetched )
} catch {
setQueries( [] )
} finally {
setLoading( false )
}
}, [ brandId ] )
useEffect( () => {
fetchQueries()
}, [ fetchQueries ] )
const handleToggleStatus = useCallback( async ( query, newValue ) => {
if ( ! brandId ) {
return
}
setTogglingId( query.id )
setQueries( ( prev ) => {
const updated = prev.map( ( q ) => q.id === query.id ? { ...q, enabled: newValue } : q )
return [ ...updated ].sort( ( a, b ) => queryOrder.indexOf( a.id ) - queryOrder.indexOf( b.id ) )
} )
try {
await updateQuery( brandId, query.id, { enabled: newValue } )
} catch {
setQueries( ( prev ) => {
const reverted = prev.map( ( q ) => q.id === query.id ? { ...q, enabled: query.enabled } : q )
return [ ...reverted ].sort( ( a, b ) => queryOrder.indexOf( a.id ) - queryOrder.indexOf( b.id ) )
} )
} finally {
setTogglingId( null )
}
}, [ brandId ] )
const handleRegenerateQueries = useCallback( async () => {
if ( ! brandId ) {
return
}
setRegenConfirm( false )
setIsRegenerating( true )
setLoading( true )
try {
const data = await generateQueries( brandId )
setQueries( Array.isArray( data?.queries ) ? data.queries : [] )
} catch {
await fetchQueries()
} finally {
setIsRegenerating( false )
setLoading( false )
}
}, [ brandId, fetchQueries ] )
return (
<div className={ ns }>
{ /* Toolbar */ }
<div className={ `${ ns }__toolbar` }>
<LoadingButton
variant="secondary"
onClick={ () => queries.length > 0 ? setRegenConfirm( true ) : handleRegenerateQueries() }
isLoading={ isRegenerating }
loadingLabel={ __( 'Regenerating…', 'seo-by-rank-math' ) }
iconLeft={ <span className="dashicons dashicons-update" aria-hidden="true" /> }
disabled={ loading }
>
{ __( 'Regenerate baseline queries', 'seo-by-rank-math' ) }
</LoadingButton>
</div>
{ loading && <TableSkeleton columns={ 4 } rows={ 5 } /> }
{ ! loading && queries.length === 0 && (
<EmptyState
heading={ __( 'No queries yet', 'seo-by-rank-math' ) }
description={ __(
'Regenerate baseline queries to start tracking how AI answers questions about this brand.',
'seo-by-rank-math'
) }
/>
) }
{ /* Table */ }
{ ! loading && queries.length > 0 && (
<DataTable
columns={ [
{
key: 'text',
label: __( 'Query text', 'seo-by-rank-math' ),
width: '56%',
render: ( row ) => row.text,
},
{
key: 'created_at',
label: __( 'Created', 'seo-by-rank-math' ),
render: ( row ) => formatLongDate( row.created_at ),
},
{
key: 'updated_at',
label: __( 'Last updated', 'seo-by-rank-math' ),
render: ( row ) => formatLongDate( row.updated_at ?? row.created_at ),
},
{
key: 'status',
label: __( 'Status', 'seo-by-rank-math' ),
width: '120px',
render: ( row ) => (
<StatusToggle
value={ row.enabled !== false }
onChange={ ( val ) => handleToggleStatus( row, val ) }
isLoading={ togglingId === row.id }
/>
),
},
] }
rows={ queries }
rowKey="id"
/>
) }
{ regenConfirm && (
<ConfirmModal
title={ __( 'Regenerate queries?', 'seo-by-rank-math' ) }
message={ __(
'This will replace all existing baseline queries with new AI-generated ones. Continue?',
'seo-by-rank-math'
) }
confirmLabel={ __( 'Regenerate', 'seo-by-rank-math' ) }
isDestructive={ false }
onConfirm={ handleRegenerateQueries }
onCancel={ () => setRegenConfirm( false ) }
/>
) }
</div>
)
}
export default QueriesTable
@@ -0,0 +1,61 @@
/**
* QueriesTable — Brand detail Queries sub-tab styles.
*/
@import '../scss/variables';
.rank-math-ai-visibility-queries-table {
display: flex;
flex-direction: column;
gap: 30px;
&__toolbar {
display: flex;
align-items: center;
gap: 12px;
.components-button {
min-height: 36px;
font-weight: 300;
}
.dashicons {
font-size: 14px;
width: 14px;
height: 14px;
line-height: 14px;
}
}
// Table markup replaced by shared <DataTable> component.
// Table styles now live in DataTable.scss.
// Column widths are set via the columns[].width prop (inline style on <th>).
.rank-math-ai-visibility-data-table__th {
font-weight: 500;
font-size: 14px;
line-height: 20px;
color: #1E1E1E;
padding: 13px;
&:first-child {
padding-left: 35px;
}
}
.rank-math-ai-visibility-data-table__td {
padding: 30px 16px;
font-weight: 400;
font-size: 13px;
line-height: 19px;
color: #1E1E1E;
&:first-child {
padding: 20px 35px;
}
&:nth-child(2),
&:nth-child(3) {
color: #868686;
}
}
}
@@ -0,0 +1,100 @@
/**
* RunDetail — transcript viewer for the brand's latest analysis.
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
import { useState, useMemo, useEffect } from '@wordpress/element'
import { __ } from '@wordpress/i18n'
/**
* Internal dependencies
*/
import { TableSkeleton } from '@rank-math/components'
import { TranscriptViewer, EmptyState } from '../shared/components'
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 Analysis run (matched by platform) this result belongs to.
* @return {Object} Normalised entry.
*/
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
* @param {Object|null} props.insights Latest-analysis insights payload.
* @param {boolean} props.loading Whether insights are loading.
* @return {JSX.Element} Transcript viewer or loading/empty state.
*/
const RunDetail = ( { insights = null, loading = false } ) => {
const entries = useMemo(
() => {
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 ]
)
const [ selectedId, setSelectedId ] = useState( null )
useEffect( () => {
setSelectedId( entries[ 0 ]?.id ?? null )
}, [ entries ] )
const ns = 'rank-math-ai-visibility-run-detail'
if ( loading ) {
return <TableSkeleton columns={ 3 } rows={ 4 } />
}
if ( ! entries.length ) {
return (
<div className={ ns }>
<EmptyState
heading={ __( 'No transcripts found', 'seo-by-rank-math' ) }
description={ __( 'Transcripts will appear here once the first analysis completes.', 'seo-by-rank-math' ) }
/>
</div>
)
}
return (
<div className={ ns }>
<TranscriptViewer
entries={ entries }
selectedEntryId={ selectedId }
onSelectEntry={ setSelectedId }
/>
</div>
)
}
RunDetail.displayName = 'RunDetail'
export default RunDetail
@@ -0,0 +1,27 @@
/**
* RunDetail — transcript viewer wrapper styles.
*/
@import '../scss/variables';
.rank-math-ai-visibility-run-detail {
&--loading {
display: flex;
justify-content: center;
padding: $space-xl;
}
&--error {
p {
@include error-state;
}
}
&--empty {
p {
font-size: 13px;
color: $color-text-muted;
margin: 0;
}
}
}
@@ -0,0 +1,185 @@
/**
* BrandDetail — brand detail page wrapper.
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n'
import { useState, useEffect, createElement } from '@wordpress/element'
import { TabPanel } from '@wordpress/components'
/**
* Internal dependencies
*/
import { TableSkeleton } from '@rank-math/components'
import { getBrand, getInsights, updateBrand } from '../shared/services/api/aiVisibilityApi'
import useFetch from '../shared/hooks/useFetch'
import { AddBrandModal } from '../shared/Modals'
import {
navigateBackToDashboard,
getActiveBrandTab,
setActiveBrandTabInUrl,
navigateToReportsTab,
} from '../utils/urlState'
import BrandTopbar from './BrandTopbar'
import BrandHeader from './BrandHeader'
import BrandOverview from './BrandOverview'
import QueriesTable from './QueriesTable'
import CompetitorsTable from './CompetitorsTable'
import RunDetail from './RunDetail'
import './BrandDetail.scss'
const OverviewView = ( { brand, insights, insightsLoading } ) => (
<BrandOverview brand={ brand } insights={ insights } loading={ insightsLoading } />
)
const QueriesView = ( { brand } ) => <QueriesTable brandId={ brand?.id } />
const CompetitorsView = ( { insights, insightsLoading } ) => (
<CompetitorsTable insights={ insights } loading={ insightsLoading } />
)
const TranscriptsView = ( { insights, insightsLoading } ) => (
<RunDetail insights={ insights } loading={ insightsLoading } />
)
const SUB_TABS = [
{ name: 'overview', title: __( 'Overview', 'seo-by-rank-math' ), view: OverviewView },
{ name: 'queries', title: __( 'Queries', 'seo-by-rank-math' ), view: QueriesView },
{ name: 'competitors', title: __( 'Competitors', 'seo-by-rank-math' ), view: CompetitorsView },
{ name: 'transcripts', title: __( 'Raw data / Transcripts', 'seo-by-rank-math' ), view: TranscriptsView },
]
/**
* @param {Object} props
* @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 = [], languages = [], defaultLanguage = '', intervals = [], platforms = {}, maxPlatforms = 1 } ) => {
const handleBack = onBack || navigateBackToDashboard
const { data: brandData, loading, error, setData: setBrandData } = useFetch(
() => getBrand( brandId ),
[ brandId ],
{ skip: ! brandId, errorMessage: __( 'Failed to load brand.', 'seo-by-rank-math' ) }
)
const brand = brandData?.brand ?? null
const { data: insightsData, loading: insightsLoading } = useFetch(
() => getInsights( brandId ),
[ brandId ],
{ skip: ! brandId, errorMessage: __( 'Failed to load insights.', 'seo-by-rank-math' ) }
)
const insights = insightsData?.insights ?? null
const [ activeSubTab, setActiveSubTab ] = useState( () => getActiveBrandTab() )
const [ isEditModalOpen, setEditModalOpen ] = useState( false )
const [ isSaving, setIsSaving ] = useState( false )
const [ saveError, setSaveError ] = useState( null )
const handleSaveBrand = async ( data ) => {
setIsSaving( true )
setSaveError( null )
try {
const result = await updateBrand( brandId, data )
setBrandData( { brand: result?.brand ?? { ...brand, ...data } } )
setEditModalOpen( false )
} catch ( err ) {
setSaveError( err?.message ?? __( 'Failed to save brand.', 'seo-by-rank-math' ) )
} finally {
setIsSaving( false )
}
}
const ns = 'rank-math-ai-visibility-brand-detail'
const handleExport = () => navigateToReportsTab( brand?.id )
useEffect( () => {
const handlePopState = () => setActiveSubTab( getActiveBrandTab() )
window.addEventListener( 'popstate', handlePopState )
return () => window.removeEventListener( 'popstate', handlePopState )
}, [] )
if ( loading ) {
return <TableSkeleton columns={ 3 } rows={ 4 } />
}
if ( error || ! brand ) {
return (
<div className={ `${ ns } ${ ns }--error` }>
<p>{ error || __( 'Brand not found.', 'seo-by-rank-math' ) }</p>
<button
className="button"
onClick={ handleBack }
>
{ __( '← Back to Dashboard', 'seo-by-rank-math' ) }
</button>
</div>
)
}
return (
<div className={ ns }>
<BrandTopbar
onBack={ handleBack }
onExport={ handleExport }
/>
<div className={ `${ ns }__content` }>
<BrandHeader
brand={ brand }
onEdit={ () => setEditModalOpen( true ) }
/>
<TabPanel
key={ activeSubTab }
className={ `rank-math-tabs ${ ns }__tabs` }
activeClass="is-active"
initialTabName={ activeSubTab }
tabs={ SUB_TABS }
onSelect={ ( tabName ) => {
setActiveBrandTabInUrl( tabName )
setActiveSubTab( tabName )
} }
>
{ ( tab ) => (
<div className={ `${ ns }__tab ${ ns }__tab--${ tab.name }` }>
{ createElement( tab.view, { brand, insights, insightsLoading } ) }
</div>
) }
</TabPanel>
</div>
{ isEditModalOpen && (
<AddBrandModal
brand={ brand }
onSave={ handleSaveBrand }
onClose={ () => {
setEditModalOpen( false )
setSaveError( null )
} }
isSaving={ isSaving }
apiError={ saveError }
locales={ locales }
languages={ languages }
defaultLanguage={ defaultLanguage }
intervals={ intervals }
platforms={ platforms }
maxPlatforms={ maxPlatforms }
/>
) }
</div>
)
}
export default BrandDetail
@@ -0,0 +1,65 @@
/**
* Wordpress dependencies
*/
import { __ } from '@wordpress/i18n'
/**
* Internal dependencies
*/
import './style.scss'
import { StatusButton, TextControl, ConnectAccountBody } from '@rank-math/components'
import getLink from '@helpers/getLink'
export default ( { config = {} } ) => {
const { isSiteConnected, registerProductNonce } = config
const { activateUrl, isSiteUrlValid } = config.aiVisibility ?? {}
const ns = 'rank-math-ai-visibility-account'
const status = isSiteConnected ? 'connected' : 'disconnected'
const statusLabel = isSiteConnected
? __( 'Connected', 'seo-by-rank-math' )
: __( 'Not Connected', 'seo-by-rank-math' )
return (
<div
className={ `${ ns } ${
isSiteConnected ? `${ ns }-connected` : `${ ns }-disconnected`
}` }
>
<header>
<h3>{ __( 'Account Connection Required', 'seo-by-rank-math' ) }</h3>
<StatusButton status={ status }>{ statusLabel }</StatusButton>
</header>
<div className={ `${ ns }-content` }>
<form method="post">
<TextControl
type="hidden"
name="registration-action"
value={ isSiteConnected ? 'deregister' : 'register' }
/>
<TextControl
type="hidden"
name="_wpnonce"
value={ registerProductNonce }
/>
<ConnectAccountBody
description={ __(
'Connect your account for free to start tracking your brand\'s AI visibility.',
'seo-by-rank-math'
) }
helpLink={ getLink( 'ai-visibility-connect', 'AI Visibility Connect' ) }
activateUrl={ activateUrl }
isSiteUrlValid={ isSiteUrlValid }
note={ __( 'Takes less than 30 seconds to get started', 'seo-by-rank-math' ) }
noteClassName={ `${ ns }-not-registered-note` }
/>
</form>
</div>
</div>
)
}
@@ -0,0 +1,71 @@
.rank-math-ai-visibility-account {
border: 1px solid #E0E0E0;
border-radius: 4px;
h3 {
font-style: normal;
font-weight: 500;
font-size: 20px;
line-height: 26px;
color: #C64539;
margin: 0;
}
header {
padding: 19px 28px;
border-bottom: 1px solid #E0E0E0;
display: flex;
align-items: center;
justify-content: space-between;
}
.rank-math-status-button.components-button.is-disconnected {
background: #C64539;
font-size: 13px;
font-weight: 300;
border-radius: 2px;
svg {
width: 10px;
}
}
&-content {
display: flex;
padding: 80px;
align-items: center;
justify-content: center;
text-align: center;
font-weight: 400;
font-size: 16px;
line-height: 23px;
color: #1E1E1E;
a {
color: #017CBA;
}
p {
margin: 0;
font-size: 14px;
font-weight: 400;
line-height: 23px;
&.rank-math-ai-visibility-account-not-registered-note {
margin-top: 30px;
font-weight: 500;
line-height: 16px;
color: #757575;
}
}
.rank-math-button.components-button.button-animate {
margin-top: 32px;
font-size: 22px;
font-weight: 400;
line-height: 80px;
padding: 0 42px;
}
}
}
@@ -0,0 +1,160 @@
/**
* BrandsTable — brands list table for the Dashboard tab.
*
* @since 1.0.273
*/
/**
* External dependencies
*/
import { get } from 'lodash'
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n'
import { useMemo, memo } from '@wordpress/element'
/**
* Internal dependencies
*/
import { ListTable as Table, TableSkeleton } from '@rank-math/components'
import { formatLongDate } from '../utils/formatDate'
import { getAnalysisState } from '../utils/analysisState'
import {
RankBadge,
SentimentBadge,
CountryFlag,
ActionButtons,
ScoreBadge,
CountBadge,
StatusIcon,
} from '../shared/components'
import './BrandsTable.scss'
/**
* @param {Object} props
* @param {Array} [props.brands=[]]
* @param {boolean} [props.loading=false]
* @param {Object} [props.pagination={}] `{ page, perPage, total, pages }`
* @param {Function} [props.onView]
* @param {Function} [props.onEdit]
* @param {Function} [props.onDisable]
* @param {Function} [props.onPageChange]
* @param {Function} [props.onPerPageChange]
* @return {JSX.Element} Rendered component.
*/
const BrandsTable = ( {
brands = [],
loading = false,
pagination = {},
onView = () => {},
onEdit = () => {},
onDisable = () => {},
onPageChange = () => {},
onPerPageChange = () => {},
} ) => {
const ns = 'rank-math-ai-visibility-brands-table'
const headers = useMemo( () => [
{
key: 'name',
label: __( 'Brand', 'seo-by-rank-math' ),
render: ( value, row ) => (
<div className={ `${ ns }__brand-cell` }>
{ /* eslint-disable-next-line jsx-a11y/anchor-is-valid */ }
<a href="#" className={ `${ ns }__brand-name` } onClick={ ( event ) => {
event.preventDefault()
onView( row )
} }>
{ value }
</a>
<div className={ `${ ns }__brand-link` }>
<a
className={ `${ ns }__brand-url` }
href={ row.url }
target="_blank"
rel="noreferrer"
>
{ row.url }
</a>
{ row.locale && <CountryFlag locale={ row.locale } /> }
</div>
</div>
),
},
{
key: 'score',
label: __( 'AI Visibility Score', 'seo-by-rank-math' ),
render: ( value ) => <ScoreBadge score={ value ?? null } />,
},
{
key: 'rank',
label: __( 'Avg Rank', 'seo-by-rank-math' ),
render: ( value ) => <RankBadge rank={ value } />,
},
{
key: 'avg_sentiment',
label: __( 'Avg sentiment', 'seo-by-rank-math' ),
render: ( value ) => <SentimentBadge score={ value } />,
},
{
key: 'mentions',
label: __( 'Mentions', 'seo-by-rank-math' ),
render: ( value ) => <CountBadge value={ value } variant="mentions" />,
},
{
key: 'citations',
label: __( 'Citations', 'seo-by-rank-math' ),
render: ( value ) => <CountBadge value={ value } variant="citations" />,
},
{
key: 'last_analyzed',
label: __( 'Last analyzed', 'seo-by-rank-math' ),
render: ( value, row ) => {
const state = getAnalysisState( row )
return (
<span className={ `${ ns }__last-analyzed` }>
{ value ? formatLongDate( value ) : ( ! state && '-' ) }
{ state && <StatusIcon variant={ state } /> }
</span>
)
},
},
{
key: 'id',
label: __( 'Actions', 'seo-by-rank-math' ),
render: ( _, row ) => (
<ActionButtons
status={ row?.status }
onView={ () => onView( row ) }
onEdit={ () => onEdit( row ) }
onDisable={ () => onDisable( row ) }
/>
),
},
], [ onView, onEdit, onDisable ] )
if ( loading && ! brands.length ) {
return <TableSkeleton columns={ 7 } rows={ 10 } />
}
return (
<div className={ ns }>
<Table
storageKey="ai-visibility-brands"
headers={ headers }
rows={ brands }
currentPage={ get( pagination, 'page', 1 ) }
rowsPerPage={ get( pagination, 'perPage', 10 ) }
totalItems={ get( pagination, 'total', brands.length ) }
totalPages={ get( pagination, 'pages', 1 ) }
onPageChange={ onPageChange }
onRowsPerPageChange={ onPerPageChange }
getRowClass={ ( row ) => row?.status === 'inactive' ? 'is-disabled' : '' }
/>
</div>
)
}
export default memo( BrandsTable )
@@ -0,0 +1,152 @@
/**
* BrandsTable — brands list table column overrides.
*/
@import '../scss/variables';
.rank-math-ai-visibility-brands-table {
&__last-analyzed {
color: #868686;
display: inline-flex;
align-items: center;
gap: 4px;
}
tbody .rank-math-table-row .rank-math-table-primary-column a {
color: #017CBA;
font-weight: 400;
}
&__brand-cell {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 5px;
}
tbody .rank-math-table-row .rank-math-table-primary-column .rank-math-ai-visibility-brands-table__brand-name {
font-size: 13px;
font-weight: 600;
color: $color-text-primary;
line-height: 1.4;
&:hover {
color: $color-text-primary;
text-decoration: none;
}
}
&__brand-url {
font-size: 12px;
color: $color-btn-primary;
line-height: 1.4;
word-break: break-all;
&:hover {
text-decoration: underline;
}
}
&__brand-link {
display: inline-flex;
gap: 4px;
}
.rank-math-table {
&-cell-content {
font-size: 13px;
}
&-header-cell {
font-size: 14px;
}
thead {
background-color: #FCFCFC;
th {
color: #1E1E1E;
font-size: 14px;
&:first-child {
padding-left: 25px;
}
}
}
tbody {
tr td:first-child {
padding-left: 25px;
}
.rank-math-table-row {
&:hover,
&:nth-child(odd) {
background: transparent;
}
// Disabled (inactive) brand — replace all colors with flat gray.
&.is-disabled {
// All plain text cells (mentions, citations, date).
td {
color: #c4c4c4;
}
// Brand name, URL, last-analyzed.
.rank-math-ai-visibility-brands-table {
&__brand-name {
color: #c4c4c4;
}
&__brand-url {
color: #c4c4c4;
&:hover {
text-decoration: none;
}
}
&__last-analyzed {
color: #c4c4c4;
}
}
// Country flag locale code.
.rank-math-ai-visibility-country-flag__code {
color: #c4c4c4;
}
// Score badge — strip variant color, replace with gray.
.rank-math-ai-visibility-score-badge {
color: #c4c4c4 !important;
border-color: #c4c4c4 !important;
background-color: rgba(196, 196, 196, 0.1) !important;
}
// Rank badge — strip variant color, replace with gray.
.rank-math-ai-visibility-rank-badge {
color: #c4c4c4 !important;
border-color: #c4c4c4 !important;
background-color: rgba(196, 196, 196, 0.2) !important;
}
// Sentiment badge — strip variant color, replace with gray.
// Also covers the SVG smiley icon via currentColor.
.rank-math-ai-visibility-sentiment-badge {
color: #c4c4c4 !important;
border-color: #c4c4c4 !important;
background-color: rgba(196, 196, 196, 0.08) !important;
svg {
color: #c4c4c4;
path {
fill: #c4c4c4 !important;
}
}
}
}
}
}
}
}
@@ -0,0 +1,55 @@
/**
* BrandsTableToolbar — search + add-brand controls above the brands table.
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n'
import { SearchControl } from '@wordpress/components'
/**
* Internal dependencies
*/
import { Button } from '../shared/components'
import './BrandsTableToolbar.scss'
/**
* @param {Object} props
* @param {string} [props.searchValue='']
* @param {Function} [props.onSearchChange]
* @param {Function} [props.onAdd]
* @return {JSX.Element} Rendered component.
*/
const BrandsTableToolbar = ( {
searchValue = '',
onSearchChange = () => {},
onAdd = () => {},
} ) => {
const ns = 'rank-math-ai-visibility-brands-toolbar'
return (
<div className={ ns }>
<Button
variant="primary"
onClick={ onAdd }
>
{ __( '+ Add Brand / Product', 'seo-by-rank-math' ) }
</Button>
<SearchControl
className={ `${ ns }__search` }
placeholder={ __( 'Search name or URL', 'seo-by-rank-math' ) }
value={ searchValue }
onChange={ onSearchChange }
__nextHasNoMarginBottom={ true }
/>
</div>
)
}
BrandsTableToolbar.displayName = 'BrandsTableToolbar'
export default BrandsTableToolbar
@@ -0,0 +1,38 @@
/**
* BrandsTableToolbar — search + add-brand bar above the brands table.
*/
@import '../scss/variables';
.rank-math-ai-visibility-brands-toolbar {
display: flex;
align-items: center;
gap: $space-md;
&__search.components-base-control {
flex: 0 0 auto;
margin: 0;
width: 200px;
input[type='text'],
input[type='search'] {
height: 36px;
border-radius: 2px;
border-color: #949494;
font-size: 13px;
&:focus {
border-color: $color-btn-primary;
box-shadow: 0 0 0 1px $color-btn-primary;
}
}
input[type='text'] {
padding: 0 12px;
}
input[type='search'] {
padding: 0 5px;
}
}
}
@@ -0,0 +1,83 @@
/**
* Dashboard tab — layout styles.
*/
@import '../scss/variables';
.rank-math-ai-visibility-dashboard {
display: flex;
flex-direction: column;
gap: 26px;
&__error {
padding: $space-sm $space-md;
background: #fef0f0;
border: 1px solid $color-trend-down;
border-radius: $radius-sm;
color: $color-trend-down;
font-size: 14px;
}
&__stats {
display: flex;
gap: $card-row-gap;
margin-top: 16px;
// On narrow viewports stack cards vertically.
@media ( max-width: 782px ) {
flex-direction: column;
}
}
&__empty {
background: $color-surface;
border: $border-width solid $border-color;
border-radius: $radius-sm;
}
&__table-card {
background: #fff;
border: 1px solid $color-border;
border-radius: $radius-sm;
overflow: hidden;
position: relative;
// Toolbar padding inside the card.
.rank-math-ai-visibility-brands-toolbar {
padding: 14px 25px;
border-bottom: 1px solid $color-border;
gap: 8px;
&__search.components-base-control {
width: 260px;
}
}
.rank-math-table-header {
display: none;
}
.rank-math-table-card {
border: none;
border-radius: 0;
background: transparent;
box-shadow: none;
}
// Center the table pagination row.
.rank-math-table-footer,
.rank-math-table__pagination {
display: flex;
justify-content: center;
}
> svg {
position: absolute;
top: 0;
left: 0;
z-index: 999;
opacity: .5;
}
}
}
@@ -0,0 +1,87 @@
/**
* GatedPreview — blurred decorative dashboard shown behind access-gate modals.
* Uses static sample data; no API calls are made.
*
* @since 1.0.281
*/
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n'
import { trendingUp } from '@wordpress/icons'
/**
* Internal dependencies
*/
import { StatCard } from '../shared/components'
import BrandsTableToolbar from './BrandsTableToolbar'
import BrandsTable from './BrandsTable'
import './GatedPreview.scss'
const noop = () => {}
// Display-only sample data — intentionally untranslated.
const SAMPLE_BRANDS = [
{ id: 'preview-1', name: 'Playstation 5', url: 'sony.com', locale: 'US', score: 94, rank: 1, avg_sentiment: 81, mentions: 4, citations: 2, last_analyzed: '2026-03-16', status: 'active' },
{ id: 'preview-2', name: 'iPad', url: 'apple.com', locale: 'US', score: 94, rank: 1, avg_sentiment: 76, mentions: 9, citations: 16, last_analyzed: '2026-03-16', status: 'active' },
{ id: 'preview-3', name: 'MiniCRM', url: 'https://minicrm.hu/', locale: 'HU', score: null, rank: null, avg_sentiment: null, mentions: null, citations: null, last_analyzed: '2026-03-16', status: 'active' },
{ id: 'preview-4', name: 'BackWPup', url: 'https://backwpup.com', locale: '', score: null, rank: null, avg_sentiment: null, mentions: null, citations: null, last_analyzed: '2026-03-16', status: 'active' },
{ id: 'preview-5', name: 'GTmetrix', url: 'https://gtmetrix.com', locale: '', score: null, rank: null, avg_sentiment: null, mentions: null, citations: null, last_analyzed: '2026-03-16', status: 'active' },
{ id: 'preview-6', name: 'Rank Math', url: 'https://rankmath.com/', locale: '', score: 23, rank: 3, avg_sentiment: 40, mentions: 2, citations: 1, last_analyzed: '2026-03-16', status: 'inactive' },
{ id: 'preview-7', name: 'WP Rocket', url: 'https://wp-rocket.me', locale: '', score: 23, rank: 3, avg_sentiment: 40, mentions: 2, citations: 1, last_analyzed: '2026-03-16', status: 'active' },
]
// Reuses the Dashboard BEM namespace so Dashboard.scss layout applies.
const GatedPreview = () => {
const ns = 'rank-math-ai-visibility-dashboard'
return (
<div
className={ `${ ns } rank-math-ai-visibility-gated-preview` }
aria-hidden="true"
>
<div className={ `${ ns }__stats` }>
<StatCard
className="rank-math-ai-visibility-stat-card--active-brands"
icon=" rm-icon rm-icon-ai-visibility"
label={ __( 'Global AI Visibility Score', 'seo-by-rank-math' ) }
value="70/100"
/>
<StatCard
className="rank-math-ai-visibility-stat-card--analyses"
icon={ trendingUp }
label={ __( 'Analyses in the last 7 days', 'seo-by-rank-math' ) }
value={ 0 }
/>
<StatCard
className="rank-math-ai-visibility-stat-card--mentions"
icon="rm-icon rm-icon-comments"
label={ __( 'Avg mentions per brand', 'seo-by-rank-math' ) }
value={ 3.2 }
/>
</div>
<div className={ `${ ns }__table-card` }>
<BrandsTableToolbar
searchValue=""
onSearchChange={ noop }
onAdd={ noop }
/>
<BrandsTable
brands={ SAMPLE_BRANDS }
loading={ false }
onView={ noop }
onEdit={ noop }
onDisable={ noop }
/>
</div>
</div>
)
}
GatedPreview.displayName = 'GatedPreview'
export default GatedPreview
@@ -0,0 +1,9 @@
/**
* GatedPreview — blurred decorative dashboard behind the access-gate modals.
*/
.rank-math-ai-visibility-gated-preview {
filter: blur( 4px );
pointer-events: none;
user-select: none;
}
@@ -0,0 +1,380 @@
/**
* Dashboard tab
*
* @since 1.0.273
*/
/**
* External dependencies
*/
import { get, toLower, isNil } from 'lodash'
/**
* WordPress dependencies
*/
import { __, sprintf } from '@wordpress/i18n'
import { Notice } from '@wordpress/components'
import { useState, useEffect, useRef } from '@wordpress/element'
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'
import BrandsTableToolbar from './BrandsTableToolbar'
import BrandsTable from './BrandsTable'
import BrandDetail from '../BrandDetail'
import { getActiveBrandId, navigateToBrand, navigateBackToDashboard } from '../utils/urlState'
import './Dashboard.scss'
// Plans not listed here are treated as unlimited.
const BRAND_LIMITS = {
starter: 1,
creator: 10,
expert: 50,
}
const TOP_TIER_PLAN = 'expert' // no upgrade path — show limit-reached messaging
/**
* @param {Object|null} confirmBrand
* @param {string} confirmAction 'disable' | 'enable'
* @return {string} Localised confirmation message.
*/
const getConfirmMessage = ( confirmBrand, confirmAction ) => {
if ( ! confirmBrand ) {
return ''
}
if ( confirmAction === 'enable' ) {
return sprintf(
/* translators: %s is the brand name, e.g. "Nike". */
__( `Resume tracking "%s"? Analysis will run on the next scheduled cycle.`, 'seo-by-rank-math' ),
confirmBrand.name
)
}
return sprintf(
/* translators: %s is the brand name, e.g. "Nike". */
__( `Stop tracking "%s"? You can re-enable it later.`, 'seo-by-rank-math' ),
confirmBrand.name
)
}
/**
* 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.
* @return {string|number|null} Placeholder, null (empty), 0 (missing) or formatted value.
*/
const getStatValue = ( { loading, hasBrands, raw, format } ) => {
if ( loading ) {
return '—'
}
if ( ! hasBrands ) {
return null
}
if ( isNil( raw ) ) {
return 0
}
return format ? format( raw ) : raw
}
/**
* @param {Object} props
* @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 = [], languages = [], defaultLanguage = '', platforms = {}, maxPlatforms = 1, onBrandCreated = () => {}, intervals = [] } ) => {
const [ activeBrandId, setActiveBrandId ] = useState( getActiveBrandId )
useEffect( () => {
const handlePopState = () => setActiveBrandId( getActiveBrandId() )
window.addEventListener( 'popstate', handlePopState )
return () => window.removeEventListener( 'popstate', handlePopState )
}, [] )
const {
brands,
summary,
loading,
error,
handleSearch,
handleAddBrand,
handleUpdateBrand,
handleDisableBrand,
handleEnableBrand,
} = useDashboard()
const [ isAddModalOpen, setAddModalOpen ] = useState( false )
const [ editBrand, setEditBrand ] = useState( null )
const [ isSaving, setIsSaving ] = useState( false )
const [ saveError, setSaveError ] = useState( null )
const [ confirmBrand, setConfirmBrand ] = useState( null )
const [ confirmAction, setConfirmAction ] = useState( 'delete' )
const [ isProcessing, setIsProcessing ] = useState( false )
const [ actionError, setActionError ] = useState( null )
const [ isUpgradeModalOpen, setUpgradeModalOpen ] = useState( false )
// 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
return
}
const timer = setTimeout( () => {
handleSearch( searchQuery.trim() )
resetPage()
}, 300 )
return () => clearTimeout( timer )
}, [ searchQuery, handleSearch, resetPage ] )
const hasActiveSearch = !! searchQuery.trim()
const isEmpty = ! loading && brands.length === 0 && ! hasActiveSearch
const openDisableConfirm = ( brand ) => {
setConfirmBrand( brand )
setConfirmAction( brand?.status === 'inactive' ? 'enable' : 'disable' )
}
const closeConfirm = () => {
setConfirmBrand( null )
setActionError( null )
}
const confirmTitle = confirmAction === 'enable'
? __( 'Activate brand?', 'seo-by-rank-math' )
: __( 'Deactivate brand?', 'seo-by-rank-math' )
const confirmMessage = getConfirmMessage( confirmBrand, confirmAction )
const closeAddModal = () => {
setAddModalOpen( false )
setEditBrand( null )
setSaveError( null )
}
const plan = toLower( get( window, 'rankMath.aiVisibility.plan', '' ) )
const brandLimit = get( BRAND_LIMITS, plan, null )
const openAddBrand = () => {
if ( null !== brandLimit && brands.length >= brandLimit ) {
setUpgradeModalOpen( true )
return
}
setEditBrand( null )
setAddModalOpen( true )
}
const handleSaveBrand = async ( data ) => {
setSaveError( null )
setIsSaving( true )
try {
if ( editBrand ) {
await handleUpdateBrand( editBrand.id, data )
} else {
await handleAddBrand( data )
onBrandCreated( __( 'Brand added! The first analysis is running — data will appear in approximately 10 minutes.', 'seo-by-rank-math' ) )
}
closeAddModal()
} catch ( err ) {
setSaveError( err?.message || __( 'Something went wrong. Please try again.', 'seo-by-rank-math' ) )
} finally {
setIsSaving( false )
}
}
const onConfirmAction = async () => {
if ( ! confirmBrand ) {
return
}
setIsProcessing( true )
setActionError( null )
try {
if ( confirmAction === 'disable' ) {
await handleDisableBrand( confirmBrand.id )
} else if ( confirmAction === 'enable' ) {
await handleEnableBrand( confirmBrand.id )
}
closeConfirm()
} catch ( err ) {
setActionError( err?.message ?? __( 'Action failed. Please try again.', 'seo-by-rank-math' ) )
} finally {
setIsProcessing( false )
}
}
const handleViewBrand = ( brand ) => {
navigateToBrand( brand.id )
setActiveBrandId( brand.id )
}
const handleBackToDashboard = () => {
navigateBackToDashboard()
setActiveBrandId( null )
}
if ( activeBrandId ) {
return (
<BrandDetail
brandId={ activeBrandId }
onBack={ handleBackToDashboard }
locales={ locales }
languages={ languages }
defaultLanguage={ defaultLanguage }
intervals={ intervals }
platforms={ platforms }
maxPlatforms={ maxPlatforms }
/>
)
}
const ns = 'rank-math-ai-visibility-dashboard'
return (
<div className={ ns }>
{ error && (
<Notice status="error" isDismissible={ false }>
{ error }
</Notice>
) }
<div className={ `${ ns }__stats` }>
<StatCard
className="rank-math-ai-visibility-stat-card--active-brands"
icon=" rm-icon rm-icon-ai-visibility"
label={ __( 'Global AI Visibility Score', 'seo-by-rank-math' ) }
value={ getStatValue( { loading, hasBrands: brands.length > 0, raw: summary?.ai_visibility_score, format: ( v ) => v + '/100' } ) }
tooltip={ __( 'Average rank score across all tracked brands.', 'seo-by-rank-math' ) }
/>
<StatCard
className="rank-math-ai-visibility-stat-card--analyses"
icon={ trendingUp }
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
className="rank-math-ai-visibility-stat-card--mentions"
icon="rm-icon rm-icon-comments"
label={ __( 'Avg mentions per brand', 'seo-by-rank-math' ) }
value={ getStatValue( { loading, hasBrands: brands.length > 0, raw: summary?.avg_mentions_per_brand } ) }
tooltip={ __( 'Average number of AI-generated mentions across all tracked brands.', 'seo-by-rank-math' ) }
/>
</div>
{ isEmpty && (
<div className={ `${ ns }__empty` }>
<EmptyState
icon={ store }
heading={ __( 'No brands or products tracked yet', 'seo-by-rank-math' ) }
description={ __(
'Add a brand or a specific product to see how you rank against competitors. Monitor your AI visibility, discover where you stand, and uncover opportunities to grow.',
'seo-by-rank-math'
) }
ctaLabel={ __( '+ Add Your First Brand', 'seo-by-rank-math' ) }
onCta={ openAddBrand }
/>
</div>
) }
{ ! isEmpty && (
<div className={ `${ ns }__table-card` }>
<BrandsTableToolbar
searchValue={ searchQuery }
onSearchChange={ setSearchQuery }
onAdd={ openAddBrand }
/>
<BrandsTable
brands={ pageItems }
loading={ loading }
pagination={ { ...pagination, total, pages } }
onView={ handleViewBrand }
onEdit={ async ( brand ) => {
setEditBrand( brand )
setAddModalOpen( true )
try {
const result = await getBrand( brand.id )
if ( result?.brand ) {
setEditBrand( result.brand )
}
} catch {
// keep the partial brand already set
}
} }
onDisable={ ( brand ) => openDisableConfirm( brand ) }
onPageChange={ onPageChange }
onPerPageChange={ onPerPageChange }
/>
</div>
) }
{ isAddModalOpen && (
<AddBrandModal
brand={ editBrand }
onSave={ handleSaveBrand }
onClose={ closeAddModal }
isSaving={ isSaving }
apiError={ saveError }
locales={ locales }
languages={ languages }
defaultLanguage={ defaultLanguage }
intervals={ intervals }
platforms={ platforms }
maxPlatforms={ maxPlatforms }
/>
) }
{ isUpgradeModalOpen && (
<UpgradePlanModal
plan={ plan }
isTopTier={ TOP_TIER_PLAN === plan }
onClose={ () => setUpgradeModalOpen( false ) }
/>
) }
{ confirmBrand && (
<ConfirmModal
title={ confirmTitle }
message={ confirmMessage }
confirmLabel={ confirmAction === 'enable'
? __( 'Activate', 'seo-by-rank-math' )
: __( 'Deactivate', 'seo-by-rank-math' )
}
isDestructive={ confirmAction === 'disable' }
isProcessing={ isProcessing }
error={ actionError }
onConfirm={ onConfirmAction }
onCancel={ closeConfirm }
/>
) }
</div>
)
}
export default Dashboard
@@ -0,0 +1,421 @@
/* global mixpanel */
/**
* Reports — Reports & Export tab.
*
* @since 1.0.273
*/
/**
* External dependencies
*/
import { round } from 'lodash'
/**
* WordPress dependencies
*/
import { useState, useCallback, useMemo, useEffect, useRef } from '@wordpress/element'
import { __ } from '@wordpress/i18n'
import { SelectControl, Notice } from '@wordpress/components'
/**
* Internal dependencies
*/
import { getInsights } from '../shared/services/api/aiVisibilityApi'
import { TableSkeleton } from '@rank-math/components'
import { Button, LoadingButton, RankBadge, SentimentBadge, SectionHeader, ScoreBadge, DataTable, CountBadge } from '../shared/components'
import useDashboard from '../shared/hooks/useDashboard'
import { getReportBrandParam } from '../utils/urlState'
import { formatDateTime } from '../utils/formatDate'
import downloadJson from '../utils/downloadJson'
import { HelpTooltip } from '@rank-math/components'
import './Reports.scss'
/**
* ReportStatCard component.
*
* @param {Object} props
* @param {string} props.icon Dashicon class suffix.
* @param {string} props.label Card label.
* @param {string|number|null} props.value Numeric value or null for N/A.
* @param {string} props.iconBg CSS background for the icon circle.
* @param {string} props.iconColor Icon colour hex.
* @param {string} props.tooltip Tooltip text for the help icon.
* @param {string} [props.className] Optional additional class(es) for the root.
* @return {JSX.Element} Report stat card.
*/
const ReportStatCard = ( { icon, label, value, iconBg, iconColor, tooltip, className } ) => {
const ns = 'rank-math-ai-visibility-reports'
return (
<div className={ `${ ns }__stat-card${ className ? ` ${ className }` : '' }` }>
<div
className={ `${ ns }__stat-icon` }
style={ { background: iconBg } }
>
<span
className={ `dashicons dashicons-${ icon }` }
style={ { color: iconColor } }
aria-hidden="true"
/>
</div>
<div className={ `${ ns }__stat-body` }>
<span className={ `${ ns }__stat-label` }>
{ label }
<HelpTooltip text={ tooltip } />
</span>
<span className={ `${ ns }__stat-value${ value === null || value === undefined ? ` ${ ns }__stat-value--na` : '' }` }>
{ value !== null && value !== undefined ? value : 'N/A' }
</span>
</div>
</div>
)
}
/**
* Reports component.
*
* @return {JSX.Element} Two-panel reports view.
*/
const Reports = () => {
const ns = 'rank-math-ai-visibility-reports'
const { brands, summary: dashboardSummary } = useDashboard()
const SELECT_BRAND_LABEL = __( 'Select Brand', 'seo-by-rank-math' )
const brandOptions = useMemo( () => [
{ label: SELECT_BRAND_LABEL, value: '' },
...brands.map( ( b ) => ( { label: b.name, value: String( b.id ) } ) ),
], [ brands ] )
const [ filters, setFilters ] = useState( () => ( {
brandId: getReportBrandParam(),
} ) )
const setFilter = ( key ) => ( value ) => setFilters( ( prev ) => ( { ...prev, [ key ]: value } ) )
const [ report, setReport ] = useState( null )
const [ reportBrand, setReportBrand ] = useState( null )
const [ loading, setLoading ] = useState( false )
const [ error, setError ] = useState( null )
const autoGeneratedRef = useRef( false )
useEffect( () => {
if ( ! autoGeneratedRef.current && filters.brandId && brands.length > 0 ) {
autoGeneratedRef.current = true
handleGenerate()
}
}, [ brands ] )
// Phase 1: one report row per brand, built client-side from cached data
// (latest analysis only). Date-range history awaits the Phase 2 endpoint.
const handleGenerate = useCallback( async () => {
setLoading( true )
setError( null )
setReportBrand( brands.find( ( b ) => String( b.id ) === filters.brandId ) || null )
try {
const selected = ( filters.brandId
? brands.filter( ( b ) => String( b.id ) === filters.brandId )
: brands
).filter( ( b ) => b.last_analyzed )
const rows = selected.map( ( b ) => ( {
id: b.id,
score: b.score,
rank: b.rank,
sentiment: b.avg_sentiment,
mentions: b.mentions,
citations: b.citations,
competitors: [],
date: b.last_analyzed,
} ) )
// Single-brand report: enrich with competitor names from the
// cached insights payload.
if ( filters.brandId && rows.length ) {
try {
const data = await getInsights( filters.brandId )
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.
}
}
const sum = ( key ) => rows.reduce( ( s, r ) => s + ( r[ key ] ?? 0 ), 0 )
const reportData = {
summary: {
score: filters.brandId
? rows[ 0 ]?.score ?? null
: dashboardSummary?.rank_score ?? null,
avg_sentiment: rows.length
? Math.round( sum( 'sentiment' ) / rows.length )
: null,
total_mentions: sum( 'mentions' ),
total_citations: sum( 'citations' ),
},
details: rows,
}
setReport( reportData )
if ( rankMath.tracking ) {
const { plugin, email, language, path } = rankMath.tracking
mixpanel.identify( email )
mixpanel.track( 'AI Visibility Report Generated', {
has_data: rows.length > 0,
context: 'wp_plugin',
brand: 'rankmath',
application: 'rankmath',
plugin,
path,
language,
} )
}
} catch ( err ) {
setError( err?.message || __( 'Failed to generate report.', 'seo-by-rank-math' ) )
} finally {
setLoading( false )
}
}, [ filters, brands, dashboardSummary ] )
const summary = report?.summary ?? {}
const rows = report?.details ?? []
const previewSubtitle = useMemo( () => {
return reportBrand ? reportBrand.name : ''
}, [ reportBrand ] )
return (
<div className={ ns }>
<SectionHeader
title={ __( 'Reports & Export', 'seo-by-rank-math' ) }
subtitle={ __( 'Export daily aggregates for a brand.', 'seo-by-rank-math' ) }
/>
<div className={ `${ ns }__layout` }>
<aside className={ `${ ns }__filters` }>
{ /* Panel header */ }
<div className={ `${ ns }__filters-header` }>
<span className="dashicons dashicons-filter" aria-hidden="true" />
<div>
<p className={ `${ ns }__filters-title` }>
{ __( 'Filters', 'seo-by-rank-math' ) }
</p>
<p className={ `${ ns }__filters-subtitle` }>
{ __( 'Select brand and format.', 'seo-by-rank-math' ) }
</p>
</div>
</div>
{ /* Panel body — form fields + CTA */ }
<div className={ `${ ns }__filters-body` }>
{ /* Brand — SelectControl renders its own associated label */ }
<div className={ `${ ns }__filter-field` }>
<SelectControl
label={ __( 'BRAND', 'seo-by-rank-math' ) }
value={ filters.brandId }
options={ brandOptions }
onChange={ ( value ) => {
setFilter( 'brandId' )( value )
if ( ! value ) {
setReport( null )
setReportBrand( null )
setError( null )
}
} }
__next40pxDefaultSize={ true }
__nextHasNoMarginBottom={ true }
/>
</div>
<LoadingButton
className={ `${ ns }__generate-btn` }
onClick={ handleGenerate }
isLoading={ loading }
loadingLabel={ __( 'Generating…', 'seo-by-rank-math' ) }
disabled={ ! filters.brandId }
>
{ __( 'Generate preview', 'seo-by-rank-math' ) }
</LoadingButton>
</div>
</aside>
{ /* ── Right: preview panel ── */ }
<div className={ `${ ns }__preview` }>
{ error && (
<Notice status="error" isDismissible={ false }>
{ error }
</Notice>
) }
{ loading && <TableSkeleton columns={ 5 } rows={ 4 } /> }
{ ! report && ! loading && ! error && (
<div className={ `${ ns }__empty` }>
<p>{ __( 'Select a brand, then click "Generate preview".', 'seo-by-rank-math' ) }</p>
</div>
) }
{ report && (
<div className={ `${ ns }__report-card` }>
{ /* Card header: chart icon + title/subtitle + actions */ }
<div className={ `${ ns }__preview-header` }>
<div className={ `${ ns }__preview-title-row` }>
<span className="dashicons dashicons-chart-bar" aria-hidden="true" />
<div>
<p className={ `${ ns }__preview-title` }>
{ __( 'Preview', 'seo-by-rank-math' ) }
</p>
{ previewSubtitle && (
<p className={ `${ ns }__preview-subtitle` }>
{ previewSubtitle }
</p>
) }
</div>
</div>
<div className={ `${ ns }__preview-actions` }>
<Button
variant="secondary"
onClick={ () => {
downloadJson( report, 'ai-visibility-report.json' )
if ( rankMath.tracking ) {
const { plugin, email, language, path } = rankMath.tracking
mixpanel.identify( email )
mixpanel.track( 'Button Clicked', {
button: 'Download AI Visibility Report',
context: 'wp_plugin',
brand: 'rankmath',
application: 'rankmath',
plugin,
path,
language,
} )
}
} }
>
{ __( 'Download JSON', 'seo-by-rank-math' ) }
</Button>
</div>
</div>
{ /* Card body: stat cards + table */ }
<div className={ `${ ns }__report-card-body` }>
{ /* Stat cards */ }
<div className={ `${ ns }__stat-cards` }>
<ReportStatCard
icon=" rm-icon-ai-visibility"
className="rank-math-ai-visibility-reports-overall-score"
label={ __( 'Global AI Visibility Score', 'seo-by-rank-math' ) }
value={ summary.score !== null && summary.score !== undefined
? `${ summary.score }/100`
: null
}
iconBg="rgba(1,124,186,0.12)"
iconColor="#017CBA"
tooltip={ __( 'The overall AI Visibility Score for the selected brand and date range, calculated based on the volume of mentions, sentiment, and other factors.', 'seo-by-rank-math' ) }
/>
<ReportStatCard
icon="smiley"
className="rank-math-ai-visibility-reports-overall-sentiment"
label={ __( 'Avg Sentiment', 'seo-by-rank-math' ) }
value={ summary.avg_sentiment !== null && summary.avg_sentiment !== undefined ? `${ round( summary.avg_sentiment ) }%` : null }
iconBg="rgba(82,96,185,0.12)"
iconColor="#5260B9"
tooltip={ __( 'The average sentiment score across all AI mentions for the selected brand and date range. Calculated by analyzing the sentiment of each mention and averaging the scores.', 'seo-by-rank-math' ) }
/>
<ReportStatCard
icon=" rm-icon-comments"
className="rank-math-ai-visibility-reports-total-mentions"
label={ __( 'Total Mentions', 'seo-by-rank-math' ) }
value={ summary.total_mentions ?? 0 }
iconBg="rgba(255,171,64,0.15)"
iconColor="#F59E0B"
tooltip={ __( 'The total number of AI-generated mentions of the selected brand within the specified date range.', 'seo-by-rank-math' ) }
/>
<ReportStatCard
icon=" rm-icon-misc"
className="rank-math-ai-visibility-reports-total-citations"
label={ __( 'Total Citations', 'seo-by-rank-math' ) }
value={ summary.total_citations ?? 0 }
iconBg="rgba(66,178,104,0.15)"
iconColor="#42B268"
tooltip={ __( 'The total number of AI-generated mentions that include a link to the selected brand’s website within the specified date range.', 'seo-by-rank-math' ) }
/>
</div>
{ /* Per-run data table */ }
{ rows.length > 0 && (
<DataTable
columns={ [
{
key: 'score',
label: __( 'AI Visibility Score', 'seo-by-rank-math' ),
render: ( row ) => <ScoreBadge score={ row.score ?? null } />,
},
{
key: 'rank',
label: __( 'Avg Rank', 'seo-by-rank-math' ),
render: ( row ) => <RankBadge rank={ row.rank ?? null } />,
},
{
key: 'sentiment',
label: __( 'Sentiment', 'seo-by-rank-math' ),
render: ( row ) => <SentimentBadge score={ row.sentiment ?? null } />,
},
{
key: 'mentions',
label: __( 'Mentions', 'seo-by-rank-math' ),
render: ( row ) => <CountBadge value={ row.mentions ?? null } variant="mentions" />,
},
{
key: 'citations',
label: __( 'Citations', 'seo-by-rank-math' ),
render: ( row ) => <CountBadge value={ row.citations ?? null } variant="citations" />,
},
{
key: 'competitors',
label: __( 'Top competitors', 'seo-by-rank-math' ),
render: ( row ) => (
<div className={ `${ ns }__competitors` }>
{ ( row.competitors || [] ).map( ( c ) => (
<span key={ c } className={ `${ ns }__competitor-tag` }>{ c }</span>
) ) }
</div>
),
},
{
key: 'date',
label: __( 'Date', 'seo-by-rank-math' ),
render: ( row ) => formatDateTime( row.date ),
},
] }
rows={ rows }
rowKey={ ( row, i ) => row.id ?? i }
/>
) }
</div>
</div>
) }
</div>
</div>
</div>
)
}
Reports.displayName = 'Reports'
export default Reports
@@ -0,0 +1,288 @@
/**
* Reports — Reports & Export tab styles.
*/
@import '../scss/variables';
.rank-math-ai-visibility-reports {
display: flex;
flex-direction: column;
gap: $space-lg;
&-total-citations .rank-math-ai-visibility-reports__stat-value,
&-total-mentions .rank-math-ai-visibility-reports__stat-value {
font-size: 26px;
}
&__layout {
display: grid;
grid-template-columns: 1fr 3fr;
gap: 16px;
}
&__filters {
display: flex;
flex-direction: column;
gap: 0;
padding: 0;
background: $color-surface;
border: 1px solid $color-border;
border-radius: 4px;
align-self: baseline;
min-width: 0;
}
&__filters-header {
display: flex;
align-items: center;
min-height: 68px;
gap: 9px;
padding: 0 18px 0 24px;
border-bottom: 1px solid $color-border;
.dashicons {
font-size: 18px;
width: 18px;
height: 18px;
color: $color-text-muted;
flex-shrink: 0;
}
}
// Panel body — wraps Brand + Date Range + button below the header
&__filters-body {
display: flex;
flex-direction: column;
gap: 12px;
padding: 20px 24px 24px;
}
// Nested under __filters-header to raise specificity to (0,2,0) and beat WP admin `p` rules
&__filters-header &__filters-title {
font-size: 13px;
font-weight: 500;
line-height: 16px;
color: $color-text-primary;
margin: 0 0 2px;
}
&__filters-header &__filters-subtitle {
font-size: 12px;
line-height: 20px;
color: $color-text-secondary;
margin: 0;
}
&__filter-field {
display: flex;
flex-direction: column;
gap: 8px;
// Override WP SelectControl label
.components-base-control__label {
font-size: 11px;
font-weight: 600;
color: $color-text-primary;
letter-spacing: 0.1px;
text-transform: uppercase;
}
}
// Generate preview button — layout only (appearance comes from shared Button component)
&__generate-btn {
align-self: flex-start;
margin-top: 24px;
}
// ── Right: preview panel ───────────────────────────────────────────────────
&__preview {
display: flex;
flex-direction: column;
gap: $space-lg;
min-width: 0; // critical: lets the grid item shrink; without this the wide table overflows
}
&__empty {
display: flex;
align-items: center;
justify-content: center;
min-height: 100%;
background: $color-surface;
border: 1px dashed $color-border;
border-radius: 4px;
p {
font-size: 14px;
color: $color-text-muted;
margin: 0;
text-align: center;
}
}
// Card container — wraps header + body when report data is loaded
&__report-card {
@include card-base;
overflow: hidden;
}
// Preview header: chart icon + title/subtitle + action buttons (card top bar)
&__preview-header {
display: flex;
align-items: center;
justify-content: space-between;
min-height: 68px;
padding: 0 18px 0 24px;
gap: $space-md;
border-bottom: 1px solid $color-border;
}
&__preview-title-row {
display: flex;
align-items: center;
gap: 12px;
.dashicons {
font-size: 18px;
width: 18px;
height: 18px;
color: $color-text-muted;
flex-shrink: 0;
}
}
// Nested under __preview-header to raise specificity to (0,2,0) and beat WP admin `p` rules
&__preview-header &__preview-title {
font-size: 13px;
font-weight: 500;
line-height: 16px;
color: $color-text-primary;
margin: 0 0 2px;
}
&__preview-header &__preview-subtitle {
font-size: 12px;
font-weight: 300;
line-height: 20px;
color: $color-text-secondary;
margin: 0;
}
&__preview-actions {
display: flex;
gap: $space-sm;
flex-shrink: 0;
align-items: center;
}
// Card body — wraps stat cards + table with consistent padding
&__report-card-body {
padding: 30px 20px 20px 20px;
display: flex;
flex-direction: column;
gap: 26px;
min-width: 0; // inherit grid shrink behaviour
overflow-x: auto; // scroll horizontally when table is wider than the panel
}
// 4 stat cards row
&__stat-cards {
display: grid;
grid-template-columns: repeat( 4, 1fr );
gap: 12px;
}
&__stat-card {
@include card-base;
display: flex;
gap: $space-md;
padding: 34px 17px;
}
// Colored circular icon
&__stat-icon {
display: flex;
align-items: center;
justify-content: center;
min-width: 44px;
flex-shrink: 0;
width: 45.5px;
height: 38.52px;
border-radius: 7.16667px;
.dashicons {
font-size: 20px;
width: 20px;
height: 20px;
}
}
&__stat-body {
display: flex;
flex-direction: column;
gap: 8px;
min-width: 0;
}
&__stat-label {
font-size: 12px;
white-space: nowrap;
gap: 8px;
display: inline-flex;
}
&__stat-value {
font-size: 30px;
font-weight: 500;
color: #1e1e1e;
line-height: 1;
// "N/A" — muted appearance when no real value
&--na {
color: $color-text-secondary;
font-weight: 400;
}
}
// Per-run data table replaced by shared <DataTable> component (DataTable.scss).
// Reports uses 14px header font and 10px/24px cell padding — override via wrapper.
&__report-card-body .rank-math-ai-visibility-data-table {
&__th {
padding: 15px 18px;
font-size: 14px;
color: $color-text-primary;
}
&__td {
padding: 10px 16px;
&--date {
color: #868686;
}
}
}
// Top competitors — inline pill tags
&__competitors {
display: flex;
flex-wrap: wrap;
gap: 7px;
}
&__competitor-tag {
box-sizing: border-box;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
padding: 4px 8px;
gap: 6px;
border: 1px solid rgba(0, 0, 0, 0.1);
border-radius: 2px;
font-weight: 400;
font-size: 12px;
line-height: 13px;
color: rgba(0, 0, 0, 0.5);
}
}
@@ -0,0 +1,6 @@
/**
* Reports & Export tab.
*
* @since 1.0.273
*/
export { default } from './Reports'
@@ -0,0 +1,26 @@
/**
* AI Visibility — entry point.
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
import { createRoot } from '@wordpress/element'
/**
* Internal dependencies
*/
import App from './App'
import './App.scss'
document.addEventListener( 'DOMContentLoaded', () => {
const container = document.getElementById( 'rank-math-ai-visibility-container' )
if ( ! container ) {
return
}
const config = window.rankMath ?? {}
createRoot( container ).render( <App config={ config } /> )
} )
@@ -0,0 +1,311 @@
/**
* AI Visibility — SCSS design tokens.
*
* All values sourced directly from the Figma file:
* https://www.figma.com/design/Ro0jblj6zP93S52TzqGfBU/AI-Visibility
*
* Module-scoped variables. The Rank Math codebase has no centralised tokens
* file, so each module defines its own here.
*
* Usage:
* @import '../scss/variables';
* .foo { color: $color-text-muted; }
*/
// ---------------------------------------------------------------------------
// Colors — surfaces & borders
// ---------------------------------------------------------------------------
// Card / panel background.
$color-surface: #fff;
// Border on cards and separators (Figma token: Color/Layout/borders).
$color-border: #e0e0e0;
// Input field border — slightly darker than card borders (used on date pickers,
// select control backdrop, etc.).
$color-input-border: #949494;
// ---------------------------------------------------------------------------
// Colors — text
// ---------------------------------------------------------------------------
// Primary text — empty state heading, strong labels.
$color-text-primary: #1e1e1e;
// Secondary text — section subtitles
$color-text-secondary: #868686;
// Muted / secondary text — stat labels, stat values (zero state), body copy.
$color-text-muted: #9b9b9b;
// Body copy on light surfaces — modal intro text, footer notes
// (matches the secondary button text colour used in Button.scss).
$color-text-body: #4e4e4e;
// Text / icons on dark or gradient backgrounds — gate modal headers,
// video placeholder.
$color-text-light: #fff;
// ---------------------------------------------------------------------------
// Colors — trend indicators
// (applied to the "Changes, Period" chip on stat cards)
// ---------------------------------------------------------------------------
// Positive trend (direction: up).
$color-trend-up: #42B268;
$color-trend-up-bg: #42B26814; // for up badge background (not in Figma, but added for better accessibility)
// Negative trend (direction: down).
$color-trend-down: #F66276;
$color-trend-down-bg: #F6627614; // for down badge background (not in Figma, but added for better accessibility)
// Neutral / flat trend (delta: 0 or no data).
$color-trend-neutral: #B7B7B7;
$color-trend-neutral-bg: #B1B1B114;
// ---------------------------------------------------------------------------
// Colors — rank badge
// (Status-Anchor-Tag component, Figma node 3-1043)
// All backgrounds use the badge colour at 30 % opacity (hex suffix 4D).
// ---------------------------------------------------------------------------
// Rank 1 — green (reuses $color-trend-up).
// Rank 2 — amber (unique to rank badges; not shared with trend indicators).
$color-rank-2: #F2B02D;
// Rank 3 — pink/red (reuses $color-trend-down).
// Rank − — grey (reuses $color-trend-neutral).
// Shared badge padding (Figma: 6 px each side — distinct from the 4 px
// trend-chip padding in $stat-trend-badge-padding-x).
$rank-badge-padding-x: 6px;
// ---------------------------------------------------------------------------
// Colors — interactive
// ---------------------------------------------------------------------------
// Primary CTA button background (Figma token: Button/button-primary-default).
$color-btn-primary: #017cba;
// Primary button text.
$color-btn-primary-text: #fff;
// ---------------------------------------------------------------------------
// Typography — font family
// ---------------------------------------------------------------------------
// SF Pro Text is used throughout the design. In a browser context this
// resolves to the OS system-ui font, which WordPress admin already sets.
// Declare it here so components can reference it explicitly if needed.
$font-family-base: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
// ---------------------------------------------------------------------------
// Typography — stat card
// ---------------------------------------------------------------------------
// Stat card label (e.g. "Active brands", "Analyses in last 24h").
$stat-label-size: 16px; // Figma: SF Pro Text 16px
$stat-label-weight: 500; // Figma: Medium
$stat-label-line-height: 26px; // Figma: 26px
$stat-label-color: $color-text-muted;
// Stat card value (the large number e.g. "0", "5", "3.4").
$stat-value-size: 30px;
$stat-value-weight: 600;
$stat-value-line-height: 32px;
$stat-value-color: $color-text-muted;
// Trend / delta chip text.
// The delta ("-0%") renders as a pill-badge; the label ("this month") is plain text.
$stat-trend-delta-size: 14px; // Figma: badge font size
$stat-trend-badge-bg: #B1B1B114; // Figma: neutral badge background (translucent grey)
$stat-trend-badge-radius: 30px;
$stat-trend-badge-padding-x: 4px;
$stat-trend-badge-padding-y: 4px;
$stat-trend-label-size: 12px; // Figma: plain trailing-label font size
$stat-trend-label-lh: 16px; // Figma: 16px
$stat-trend-gap: 6px; // gap between badge and plain label
// StatCard content column gaps (Figma "Frame 45" / "Data" containers).
$stat-label-data-gap: 4px; // gap between label row and value+trend block (~11–13 px in Figma)
$stat-value-trend-gap: 16px; // gap between value and trend chip inside data block
// ---------------------------------------------------------------------------
// Typography — empty state
// ---------------------------------------------------------------------------
// "No brands or products tracked yet" heading.
$empty-heading-size: 28px; // Figma: 28px
$empty-heading-weight: 400; // Figma: Medium
$empty-heading-line-height: 34px; // Figma: 34px
$empty-heading-color: $color-text-primary;
// Supporting body copy beneath the heading.
$empty-body-size: 16px;
$empty-body-weight: 400;
$empty-body-line-height: 23px;
$empty-body-color: $color-text-muted;
// ---------------------------------------------------------------------------
// Spacing
// ---------------------------------------------------------------------------
$space-xs: 4px;
$space-sm: 8px;
$space-md: 16px;
$space-lg: 24px;
$space-xl: 32px;
// Card content padding (top/left/right differ from bottom per Figma).
$card-padding-top: 16px;
$card-padding-x: 16px;
$card-padding-bottom: 16px;
// Gap between the two stacked groups inside a card (label row → value row).
$card-inner-gap: 11px;
// Gap between the three stat cards in the row.
$card-row-gap: 16px;
// ---------------------------------------------------------------------------
// Borders & radii
// ---------------------------------------------------------------------------
$radius-sm: 4px;
$radius-md: 8px;
$radius-btn: 2px; // Button corner radius — Figma token Number/Radius/radius-xs
$border-width: 1px;
$border-color: $color-border;
// ---------------------------------------------------------------------------
// Components — button
// ---------------------------------------------------------------------------
$btn-height: 36px;
$btn-radius: $radius-btn; // 6px
$btn-padding-x: $space-md;
$btn-gap: $space-sm;
// ---------------------------------------------------------------------------
// Components — empty state
// ---------------------------------------------------------------------------
// Vertical gap between icon → heading → body → button.
$empty-state-gap: 16px;
// Icon container — Figma "Tool Icon Container" (64 × 64, radius 40px, padding 10px).
$empty-state-icon-size: 64px; // container width & height
$empty-state-icon-radius: 40px; // rounded rect (not full circle)
$empty-state-icon-padding: 10px; // inner padding around SVG
$empty-state-icon-bg: rgba(57, 116, 198, 0.10); // #3974C6 @ 10% opacity
$empty-state-icon-svg: 28px; // inner SVG / Frame size
// ---------------------------------------------------------------------------
// Colors — access & upgrade modals
// (Figma: Free Users / Paid Users / Upgrade Plan flows)
// ---------------------------------------------------------------------------
// Gradient header (purple → blue) used on the access-gate modal headers and
// the Upgrade Plan modal body backdrop.
$gate-gradient-start: #7053c9;
$gate-gradient-end: #59abf7;
$gate-gradient: linear-gradient( 96deg, $gate-gradient-start 0%, $gate-gradient-end 100% );
// Green CTA ("Start 15-Day Free Trial", "Go to Dashboard") + feature checkmarks.
$color-cta: #16a571;
$color-cta-text: #fff;
// Trial auto-renew notice (Paid Users modal).
$trial-notice-bg: #ebf3fa;
$trial-notice-border: #017cba; // reuses the primary blue as the left accent
// Footnote under the CTA ("30-Day Money-Back Guarantee").
$gate-footnote-color: #757575;
// Quick Start Guide video placeholder (success modal).
$gate-video-bg: #131a2a;
// ---------------------------------------------------------------------------
// Mixins — card & table base patterns
// (reused across CompetitorsTable, QueriesTable, Reports, etc.)
// ---------------------------------------------------------------------------
/// Card-like surface: white bg, 1px border, 4px radius.
@mixin card-base {
background: $color-surface;
border: 1px solid $color-border;
border-radius: $radius-sm;
}
/// Standard data table wrapper: full-width, collapsed borders, 13px font.
@mixin table-base {
width: 100%;
border-collapse: collapse;
font-size: 13px;
border: 1px solid $color-border;
background: $color-surface;
}
/// Standard header cell: left-aligned, grey header bg, border-bottom.
@mixin table-header-cell {
padding: 14px 22px;
text-align: left;
font-size: 12px;
font-weight: 500;
color: #3c434a;
border-bottom: 1px solid $color-border;
background: #f9f9f9;
white-space: nowrap;
}
/// Standard body cell: left-aligned, 14px 22px padding, primary text.
@mixin table-body-cell {
padding: 14px 22px;
vertical-align: middle;
color: $color-text-primary;
line-height: 1.5;
}
/// Standard table row: bottom border, hover highlight, no border on last row.
@mixin table-row-base {
border-bottom: 1px solid $color-border;
&:last-child {
border-bottom: none;
}
&:hover {
background: rgba( 0, 0, 0, 0.01 );
}
}
/// Error state: 13px red text, no margin.
/// Apply inside an `--error` modifier block, targeting the inner `p`.
/// Usage: &--error { p { @include error-state; } }
@mixin error-state {
font-size: 13px;
color: $color-trend-down;
margin: 0;
}
/// Consistent focus ring for text/date inputs and WP InputControl backdrops.
/// Uses !important on border-color and box-shadow to beat WP admin's
/// `var(--wp-admin-theme-color)` injection which wins on specificity alone.
/// Usage: input:focus { @include input-focus-ring; outline: none; }
@mixin input-focus-ring {
border-color: $color-btn-primary !important;
box-shadow: 0 0 0 2px rgba( 1, 124, 186, 0.15 ) !important;
}
// Secondary focus ring for focused elements inside a focused wrapper (e.g. search input
@mixin input-focus-ring-secondary {
border-color: $color-input-border !important;
box-shadow: 0 0 0 2px rgba( 148, 148, 148, 0.15 ) !important;
}
@keyframes spin {
from { transform: rotate( 0deg ); }
to { transform: rotate( 360deg ); }
}
@@ -0,0 +1,77 @@
/**
* AccessGateModal — shared gradient-header shell for the access-gate modals
* (Free Users, Paid Users trial, trial success). Non-dismissible by default.
*
* @since 1.0.281
*/
/**
* External dependencies
*/
import { compact, join } from 'lodash'
/**
* WordPress dependencies
*/
import { Modal } from '@wordpress/components'
/**
* Internal dependencies
*/
import './AccessGateModal.scss'
import './ContentOverlay.scss'
const noop = () => {}
/**
* AccessGateModal component.
*
* @param {Object} props
* @param {string} [props.icon] Header icon class (e.g. 'dashicons dashicons-lock').
* @param {string} props.title Header title.
* @param {string} [props.className] Extra class for per-modal overrides.
* @param {boolean} [props.isDismissible=false] Allow closing via ESC / outside click.
* @param {Function} [props.onRequestClose] Close handler. Defaults to a no-op.
* @param {*} props.children Body content.
* @return {JSX.Element} Modal with gradient header.
*/
const AccessGateModal = ( {
icon = '',
title,
className = '',
isDismissible = false,
onRequestClose = noop,
children,
} ) => {
const ns = 'rank-math-ai-visibility-access-gate-modal'
return (
<Modal
onRequestClose={ onRequestClose }
className={ join( compact( [ ns, className ] ), ' ' ) }
overlayClassName="rank-math-modal-overlay rank-math-ai-visibility-content-overlay"
isDismissible={ isDismissible }
shouldCloseOnEsc={ isDismissible }
shouldCloseOnClickOutside={ isDismissible }
aria={ { labelledby: `${ ns }-title` } }
__experimentalHideHeader
>
<div className={ `${ ns }__header` }>
{ icon && (
<i className={ `${ ns }__header-icon ${ icon }` } aria-hidden="true" />
) }
<h1 id={ `${ ns }-title` } className={ `${ ns }__title` }>
{ title }
</h1>
</div>
<div className={ `${ ns }__body` }>
{ children }
</div>
</Modal>
)
}
AccessGateModal.displayName = 'AccessGateModal'
export default AccessGateModal
@@ -0,0 +1,151 @@
/**
* AccessGateModal — gradient-header shell styles + shared "gate" elements
* (intro, notice, error box, green CTA, footnote).
*/
@import '../../scss/variables';
.rank-math-ai-visibility-access-gate-modal {
&.components-modal__frame {
width: 600px;
max-width: 95vw;
max-height: 95%;
}
// Custom gradient header + body handle all spacing.
.components-modal__content {
padding: 0;
}
// -------------------------------------------------------------------------
// Gradient header — icon + title on the purple → blue gradient.
// -------------------------------------------------------------------------
&__header {
display: flex;
align-items: center;
gap: 14px;
padding: 26px 56px;
background: $gate-gradient;
}
&__header-icon {
flex-shrink: 0;
color: $color-text-light;
&.dashicons,
&.rm-icon {
width: 26px;
height: 26px;
font-size: 26px;
line-height: 1;
}
}
&__title {
margin: 0;
font-size: 20px;
font-weight: 500;
line-height: 1.3;
color: $color-text-light !important;
}
// -------------------------------------------------------------------------
// Body — vertical stack supplied by each modal.
// -------------------------------------------------------------------------
&__body {
display: flex;
flex-direction: column;
gap: $space-lg;
padding: $space-xl 56px 28px;
}
}
// ---------------------------------------------------------------------------
// Shared gate elements — used inside UpgradeToUnlockModal & ActivateTrialModal.
// ---------------------------------------------------------------------------
.rank-math-ai-visibility-gate {
&__intro {
margin: 0;
font-size: 14px;
line-height: 1.65;
color: $color-text-body;
strong {
color: $color-text-primary;
font-weight: 600;
}
}
// Trial auto-renew notice (Paid Users modal).
&__notice {
margin: 0;
padding: 12px 16px;
font-size: 13px;
line-height: 1.55;
color: $color-text-primary;
background: $trial-notice-bg;
border-left: 3px solid $trial-notice-border;
border-radius: 0 $radius-sm $radius-sm 0;
}
// API error — mirrors AddBrandModal's error box styling.
&__error {
margin: 0;
padding: 10px 14px;
background-color: #fff3f3;
border: 1px solid #f0b8b8;
border-radius: $radius-sm;
color: #c0392b;
font-size: 13px;
line-height: 1.5;
}
&__actions {
display: flex;
}
&__footnote {
margin: -12px 0 0;
font-size: 12px;
color: $gate-footnote-color;
}
}
// Green CTA — overrides the module primary button colour.
// Triple selector beats `&--primary.components-button` in Button.scss.
.rank-math-ai-visibility-btn.rank-math-ai-visibility-gate__cta.components-button {
background: $color-cta;
color: $color-cta-text;
font-size: 14px;
padding: 12px 16px;
svg {
fill: $color-cta-text;
}
&:hover:not( :disabled ) {
background: darken( $color-cta, 6% );
color: $color-cta-text !important;
}
&:focus-visible {
background: $color-cta;
color: $color-cta-text !important;
box-shadow: 0 0 0 2px #fff, 0 0 0 4px $color-cta;
}
&:focus:not( :focus-visible ):not( :disabled ) {
background: $color-cta;
color: $color-cta-text !important;
}
&:active:not( :disabled ) {
background: darken( $color-cta, 10% );
color: $color-cta-text !important;
}
}
@@ -0,0 +1,292 @@
/**
* ActivateTrialModal — 15-day trial gate for PRO users on the Free plan.
* Flow: idle / error → activating → success (logic in useTrialActivation).
*
* @since 1.0.281
*/
/**
* WordPress dependencies
*/
import { __, sprintf } from '@wordpress/i18n'
import { useState, useEffect } from '@wordpress/element'
import { Modal, Spinner, Icon } from '@wordpress/components'
import { arrowRight } from '@wordpress/icons'
/**
* Internal dependencies
*/
import getLink from '@helpers/getLink'
import Button from '../components/Button'
import AccessGateModal from './AccessGateModal'
import FeatureChecklist from './FeatureChecklist'
import useTrialActivation, { ACTIVATION_STATUS } from '../hooks/useTrialActivation'
import './ActivateTrialModal.scss'
const noop = () => {}
/**
* Cosmetic provisioning steps — advance on a timer, not backend progress.
*/
const ACTIVATION_STEPS = [
__( 'Authenticating credentials…', 'seo-by-rank-math' ),
__( 'Provisioning AI tracking workspace…', 'seo-by-rank-math' ),
__( 'Connecting to AI search models…', 'seo-by-rank-math' ),
]
/** How often the cosmetic step list advances (ms). */
const STEP_ADVANCE_MS = 1200
/**
* Trial length in days — keep in sync with the backend trial duration.
*/
const TRIAL_DAYS = 15
/**
* @param {Object} props
* @param {string|null} props.error Error message from a failed attempt.
* @param {Function} props.onActivate Start/Retry handler.
* @return {JSX.Element} Trial pitch or error state.
*/
const TrialPitch = ( { error, onActivate } ) => {
const ns = 'rank-math-ai-visibility-gate'
const renewDate = new Date( Date.now() + ( TRIAL_DAYS * 24 * 60 * 60 * 1000 ) )
.toLocaleDateString( undefined, { year: 'numeric', month: 'long', day: 'numeric' } )
return (
<AccessGateModal
icon="dashicons dashicons-unlock"
title={ __( 'Activate Your AI Visibility Trial', 'seo-by-rank-math' ) }
className="rank-math-ai-visibility-trial-modal"
>
<p className={ `${ ns }__intro` }>
{ sprintf(
/* translators: %d: trial length in days. */
__( 'Start your free trial and see exactly where AI mentions your brand. Your %d-day trial gives you full access to track, analyze, and grow your presence, before your competitors do.', 'seo-by-rank-math' ),
TRIAL_DAYS
) }
</p>
<FeatureChecklist />
<p className={ `${ ns }__notice` }>
{ sprintf(
/* translators: %s: localized auto-renew date, e.g. "June 26, 2026". */
__( 'Your trial begins immediately. Auto-renews on %s unless cancelled.', 'seo-by-rank-math' ),
renewDate
) }
</p>
{ error && (
<div className={ `${ ns }__error` } role="alert">
{ error }
</div>
) }
<div className={ `${ ns }__actions` }>
<Button
variant="primary"
className={ `${ ns }__cta` }
onClick={ onActivate }
iconRight={ <Icon icon={ arrowRight } size={ 18 } /> }
>
{ error
? __( 'Retry Activation', 'seo-by-rank-math' )
: __( 'Start 15-Day Free Trial', 'seo-by-rank-math' )
}
</Button>
</div>
<p className={ `${ ns }__footnote` }>
{ __( '30-Day Money-Back Guarantee', 'seo-by-rank-math' ) }
</p>
</AccessGateModal>
)
}
/**
* Visual state of a provisioning step row.
*
* @param {number} index Step index.
* @param {number} activeStep Currently active step index.
* @return {string} 'done' | 'active' | 'pending'.
*/
const getStepState = ( index, activeStep ) => {
if ( index < activeStep ) {
return 'done'
}
return index === activeStep ? 'active' : 'pending'
}
/**
* Activating state — spinner, headline, and cosmetic provisioning steps.
*
* @return {JSX.Element} Activating progress modal.
*/
const ActivatingState = () => {
const ns = 'rank-math-ai-visibility-activating-modal'
const [ activeStep, setActiveStep ] = useState( 0 )
// Advance the steps on a timer; hold on the last one until the hook resolves.
useEffect( () => {
const intervalId = setInterval( () => {
setActiveStep( ( step ) => Math.min( step + 1, ACTIVATION_STEPS.length - 1 ) )
}, STEP_ADVANCE_MS )
return () => clearInterval( intervalId )
}, [] )
return (
<Modal
onRequestClose={ noop }
className={ ns }
overlayClassName="rank-math-modal-overlay rank-math-ai-visibility-content-overlay"
isDismissible={ false }
shouldCloseOnEsc={ false }
shouldCloseOnClickOutside={ false }
aria={ { labelledby: `${ ns }-title` } }
__experimentalHideHeader
>
<div className={ `${ ns }__spinner` }>
<Spinner />
</div>
<h1 id={ `${ ns }-title` } className={ `${ ns }__title` }>
{ __( 'Activating Your AI Visibility Trial…', 'seo-by-rank-math' ) }
</h1>
<p className={ `${ ns }__subtitle` }>
{ __( "We're setting up your workspace and connecting AI models. This will take just a moment.", 'seo-by-rank-math' ) }
</p>
<ul className={ `${ ns }__steps` }>
{ ACTIVATION_STEPS.map( ( step, index ) => {
const state = getStepState( index, activeStep )
return (
<li key={ step } className={ `${ ns }__step ${ ns }__step--${ state }` }>
<span className={ `${ ns }__step-icon` } aria-hidden="true">
{ 'done' === state
? <i className="rm-icon rm-icon-tick" />
: <span className={ `${ ns }__step-circle` } />
}
</span>
{ step }
</li>
)
} ) }
</ul>
</Modal>
)
}
/**
* Success state — "Welcome to AI Visibility" with the Go to Dashboard CTA.
*
* @return {JSX.Element} Trial success modal.
*/
// Placeholder - swap this URL for the real quick-start guide video when ready.
const QUICK_START_VIDEO_URL = 'https://www.youtube.com/embed/aqz-KE-bpKQ?autoplay=1'
const SuccessState = () => {
const ns = 'rank-math-ai-visibility-trial-success'
const [ isPlaying, setIsPlaying ] = useState( false )
// Reload re-localizes the refreshed plan from PHP, dropping the gate.
const goToDashboard = () => window.location.reload()
return (
<AccessGateModal
icon="dashicons dashicons-yes-alt"
title={ __( 'Welcome to AI Visibility', 'seo-by-rank-math' ) }
className={ ns }
>
<p className="rank-math-ai-visibility-gate__intro">
{ __( "Your 15-day free trial is now active. We've sent a confirmation email with your trial details and next steps.", 'seo-by-rank-math' ) }
</p>
{ /* Quick Start Guide — click to play. */ }
{ isPlaying ? (
<div className={ `${ ns }__video ${ ns }__video--playing` }>
<iframe
className={ `${ ns }__video-iframe` }
src={ QUICK_START_VIDEO_URL }
title={ __( 'Quick Start Guide', 'seo-by-rank-math' ) }
allow="autoplay; fullscreen"
allowFullScreen
/>
</div>
) : (
<div
className={ `${ ns }__video ${ ns }__video--idle` }
role="button"
tabIndex={ 0 }
onClick={ () => setIsPlaying( true ) }
onKeyDown={ ( e ) => ( e.key === 'Enter' || e.key === ' ' ) && setIsPlaying( true ) }
aria-label={ __( 'Play Quick Start Guide', 'seo-by-rank-math' ) }
>
<i className={ `${ ns }__video-play dashicons dashicons-controls-play` } aria-hidden="true" />
<span className={ `${ ns }__video-caption` }>
{ __( 'Quick Start Guide', 'seo-by-rank-math' ) }
</span>
</div>
) }
<div className={ `${ ns }__links` }>
<a
href={ getLink( 'knowledgebase', 'AI Visibility Welcome Modal' ) }
target="_blank"
rel="noreferrer"
className={ `${ ns }__link` }
>
<i className="rm-icon rm-icon-book" aria-hidden="true" />
{ __( 'Knowledge Base', 'seo-by-rank-math' ) }
</a>
<a
href={ getLink( 'support', 'AI Visibility Welcome Modal' ) }
target="_blank"
rel="noreferrer"
className={ `${ ns }__link` }
>
<i className="rm-icon rm-icon-support" aria-hidden="true" />
{ __( 'Contact Support', 'seo-by-rank-math' ) }
</a>
</div>
<div className="rank-math-ai-visibility-gate__actions">
<Button
variant="primary"
className="rank-math-ai-visibility-gate__cta"
onClick={ goToDashboard }
iconRight={ <Icon icon={ arrowRight } size={ 18 } /> }
>
{ __( 'Go to Dashboard', 'seo-by-rank-math' ) }
</Button>
</div>
</AccessGateModal>
)
}
/**
* ActivateTrialModal component.
*
* @return {JSX.Element} Trial activation flow modal.
*/
const ActivateTrialModal = () => {
const { status, error, activate } = useTrialActivation()
if ( ACTIVATION_STATUS.ACTIVATING === status ) {
return <ActivatingState />
}
if ( ACTIVATION_STATUS.SUCCESS === status ) {
return <SuccessState />
}
// idle + error share the pitch layout; error adds the notice + Retry CTA.
return <TrialPitch error={ error } onActivate={ activate } />
}
ActivateTrialModal.displayName = 'ActivateTrialModal'
export default ActivateTrialModal
@@ -0,0 +1,211 @@
/**
* ActivateTrialModal — activating + success state styles.
*
* The idle/error pitch reuses the shared gate styles in GradientModal.scss.
*/
@import '../../scss/variables';
// ---------------------------------------------------------------------------
// Activating state — compact centered modal with spinner + steps.
// ---------------------------------------------------------------------------
.rank-math-ai-visibility-activating-modal {
&.components-modal__frame {
width: 440px;
max-width: 95vw;
}
.components-modal__content {
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
padding: 40px 40px $space-xl;
text-align: center;
}
&__spinner {
margin-bottom: 4px;
.components-spinner {
width: 44px;
height: 44px;
margin: 0;
color: $color-btn-primary;
}
}
&__title {
margin: 0;
font-size: 18px;
font-weight: 500;
line-height: 1.35;
color: $color-btn-primary;
}
&__subtitle {
margin: 0;
font-size: 13px;
line-height: 1.55;
color: $gate-footnote-color;
}
// ── Provisioning steps ──
&__steps {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: $space-sm;
margin: 12px 0 0;
padding: 0;
list-style: none;
text-align: left;
}
&__step {
display: flex;
align-items: center;
gap: 8px;
margin: 0;
font-size: 12px;
line-height: 1.4;
color: $color-text-muted;
transition: color 0.2s ease, opacity 0.2s ease;
&--done,
&--active {
color: $color-btn-primary;
}
&--pending {
opacity: 0.6;
}
}
&__step-icon {
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
width: 14px;
height: 14px;
color: currentColor;
.rm-icon {
font-size: 13px;
line-height: 1;
}
}
// Hollow circle for active/pending steps; active one spins a dash.
&__step-circle {
display: block;
width: 12px;
height: 12px;
border: 1.4px solid currentColor;
border-radius: 50%;
}
&__step--active &__step-circle {
border-top-color: transparent;
animation: rank-math-aiv-step-spin 0.9s linear infinite;
}
}
@keyframes rank-math-aiv-step-spin {
to {
transform: rotate( 360deg );
}
}
// ---------------------------------------------------------------------------
// Success state — Quick Start Guide placeholder + help links.
// ---------------------------------------------------------------------------
.rank-math-ai-visibility-trial-success {
&__video {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: $space-lg;
min-height: 280px;
padding: $space-xl $space-lg;
background: $gate-video-bg;
border-radius: $radius-md;
color: $color-text-light;
}
&__video--idle {
cursor: pointer;
&:hover,
&:focus-visible {
outline: none;
.rank-math-ai-visibility-trial-success__video-play {
opacity: .75;
transform: scale( 1.1 );
}
}
}
&__video--playing {
padding: 0;
overflow: hidden;
}
&__video-iframe {
display: block;
width: 100%;
height: 280px;
border: 0;
border-radius: $radius-md;
}
&__video-play.dashicons {
width: 48px;
height: 48px;
font-size: 48px;
line-height: 1;
transition: opacity .2s ease, transform .2s ease;
}
&__video-caption {
font-size: 12px;
font-weight: 500;
letter-spacing: 1.5px;
text-transform: uppercase;
}
&__links {
display: flex;
align-items: center;
gap: 28px;
}
&__link {
display: inline-flex;
align-items: center;
gap: 7px;
font-size: 14px;
color: $color-btn-primary;
text-decoration: none;
.rm-icon {
flex-shrink: 0;
font-size: 16px;
line-height: 1;
}
&:hover,
&:focus {
color: darken( $color-btn-primary, 8% );
text-decoration: underline;
box-shadow: none;
}
}
}
@@ -0,0 +1,502 @@
/**
* AddBrandModal — add / edit brand form dialog.
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
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'
/**
* Internal dependencies
*/
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'
/**
* 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: '',
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', 'language' ]
// ---------------------------------------------------------------------------
// Sub-components
// ---------------------------------------------------------------------------
/** "Coming Soon" pill badge. */
const ComingSoonBadge = () => (
<span className="rank-math-ai-visibility-add-brand-modal__coming-soon">
{ __( 'Coming Soon', 'seo-by-rank-math' ) }
</span>
)
/**
* Single platform row — checkbox + label + optional badge.
*
* @param {Object} props
* @param {Object} props.platform Platform definition object.
* @param {boolean} props.checked Whether the checkbox is checked.
* @param {Function} props.onChange Toggle handler.
* @param {boolean} props.disabled Parent-level disabled (isSaving).
*/
const PlatformRow = ( { platform, checked, onChange, disabled } ) => {
const ns = 'rank-math-ai-visibility-add-brand-modal'
const isEnabled = platform.enabled
const rowClass = [
`${ ns }__platform-row`,
! isEnabled ? `${ ns }__platform-row--disabled` : '',
].filter( Boolean ).join( ' ' )
return (
<div className={ rowClass }>
<CheckboxControl
label={ platform.label }
checked={ isEnabled ? checked : false }
onChange={ isEnabled ? onChange : undefined }
disabled={ ! isEnabled || disabled }
__nextHasNoMarginBottom={ true }
/>
{ ! isEnabled && <ComingSoonBadge /> }
</div>
)
}
/**
* 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 {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 = ( {
brand = null,
onSave,
onClose,
isSaving = false,
apiError = null,
locales = [],
languages = [],
defaultLanguage = '',
intervals = [],
platforms = {},
maxPlatforms = 1,
} ) => {
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'
// Refs to field wrappers — used to scroll/focus the first errored field.
const fieldRefs = {
name: useRef( null ),
url: useRef( null ),
description: useRef( null ),
language: useRef( null ),
}
// Locale options — object map expected by SelectWithSearch: { value: label, … }
// Memoized so the object is only rebuilt when the locales prop changes.
const localeOptions = useMemo(
() => locales.reduce( ( acc, { value, label } ) => {
acc[ value ] = label
return acc
}, { '': __( 'Select country (optional)', 'seo-by-rank-math' ) } ),
[ 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 ) {
setForm( {
id: brand.id,
name: brand.name ?? '',
url: brand.url ?? '',
description: brand.description ?? '',
locale: brand.locale ?? '',
// 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( emptyForm( platformList, defaultLanguage ) )
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ brand ] )
// ── Field helpers ────────────────────────────────────────────────────────
const set = ( field ) => ( value ) => {
setForm( ( prev ) => ( { ...prev, [ field ]: value } ) )
setErrors( ( prev ) => {
if ( ! prev[ field ] ) {
return prev
}
const next = { ...prev }
delete next[ field ]
return next
} )
}
/**
* Toggle a platform. Selecting past the plan cap evicts the oldest pick.
*
* @param {string} id Platform id to toggle.
*/
const togglePlatform = ( id ) => {
setForm( ( prev ) => {
if ( prev.platforms.includes( id ) ) {
return {
...prev,
platforms: prev.platforms.filter( ( p ) => p !== id ),
}
}
const next = [ ...prev.platforms, id ]
return {
...prev,
platforms: next.slice( Math.max( 0, next.length - maxPlatforms ) ),
}
} )
}
/**
* On blur: if the user typed a bare domain or a protocol-relative URL,
* silently prepend `https://` so validation always sees a full URL.
*/
const handleUrlBlur = () => {
const val = form.url.trim()
if ( ! val || /^https?:\/\//i.test( val ) ) {
return
}
const normalized = val.startsWith( '//' ) ? 'https:' + val : 'https://' + val
set( 'url' )( normalized )
}
// ── Validation ───────────────────────────────────────────────────────────
const validate = () => {
const newErrors = {}
if ( ! form.name.trim() ) {
newErrors.name = __( 'Brand name is required.', 'seo-by-rank-math' )
}
if ( ! form.url.trim() ) {
newErrors.url = __( 'Website URL is required.', 'seo-by-rank-math' )
} else if ( ! /^https?:\/\/.+\..+/.test( form.url.trim() ) ) {
newErrors.url = __( 'Please enter a valid URL (must start with https://).', 'seo-by-rank-math' )
}
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
}
/**
* Scroll to (and focus) the first field that has a validation error,
* so the user is taken straight to what needs fixing.
*
* @param {Object} errs Errors keyed by field name.
*/
const scrollToFirstError = ( errs ) => {
const firstField = FIELD_ORDER.find( ( field ) => errs[ field ] )
const node = firstField ? fieldRefs[ firstField ]?.current : null
if ( ! node ) {
return
}
node.scrollIntoView( { behavior: 'smooth', block: 'center' } )
const input = node.querySelector( 'input, textarea' )
if ( input ) {
input.focus( { preventScroll: true } )
}
}
// ── Save ─────────────────────────────────────────────────────────────────
const handleSave = () => {
const newErrors = validate()
if ( Object.keys( newErrors ).length > 0 ) {
scrollToFirstError( newErrors )
return
}
onSave( {
name: form.name.trim(),
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 || ! form?.language || Object.keys( errors ).length > 0
return (
<Modal
onRequestClose={ onClose }
className={ ns }
__experimentalHideHeader
>
{ /* ── Custom header: title + subtitle + close button ── */ }
<div className={ `${ ns }__header` }>
<div className={ `${ ns }__header-text` }>
<h1 className={ `${ ns }__title` }>
{ isEditMode ? __( 'Edit Brand or Product', 'seo-by-rank-math' ) : __( 'Add Brand or Product', 'seo-by-rank-math' ) }
</h1>
<p className={ `${ ns }__subtitle` }>
{ __( 'Share the basics so we can start tracking this brand or a product.', 'seo-by-rank-math' ) }
<a href={ getLink( 'ai-visibility', 'AI Visibility Add Brand Modal' ) } target="_blank" rel="noopener noreferrer">
{ __( 'Learn more', 'seo-by-rank-math' ) }
</a>
</p>
</div>
<Button
variant=""
onClick={ onClose }
disabled={ isSaving }
className={ `${ ns }__close` }
>
<Icon icon={ close } size={ 24 } />
</Button>
</div>
{ /* ── Divider between header and body ── */ }
<hr className={ `${ ns }__divider` } />
{ /* ── Body: form fields ── */ }
<div className={ `${ ns }__body` }>
{ /* Brand / Product Name */ }
<div className={ `${ ns }__field` } ref={ fieldRefs.name }>
<TextControl
label={ __( 'Brand / Product Name', 'seo-by-rank-math' ) }
value={ form.name }
onChange={ set( 'name' ) }
placeholder={ __( 'Enter your brand or product name', 'seo-by-rank-math' ) }
disabled={ isSaving }
help={ errors.name }
className={ errors.name ? `${ ns }__field--error` : '' }
__next40pxDefaultSize={ true }
__nextHasNoMarginBottom={ true }
/>
</div>
{ /* Brand / Product URL */ }
<div className={ `${ ns }__field` } ref={ fieldRefs.url }>
<TextControl
label={ __( 'Brand / Product URL', 'seo-by-rank-math' ) }
value={ form.url }
onChange={ set( 'url' ) }
onBlur={ handleUrlBlur }
placeholder="https://example.com"
type="url"
disabled={ isSaving }
help={ errors.url }
className={ errors.url ? `${ ns }__field--error` : '' }
__next40pxDefaultSize={ true }
__nextHasNoMarginBottom={ true }
/>
</div>
{ /* Description */ }
<div className={ `${ ns }__field` } ref={ fieldRefs.description }>
<TextareaControl
label={ __( 'How would you describe your brand/product?', 'seo-by-rank-math' ) }
value={ form.description }
onChange={ set( 'description' ) }
placeholder={ __( 'Describe what your brand/product does, who it\'s for, and what makes it unique. This helps AI models identify and accurately represent you.', 'seo-by-rank-math' ) }
disabled={ isSaving }
rows={ 3 }
help={ errors.description }
className={ errors.description ? `${ ns }__field--error` : '' }
__nextHasNoMarginBottom={ true }
/>
</div>
{ /* Target Country (optional) */ }
<div className={ `${ ns }__field` }>
<span className={ `${ ns }__label` }>
{ __( 'Target Country (Optional)', 'seo-by-rank-math' ) }
</span>
<SelectWithSearch
value={ form.locale }
options={ localeOptions }
onChange={ set( 'locale' ) }
disabled={ isSaving }
/>
</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={ intervals }
onChange={ set( 'interval' ) }
disabled={ isSaving }
__next40pxDefaultSize={ true }
__nextHasNoMarginBottom={ true }
/>
</div>
{ /* AI Platforms */ }
<div className={ `${ ns }__field` }>
<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` }>
{ platformList.map( ( platform ) => (
<PlatformRow
key={ platform.id }
platform={ platform }
checked={ form.platforms.includes( platform.id ) }
onChange={ () => togglePlatform( platform.id ) }
disabled={ isSaving }
/>
) ) }
</div>
</div>
</div>
{ /* ── API error message ── */ }
{ apiError && (
<div className={ `${ ns }__api-error` } role="alert">
{ apiError }
</div>
) }
{ /* ── Footer ── */ }
<div className={ `${ ns }__footer` }>
<Button
variant="secondary"
onClick={ onClose }
disabled={ isSaving }
>
{ __( 'Cancel', 'seo-by-rank-math' ) }
</Button>
<LoadingButton
variant="primary"
onClick={ handleSave }
isLoading={ isSaving }
loadingLabel={ isEditMode
? __( 'Saving…', 'seo-by-rank-math' )
: __( 'Adding…', 'seo-by-rank-math' )
}
disabled={ isActionDisabled }
>
{
isEditMode
? __( 'Save Changes', 'seo-by-rank-math' )
: __( 'Add', 'seo-by-rank-math' )
}
</LoadingButton>
</div>
</Modal>
)
}
AddBrandModal.displayName = 'AddBrandModal'
export default AddBrandModal
@@ -0,0 +1,292 @@
/**
* AddBrandModal — add / edit brand form styles.
*/
@import '../../scss/variables';
.rank-math-ai-visibility-add-brand-modal {
&.components-modal__frame {
width: 585px;
max-width: 95vw;
max-height: 85%;
}
// Remove default padding — our custom header + body handle all spacing.
.components-modal__content {
padding: 0;
}
// -------------------------------------------------------------------------
// Custom header — title + subtitle on the left, close × on the right.
// -------------------------------------------------------------------------
&__header {
display: flex;
align-items: flex-start;
justify-content: space-between;
padding: 30px 32px 32px 54px;
}
&__header-text {
display: flex;
flex-direction: column;
gap: 6px;
}
&__title {
margin: 0;
font-size: 18px;
font-weight: 400;
line-height: 1.3;
color: $color-text-primary;
}
&__subtitle {
margin: 0;
font-size: 13px;
line-height: 1.5;
color: $color-text-muted;
a {
margin-left: 2px;
}
}
&__close {
display: flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
padding: 0;
background: transparent;
border: none;
border-radius: $radius-sm;
color: $color-text-muted;
cursor: pointer;
flex-shrink: 0;
margin-top: -4px;
&:hover {
background: rgba( 0, 0, 0, 0.06 );
color: $color-text-primary;
}
&:focus-visible {
outline: 2px solid $color-text-secondary;
outline-offset: 2px;
}
&[aria-expanded="true"],
&:hover:not(:disabled, [aria-disabled="true"]) {
background: transparent;
color: inherit;
}
&:focus:not(:active) {
box-shadow: none;
}
}
// -------------------------------------------------------------------------
// Divider between header and body.
// -------------------------------------------------------------------------
&__divider {
margin: 0;
border: none;
border-top: 1px solid $color-border;
}
// -------------------------------------------------------------------------
// Body — vertical stack of field wrappers.
// -------------------------------------------------------------------------
&__body {
display: flex;
flex-direction: column;
gap: 22px;
padding: 36px 56px;;
}
&__field {
display: flex;
flex-direction: column;
gap: 6px;
}
&__label {
display: flex;
align-items: center;
gap: 6px;
font-size: 11px;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.5px;
color: $color-text-primary;
}
&__info-icon {
color: $color-text-muted;
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;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.5px;
color: $color-text-primary;
}
.rank-math-select-with-searchbox {
max-width: 100%;
.components-button {
font-weight: normal;
font-size: inherit;
font-family: inherit;
line-height: inherit;
}
}
// -------------------------------------------------------------------------
// Inline validation error state.
// -------------------------------------------------------------------------
&__field--error {
.components-text-control__input, .components-textarea-control__input {
border-color: $color-trend-down;
&:focus {
box-shadow: 0 0 0 1px $color-trend-down;
border-color: $color-trend-down;
}
}
.components-base-control__help {
color: $color-trend-down;
}
}
// -------------------------------------------------------------------------
// Collapse WP default bottom margins on form controls.
// -------------------------------------------------------------------------
.components-base-control {
margin-bottom: 0;
}
// -------------------------------------------------------------------------
// AI Platforms — 2-column checkbox grid.
// -------------------------------------------------------------------------
&__platforms {
display: grid;
grid-template-columns: 1fr 1fr;
grid-auto-flow: row;
gap: 10px 16px;
margin-top: 4px;
}
&__platform-row {
display: flex;
align-items: center;
gap: 8px;
.components-checkbox-control {
margin-bottom: 0;
}
.components-checkbox-control__input-container,
.components-checkbox-control__label {
cursor: pointer;
}
&--disabled {
opacity: 0.65;
.components-checkbox-control__input-container,
.components-checkbox-control__label {
cursor: not-allowed;
}
}
}
// -------------------------------------------------------------------------
// "Coming Soon" pill badge.
// -------------------------------------------------------------------------
&__coming-soon {
display: inline-flex;
align-items: center;
padding: 0px 4px;
background-color: #B7B7B724;
color: #9D9D9D;
font-size: 10px;
font-weight: 500;
white-space: nowrap;
flex-shrink: 0;
border: 1px solid #B7B7B721;
border-radius: 2px;
}
// -------------------------------------------------------------------------
// API error — shown above the footer when a backend error occurs.
// -------------------------------------------------------------------------
&__api-error {
margin: 0 54px 0 54px;
padding: 10px 14px;
background-color: #fff3f3;
border: 1px solid #f0b8b8;
border-radius: 4px;
color: #c0392b;
font-size: 13px;
line-height: 1.5;
}
// -------------------------------------------------------------------------
// Footer — right-aligned Cancel + primary action button.
// -------------------------------------------------------------------------
&__footer {
display: flex;
justify-content: flex-end;
align-items: center;
gap: 12px;
padding: 20px 54px 24px 24px;
.components-button {
&.is-primary {
min-height: 40px;
padding: 12px 16px;
font-weight: 300;
}
&.is-secondary {
min-height: 40px;
padding: 12px 16px;
color: #757575;
border-color: #949494;
}
}
}
.rank-math-ai-visibility-add-brand-modal__close {
padding: 0px;
color: #9b9b9b;
}
}
@@ -0,0 +1,101 @@
/**
* CheckoutIframe — authenticated Content AI checkout/upgrade iframe.
*
* Fetches a fresh single-use checkout URL on mount (token expires in 15 min
* and is consumed on first load) and renders it. A new URL is requested per
* mount, so the parent must remount this component for each session rather
* than reuse a stale URL.
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n'
import { useState, useEffect, useRef } from '@wordpress/element'
import { Spinner } from '@wordpress/components'
/**
* Internal dependencies
*/
import Button from '../components/Button'
import { getCheckoutUrl } from '../services/api/aiVisibilityApi'
import './CheckoutIframe.scss'
/**
* CheckoutIframe component.
*
* @return {JSX.Element} Loading, error, or iframe view.
*/
const CheckoutIframe = () => {
const ns = 'rank-math-ai-visibility-checkout-iframe'
const [ url, setUrl ] = useState( '' )
const [ error, setError ] = useState( null )
const [ loading, setLoading ] = useState( true )
const requested = useRef( false )
const fetchUrl = () => {
setLoading( true )
setError( null )
getCheckoutUrl()
.then( ( data ) => {
// A missing URL means an error envelope slipped through with a
// 2xx status (apiFetch only rejects on non-2xx), so surface its
// message instead of rendering a blank iframe.
if ( ! data?.url ) {
throw new Error( data?.message || __( 'Could not start the checkout session. Please try again.', 'seo-by-rank-math' ) )
}
setUrl( data.url )
} )
.catch( ( err ) => setError( err?.message || __( 'Could not start the checkout session. Please try again.', 'seo-by-rank-math' ) ) )
.finally( () => setLoading( false ) )
}
useEffect( () => {
if ( requested.current ) {
return
}
requested.current = true
fetchUrl()
}, [] )
const retry = () => {
requested.current = true
fetchUrl()
}
if ( loading ) {
return (
<div className={ `${ ns }__state` }>
<Spinner />
</div>
)
}
if ( error ) {
return (
<div className={ `${ ns }__state` }>
<p className={ `${ ns }__error` }>{ error }</p>
<Button variant="secondary" onClick={ retry }>
{ __( 'Try Again', 'seo-by-rank-math' ) }
</Button>
</div>
)
}
return (
<iframe
className={ ns }
src={ url }
title={ __( 'Upgrade your Content AI plan', 'seo-by-rank-math' ) }
/>
)
}
CheckoutIframe.displayName = 'CheckoutIframe'
export default CheckoutIframe
@@ -0,0 +1,32 @@
/**
* CheckoutIframe — Content AI checkout iframe + loading/error states.
*/
@import '../../scss/variables';
.rank-math-ai-visibility-checkout-iframe {
display: block;
width: 100%;
height: 100%;
border: 0;
// Loading / error state — fills the body, on a white surface so the
// spinner/message stays readable over the gradient body.
&__state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: $space-md;
height: 72vh;
background: $color-surface;
}
&__error {
margin: 0;
max-width: 360px;
font-size: 14px;
color: $color-text-body;
text-align: center;
}
}
@@ -0,0 +1,88 @@
/**
* ConfirmModal — generic confirmation dialog for destructive actions.
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n'
import { Modal } from '@wordpress/components'
/**
* Internal dependencies
*/
import Button from '../components/Button'
import LoadingButton from '../components/LoadingButton'
import './ConfirmModal.scss'
/**
* ConfirmModal component.
*
* @param {Object} props
* @param {string} props.title Dialog heading (passed to WP Modal).
* @param {string} props.message Body copy — explains the action.
* @param {string} [props.confirmLabel] Confirm button label. Default "Confirm".
* @param {string} [props.cancelLabel] Cancel button label. Default "Cancel".
* @param {boolean} [props.isDestructive=false] Renders confirm button in red.
* @param {boolean} [props.isProcessing=false] Disables + spins both buttons.
* @param {string|null} [props.error=null] Error message shown inside the modal on failure.
* @param {Function} [props.onConfirm] Handler for Confirm click.
* @param {Function} [props.onCancel] Handler for Cancel / close.
* @return {JSX.Element} Confirmation dialog with Cancel and Confirm buttons.
*/
const ConfirmModal = ( {
title,
message,
confirmLabel = __( 'Confirm', 'seo-by-rank-math' ),
cancelLabel = __( 'Cancel', 'seo-by-rank-math' ),
isDestructive = false,
isProcessing = false,
error = null,
onConfirm,
onCancel,
} ) => {
const ns = 'rank-math-ai-visibility-confirm-modal'
return (
<Modal
title={ title }
onRequestClose={ onCancel }
className={ ns }
>
<p className={ `${ ns }__message` }>
{ message }
</p>
{ error && (
<p className={ `${ ns }__error` }>
{ error }
</p>
) }
<div className={ `${ ns }__footer` }>
<Button
variant="secondary"
onClick={ onCancel }
disabled={ isProcessing }
>
{ cancelLabel }
</Button>
<LoadingButton
variant="primary"
isDestructive={ isDestructive }
onClick={ onConfirm }
isLoading={ isProcessing }
loadingLabel={ `${ confirmLabel }…` }
>
{ confirmLabel }
</LoadingButton>
</div>
</Modal>
)
}
ConfirmModal.displayName = 'ConfirmModal'
export default ConfirmModal
@@ -0,0 +1,74 @@
/**
* ConfirmModal — styles for the generic confirmation dialog.
*
* All colour tokens come from `_variables.scss`.
*/
@import '../../scss/variables';
.rank-math-ai-visibility-confirm-modal {
// Give the content area uniform padding — bottom space so buttons
// don't sit flush against the modal edge.
.components-modal__content {
padding-bottom: 0;
}
// -------------------------------------------------------------------------
// Message body
// -------------------------------------------------------------------------
&__message {
margin: 0 0 24px;
font-size: 14px;
line-height: 1.6;
color: $color-text-primary;
}
// -------------------------------------------------------------------------
// Footer — Cancel + Confirm buttons, right-aligned.
// Both buttons use the same height (40 px) and padding for visual harmony.
// -------------------------------------------------------------------------
&__footer {
display: flex;
justify-content: flex-end;
align-items: center;
gap: 12px;
padding: 20px 0 28px;
border-top: 1px solid $color-border;
margin-top: 4px;
// Uniform button sizing so both sit in the same visual family.
.components-button {
min-height: 36px;
padding: 8px 16px;
font-size: 13px;
font-weight: 500;
// Cancel — neutral grey outline (not WP's default blue secondary).
&.is-secondary {
color: #5c5f62;
border-color: #8c9196;
&:hover:not( :disabled ) {
color: #1d2327;
border-color: #5c5f62;
background: rgba( 0, 0, 0, 0.04 );
}
}
// Disable / destructive — red fill, consistent with danger action.
&.is-primary.is-destructive {
background: $color-trend-down;
border-color: $color-trend-down;
color: #fff;
&:hover:not( :disabled ) {
background: darken( $color-trend-down, 8% );
border-color: darken( $color-trend-down, 8% );
}
}
}
}
}
@@ -0,0 +1,60 @@
/**
* ContentOverlay — confines the WP Modal overlay to the wp-admin content
* area so the admin bar, sidebar menu, and footer stay clickable.
* Applied via the Modal `overlayClassName` prop; offsets mirror wp-admin's
* own layout rules.
*/
.rank-math-ai-visibility-content-overlay.components-modal__screen-overlay {
top: 32px; // #wpadminbar
left: 160px; // #adminmenuwrap
z-index: 999999;
// Collapsed admin menu ("Collapse menu" toggle).
body.folded & {
left: 36px;
}
// RTL admin — menu sits on the right.
body.rtl & {
left: 0;
right: 160px;
}
body.rtl.folded & {
right: 36px;
}
// Auto-folded menu between 783–960px.
@media ( max-width: 960px ) {
body.auto-fold & {
left: 36px;
}
body.rtl.auto-fold & {
left: 0;
right: 36px;
}
}
// Mobile — admin bar grows to 46px and the menu goes off-canvas.
@media ( max-width: 782px ) {
top: 46px;
&,
body.folded &,
body.auto-fold &,
body.rtl & {
left: 0;
right: 0;
}
}
}
// The footer (#wpfooter) lives in the page flow, so a fixed overlay can't be
// excluded from it geometrically — lift it above the overlay (z-index 100000)
// while one of our content-area modals is open.
body:has( .rank-math-ai-visibility-content-overlay ) #wpfooter {
position: relative;
z-index: 100001;
}
@@ -0,0 +1,53 @@
/**
* FeatureChecklist — green check-bullet benefit list shared by the
* UpgradeToUnlockModal and ActivateTrialModal.
*
* @since 1.0.281
*/
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n'
/**
* Internal dependencies
*/
import './FeatureChecklist.scss'
/**
* Default benefit rows — copy matches the Figma designs verbatim.
*/
const DEFAULT_FEATURES = [
__( 'Track how often AI mentions your brand', 'seo-by-rank-math' ),
__( 'Monitor sentiment across AI search results', 'seo-by-rank-math' ),
__( 'See which pages AI models cite as sources', 'seo-by-rank-math' ),
__( 'Benchmark your AI visibility against competitors', 'seo-by-rank-math' ),
__( 'Spot opportunities to grow your AI-driven traffic', 'seo-by-rank-math' ),
]
/**
* FeatureChecklist component.
*
* @param {Object} props
* @param {string[]} [props.features] Feature labels. Defaults to the Figma list.
* @return {JSX.Element} Unordered list with green check bullets.
*/
const FeatureChecklist = ( { features = DEFAULT_FEATURES } ) => {
const ns = 'rank-math-ai-visibility-feature-checklist'
return (
<ul className={ ns }>
{ features.map( ( feature ) => (
<li key={ feature } className={ `${ ns }__item` }>
<i className={ `${ ns }__icon dashicons dashicons-yes-alt` } aria-hidden="true" />
<span className={ `${ ns }__label` }>{ feature }</span>
</li>
) ) }
</ul>
)
}
FeatureChecklist.displayName = 'FeatureChecklist'
export default FeatureChecklist
@@ -0,0 +1,36 @@
/**
* FeatureChecklist — green check-bullet feature list styles.
*/
@import '../../scss/variables';
.rank-math-ai-visibility-feature-checklist {
display: flex;
flex-direction: column;
gap: 14px;
margin: 0;
padding: 0;
list-style: none;
&__item {
display: flex;
align-items: center;
gap: 14px;
margin: 0;
}
&__icon.dashicons {
flex-shrink: 0;
width: 20px;
height: 20px;
font-size: 20px;
line-height: 1;
color: $color-cta;
}
&__label {
font-size: 14px;
line-height: 1.4;
color: $color-text-primary;
}
}
@@ -0,0 +1,102 @@
/**
* UpgradePlanModal — shown when adding a brand would exceed the plan's
* limit. Body hosts the Content AI checkout iframe by default; pass
* `children` to override it.
*
* @since 1.0.281
*/
/**
* External dependencies
*/
import { upperFirst } from 'lodash'
/**
* WordPress dependencies
*/
import { __, sprintf } from '@wordpress/i18n'
import { Modal, Icon } from '@wordpress/components'
import { close } from '@wordpress/icons'
/**
* Internal dependencies
*/
import Button from '../components/Button'
import CheckoutIframe from './CheckoutIframe'
import './UpgradePlanModal.scss'
/**
* UpgradePlanModal component.
*
* @param {Object} props
* @param {string} props.plan Current Content AI plan slug.
* @param {boolean} [props.isTopTier=false] Highest plan — show limit-reached copy.
* @param {Function} props.onClose Close handler.
* @param {*} [props.children] Body override. Defaults to the checkout iframe.
* @return {JSX.Element} Upgrade Plan modal.
*/
const UpgradePlanModal = ( { plan = '', isTopTier = false, onClose, children = null } ) => {
const ns = 'rank-math-ai-visibility-upgrade-plan-modal'
const subtitle = isTopTier
? __( 'You\'ve reached the maximum number of brands available on your plan. Contact support if you need a higher limit.', 'seo-by-rank-math' )
: sprintf(
/* translators: %s: current plan name, e.g. "Starter". */
__( 'You\'ve reached the brand limit for your current %s plan.', 'seo-by-rank-math' ),
upperFirst( plan )
)
return (
<Modal
onRequestClose={ onClose }
className={ ns }
overlayClassName="rank-math-modal-overlay rank-math-ai-visibility-content-overlay"
aria={ { labelledby: `${ ns }-title` } }
__experimentalHideHeader
>
<div className={ `${ ns }__header` }>
<i className={ `${ ns }__header-icon dashicons dashicons-warning` } aria-hidden="true" />
<div className={ `${ ns }__header-text` }>
<h1 id={ `${ ns }-title` } className={ `${ ns }__title` }>
{ __( 'Upgrade Your Plan', 'seo-by-rank-math' ) }
</h1>
<p className={ `${ ns }__subtitle` }>
{ subtitle }
</p>
</div>
<Button
variant=""
onClick={ onClose }
className={ `${ ns }__close` }
label={ __( 'Close', 'seo-by-rank-math' ) }
>
<Icon icon={ close } size={ 20 } />
</Button>
</div>
<div className={ `${ ns }__body` }>
{ children || <CheckoutIframe /> }
</div>
<div className={ `${ ns }__footer` }>
<p className={ `${ ns }__guarantee` }>
{ __( 'All plans include a 30-day money-back guarantee.', 'seo-by-rank-math' ) }
</p>
<Button
variant="link"
onClick={ onClose }
className={ `${ ns }__later` }
>
{ __( 'I\'ll do this later', 'seo-by-rank-math' ) }
</Button>
</div>
</Modal>
)
}
UpgradePlanModal.displayName = 'UpgradePlanModal'
export default UpgradePlanModal
@@ -0,0 +1,155 @@
/**
* UpgradePlanModal — brand-limit upgrade prompt shell styles.
*/
@import '../../scss/variables';
.rank-math-ai-visibility-upgrade-plan-modal {
&.components-modal__frame {
width: 1060px;
max-width: 95vw;
max-height: 92vh;
}
.components-modal__content {
padding: 0;
}
// -------------------------------------------------------------------------
// Header — icon + title/subtitle on the left, close × on the right.
// -------------------------------------------------------------------------
&__header {
display: flex;
align-items: flex-start;
gap: 14px;
padding: $space-lg $space-xl;
}
&__header-icon.dashicons {
flex-shrink: 0;
margin-top: 2px;
width: 24px;
height: 24px;
font-size: 24px;
line-height: 1;
color: $color-text-primary;
}
&__header-text {
display: flex;
flex-direction: column;
gap: 4px;
flex: 1;
}
&__title {
margin: 0;
font-size: 18px;
font-weight: 600;
line-height: 1.3;
color: $color-text-primary;
}
&__subtitle {
margin: 0;
font-size: 13px;
line-height: 1.5;
color: $gate-footnote-color;
}
&__close.components-button {
display: flex;
align-items: center;
justify-content: center;
width: 30px;
height: 30px;
padding: 0;
flex-shrink: 0;
background: transparent;
border: 1px solid $color-border;
border-radius: $radius-sm;
color: $color-text-muted;
cursor: pointer;
&:hover:not( :disabled ) {
background: rgba( 0, 0, 0, 0.04 );
color: $color-text-primary !important;
}
&:focus-visible {
outline: 2px solid $color-btn-primary;
outline-offset: 2px;
box-shadow: none;
}
&:focus:not( :active ) {
box-shadow: none;
}
}
// -------------------------------------------------------------------------
// Body — gradient backdrop; hosts the pricing iframe once available.
// -------------------------------------------------------------------------
&__body {
background: $gate-gradient;
// Definite, viewport-based height so the full pricing page shows and
// scrolls internally — the iframe content has no height of its own.
iframe {
display: block;
width: 100%;
height: 72vh;
border: 0;
}
}
// -------------------------------------------------------------------------
// Footer — guarantee note (left) + "I'll do this later" (right).
// -------------------------------------------------------------------------
&__footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: $space-md;
padding: $space-md $space-xl;
background: $color-surface;
}
&__guarantee {
margin: 0;
font-size: 13px;
color: $color-text-body;
}
&__later.components-button {
padding: 0;
height: auto;
font-size: 14px;
font-weight: 500;
color: $color-btn-primary;
background: transparent;
border: none;
box-shadow: none;
text-decoration: none;
&:hover:not( :disabled ) {
color: darken( $color-btn-primary, 8% ) !important;
text-decoration: underline;
background: transparent;
}
&:focus-visible {
outline: 2px solid $color-btn-primary;
outline-offset: 2px;
box-shadow: none;
}
&:focus:not( :focus-visible ) {
box-shadow: none;
}
}
}
@@ -0,0 +1,70 @@
/**
* UpgradeToUnlockModal — access gate for free plugin users on the Free
* Content AI plan. The CTA links to the Content AI purchase page; the
* module unlocks automatically on reload after purchase.
*
* @since 1.0.281
*/
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n'
import { Icon } from '@wordpress/components'
import { arrowRight } from '@wordpress/icons'
/**
* Internal dependencies
*/
import getLink from '@helpers/getLink'
import Button from '../components/Button'
import AccessGateModal from './AccessGateModal'
import FeatureChecklist from './FeatureChecklist'
/**
* UpgradeToUnlockModal component.
*
* @return {JSX.Element} Non-dismissible upgrade gate modal.
*/
const UpgradeToUnlockModal = () => {
const ns = 'rank-math-ai-visibility-gate'
return (
<AccessGateModal
icon="dashicons dashicons-lock"
title={ __( 'Upgrade to Unlock AI Visibility', 'seo-by-rank-math' ) }
className="rank-math-ai-visibility-unlock-modal"
>
<p className={ `${ ns }__intro` }>
<strong>
{ __( 'Your competitors are already tracking their AI presence. You should be too.', 'seo-by-rank-math' ) }
</strong>
{ ' ' }
{ __( 'Upgrade to unlock AI Visibility module and see where your brand appears across ChatGPT, and other AI platforms, and take action before you fall further behind.', 'seo-by-rank-math' ) }
</p>
<FeatureChecklist />
<div className={ `${ ns }__actions` }>
<Button
variant="primary"
className={ `${ ns }__cta` }
href={ getLink( 'content-ai-pricing-tables', 'AI Visibility Upgrade Modal' ) }
target="_blank"
rel="noreferrer"
iconRight={ <Icon icon={ arrowRight } size={ 18 } /> }
>
{ __( 'Start 15-Day Free Trial', 'seo-by-rank-math' ) }
</Button>
</div>
<p className={ `${ ns }__footnote` }>
{ __( '30-Day Money-Back Guarantee', 'seo-by-rank-math' ) }
</p>
</AccessGateModal>
)
}
UpgradeToUnlockModal.displayName = 'UpgradeToUnlockModal'
export default UpgradeToUnlockModal
@@ -0,0 +1,15 @@
/**
* AI Visibility — shared Modals barrel.
*
* Re-exports every shared modal so call sites import from
* '../../shared/Modals' rather than per-file paths.
*/
export { default as ConfirmModal } from './ConfirmModal'
export { default as AddBrandModal } from './AddBrandModal'
export { default as AccessGateModal } from './AccessGateModal'
export { default as FeatureChecklist } from './FeatureChecklist'
export { default as UpgradeToUnlockModal } from './UpgradeToUnlockModal'
export { default as ActivateTrialModal } from './ActivateTrialModal'
export { default as UpgradePlanModal } from './UpgradePlanModal'
export { default as CheckoutIframe } from './CheckoutIframe'
@@ -0,0 +1,88 @@
/**
* ActionButtons — View / Edit / Disable action buttons for a brand table row.
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
import { memo } from '@wordpress/element'
import { __ } from '@wordpress/i18n'
/**
* Internal dependencies
*/
import Button from './Button'
import './ActionButtons.scss'
/**
* @param {Object} props
* @param {string} props.status Brand status ('active' | 'inactive').
* @param {Function} [props.onView] View handler.
* @param {Function} [props.onEdit] Edit handler.
* @param {Function} [props.onDisable] Disable/Enable handler.
* @return {JSX.Element} Rendered component.
*/
const ActionButtons = memo( ( { status, onView, onEdit, onDisable } ) => {
const ns = 'rank-math-ai-visibility-action-buttons'
const handleStatus = () => {
onDisable( status === 'inactive' ? 'activate' : 'deactivate' )
}
return (
<div className={ ns }>
<Button
variant="icon"
className={ `${ ns }__view` }
onClick={ onView }
aria-label={ __( 'View', 'seo-by-rank-math' ) }
>
<span className={ `${ ns }__inner` }>
<span className="rm-icon-eye" />
<span className={ `${ ns }__label` }>{ __( 'View', 'seo-by-rank-math' ) }</span>
</span>
</Button>
<Button
variant="icon"
className={ `${ ns }__edit` }
onClick={ onEdit }
aria-label={ __( 'Edit', 'seo-by-rank-math' ) }
>
<span className={ `${ ns }__inner` }>
<span className="rm-icon rm-icon-edit" />
<span className={ `${ ns }__label` }>{ __( 'Edit', 'seo-by-rank-math' ) }</span>
</span>
</Button>
<Button
variant="icon"
className={ `${ status === 'inactive' ? `${ ns }__inactive` : `${ ns }__active` }` }
onClick={ handleStatus }
aria-label={ status === 'inactive' ? __( 'Activate', 'seo-by-rank-math' ) : __( 'Deactivate', 'seo-by-rank-math' ) }
>
{
status === 'inactive' ? (
<span className={ `${ ns }__inner` }>
<span className="dashicons dashicons-controls-play" />
<span className={ `${ ns }__label` }>{ __( 'Activate', 'seo-by-rank-math' ) }</span>
</span>
) : (
<span className={ `${ ns }__inner` }>
<span className="rm-icon-off" />
<span className={ `${ ns }__label` }>{ __( 'Deactivate', 'seo-by-rank-math' ) }</span>
</span>
)
}
</Button>
</div>
)
} )
ActionButtons.displayName = 'ActionButtons'
export default ActionButtons
@@ -0,0 +1,243 @@
/**
* ActionButtons — colour overrides for Run and Disable icon buttons.
*/
@import '../../scss/variables';
.rank-math-ai-visibility-action-buttons {
display: grid;
grid-template-columns: repeat( 3, 28px );
gap: 8px;
align-items: center;
flex-shrink: 0;
// Icon sizing — dashicons + SVG
.dashicons {
height: 16px;
width: 16px;
font-size: 16px;
line-height: 1;
flex-shrink: 0;
}
svg {
@extend .dashicons;
path,
circle {
fill: currentColor;
}
}
.rank-math-ai-visibility-btn--icon.components-button {
width: 28px;
height: 28px;
min-width: unset;
padding: 0;
gap: 0;
border: none;
background: transparent;
box-shadow: none;
position: relative;
overflow: visible;
z-index: 1;
&:hover:not( :disabled ),
&:focus:not( :disabled ) {
background: transparent;
box-shadow: none;
}
&:hover:not( :disabled ) {
z-index: 10; // Rise above adjacent buttons when expanded
}
// Suppress WP focus ring (focus visually shifts to __inner)
&:focus-visible {
outline: none;
box-shadow: none;
}
}
&__inner {
box-sizing: border-box; // min-width counts total width incl. padding (fixes 40px→28px bug)
position: absolute;
left: 0;
top: 0;
height: 28px;
display: flex;
align-items: center;
padding: 0 6px;
border-radius: 2px;
white-space: nowrap;
min-width: 28px; // total = 28px (border-box), so content = 16px, icon centred by padding
box-shadow: 0 0 0 1px #C6C6C6;
background: transparent;
color: #757575;
pointer-events: none; // Clicks pass through to the <button> below
transition: min-width 0.2s ease,
box-shadow 0.15s ease,
background 0.15s ease,
color 0.15s ease;
// Icon spans — fixed 16×16 so centering maths hold regardless of icon font-size
> span:not( .rank-math-ai-visibility-action-buttons__label ) {
flex-shrink: 0;
width: 16px;
height: 16px;
display: inline-flex;
align-items: center;
justify-content: center;
line-height: 1;
}
}
// -------------------------------------------------------------------------
// Label — hidden, slides in on hover
// -------------------------------------------------------------------------
&__label {
max-width: 0;
overflow: hidden;
opacity: 0;
white-space: nowrap;
font-size: 12px;
line-height: 1;
// margin properties are set per-direction below
transition: max-width 0.2s ease,
opacity 0.15s ease,
margin-left 0.15s ease;
}
// -------------------------------------------------------------------------
// View — default green, hover green, expands RIGHT
// -------------------------------------------------------------------------
&__view.rank-math-ai-visibility-btn--icon.components-button {
.rank-math-ai-visibility-action-buttons__inner {
box-shadow: 0 0 0 1px #42B268;
color: #42B268;
}
&:hover:not( :disabled ) {
.rank-math-ai-visibility-action-buttons__inner {
min-width: 64px;
box-shadow: 0 0 0 1px #198B3F;
background: #F0F9F3;
color: #198B3F;
}
.rank-math-ai-visibility-action-buttons__label {
max-width: 50px;
opacity: 1;
margin-left: 4px;
}
}
}
// -------------------------------------------------------------------------
// Edit — default grey, hover grey, expands RIGHT
// -------------------------------------------------------------------------
&__edit.rank-math-ai-visibility-btn--icon.components-button {
&:hover:not( :disabled ) {
.rank-math-ai-visibility-action-buttons__inner {
min-width: 64px;
box-shadow: 0 0 0 1px #9B9B9B;
background: #F8F8F8;
color: #383838;
}
.rank-math-ai-visibility-action-buttons__label {
max-width: 40px;
opacity: 1;
margin-left: 4px;
}
}
}
// -------------------------------------------------------------------------
// Run / Activate — blue pill, expands LEFT
// right:0 anchors the pill to the button's right edge.
// row-reverse keeps the icon on the right as the label grows leftward.
// -------------------------------------------------------------------------
&__inactive.rank-math-ai-visibility-btn--icon.components-button {
// Default pill: blue border
.rank-math-ai-visibility-action-buttons__inner {
right: 0;
left: auto;
flex-direction: row-reverse;
box-shadow: 0 0 0 1px $color-btn-primary;
color: $color-btn-primary;
}
// Label uses margin-right so the gap is between label and icon (icon is on right)
.rank-math-ai-visibility-action-buttons__label {
transition: max-width 0.2s ease,
opacity 0.15s ease,
margin-right 0.15s ease;
}
&:hover:not( :disabled ) {
.rank-math-ai-visibility-action-buttons__inner {
min-width: 64px;
box-shadow: 0 0 0 1px #006BA1;
background: #EBF5FA;
color: #006BA1;
}
.rank-math-ai-visibility-action-buttons__label {
max-width: 36px;
opacity: 1;
margin-right: 4px;
}
}
}
// -------------------------------------------------------------------------
// Activate/Deactivate — red/pink pill, expands LEFT
// -------------------------------------------------------------------------
&__active.rank-math-ai-visibility-btn--icon.components-button {
.rank-math-ai-visibility-action-buttons__inner {
box-shadow: 0 0 0 1px $color-trend-down;
color: $color-trend-down;
}
&:hover:not( :disabled ) {
.rank-math-ai-visibility-action-buttons__inner {
box-shadow: 0 0 0 1px $color-trend-down;
background: #FFF9FA;
color: #F24F65;
}
}
}
&__inactive.rank-math-ai-visibility-btn--icon.components-button,
&__active.rank-math-ai-visibility-btn--icon.components-button {
// Default pill: red border
.rank-math-ai-visibility-action-buttons__inner {
right: 0;
left: auto;
flex-direction: row-reverse;
}
.rank-math-ai-visibility-action-buttons__label {
transition: max-width 0.2s ease,
opacity 0.15s ease,
margin-right 0.15s ease;
}
&:hover:not( :disabled ) {
.rank-math-ai-visibility-action-buttons__inner {
min-width: 64px;
}
.rank-math-ai-visibility-action-buttons__label {
max-width: 80px;
opacity: 1;
margin-right: 4px;
}
}
}
}
@@ -0,0 +1,78 @@
/**
* Button — module-scoped primary button.
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
import { Button as WpButton } from '@wordpress/components'
/**
* Internal dependencies
*/
import './Button.scss'
/**
* AI-Visibility primary button.
*
* @param {Object} props
* @param {string} [props.variant='primary'] WP Button variant ('primary'|'secondary'|'tertiary'|'link'|'icon').
* @param {string} [props.className] Additional class names.
* @param {string} [props.iconVariant] Icon-button colour sub-variant: 'danger' | 'active' | 'borderless'.
* Adds `--icon-{variant}` BEM modifier. Consumed here — never reaches DOM.
* @param {*} [props.iconLeft] React node rendered before `children` (e.g. a WP icon).
* Consumed here — never reaches DOM.
* @param {*} [props.iconRight] React node rendered after `children`.
* Consumed here — never reaches DOM.
* @param {boolean} [props.isDestructive] Destructive styling (red).
* @param {boolean} [props.disabled] Disabled state.
* @param {boolean} [props.isBusy] Loading spinner state.
* @param {Function} [props.onClick] Click handler.
* @param {*} props.children Button label / content.
*
* @return {JSX.Element} Button element with AI-Visibility styles and WP Button functionality.
*/
const Button = ( {
variant = 'primary',
className = '',
iconVariant,
iconLeft,
iconRight,
children,
...rest
} ) => {
const ns = 'rank-math-ai-visibility-btn'
const cls = [
ns,
`${ ns }--${ variant }`,
iconVariant && `${ ns }--icon-${ iconVariant }`,
className,
]
.filter( Boolean )
.join( ' ' )
return (
<WpButton
variant={ variant }
className={ cls }
{ ...rest }
>
{ iconLeft && (
<span className={ `${ ns }__icon-left` } aria-hidden="true">
{ iconLeft }
</span>
) }
{ children }
{ iconRight && (
<span className={ `${ ns }__icon-right` } aria-hidden="true">
{ iconRight }
</span>
) }
</WpButton>
)
}
export default Button
@@ -0,0 +1,285 @@
/**
* Button — module-scoped button styles.
*/
@import '../../scss/variables';
// ---------------------------------------------------------------------------
// Base — shared across all variants
// ---------------------------------------------------------------------------
.rank-math-ai-visibility-btn {
&.components-button {
padding: 10px 12px;
gap: 8px;
border-radius: $radius-btn;
font-size: 13px;
font-weight: 400;
line-height: 1;
white-space: nowrap;
cursor: pointer;
height: auto;
}
// ---------------------------------------------------------------------------
// Primary — solid blue fill (#017CBA)
// ---------------------------------------------------------------------------
&--primary.components-button {
background: $color-btn-primary;
color: $color-btn-primary-text;
border: none;
box-shadow: none;
&:hover:not( :disabled ) {
background: darken( $color-btn-primary, 8% );
color: $color-btn-primary-text !important; // beats WP admin theme-color override
box-shadow: none;
}
&:focus-visible {
background: $color-btn-primary;
color: $color-btn-primary-text !important;
box-shadow: 0 0 0 2px #fff, 0 0 0 4px $color-btn-primary;
outline: none;
}
// WP .components-button:focus (non-visible) — reset to match non-focused state
&:focus:not( :focus-visible ):not( :disabled ) {
background: $color-btn-primary;
color: $color-btn-primary-text !important;
box-shadow: none;
outline: none;
}
&:active:not( :disabled ) {
background: darken( $color-btn-primary, 12% );
color: $color-btn-primary-text !important;
box-shadow: none;
}
&:disabled,
&[aria-disabled='true'] {
opacity: 0.6;
cursor: not-allowed;
}
}
// ---------------------------------------------------------------------------
// Secondary — outline (#949494 border, #4E4E4E text)
// ---------------------------------------------------------------------------
&--secondary.components-button {
background: transparent;
color: #4E4E4E;
border: 1px solid $color-input-border;
border-radius: $radius-btn;
box-shadow: none;
&:hover:not( :disabled ) {
background: transparent;
color: #4E4E4E !important; // beats WP admin theme-color override on hover
border-color: #4E4E4E;
box-shadow: none;
}
&:focus-visible {
color: #4E4E4E !important;
box-shadow: none;
outline: 2px solid $color-btn-primary;
outline-offset: 2px;
}
// WP .components-button:focus (non-visible) — reset ugly inset box-shadow
&:focus:not( :focus-visible ):not( :disabled ) {
color: #4E4E4E !important;
box-shadow: none;
outline: none;
}
&:disabled,
&[aria-disabled='true'] {
opacity: 0.6;
cursor: not-allowed;
}
}
// ---------------------------------------------------------------------------
// Icon — square 28×28 icon-only button
// ---------------------------------------------------------------------------
&--icon.components-button {
width: 28px;
height: 28px;
min-width: 0;
padding: 0;
border: 1px solid $color-border;
border-radius: $radius-sm;
background: transparent;
color: $color-text-muted;
box-shadow: none;
transition: background 0.15s ease, color 0.15s ease, border-color 0.15s ease;
display: inline-flex;
align-items: center;
justify-content: center;
svg {
display: block;
flex-shrink: 0;
}
&:hover:not( :disabled ) {
background: rgba( 0, 0, 0, 0.05 );
color: $color-text-muted;
}
&:focus-visible {
outline: 2px solid $color-btn-primary;
outline-offset: 2px;
box-shadow: none;
}
&:disabled,
&[aria-disabled='true'] {
opacity: 0.6;
cursor: not-allowed;
}
}
// ---------------------------------------------------------------------------
// Destructive — red primary for irreversible actions
// ---------------------------------------------------------------------------
&--primary.components-button.is-destructive {
background: $color-trend-down;
color: #fff;
border: none;
&:hover:not( :disabled ) {
background: darken( $color-trend-down, 8% );
color: #fff !important;
}
}
// ---------------------------------------------------------------------------
// Icon colour sub-variants (--danger, --active) via `iconVariant` prop
// ---------------------------------------------------------------------------
&--icon-danger.components-button {
color: $color-trend-down;
border-color: $color-trend-down;
background: rgba( 246, 98, 118, 0.08 );
svg { fill: $color-trend-down; }
&:hover:not( :disabled ) {
background: rgba( 246, 98, 118, 0.14 );
color: $color-trend-down;
}
}
&--icon-active.components-button {
color: $color-btn-primary;
border-color: $color-btn-primary;
background: rgba( 1, 124, 186, 0.08 );
svg { fill: $color-btn-primary; }
&:hover:not( :disabled ) {
background: rgba( 1, 124, 186, 0.14 );
color: $color-btn-primary;
}
}
// ---------------------------------------------------------------------------
// Icon slot wrappers — for iconLeft / iconRight props
// ---------------------------------------------------------------------------
&__icon-left,
&__icon-right {
display: inline-flex;
align-items: center;
flex-shrink: 0;
line-height: 0;
svg {
display: block;
width: 16px;
height: 16px;
}
}
// ---------------------------------------------------------------------------
// View Transcript — compact pill variant used in the run-detail query table
// ---------------------------------------------------------------------------
&.rank-math-ai-visibility-view-transcript {
padding: 7px 8px;
gap: 6px;
background: transparent !important;
border: 1px solid #42B268 !important;
border-radius: $radius-btn;
font-size: 12px;
color: #42B268 !important;
box-shadow: none !important;
&:hover:not( :disabled ) {
background: #F0F9F3 !important;
color: #198B3F !important;
border-color: #198B3F !important;
box-shadow: none !important;
}
&:focus-visible {
outline: none !important;
box-shadow: none !important;
color: #42B268 !important;
}
&:focus:not( :focus-visible ) {
box-shadow: none !important;
outline: none !important;
color: #42B268 !important;
}
.dashicons {
color: #42B268;
height: 13px;
width: 13px;
font-size: 14px;
}
}
}
// ---------------------------------------------------------------------------
// WP Modal close button — override WP admin blue hover inside our modals
// ---------------------------------------------------------------------------
.components-modal__header {
button.components-button {
color: $color-text-muted;
background: transparent;
box-shadow: none;
&:hover:not( :disabled ) {
background: rgba( 0, 0, 0, 0.06 );
color: $color-text-primary !important;
box-shadow: none;
}
&:focus-visible {
outline: 2px solid $color-btn-primary;
outline-offset: 2px;
box-shadow: none;
color: $color-text-primary !important;
}
&:focus:not( :focus-visible ) {
box-shadow: none;
}
svg {
fill: currentColor;
}
}
}
@@ -0,0 +1,33 @@
/**
* CountBadge — 28×28 circular count pill.
*
* @since 1.0.273
*/
/**
* Internal dependencies
*/
import './CountBadge.scss'
/**
* CountBadge component.
*
* @param {Object} props
* @param {number|string|null} props.value Numeric count, or null/'error'/'warning' for no data.
* @param {string} [props.variant] 'citations' | 'mentions' | 'neutral' (default).
* @return {JSX.Element} Circular count badge.
*/
const CountBadge = ( { value, variant = 'neutral' } ) => {
const isSpecial = value === null || value === undefined || value === 'error' || value === 'warning'
const display = isSpecial ? '-' : value
const ns = 'rank-math-ai-visibility-count-badge'
return (
<span className={ `${ ns } ${ ns }--${ variant }` }>
{ display }
</span>
)
}
export default CountBadge
@@ -0,0 +1,27 @@
/**
* CountBadge — 28×28 circular count pill.
*/
@import '../../scss/variables';
.rank-math-ai-visibility-count-badge {
display: inline-flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
border-radius: 50%;
font-size: 12px;
font-weight: 400;
color: $color-text-primary;
line-height: 1;
background: rgba( 0, 0, 0, 0.05 );
&--citations {
background: rgba( 66, 178, 104, 0.08 );
}
&--mentions {
background: rgba( 223, 150, 44, 0.08 );
}
}
@@ -0,0 +1,76 @@
/**
* CountryFlag — locale tag showing a flag emoji and region code.
*
* Flag emoji is produced via the Unicode regional-indicator trick, which
* works on macOS, iOS, Android, and Linux. Windows Chrome renders country
* flags as letter-pair glyphs; if Windows fidelity becomes a requirement,
* swap the emoji span for an <img> without changing the component API.
*
* @since 1.0.273
*/
/**
* Internal dependencies
*/
import './CountryFlag.scss'
/**
* Convert a 2-letter region code (e.g. "US", "EU") to a flag emoji string
* using Unicode regional-indicator symbols (U+1F1E6 … U+1F1FF).
*
* @param {string} region Two-letter ISO 3166-1 alpha-2 or regional code.
* @return {string} Flag emoji, e.g. "🇺🇸".
*/
const toFlagEmoji = ( region ) =>
[ ...region.toUpperCase() ]
.map( ( char ) => String.fromCodePoint( 0x1f1e6 + char.charCodeAt( 0 ) - 65 ) )
.join( '' )
/**
* Extract the region code from a BCP 47 locale string or return the raw
* value when it is already a plain code (e.g. "US", "EU").
*
* @param {string} locale e.g. "en-US" or "US".
* @return {string} Upper-cased region code, e.g. "US".
*/
const extractRegion = ( locale ) => {
if ( ! locale ) {
return ''
}
const parts = locale.split( '-' )
return ( parts[ 1 ] || parts[ 0 ] ).toUpperCase()
}
/**
* CountryFlag component.
*
* @param {Object} props
* @param {string} props.locale BCP 47 locale ("en-US") or plain region code ("US").
* @return {JSX.Element|null} Null when locale is falsy.
*/
const CountryFlag = ( { locale } ) => {
if ( ! locale ) {
return null
}
const region = extractRegion( locale )
const flag = toFlagEmoji( region )
const ns = 'rank-math-ai-visibility-country-flag'
return (
<span
className={ ns }
aria-label={ region }
>
<span className={ `${ ns }__emoji` } aria-hidden="true">
{ flag }
</span>
<span className={ `${ ns }__code` }>
{ region }
</span>
</span>
)
}
export default CountryFlag
@@ -0,0 +1,34 @@
/**
* CountryFlag — styles.
*/
@import '../../scss/variables';
$country-flag-bg: #6D7A8717;
$country-flag-border: #CECECE;
.rank-math-ai-visibility-country-flag {
display: inline-flex;
align-items: center;
gap: 2px;
height: 16px;
padding: 0 6px;
border-radius: 2px;
border: 1px solid $country-flag-border;
background: $country-flag-bg;
font-size: 11px;
font-weight: 400;
line-height: 1;
white-space: nowrap;
color: $color-text-muted;
&__emoji {
font-size: 11px;
line-height: 1;
}
&__code {
font-size: 11px;
line-height: 1;
}
}
@@ -0,0 +1,63 @@
/**
* DataTable — generic data table for the AI Visibility module.
*
* @since 1.0.273
*/
/**
* Internal dependencies
*/
import './DataTable.scss'
/**
* DataTable component.
*
* @param {Object} props
* @param {Array} props.columns Column definitions (see above).
* @param {Array} props.rows Row data objects.
* @param {string|Function} [props.rowKey] Key name or function to derive a unique key per row. Default 'id'.
* @param {string} [props.className] Extra class appended to the <table> element.
* @return {JSX.Element} Rendered data table.
*/
const DataTable = ( { columns = [], rows = [], rowKey = 'id', className = '' } ) => {
const ns = 'rank-math-ai-visibility-data-table'
const tableClass = [ ns, className ].filter( Boolean ).join( ' ' )
const getRowKey = typeof rowKey === 'function'
? rowKey
: ( row ) => row[ rowKey ]
return (
<table className={ tableClass }>
<thead>
<tr>
{ columns.map( ( col ) => (
<th
key={ col.key }
className={ `${ ns }__th` }
style={ col.width ? { width: col.width } : undefined }
>
{ col.label }
</th>
) ) }
</tr>
</thead>
<tbody>
{ rows.map( ( row, i ) => (
<tr key={ getRowKey( row, i ) } className={ `${ ns }__row` }>
{ columns.map( ( col ) => (
<td key={ col.key } className={ `${ ns }__td ${ ns }__td--${ col.key }` }>
{ col.render ? col.render( row ) : ( row[ col.key ] ?? '—' ) }
</td>
) ) }
</tr>
) ) }
</tbody>
</table>
)
}
DataTable.displayName = 'DataTable'
export default DataTable
@@ -0,0 +1,21 @@
/**
* DataTable — shared data table styles.
*/
@import '../../scss/variables';
.rank-math-ai-visibility-data-table {
@include table-base;
&__th {
@include table-header-cell;
}
&__row {
@include table-row-base;
}
&__td {
@include table-body-cell;
}
}
@@ -0,0 +1,38 @@
/**
* DateInput — calendar icon + native date picker.
*
* @since 1.0.273
*/
/**
* Internal dependencies
*/
import './DateInput.scss'
/**
* DateInput component.
*
* @param {Object} props
* @param {string} props.value Current date value (YYYY-MM-DD).
* @param {Function} props.onChange Change handler — receives the native event.
* @param {string} props.ariaLabel Accessible label for the input.
* @param {string} [props.id] Optional id attribute for the input.
* @param {string} [props.className] CSS class for the input element.
* @return {JSX.Element} Calendar icon + date input.
*/
const DateInput = ( { value, onChange, ariaLabel, id, className } ) => (
<div className="rank-math-ai-visibility-date-input">
<input
type="date"
id={ id }
value={ value }
onChange={ onChange }
aria-label={ ariaLabel }
className={ className }
/>
</div>
)
DateInput.displayName = 'DateInput'
export default DateInput
@@ -0,0 +1,44 @@
/**
* DateInput component styles.
*/
@import '../../scss/variables';
.rank-math-ai-visibility-date-input {
display: inline-flex;
align-items: center;
gap: 4px;
height: 34px;
padding: 0 8px;
border: 1px solid $color-input-border;
border-radius: 2px;
&:focus-within {
@include input-focus-ring-secondary;
}
input {
border: none;
color: #383838;
padding: 0;
min-width: auto;
width: auto;
min-height: auto;
&:focus {
border: none !important;
box-shadow: none !important;
outline: none !important;
}
&::-webkit-datetime-edit {
max-width: max-content;
}
&::-webkit-calendar-picker-indicator {
opacity: .5;
background-size: 14px;
padding-left: 4px;
}
}
}
@@ -0,0 +1,63 @@
/**
* EmptyState — centred icon + heading + description + optional CTA.
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
import { Icon } from '@wordpress/components'
/**
* Internal dependencies
*/
import Button from './Button'
import './EmptyState.scss'
/**
* EmptyState component.
*
* @param {Object} props
* @param {*} props.icon WordPress icon glyph (from `@wordpress/icons`) passed to <Icon>.
* @param {string} props.heading Primary heading text.
* @param {string} props.description Supporting body copy.
* @param {string} [props.ctaLabel] CTA button label. Button omitted when absent.
* @param {Function} [props.onCta] CTA click handler. Button omitted when absent.
*
* @return {JSX.Element} Centred icon, heading, description, and optional CTA button.
*/
const EmptyState = ( { icon, heading, description, ctaLabel, onCta } ) => {
const hasCta = ctaLabel && onCta
const ns = 'rank-math-ai-visibility-empty-state'
return (
<div className={ ns }>
{ icon && (
<div className={ `${ ns }__icon` } aria-hidden="true">
<Icon icon={ icon } />
</div>
) }
<h2 className={ `${ ns }__heading` }>
{ heading }
</h2>
<p className={ `${ ns }__description` }>
{ description }
</p>
{ hasCta && (
<Button
className={ `${ ns }__cta` }
onClick={ onCta }
>
{ ctaLabel }
</Button>
) }
</div>
)
}
export default EmptyState
@@ -0,0 +1,65 @@
/**
* EmptyState — styles.
*/
@import '../../scss/variables';
.rank-math-ai-visibility-empty-state {
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
gap: 16px;
padding: 100px 0;
&__icon {
width: 60px;
height: 60px;
border-radius: $empty-state-icon-radius; // 40 px (rounded rect, not full circle)
background: $empty-state-icon-bg; // rgba(57, 116, 198, 0.10)
padding: $empty-state-icon-padding; // 10 px inner padding around SVG
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
box-sizing: border-box;
// Icon SVG / WordPress Icon fills this container.
svg {
width: $empty-state-icon-svg;
height: $empty-state-icon-svg;
fill: $color-btn-primary;
}
}
// ---------------------------------------------------------------------------
// Heading
// ---------------------------------------------------------------------------
.rank-math-ai-visibility-empty-state__heading {
margin: 0 0 8px 0;
font-size: $empty-heading-size; // 28 px
font-weight: $empty-heading-weight; // 500
line-height: $empty-heading-line-height; // 34 px
color: $empty-heading-color; // #1e1e1e
}
// ---------------------------------------------------------------------------
// Description
// ---------------------------------------------------------------------------
.rank-math-ai-visibility-empty-state__description {
margin: 0 0 15px 0;
font-size: 16px;
font-weight: 300;
line-height: 23px;
color: #868686;
max-width: 580px;
}
// CTA button — sizing comes from the shared Button component (Button.scss).
// No local overrides needed; the .rank-math-ai-visibility-btn class handles it.
.components-button.rank-math-ai-visibility-btn.rank-math-ai-visibility-empty-state__cta {
font-weight: 300;
}
}
@@ -0,0 +1,55 @@
/**
* LoadingButton — Button with built-in loading state.
*
* Renders a WP Spinner to the left of the label while loading.
* Never changes the button colour — only adds a spinner and swaps the text.
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
import { Spinner } from '@wordpress/components'
/**
* Internal dependencies
*/
import Button from './Button'
/**
* @param {Object} props
* @param {boolean} [props.isLoading=false] Swaps label and disables the button. If `iconLeft` is
* provided, also replaces it with a Spinner while loading.
* @param {string} [props.loadingLabel] Label shown while loading. Falls back to `children + '…'`.
* @param {*} props.children Default label.
* @param {boolean} [props.disabled] Additional disabled condition (independent of isLoading).
* @param {*} [props.iconLeft] Icon shown when not loading. When provided, it is replaced
* by a Spinner while loading. Omit for text-only buttons.
* @param {*} [props.iconRight] Icon shown to the right; unaffected by loading state.
* @param {string} [props.variant] WP Button variant passed through.
* @return {JSX.Element} Button with loading state support.
*/
const LoadingButton = ( {
isLoading = false,
loadingLabel,
children,
disabled,
iconLeft,
...rest
} ) => {
const label = isLoading ? ( loadingLabel ?? `${ children }…` ) : children
const leftIcon = iconLeft && isLoading ? <Spinner /> : iconLeft
return (
<Button
iconLeft={ leftIcon }
disabled={ disabled || isLoading }
{ ...rest }
>
{ label }
</Button>
)
}
export default LoadingButton
@@ -0,0 +1,57 @@
/**
* PageTopbar — shared top-bar layout for full-page detail views.
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n'
/**
* Internal dependencies
*/
import Button from './Button'
import './PageTopbar.scss'
/**
* PageTopbar component.
*
* @param {Object} props
* @param {Function} props.onBack Handler for the Back button.
* @param {string} [props.backLabel] Label for the Back button. Defaults to "← Back".
* @param {string} [props.title] Page title shown to the right of Back.
* @param {JSX.Element} [props.actions] Right-side action buttons.
* @param {string} [props.className=''] Extra class on the root element.
* @return {JSX.Element} Topbar with back + title on the left, actions on the right.
*/
const PageTopbar = ( {
onBack,
backLabel,
title,
actions,
className = '',
} ) => {
const ns = 'rank-math-ai-visibility-page-topbar'
return (
<div className={ [ ns, className ].filter( Boolean ).join( ' ' ) }>
<div className={ `${ ns }__left` }>
<Button onClick={ onBack }>
{ backLabel || __( '← Back', 'seo-by-rank-math' ) }
</Button>
{ title && (
<span className={ `${ ns }__title` }>{ title }</span>
) }
</div>
{ actions && (
<div className={ `${ ns }__actions` }>{ actions }</div>
) }
</div>
)
}
PageTopbar.displayName = 'PageTopbar'
export default PageTopbar
@@ -0,0 +1,30 @@
/**
* PageTopbar — shared top-bar layout used on Brand/Analysis Detail pages.
*/
@import '../../scss/variables';
.rank-math-ai-visibility-page-topbar {
display: flex;
align-items: center;
justify-content: space-between;
&__left {
display: flex;
align-items: center;
gap: 16px;
font-size: 14px;
}
&__title {
font-size: 16px;
font-weight: 500;
color: $color-text-primary;
}
&__actions {
display: flex;
align-items: center;
gap: $space-sm;
}
}
@@ -0,0 +1,58 @@
/**
* RankBadge — coloured pill showing a brand's rank position.
*
* @since 1.0.273
*/
/**
* Internal dependencies
*/
import './RankBadge.scss'
/**
* Resolve the BEM modifier from a numeric rank value.
*
* @param {number|null|undefined} rank
* @return {string} BEM modifier: 'rank-1', 'rank-2', 'rank-3', or 'neutral'.
*/
const getRankModifier = ( rank ) => {
if ( rank === null || rank === undefined ) {
return 'neutral'
}
const n = parseInt( rank, 10 )
if ( n === 1 ) {
return 'rank-1'
}
if ( n === 2 ) {
return 'rank-2'
}
// Rank 3 and anything beyond → red badge.
return 'rank-3'
}
/**
* RankBadge component.
*
* @param {Object} props
* @param {number|null} props.rank Numeric rank (1, 2, 3 …) or null for no data.
* @return {JSX.Element} Coloured rank circle badge.
*/
const RankBadge = ( { rank } ) => {
const modifier = getRankModifier( rank )
const label = ( rank !== null && rank !== undefined )
? `${ rank }`
: '\u2212' // "−" (Unicode minus sign)
const ns = 'rank-math-ai-visibility-rank-badge'
return (
<span className={ `${ ns } ${ ns }--${ modifier }` }>
{ label }
</span>
)
}
export default RankBadge
@@ -0,0 +1,50 @@
/**
* RankBadge — styles.
*/
@import '../../scss/variables';
.rank-math-ai-visibility-rank-badge {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 30px;
height: 30px;
padding: 0;
border-radius: 50%;
border-width: 1px;
border-style: solid;
font-size: 12px;
font-weight: 600;
line-height: 1;
white-space: nowrap;
flex-shrink: 0;
// -------------------------------------------------------------------------
// Colour variants
// -------------------------------------------------------------------------
&--rank-1 {
color: #42B268;
background-color: #42B2681A;
border-color: #42B268
}
&--rank-3 {
color: #F66276;
background-color: #F662761A;
border-color: #F66276
}
&--rank-2 {
color: #F2B02D;
background-color: #F2B02D1A;
border-color: #F2B02D
}
&--neutral {
color: #B7B7B7;
background-color: #B7B7B71A;
border-color: #B7B7B7;
}
}
@@ -0,0 +1,57 @@
/**
* ScoreBadge — AI Visibility Score pill (X/100).
*
* @since 1.0.273
*/
/**
* Internal dependencies
*/
import './ScoreBadge.scss'
/**
* Resolve the BEM modifier from a numeric score.
*
* @param {number|null|undefined} score AI Visibility score 0–100.
* @return {string} BEM modifier: 'good' | 'average' | 'poor' | 'neutral'.
*/
const getVariant = ( score ) => {
if ( score === null || score === undefined ) {
return 'neutral'
}
const n = Number( score )
if ( n >= 70 ) {
return 'good'
}
if ( n >= 40 ) {
return 'average'
}
return 'poor'
}
/**
* ScoreBadge component.
*
* @param {Object} props
* @param {number|null} props.score AI Visibility score 0–100, or null for no data.
* @param {boolean} [props.showOutOf=true] Append "/100" after the score.
* @return {JSX.Element} Coloured score pill.
*/
const ScoreBadge = ( { score, showOutOf = true } ) => {
const variant = getVariant( score )
const hasValue = score !== null && score !== undefined
let label = '-/-'
if ( hasValue ) {
label = showOutOf ? `${ score } / 100` : String( score )
}
const ns = 'rank-math-ai-visibility-score-badge'
return (
<span className={ `${ ns } ${ ns }--${ variant }` }>
{ label }
</span>
)
}
export default ScoreBadge
@@ -0,0 +1,41 @@
/**
* ScoreBadge — AI Visibility Score pill (X/100).
*/
@import '../../scss/variables';
.rank-math-ai-visibility-score-badge {
display: inline-flex;
align-items: center;
padding: 3px 6px;
border-radius: 2px;
font-size: 11px;
font-weight: 600;
white-space: nowrap;
border: 1px solid #B7B7B7;
background: rgba(183, 183, 183, 0.1);
color: #B7B7B7;
min-width: 44px;
justify-content: center;
// Score ≥ 70 — green
&--good {
background: rgba( 66, 178, 104, 0.1 );
border-color: #42B268;
color: #198B3F;
}
// Score 40–69 — amber
&--average {
background: rgba( 232, 166, 35, 0.1 );
border-color: #E8A623;
color: #D18E08;
}
// Score < 40 — red
&--poor {
background: rgba( 246, 98, 118, 0.1 );
border-color: #F66276;
color: #F66276;
}
}
@@ -0,0 +1,41 @@
/**
* SectionHeader — page/section title + optional subtitle.
*
* @since 1.0.273
*/
/**
* Internal dependencies
*/
import './SectionHeader.scss'
/**
* SectionHeader component.
*
* @param {Object} props
* @param {string} props.title Section heading (required).
* @param {string} [props.subtitle] Optional supporting text beneath the heading.
* @return {JSX.Element|null} Section heading pair, or null when title is falsy.
*/
const SectionHeader = ( { title, subtitle } ) => {
if ( ! title ) {
return null
}
const ns = 'rank-math-ai-visibility-section-header'
return (
<div className={ ns }>
<h2 className={ `${ ns }__title` }>
{ title }
</h2>
{ subtitle && (
<p className={ `${ ns }__subtitle` }>
{ subtitle }
</p>
) }
</div>
)
}
export default SectionHeader
@@ -0,0 +1,27 @@
/**
* SectionHeader — styles.
*/
@import '../../scss/variables';
.rank-math-ai-visibility-section-header {
display: flex;
flex-direction: column;
gap: 8px;
.rank-math-ai-visibility-section-header__title {
margin: 0;
font-size: 18px;
font-weight: 500;
line-height: 26px;
color: $color-text-primary;
}
.rank-math-ai-visibility-section-header__subtitle {
margin: 0;
font-size: 12px;
font-weight: 400;
line-height: 16px;
color: $color-text-secondary;
}
}
@@ -0,0 +1,120 @@
/**
* SentimentBadge — coloured pill showing an average sentiment score.
*
* @since 1.0.273
*/
/**
* External dependencies
*/
import { round } from 'lodash'
/**
* Internal dependencies
*/
import './SentimentBadge.scss'
/**
* Simple smiley face SVG icon — coloured via `currentColor` (inherits from badge).
*
* @param {Object} props Component props.
* @param {string} props.modifier BEM modifier for the badge variant (e.g. 'positive', 'negative').
* @return {JSX.Element} 12×12 smiley face SVG.
*/
const SmileyIcon = ( { modifier } ) => {
if ( modifier === 'positive' ) {
return (
<svg
width="12"
height="12"
viewBox="0 0 12 12"
style={ { fill: 'none', flexShrink: 0 } }
aria-hidden="true"
>
<circle cx="6" cy="6" r="5" stroke="currentColor" strokeWidth="1" />
<circle cx="4" cy="4.8" r="0.8" fill="currentColor" />
<circle cx="8" cy="4.8" r="0.8" fill="currentColor" />
<path
d="M3.5 7 Q6 9 8.5 7"
stroke="currentColor"
strokeWidth="1"
strokeLinecap="round"
/>
</svg>
)
}
if ( modifier === 'negative' ) {
return (
<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M5.83335 5.38542C5.83335 4.98271 5.50687 4.65625 5.10417 4.65625C4.70146 4.65625 4.375 4.98271 4.375 5.38542C4.375 5.78812 4.70146 6.11467 5.10417 6.11467C5.50687 6.11467 5.83335 5.78812 5.83335 5.38542Z" fill="#F66276" />
<path d="M8.89567 4.65625C9.2984 4.65625 9.62484 4.98271 9.62484 5.38542C9.62484 5.78812 9.2984 6.11467 8.89567 6.11467C8.493 6.11467 8.1665 5.78818 8.1665 5.38548C8.1665 4.98277 8.493 4.65625 8.89567 4.65625Z" fill="#F66276" />
<path d="M5.38427 9.48806C5.23378 9.67712 4.95854 9.70833 4.76951 9.55783C4.58048 9.40733 4.54924 9.13211 4.69974 8.94305C5.23746 8.26767 6.06821 7.8335 7.00003 7.8335C7.9319 7.8335 8.76263 8.26767 9.30034 8.94305C9.45084 9.13211 9.41963 9.40733 9.23058 9.55783C9.04158 9.70833 8.7663 9.67712 8.6158 9.48806C8.23699 9.01224 7.65412 8.7085 7.00003 8.7085C6.34599 8.7085 5.76313 9.01224 5.38427 9.48806Z" fill="#F66276" />
<path fillRule="evenodd" clipRule="evenodd" d="M6.99984 1.1665C3.77817 1.1665 1.1665 3.77817 1.1665 6.99984C1.1665 10.2215 3.77817 12.8332 6.99984 12.8332C10.2215 12.8332 12.8332 10.2215 12.8332 6.99984C12.8332 3.77817 10.2215 1.1665 6.99984 1.1665ZM2.0415 6.99984C2.0415 4.26143 4.26143 2.0415 6.99984 2.0415C9.73824 2.0415 11.9582 4.26143 11.9582 6.99984C11.9582 9.73824 9.73824 11.9582 6.99984 11.9582C4.26143 11.9582 2.0415 9.73824 2.0415 6.99984Z" fill="#F66276" />
</svg>
)
}
return (
<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M5.63997 5.38542C5.63997 4.98271 5.31352 4.65625 4.91081 4.65625C4.5081 4.65625 4.18164 4.98271 4.18164 5.38542C4.18164 5.78812 4.5081 6.11467 4.91081 6.11467C5.31352 6.11467 5.63997 5.78812 5.63997 5.38542Z" fill="#E8A623" />
<path d="M4.7207 8.30566C4.47908 8.30566 4.2832 8.50155 4.2832 8.74316C4.2832 8.98478 4.47908 9.18066 4.7207 9.18066H9.27886C9.52047 9.18066 9.71636 8.98478 9.71636 8.74316C9.71636 8.50155 9.52047 8.30566 9.27886 8.30566H4.7207Z" fill="#E8A623" />
<path d="M9.08903 4.65625C9.49176 4.65625 9.8182 4.98271 9.8182 5.38542C9.8182 5.78812 9.49176 6.11467 9.08903 6.11467C8.6863 6.11467 8.35986 5.78818 8.35986 5.38548C8.35986 4.98277 8.6863 4.65625 9.08903 4.65625Z" fill="#E8A623" />
<path fillRule="evenodd" clipRule="evenodd" d="M6.99984 1.1665C3.77817 1.1665 1.1665 3.77817 1.1665 6.99984C1.1665 10.2215 3.77817 12.8332 6.99984 12.8332C10.2215 12.8332 12.8332 10.2215 12.8332 6.99984C12.8332 3.77817 10.2215 1.1665 6.99984 1.1665ZM2.0415 6.99984C2.0415 4.26143 4.26143 2.0415 6.99984 2.0415C9.73824 2.0415 11.9582 4.26143 11.9582 6.99984C11.9582 9.73824 9.73824 11.9582 6.99984 11.9582C4.26143 11.9582 2.0415 9.73824 2.0415 6.99984Z" fill="#E8A623" />
</svg>
)
}
/**
* Resolve BEM modifier and badge hex colour from a numeric sentiment value.
*
* @param {number|null|undefined} value Sentiment 0–100, or null.
* @return {{ modifier: string }} BEM modifier for the badge.
*/
const resolveVariant = ( value ) => {
if ( value === null || value === undefined ) {
return { modifier: 'neutral' }
}
const n = Number( value )
if ( n >= 70 ) {
return { modifier: 'positive' }
}
if ( n >= 50 ) {
return { modifier: 'warning' }
}
return { modifier: 'negative' }
}
/**
* SentimentBadge component.
*
* @param {Object} props
* @param {number|null} props.score Sentiment score 0–100, or null for no data.
* @return {JSX.Element} Coloured sentiment pill with smiley icon and score percentage.
*/
const SentimentBadge = ( { score } ) => {
const { modifier } = resolveVariant( score )
const hasValue = score !== null && score !== undefined
const ns = 'rank-math-ai-visibility-sentiment-badge'
return (
<span
className={ `${ ns } ${ ns }--${ modifier }` }
>
{ hasValue && (
<span className={ `${ ns }__icon` }>
<SmileyIcon modifier={ modifier } />
</span>
) }
<span className={ `${ ns }__label` }>
{ hasValue ? `${ round( score ) }%` : '−' }
</span>
</span>
)
}
export default SentimentBadge
@@ -0,0 +1,56 @@
/**
* SentimentBadge — styles.
*/
@import '../../scss/variables';
.rank-math-ai-visibility-sentiment-badge {
display: inline-flex;
align-items: center;
gap: 4px;
height: 18px;
padding: 0 6px;
border-radius: 20px;
border-width: 1px;
border-style: solid;
font-size: 12px;
font-weight: 400;
line-height: 1;
white-space: nowrap;
min-width: 40px;
justify-content: center;
&--positive {
color: $color-trend-up;
background-color: $color-trend-up-bg;
border-color: $color-trend-up
}
&--warning {
color: $color-rank-2;
background-color: #{$color-rank-2}14;
border-color: $color-rank-2
}
&--negative {
color: $color-trend-down;
background-color: $color-trend-down-bg;
border-color: $color-trend-down
}
&--neutral {
color: $color-trend-neutral;
background-color: #{$color-trend-neutral}14;
border-color: $color-trend-neutral;
}
&__icon {
flex-shrink: 0;
display: inline-flex;
}
&__label {
font-size: 11px;
font-weight: bold;
}
}
@@ -0,0 +1,39 @@
/**
* StartTime — formatted start-time cell for the analyses table.
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
import { memo } from '@wordpress/element'
/**
* Internal dependencies
*/
import { formatDateTime } from '../../utils/formatDate'
import './StartTime.scss'
/**
* @param {Object} props
* @param {string} [props.value] ISO date string from the API.
* @return {JSX.Element} Rendered component.
*/
const StartTime = memo( ( { value = '-' } ) => {
const ns = 'rank-math-ai-visibility-processed-start-time'
if ( value && value !== '-' ) {
value = formatDateTime( value ) || value
}
return (
<div className={ ns }>
{ value }
</div>
)
} )
StartTime.displayName = 'StartTime'
export default StartTime
@@ -0,0 +1,9 @@
/**
* StartTime component styles.
*/
@import '../../scss/variables';
.rank-math-ai-visibility-processed-start-time {
color: #868686;
}
@@ -0,0 +1,90 @@
/**
* StatCard — dashboard summary card.
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
import { Icon } from '@wordpress/components'
/**
* Internal dependencies
*/
import { HelpTooltip } from '@rank-math/components'
import './StatCard.scss'
/**
* StatCard component.
*
* @param {Object} props
* @param {JSX.Element|string} [props.icon] WP icon glyph passed to <Icon icon={…}>, or a dashicon class
* suffix string (e.g. "smiley") rendered as a native dashicon span.
* @param {string} props.label Stat label, e.g. "Active brands".
* @param {string|number} props.value Primary numeric/text value, e.g. "0".
* @param {string} [props.tooltip] Tooltip text for the help icon.
* @param {string} [props.className] Extra class(es) for the card root. Use to set
* - -stat-icon-bg / --stat-icon-color CSS custom
* properties for per-card icon colours.
* @param {string|JSX.Element} [props.sub] Optional sub-label rendered below the value (e.g. a date string).
* @param {boolean} [props.compact] Reduce card padding to 20px (adds --compact modifier).
* @param {Object} [props.analysis] Optional analysis object. If provided, the card will apply
*
* @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' || analysis?.status === 'partial' ) ) ?? ( value !== null && value !== undefined && value !== '' && value !== '—' )
const ns = 'rank-math-ai-visibility-stat-card'
const rootClass = [
ns,
hasData && `${ ns }--has-data`,
compact && `${ ns }--compact`,
className,
].filter( Boolean ).join( ' ' )
const labelClass = `${ ns }__label`
const valueClass = `${ ns }__value`
return (
<div className={ rootClass }>
{ icon && (
<span className={ `${ ns }__icon-wrap` }>
{ typeof icon === 'string' ? (
<span className={ `dashicons dashicons-${ icon } ${ ns }__icon` } />
) : (
<Icon
icon={ icon }
className={ `${ ns }__icon` }
/>
) }
</span>
) }
<div className={ `${ ns }__content` }>
<div className={ `${ ns }__label-row` }>
<span className={ labelClass }>{ label }</span>
{ tooltip && HelpTooltip && (
<HelpTooltip text={ tooltip } />
) }
</div>
<div className={ `${ ns }__data` }>
<span className={ valueClass }>{ value !== null && value !== undefined ? value : 'N/A' }</span>
{ sub && (
<span className={ `${ ns }__sub` }>{ sub }</span>
) }
</div>
</div>
</div>
)
}
export default StatCard
@@ -0,0 +1,196 @@
/**
* StatCard — styles.
*/
@import '../../scss/variables';
.rank-math-ai-visibility-stat-card {
background: #fff;
border: 1px solid #e0e0e0;
border-radius: 4px;
padding: 40px 24px;
display: flex;
flex-direction: row;
align-items: flex-start;
gap: 20px;
flex: 1 1 0;
min-width: 0;
&__icon-wrap {
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
width: 48px;
height: 42px;
background: var( --stat-icon-bg, #f0f0f0 );
border-radius: 6px;
}
&.rank-math-ai-visibility-brand-overview__stat-card {
&--score {
.rank-math-ai-visibility-stat-card__icon-wrap {
background: #017CBA1F;
.dashicons {
color: #017CBA;
}
}
}
&--mentions {
.rank-math-ai-visibility-stat-card__icon-wrap {
background: #DF962C1F;
svg {
fill: #DF962C;
}
.dashicons {
color: #DF962C;
}
}
}
&--sentiment {
.rank-math-ai-visibility-stat-card__icon-wrap {
background: #5260B91F;
.dashicons {
color: #5260B9;
}
}
}
&--competitor {
.rank-math-ai-visibility-stat-card__icon-wrap {
background: #F662761F;
.dashicons {
color: #F66276;
}
}
}
&--citations, &--rank {
.rank-math-ai-visibility-stat-card__icon-wrap {
background: rgba(66,178,104,.08);
.dashicons {
color: #42B268;
}
}
}
}
&__icon {
width: 24px;
height: 24px;
flex-shrink: 0;
// Default: muted grey. Override per card via --stat-icon-color on the root element.
// SVG icons (fill) and dashicons (color) — both controlled by the same variable.
fill: var( --stat-icon-color, #{$color-text-muted} );
color: var( --stat-icon-color, #{$color-text-muted} );
// Dashicon sizing when used as the icon element.
&.dashicons {
width: 20px;
height: 20px;
font-size: 20px;
line-height: 1;
}
}
&__content {
display: flex;
flex-direction: column;
gap: 11px;
min-width: 0;
}
&__label-row {
display: flex;
align-items: center;
gap: 8px;
}
&__label {
font-size: 16px;
line-height: normal;
font-weight: 400;
color: #9b9b9b;
}
&--has-data {
.rank-math-ai-visibility-stat-card__label,
.rank-math-ai-visibility-stat-card__value {
color: inherit;
}
}
// Data block — wraps value + trend chip.
&__data {
display: flex;
flex-direction: column;
gap: 8px;
min-width: 0;
}
&__value {
font-size: $stat-value-size;
font-weight: $stat-value-weight;
line-height: $stat-value-line-height;
color: $stat-value-color;
}
// Active brands / Rank Score — blue
&--active-brands {
--stat-icon-bg: #017CBA1F;
--stat-icon-color: #017CBA;
}
// Analyses in last 24h — indigo
&--analyses {
--stat-icon-bg: #5260B91F;
--stat-icon-color: #5260B9;
}
// Avg mentions per brand — amber
&--mentions {
--stat-icon-bg: #E8A6231F;
--stat-icon-color: #E8A623;
}
// -------------------------------------------------------------------------
// Compact modifier — reduced padding for dense contexts (e.g. AnalysisRunDetail)
// -------------------------------------------------------------------------
&--target-brand .rank-math-ai-visibility-stat-card__icon-wrap {
background: #017CBA1F;
.dashicons {
color: #017CBA;
}
}
&--duration-timing .rank-math-ai-visibility-stat-card__icon-wrap {
background: #5260B91F;
.dashicons {
color: #5260B9;
}
}
&--compact {
padding: 20px;
}
// Sub-label — rendered below the value (e.g. a date string).
&__sub {
font-size: 12px;
color: $color-text-muted;
margin-top: 2px;
}
}
@@ -0,0 +1,57 @@
/**
* StatusBadge — run status pill (success / error / partial).
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n'
/**
* Internal dependencies
*/
import './StatusBadge.scss'
/**
* Get the human-readable label for a run status.
*
* @param {string} status 'success' | 'partial' | 'error'
* @return {string} Translated status label.
*/
const getStatusLabel = ( status ) => {
if ( status === 'success' ) {
return __( 'Success', 'seo-by-rank-math' )
}
if ( status === 'partial' ) {
return __( 'Partial', 'seo-by-rank-math' )
}
return __( 'Failed', 'seo-by-rank-math' )
}
/**
* StatusBadge component.
*
* @param {Object} props
* @param {string} [props.status] 'success' | 'error' | 'partial'
* @return {JSX.Element|null} Coloured status pill with SVG icon.
*/
const StatusBadge = ( { status } ) => {
if ( ! status ) {
return null
}
const isSuccess = status === 'success'
const ns = 'rank-math-ai-visibility-status-badge'
return (
<span className={ `${ ns } ${ ns }--${ status }` }>
{ isSuccess ? <i className="dashicons dashicons-yes" aria-hidden="true" /> : <i className="dashicons dashicons-no" aria-hidden="true" /> }
{ getStatusLabel( status ) }
</span>
)
}
export default StatusBadge
@@ -0,0 +1,46 @@
/**
* StatusBadge — run status pill (success / error / partial).
*/
@import '../../scss/variables';
.rank-math-ai-visibility-status-badge {
display: inline-flex;
align-items: center;
gap: 4px;
font-size: 11px;
font-weight: 400;
padding: 2px 6px 2px 3px;
border-radius: 20px;
flex-shrink: 0;
white-space: nowrap;
line-height: 1;
svg {
flex-shrink: 0;
}
.dashicons {
height: 14px;
width: 14px;
font-size: 14px;
}
&--success {
color: $color-trend-up;
background: rgba( 66, 178, 104, 0.1 );
border: 1px solid rgba( 66, 178, 104, 0.35 );
}
&--error {
color: $color-trend-down;
background: rgba( 246, 98, 118, 0.1 );
border: 1px solid rgba( 246, 98, 118, 0.35 );
}
&--partial {
color: $color-rank-2;
background: rgba( 242, 176, 45, 0.1 );
border: 1px solid rgba( 242, 176, 45, 0.35 );
}
}
@@ -0,0 +1,68 @@
/**
* StatusIcon — inline status indicator (icon + hover-reveal label).
*
* The root keeps a fixed footprint; the pill expands as an absolutely
* positioned overlay, so revealing the label never shifts surrounding layout.
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n'
import { Tooltip } from '@wordpress/components'
/**
* Internal dependencies
*/
import './StatusIcon.scss'
const VARIANTS = {
error: {
icon: 'dashicons-warning',
label: __( 'Error', 'seo-by-rank-math' ),
tooltip: __( 'Last analysis failed. It will be retried automatically.', 'seo-by-rank-math' ),
},
running: {
icon: 'dashicons-update',
label: __( 'Running', 'seo-by-rank-math' ),
tooltip: __( 'Analysis in progress — data will appear in approximately 10 minutes.', 'seo-by-rank-math' ),
},
pending: {
icon: 'dashicons-update',
label: __( 'Pending', 'seo-by-rank-math' ),
tooltip: __( 'Analysis in progress — data will appear in approximately 10 minutes.', 'seo-by-rank-math' ),
},
}
/**
* StatusIcon component.
*
* @param {Object} props
* @param {'error'|'running'|'pending'} props.variant Status variant.
* @return {JSX.Element|null} Status icon, or null for unknown variants.
*/
const StatusIcon = ( { variant } ) => {
const config = VARIANTS[ variant ]
if ( ! config ) {
return null
}
const ns = 'rank-math-ai-visibility-status-icon'
return (
<Tooltip text={ config.tooltip }>
<span className={ `${ ns } ${ ns }--${ variant }` }>
<span className={ `${ ns }__pill` }>
<span className={ `dashicons ${ config.icon }` } />
<span className={ `${ ns }__label` }>{ config.label }</span>
</span>
</span>
</Tooltip>
)
}
StatusIcon.displayName = 'StatusIcon'
export default StatusIcon
@@ -0,0 +1,86 @@
/**
* StatusIcon — shared inline status indicator.
*
* The root is a fixed 26x26 anchor; the pill is an absolute overlay that
* expands on hover without affecting surrounding layout (no jump).
*/
@import '../../scss/variables';
.rank-math-ai-visibility-status-icon {
position: relative;
display: inline-flex;
width: 26px;
height: 26px;
flex-shrink: 0;
vertical-align: middle;
&__pill {
position: absolute;
top: 50%;
left: 0;
transform: translateY( -50% );
display: inline-flex;
align-items: center;
border-radius: 100px;
border: 1px solid transparent;
padding: 4px;
background: #fff;
cursor: default;
white-space: nowrap;
transition: background 0.18s ease;
}
.dashicons {
width: 16px;
height: 16px;
font-size: 16px;
&.dashicons-update {
font-weight: 100;
animation: spin 2s linear infinite;
}
}
&:hover {
z-index: 10;
}
&--error &__pill {
color: #E05252;
border-color: #E05252;
}
&--error:hover &__pill {
background: #FCEEEE;
}
&--running &__pill,
&--pending &__pill {
color: #E08C1A;
border-color: #E08C1A;
}
&--running:hover &__pill,
&--pending:hover &__pill {
background: #FCF3E8;
}
&__label {
font-size: 12px;
font-weight: 500;
line-height: 1;
max-width: 0;
overflow: hidden;
opacity: 0;
transition: max-width 0.18s ease, opacity 0.15s ease,
margin-left 0.15s ease;
}
&:hover &__label {
max-width: 60px;
opacity: 1;
margin-left: 4px;
}
}
@@ -0,0 +1,54 @@
/**
* StatusToggle — enabled/disabled checkbox for a query row.
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n'
import { CheckboxControl } from '@wordpress/components'
/**
* Internal dependencies
*/
import './StatusToggle.scss'
/**
* StatusToggle component.
*
* @param {Object} props
* @param {boolean} props.value Checked state — true = enabled, false = disabled.
* @param {Function} props.onChange Called with the new boolean value on change.
* @param {boolean} [props.disabled=false] Disables interaction when true.
* @param {boolean} [props.isLoading=false] Shows in-progress label when true.
* @return {JSX.Element} Checkbox toggle with contextual label.
*/
const StatusToggle = ( { value, onChange, disabled = false, isLoading = false } ) => {
let label
if ( isLoading ) {
label = value
? __( 'Enabling…', 'seo-by-rank-math' )
: __( 'Disabling…', 'seo-by-rank-math' )
} else {
label = value
? __( 'Enabled', 'seo-by-rank-math' )
: __( 'Disabled', 'seo-by-rank-math' )
}
return (
<CheckboxControl
className="rank-math-ai-visibility-status-toggle"
label={ label }
checked={ value }
onChange={ onChange }
disabled={ disabled || isLoading }
__nextHasNoMarginBottom={ true }
/>
)
}
StatusToggle.displayName = 'StatusToggle'
export default StatusToggle
@@ -0,0 +1,58 @@
/**
* StatusToggle — query status checkbox styles.
*/
@import '../../scss/variables';
.rank-math-ai-visibility-status-toggle {
&.components-checkbox-control {
margin-bottom: 0;
}
.components-base-control__field {
display: flex;
align-items: center;
margin: 0;
}
// WP CheckboxControl renders an inner HStack between the checkbox box and
// the label — target it directly because the HStack resets gap to 0.
.components-h-stack {
gap: 8px !important;
}
// Ensure the input container doesn't collapse.
.components-checkbox-control__input-container {
flex-shrink: 0;
margin: 0;
}
// Pin checked colour to the module's primary blue.
.components-checkbox-control__input[type='checkbox'] {
margin: 0;
&:checked {
background-color: $color-btn-primary;
border-color: $color-btn-primary;
}
&:focus {
box-shadow: 0 0 0 2px #fff, 0 0 0 4px $color-btn-primary;
}
}
// Label — 13 px to match table cell body text.
.components-checkbox-control__label {
font-size: 13px;
font-weight: 400;
color: $color-text-primary;
line-height: 1;
margin: 0;
}
// Reduce opacity when the whole control is disabled.
.components-checkbox-control__input[type='checkbox']:disabled {
opacity: 0.6;
}
}
@@ -0,0 +1,255 @@
/**
* TranscriptModal — two-panel transcript modal.
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
import { useState } from '@wordpress/element'
import { __ } from '@wordpress/i18n'
import { Modal } from '@wordpress/components'
/**
* Internal dependencies
*/
import Button from './Button'
import './TranscriptModal.scss'
/**
* Apply syntax highlighting to a JSON string.
* Escapes HTML entities first, then wraps tokens in <span class="json-*"> elements.
* Safe to use with dangerouslySetInnerHTML since input is our own serialised data.
*
* Colour classes (defined in TranscriptModal.scss):
* .json-key → amber #F2B02D (object keys)
* .json-string → teal #5DBEC4 (string values)
* .json-number → white #e5e7eb (numbers)
* .json-boolean → teal #5DBEC4 (true / false)
* .json-null → grey #9ca3af (null)
*
* @param {string} json JSON string to highlight.
* @return {string} HTML string with <span> tokens.
*/
const highlightJson = ( json ) => {
// 1. Escape HTML entities.
const escaped = json
.replace( /&/g, '&amp;' )
.replace( /</g, '&lt;' )
.replace( />/g, '&gt;' )
// 2. Tokenise and wrap.
return escaped.replace(
// Matches: "key": | "string value" | true/false/null | numbers
/("(?:\\u[a-fA-F0-9]{4}|\\[^u]|[^\\"])*"(?:\s*:)?|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)/g,
( token ) => {
if ( token.endsWith( ':' ) || ( token.startsWith( '"' ) && token.endsWith( '":' ) ) ) {
return `<span class="json-key">${ token }</span>`
}
if ( token.startsWith( '"' ) ) {
return `<span class="json-string">${ token }</span>`
}
if ( token === 'true' || token === 'false' ) {
return `<span class="json-boolean">${ token }</span>`
}
if ( token === 'null' ) {
return `<span class="json-null">${ token }</span>`
}
return `<span class="json-number">${ token }</span>`
}
)
}
/**
* Copy text to clipboard with execCommand fallback.
*
* @param {string} text Text to copy.
* @param {Function} onSuccess Called after successful copy.
*/
const copyToClipboard = ( text, onSuccess ) => {
const done = () => {
onSuccess()
}
if ( window.navigator.clipboard ) {
window.navigator.clipboard.writeText( text ).then( done ).catch( () => fallback() )
} else {
fallback()
}
function fallback() {
const el = document.createElement( 'textarea' )
el.value = text
el.style.cssText = 'position:fixed;top:0;left:0;opacity:0;pointer-events:none'
document.body.appendChild( el )
el.focus()
el.select()
try {
document.execCommand( 'copy' )
done()
} catch {
// Silently swallow — clipboard unavailable in this context.
}
document.body.removeChild( el )
}
}
/**
* TranscriptModal component.
*
* @param {Object} props
* @param {Object} props.entry The transcript entry to display.
* @param {Function} props.onClose Called when the modal should close.
* @return {JSX.Element} Two-panel transcript modal.
*/
/**
* Prepare an entry for JSON serialisation.
* Parses `extraction_data` if it is a JSON string so it renders as a nested
* object rather than an escaped string.
*
* @param {Object} entryObj The transcript entry.
* @return {Object} Entry with `extraction_data` parsed.
*/
const prepareEntry = ( entryObj ) => {
if ( typeof entryObj.extraction_data !== 'string' ) {
return entryObj
}
try {
return { ...entryObj, extraction_data: JSON.parse( entryObj.extraction_data ) }
} catch {
return entryObj
}
}
const TranscriptModal = ( { entry, onClose } ) => {
const ns = 'rank-math-ai-visibility-transcript-modal'
const [ copiedText, setCopiedText ] = useState( false )
const [ copiedJson, setCopiedJson ] = useState( false )
const handleCopyText = () => {
const text = [
__( 'Query:', 'seo-by-rank-math' ) + ' ' + ( entry.query || '' ),
'',
__( 'Response:', 'seo-by-rank-math' ) + ' ' + ( entry.response || entry.excerpt || '' ),
].join( '\n' )
copyToClipboard( text, () => {
setCopiedText( true )
setTimeout( () => setCopiedText( false ), 2000 )
} )
}
const handleCopyJson = () => {
copyToClipboard( JSON.stringify( prepareEntry( entry ), null, 2 ), () => {
setCopiedJson( true )
setTimeout( () => setCopiedJson( false ), 2000 )
} )
}
return (
<Modal
title={ (
<span className={ `${ ns }__modal-title` }>
<span className="dashicons rm-icon-comments" aria-hidden="true" />
{ __( 'Transcript', 'seo-by-rank-math' ) }
</span>
) }
onRequestClose={ onClose }
className={ `${ ns }__wrapper` }
size="large"
>
<div className={ ns }>
<div className={ `${ ns }__left` }>
<div className={ `${ ns }__left-header` }>
<Button
variant="secondary"
className={ `${ ns }__copy-btn` }
onClick={ handleCopyText }
iconLeft={ <span className="dashicons dashicons-clipboard" /> }
>
{ copiedText
? __( 'Copied!', 'seo-by-rank-math' )
: __( 'Copy Raw Text', 'seo-by-rank-math' )
}
</Button>
</div>
<div className={ `${ ns }__sections` }>
<div className={ `${ ns }__section` }>
<div className={ `${ ns }__section-left` }>
<span className={ `${ ns }__section-icon` }>
<span className="dashicons dashicons-admin-users" aria-hidden="true" />
</span>
</div>
<div className={ `${ ns }__section-right` }>
<div className={ `${ ns }__section-label` }>
{ __( 'Original Query', 'seo-by-rank-math' ) }
</div>
<div className={ `${ ns }__content-box` }>
{ entry.query || '—' }
</div>
</div>
</div>
<div className={ `${ ns }__section` }>
<div className={ `${ ns }__section-left` }>
<span className={ `${ ns }__section-icon` }>
<span className="dashicons dashicons-superhero-alt" aria-hidden="true" />
</span>
</div>
<div className={ `${ ns }__section-right` }>
<div className={ `${ ns }__section-label` }>
{ __( 'Model Response', 'seo-by-rank-math' ) }
</div>
<div className={ `${ ns }__content-box ${ ns }__content-box--response` }>
{ entry.response || entry.excerpt || '—' }
</div>
</div>
</div>
</div>
</div>
<div className={ `${ ns }__right` }>
<div className={ `${ ns }__right-header` }>
<div className={ `${ ns }__right-title` }>
<span className={ `${ ns }__json-badge` }>{ '{}' }</span>
{ __( 'Extracted Signals', 'seo-by-rank-math' ) }
</div>
<Button
variant="secondary"
onClick={ handleCopyJson }
className={ `${ ns }__copy-json-btn` }
iconLeft={ <span className="dashicons dashicons-clipboard" /> }
>
{ copiedJson
? __( 'Copied!', 'seo-by-rank-math' )
: __( 'Copy JSON', 'seo-by-rank-math' )
}
</Button>
</div>
<div className={ `${ ns }__json-viewer` }>
{ /* dangerouslySetInnerHTML is safe: content is our own serialised JSON */ }
<pre
className={ `${ ns }__json-pre` }
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={ {
__html: highlightJson( JSON.stringify( prepareEntry( entry ), null, 2 ) ),
} }
/>
</div>
</div>
</div>
</Modal>
)
}
TranscriptModal.displayName = 'TranscriptModal'
export default TranscriptModal
@@ -0,0 +1,259 @@
/**
* TranscriptModal — two-panel transcript modal styles.
*/
@import '../../scss/variables';
.rank-math-ai-visibility-transcript-modal {
display: grid;
grid-template-columns: 56fr 44fr;
flex: 1 1 0;
min-height: 0;
overflow: hidden;
height: 100%;
max-height: 50vh;
&__modal-title {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
}
// Override WP Modal
&__wrapper {
.components-modal__frame {
max-width: 1130px;
width: 92vw;
max-height: 90vh;
display: flex !important;
flex-direction: column !important;
}
.components-modal__header {
flex-shrink: 0;
padding: 22px 28px;
border-bottom: 1px solid #E0E0E0;
.components-modal__header-heading {
font-size: 13px;
}
}
.components-modal__content {
padding: 0 !important;
overflow: hidden;
flex: 1 1 0;
min-height: 0;
display: flex;
flex-direction: column;
}
}
&__section-right {
flex: 1;
}
&__left,
&__right {
display: flex;
flex-direction: column;
height: 100%;
overflow: hidden;
}
&__sections,
&__json-viewer {
flex: 1;
overflow-y: auto;
min-height: 0;
}
&__left {
display: flex;
flex-direction: column;
gap: 4px;
padding: 25px;
background: $color-surface;
border-right: 1px solid $color-border;
overflow-y: auto;
}
&__left-header {
display: flex;
justify-content: flex-end;
}
// "Copy Raw Text" — small pill button in left header
&__copy-btn {
&.rank-math-ai-visibility-btn.components-button {
font-size: 12px;
padding: 4px 10px;
min-height: 28px;
height: 28px;
color: $color-text-muted;
border-color: $color-border;
background: transparent;
&:hover {
color: $color-btn-primary;
border-color: $color-btn-primary;
background: transparent;
}
.dashicons {
font-size: 13px;
width: 13px;
height: 13px;
}
}
}
&__right {
.rank-math-ai-visibility-transcript-modal__copy-json-btn.rank-math-ai-visibility-btn.components-button {
color: #C6C6C6;
border-color: #C6C6C6;
}
}
&__sections {
gap: 40px;
display: flex;
flex-direction: column;
}
&__section {
display: flex;
gap: 10px;
}
&__section-label {
display: flex;
align-items: center;
gap: 10px;
font-size: 12px;
color: #868686;
font-weight: 500;
margin-bottom: 8px;
}
&__section-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 34px;
height: 34px;
min-width: 30px;
border-radius: 50%;
background: #fff;
border: 1px solid #E3E3E3;
color: #1E1E1E;
.dashicons {
font-size: 16px;
width: 16px;
height: 16px;
}
}
&__content-box {
padding: 20px 24px;
border: 1px solid $color-border;
border-radius: 0 11px 11px 11px;
font-size: 12px;
color: $color-text-primary;
line-height: 1.6;
background: $color-surface;
white-space: pre-wrap;
&--response {
max-height: 280px;
overflow-y: auto;
}
}
&__right {
display: flex;
flex-direction: column;
background: #1c1c1c;
overflow: hidden;
}
&__right-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 20px 40px;
flex-shrink: 0;
}
&__right-title {
display: flex;
align-items: center;
gap: 10px;
font-size: 13px;
font-weight: 500;
color: #C6C6C6;
}
&__json-badge {
display: inline-flex;
align-items: center;
justify-content: center;
width: 34px;
height: 34px;
border-radius: 50%;
background: #fff;
font-size: 11px;
font-weight: 400;
color: #1E1E1E;
font-family: monospace;
}
// "Copy JSON" — small pill button on dark header
&__copy-json-btn {
&.rank-math-ai-visibility-btn.components-button {
font-size: 12px;
padding: 4px 10px;
min-height: 28px;
height: 28px;
color: #9ca3af;
background: rgba( 255, 255, 255, 0.06 );
border: 1px solid rgba( 255, 255, 255, 0.12 );
&:hover {
color: #e5e7eb;
background: rgba( 255, 255, 255, 0.12 );
border-color: rgba( 255, 255, 255, 0.25 );
}
.dashicons {
font-size: 13px;
width: 13px;
height: 13px;
}
}
}
&__json-viewer {
flex: 1;
overflow-y: auto;
padding: 0 40px;
}
&__json-pre {
margin: 0;
font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
font-size: 12px;
line-height: 1.7;
color: #d1d5db;
white-space: pre;
overflow-x: auto;
.json-key { color: #F2B02D; margin-left: 8px; } // amber — object keys
.json-string { color: #5DBEC4; } // teal — string values
.json-number { color: #e5e7eb; } // white — numbers
.json-boolean { color: #5DBEC4; } // teal — true / false
.json-null { color: #9ca3af; } // grey — null
}
}
@@ -0,0 +1,254 @@
/**
* TranscriptViewer — two-panel transcript viewer.
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
import { useState, useMemo } from '@wordpress/element'
import { __ } from '@wordpress/i18n'
import { SelectControl } from '@wordpress/components'
/**
* Internal dependencies
*/
import TranscriptModal from './TranscriptModal'
import StatusBadge from './StatusBadge'
import DateInput from './DateInput'
import { formatDateTime } from '../../utils/formatDate'
import './TranscriptViewer.scss'
/**
* Format ISO timestamp as "Apr 15, 2026 · 10:00 AM".
*
* @param {string} isoStr ISO date string.
* @return {string} Formatted timestamp or '—'.
*/
const formatTimestamp = ( isoStr ) => formatDateTime( isoStr, ' · ' )
/**
* @param {Object} props
* @param {Object} props.entry Transcript entry data.
* @param {boolean} props.isSelected Whether this card is active.
* @param {Function} props.onSelect Called with entry.id on left panel click.
* @param {Function} props.onViewTranscript Called with full entry object when "View >" is clicked.
* @return {JSX.Element} Rendered component.
*/
const EntryCard = ( { entry, isSelected, onSelect, onViewTranscript = () => {} } ) => {
const ns = 'rank-math-ai-visibility-transcript-viewer'
const modelName = entry.model || entry.platform || ''
return (
<div
role="button"
tabIndex={ 0 }
className={ [
`${ ns }__entry-card`,
isSelected ? `${ ns }__entry-card--selected` : '',
].filter( Boolean ).join( ' ' ) }
onClick={ () => onSelect( entry.id ) }
onKeyDown={ ( e ) => ( e.key === 'Enter' || e.key === ' ' ) && onSelect( entry.id ) }
aria-current={ isSelected ? 'true' : undefined }
>
<div className={ `${ ns }__entry-meta` }>
<span className={ `${ ns }__entry-timestamp` }>
{ formatTimestamp( entry.created_at ) }
{ modelName && ` · ${ modelName }` }
</span>
<StatusBadge status={ entry.status } />
</div>
<p className={ `${ ns }__entry-query-text` }>
{ entry.query || '—' }
</p>
<div className={ `${ ns }__entry-footer` }>
{ entry.duration_seconds !== null && entry.duration_seconds !== undefined && (
<span className={ `${ ns }__entry-duration` }>
<span className="dashicons dashicons-clock" aria-hidden="true" />
{ entry.duration_seconds }s
</span>
) }
<span
role="button"
tabIndex={ 0 }
className={ `${ ns }__entry-view-link` }
onClick={ ( e ) => {
e.stopPropagation(); onViewTranscript( entry )
} }
onKeyDown={ ( e ) => ( e.key === 'Enter' || e.key === ' ' ) && onViewTranscript( entry ) }
>
{ __( 'View', 'seo-by-rank-math' ) }
<span className="dashicons dashicons-arrow-right-alt2" aria-hidden="true" />
</span>
</div>
</div>
)
}
/**
* @param {Object} props
* @param {Object|null} props.entry Selected entry, or null.
* @return {JSX.Element} Right-panel transcript preview.
*/
const TranscriptDetail = ( { entry } ) => {
const ns = 'rank-math-ai-visibility-transcript-viewer'
return (
<div className={ `${ ns }__detail` }>
<div className={ `${ ns }__detail-header` }>
<span className="dashicons rm-icon-comments" aria-hidden="true" />
<span className={ `${ ns }__detail-header-title` }>
{ __( 'Transcript preview', 'seo-by-rank-math' ) }
</span>
</div>
{ entry ? (
<div className={ `${ ns }__detail-content` }>
<div className={ `${ ns }__section` }>
<div className={ `${ ns }__section-left` }>
<span className="dashicons dashicons-admin-users" aria-hidden="true" />
</div>
<div className={ `${ ns }__section-right` }>
<div className={ `${ ns }__section-label` }>
{ __( 'Original Query', 'seo-by-rank-math' ) }
</div>
<div className={ `${ ns }__query-box` }>
{ entry.query || '—' }
</div>
</div>
</div>
<div className={ `${ ns }__section` }>
<div className={ `${ ns }__section-left` }>
<span className="dashicons dashicons-superhero-alt" aria-hidden="true" />
</div>
<div className={ `${ ns }__section-right` }>
<div className={ `${ ns }__section-label` }>
{ __( 'Model Response', 'seo-by-rank-math' ) }
</div>
<div className={ `${ ns }__response-box` }>
{ entry.response || entry.excerpt || '—' }
</div>
</div>
</div>
</div>
) : (
<div className={ `${ ns }__detail-empty` }>
<p>{ __( 'Select a query to preview its transcript.', 'seo-by-rank-math' ) }</p>
</div>
) }
</div>
)
}
/**
* @param {Object} props
* @param {Array} [props.entries=[]] Transcript entry objects.
* @param {*} [props.selectedEntryId] ID shown in the detail panel.
* @param {Function} [props.onSelectEntry] Called with entry ID on selection.
* @return {JSX.Element} Two-panel viewer.
*/
const TranscriptViewer = ( {
entries = [],
selectedEntryId = null,
onSelectEntry = () => {},
} ) => {
const ns = 'rank-math-ai-visibility-transcript-viewer'
const [ dateFilter, setDateFilter ] = useState( '' )
const [ queryFilter, setQueryFilter ] = useState( '' )
const [ modalEntry, setModalEntry ] = useState( null )
const queryOptions = useMemo( () => [
{ label: __( 'All queries', 'seo-by-rank-math' ), value: '' },
...entries.map( ( e ) => {
let label = `Entry ${ e.id }`
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 ] )
const filteredEntries = useMemo( () => {
let result = entries
if ( dateFilter ) {
result = result.filter( ( e ) => e.created_at?.startsWith( dateFilter ) )
}
if ( queryFilter ) {
result = result.filter( ( e ) => String( e.id ) === queryFilter )
}
return result
}, [ entries, dateFilter, queryFilter ] )
const effectiveId = selectedEntryId ?? filteredEntries[ 0 ]?.id ?? null
const selectedEntry = entries.find( ( e ) => e.id === effectiveId ) ?? null
return (
<div className={ ns }>
<div className={ `${ ns }__left` }>
<div className={ `${ ns }__filter-bar` }>
<div className={ `${ ns }__date-filter` }>
<DateInput
value={ dateFilter }
onChange={ ( e ) => setDateFilter( e.target.value ) }
ariaLabel={ __( 'Filter by date', 'seo-by-rank-math' ) }
className={ `${ ns }__date-input` }
/>
</div>
<SelectControl
value={ queryFilter }
options={ queryOptions }
onChange={ setQueryFilter }
className={ `${ ns }__query-select` }
__nextHasNoMarginBottom={ true }
/>
</div>
<div className={ `${ ns }__entry-list` }>
{ filteredEntries.length === 0 ? (
<p className={ `${ ns }__empty-list` }>
{ __( 'No entries match the current filters.', 'seo-by-rank-math' ) }
</p>
) : (
filteredEntries.map( ( entry ) => (
<EntryCard
key={ entry.id }
entry={ entry }
isSelected={ entry.id === effectiveId }
onSelect={ onSelectEntry }
onViewTranscript={ setModalEntry }
/>
) )
) }
</div>
</div>
<TranscriptDetail entry={ selectedEntry } />
{ modalEntry && (
<TranscriptModal
entry={ modalEntry }
onClose={ () => setModalEntry( null ) }
/>
) }
</div>
)
}
TranscriptViewer.displayName = 'TranscriptViewer'
export default TranscriptViewer
@@ -0,0 +1,274 @@
/**
* TranscriptViewer.scss
*/
@import '../../scss/variables';
.rank-math-ai-visibility-transcript-viewer {
display: grid;
grid-template-columns: 450px 1fr;
min-height: 500px;
background: $color-surface;
overflow: hidden;
gap: 23px;
&__left {
border-right: 1px solid $color-border;
display: flex;
flex-direction: column;
overflow: hidden;
background: $color-surface;
border: 1px solid #e0e0e0;
border-radius: 4px;
}
&__section-right {
flex: 1;
}
&__filter-bar {
display: flex;
align-items: center;
gap: 12px;
padding: 18px;
border-bottom: 1px solid $color-border;
background: $color-surface;
flex-shrink: 0;
}
&__date-filter {
display: inline-flex;
align-items: center;
background: #FFFFFF;
.dashicons {
font-size: 13px;
width: 13px;
height: 13px;
color: $color-text-muted;
}
input {
border: none;
}
}
&__date-input {
border: none;
outline: none;
font-size: 12px;
color: $color-text-primary;
background: transparent;
width: 105px;
padding: 0;
}
&__query-select {
flex: 1;
min-width: 0;
}
&__entry-list {
overflow-y: auto;
flex: 1;
padding: 26px 18px;
display: flex;
flex-direction: column;
gap: 14px;
background: #FCFCFC;
}
&__empty-list {
font-size: 13px;
color: $color-text-muted;
padding: $space-md;
margin: 0;
text-align: center;
}
&__entry-card {
display: block;
padding: 26px;
border: 1px solid $color-border;
border-radius: 4px;
cursor: pointer;
transition: border-color 0.12s ease;
background: $color-surface;
&:hover {
border-color: darken( $color-border, 10% );
}
&--selected {
border: 1px solid $color-btn-primary;
}
}
&__entry-meta {
display: flex;
align-items: center;
justify-content: space-between;
gap: $space-sm;
margin-bottom: 20px;
}
&__entry-timestamp {
font-size: 12px;
color: #868686;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
flex: 1;
min-width: 0;
}
.rank-math-ai-visibility-transcript-viewer__entry-query-text {
font-size: 12px;
color: $color-text-primary;
margin: 0 0 10px;
line-height: 1.5;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
margin-bottom: 20px;
}
&__entry-footer {
display: flex;
align-items: center;
justify-content: space-between;
}
&__entry-duration {
display: inline-flex;
align-items: center;
gap: 3px;
font-size: 12px;
color: #9ca3af;
.dashicons {
font-size: 13px;
width: 13px;
height: 13px;
}
}
&__entry-view-link {
display: inline-flex;
align-items: center;
gap: 2px;
font-size: 12px;
color: $color-btn-primary;
font-weight: 500;
cursor: pointer;
user-select: none;
.dashicons {
font-size: 14px;
width: 14px;
height: 14px;
line-height: 1;
}
&:hover {
color: darken( $color-btn-primary, 10% );
}
}
&__detail {
display: flex;
flex-direction: column;
overflow-y: auto;
background: #FCFCFC;
border: 1px solid #e0e0e0;
border-radius: 4px;
}
&__detail-header {
display: flex;
align-items: center;
gap: 8px;
padding: 22px 18px;
border-bottom: 1px solid $color-border;
flex-shrink: 0;
.dashicons {
font-size: 16px;
width: 16px;
height: 16px;
}
}
&__detail-header-title {
font-size: 14px;
font-weight: 500;
color: $color-text-primary;
}
&__detail-empty {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
p {
font-size: 13px;
color: $color-text-muted;
margin: 0;
}
}
&__detail-content {
padding: 24px;
display: flex;
flex-direction: column;
gap: 40px;
background: #FCFCFC;
}
&__section {
display: flex;
gap: 10px;
.dashicons {
display: inline-flex;
align-items: center;
justify-content: center;
width: 34px;
height: 34px;
min-width: 34px;
border-radius: 50%;
background: #fff;
font-size: 14px;
border: 1px solid #E3E3E3;
}
}
&__section-label {
display: flex;
align-items: center;
gap: 10px;
font-size: 12px;
color: #868686;
font-weight: 500;
margin-bottom: 8px;
}
&__query-box,
&__response-box {
padding: 20px 24px;
border: 1px solid $color-border;
border-radius: 0 11px 11px 11px;
font-size: 12px;
color: $color-text-primary;
line-height: 1.6;
background: $color-surface;
white-space: pre-wrap;
}
&__date-input.input[type="date"] {
border: none;
}
}
@@ -0,0 +1,25 @@
/**
* AI Visibility — shared components barrel.
*/
export { default as Button } from './Button'
export { default as LoadingButton } from './LoadingButton'
export { default as StatCard } from './StatCard'
export { default as EmptyState } from './EmptyState'
export { default as RankBadge } from './RankBadge'
export { default as SentimentBadge } from './SentimentBadge'
export { default as CountryFlag } from './CountryFlag'
export { default as SectionHeader } from './SectionHeader'
export { default as ActionButtons } from './ActionButtons'
export { default as ConfirmModal } from '../Modals/ConfirmModal'
export { default as StatusToggle } from './StatusToggle'
export { default as TranscriptViewer } from './TranscriptViewer'
export { default as TranscriptModal } from './TranscriptModal'
export { default as StartTime } from './StartTime'
export { default as ScoreBadge } from './ScoreBadge'
export { default as StatusBadge } from './StatusBadge'
export { default as CountBadge } from './CountBadge'
export { default as DataTable } from './DataTable'
export { default as PageTopbar } from './PageTopbar'
export { default as DateInput } from './DateInput'
export { default as StatusIcon } from './StatusIcon'
@@ -0,0 +1,199 @@
/**
* useDashboard — dashboard data hook.
*
* Manages summary metrics, per-brand rollup rows, mutations, and the
* first-analysis poller. Implements stale-while-revalidate: serves a stale
* cache immediately, then revalidates in the background.
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
import { useState, useEffect, useCallback, useRef } from '@wordpress/element'
import { __ } from '@wordpress/i18n'
/**
* Internal dependencies
*/
import {
getOverview,
getInsights,
createBrand,
updateBrand,
setBrandStatus,
} from '../services/api/aiVisibilityApi'
import { getAnalysisState } from '../../utils/analysisState'
const POLL_INTERVAL_MS = 20000
const POLL_MAX_ATTEMPTS = 10
const POLL_MAX_ERRORS = 3
/**
* Whether a brand qualifies for first-analysis polling.
*
* Only brands awaiting their first result (no `last_analyzed` yet) are
* pollable: the insights endpoint always returns the last *completed* run, so
* polling a brand that already has data can't detect a newer run completing —
* that resolves on the normal /overview refresh instead.
*
* @param {Object} brand Brand row.
* @return {boolean} True when pollable.
*/
const isPollable = ( brand ) => 'running' === getAnalysisState( brand ) && ! brand.last_analyzed
/**
* Dashboard data hook.
*
* @return {Object} summary, brands, loading, isStale, error, refetch, mutation handlers.
*/
const useDashboard = () => {
const [ summary, setSummary ] = useState( null )
const [ brands, setBrands ] = useState( [] )
const [ loading, setLoading ] = useState( true )
const [ isStale, setIsStale ] = useState( false )
const [ error, setError ] = useState( null )
const isFetching = useRef( false )
const pollState = useRef( {} ) // per-brand attempt/error counters
const searchRef = useRef( '' ) // preserved across refreshes/polls
/**
* @param {boolean} [refresh=false] Force upstream revalidation.
* @return {Promise<Object|null>} Envelope or null on guard/error.
*/
const fetchDashboard = useCallback( async ( refresh = false ) => {
if ( isFetching.current ) {
return null
}
isFetching.current = true
setError( null )
try {
const data = await getOverview( { refresh, search: searchRef.current } )
setSummary( data?.summary ?? null )
setBrands( Array.isArray( data?.brands ) ? data.brands : [] )
setIsStale( !! data?.is_stale )
return data
} catch ( err ) {
setError( err?.message || __( 'Failed to load dashboard data.', 'seo-by-rank-math' ) )
return null
} finally {
isFetching.current = false
setLoading( false )
}
}, [] )
/**
* @param {string} term Search term (filters cached rows server-side).
* @return {Promise<Object|null>}
*/
const handleSearch = useCallback( ( term ) => {
searchRef.current = term || ''
return fetchDashboard()
}, [ fetchDashboard ] )
// Initial load; revalidate if the served cache was stale.
useEffect( () => {
const load = async () => {
const data = await fetchDashboard()
if ( data?.is_stale ) {
await fetchDashboard( true )
}
}
load()
}, [ fetchDashboard ] )
// First-analysis poller — bounded per-brand, paused when tab is hidden.
useEffect( () => {
const pollable = brands.filter( isPollable )
if ( ! pollable.length ) {
return
}
const intervalId = setInterval( async () => {
if ( document.hidden ) {
return
}
for ( const brand of pollable ) {
if ( ! pollState.current[ brand.id ] ) {
pollState.current[ brand.id ] = { attempts: 0, errors: 0 }
}
const state = pollState.current[ brand.id ]
if ( state.attempts >= POLL_MAX_ATTEMPTS || state.errors >= POLL_MAX_ERRORS ) {
continue
}
state.attempts++
try {
const data = await getInsights( brand.id )
state.errors = 0
// First analysis completed (404→insights). Refresh from the
// API so the row's analysis_status reflects completion and
// the running icon clears.
if ( data?.insights ) {
await fetchDashboard( true )
}
} catch {
state.errors++
}
}
}, POLL_INTERVAL_MS )
return () => clearInterval( intervalId )
}, [ brands, fetchDashboard ] )
/**
* @param {Function} mutation API call to run.
* @param {string} fallbackMsg Error fallback message.
* @return {Promise<*>}
*/
const mutate = useCallback( async ( mutation, fallbackMsg ) => {
try {
const result = await mutation()
await fetchDashboard()
return result
} catch ( err ) {
setError( err?.message || fallbackMsg )
throw err
}
}, [ fetchDashboard ] )
const handleAddBrand = useCallback(
( data ) => mutate( () => createBrand( data ), __( 'Failed to create brand.', 'seo-by-rank-math' ) ),
[ mutate ]
)
const handleUpdateBrand = useCallback(
( id, data ) => mutate( () => updateBrand( id, data ), __( 'Failed to update brand.', 'seo-by-rank-math' ) ),
[ mutate ]
)
const handleDisableBrand = useCallback(
( id ) => mutate( () => setBrandStatus( id, 'inactive' ), __( 'Failed to disable brand.', 'seo-by-rank-math' ) ),
[ mutate ]
)
const handleEnableBrand = useCallback(
( id ) => mutate( () => setBrandStatus( id, 'active' ), __( 'Failed to enable brand.', 'seo-by-rank-math' ) ),
[ mutate ]
)
return {
summary,
brands,
loading,
isStale,
error,
refetch: fetchDashboard,
handleSearch,
handleAddBrand,
handleUpdateBrand,
handleDisableBrand,
handleEnableBrand,
}
}
export default useDashboard
@@ -0,0 +1,67 @@
/**
* useFetch — generic data-fetching hook with cancelled-flag guard.
*
* Options: skip (bail out when truthy), errorMessage (fallback), initialData.
* Returns setData for optimistic updates without triggering a re-fetch.
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
import { useState, useEffect } from '@wordpress/element'
/**
* @param {Function} fetcher Returns a Promise; re-called on deps change.
* @param {Array} deps useEffect dependency array.
* @param {Object} [options]
* @param {boolean} [options.skip] Skip the fetch when truthy.
* @param {string} [options.errorMessage]
* @param {*} [options.initialData]
* @return {Object} { data, loading, error, setData }
*/
const useFetch = ( fetcher, deps, options = {} ) => {
const {
skip = false,
errorMessage = 'Failed to load.',
initialData = null,
} = options
const [ data, setData ] = useState( initialData )
const [ loading, setLoading ] = useState( ! skip )
const [ error, setError ] = useState( null )
useEffect( () => {
if ( skip ) {
setLoading( false )
return
}
let cancelled = false
setLoading( true )
setError( null )
fetcher()
.then( ( result ) => {
if ( ! cancelled ) {
setData( result )
setLoading( false )
}
} )
.catch( ( err ) => {
if ( ! cancelled ) {
setError( err?.message || errorMessage )
setLoading( false )
}
} )
return () => {
cancelled = true
}
}, deps )
return { data, loading, error, setData }
}
export default useFetch
@@ -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
@@ -0,0 +1,69 @@
/**
* useTrialActivation — trial activation state machine.
*
* idle ──activate()──▶ activating ──▶ success / error (retry via activate()).
*
* @since 1.0.281
*/
/**
* WordPress dependencies
*/
import { useState, useCallback } from '@wordpress/element'
import { __ } from '@wordpress/i18n'
/**
* Internal dependencies
*/
import { activateTrial } from '../services/api/aiVisibilityApi'
/**
* Activation flow statuses.
*/
export const ACTIVATION_STATUS = {
IDLE: 'idle',
ACTIVATING: 'activating',
SUCCESS: 'success',
ERROR: 'error',
}
// Keep the loader visible long enough to avoid a flash on fast responses.
const MIN_ACTIVATING_MS = 3500
/**
* Trial activation hook.
*
* @return {Object} { status, error, activate } Activation state and handler.
*/
const useTrialActivation = () => {
const [ status, setStatus ] = useState( ACTIVATION_STATUS.IDLE )
const [ error, setError ] = useState( null )
const activate = useCallback( async () => {
setStatus( ACTIVATION_STATUS.ACTIVATING )
setError( null )
const startedAt = Date.now()
try {
await activateTrial()
// Keep the loader visible for the minimum duration.
const remaining = MIN_ACTIVATING_MS - ( Date.now() - startedAt )
if ( remaining > 0 ) {
await new Promise( ( done ) => setTimeout( done, remaining ) )
}
setStatus( ACTIVATION_STATUS.SUCCESS )
} catch ( err ) {
setStatus( ACTIVATION_STATUS.ERROR )
setError(
err?.message || __( 'Something went wrong while activating your trial. Please try again.', 'seo-by-rank-math' )
)
}
}, [] )
return { status, error, activate }
}
export default useTrialActivation
@@ -0,0 +1,143 @@
/**
* AI Visibility — REST API service layer.
*
* Wraps `@wordpress/api-fetch` and unwraps the `{ success, data }` envelope.
* All caching is server-side; these calls are cheap cache reads in steady state.
*
* @since 1.0.273
*/
/**
* WordPress dependencies
*/
import apiFetch from '@wordpress/api-fetch'
import { addQueryArgs } from '@wordpress/url'
export const NAMESPACE = '/rankmath/v1/ai-visibility'
/**
* @param {string} path REST path.
* @param {Object} options apiFetch options.
* @return {Promise<*>} Unwrapped `data` payload.
*/
const request = async ( path, options = {} ) => {
const response = await apiFetch( { path, ...options } )
return response && response.success === true ? response.data : response
}
/**
* @param {string} path Path under the namespace.
* @param {Object} [params] Query params.
* @return {string} Full path.
*/
const buildPath = ( path, params ) => {
const full = `${ NAMESPACE }${ path }`
return params && Object.keys( params ).length ? addQueryArgs( full, params ) : full
}
/**
* GET /overview — summary + per-brand rollup rows.
*
* @param {Object} [params] Optional params.
* @param {boolean} [params.refresh] Force upstream revalidation (SWR).
* @param {string} [params.search] Server-side name/URL filter.
* @return {Promise<{ summary: Object, brands: Array, is_stale: boolean }>} Overview data.
*/
export const getOverview = ( { refresh = false, search = '' } = {} ) =>
request( buildPath( '/overview', {
...( refresh ? { refresh: 1 } : {} ),
...( search ? { search } : {} ),
} ) )
/**
* GET /brands/{id} — brand identity (cache-first).
*
* @param {string} id Brand UUID.
* @return {Promise<{ brand: Object }>} Brand details.
*/
export const getBrand = ( id ) => request( buildPath( `/brands/${ id }` ) )
/**
* POST /brands — create a brand.
*
* @param {Object} data Brand payload (name, url, description, locale).
* @return {Promise<{ brand: Object }>} Created brand.
*/
export const createBrand = ( data ) =>
request( buildPath( '/brands' ), { method: 'POST', data } )
/**
* PUT /brands/{id} — update brand fields.
*
* @param {string} id Brand UUID.
* @param {Object} data Partial brand payload.
* @return {Promise<{ brand: Object }>} Updated brand.
*/
export const updateBrand = ( id, data ) =>
request( buildPath( `/brands/${ id }` ), { method: 'PUT', data } )
/**
* PATCH /brands/{id} — set brand status ('active' or 'inactive').
*
* @param {string} id Brand UUID.
* @param {string} status New status.
* @return {Promise<{ brand: Object }>} Updated brand.
*/
export const setBrandStatus = ( id, status ) =>
request( buildPath( `/brands/${ id }` ), { method: 'PATCH', data: { status } } )
/**
* Activate 15-day AI Visibility free trial.
*
* @return {Promise<{ activated: boolean }>} Activation result.
*/
export const activateTrial = () =>
request( buildPath( '/trial/activate' ), { method: 'POST' } )
/**
* Get an authenticated, single-use Content AI checkout iframe URL.
*
* Fetch a fresh URL per iframe session — the token in it expires in 15 min
* and is consumed on first load, so never reload the iframe with the same URL.
*
* @return {Promise<{ url: string }>} Iframe src URL.
*/
export const getCheckoutUrl = () =>
request( buildPath( '/checkout-url' ), { method: 'POST' } )
/**
* GET /brands/{id}/insights — latest-analysis payload (cache-first).
* Returns `{ pending: true }` when no completed analysis exists yet.
*
* @param {string} id Brand UUID.
* @return {Promise<{ insights: Object }|{ pending: boolean }>} Latest insights or pending status.
*/
export const getInsights = ( id ) => request( buildPath( `/brands/${ id }/insights` ) )
/**
* GET /brands/{id}/queries — query list (cache-first, 24h TTL).
*
* @param {string} id Brand UUID.
* @return {Promise<{ queries: Array }>} List of queries with their current enabled/disabled status and performance metrics.
*/
export const getQueries = ( id ) => request( buildPath( `/brands/${ id }/queries` ) )
/**
* PUT /brands/{id}/queries/{queryId} — enable/disable a query.
*
* @param {string} id Brand UUID.
* @param {string} queryId Query UUID.
* @param {Object} data `{ enabled }`.
* @return {Promise<{ query: Object }>} Updated query.
*/
export const updateQuery = ( id, queryId, data ) =>
request( buildPath( `/brands/${ id }/queries/${ queryId }` ), { method: 'PUT', data } )
/**
* POST /brands/{id}/generate-queries — regenerate baseline queries.
*
* @param {string} id Brand UUID.
* @return {Promise<{ queries: Array }>} New query list (same shape as GET /queries).
*/
export const generateQueries = ( id ) =>
request( buildPath( `/brands/${ id }/generate-queries` ), { method: 'POST' } )

Some files were not shown because too many files have changed in this diff Show More