diff --git a/projects/packages/premium-analytics/changelog/add-pa-widget-modules-init b/projects/packages/premium-analytics/changelog/add-pa-widget-modules-init new file mode 100644 index 000000000000..a2c932e04102 --- /dev/null +++ b/projects/packages/premium-analytics/changelog/add-pa-widget-modules-init @@ -0,0 +1,3 @@ +Significance: patch +Type: changed +Comment: Internal refactor: register the dashboard entities in the init module instead of on each route load. No user-facing change. diff --git a/projects/packages/premium-analytics/packages/data/src/api/constants.ts b/projects/packages/premium-analytics/packages/data/src/api/constants.ts index 980ab7a695ae..87af2afe296b 100644 --- a/projects/packages/premium-analytics/packages/data/src/api/constants.ts +++ b/projects/packages/premium-analytics/packages/data/src/api/constants.ts @@ -1 +1,17 @@ export const statsProxyPath = '/jetpack-premium-analytics/v1/proxy'; + +/** + * Identifier of the Premium Analytics dashboard, formatted as + * `_` to mirror the underscore form produced by the + * wp-build pipeline. Used as the `{name}` segment of the default-layout + * REST route. + * + * Must match `DASHBOARD_NAME` in `src/dashboard-layout.php`. + */ +export const DASHBOARD_NAME = 'jetpack-premium-analytics_dashboard'; + +/** + * REST namespace that exposes Premium Analytics dashboard endpoints. + * Must match `DASHBOARD_REST_NAMESPACE` in `src/rest-namespace.php`. + */ +export const DASHBOARD_REST_NAMESPACE = 'wpcom/v2'; diff --git a/projects/packages/premium-analytics/routes/dashboard-entities.test.ts b/projects/packages/premium-analytics/packages/data/src/entities/__tests__/dashboard-entities.test.ts similarity index 97% rename from projects/packages/premium-analytics/routes/dashboard-entities.test.ts rename to projects/packages/premium-analytics/packages/data/src/entities/__tests__/dashboard-entities.test.ts index 751b31045794..88fddbd29e42 100644 --- a/projects/packages/premium-analytics/routes/dashboard-entities.test.ts +++ b/projects/packages/premium-analytics/packages/data/src/entities/__tests__/dashboard-entities.test.ts @@ -1,4 +1,4 @@ -import { ensureDashboardEntities } from './dashboard-entities'; +import { ensureDashboardEntities } from '../dashboard-entities'; const mockGetEntityConfig = jest.fn(); const mockAddEntities = jest.fn(); diff --git a/projects/packages/premium-analytics/routes/dashboard-entities.ts b/projects/packages/premium-analytics/packages/data/src/entities/dashboard-entities.ts similarity index 69% rename from projects/packages/premium-analytics/routes/dashboard-entities.ts rename to projects/packages/premium-analytics/packages/data/src/entities/dashboard-entities.ts index 0befd1b862e5..90bed2ec7154 100644 --- a/projects/packages/premium-analytics/routes/dashboard-entities.ts +++ b/projects/packages/premium-analytics/packages/data/src/entities/dashboard-entities.ts @@ -7,10 +7,10 @@ import { __ } from '@wordpress/i18n'; /** * Internal dependencies */ -import { DASHBOARD_NAME, DASHBOARD_REST_NAMESPACE } from './dashboard/hooks/constants'; +import { DASHBOARD_NAME, DASHBOARD_REST_NAMESPACE } from '../api/constants'; /** - * The core-data entities the analytics routes read dashboard metadata from. + * The core-data entities the analytics dashboard reads its metadata from. */ const DASHBOARD_ENTITY_NAMES = [ 'widgetModule', 'dashboardSection' ] as const; @@ -52,15 +52,9 @@ function buildEntityConfig( name: DashboardEntityName ): object { /** * Register the dashboard core-data entities, skipping any already registered. * - * Routes call this from `beforeLoad`, which re-runs on every navigation and - * preload, so each entity is guarded individually. The helper owns the - * complete entity set on purpose: registration is config-only (no request is - * made until something reads the entity), so registering an entity a route - * never reads costs nothing, while letting callers pick a subset restores the - * route-level invariant that caused the original regression — a detail route - * registering `widgetModule` alone made the dashboard's guard treat the store - * as fully seeded, `dashboardSection` was never registered, and the dashboard - * resolved zero sections and force-opened an empty edit-mode canvas. + * Always registers the complete set: registering a subset seeds the guard, so + * a later caller skips the entities it left out. That is how `dashboardSection` + * went missing once and the dashboard force-opened an empty edit-mode canvas. */ export function ensureDashboardEntities(): void { const coreSelect = select( coreStore ) as unknown as { diff --git a/projects/packages/premium-analytics/packages/data/src/index.ts b/projects/packages/premium-analytics/packages/data/src/index.ts index c4d916d537ba..fbcf6ed767b4 100644 --- a/projects/packages/premium-analytics/packages/data/src/index.ts +++ b/projects/packages/premium-analytics/packages/data/src/index.ts @@ -3,6 +3,7 @@ export { GlobalErrorProvider, useGlobalError } from './providers/global-error-co export { globalErrorManager, type GlobalErrorType } from './providers/global-error-manager'; export { ReportScopeProvider, useReportScope, type ReportScope } from './providers/report-scope'; export * from './hooks'; +export { ensureDashboardEntities } from './entities/dashboard-entities'; export { latestPostQuery, postContentQuery } from './queries/latest-post-query'; export type { LatestPost, LatestPostResponse } from './processing/latest-post'; export { statsInsightsQuery } from './queries/stats-insights-query'; diff --git a/projects/packages/premium-analytics/packages/init/package.json b/projects/packages/premium-analytics/packages/init/package.json index 563095855ba0..e2c3d40033ef 100644 --- a/projects/packages/premium-analytics/packages/init/package.json +++ b/projects/packages/premium-analytics/packages/init/package.json @@ -9,6 +9,7 @@ "dependencies": { "@automattic/jetpack-script-data": "workspace:*", "@automattic/jetpack-wp-build-polyfills": "workspace:*", + "@jetpack-premium-analytics/data": "workspace:*", "@wordpress/api-fetch": "7.54.0", "@wordpress/boot": "0.21.0", "@wordpress/data": "10.54.0", diff --git a/projects/packages/premium-analytics/packages/init/src/index.ts b/projects/packages/premium-analytics/packages/init/src/index.ts index 0b94f1a806d8..0108cf322e07 100644 --- a/projects/packages/premium-analytics/packages/init/src/index.ts +++ b/projects/packages/premium-analytics/packages/init/src/index.ts @@ -3,6 +3,7 @@ */ import { getScriptData } from '@automattic/jetpack-script-data'; import { loadI18nCatalogs } from '@automattic/jetpack-wp-build-polyfills/src/js/load-i18n-catalogs'; +import { ensureDashboardEntities } from '@jetpack-premium-analytics/data'; import apiFetch from '@wordpress/api-fetch'; import { store as bootStore } from '@wordpress/boot'; import { dispatch } from '@wordpress/data'; @@ -58,4 +59,7 @@ export async function init(): Promise< void > { } ); await catalogs; + + // After the catalogs: the entity labels are built with `__()` at call time. + ensureDashboardEntities(); } diff --git a/projects/packages/premium-analytics/routes/dashboard/hooks/constants.ts b/projects/packages/premium-analytics/routes/dashboard/hooks/constants.ts index f6d7f383108e..ce09fd8895ed 100644 --- a/projects/packages/premium-analytics/routes/dashboard/hooks/constants.ts +++ b/projects/packages/premium-analytics/routes/dashboard/hooks/constants.ts @@ -1,20 +1,12 @@ /** - * Identifiers shared by the dashboard hooks and mirrored on the server. + * Preferences identifiers shared by the dashboard hooks and mirrored on the + * server. * - * Centralized so the preferences scope, keys, dashboard name, and REST - * namespace can be renamed in one place — e.g. to fully isolate Premium - * Analytics' stored preferences from the core dashboard's. The values - * here must match the constants in `src/dashboard-layout.php`. + * Centralized so the preferences scope and keys can be renamed in one place — + * e.g. to fully isolate Premium Analytics' stored preferences from the core + * dashboard's. */ -/** - * Identifier of the Premium Analytics dashboard, formatted as - * `_` to mirror the underscore form produced by the - * wp-build pipeline. Used as the `{name}` segment of the default-layout - * REST route. - */ -export const DASHBOARD_NAME = 'jetpack-premium-analytics_dashboard'; - /** * Preferences scope under which the dashboard layout and grid settings * are stored. Mirrors the scope the server-side default injection writes @@ -25,8 +17,5 @@ export const DASHBOARD_PREFERENCES_SCOPE = 'jetpack-premium-analytics/dashboard' /** Preferences key holding the dashboard grid settings. */ export const DASHBOARD_GRID_SETTINGS_KEY = 'dashboardGridSettings'; -/** REST namespace that exposes Premium Analytics dashboard endpoints. */ -export const DASHBOARD_REST_NAMESPACE = 'wpcom/v2'; - /** Preferences key holding when the reader completed or dismissed the onboarding, as an ISO date. */ export const DASHBOARD_ONBOARDING_KEY = 'onboardingCompletedAt'; diff --git a/projects/packages/premium-analytics/routes/dashboard/hooks/use-dashboard-sections.ts b/projects/packages/premium-analytics/routes/dashboard/hooks/use-dashboard-sections.ts index 0ce035402541..2fbfdbc5ae45 100644 --- a/projects/packages/premium-analytics/routes/dashboard/hooks/use-dashboard-sections.ts +++ b/projects/packages/premium-analytics/routes/dashboard/hooks/use-dashboard-sections.ts @@ -9,7 +9,7 @@ import type { DashboardSection } from '../config'; /** * Get the ordered list of dashboard sections. Reads the `dashboardSection` - * core-data entity (registered in the route's `beforeLoad`), which resolves + * core-data entity (registered at app boot in `packages/init`), which resolves * from `GET /sections`. * * `hasResolved` distinguishes "still fetching" (empty `sections`) from a diff --git a/projects/packages/premium-analytics/routes/dashboard/route.test.ts b/projects/packages/premium-analytics/routes/dashboard/route.test.ts index b346d77ce24c..631449f3bd0a 100644 --- a/projects/packages/premium-analytics/routes/dashboard/route.test.ts +++ b/projects/packages/premium-analytics/routes/dashboard/route.test.ts @@ -39,15 +39,6 @@ jest.mock( '@wordpress/route', () => ( { redirect: jest.fn( ( options: object ) => ( { isRedirect: true, ...options } ) ), } ) ); -const mockGetEntityConfig = jest.fn(); -const mockAddEntities = jest.fn(); -jest.mock( '@wordpress/data', () => ( { - select: () => ( { getEntityConfig: mockGetEntityConfig } ), - dispatch: () => ( { addEntities: mockAddEntities } ), -} ) ); - -jest.mock( '@wordpress/core-data', () => ( { store: {} } ) ); - // A search that needs no seeding: the seed check is mocked false. const settledSearch = { from: '2026-06-01T00:00:00', @@ -58,21 +49,9 @@ const settledSearch = { const beforeLoad = ( search?: object ) => route.beforeLoad( { search } as Parameters< typeof route.beforeLoad >[ 0 ] ); -/** - * The names registered across all `addEntities` calls. - * - * @return The registered entity names. - */ -function registeredNames(): string[] { - return mockAddEntities.mock.calls.flatMap( ( [ entities ] ) => - ( entities as { name: string }[] ).map( entity => entity.name ) - ); -} - describe( 'dashboard route.beforeLoad', () => { afterEach( () => { jest.clearAllMocks(); - mockGetEntityConfig.mockReset(); } ); it( 'redirects to /connect when the site is not connected', async () => { @@ -140,32 +119,4 @@ describe( 'dashboard route.beforeLoad', () => { expect( search ).toMatchObject( { comp: '1', compare_preset: 'previous-period' } ); } ); - - it( 'registers both dashboard entities on a fresh store', async () => { - mockGetEntityConfig.mockReturnValue( undefined ); - - await beforeLoad( settledSearch ); - - expect( registeredNames() ).toEqual( [ 'widgetModule', 'dashboardSection' ] ); - } ); - - it( 'registers dashboardSection even when a detail-page entry already registered widgetModule', async () => { - // Regression: reloading on a detail page had registered `widgetModule` alone, - // so the old guard skipped `dashboardSection`, force-opening an empty canvas. - mockGetEntityConfig.mockImplementation( ( _kind: string, name: string ) => - name === 'widgetModule' ? {} : undefined - ); - - await beforeLoad( settledSearch ); - - expect( registeredNames() ).toEqual( [ 'dashboardSection' ] ); - } ); - - it( 'does not re-register entities that already exist', async () => { - mockGetEntityConfig.mockReturnValue( {} ); - - await beforeLoad( settledSearch ); - - expect( mockAddEntities ).not.toHaveBeenCalled(); - } ); } ); diff --git a/projects/packages/premium-analytics/routes/dashboard/route.ts b/projects/packages/premium-analytics/routes/dashboard/route.ts index f4e2eae54e2b..9213bbc331c5 100644 --- a/projects/packages/premium-analytics/routes/dashboard/route.ts +++ b/projects/packages/premium-analytics/routes/dashboard/route.ts @@ -12,7 +12,6 @@ import { redirect } from '@wordpress/route'; /** * Internal dependencies */ -import { ensureDashboardEntities } from '../dashboard-entities'; import { isPremiumAnalyticsSiteConnected } from '../site-readiness'; type DashboardSearch = Record< string, string | undefined >; @@ -20,8 +19,7 @@ type DashboardSearch = Record< string, string | undefined >; /** * Route lifecycle for the dashboard. The initial analytics sync is not a guard * — only the store section waits on it and shows progress meanwhile (see - * `stage.tsx`). Widget-module registration is idempotent for repeat visits; it - * could move to `packages/init` and run once at boot — tracked as a follow-up. + * `stage.tsx`). */ export const route = { beforeLoad: async ( { search }: { search?: DashboardSearch } = {} ) => { @@ -66,7 +64,5 @@ export const route = { search: seeded as unknown as never, } ); } - - ensureDashboardEntities(); }, }; diff --git a/projects/packages/premium-analytics/routes/post-detail/route.test.ts b/projects/packages/premium-analytics/routes/post-detail/route.test.ts index cec4597218e1..9f0896e4fc47 100644 --- a/projects/packages/premium-analytics/routes/post-detail/route.test.ts +++ b/projects/packages/premium-analytics/routes/post-detail/route.test.ts @@ -1,5 +1,4 @@ import { ensureCoreSettingsReady } from '@jetpack-premium-analytics/data'; -import { select } from '@wordpress/data'; import { redirect } from '@wordpress/route'; import { route } from './route'; @@ -8,11 +7,6 @@ jest.mock( '@jetpack-premium-analytics/data', () => ( { ensureCoreSettingsReady: jest.fn(), } ) ); -jest.mock( '@wordpress/core-data', () => ( { store: {} } ) ); -jest.mock( '@wordpress/data', () => ( { - dispatch: jest.fn(), - select: jest.fn(), -} ) ); jest.mock( '@wordpress/route', () => ( { redirect: jest.fn( options => options ), } ) ); @@ -26,7 +20,6 @@ jest.mock( './config', () => ( { const mockEnsureCoreSettingsReady = ensureCoreSettingsReady as jest.MockedFunction< typeof ensureCoreSettingsReady >; -const mockSelect = select as jest.MockedFunction< typeof select >; const mockRedirect = redirect as jest.MockedFunction< typeof redirect >; const seededSearch = { @@ -40,10 +33,6 @@ describe( 'post detail route report origin', () => { beforeEach( () => { jest.clearAllMocks(); mockEnsureCoreSettingsReady.mockResolvedValue( undefined ); - mockSelect.mockReturnValue( { - getEntityConfig: () => ( {} ), - getEntityRecord: () => undefined, - } as never ); } ); it( 'carries the report origin through the seeding redirect', async () => { diff --git a/projects/packages/premium-analytics/routes/post-detail/route.ts b/projects/packages/premium-analytics/routes/post-detail/route.ts index ec5d5d8e6619..be093fa426f9 100644 --- a/projects/packages/premium-analytics/routes/post-detail/route.ts +++ b/projects/packages/premium-analytics/routes/post-detail/route.ts @@ -11,7 +11,6 @@ import { redirect } from '@wordpress/route'; /** * Internal dependencies */ -import { ensureDashboardEntities } from '../dashboard-entities'; import { isPremiumAnalyticsSiteConnected } from '../site-readiness'; import { resolveTabId } from './config'; @@ -32,8 +31,7 @@ function isValidPostId( value: string | undefined ): value is string { * Route lifecycle for the post/page detail page. * * `post_id` is seeded from the route param so every widget on the page is scoped - * to this single resource. The widget-modules entity is registered here too, so - * a direct deep link resolves widget types without visiting the dashboard first. + * to this single resource. */ export const route = { beforeLoad: async ( { @@ -102,7 +100,5 @@ export const route = { search: seeded as unknown as never, } ); } - - ensureDashboardEntities(); }, }; diff --git a/projects/packages/premium-analytics/routes/video-detail/route.test.ts b/projects/packages/premium-analytics/routes/video-detail/route.test.ts index 37d91369b2b4..8045b80480b7 100644 --- a/projects/packages/premium-analytics/routes/video-detail/route.test.ts +++ b/projects/packages/premium-analytics/routes/video-detail/route.test.ts @@ -29,15 +29,6 @@ jest.mock( '@wordpress/route', () => ( { redirect: jest.fn( ( options: object ) => ( { isRedirect: true, ...options } ) ), } ) ); -const mockGetEntityConfig = jest.fn( () => ( {} ) ); -const mockAddEntities = jest.fn(); -jest.mock( '@wordpress/data', () => ( { - select: () => ( { getEntityConfig: mockGetEntityConfig } ), - dispatch: () => ( { addEntities: mockAddEntities } ), -} ) ); - -jest.mock( '@wordpress/core-data', () => ( { store: {} } ) ); - // A search that needs no seeding at all for video 42: dates present (the seed // check is mocked false), the post scope matches, and no comparison params. const settledSearch = { @@ -52,7 +43,6 @@ const beforeLoad = ( params?: object, search?: object ) => describe( 'video detail route.beforeLoad', () => { afterEach( () => { jest.clearAllMocks(); - mockGetEntityConfig.mockReturnValue( {} ); } ); it( 'redirects to /connect when the site is not connected', async () => { @@ -139,23 +129,11 @@ describe( 'video detail route.beforeLoad', () => { compare_from: '2026-05-01T00:00:00', } ); } ); - - it( 'registers the widget-module entity exactly once', async () => { - mockGetEntityConfig.mockReturnValueOnce( undefined as unknown as object ); - - await beforeLoad( { videoId: '42' }, settledSearch ); - expect( mockAddEntities ).toHaveBeenCalledTimes( 1 ); - - // Registered now, so the next pass skips. - await beforeLoad( { videoId: '42' }, settledSearch ); - expect( mockAddEntities ).toHaveBeenCalledTimes( 1 ); - } ); } ); describe( 'video detail route report origin', () => { afterEach( () => { jest.clearAllMocks(); - mockGetEntityConfig.mockReturnValue( {} ); } ); it( 'carries the report origin through the seeding redirect', async () => { diff --git a/projects/packages/premium-analytics/routes/video-detail/route.ts b/projects/packages/premium-analytics/routes/video-detail/route.ts index 7b8526f27e34..6f2321816123 100644 --- a/projects/packages/premium-analytics/routes/video-detail/route.ts +++ b/projects/packages/premium-analytics/routes/video-detail/route.ts @@ -11,7 +11,6 @@ import { redirect } from '@wordpress/route'; /** * Internal dependencies */ -import { ensureDashboardEntities } from '../dashboard-entities'; import { isPremiumAnalyticsSiteConnected, isVideoPressAvailable } from '../site-readiness'; type VideoDetailParams = { videoId?: string }; @@ -97,7 +96,5 @@ export const route = { search: seeded as unknown as never, } ); } - - ensureDashboardEntities(); }, };