Actualizacion 7.1.2
This commit is contained in:
+1
-1
File diff suppressed because one or more lines are too long
+10
-10
@@ -7,7 +7,7 @@
|
||||
/**
|
||||
* WordPress dependencies
|
||||
*/
|
||||
import { useMemo, useState, useEffect } from '@wordpress/element'
|
||||
import { useMemo, useState, useEffect, useRef } from '@wordpress/element'
|
||||
import { __ } from '@wordpress/i18n'
|
||||
import { SelectControl, SearchControl, Button } from '@wordpress/components'
|
||||
|
||||
@@ -43,28 +43,31 @@ const AnalysesFilterBar = ( {
|
||||
} ) => {
|
||||
const ns = 'rank-math-ai-visibility-analyses-filter-bar'
|
||||
|
||||
// Prepend "All Brands" option to the brand list.
|
||||
const brandSelectOptions = useMemo( () => [
|
||||
{ label: __( 'All Brands', 'seo-by-rank-math' ), value: '' },
|
||||
...brandOptions,
|
||||
], [ brandOptions ] )
|
||||
|
||||
// The hook stores brandIds as an array. For the single-select UI we store
|
||||
// the first item (or '') and convert back on change.
|
||||
// brandIds is an array; the single-select UI only needs the first item.
|
||||
const activeBrandId = ( filters.brandIds && filters.brandIds[ 0 ] )
|
||||
? String( filters.brandIds[ 0 ] )
|
||||
: ''
|
||||
|
||||
// Local search state — debounced 300 ms before propagating to the hook.
|
||||
// This prevents a new API request on every keystroke.
|
||||
const [ localSearch, setLocalSearch ] = useState( filters.search || '' )
|
||||
const isFirstSearchRender = useRef( true )
|
||||
|
||||
// Sync local state if the parent resets filters externally (e.g. "clear all").
|
||||
// Sync when the parent resets filters externally (e.g. "clear all").
|
||||
useEffect( () => {
|
||||
setLocalSearch( filters.search || '' )
|
||||
}, [ filters.search ] )
|
||||
|
||||
// Skip on mount — avoids a no-op filter change resetting pagination.
|
||||
useEffect( () => {
|
||||
if ( isFirstSearchRender.current ) {
|
||||
isFirstSearchRender.current = false
|
||||
return
|
||||
}
|
||||
|
||||
const timer = setTimeout( () => {
|
||||
onFilterChange( { search: localSearch } )
|
||||
}, 300 )
|
||||
@@ -82,7 +85,6 @@ const AnalysesFilterBar = ( {
|
||||
return (
|
||||
<div className={ ns }>
|
||||
|
||||
{ /* Brand — standard SelectControl, matches Status style */ }
|
||||
<SelectControl
|
||||
className={ `${ ns }__brand` }
|
||||
value={ activeBrandId }
|
||||
@@ -102,7 +104,6 @@ const AnalysesFilterBar = ( {
|
||||
__nextHasNoMarginBottom={ true }
|
||||
/>
|
||||
|
||||
{ /* Search — value bound to local state; propagation is debounced 300 ms */ }
|
||||
<SearchControl
|
||||
className={ `${ ns }__search` }
|
||||
placeholder={ __( 'Search', 'seo-by-rank-math' ) }
|
||||
@@ -123,7 +124,6 @@ const AnalysesFilterBar = ( {
|
||||
</Button>
|
||||
) }
|
||||
|
||||
{ /* Date range: [📅 From] - [📅 To] */ }
|
||||
<div className={ `${ ns }__dates` }>
|
||||
<div className={ `${ ns }__date-wrap` }>
|
||||
<DateInput
|
||||
|
||||
+27
-15
@@ -26,20 +26,28 @@ import './AnalysisRunDetail.scss'
|
||||
/**
|
||||
* Map an insights query result to the shape TranscriptModal expects.
|
||||
*
|
||||
* The id is qualified by platform — the backend reuses the same query_id
|
||||
* across platforms, so an unqualified id would collide.
|
||||
*
|
||||
* @param {Object} result Query result from the insights payload.
|
||||
* @param {number} index Fallback index.
|
||||
* @param {Object} analysis Parent analysis meta.
|
||||
* @param {Object} analysis Analysis run (matched by platform) this result belongs to.
|
||||
* @return {Object} Normalised entry.
|
||||
*/
|
||||
const normalise = ( result, index, analysis ) => ( {
|
||||
...result,
|
||||
id: result.query_id ?? index,
|
||||
query: result.query_text ?? '',
|
||||
response: result.response ?? '',
|
||||
created_at: analysis?.finished_at ?? null,
|
||||
duration_seconds: analysis?.duration_seconds ?? null,
|
||||
model: null,
|
||||
} )
|
||||
const normalise = ( result, index, analysis ) => {
|
||||
const baseId = result.query_id ?? index
|
||||
const platform = result.platform ?? 'default'
|
||||
|
||||
return {
|
||||
...result,
|
||||
id: `${ baseId }-${ platform }`,
|
||||
query: result.query_text ?? '',
|
||||
response: result.response ?? '',
|
||||
created_at: analysis?.finished_at ?? null,
|
||||
duration_seconds: analysis?.duration_seconds ?? null,
|
||||
model: null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* AnalysisRunDetail component.
|
||||
@@ -60,10 +68,14 @@ const AnalysisRunDetail = ( { row, onBack } ) => {
|
||||
const insights = insightsData?.insights ?? null
|
||||
const [ modalEntry, setModalEntry ] = useState( null )
|
||||
|
||||
const transcripts = ( insights?.query_results ?? [] ).map( ( result, i ) => normalise( result, i, insights?.analysis ) )
|
||||
const totalDuration = insights?.analysis?.duration_seconds ?? 0
|
||||
const analyses = insights?.analyses ?? []
|
||||
const findAnalysis = ( platform ) => analyses.find( ( analysis ) => analysis.platform === platform ) ?? analyses[ 0 ] ?? null
|
||||
|
||||
const transcripts = ( insights?.query_results ?? [] ).map( ( result, i ) => normalise( result, i, findAnalysis( result.platform ) ) )
|
||||
const totalDuration = analyses.reduce( ( sum, analysis ) => sum + ( analysis.duration_seconds ?? 0 ), 0 )
|
||||
const durationLabel = totalDuration ? `${ totalDuration }s` : '—'
|
||||
const startedAt = row?.started_at ?? insights?.analysis?.started_at
|
||||
const startedAts = analyses.map( ( analysis ) => analysis.started_at ).filter( Boolean ).sort()
|
||||
const startedAt = row?.started_at ?? startedAts[ 0 ]
|
||||
|
||||
const handleExportReport = () => navigateToReportsTab( row.id )
|
||||
|
||||
@@ -94,7 +106,7 @@ const AnalysisRunDetail = ( { row, onBack } ) => {
|
||||
value={ row?.brand_name || '—' }
|
||||
className="rank-math-ai-visibility-stat-card--target-brand"
|
||||
tooltip={ __( 'The brand this analysis run is for.', 'seo-by-rank-math' ) }
|
||||
analysis={ insights?.analysis }
|
||||
analysis={ analyses[ 0 ] ?? null }
|
||||
/>
|
||||
|
||||
<StatCard
|
||||
@@ -105,7 +117,7 @@ const AnalysisRunDetail = ( { row, onBack } ) => {
|
||||
sub={ formatShortDate( startedAt ) }
|
||||
className="rank-math-ai-visibility-stat-card--duration-timing"
|
||||
tooltip={ __( 'Total duration of all queries in this run, and the date it was started.', 'seo-by-rank-math' ) }
|
||||
analysis={ insights?.analysis }
|
||||
analysis={ analyses[ 0 ] ?? null }
|
||||
/>
|
||||
|
||||
</div>
|
||||
|
||||
+14
-25
@@ -20,6 +20,7 @@ import { addQueryArgs } from '@wordpress/url'
|
||||
* Internal dependencies
|
||||
*/
|
||||
import useDashboard from '../shared/hooks/useDashboard'
|
||||
import usePagination from '../shared/hooks/usePagination'
|
||||
import { getAnalysisState } from '../utils/analysisState'
|
||||
import { SectionHeader } from '../shared/components'
|
||||
import AnalysesFilterBar from './AnalysesFilterBar'
|
||||
@@ -36,20 +37,15 @@ const DEFAULT_FILTERS = {
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync filters + pagination into the URL without reloading.
|
||||
*
|
||||
* @param {Object} filters Active filter bag.
|
||||
* @param {Object} pagination Active pagination.
|
||||
* @param {Object} filters Active filter bag.
|
||||
*/
|
||||
const writeToUrl = ( filters, pagination ) => {
|
||||
const writeFiltersToUrl = ( filters ) => {
|
||||
const params = {
|
||||
aiv_brands: filters.brandIds.length ? filters.brandIds.join( ',' ) : undefined,
|
||||
aiv_status: filters.status || undefined,
|
||||
aiv_search: filters.search || undefined,
|
||||
aiv_from: filters.dateFrom || undefined,
|
||||
aiv_to: filters.dateTo || undefined,
|
||||
aiv_page: pagination.page > 1 ? pagination.page : undefined,
|
||||
aiv_per: pagination.perPage !== 10 ? pagination.perPage : undefined,
|
||||
}
|
||||
|
||||
const url = addQueryArgs( window.location.href, params )
|
||||
@@ -70,8 +66,7 @@ const toRunRow = ( brand ) => {
|
||||
brand_id: brand.id,
|
||||
brand_name: brand.name,
|
||||
started_at: brand.last_analyzed,
|
||||
// Display/filter bucket: running | error | done | none. Same icon
|
||||
// derivation as the Dashboard column, so the two tabs never disagree.
|
||||
// Matches the Dashboard column's derivation, so both tabs agree.
|
||||
status: state ?? ( brand.last_analyzed ? 'done' : 'none' ),
|
||||
}
|
||||
}
|
||||
@@ -85,7 +80,6 @@ const Analyses = () => {
|
||||
const { brands, loading, error } = useDashboard()
|
||||
|
||||
const [ filters, setFilters ] = useState( DEFAULT_FILTERS )
|
||||
const [ pagination, setPagination ] = useState( { page: 1, perPage: 10 } )
|
||||
const [ selectedRow, setSelectedRow ] = useState( null )
|
||||
|
||||
const brandOptions = useMemo(
|
||||
@@ -93,7 +87,6 @@ const Analyses = () => {
|
||||
[ brands ]
|
||||
)
|
||||
|
||||
// Derive + filter rows client-side.
|
||||
const filteredItems = useMemo( () => {
|
||||
return brands.map( toRunRow ).filter( ( item ) => {
|
||||
if ( filters.search && ! item.brand_name.toLowerCase().includes( filters.search.toLowerCase() ) ) {
|
||||
@@ -118,26 +111,22 @@ const Analyses = () => {
|
||||
} )
|
||||
}, [ brands, filters ] )
|
||||
|
||||
const total = filteredItems.length
|
||||
const pages = Math.max( 1, Math.ceil( total / pagination.perPage ) )
|
||||
const pageItems = useMemo( () => {
|
||||
const offset = ( pagination.page - 1 ) * pagination.perPage
|
||||
return filteredItems.slice( offset, offset + pagination.perPage )
|
||||
}, [ filteredItems, pagination ] )
|
||||
const { pagination, pageItems, total, pages, onPageChange, onPerPageChange, resetPage } =
|
||||
usePagination( filteredItems, { perPage: 10, syncUrl: true } )
|
||||
|
||||
const handleFilterChange = useCallback( ( patch ) => {
|
||||
setFilters( ( prev ) => ( { ...prev, ...patch } ) )
|
||||
setPagination( ( prev ) => ( { ...prev, page: 1 } ) )
|
||||
}, [] )
|
||||
resetPage()
|
||||
}, [ resetPage ] )
|
||||
|
||||
const handleClearFilters = useCallback( () => {
|
||||
setFilters( DEFAULT_FILTERS )
|
||||
setPagination( ( prev ) => ( { ...prev, page: 1 } ) )
|
||||
}, [] )
|
||||
resetPage()
|
||||
}, [ resetPage ] )
|
||||
|
||||
useEffect( () => {
|
||||
writeToUrl( filters, pagination )
|
||||
}, [ filters, pagination ] )
|
||||
writeFiltersToUrl( filters )
|
||||
}, [ filters ] )
|
||||
|
||||
if ( selectedRow ) {
|
||||
return (
|
||||
@@ -177,8 +166,8 @@ const Analyses = () => {
|
||||
loading={ loading }
|
||||
pagination={ { ...pagination, total, pages } }
|
||||
onViewDetail={ ( row ) => setSelectedRow( row ) }
|
||||
onPageChange={ ( page ) => setPagination( ( prev ) => ( { ...prev, page: Math.max( 1, page ) } ) ) }
|
||||
onPerPageChange={ ( perPage ) => setPagination( { page: 1, perPage: Math.max( 1, perPage ) } ) }
|
||||
onPageChange={ onPageChange }
|
||||
onPerPageChange={ onPerPageChange }
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
+2
-2
@@ -76,7 +76,7 @@ const App = ( { config = {} } ) => {
|
||||
setActiveTab( tabName )
|
||||
}
|
||||
|
||||
const { isSiteConnected, isPro, plan, locales = [] } = rankMath.aiVisibility
|
||||
const { isSiteConnected, isPro, plan, locales = [], languages = [], defaultLanguage = '', intervals = [], platforms = {}, maxPlatforms = 1 } = rankMath.aiVisibility
|
||||
|
||||
// Access gate — Free Content AI plan: PRO users get the trial flow,
|
||||
// free plugin users get the upgrade modal.
|
||||
@@ -100,7 +100,7 @@ const App = ( { config = {} } ) => {
|
||||
<div className={ 'rank-math-ai-visibility__tab rank-math-ai-visibility__tab--' + tab.name }>
|
||||
{ ! isSiteConnected && <Connect config={ config } /> }
|
||||
{ isSiteConnected && (
|
||||
isPlanGated ? <GatedPreview /> : createElement( tab.view, { locales, onBrandCreated: showSnackbar } )
|
||||
isPlanGated ? <GatedPreview /> : createElement( tab.view, { locales, languages, defaultLanguage, intervals, platforms, maxPlatforms, onBrandCreated: showSnackbar } )
|
||||
) }
|
||||
</div>
|
||||
) }
|
||||
|
||||
+5
@@ -72,6 +72,11 @@ const BrandHeader = ( {
|
||||
{ brand.url }
|
||||
</a>
|
||||
{ brand.locale && <CountryFlag locale={ brand.locale } /> }
|
||||
{ brand.language && (
|
||||
<span className={ `${ ns }__language` }>
|
||||
{ brand.language }
|
||||
</span>
|
||||
) }
|
||||
<a
|
||||
className={ `${ ns }__external` }
|
||||
href={ getBrandUrl( brand.url ) }
|
||||
|
||||
+10
@@ -81,6 +81,16 @@
|
||||
}
|
||||
}
|
||||
|
||||
&__language {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 2px 8px;
|
||||
border-radius: 20px;
|
||||
font-size: 11px;
|
||||
color: $color-text-muted;
|
||||
border: 1px solid $color-border;
|
||||
}
|
||||
|
||||
&__external {
|
||||
color: #757575;
|
||||
display: inline-flex;
|
||||
|
||||
+3
-3
@@ -50,7 +50,7 @@ const BrandOverview = ( { brand, insights = null, loading = false } ) => {
|
||||
: placeholder
|
||||
}
|
||||
tooltip={ __( 'AI Visibility Score for this brand across AI platforms.', 'seo-by-rank-math' ) }
|
||||
analysis={ insights?.analysis }
|
||||
analysis={ insights?.analyses?.[ 0 ] }
|
||||
/>
|
||||
|
||||
<StatCard
|
||||
@@ -71,7 +71,7 @@ const BrandOverview = ( { brand, insights = null, loading = false } ) => {
|
||||
: placeholder
|
||||
}
|
||||
tooltip={ __( 'Average sentiment score across all AI mentions of this brand.', 'seo-by-rank-math' ) }
|
||||
analysis={ insights?.analysis }
|
||||
analysis={ insights?.analyses?.[ 0 ] }
|
||||
/>
|
||||
|
||||
<StatCard
|
||||
@@ -98,7 +98,7 @@ const BrandOverview = ( { brand, insights = null, loading = false } ) => {
|
||||
label={ __( 'Top Competitor', 'seo-by-rank-math' ) }
|
||||
value={ topCompetitor || placeholder }
|
||||
tooltip={ __( 'The competitor brand with the highest share of voice in AI mentions.', 'seo-by-rank-math' ) }
|
||||
analysis={ insights?.analysis }
|
||||
analysis={ insights?.analyses?.[ 0 ] }
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
+25
-12
@@ -20,21 +20,29 @@ import './RunDetail.scss'
|
||||
/**
|
||||
* Map an insights query result to the shape TranscriptViewer expects.
|
||||
*
|
||||
* The id is qualified by platform — the backend reuses the same query_id
|
||||
* across platforms, so an unqualified id would collide.
|
||||
*
|
||||
* @param {Object} result Query result from the insights payload.
|
||||
* @param {number} index Fallback index.
|
||||
* @param {Object} analysis Parent analysis meta.
|
||||
* @param {Object} analysis Analysis run (matched by platform) this result belongs to.
|
||||
* @return {Object} Normalised entry.
|
||||
*/
|
||||
const toEntry = ( result, index, analysis ) => ( {
|
||||
...result,
|
||||
id: result.query_id ?? index,
|
||||
query: result.query_text ?? '',
|
||||
response: result.response ?? '',
|
||||
created_at: analysis?.finished_at ?? null,
|
||||
duration_seconds: analysis?.duration_seconds ?? null,
|
||||
status: result.found ? 'success' : 'partial',
|
||||
model: null,
|
||||
} )
|
||||
const toEntry = ( result, index, analysis ) => {
|
||||
const baseId = result.query_id ?? index
|
||||
const platform = result.platform ?? 'default'
|
||||
|
||||
return {
|
||||
...result,
|
||||
id: `${ baseId }-${ platform }`,
|
||||
query: result.query_text ?? '',
|
||||
response: result.response ?? '',
|
||||
created_at: analysis?.finished_at ?? null,
|
||||
duration_seconds: analysis?.duration_seconds ?? null,
|
||||
status: result.found ? 'success' : 'partial',
|
||||
model: null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} props
|
||||
@@ -44,7 +52,12 @@ const toEntry = ( result, index, analysis ) => ( {
|
||||
*/
|
||||
const RunDetail = ( { insights = null, loading = false } ) => {
|
||||
const entries = useMemo(
|
||||
() => ( insights?.query_results ?? [] ).map( ( result, i ) => toEntry( result, i, insights?.analysis ) ),
|
||||
() => {
|
||||
const analyses = insights?.analyses ?? []
|
||||
const findAnalysis = ( platform ) => analyses.find( ( analysis ) => analysis.platform === platform ) ?? analyses[ 0 ] ?? null
|
||||
|
||||
return ( insights?.query_results ?? [] ).map( ( result, i ) => toEntry( result, i, findAnalysis( result.platform ) ) )
|
||||
},
|
||||
[ insights ]
|
||||
)
|
||||
|
||||
|
||||
+11
-1
@@ -55,9 +55,14 @@ const SUB_TABS = [
|
||||
* @param {number} props.brandId
|
||||
* @param {Function} [props.onBack]
|
||||
* @param {Array} [props.locales]
|
||||
* @param {Array} [props.languages]
|
||||
* @param {string} [props.defaultLanguage] Default language for new brands (site language).
|
||||
* @param {Array} [props.intervals]
|
||||
* @param {Object} [props.platforms] AI platform registry from PHP.
|
||||
* @param {number} [props.maxPlatforms] Platforms selectable on the current plan.
|
||||
* @return {JSX.Element} Rendered component.
|
||||
*/
|
||||
const BrandDetail = ( { brandId, onBack, locales = [] } ) => {
|
||||
const BrandDetail = ( { brandId, onBack, locales = [], languages = [], defaultLanguage = '', intervals = [], platforms = {}, maxPlatforms = 1 } ) => {
|
||||
const handleBack = onBack || navigateBackToDashboard
|
||||
const { data: brandData, loading, error, setData: setBrandData } = useFetch(
|
||||
() => getBrand( brandId ),
|
||||
@@ -165,6 +170,11 @@ const BrandDetail = ( { brandId, onBack, locales = [] } ) => {
|
||||
isSaving={ isSaving }
|
||||
apiError={ saveError }
|
||||
locales={ locales }
|
||||
languages={ languages }
|
||||
defaultLanguage={ defaultLanguage }
|
||||
intervals={ intervals }
|
||||
platforms={ platforms }
|
||||
maxPlatforms={ maxPlatforms }
|
||||
/>
|
||||
) }
|
||||
|
||||
|
||||
+1
-1
@@ -52,7 +52,7 @@ const GatedPreview = () => {
|
||||
<StatCard
|
||||
className="rank-math-ai-visibility-stat-card--analyses"
|
||||
icon={ trendingUp }
|
||||
label={ __( 'Analyses in last 24h', 'seo-by-rank-math' ) }
|
||||
label={ __( 'Analyses in the last 7 days', 'seo-by-rank-math' ) }
|
||||
value={ 0 }
|
||||
/>
|
||||
<StatCard
|
||||
|
||||
+36
-15
@@ -21,6 +21,7 @@ import { trendingUp, store } from '@wordpress/icons'
|
||||
* Internal dependencies
|
||||
*/
|
||||
import useDashboard from '../shared/hooks/useDashboard'
|
||||
import usePagination from '../shared/hooks/usePagination'
|
||||
import { getBrand } from '../shared/services/api/aiVisibilityApi'
|
||||
import { StatCard, EmptyState } from '../shared/components'
|
||||
import { ConfirmModal, AddBrandModal, UpgradePlanModal } from '../shared/Modals'
|
||||
@@ -67,11 +68,11 @@ const getConfirmMessage = ( confirmBrand, confirmAction ) => {
|
||||
/**
|
||||
* Resolve the display value for a summary StatCard.
|
||||
*
|
||||
* @param {Object} options
|
||||
* @param {boolean} options.loading Whether the dashboard is still loading.
|
||||
* @param {boolean} options.hasBrands Whether any brands are tracked.
|
||||
* @param {*} options.raw Raw summary value (may be null/undefined).
|
||||
* @param {Function} [options.format] Optional formatter for a present value.
|
||||
* @param {Object} options
|
||||
* @param {boolean} options.loading Whether the dashboard is still loading.
|
||||
* @param {boolean} options.hasBrands Whether any brands are tracked.
|
||||
* @param {*} options.raw Raw summary value (may be null/undefined).
|
||||
* @param {Function} [options.format] Optional formatter for a present value.
|
||||
* @return {string|number|null} Placeholder, null (empty), 0 (missing) or formatted value.
|
||||
*/
|
||||
const getStatValue = ( { loading, hasBrands, raw, format } ) => {
|
||||
@@ -89,11 +90,16 @@ const getStatValue = ( { loading, hasBrands, raw, format } ) => {
|
||||
|
||||
/**
|
||||
* @param {Object} props
|
||||
* @param {Array} [props.locales] Locale options for the brand modals.
|
||||
* @param {Function} [props.onBrandCreated] Callback when a new brand is successfully created.
|
||||
* @param {Array} [props.locales] Locale options for the brand modals.
|
||||
* @param {Array} [props.languages] Output language options for the brand modals.
|
||||
* @param {string} [props.defaultLanguage] Default language for new brands (site language).
|
||||
* @param {Object} [props.platforms] AI platform registry from PHP.
|
||||
* @param {number} [props.maxPlatforms] Platforms selectable on the current plan.
|
||||
* @param {Function} [props.onBrandCreated] Callback when a new brand is successfully created.
|
||||
* @param {Array} [props.intervals] Interval options for the brand modals.
|
||||
* @return {JSX.Element} Rendered component.
|
||||
*/
|
||||
const Dashboard = ( { locales = [], onBrandCreated = () => {} } ) => {
|
||||
const Dashboard = ( { locales = [], languages = [], defaultLanguage = '', platforms = {}, maxPlatforms = 1, onBrandCreated = () => {}, intervals = [] } ) => {
|
||||
const [ activeBrandId, setActiveBrandId ] = useState( getActiveBrandId )
|
||||
|
||||
useEffect( () => {
|
||||
@@ -114,13 +120,11 @@ const Dashboard = ( { locales = [], onBrandCreated = () => {} } ) => {
|
||||
handleEnableBrand,
|
||||
} = useDashboard()
|
||||
|
||||
// Modal state
|
||||
const [ isAddModalOpen, setAddModalOpen ] = useState( false )
|
||||
const [ editBrand, setEditBrand ] = useState( null )
|
||||
const [ isSaving, setIsSaving ] = useState( false )
|
||||
const [ saveError, setSaveError ] = useState( null )
|
||||
|
||||
// ConfirmModal state
|
||||
const [ confirmBrand, setConfirmBrand ] = useState( null )
|
||||
const [ confirmAction, setConfirmAction ] = useState( 'delete' )
|
||||
const [ isProcessing, setIsProcessing ] = useState( false )
|
||||
@@ -128,10 +132,13 @@ const Dashboard = ( { locales = [], onBrandCreated = () => {} } ) => {
|
||||
|
||||
const [ isUpgradeModalOpen, setUpgradeModalOpen ] = useState( false )
|
||||
|
||||
// Search: debounced 300 ms, proxy filters cached rows server-side.
|
||||
// Search is debounced 300ms.
|
||||
const [ searchQuery, setSearchQuery ] = useState( '' )
|
||||
const isFirstSearchRender = useRef( true )
|
||||
|
||||
const { pagination, pageItems, total, pages, onPageChange, onPerPageChange, resetPage } =
|
||||
usePagination( brands, { perPage: 10, syncUrl: true } )
|
||||
|
||||
useEffect( () => {
|
||||
if ( isFirstSearchRender.current ) {
|
||||
isFirstSearchRender.current = false
|
||||
@@ -140,9 +147,10 @@ const Dashboard = ( { locales = [], onBrandCreated = () => {} } ) => {
|
||||
|
||||
const timer = setTimeout( () => {
|
||||
handleSearch( searchQuery.trim() )
|
||||
resetPage()
|
||||
}, 300 )
|
||||
return () => clearTimeout( timer )
|
||||
}, [ searchQuery, handleSearch ] )
|
||||
}, [ searchQuery, handleSearch, resetPage ] )
|
||||
|
||||
const hasActiveSearch = !! searchQuery.trim()
|
||||
const isEmpty = ! loading && brands.length === 0 && ! hasActiveSearch
|
||||
@@ -234,6 +242,11 @@ const Dashboard = ( { locales = [], onBrandCreated = () => {} } ) => {
|
||||
brandId={ activeBrandId }
|
||||
onBack={ handleBackToDashboard }
|
||||
locales={ locales }
|
||||
languages={ languages }
|
||||
defaultLanguage={ defaultLanguage }
|
||||
intervals={ intervals }
|
||||
platforms={ platforms }
|
||||
maxPlatforms={ maxPlatforms }
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -260,8 +273,8 @@ const Dashboard = ( { locales = [], onBrandCreated = () => {} } ) => {
|
||||
<StatCard
|
||||
className="rank-math-ai-visibility-stat-card--analyses"
|
||||
icon={ trendingUp }
|
||||
label={ __( 'Analyses in last 24h', 'seo-by-rank-math' ) }
|
||||
value={ getStatValue( { loading, hasBrands: brands.length > 0, raw: summary?.analyses_last_24h } ) }
|
||||
label={ __( 'Analyses in the last 7 days', 'seo-by-rank-math' ) }
|
||||
value={ getStatValue( { loading, hasBrands: brands.length > 0, raw: summary?.analyses_last_7d } ) }
|
||||
tooltip={ __( 'Total analysis runs completed in the past 24 hours.', 'seo-by-rank-math' ) }
|
||||
/>
|
||||
<StatCard
|
||||
@@ -297,8 +310,9 @@ const Dashboard = ( { locales = [], onBrandCreated = () => {} } ) => {
|
||||
/>
|
||||
|
||||
<BrandsTable
|
||||
brands={ brands }
|
||||
brands={ pageItems }
|
||||
loading={ loading }
|
||||
pagination={ { ...pagination, total, pages } }
|
||||
onView={ handleViewBrand }
|
||||
onEdit={ async ( brand ) => {
|
||||
setEditBrand( brand )
|
||||
@@ -313,6 +327,8 @@ const Dashboard = ( { locales = [], onBrandCreated = () => {} } ) => {
|
||||
}
|
||||
} }
|
||||
onDisable={ ( brand ) => openDisableConfirm( brand ) }
|
||||
onPageChange={ onPageChange }
|
||||
onPerPageChange={ onPerPageChange }
|
||||
/>
|
||||
</div>
|
||||
) }
|
||||
@@ -325,6 +341,11 @@ const Dashboard = ( { locales = [], onBrandCreated = () => {} } ) => {
|
||||
isSaving={ isSaving }
|
||||
apiError={ saveError }
|
||||
locales={ locales }
|
||||
languages={ languages }
|
||||
defaultLanguage={ defaultLanguage }
|
||||
intervals={ intervals }
|
||||
platforms={ platforms }
|
||||
maxPlatforms={ maxPlatforms }
|
||||
/>
|
||||
) }
|
||||
|
||||
|
||||
+4
@@ -136,7 +136,11 @@ const Reports = () => {
|
||||
rows[ 0 ].competitors = ( data?.insights?.competitors ?? [] ).map( ( c ) => c.name )
|
||||
rows[ 0 ].queries = ( data?.insights?.query_results ?? [] ).map( ( q ) => ( {
|
||||
query: q.query_text ?? '',
|
||||
platform: q.platform ?? null,
|
||||
response: q.response ?? '',
|
||||
found: q.found ?? null,
|
||||
sentiment_score: q.sentiment ?? null,
|
||||
citations_count: q.citations ?? null,
|
||||
} ) )
|
||||
} catch {
|
||||
// Competitors and queries are nice-to-have in the report — ignore.
|
||||
|
||||
+120
-77
@@ -7,7 +7,7 @@
|
||||
/**
|
||||
* WordPress dependencies
|
||||
*/
|
||||
import { __ } from '@wordpress/i18n'
|
||||
import { __, _n, sprintf } from '@wordpress/i18n'
|
||||
import { useState, useEffect, useMemo, useRef } from '@wordpress/element'
|
||||
import { Modal, TextControl, TextareaControl, SelectControl, CheckboxControl, Icon } from '@wordpress/components'
|
||||
import { close } from '@wordpress/icons'
|
||||
@@ -19,54 +19,31 @@ import { SelectWithSearch } from '@rank-math/components'
|
||||
import Button from '../components/Button'
|
||||
import LoadingButton from '../components/LoadingButton'
|
||||
import getLink from '@helpers/getLink'
|
||||
import { toPlatformList, getDefaultPlatforms, getEnabledPlatformIds } from '../services/platforms'
|
||||
import './AddBrandModal.scss'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Constants
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const EMPTY_FORM = {
|
||||
/**
|
||||
* Blank form state.
|
||||
*
|
||||
* @param {Array} platformList Available platforms.
|
||||
* @param {string} [defaultLanguage=''] Default language for a new brand (site language).
|
||||
* @return {Object} Empty form values.
|
||||
*/
|
||||
const emptyForm = ( platformList, defaultLanguage = '' ) => ( {
|
||||
name: '',
|
||||
url: '',
|
||||
description: '',
|
||||
locale: '',
|
||||
interval: 'weekly',
|
||||
platforms: [ 'chatgpt' ],
|
||||
}
|
||||
language: defaultLanguage,
|
||||
interval: 'monthly',
|
||||
platforms: getDefaultPlatforms( platformList ),
|
||||
} )
|
||||
|
||||
/**
|
||||
* Order in which fields are validated / scrolled to.
|
||||
* Used to focus the first errored field on a failed save.
|
||||
*/
|
||||
const FIELD_ORDER = [ 'name', 'url', 'description' ]
|
||||
|
||||
/**
|
||||
* Analysis interval options.
|
||||
*/
|
||||
const INTERVAL_OPTIONS = [
|
||||
{ label: __( 'Weekly', 'seo-by-rank-math' ), value: 'weekly', disabled: false },
|
||||
{ label: __( 'Monthly (Coming Soon)', 'seo-by-rank-math' ), value: 'monthly', disabled: true },
|
||||
{ label: __( 'Daily (Coming Soon)', 'seo-by-rank-math' ), value: 'daily', disabled: true },
|
||||
]
|
||||
|
||||
/**
|
||||
* AI Platform definitions.
|
||||
*
|
||||
* `enabled` — whether the platform is available for selection.
|
||||
* Disabled platforms show a "Coming Soon" badge.
|
||||
*
|
||||
* Layout: left column = index 0–2, right column = index 3–4.
|
||||
*/
|
||||
const AI_PLATFORMS = [
|
||||
{ id: 'chatgpt', label: 'ChatGPT', enabled: true },
|
||||
{ id: 'perplexity', label: 'Perplexity', enabled: false },
|
||||
{ id: 'google_ai_overview', label: 'Google AI Overview', enabled: false },
|
||||
{ id: 'gemini', label: 'Gemini', enabled: false },
|
||||
{ id: 'claude', label: 'Claude', enabled: false },
|
||||
]
|
||||
|
||||
const LEFT_PLATFORMS = AI_PLATFORMS.slice( 0, 3 )
|
||||
const RIGHT_PLATFORMS = AI_PLATFORMS.slice( 3 )
|
||||
const FIELD_ORDER = [ 'name', 'url', 'description', 'language' ]
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Sub-components
|
||||
@@ -114,12 +91,17 @@ const PlatformRow = ( { platform, checked, onChange, disabled } ) => {
|
||||
* AddBrandModal component.
|
||||
*
|
||||
* @param {Object} props
|
||||
* @param {Object|null} [props.brand=null] null = add mode, object = edit (pre-fills form).
|
||||
* @param {Function} props.onSave Called with the validated form payload.
|
||||
* @param {Function} props.onClose Called when the modal should close.
|
||||
* @param {boolean} [props.isSaving=false] Shows spinner + disables all fields.
|
||||
* @param {string | null} props.apiError API error message to display.
|
||||
* @param {Array} [props.locales=[]] Locale options injected from PHP via wp_localize_script.
|
||||
* @param {Object|null} [props.brand=null] null = add mode, object = edit (pre-fills form).
|
||||
* @param {Function} props.onSave Called with the validated form payload.
|
||||
* @param {Function} props.onClose Called when the modal should close.
|
||||
* @param {boolean} [props.isSaving=false] Shows spinner + disables all fields.
|
||||
* @param {string | null} props.apiError API error message to display.
|
||||
* @param {Array} [props.locales=[]] Locale options injected from PHP via wp_localize_script.
|
||||
* @param {Array} [props.languages=[]] Output language options injected from PHP via wp_localize_script.
|
||||
* @param {string} [props.defaultLanguage=''] Default language for a new brand (site language), injected from PHP.
|
||||
* @param {Array} [props.intervals=[]] { label, value, disabled } options injected from PHP via wp_localize_script.
|
||||
* @param {Object} [props.platforms={}] AI platform registry injected from PHP.
|
||||
* @param {number} [props.maxPlatforms=1] Platforms selectable on the current plan.
|
||||
* @return {JSX.Element} Brand add/edit dialog.
|
||||
*/
|
||||
const AddBrandModal = ( {
|
||||
@@ -129,8 +111,16 @@ const AddBrandModal = ( {
|
||||
isSaving = false,
|
||||
apiError = null,
|
||||
locales = [],
|
||||
languages = [],
|
||||
defaultLanguage = '',
|
||||
intervals = [],
|
||||
platforms = {},
|
||||
maxPlatforms = 1,
|
||||
} ) => {
|
||||
const [ form, setForm ] = useState( EMPTY_FORM )
|
||||
const platformList = useMemo( () => toPlatformList( platforms ), [ platforms ] )
|
||||
const enabledPlatformCount = useMemo( () => getEnabledPlatformIds( platformList ).length, [ platformList ] )
|
||||
|
||||
const [ form, setForm ] = useState( () => emptyForm( platformList, defaultLanguage ) )
|
||||
const [ errors, setErrors ] = useState( {} )
|
||||
|
||||
const ns = 'rank-math-ai-visibility-add-brand-modal'
|
||||
@@ -140,6 +130,7 @@ const AddBrandModal = ( {
|
||||
name: useRef( null ),
|
||||
url: useRef( null ),
|
||||
description: useRef( null ),
|
||||
language: useRef( null ),
|
||||
}
|
||||
|
||||
// Locale options — object map expected by SelectWithSearch: { value: label, … }
|
||||
@@ -152,6 +143,14 @@ const AddBrandModal = ( {
|
||||
[ locales ]
|
||||
)
|
||||
|
||||
const languageOptions = useMemo(
|
||||
() => languages.reduce( ( acc, { name, icon } ) => {
|
||||
acc[ name ] = icon ? `${ icon } ${ name }` : name
|
||||
return acc
|
||||
}, {} ),
|
||||
[ languages ]
|
||||
)
|
||||
|
||||
// Pre-fill when editing.
|
||||
useEffect( () => {
|
||||
if ( brand ) {
|
||||
@@ -161,12 +160,17 @@ const AddBrandModal = ( {
|
||||
url: brand.url ?? '',
|
||||
description: brand.description ?? '',
|
||||
locale: brand.locale ?? '',
|
||||
interval: brand.interval ?? 'weekly',
|
||||
platforms: brand.platforms ?? [ 'chatgpt' ],
|
||||
// Legacy brands predate the language field.
|
||||
language: brand.language ?? 'US English',
|
||||
interval: brand.interval ?? 'monthly',
|
||||
platforms: brand.platforms?.length
|
||||
? brand.platforms.slice( 0, maxPlatforms )
|
||||
: getDefaultPlatforms( platformList ),
|
||||
} )
|
||||
} else {
|
||||
setForm( EMPTY_FORM )
|
||||
setForm( emptyForm( platformList, defaultLanguage ) )
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [ brand ] )
|
||||
|
||||
// ── Field helpers ────────────────────────────────────────────────────────
|
||||
@@ -184,18 +188,24 @@ const AddBrandModal = ( {
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle a platform ID in the platforms array.
|
||||
* Toggle a platform. Selecting past the plan cap evicts the oldest pick.
|
||||
*
|
||||
* @param {string} id Platform id to toggle.
|
||||
*/
|
||||
const togglePlatform = ( id ) => {
|
||||
setForm( ( prev ) => {
|
||||
const exists = prev.platforms.includes( id )
|
||||
if ( prev.platforms.includes( id ) ) {
|
||||
return {
|
||||
...prev,
|
||||
platforms: prev.platforms.filter( ( p ) => p !== id ),
|
||||
}
|
||||
}
|
||||
|
||||
const next = [ ...prev.platforms, id ]
|
||||
|
||||
return {
|
||||
...prev,
|
||||
platforms: exists
|
||||
? prev.platforms.filter( ( p ) => p !== id )
|
||||
: [ ...prev.platforms, id ],
|
||||
platforms: next.slice( Math.max( 0, next.length - maxPlatforms ) ),
|
||||
}
|
||||
} )
|
||||
}
|
||||
@@ -229,6 +239,9 @@ const AddBrandModal = ( {
|
||||
if ( ! form.description.trim() ) {
|
||||
newErrors.description = __( 'Description is required.', 'seo-by-rank-math' )
|
||||
}
|
||||
if ( ! form.language ) {
|
||||
newErrors.language = __( 'Language is required.', 'seo-by-rank-math' )
|
||||
}
|
||||
|
||||
setErrors( newErrors )
|
||||
return newErrors
|
||||
@@ -266,13 +279,14 @@ const AddBrandModal = ( {
|
||||
url: form.url.trim(),
|
||||
description: form.description.trim(),
|
||||
locale: form.locale,
|
||||
language: form.language,
|
||||
interval: form.interval,
|
||||
platforms: form.platforms,
|
||||
} )
|
||||
}
|
||||
|
||||
const isEditMode = Boolean( brand )
|
||||
const isActionDisabled = isSaving || form?.platforms?.length === 0 || Object.keys( errors ).length > 0
|
||||
const isActionDisabled = isSaving || form?.platforms?.length === 0 || ! form?.language || Object.keys( errors ).length > 0
|
||||
|
||||
return (
|
||||
<Modal
|
||||
@@ -370,12 +384,35 @@ const AddBrandModal = ( {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={ `${ ns }__field` } ref={ fieldRefs.language }>
|
||||
<span className={ `${ ns }__label` }>
|
||||
{ __( 'Output Language', 'seo-by-rank-math' ) }
|
||||
</span>
|
||||
<SelectWithSearch
|
||||
value={ form.language }
|
||||
options={ languageOptions }
|
||||
onChange={ set( 'language' ) }
|
||||
disabled={ isSaving || isEditMode }
|
||||
className={ errors.language ? `${ ns }__field--error` : '' }
|
||||
/>
|
||||
{ errors.language && (
|
||||
<p className={ `${ ns }__field-note ${ ns }__field-note--error` }>
|
||||
{ errors.language }
|
||||
</p>
|
||||
) }
|
||||
{ isEditMode && (
|
||||
<p className={ `${ ns }__field-note` }>
|
||||
{ __( 'Language can\'t be changed after a brand is created.', 'seo-by-rank-math' ) }
|
||||
</p>
|
||||
) }
|
||||
</div>
|
||||
|
||||
{ /* Interval */ }
|
||||
<div className={ `${ ns }__field` }>
|
||||
<SelectControl
|
||||
label={ __( 'Frequency of analyses', 'seo-by-rank-math' ) }
|
||||
value={ form.interval }
|
||||
options={ INTERVAL_OPTIONS }
|
||||
options={ intervals }
|
||||
onChange={ set( 'interval' ) }
|
||||
disabled={ isSaving }
|
||||
__next40pxDefaultSize={ true }
|
||||
@@ -388,29 +425,35 @@ const AddBrandModal = ( {
|
||||
<span className={ `${ ns }__label` }>
|
||||
{ __( 'AI Platforms', 'seo-by-rank-math' ) }
|
||||
</span>
|
||||
{ maxPlatforms < enabledPlatformCount && (
|
||||
<p className={ `${ ns }__field-note` }>
|
||||
{ sprintf(
|
||||
/* translators: %d: number of AI platforms selectable on the current plan. */
|
||||
_n(
|
||||
'Your plan lets you track %d platform per brand. Upgrade to Expert to track them all at once.',
|
||||
'Your plan lets you track %d platforms per brand. Upgrade to Expert to track them all at once.',
|
||||
maxPlatforms,
|
||||
'seo-by-rank-math'
|
||||
),
|
||||
maxPlatforms
|
||||
) }
|
||||
</p>
|
||||
) }
|
||||
{ form.platforms.length === 0 && (
|
||||
<p className={ `${ ns }__field-note ${ ns }__field-note--error` }>
|
||||
{ __( 'Select at least one AI platform.', 'seo-by-rank-math' ) }
|
||||
</p>
|
||||
) }
|
||||
<div className={ `${ ns }__platforms` }>
|
||||
<div className={ `${ ns }__platforms-col` }>
|
||||
{ LEFT_PLATFORMS.map( ( platform ) => (
|
||||
<PlatformRow
|
||||
key={ platform.id }
|
||||
platform={ platform }
|
||||
checked={ form.platforms.includes( platform.id ) }
|
||||
onChange={ () => togglePlatform( platform.id ) }
|
||||
disabled={ isSaving }
|
||||
/>
|
||||
) ) }
|
||||
</div>
|
||||
<div className={ `${ ns }__platforms-col` }>
|
||||
{ RIGHT_PLATFORMS.map( ( platform ) => (
|
||||
<PlatformRow
|
||||
key={ platform.id }
|
||||
platform={ platform }
|
||||
checked={ form.platforms.includes( platform.id ) }
|
||||
onChange={ () => togglePlatform( platform.id ) }
|
||||
disabled={ isSaving }
|
||||
/>
|
||||
) ) }
|
||||
</div>
|
||||
{ platformList.map( ( platform ) => (
|
||||
<PlatformRow
|
||||
key={ platform.id }
|
||||
platform={ platform }
|
||||
checked={ form.platforms.includes( platform.id ) }
|
||||
onChange={ () => togglePlatform( platform.id ) }
|
||||
disabled={ isSaving }
|
||||
/>
|
||||
) ) }
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
+11
-6
@@ -132,6 +132,16 @@
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
&__field-note {
|
||||
margin: 4px 0 0;
|
||||
font-size: 12px;
|
||||
color: $color-text-muted;
|
||||
|
||||
&--error {
|
||||
color: $color-trend-down;
|
||||
}
|
||||
}
|
||||
|
||||
.components-base-control__label,
|
||||
.components-input-control__label {
|
||||
font-size: 11px;
|
||||
@@ -186,16 +196,11 @@
|
||||
&__platforms {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
grid-auto-flow: row;
|
||||
gap: 10px 16px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
&__platforms-col {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
&__platform-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
+1
-1
@@ -34,7 +34,7 @@ import './StatCard.scss'
|
||||
* @return {JSX.Element} Stat card with icon, label, value, and optional trend.
|
||||
*/
|
||||
const StatCard = ( { icon, label, value, tooltip, sub, compact = false, className = '', analysis = null } ) => {
|
||||
const hasData = ( analysis?.status && analysis?.status === 'done' ) ?? ( value !== null && value !== undefined && value !== '' && value !== '—' )
|
||||
const hasData = ( analysis?.status && ( analysis?.status === 'done' || analysis?.status === 'partial' ) ) ?? ( value !== null && value !== undefined && value !== '' && value !== '—' )
|
||||
|
||||
const ns = 'rank-math-ai-visibility-stat-card'
|
||||
|
||||
|
||||
+4
@@ -173,6 +173,10 @@ const TranscriptViewer = ( {
|
||||
if ( e.query ) {
|
||||
label = e.query.length > 60 ? e.query.slice( 0, 60 ) + '…' : e.query
|
||||
}
|
||||
// Append platform — multiple platforms can share the same query text.
|
||||
if ( e.platform ) {
|
||||
label += ` — ${ e.platform }`
|
||||
}
|
||||
return { label, value: String( e.id ) }
|
||||
} ),
|
||||
], [ entries ] )
|
||||
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* usePagination — client-side pagination over an in-memory array.
|
||||
*
|
||||
* @since 1.0.274
|
||||
*/
|
||||
|
||||
/**
|
||||
* WordPress dependencies
|
||||
*/
|
||||
import { useState, useMemo, useCallback, useEffect, useRef } from '@wordpress/element'
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import { getPageFromUrl, getPerPageFromUrl, writePaginationToUrl } from '../../utils/urlState'
|
||||
|
||||
const DEFAULT_PER_PAGE = 10
|
||||
|
||||
/**
|
||||
* @param {Array} items Full, already-filtered item list to paginate.
|
||||
* @param {Object} [options]
|
||||
* @param {number} [options.perPage=10] Default/initial page size.
|
||||
* @param {boolean} [options.syncUrl=false] Read the initial page from the URL and keep it updated.
|
||||
* @return {Object} `{ pagination, pageItems, total, pages, onPageChange, onPerPageChange, resetPage }`
|
||||
*/
|
||||
const usePagination = ( items = [], { perPage = DEFAULT_PER_PAGE, syncUrl = false } = {} ) => {
|
||||
const [ pagination, setPagination ] = useState( () => ( {
|
||||
page: syncUrl ? getPageFromUrl( 1 ) : 1,
|
||||
perPage: syncUrl ? getPerPageFromUrl( perPage ) : perPage,
|
||||
} ) )
|
||||
|
||||
const total = items.length
|
||||
const pages = Math.max( 1, Math.ceil( total / pagination.perPage ) )
|
||||
|
||||
const pageItems = useMemo( () => {
|
||||
const offset = ( pagination.page - 1 ) * pagination.perPage
|
||||
return items.slice( offset, offset + pagination.perPage )
|
||||
}, [ items, pagination ] )
|
||||
|
||||
// Clamp out-of-range pages, but not on mount (would clobber a URL-provided page).
|
||||
const isFirstRun = useRef( true )
|
||||
useEffect( () => {
|
||||
if ( isFirstRun.current ) {
|
||||
isFirstRun.current = false
|
||||
return
|
||||
}
|
||||
setPagination( ( prev ) => ( prev.page > pages ? { ...prev, page: pages } : prev ) )
|
||||
}, [ pages ] )
|
||||
|
||||
useEffect( () => {
|
||||
if ( syncUrl ) {
|
||||
writePaginationToUrl( pagination, perPage )
|
||||
}
|
||||
}, [ pagination, syncUrl, perPage ] )
|
||||
|
||||
const onPageChange = useCallback(
|
||||
( page ) => setPagination( ( prev ) => ( { ...prev, page: Math.max( 1, page ) } ) ),
|
||||
[]
|
||||
)
|
||||
|
||||
const onPerPageChange = useCallback(
|
||||
( newPerPage ) => setPagination( { page: 1, perPage: Math.max( 1, newPerPage ) } ),
|
||||
[]
|
||||
)
|
||||
|
||||
const resetPage = useCallback(
|
||||
() => setPagination( ( prev ) => ( prev.page === 1 ? prev : { ...prev, page: 1 } ) ),
|
||||
[]
|
||||
)
|
||||
|
||||
return { pagination, pageItems, total, pages, onPageChange, onPerPageChange, resetPage }
|
||||
}
|
||||
|
||||
export default usePagination
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* AI platform registry helpers — mirrors `Platforms` in PHP.
|
||||
*
|
||||
* @since 1.0.275
|
||||
*/
|
||||
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { map, filter } from 'lodash'
|
||||
|
||||
/**
|
||||
* Convert the localized registry map into a list, preserving key order.
|
||||
*
|
||||
* @param {Object} platforms Registry keyed by platform ID.
|
||||
* @return {Array<{id: string, label: string, enabled: boolean}>} Platform list.
|
||||
*/
|
||||
export const toPlatformList = ( platforms = {} ) =>
|
||||
map( platforms, ( platform, id ) => ( {
|
||||
id,
|
||||
label: platform?.label ?? id,
|
||||
enabled: Boolean( platform?.enabled ),
|
||||
} ) )
|
||||
|
||||
/**
|
||||
* Platform IDs available for selection.
|
||||
*
|
||||
* @param {Array} platformList Output of toPlatformList().
|
||||
* @return {string[]} Enabled platform IDs.
|
||||
*/
|
||||
export const getEnabledPlatformIds = ( platformList = [] ) =>
|
||||
map( filter( platformList, 'enabled' ), 'id' )
|
||||
|
||||
/**
|
||||
* Default selection for a new brand — the first enabled platform.
|
||||
*
|
||||
* @param {Array} platformList Output of toPlatformList().
|
||||
* @return {string[]} Default platform IDs.
|
||||
*/
|
||||
export const getDefaultPlatforms = ( platformList = [] ) =>
|
||||
getEnabledPlatformIds( platformList ).slice( 0, 1 )
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
* Derive a brand's display analysis state from its `analysis_status`.
|
||||
*
|
||||
* API status semantics:
|
||||
* success → ran successfully (a future weekly run is masked as success)
|
||||
* success → ran successfully (a future monthly run is masked as success)
|
||||
* partial → last run completed partially
|
||||
* pending → awaiting first run, or an overdue run is due
|
||||
* running → a run is currently in progress
|
||||
|
||||
+30
@@ -110,3 +110,33 @@ export const navigateToReportsTab = ( brandId ) => {
|
||||
window.history.pushState( {}, '', url )
|
||||
window.dispatchEvent( new window.PopStateEvent( 'popstate' ) )
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} [fallback=1] Fallback when `aiv_page` is absent/invalid.
|
||||
* @return {number} Page number from the URL.
|
||||
*/
|
||||
export const getPageFromUrl = ( fallback = 1 ) => {
|
||||
const raw = parseInt( getQueryArg( window.location.href, 'aiv_page' ), 10 )
|
||||
return raw > 0 ? raw : fallback
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} [fallback=10] Fallback when `aiv_per` is absent/invalid.
|
||||
* @return {number} Page size from the URL.
|
||||
*/
|
||||
export const getPerPageFromUrl = ( fallback = 10 ) => {
|
||||
const raw = parseInt( getQueryArg( window.location.href, 'aiv_per' ), 10 )
|
||||
return raw > 0 ? raw : fallback
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} pagination `{ page, perPage }`.
|
||||
* @param {number} [defaultPerPage=10] Omitted from the URL when matched.
|
||||
*/
|
||||
export const writePaginationToUrl = ( pagination, defaultPerPage = 10 ) => {
|
||||
const url = addQueryArgs( window.location.href, {
|
||||
aiv_page: pagination.page > 1 ? pagination.page : undefined,
|
||||
aiv_per: pagination.perPage !== defaultPerPage ? pagination.perPage : undefined,
|
||||
} )
|
||||
window.history.replaceState( {}, '', url )
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user