Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
@@ -1 +1,17 @@
export const statsProxyPath = '/jetpack-premium-analytics/v1/proxy';

/**
* Identifier of the Premium Analytics dashboard, formatted as
* `<plugin>_<page>` 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';
Comment on lines +7 to +11

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DASHBOARD_REST_NAMESPACE below kept its PHP pointer but this one lost the src/dashboard-layout.php one it had in the old header, and a rename on either side would just 404 the sections entity quietly.

Suggested change
* REST route.
*/
export const DASHBOARD_NAME = 'jetpack-premium-analytics_dashboard';
* 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';
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ensureDashboardEntities } from './dashboard-entities';
import { ensureDashboardEntities } from '../dashboard-entities';

const mockGetEntityConfig = jest.fn();
const mockAddEntities = jest.fn();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Small one: importing from the data barrel makes the whole @jetpack-premium-analytics/data module a static dep of init (it shows up in modules/init/index.min.asset.php now), so it evaluates before init() on every page, /connect included. Probably fine since every real route needs it anyway, just flagging in case you'd rather keep init tiny.

import apiFetch from '@wordpress/api-fetch';
import { store as bootStore } from '@wordpress/boot';
import { dispatch } from '@wordpress/data';
Expand Down Expand Up @@ -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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still no test on this path - it's now the only place the entities get registered, and the "after await catalogs" ordering is only a comment. A tiny init test that mocks loadI18nCatalogs and asserts ensureDashboardEntities runs after it resolves would pin both down. Non-blocking, happy for it to be a follow up.

Also just wondering - as far as I can tell nothing in the app reads the entity label (core-data only uses it in the editor's saved-states panel), so the after-catalogs ordering might not be load-bearing at all. If that's right, registering up in the sync block next to setupApiFetch() would also mean nothing throwing upstream in init() can skip it (the page template swallows init errors and boots anyway). I might be missing a reader of label tho, so take it as a question.

}
Original file line number Diff line number Diff line change
@@ -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
* `<plugin>_<page>` 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
Expand All @@ -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';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Heads up - trunk moved under this after the rebase: #51948 added DASHBOARD_ONBOARDING_KEY right below the old DASHBOARD_REST_NAMESPACE, so this file conflicts now. Just a trunk merge and keep both, nothing to rethink.

Also while you're in here, the header above still says these must match src/dashboard-layout.php, but now that DASHBOARD_NAME moved out nothing in src/ defines the prefs scope or key anymore, so that sentence is a bit misleading I think.


/** 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';
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -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 () => {
Expand Down Expand Up @@ -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();
} );
} );
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,14 @@ import { redirect } from '@wordpress/route';
/**
* Internal dependencies
*/
import { ensureDashboardEntities } from '../dashboard-entities';
import { isPremiumAnalyticsSiteConnected } from '../site-readiness';

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 } = {} ) => {
Expand Down Expand Up @@ -66,7 +64,5 @@ export const route = {
search: seeded as unknown as never,
} );
}

ensureDashboardEntities();
},
};
Original file line number Diff line number Diff line change
@@ -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';

Expand All @@ -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 ),
} ) );
Expand All @@ -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 = {
Expand All @@ -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 () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -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 ( {
Expand Down Expand Up @@ -102,7 +100,5 @@ export const route = {
search: seeded as unknown as never,
} );
}

ensureDashboardEntities();
},
};
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand All @@ -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 () => {
Expand Down Expand Up @@ -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 () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
Expand Down Expand Up @@ -97,7 +96,5 @@ export const route = {
search: seeded as unknown as never,
} );
}

ensureDashboardEntities();
},
};
Loading