From 902ac2f797be0bed51f6063b9fd9d9e87f6f0cd8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dami=C3=A1n=20Su=C3=A1rez?= Date: Mon, 28 Sep 2026 12:08:42 +0100 Subject: [PATCH 01/22] drop unregistered widget types from defaults the default-layout policy asks the widget registry once it can answer --- ...extensibility-videopress-layout-validation | 4 + .../docs/dashboard-sections.md | 26 ++--- .../docs/dashboard-widgets.md | 2 +- .../src/dashboard-layout.php | 37 ++++++- .../tests/php/Dashboard_Layout_Test.php | 100 ++++++++++++++++++ 5 files changed, 155 insertions(+), 14 deletions(-) create mode 100644 projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-layout-validation diff --git a/projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-layout-validation b/projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-layout-validation new file mode 100644 index 000000000000..46b02c15a29e --- /dev/null +++ b/projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-layout-validation @@ -0,0 +1,4 @@ +Significance: patch +Type: changed + +Dashboard: Drop the instances of unregistered widget types from a section's default layout. diff --git a/projects/packages/premium-analytics/docs/dashboard-sections.md b/projects/packages/premium-analytics/docs/dashboard-sections.md index 369f0c3c1c5e..b2f75593da1d 100644 --- a/projects/packages/premium-analytics/docs/dashboard-sections.md +++ b/projects/packages/premium-analytics/docs/dashboard-sections.md @@ -21,18 +21,18 @@ This page covers sections only. Widget types have their own page, [Dashboard wid ## Files -| File | Role | -| -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `src/class-dashboard-section.php` | The section model: properties, `is_available()`, `get_default_layout()`, `to_array()`. | -| `src/class-dashboard-section-registry.php` | The registry: `register()` with its validations, the reads, and the lazy hydration that fires the registration action. | -| `src/dashboard-sections.php` | The section API: the `register_dashboard_section()` family, the preview scope, the script data, the REST routes and their schema. | -| `src/dashboard-layout.php` | Layout primitives: `DASHBOARD_NAME`, the default-layout filter name, `get_dashboard_default_widget_instance()`, and the package's availability policy on default layouts. | -| `src/default-dashboard-sections.php` | The package's own sections: Traffic, Insights, Subscribers, Store, their gates and their default layouts, registered through the action like any plugin's. | -| `src/class-analytics.php` | Loads the three files above on wp-admin requests (`load_dashboard_components()`). | -| `src/class-dashboard-support-routes.php` | Loads them on REST requests (`boot_routes()`), on connected sites and, called directly by WordPress.com, on Simple. | -| `packages/data/src/entities/dashboard-entities.ts` | The `dashboardSection` core-data entity the client reads. | -| `routes/dashboard/` | `useDashboardSections()`, `useActiveSection()`, `useDashboardSectionLayout()`, and the stage that renders the navigation. | -| `routes/site-readiness.ts` | `isDashboardSectionInPreviewScope()`, the report routes' gate, fed by the inline script data. | +| File | Role | +| -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `src/class-dashboard-section.php` | The section model: properties, `is_available()`, `get_default_layout()`, `to_array()`. | +| `src/class-dashboard-section-registry.php` | The registry: `register()` with its validations, the reads, and the lazy hydration that fires the registration action. | +| `src/dashboard-sections.php` | The section API: the `register_dashboard_section()` family, the preview scope, the script data, the REST routes and their schema. | +| `src/dashboard-layout.php` | Layout primitives: `DASHBOARD_NAME`, the default-layout filter name, `get_dashboard_default_widget_instance()`, and the package's availability policy on default layouts. | +| `src/default-dashboard-sections.php` | The package's own sections: Traffic, Insights, Subscribers, Store, their gates and their default layouts, registered through the action like any plugin's. | +| `src/class-analytics.php` | Loads the three files above on wp-admin requests (`load_dashboard_components()`). | +| `src/class-dashboard-support-routes.php` | Loads them on REST requests (`boot_routes()`), on connected sites and, called directly by WordPress.com, on Simple. | +| `packages/data/src/entities/dashboard-entities.ts` | The `dashboardSection` core-data entity the client reads. | +| `routes/dashboard/` | `useDashboardSections()`, `useActiveSection()`, `useDashboardSectionLayout()`, and the stage that renders the navigation. | +| `routes/site-readiness.ts` | `isDashboardSectionInPreviewScope()`, the report routes' gate, fed by the inline script data. | ## When the section files load @@ -152,6 +152,8 @@ add_filter( The package removes the instances the site cannot serve at priority 100, `remove_unsupported_default_layout_items()` over `get_widget_support_context()`. A persisted layout keeps such an instance as a removable ghost widget, but a default must not seed one. Running late means an instance a plugin added gets the same treatment as a bundled one. +The same callback drops an instance whose type the widget type registry has not registered, once the registry can answer: after `init`, with the widget type API loaded and at least one type registered. Before that, or on a checkout without a build, the default stays as declared. + The client stores customized layouts in the `dashboardSectionLayouts` preference, keyed by slug. `useDashboardSectionLayout()` renders the stored layout when there is one and the section's `default_layout` otherwise. Reset deletes the stored entry rather than copying the default into it, so a section that was reset follows later changes to the default. diff --git a/projects/packages/premium-analytics/docs/dashboard-widgets.md b/projects/packages/premium-analytics/docs/dashboard-widgets.md index 5f9783103b69..ace80912477c 100644 --- a/projects/packages/premium-analytics/docs/dashboard-widgets.md +++ b/projects/packages/premium-analytics/docs/dashboard-widgets.md @@ -106,7 +106,7 @@ Two filters, both problem-agnostic: The package's own policy hooks the first, in `src/widget-availability.php`: developer-only widgets off production, the store and bookings categories without WooCommerce or Bookings, the store report categories without the capability. A plugin's manifest goes through the same filter when it registers through `register_widget_types_from_manifest()`; a type registered one by one with `register_widget_type()` does not. Either way, a plugin decides in its callback whether to register at all, as the section owners do. -A third policy, in `src/widget-type-support.php`, acts on default layouts rather than on the registry: `remove_unsupported_default_layout_items()` drops from a section's default the instances whose type the site cannot serve. It reads a fixed list, not the registry (see [Default layouts](dashboard-sections.md#default-layouts)). +A third policy, in `src/widget-type-support.php`, acts on default layouts rather than on the registry: `remove_unsupported_default_layout_items()` drops from a section's default the instances whose type the site cannot serve. It reads the package's fixed list and, once the registry can answer, the registry itself: an instance whose type is not registered is dropped too (see [Default layouts](dashboard-sections.md#default-layouts)). ## Versioning the contract diff --git a/projects/packages/premium-analytics/src/dashboard-layout.php b/projects/packages/premium-analytics/src/dashboard-layout.php index 8bb42c5fb3c3..83d87d65ec80 100644 --- a/projects/packages/premium-analytics/src/dashboard-layout.php +++ b/projects/packages/premium-analytics/src/dashboard-layout.php @@ -76,14 +76,49 @@ function get_dashboard_default_widget_instance( * @return array The layout minus the unsupported instances. */ function remove_unsupported_default_layout_items( $layout ) { - return remove_unsupported_widget_items( + $layout = remove_unsupported_widget_items( is_array( $layout ) ? $layout : array(), 'type', get_widget_support_context() ); + + return remove_unregistered_default_layout_items( $layout ); } add_filter( DASHBOARD_DEFAULT_LAYOUT_FILTER, __NAMESPACE__ . '\\remove_unsupported_default_layout_items', 100 ); +/** + * Drops the widget instances whose type the widget type registry does not know. + * + * Only once the registry can answer: after `init`, with the widget type API loaded and at least + * one type registered. Before that, or on a checkout without a build, the default stays as + * declared rather than emptying itself. + * + * @since $$next-version$$ + * + * @param array $layout Default widget instances. + * @return array The layout minus the instances of unregistered types. + */ +function remove_unregistered_default_layout_items( $layout ) { + if ( ! did_action( 'init' ) || ! function_exists( __NAMESPACE__ . '\\ensure_widget_registry_ready' ) ) { + return $layout; + } + + ensure_widget_registry_ready(); + $registered = Widget_Type_Registry::get_instance()->get_all_registered(); + if ( empty( $registered ) ) { + return $layout; + } + + return array_values( + array_filter( + $layout, + static function ( $item ) use ( $registered ) { + return ! is_array( $item ) || isset( $registered[ $item['type'] ?? '' ] ); + } + ) + ); +} + /** * No-op kept for older copies of the package: they guard their include of this file on this * symbol and call it from boot_routes(), so a newer copy loading first must still define it. diff --git a/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php b/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php index 138efeb32095..82d029b5b7f2 100644 --- a/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php +++ b/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php @@ -13,11 +13,15 @@ require_once __DIR__ . '/../../src/dashboard-sections.php'; require_once __DIR__ . '/../../src/default-dashboard-sections.php'; +require_once __DIR__ . '/../../src/widget-modules.php'; +require_once __DIR__ . '/../../src/widget-types.php'; +require_once __DIR__ . '/traits/trait-widget-manifest-fixture.php'; /** * Tests for the dashboard default-layout primitives and the package's bundled defaults. */ class Dashboard_Layout_Test extends BaseTestCase { + use Widget_Manifest_Fixture_Trait; /** * Default-layout filter callback a test hooked, removed on tear down. @@ -32,6 +36,11 @@ class Dashboard_Layout_Test extends BaseTestCase { public function set_up() { parent::set_up(); + // No build manifest here: the widget registry holds only what a test registers. + add_filter( 'jetpack_premium_analytics_widgets_manifest_path', array( $this, 'use_absent_widget_manifest' ) ); + $GLOBALS['jpa_test_widget_manifest'] = array(); + $this->reset_widget_registry(); + register_default_dashboard_sections(); } @@ -49,6 +58,9 @@ public function tear_down() { $instance->setAccessible( true ); } $instance->setValue( null, null ); + $this->reset_widget_registry(); + remove_filter( 'jetpack_premium_analytics_widgets_manifest_path', array( $this, 'use_absent_widget_manifest' ) ); + unset( $GLOBALS['jpa_test_widget_manifest'] ); Constants::clear_constants(); // The default layout reaches Host::is_wpcom_platform(), which memoizes @@ -208,6 +220,7 @@ public function test_insights_default_keeps_shares_on_wpcom_simple() { * and the other sections are left alone. */ public function test_filter_adds_a_widget_to_one_section_default() { + $this->register_example_widget_type( 'example/widget' ); $this->filter_default_layout( static function ( $layout, $section_id ) { if ( 'analytics/traffic' === $section_id ) { @@ -240,6 +253,93 @@ static function ( $layout, $section_id ) { $this->assertNotContains( 'jpa/file-downloads', $this->served_layout_types( 'analytics/insights' ) ); } + /** + * A default never seeds a type the site has not registered, whoever added the instance. + */ + public function test_default_drops_an_instance_whose_type_is_not_registered() { + $this->register_example_widget_type( 'example/registered' ); + $this->filter_default_layout( + static function ( $layout, $section_id ) { + if ( 'analytics/traffic' === $section_id ) { + $layout[] = get_dashboard_default_widget_instance( 'example-registered', 'example/registered', 20 ); + $layout[] = get_dashboard_default_widget_instance( 'example-unregistered', 'example/unregistered', 21 ); + } + return $layout; + } + ); + + $layout_types = $this->served_layout_types( 'analytics/traffic' ); + + $this->assertContains( 'example/registered', $layout_types ); + $this->assertNotContains( 'example/unregistered', $layout_types, 'A default must not seed a type the site has not registered.' ); + } + + /** + * Before init the registry cannot hydrate, so the policy leaves the default as declared. + */ + public function test_default_keeps_unregistered_instances_before_init() { + global $wp_actions; + $init_runs = $wp_actions['init'] ?? null; + unset( $wp_actions['init'] ); + + try { + $layout = remove_unsupported_default_layout_items( + array( get_dashboard_default_widget_instance( 'example-unregistered', 'example/unregistered', 20 ) ) + ); + } finally { + if ( null !== $init_runs ) { + $wp_actions['init'] = $init_runs; + } + } + + $this->assertSame( array( 'example/unregistered' ), array_column( $layout, 'type' ) ); + } + + /** + * With nothing registered, a checkout without a build, the default is left alone rather than emptied. + */ + public function test_default_keeps_unregistered_instances_when_no_type_is_registered() { + if ( array() !== Widget_Type_Registry::get_instance()->get_all_registered() ) { + $this->markTestSkipped( 'A widget manifest is loaded in this process.' ); + } + + $layout = remove_unsupported_default_layout_items( + array( get_dashboard_default_widget_instance( 'example-unregistered', 'example/unregistered', 20 ) ) + ); + + $this->assertSame( array( 'example/unregistered' ), array_column( $layout, 'type' ) ); + } + + /** + * Register a widget type the way a plugin does, so a default may seed it. + * + * @param string $name Widget type name. + */ + private function register_example_widget_type( $name ) { + $this->assertInstanceOf( + Widget_Type::class, + register_widget_type( + $name, + array( + 'render_module' => 'example/render', + 'widget_module' => 'example/widget', + 'title' => 'Example', + ) + ) + ); + } + + /** + * Reset the widget type registry's main instance. + */ + private function reset_widget_registry() { + $instance = new \ReflectionProperty( Widget_Type_Registry::class, 'instance' ); + if ( PHP_VERSION_ID < 80100 ) { + $instance->setAccessible( true ); + } + $instance->setValue( null, null ); + } + /** * The Traffic tab declares its bundled widgets on the three-column grid. */ From d53f902f72ee4220586b1fb22161cfd74777c158 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dami=C3=A1n=20Su=C3=A1rez?= Date: Mon, 28 Sep 2026 14:03:26 +0100 Subject: [PATCH 02/22] declare the layout before the try in the init test phan cannot see past the finally --- .../premium-analytics/tests/php/Dashboard_Layout_Test.php | 1 + 1 file changed, 1 insertion(+) diff --git a/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php b/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php index 82d029b5b7f2..010a4a6b1677 100644 --- a/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php +++ b/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php @@ -282,6 +282,7 @@ public function test_default_keeps_unregistered_instances_before_init() { $init_runs = $wp_actions['init'] ?? null; unset( $wp_actions['init'] ); + $layout = array(); try { $layout = remove_unsupported_default_layout_items( array( get_dashboard_default_widget_instance( 'example-unregistered', 'example/unregistered', 20 ) ) From cbc3bf5f22c9259f9045c0b741cf6e22d4f21ed4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dami=C3=A1n=20Su=C3=A1rez?= Date: Mon, 28 Sep 2026 15:27:21 +0100 Subject: [PATCH 03/22] carry former names on widget types a renamed type keeps the layouts saved under its old name; contract 1.1.0 --- projects/packages/premium-analytics/AGENTS.md | 3 +- ...e-pa-extensibility-videopress-former-names | 4 + .../docs/dashboard-sections.md | 2 +- .../docs/dashboard-widgets.md | 16 +++- .../routes/dashboard/config/index.ts | 8 ++ .../config/widget-type-renames.test.ts | 55 ++++++++++++ .../dashboard/config/widget-type-renames.ts | 64 +++++++++++++ .../use-dashboard-section-layout.test.ts | 40 ++++++++- .../use-dashboard-section-layout.ts | 28 ++++-- .../routes/dashboard/stage.tsx | 15 +++- .../src/class-widget-type-registry.php | 80 +++++++++++++++++ .../src/class-widget-type.php | 10 +++ .../src/dashboard-layout.php | 60 +++++++++++-- .../premium-analytics/src/widget-modules.php | 1 + .../premium-analytics/src/widget-types.php | 27 +++++- .../groups/routes-no-mocks-part1.test.tsx | 1 + .../tests/php/Dashboard_Layout_Test.php | 30 +++++++ .../tests/php/Widget_Modules_Test.php | 21 +++++ .../tests/php/Widget_Type_Registry_Test.php | 89 +++++++++++++++++++ 19 files changed, 531 insertions(+), 23 deletions(-) create mode 100644 projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-former-names create mode 100644 projects/packages/premium-analytics/routes/dashboard/config/widget-type-renames.test.ts create mode 100644 projects/packages/premium-analytics/routes/dashboard/config/widget-type-renames.ts diff --git a/projects/packages/premium-analytics/AGENTS.md b/projects/packages/premium-analytics/AGENTS.md index 66ca3524fad8..bb9572b075a6 100644 --- a/projects/packages/premium-analytics/AGENTS.md +++ b/projects/packages/premium-analytics/AGENTS.md @@ -91,7 +91,8 @@ Add widget types from another plugin: hook `jetpack_premium_analytics_register_w compare `WIDGET_API_VERSION`, and call `register_widget_types_from_manifest()` there with the manifest that plugin's wp-build generates (`register_widget_type()` registers a single type). The widget type registry hydrates on its first read, from the page boot dependencies or from REST, and fires that -action once; `src/widget-types.php` registers the package's own build manifest the same way. +action once; `src/widget-types.php` registers the package's own build manifest the same way. A type +that changes its name declares `former_names`, so layouts saved under the old one keep rendering it. `docs/dashboard-widgets.md` walks through the path. Depends on `jetpack-connection`, `jetpack-stats`, `jetpack-sync`, `jetpack-config`. diff --git a/projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-former-names b/projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-former-names new file mode 100644 index 000000000000..089176ebd823 --- /dev/null +++ b/projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-former-names @@ -0,0 +1,4 @@ +Significance: minor +Type: added + +Dashboard: Let a widget type declare its former names, so layouts saved before a rename keep rendering it; the widget contract is 1.1.0. diff --git a/projects/packages/premium-analytics/docs/dashboard-sections.md b/projects/packages/premium-analytics/docs/dashboard-sections.md index 448f1acfa370..316acab2bf21 100644 --- a/projects/packages/premium-analytics/docs/dashboard-sections.md +++ b/projects/packages/premium-analytics/docs/dashboard-sections.md @@ -152,7 +152,7 @@ add_filter( The package removes the instances the site cannot serve at priority 100, `remove_unsupported_default_layout_items()` over `get_widget_support_context()`. A persisted layout keeps such an instance as a removable ghost widget, but a default must not seed one. Running late means an instance a plugin added gets the same treatment as a bundled one. -The same callback drops an instance whose type the widget type registry has not registered, once the registry can answer: after `init`, with the widget type API loaded and at least one type registered. Before that, or on a checkout without a build, the default stays as declared. +The same callback drops an instance whose type the widget type registry has not registered, once the registry can answer: after `init`, with the widget type API loaded and at least one type registered. Before that, or on a checkout without a build, the default stays as declared. Just ahead of it, at priority 99, `resolve_former_widget_types_in_default_layout()` renames an instance added under a former name of a registered type (see [Renaming a widget type](dashboard-widgets.md#renaming-a-widget-type)). The client stores customized layouts in the `dashboardSectionLayouts` preference, keyed by slug. `useDashboardSectionLayout()` renders the stored layout when there is one and the section's `default_layout` otherwise. diff --git a/projects/packages/premium-analytics/docs/dashboard-widgets.md b/projects/packages/premium-analytics/docs/dashboard-widgets.md index c9ed509021fb..6d2507a1ce6a 100644 --- a/projects/packages/premium-analytics/docs/dashboard-widgets.md +++ b/projects/packages/premium-analytics/docs/dashboard-widgets.md @@ -115,7 +115,7 @@ The name must be a lowercase `/` string, and must not be regist ### Arguments -Any public property of `Widget_Type`: `render_module`, `widget_module`, `presentation` (`framed`, `content-bleed` or `full-bleed`), `category`, `title`, `description`, `help` (`content` plus optional `links`), `icon` (`collection/name`), `actions`, `keywords`, `textdomain`, `i18n_manifest`. `set_props()` copies every key onto the instance. +Any public property of `Widget_Type`: `render_module`, `widget_module`, `presentation` (`framed`, `content-bleed` or `full-bleed`), `category`, `title`, `description`, `help` (`content` plus optional `links`), `icon` (`collection/name`), `actions`, `keywords`, `textdomain`, `i18n_manifest`, `former_names`. `set_props()` copies every key onto the instance. Through `register_widget_type()` the strings arrive translated and `help`, `icon` and `actions` in shape. The manifest helper translates and sanitizes them itself. @@ -131,6 +131,16 @@ Through `register_widget_type()` the strings arrive translated and `help`, `icon The package's own widget types register at priority 10. A plugin that wants to see them registered first hooks later. +### Renaming a widget type + +A type that changes its name declares the old one in `former_names`: in `widget.json`, in the `$args['former_names']` map of `register_widget_types_from_manifest()` (current name to former names), or in the arguments of `register_widget_type()`. Moving a widget to its owner's package is such a rename, `jpa/x` to `owner/x`. Declaring former names needs `WIDGET_API_VERSION` 1.1.0. + +The registry maps each former name to the current one. `get_registered()` answers for both, `resolve_name()` gives the current name, and `register()` refuses a former name a registered type or another type's former name holds, and a name that is someone's former name. + +The REST record publishes `former_names`. The dashboard stage maps a stored layout's types through them before rendering (`buildWidgetTypeRenames()`, `useDashboardSectionLayout()`), with no write-back: the current name persists with the section's next commit. On the server, `resolve_former_widget_types_in_default_layout()` renames default-layout instances at priority 99, ahead of the unregistered-type check, so a plugin that still adds an instance under the old name keeps it. + +A rename keeps the attributes as they are. One that changes them needs a migration, which nothing offers yet. + ### Script modules The module ids are what the client hands to `import()`. The package's are registered by the generated `jpa_register_widget_modules()`; a plugin's by the same generated file of its own build. @@ -159,7 +169,7 @@ On the server, `get_available_widget_types()` runs the registered map through `j ### The REST record -`GET /wpcom/v2/widget-modules` returns one record per available type: `name`, `render_module`, `widget_module`, the metadata fields, `textdomain` and `i18n_manifest`. +`GET /wpcom/v2/widget-modules` returns one record per available type: `name`, `render_module`, `widget_module`, the metadata fields, `textdomain`, `i18n_manifest` and `former_names`. It is gated on `Capabilities::current_user_can_view_analytics()`, the dashboard's own gate. The `wpcom/v2` namespace is what lets WordPress.com expose it through public-api for Simple sites. @@ -254,5 +264,5 @@ The types were `jpa/wordads-*` while they lived here. A layout persisted with th - Stories and JS tests for a plugin's widgets: the Ads widgets left this package's Storybook and jest harness with their move, and `packages/ads` has neither yet. - Precise types for the SDK: `projects/js-packages/premium-analytics-sdk` declares its exports loosely until a build step emits them from the facade. -- An alias for a renamed widget type in persisted layouts, so a move like the Ads one needs no reset. +- A migration for a rename that also changes attributes, the `deprecated` equivalent of blocks, and the upstream ask: `@wordpress/widget-primitives` knows neither former names nor deprecations. - The metadata strings of `widget.json`, which reach no catalog in any package until the strings stub ships. diff --git a/projects/packages/premium-analytics/routes/dashboard/config/index.ts b/projects/packages/premium-analytics/routes/dashboard/config/index.ts index e7e5a49a900f..d06681e30232 100644 --- a/projects/packages/premium-analytics/routes/dashboard/config/index.ts +++ b/projects/packages/premium-analytics/routes/dashboard/config/index.ts @@ -16,3 +16,11 @@ export { } from './date-filter'; export { isDashboardSectionLayouts, type DashboardSectionLayouts } from './section-layouts'; + +export { + NO_WIDGET_TYPE_RENAMES, + buildWidgetTypeRenames, + resolveLayoutTypes, + type WidgetTypeName, + type WidgetTypeRenameRecord, +} from './widget-type-renames'; diff --git a/projects/packages/premium-analytics/routes/dashboard/config/widget-type-renames.test.ts b/projects/packages/premium-analytics/routes/dashboard/config/widget-type-renames.test.ts new file mode 100644 index 000000000000..1fed53a85b6e --- /dev/null +++ b/projects/packages/premium-analytics/routes/dashboard/config/widget-type-renames.test.ts @@ -0,0 +1,55 @@ +/** + * Internal dependencies + */ +import { + NO_WIDGET_TYPE_RENAMES, + buildWidgetTypeRenames, + resolveLayoutTypes, + type WidgetTypeName, +} from './widget-type-renames'; +import type { DashboardWidget } from '@wordpress/widget-dashboard'; + +describe( 'buildWidgetTypeRenames', () => { + it( 'maps every former name to the record that claims it', () => { + const renames = buildWidgetTypeRenames( [ + { name: 'videopress/top-videos', former_names: [ 'jpa/videopress' ] }, + { name: 'jpa/clicks', former_names: null }, + { name: 'wordads/highlights' }, + ] ); + + expect( [ ...renames ] ).toEqual( [ [ 'jpa/videopress', 'videopress/top-videos' ] ] ); + } ); + + it( 'shares one empty map while there is nothing to rename', () => { + expect( buildWidgetTypeRenames( null ) ).toBe( NO_WIDGET_TYPE_RENAMES ); + expect( buildWidgetTypeRenames( [ { name: 'jpa/clicks' } ] ) ).toBe( NO_WIDGET_TYPE_RENAMES ); + } ); +} ); + +describe( 'resolveLayoutTypes', () => { + const renames = new Map< string, WidgetTypeName >( [ + [ 'jpa/videopress', 'videopress/top-videos' ], + ] ); + + it( 'renames only the items saved under a former name', () => { + const layout: DashboardWidget[] = [ + { uuid: 'videos', type: 'jpa/videopress', attributes: { view: 'plays' } }, + { uuid: 'clicks', type: 'jpa/clicks' }, + ]; + + const resolved = resolveLayoutTypes( layout, renames ); + + expect( resolved ).toEqual( [ + { uuid: 'videos', type: 'videopress/top-videos', attributes: { view: 'plays' } }, + { uuid: 'clicks', type: 'jpa/clicks' }, + ] ); + expect( resolved[ 1 ] ).toBe( layout[ 1 ] ); + } ); + + it( 'keeps the layout identity when nothing is renamed', () => { + const layout: DashboardWidget[] = [ { uuid: 'clicks', type: 'jpa/clicks' } ]; + + expect( resolveLayoutTypes( layout, renames ) ).toBe( layout ); + expect( resolveLayoutTypes( layout, NO_WIDGET_TYPE_RENAMES ) ).toBe( layout ); + } ); +} ); diff --git a/projects/packages/premium-analytics/routes/dashboard/config/widget-type-renames.ts b/projects/packages/premium-analytics/routes/dashboard/config/widget-type-renames.ts new file mode 100644 index 000000000000..111e30c87d67 --- /dev/null +++ b/projects/packages/premium-analytics/routes/dashboard/config/widget-type-renames.ts @@ -0,0 +1,64 @@ +/** + * External dependencies + */ +import type { DashboardWidget } from '@wordpress/widget-dashboard'; + +/** + * A namespaced widget type name, as the dashboard types it. + */ +export type WidgetTypeName = DashboardWidget[ 'type' ]; + +/** + * The fields of a widget module record a rename reads. + */ +export type WidgetTypeRenameRecord = { + name: string; + former_names?: string[] | null; +}; + +export const NO_WIDGET_TYPE_RENAMES: ReadonlyMap< string, WidgetTypeName > = new Map(); + +/** + * Map each former widget type name to the current one, from the widget module records. + * + * @param records - The widget module records, or nothing while they resolve. + * @return Former name to current name. + */ +export function buildWidgetTypeRenames( + records: readonly WidgetTypeRenameRecord[] | null | undefined +): ReadonlyMap< string, WidgetTypeName > { + if ( ! records?.length ) { + return NO_WIDGET_TYPE_RENAMES; + } + + const renames = new Map< string, WidgetTypeName >(); + for ( const record of records ) { + for ( const formerName of record.former_names ?? [] ) { + renames.set( formerName, record.name as WidgetTypeName ); + } + } + + return renames.size ? renames : NO_WIDGET_TYPE_RENAMES; +} + +/** + * Rename the layout items saved under a former widget type name. + * + * Hands back the same array when nothing changes, so a layout keeps its identity. + * + * @param layout - Widget instances, stored or default. + * @param renames - Former name to current name. + * @return The layout with current type names. + */ +export function resolveLayoutTypes( + layout: DashboardWidget[], + renames: ReadonlyMap< string, WidgetTypeName > +): DashboardWidget[] { + if ( ! renames.size || ! layout.some( item => renames.has( item.type ) ) ) { + return layout; + } + + return layout.map( item => + renames.has( item.type ) ? { ...item, type: renames.get( item.type ) as WidgetTypeName } : item + ); +} diff --git a/projects/packages/premium-analytics/routes/dashboard/hooks/use-dashboard-section-layout/use-dashboard-section-layout.test.ts b/projects/packages/premium-analytics/routes/dashboard/hooks/use-dashboard-section-layout/use-dashboard-section-layout.test.ts index 2568dc446876..1159adc6030a 100644 --- a/projects/packages/premium-analytics/routes/dashboard/hooks/use-dashboard-section-layout/use-dashboard-section-layout.test.ts +++ b/projects/packages/premium-analytics/routes/dashboard/hooks/use-dashboard-section-layout/use-dashboard-section-layout.test.ts @@ -9,7 +9,7 @@ import { store as preferencesStore } from '@wordpress/preferences'; */ import { DASHBOARD_PREFERENCES_SCOPE } from '../constants'; import { useDashboardSectionLayout } from './use-dashboard-section-layout'; -import type { DashboardSection } from '../../config'; +import type { DashboardSection, WidgetTypeName } from '../../config'; import type { DashboardWidget } from '@wordpress/widget-dashboard'; const PREFERENCES_KEY = 'dashboardSectionLayouts'; @@ -122,6 +122,44 @@ describe( 'useDashboardSectionLayout', () => { expect( storedLayouts() ).toBe( stored ); } ); + it( 'renders a layout stored under a former widget type name as the current type', () => { + const stored = [ { uuid: 'videos', type: 'jpa/videopress', attributes: { view: 'plays' } } ]; + dispatch( preferencesStore ).set( DASHBOARD_PREFERENCES_SCOPE, PREFERENCES_KEY, { + traffic: stored, + } ); + const renames = new Map< string, WidgetTypeName >( [ + [ 'jpa/videopress', 'videopress/top-videos' ], + ] ); + + const { result } = renderHook( () => + useDashboardSectionLayout( 'traffic', sections, renames ) + ); + + expect( result.current[ 0 ] ).toEqual( [ + { uuid: 'videos', type: 'videopress/top-videos', attributes: { view: 'plays' } }, + ] ); + // No write-back: the stored layout keeps the old name until the section commits again. + expect( storedLayouts() ).toEqual( { traffic: stored } ); + + act( () => result.current[ 1 ]( result.current[ 0 ] ) ); + + expect( storedLayouts() ).toEqual( { + traffic: [ { uuid: 'videos', type: 'videopress/top-videos', attributes: { view: 'plays' } } ], + } ); + } ); + + it( 'keeps the default identity when no stored item needs renaming', () => { + const renames = new Map< string, WidgetTypeName >( [ + [ 'jpa/videopress', 'videopress/top-videos' ], + ] ); + + const { result } = renderHook( () => + useDashboardSectionLayout( 'traffic', sections, renames ) + ); + + expect( result.current[ 0 ] ).toBe( trafficDefault ); + } ); + it( 'hands out a fresh copy of the default on reset when nothing is stored', () => { const { result } = renderHook( () => useDashboardSectionLayout( 'traffic', sections ) ); diff --git a/projects/packages/premium-analytics/routes/dashboard/hooks/use-dashboard-section-layout/use-dashboard-section-layout.ts b/projects/packages/premium-analytics/routes/dashboard/hooks/use-dashboard-section-layout/use-dashboard-section-layout.ts index cc90be220c33..b42255e0e571 100644 --- a/projects/packages/premium-analytics/routes/dashboard/hooks/use-dashboard-section-layout/use-dashboard-section-layout.ts +++ b/projects/packages/premium-analytics/routes/dashboard/hooks/use-dashboard-section-layout/use-dashboard-section-layout.ts @@ -1,9 +1,18 @@ import { useDispatch, useSelect } from '@wordpress/data'; import { store as preferencesStore } from '@wordpress/preferences'; import { useCallback, useMemo, useState } from 'react'; -import { isDashboardSectionLayouts } from '../../config'; +import { + NO_WIDGET_TYPE_RENAMES, + isDashboardSectionLayouts, + resolveLayoutTypes, +} from '../../config'; import { DASHBOARD_PREFERENCES_SCOPE, DASHBOARD_SECTION_LAYOUTS_KEY } from '../constants'; -import type { DashboardSection, DashboardSectionId, DashboardSectionLayouts } from '../../config'; +import type { + DashboardSection, + DashboardSectionId, + DashboardSectionLayouts, + WidgetTypeName, +} from '../../config'; import type { DashboardWidget } from '@wordpress/widget-dashboard'; const EMPTY_SECTION_LAYOUTS: DashboardSectionLayouts = {}; @@ -21,13 +30,19 @@ type PreferencesActions = { * snapshot would shadow the entity default forever, pinning users who asked to * follow the default to whatever it happened to be at reset time. * + * A layout saved under a former widget type name renders the current type: the items are + * renamed through `renames` on the way out, with no write-back, so the current name persists + * with the section's next commit. + * * @param activeSectionId - Currently active section slug. * @param sections - The available sections, carrying their defaults. + * @param renames - Former widget type names mapped to current ones, from the widget module records. * @return Active section layout, setter, and reset action. */ export function useDashboardSectionLayout( activeSectionId: DashboardSectionId, - sections: DashboardSection[] + sections: DashboardSection[], + renames: ReadonlyMap< string, WidgetTypeName > = NO_WIDGET_TYPE_RENAMES ): [ DashboardWidget[], ( layout: DashboardWidget[] ) => void, () => void ] { const sectionLayouts = useSelect( select => { const value = ( @@ -51,10 +66,11 @@ export function useDashboardSectionLayout( const [ resetCount, setResetCount ] = useState( 0 ); const layout = useMemo( () => { if ( Object.hasOwn( sectionLayouts, activeSectionId ) ) { - return sectionLayouts[ activeSectionId ] ?? sectionDefault; + return resolveLayoutTypes( sectionLayouts[ activeSectionId ] ?? sectionDefault, renames ); } - return resetCount ? [ ...sectionDefault ] : sectionDefault; - }, [ sectionLayouts, activeSectionId, sectionDefault, resetCount ] ); + const fallback = resolveLayoutTypes( sectionDefault, renames ); + return resetCount ? [ ...fallback ] : fallback; + }, [ sectionLayouts, activeSectionId, sectionDefault, resetCount, renames ] ); const setLayout = useCallback( ( nextLayout: DashboardWidget[] ) => { diff --git a/projects/packages/premium-analytics/routes/dashboard/stage.tsx b/projects/packages/premium-analytics/routes/dashboard/stage.tsx index 60b9d2082054..262a48b5a325 100644 --- a/projects/packages/premium-analytics/routes/dashboard/stage.tsx +++ b/projects/packages/premium-analytics/routes/dashboard/stage.tsx @@ -27,7 +27,7 @@ import { } from '@jetpack-premium-analytics/widgets-toolkit'; import { Page } from '@wordpress/admin-ui'; import { Spinner } from '@wordpress/components'; -import { useCallback, useEffect, useState } from '@wordpress/element'; +import { useCallback, useEffect, useMemo, useState } from '@wordpress/element'; import { WidgetDashboard } from '@wordpress/widget-dashboard'; import { isPremiumAnalyticsInitialSyncFinished } from '../site-readiness'; import { useWidgetModules } from '../use-widget-modules'; @@ -41,6 +41,7 @@ import { SectionSyncNotice, } from './components'; import { + buildWidgetTypeRenames, DATE_FILTER_YEAR, isSectionAwaitingSync, offersDateComparison, @@ -69,7 +70,16 @@ import type { DashboardWidget } from '@wordpress/widget-dashboard'; function Dashboard(): JSX.Element { const { sections, hasResolved: hasResolvedSections } = useDashboardSections(); const [ activeSection, setActiveSection ] = useActiveSection( sections ); - const [ layout, setLayout, resetLayout ] = useDashboardSectionLayout( activeSection, sections ); + const widgetModules = useWidgetModules(); + const widgetTypeRenames = useMemo( + () => buildWidgetTypeRenames( widgetModules ), + [ widgetModules ] + ); + const [ layout, setLayout, resetLayout ] = useDashboardSectionLayout( + activeSection, + sections, + widgetTypeRenames + ); const [ gridSettings ] = useDashboardGridSettings(); const canPerform = useDashboardPolicy(); @@ -105,7 +115,6 @@ function Dashboard(): JSX.Element { } }, [ isSyncComplete ] ); - const widgetModules = useWidgetModules(); const resolveWidgetModule = useWidgetModuleResolver( widgetModules ); const [ editMode, setEditMode ] = useState( false ); diff --git a/projects/packages/premium-analytics/src/class-widget-type-registry.php b/projects/packages/premium-analytics/src/class-widget-type-registry.php index 673b4c25ffb8..53f3224e4675 100644 --- a/projects/packages/premium-analytics/src/class-widget-type-registry.php +++ b/projects/packages/premium-analytics/src/class-widget-type-registry.php @@ -37,6 +37,13 @@ final class Widget_Type_Registry { */ private $registered_widget_types = array(); + /** + * Former names of the registered widget types, as `$former_name => $current_name` pairs. + * + * @var string[] + */ + private $former_names = array(); + /** * Whether the registration action has fired. * @@ -112,15 +119,66 @@ public function register( $name, $args = array() ) { return false; } + if ( isset( $this->former_names[ $name ] ) ) { + // One line: tools/replace-next-version-tag.sh only rewrites the token in a single-line call. + _doing_it_wrong( __METHOD__, esc_html( sprintf( /* translators: 1: Widget type name. 2: Widget type name. */ __( 'Widget type "%1$s" is a former name of "%2$s".', 'jetpack-premium-analytics-pkg' ), $name, $this->former_names[ $name ] ) ), 'jetpack-premium-analytics-$$next-version$$' ); + return false; + } + + $former_names = $widget_type ? $widget_type->former_names : ( $args['former_names'] ?? null ); + if ( null !== $former_names && ! $this->former_names_are_free( $name, $former_names ) ) { + return false; + } + if ( ! $widget_type ) { $widget_type = new Widget_Type( $name, $args ); } $this->registered_widget_types[ $name ] = $widget_type; + foreach ( (array) $widget_type->former_names as $former_name ) { + $this->former_names[ $former_name ] = $name; + } return $widget_type; } + /** + * Whether a widget type may claim the given former names. + * + * Each one must be a namespaced lowercase name that no registered type or other former name + * holds; a failure is a `_doing_it_wrong()`. + * + * @param string $name The widget type claiming the names. + * @param mixed $former_names The claimed former names. + * @return bool + */ + private function former_names_are_free( $name, $former_names ) { + $taken = ''; + if ( is_array( $former_names ) ) { + foreach ( $former_names as $former_name ) { + if ( ! is_string( $former_name ) || ! preg_match( '/^[a-z0-9-]+\/[a-z0-9-]+$/', $former_name ) || $former_name === $name ) { + $taken = is_string( $former_name ) ? $former_name : ''; + break; + } + $owner = $this->former_names[ $former_name ] ?? null; + if ( $this->is_registered( $former_name ) || ( null !== $owner && $owner !== $name ) ) { + $taken = $former_name; + break; + } + } + } else { + $taken = (string) $former_names; + } + + if ( '' === $taken && is_array( $former_names ) ) { + return true; + } + + // One line: tools/replace-next-version-tag.sh only rewrites the token in a single-line call. + _doing_it_wrong( __METHOD__, esc_html( sprintf( /* translators: 1: Widget type name. 2: Former name. */ __( 'Widget type "%1$s" cannot claim "%2$s" as a former name: it must be a namespaced lowercase name that no registered widget type holds.', 'jetpack-premium-analytics-pkg' ), $name, $taken ) ), 'jetpack-premium-analytics-$$next-version$$' ); + return false; + } + /** * Unregisters a widget type. * @@ -149,10 +207,31 @@ public function unregister( $name ) { $unregistered_widget_type = $this->registered_widget_types[ $name ]; unset( $this->registered_widget_types[ $name ] ); + $this->former_names = array_filter( + $this->former_names, + static function ( $current_name ) use ( $name ) { + return $current_name !== $name; + } + ); return $unregistered_widget_type; } + /** + * Resolves a possibly former name to the current widget type name. + * + * Does not hydrate: call it after a read, since former names arrive with their types' + * registration. An unknown name comes back unchanged. + * + * @since $$next-version$$ + * + * @param string $name Widget type name, current or former. + * @return string The current name. + */ + public function resolve_name( $name ) { + return $this->former_names[ $name ] ?? $name; + } + /** * Retrieves a registered widget type. * @@ -163,6 +242,7 @@ public function unregister( $name ) { public function get_registered( $name ) { $this->ensure_hydrated(); + $name = $this->resolve_name( $name ); if ( ! $this->is_registered( $name ) ) { return null; } diff --git a/projects/packages/premium-analytics/src/class-widget-type.php b/projects/packages/premium-analytics/src/class-widget-type.php index a229c810310f..03b5b052cf80 100644 --- a/projects/packages/premium-analytics/src/class-widget-type.php +++ b/projects/packages/premium-analytics/src/class-widget-type.php @@ -165,6 +165,16 @@ class Widget_Type { */ public $i18n_manifest = null; + /** + * Names this widget type registered under before the current one, so a layout persisted + * with an old name keeps rendering it. Null when the type was never renamed. + * + * @since $$next-version$$ + * + * @var string[]|null + */ + public $former_names = null; + /** * Constructor. * diff --git a/projects/packages/premium-analytics/src/dashboard-layout.php b/projects/packages/premium-analytics/src/dashboard-layout.php index 83d87d65ec80..4fad744c675b 100644 --- a/projects/packages/premium-analytics/src/dashboard-layout.php +++ b/projects/packages/premium-analytics/src/dashboard-layout.php @@ -86,6 +86,56 @@ function remove_unsupported_default_layout_items( $layout ) { } add_filter( DASHBOARD_DEFAULT_LAYOUT_FILTER, __NAMESPACE__ . '\\remove_unsupported_default_layout_items', 100 ); +/** + * The widget type registry once it can answer, or null before that. + * + * It cannot answer before `init`, without the widget type API loaded, or with nothing registered, + * which is a checkout without a build. + * + * @since $$next-version$$ + * + * @return Widget_Type_Registry|null + */ +function get_answering_widget_type_registry() { + if ( ! did_action( 'init' ) || ! function_exists( __NAMESPACE__ . '\\ensure_widget_registry_ready' ) ) { + return null; + } + + ensure_widget_registry_ready(); + $registry = Widget_Type_Registry::get_instance(); + + return $registry->get_all_registered() ? $registry : null; +} + +/** + * Renames the widget instances whose type is a former name of a registered widget type. + * + * Hooked before the unregistered-type check, so an instance a plugin still adds under an old + * name survives it under the current one. + * + * @since $$next-version$$ + * + * @param array $layout Default widget instances. + * @return array The layout with current type names. + */ +function resolve_former_widget_types_in_default_layout( $layout ) { + $registry = get_answering_widget_type_registry(); + if ( ! $registry || ! is_array( $layout ) ) { + return $layout; + } + + return array_map( + static function ( $item ) use ( $registry ) { + if ( is_array( $item ) && isset( $item['type'] ) ) { + $item['type'] = $registry->resolve_name( $item['type'] ); + } + return $item; + }, + $layout + ); +} +add_filter( DASHBOARD_DEFAULT_LAYOUT_FILTER, __NAMESPACE__ . '\\resolve_former_widget_types_in_default_layout', 99 ); + /** * Drops the widget instances whose type the widget type registry does not know. * @@ -99,15 +149,11 @@ function remove_unsupported_default_layout_items( $layout ) { * @return array The layout minus the instances of unregistered types. */ function remove_unregistered_default_layout_items( $layout ) { - if ( ! did_action( 'init' ) || ! function_exists( __NAMESPACE__ . '\\ensure_widget_registry_ready' ) ) { - return $layout; - } - - ensure_widget_registry_ready(); - $registered = Widget_Type_Registry::get_instance()->get_all_registered(); - if ( empty( $registered ) ) { + $registry = get_answering_widget_type_registry(); + if ( ! $registry ) { return $layout; } + $registered = $registry->get_all_registered(); return array_values( array_filter( diff --git a/projects/packages/premium-analytics/src/widget-modules.php b/projects/packages/premium-analytics/src/widget-modules.php index 3b05b86aabc4..9edda940276f 100644 --- a/projects/packages/premium-analytics/src/widget-modules.php +++ b/projects/packages/premium-analytics/src/widget-modules.php @@ -81,6 +81,7 @@ function get_widget_modules_response() { 'keywords' => $widget_type->keywords, 'textdomain' => $widget_type->textdomain, 'i18n_manifest' => $widget_type->i18n_manifest, + 'former_names' => $widget_type->former_names, ); } diff --git a/projects/packages/premium-analytics/src/widget-types.php b/projects/packages/premium-analytics/src/widget-types.php index 44bdd08c7f0e..263fe18eda02 100644 --- a/projects/packages/premium-analytics/src/widget-types.php +++ b/projects/packages/premium-analytics/src/widget-types.php @@ -45,7 +45,7 @@ * * @since $$next-version$$ */ -const WIDGET_API_VERSION = '1.0.0'; +const WIDGET_API_VERSION = '1.1.0'; /** * Returns the i18n schema describing which widget metadata fields are @@ -296,6 +296,7 @@ function sanitize_widget_icon( $icon ) { * * @type string $textdomain Text domain for the metadata strings of a candidate that declares none. * @type string $i18n_manifest URL of the build's i18n manifest, for a candidate that declares none. + * @type array $former_names Map of widget type name to the names it registered under before, for a candidate that declares none. * } * @param Widget_Type_Registry|null $registry Optional. The registry to write into. Defaults to the main instance. * @return void @@ -328,6 +329,9 @@ function register_widget_types_from_manifest( array $widgets, array $args = arra if ( empty( $widget['i18n_manifest'] ) && ! empty( $args['i18n_manifest'] ) ) { $widget['i18n_manifest'] = $args['i18n_manifest']; } + if ( empty( $widget['former_names'] ) && ! empty( $args['former_names'][ $widget['name'] ] ) ) { + $widget['former_names'] = $args['former_names'][ $widget['name'] ]; + } $widget = translate_widget_metadata( $widget ); @@ -346,11 +350,32 @@ function register_widget_types_from_manifest( array $widgets, array $args = arra 'keywords' => $widget['keywords'] ?? null, 'textdomain' => $widget['textdomain'] ?? null, 'i18n_manifest' => $widget['i18n_manifest'] ?? null, + 'former_names' => sanitize_widget_former_names( $widget['former_names'] ?? null ), ) ); } } +/** + * Normalizes a candidate's former names to a list of strings, or null when it has none. + * + * The registry validates the names themselves when the type registers. + * + * @since $$next-version$$ + * + * @param mixed $former_names The declared former names. + * @return string[]|null + */ +function sanitize_widget_former_names( $former_names ) { + if ( ! is_array( $former_names ) ) { + return null; + } + + $names = array_values( array_unique( array_filter( $former_names, 'is_string' ) ) ); + + return $names ? $names : null; +} + /** * Registers the package's own widget types from its build manifest. * diff --git a/projects/packages/premium-analytics/tests/groups/routes-no-mocks-part1.test.tsx b/projects/packages/premium-analytics/tests/groups/routes-no-mocks-part1.test.tsx index 811ce103c36e..102c3d54bc9f 100644 --- a/projects/packages/premium-analytics/tests/groups/routes-no-mocks-part1.test.tsx +++ b/projects/packages/premium-analytics/tests/groups/routes-no-mocks-part1.test.tsx @@ -4,6 +4,7 @@ import '../../routes/dashboard/components/section-sync-notice/section-sync-notic import '../../routes/dashboard/config/date-filter.test'; import '../../routes/dashboard/config/section-layouts.test'; import '../../routes/dashboard/config/sections.test'; +import '../../routes/dashboard/config/widget-type-renames.test'; import '../../routes/dashboard/hooks/use-dashboard-section-layout/use-dashboard-section-layout.test'; import '../../routes/dashboard/hooks/use-section-date-filter/use-section-date-filter.test'; import '../../routes/detail-header.test'; diff --git a/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php b/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php index 010a4a6b1677..e0b129b652e1 100644 --- a/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php +++ b/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php @@ -274,6 +274,36 @@ static function ( $layout, $section_id ) { $this->assertNotContains( 'example/unregistered', $layout_types, 'A default must not seed a type the site has not registered.' ); } + /** + * An instance a plugin still adds under a former name is renamed, and so survives the + * unregistered-type check under the current one. + */ + public function test_default_renames_an_instance_added_under_a_former_type_name() { + $this->assertInstanceOf( + Widget_Type::class, + register_widget_type( + 'example/current', + array( + 'render_module' => 'example/render', + 'former_names' => array( 'example/former' ), + ) + ) + ); + $this->filter_default_layout( + static function ( $layout, $section_id ) { + if ( 'analytics/traffic' === $section_id ) { + $layout[] = get_dashboard_default_widget_instance( 'example-former', 'example/former', 20 ); + } + return $layout; + } + ); + + $layout_types = $this->served_layout_types( 'analytics/traffic' ); + + $this->assertContains( 'example/current', $layout_types ); + $this->assertNotContains( 'example/former', $layout_types ); + } + /** * Before init the registry cannot hydrate, so the policy leaves the default as declared. */ diff --git a/projects/packages/premium-analytics/tests/php/Widget_Modules_Test.php b/projects/packages/premium-analytics/tests/php/Widget_Modules_Test.php index c452afd4c44e..3cc3c1549636 100644 --- a/projects/packages/premium-analytics/tests/php/Widget_Modules_Test.php +++ b/projects/packages/premium-analytics/tests/php/Widget_Modules_Test.php @@ -108,4 +108,25 @@ public function test_records_carry_the_catalog_location() { $this->assertSame( 'plugin-domain', $records['plugin/catalog-location']['textdomain'] ); $this->assertSame( 'https://example.org/plugin/build/i18n-manifest.json', $records['plugin/catalog-location']['i18n_manifest'] ); } + + /** + * Every record says which former names its type answers to, so the client can render a + * layout saved before a rename. + */ + public function test_records_carry_the_former_names() { + register_widget_type( + 'plugin/renamed', + array( + 'render_module' => 'plugin/widgets/renamed/render', + 'former_names' => array( 'plugin/old-name' ), + ) + ); + register_widget_type( 'plugin/never-renamed', array( 'render_module' => 'plugin/widgets/never-renamed/render' ) ); + + $records = array_column( get_widget_modules_response()->get_data(), null, 'name' ); + + $this->assertSame( array( 'plugin/old-name' ), $records['plugin/renamed']['former_names'] ); + $this->assertNull( $records['plugin/never-renamed']['former_names'] ); + $this->assertArrayNotHasKey( 'plugin/old-name', $records ); + } } diff --git a/projects/packages/premium-analytics/tests/php/Widget_Type_Registry_Test.php b/projects/packages/premium-analytics/tests/php/Widget_Type_Registry_Test.php index db60a3ce0fe9..b9aaf2d79a4c 100644 --- a/projects/packages/premium-analytics/tests/php/Widget_Type_Registry_Test.php +++ b/projects/packages/premium-analytics/tests/php/Widget_Type_Registry_Test.php @@ -407,4 +407,93 @@ public function test_register_widget_types_skips_registered_names() { $this->assertSame( array(), $this->doing_it_wrong ); $this->assertArrayHasKey( self::MANIFEST_WIDGET, get_registered_widget_types() ); } + + /** + * A former name resolves to the current type, without showing up as a type of its own. + */ + public function test_former_names_resolve_to_the_current_type() { + register_widget_type( + 'videopress/top-videos', + array( + 'render_module' => 'videopress/render', + 'former_names' => array( 'jpa/videopress' ), + ) + ); + + $registry = Widget_Type_Registry::get_instance(); + $this->assertSame( 'videopress/top-videos', $registry->resolve_name( 'jpa/videopress' ) ); + $this->assertSame( 'jpa/clicks', $registry->resolve_name( 'jpa/clicks' ) ); + $this->assertSame( 'videopress/top-videos', $registry->get_registered( 'jpa/videopress' )->name ); + $this->assertFalse( $registry->is_registered( 'jpa/videopress' ) ); + $this->assertArrayNotHasKey( 'jpa/videopress', get_registered_widget_types() ); + } + + /** + * A former name another type holds, or a name someone claims as former, is refused. + */ + public function test_former_names_cannot_collide_with_registered_or_claimed_names() { + register_widget_type( 'plugin/taken', array( 'render_module' => 'plugin/taken/render' ) ); + register_widget_type( 'plugin/current', array( 'former_names' => array( 'plugin/old' ) ) ); + $this->capture_doing_it_wrong(); + + $this->assertFalse( register_widget_type( 'plugin/other', array( 'former_names' => array( 'plugin/taken' ) ) ) ); + $this->assertFalse( register_widget_type( 'plugin/another', array( 'former_names' => array( 'plugin/old' ) ) ) ); + $this->assertFalse( register_widget_type( 'plugin/old' ) ); + $this->assertFalse( register_widget_type( 'plugin/shouty', array( 'former_names' => array( 'Plugin/Old' ) ) ) ); + + $this->assertSame( + array( + Widget_Type_Registry::class . '::former_names_are_free', + Widget_Type_Registry::class . '::former_names_are_free', + Widget_Type_Registry::class . '::register', + Widget_Type_Registry::class . '::former_names_are_free', + ), + $this->doing_it_wrong + ); + $this->assertSame( 'plugin/current', Widget_Type_Registry::get_instance()->resolve_name( 'plugin/old' ) ); + } + + /** + * Unregistering a type releases its former names. + */ + public function test_unregister_releases_the_former_names() { + $registry = Widget_Type_Registry::get_instance(); + $registry->register( 'plugin/current', array( 'former_names' => array( 'plugin/old' ) ) ); + + $registry->unregister( 'plugin/current' ); + + $this->assertSame( 'plugin/old', $registry->resolve_name( 'plugin/old' ) ); + $this->assertInstanceOf( Widget_Type::class, $registry->register( 'plugin/old' ) ); + } + + /** + * The manifest helper takes former names from the candidate, or from the registrant's map. + */ + public function test_manifest_helper_stamps_the_former_names_onto_the_type() { + register_widget_types_from_manifest( + array( + array( + 'name' => 'plugin/first', + 'render_module' => 'plugin/first/render', + ), + array( + 'name' => 'plugin/second', + 'render_module' => 'plugin/second/render', + 'former_names' => array( 'jpa/second', 'jpa/second', 42 ), + ), + ), + array( + 'former_names' => array( + 'plugin/first' => array( 'jpa/first' ), + 'plugin/second' => array( 'jpa/ignored' ), + ), + ) + ); + + $registry = Widget_Type_Registry::get_instance(); + $this->assertSame( array( 'jpa/first' ), $registry->get_registered( 'plugin/first' )->former_names ); + $this->assertSame( array( 'jpa/second' ), $registry->get_registered( 'plugin/second' )->former_names ); + $this->assertSame( 'plugin/second', $registry->resolve_name( 'jpa/second' ) ); + $this->assertSame( 'jpa/ignored', $registry->resolve_name( 'jpa/ignored' ) ); + } } From ae0bccb9ad65fd748112323400ff49f0a77be457 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dami=C3=A1n=20Su=C3=A1rez?= Date: Mon, 28 Sep 2026 16:37:33 +0100 Subject: [PATCH 04/22] treat a non-string default instance type as unknown a Widget_Type object as type dropped the whole sections route on PHP 8 --- .../src/dashboard-layout.php | 10 ++++++-- .../tests/php/Dashboard_Layout_Test.php | 25 +++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/projects/packages/premium-analytics/src/dashboard-layout.php b/projects/packages/premium-analytics/src/dashboard-layout.php index 4fad744c675b..fb858fa8be4d 100644 --- a/projects/packages/premium-analytics/src/dashboard-layout.php +++ b/projects/packages/premium-analytics/src/dashboard-layout.php @@ -126,7 +126,7 @@ function resolve_former_widget_types_in_default_layout( $layout ) { return array_map( static function ( $item ) use ( $registry ) { - if ( is_array( $item ) && isset( $item['type'] ) ) { + if ( is_array( $item ) && is_string( $item['type'] ?? null ) ) { $item['type'] = $registry->resolve_name( $item['type'] ); } return $item; @@ -159,7 +159,13 @@ function remove_unregistered_default_layout_items( $layout ) { array_filter( $layout, static function ( $item ) use ( $registered ) { - return ! is_array( $item ) || isset( $registered[ $item['type'] ?? '' ] ); + if ( ! is_array( $item ) ) { + return true; + } + // A non-string type, say the Widget_Type object register_widget_type() returns, is an + // unknown type, not a TypeError for the whole sections route. + $type = $item['type'] ?? ''; + return is_string( $type ) && isset( $registered[ $type ] ); } ) ); diff --git a/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php b/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php index e0b129b652e1..23a5884d39fc 100644 --- a/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php +++ b/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php @@ -304,6 +304,31 @@ static function ( $layout, $section_id ) { $this->assertNotContains( 'example/former', $layout_types ); } + /** + * An instance whose type is not a string, such as the Widget_Type object + * register_widget_type() returns, is an unknown type: dropped, without failing the route. + */ + public function test_default_drops_an_instance_whose_type_is_not_a_string() { + $widget_type = register_widget_type( 'example/object-typed', array( 'render_module' => 'example/render' ) ); + $this->assertInstanceOf( Widget_Type::class, $widget_type ); + $this->filter_default_layout( + static function ( $layout, $section_id ) use ( $widget_type ) { + if ( 'analytics/traffic' === $section_id ) { + $layout[] = get_dashboard_default_widget_instance( 'object-typed', $widget_type, 20 ); + $layout[] = get_dashboard_default_widget_instance( 'array-typed', array( 'example/object-typed' ), 21 ); + $layout[] = get_dashboard_default_widget_instance( 'string-typed', 'example/object-typed', 22 ); + } + return $layout; + } + ); + + $layout_types = $this->served_layout_types( 'analytics/traffic' ); + + $this->assertNotContains( $widget_type, $layout_types ); + $this->assertNotContains( array( 'example/object-typed' ), $layout_types ); + $this->assertSame( array( 'example/object-typed' ), array_values( array_filter( $layout_types, 'is_string' ) ) ); + } + /** * Before init the registry cannot hydrate, so the policy leaves the default as declared. */ From a61759cde9d1892c42a8b9556261dda737c28249 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dami=C3=A1n=20Su=C3=A1rez?= Date: Mon, 28 Sep 2026 18:41:59 +0100 Subject: [PATCH 05/22] keep the malformed-type test within the helper's types build the broken instances by hand for phan; cover the non-instance branch and the sanitizer --- .../tests/php/Dashboard_Layout_Test.php | 29 +++++++++++++++++-- .../tests/php/Widget_Type_Registry_Test.php | 10 +++++++ 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php b/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php index 23a5884d39fc..c16cc7a352f5 100644 --- a/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php +++ b/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php @@ -314,9 +314,14 @@ public function test_default_drops_an_instance_whose_type_is_not_a_string() { $this->filter_default_layout( static function ( $layout, $section_id ) use ( $widget_type ) { if ( 'analytics/traffic' === $section_id ) { - $layout[] = get_dashboard_default_widget_instance( 'object-typed', $widget_type, 20 ); - $layout[] = get_dashboard_default_widget_instance( 'array-typed', array( 'example/object-typed' ), 21 ); - $layout[] = get_dashboard_default_widget_instance( 'string-typed', 'example/object-typed', 22 ); + // What a plugin gets by passing the object register_widget_type() returns, or a list. + $object_typed = get_dashboard_default_widget_instance( 'object-typed', 'example/object-typed', 20 ); + $object_typed['type'] = $widget_type; + $array_typed = get_dashboard_default_widget_instance( 'array-typed', 'example/object-typed', 21 ); + $array_typed['type'] = array( 'example/object-typed' ); + $layout[] = $object_typed; + $layout[] = $array_typed; + $layout[] = get_dashboard_default_widget_instance( 'string-typed', 'example/object-typed', 22 ); } return $layout; } @@ -329,6 +334,24 @@ static function ( $layout, $section_id ) use ( $widget_type ) { $this->assertSame( array( 'example/object-typed' ), array_values( array_filter( $layout_types, 'is_string' ) ) ); } + /** + * Something that is not an instance at all passes through the policy untouched. + */ + public function test_policy_leaves_non_instances_alone() { + $this->register_example_widget_type( 'example/registered' ); + + $layout = remove_unsupported_default_layout_items( + array( + 'not-an-instance', + get_dashboard_default_widget_instance( 'registered', 'example/registered', 20 ), + get_dashboard_default_widget_instance( 'unregistered', 'example/unregistered', 21 ), + ) + ); + + $this->assertSame( array( 'not-an-instance', 'registered' ), array( $layout[0], $layout[1]['uuid'] ) ); + $this->assertCount( 2, $layout ); + } + /** * Before init the registry cannot hydrate, so the policy leaves the default as declared. */ diff --git a/projects/packages/premium-analytics/tests/php/Widget_Type_Registry_Test.php b/projects/packages/premium-analytics/tests/php/Widget_Type_Registry_Test.php index b9aaf2d79a4c..580cd4359dc5 100644 --- a/projects/packages/premium-analytics/tests/php/Widget_Type_Registry_Test.php +++ b/projects/packages/premium-analytics/tests/php/Widget_Type_Registry_Test.php @@ -466,6 +466,16 @@ public function test_unregister_releases_the_former_names() { $this->assertInstanceOf( Widget_Type::class, $registry->register( 'plugin/old' ) ); } + /** + * The sanitizer keeps a list of distinct strings, and nothing else. + */ + public function test_sanitize_widget_former_names_keeps_distinct_strings_only() { + $this->assertNull( sanitize_widget_former_names( null ) ); + $this->assertNull( sanitize_widget_former_names( 'jpa/old' ) ); + $this->assertNull( sanitize_widget_former_names( array( 42, null ) ) ); + $this->assertSame( array( 'jpa/old', 'jpa/older' ), sanitize_widget_former_names( array( 'jpa/old', 42, 'jpa/old', 'jpa/older' ) ) ); + } + /** * The manifest helper takes former names from the candidate, or from the registrant's map. */ From 03114b593a4d72b22e47a452afa88df59249a58e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dami=C3=A1n=20Su=C3=A1rez?= Date: Mon, 28 Sep 2026 20:06:02 +0100 Subject: [PATCH 06/22] expose the leaderboard primitives through the SDK the video plays hook too, provisional; widget contract 1.2.0; the facade must be fully declared --- ...pdate-pa-extensibility-videopress-sdk-exports | 4 ++++ .../premium-analytics-sdk/src/index.d.ts | 16 ++++++++++++++++ ...pdate-pa-extensibility-videopress-sdk-exports | 4 ++++ .../premium-analytics/docs/dashboard-widgets.md | 2 +- .../packages/sdk/src/conformance.ts | 5 +++++ .../premium-analytics/packages/sdk/src/index.ts | 9 +++++++++ .../premium-analytics/src/widget-types.php | 2 +- 7 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 projects/js-packages/premium-analytics-sdk/changelog/update-pa-extensibility-videopress-sdk-exports create mode 100644 projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-sdk-exports diff --git a/projects/js-packages/premium-analytics-sdk/changelog/update-pa-extensibility-videopress-sdk-exports b/projects/js-packages/premium-analytics-sdk/changelog/update-pa-extensibility-videopress-sdk-exports new file mode 100644 index 000000000000..8e6215da4de5 --- /dev/null +++ b/projects/js-packages/premium-analytics-sdk/changelog/update-pa-extensibility-videopress-sdk-exports @@ -0,0 +1,4 @@ +Significance: minor +Type: added + +Declare the leaderboard primitives and the video plays hook. diff --git a/projects/js-packages/premium-analytics-sdk/src/index.d.ts b/projects/js-packages/premium-analytics-sdk/src/index.d.ts index 42875bb70386..77c15c8bb5b2 100644 --- a/projects/js-packages/premium-analytics-sdk/src/index.d.ts +++ b/projects/js-packages/premium-analytics-sdk/src/index.d.ts @@ -27,6 +27,17 @@ export type DataFormat = any; export type CountLabel = any; export type ChartDisplayChartType = any; +// Leaderboards: the chart, its rows and the helpers that size and compare them. +export declare const LeaderboardChart: AnyComponent; +export declare const LeaderboardSkeleton: AnyComponent; +export declare const WIDGET_ROW_LIMIT: number; +export declare function buildLeaderboardRow( ...args: any[] ): any; +export declare function calculateDelta( ...args: any[] ): any; +export declare function getCombinedPeriodMax( ...args: any[] ): any; +export declare function sharePercentage( ...args: any[] ): any; +export declare function useWidgetNavigationSearch( ...args: any[] ): any; +export type LeaderboardChartData = any; + // Widget attributes. export declare function reportParamsAttributeField< Attributes = any >( options?: any ): any; export declare function chartTypeAttributeField< Attributes = any >( options?: any ): any; @@ -50,6 +61,11 @@ export declare function useStatsWordAdsEarnings( ...args: any[] ): any; export type StatsWordAdsResponse = any; export type StatsWordAdsEarningsResponse = any; +// The video plays hook is provisional the same way: shared with the dashboard's Videos report until +// that report moves to the VideoPress package. +export declare function useStatsVideoPlays( ...args: any[] ): any; +export type StatsVideoPlaysComparisonItem = any; + // Ads earnings history, provisional too: shared with the dashboard's Earnings report until that report // moves to the Ads package. export declare const EarningsHistoryList: AnyComponent; diff --git a/projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-sdk-exports b/projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-sdk-exports new file mode 100644 index 000000000000..f08b5cc598c4 --- /dev/null +++ b/projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-sdk-exports @@ -0,0 +1,4 @@ +Significance: minor +Type: added + +Dashboard: Expose the leaderboard primitives and the video plays hook through the SDK; the widget contract is 1.2.0. diff --git a/projects/packages/premium-analytics/docs/dashboard-widgets.md b/projects/packages/premium-analytics/docs/dashboard-widgets.md index 6d2507a1ce6a..32a0b546da78 100644 --- a/projects/packages/premium-analytics/docs/dashboard-widgets.md +++ b/projects/packages/premium-analytics/docs/dashboard-widgets.md @@ -211,7 +211,7 @@ It reads the package's fixed list and, once the registry can answer, the registr `WIDGET_API_VERSION` names the contract a widget is built against: the `@automattic/jetpack-premium-analytics-sdk` module and the exports it declares, the dashboard modules the facade re-exports from (`@jetpack-premium-analytics/widgets-toolkit`, `data`, `fields`, `datetime`, `externals`), and the `Widget_Type` fields the client reads. -The major changes when a widget built against the previous contract stops working; the minor when a consumer can rely on something new. +The major changes when a widget built against the previous contract stops working; the minor when a consumer can rely on something new. So far, 1.1.0 added `former_names` and 1.2.0 the leaderboard primitives and `useStatsVideoPlays`. Inside `plugins/jetpack` the package and a consumer module ship together, so the check is a formality. With the standalone `plugins/premium-analytics` next to another plugin, each brings its own copy, and the check is what keeps a widget built against 1.x from registering on a 2.x package. diff --git a/projects/packages/premium-analytics/packages/sdk/src/conformance.ts b/projects/packages/premium-analytics/packages/sdk/src/conformance.ts index 1e7d9114c7b4..fe81afc579d6 100644 --- a/projects/packages/premium-analytics/packages/sdk/src/conformance.ts +++ b/projects/packages/premium-analytics/packages/sdk/src/conformance.ts @@ -5,3 +5,8 @@ import type * as Api from '@automattic/jetpack-premium-analytics-sdk'; type MissingFromFacade = Exclude< keyof typeof Api, keyof typeof Facade >; export const isComplete: [ MissingFromFacade ] extends [ never ] ? true : MissingFromFacade = true; + +// And when the facade exports a value the API contract does not declare: a consumer could not import it. +type MissingFromApi = Exclude< keyof typeof Facade, keyof typeof Api >; + +export const isDeclared: [ MissingFromApi ] extends [ never ] ? true : MissingFromApi = true; diff --git a/projects/packages/premium-analytics/packages/sdk/src/index.ts b/projects/packages/premium-analytics/packages/sdk/src/index.ts index aff7994c6d2c..ff6f713d1255 100644 --- a/projects/packages/premium-analytics/packages/sdk/src/index.ts +++ b/projects/packages/premium-analytics/packages/sdk/src/index.ts @@ -6,22 +6,31 @@ export { ChartEmptyState, EarningsHistoryList, + LeaderboardChart, + LeaderboardSkeleton, MetricTabsChart, MetricTabsChartSkeleton, MetricTileGrid, MetricTileGridSkeleton, ReportLink, + WIDGET_ROW_LIMIT, WidgetFooter, WidgetRoot, WidgetState, + buildLeaderboardRow, buildMetricTab, + calculateDelta, chartTypeAttributeField, flattenEarningsBreakdown, + getCombinedPeriodMax, + sharePercentage, + useWidgetNavigationSearch, useWidgetRootContext, } from '@jetpack-premium-analytics/widgets-toolkit'; export { ReportScopeProvider, chartInterval, + useStatsVideoPlays, useStatsWordAdsEarnings, useStatsWordAdsStats, } from '@jetpack-premium-analytics/data'; diff --git a/projects/packages/premium-analytics/src/widget-types.php b/projects/packages/premium-analytics/src/widget-types.php index 263fe18eda02..97cd4db163c9 100644 --- a/projects/packages/premium-analytics/src/widget-types.php +++ b/projects/packages/premium-analytics/src/widget-types.php @@ -45,7 +45,7 @@ * * @since $$next-version$$ */ -const WIDGET_API_VERSION = '1.1.0'; +const WIDGET_API_VERSION = '1.2.0'; /** * Returns the i18n schema describing which widget metadata fields are From b185bafb8337180804eb444cbe2237a6609ed4ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dami=C3=A1n=20Su=C3=A1rez?= Date: Tue, 29 Sep 2026 08:26:10 +0100 Subject: [PATCH 07/22] move the Top videos widget to packages/videopress type videopress/top-videos, former jpa/videopress; the Traffic seed moves too --- pnpm-lock.yaml | 24 ++ ...ate-pa-extensibility-videopress-top-videos | 4 + .../docs/dashboard-sections.md | 4 +- .../widgets-toolkit/src/helpers/index.ts | 1 - .../packages/widgets-toolkit/src/index.ts | 2 - .../src/default-dashboard-sections.php | 9 +- .../src/widget-type-support.php | 4 +- .../tests/groups/widgets-no-mocks.test.tsx | 1 - .../widgets-shared-route-mock-part2.test.tsx | 1 - .../tests/php/Dashboard_Layout_Test.php | 17 +- .../tests/php/Widget_Availability_Test.php | 12 +- .../__tests__/build-video-plays-data.test.ts | 106 --------- .../videopress/__tests__/videopress.test.tsx | 187 --------------- .../widgets/videopress/package.json | 17 -- .../stories/videopress-widget.stories.tsx | 174 -------------- projects/packages/videopress/.gitattributes | 1 + projects/packages/videopress/README.md | 6 + ...ate-pa-extensibility-videopress-top-videos | 4 + projects/packages/videopress/composer.json | 10 +- projects/packages/videopress/package.json | 8 + .../src/class-analytics-dashboard.php | 215 ++++++++++++++++++ .../videopress/src/class-initializer.php | 1 + .../tests/php/Analytics_Dashboard_Test.php | 188 +++++++++++++++ ...cs_Dashboard_Without_Widget_Types_Test.php | 58 +++++ .../analytics-dashboard-manifest-fixture.php | 27 +++ projects/packages/videopress/tsconfig.json | 1 + .../top-videos}/build-video-plays-data.ts | 13 +- .../widgets/top-videos/package.json | 13 ++ .../widgets/top-videos}/render.tsx | 36 ++- .../widgets/top-videos}/style.module.css | 0 .../test/build-video-plays-data.test.ts | 97 ++++++++ .../widgets/top-videos/video-plays.ts | 34 +++ .../widgets/top-videos}/widget.json | 5 +- .../widgets/top-videos}/widget.ts | 4 +- ...ate-pa-extensibility-videopress-top-videos | 4 + projects/plugins/jetpack/composer.lock | 10 +- ...ate-pa-extensibility-videopress-top-videos | 4 + ...ate-pa-extensibility-videopress-top-videos | 3 + projects/plugins/videopress/composer.lock | 10 +- 39 files changed, 768 insertions(+), 547 deletions(-) create mode 100644 projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-top-videos delete mode 100644 projects/packages/premium-analytics/widgets/videopress/__tests__/build-video-plays-data.test.ts delete mode 100644 projects/packages/premium-analytics/widgets/videopress/__tests__/videopress.test.tsx delete mode 100644 projects/packages/premium-analytics/widgets/videopress/package.json delete mode 100644 projects/packages/premium-analytics/widgets/videopress/stories/videopress-widget.stories.tsx create mode 100644 projects/packages/videopress/changelog/update-pa-extensibility-videopress-top-videos create mode 100644 projects/packages/videopress/src/class-analytics-dashboard.php create mode 100644 projects/packages/videopress/tests/php/Analytics_Dashboard_Test.php create mode 100644 projects/packages/videopress/tests/php/Analytics_Dashboard_Without_Widget_Types_Test.php create mode 100644 projects/packages/videopress/tests/php/mocks/analytics-dashboard-manifest-fixture.php rename projects/packages/{premium-analytics/widgets/videopress => videopress/widgets/top-videos}/build-video-plays-data.ts (77%) create mode 100644 projects/packages/videopress/widgets/top-videos/package.json rename projects/packages/{premium-analytics/widgets/videopress => videopress/widgets/top-videos}/render.tsx (77%) rename projects/packages/{premium-analytics/widgets/videopress => videopress/widgets/top-videos}/style.module.css (100%) create mode 100644 projects/packages/videopress/widgets/top-videos/test/build-video-plays-data.test.ts create mode 100644 projects/packages/videopress/widgets/top-videos/video-plays.ts rename projects/packages/{premium-analytics/widgets/videopress => videopress/widgets/top-videos}/widget.json (77%) rename projects/packages/{premium-analytics/widgets/videopress => videopress/widgets/top-videos}/widget.ts (70%) create mode 100644 projects/plugins/jetpack/changelog/update-pa-extensibility-videopress-top-videos create mode 100644 projects/plugins/premium-analytics/changelog/update-pa-extensibility-videopress-top-videos create mode 100644 projects/plugins/videopress/changelog/update-pa-extensibility-videopress-top-videos diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a4429bee7781..1e0d6aab8a0b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -5074,6 +5074,9 @@ importers: '@automattic/jetpack-connection': specifier: workspace:* version: link:../../js-packages/connection + '@automattic/jetpack-premium-analytics-sdk': + specifier: workspace:* + version: link:../../js-packages/premium-analytics-sdk '@automattic/jetpack-script-data': specifier: workspace:* version: link:../../js-packages/script-data @@ -5161,6 +5164,9 @@ importers: '@wordpress/url': specifier: 4.55.0 version: 4.55.0 + '@wordpress/widget-primitives': + specifier: 0.7.0 + version: 0.7.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(postcss@8.5.23)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) clsx: specifier: 2.1.1 version: 2.1.1 @@ -30799,6 +30805,24 @@ snapshots: - supports-color - vite + '@wordpress/widget-primitives@0.7.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(postcss@8.5.23)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + '@wordpress/dataviews': 19.0.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(postcss@8.5.23)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@wordpress/element': 8.7.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + optionalDependencies: + '@types/react': 18.3.31 + transitivePeerDependencies: + - '@emotion/is-prop-valid' + - '@types/react-dom' + - esbuild + - lightningcss + - postcss + - stylelint + - supports-color + - vite + '@wordpress/widget-primitives@0.7.0(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': dependencies: '@wordpress/dataviews': 19.0.0(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) diff --git a/projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-top-videos b/projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-top-videos new file mode 100644 index 000000000000..ee30a2ad1627 --- /dev/null +++ b/projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-top-videos @@ -0,0 +1,4 @@ +Significance: minor +Type: removed + +Dashboard: Move the Top videos widget to the VideoPress package, which registers it and seeds it into the Traffic section. diff --git a/projects/packages/premium-analytics/docs/dashboard-sections.md b/projects/packages/premium-analytics/docs/dashboard-sections.md index 316acab2bf21..90aeb8839c92 100644 --- a/projects/packages/premium-analytics/docs/dashboard-sections.md +++ b/projects/packages/premium-analytics/docs/dashboard-sections.md @@ -81,7 +81,7 @@ add_action( 'is_available' => array( Capabilities::class, 'current_user_can_view_analytics' ), 'default_layout' => static function () { return array( - get_dashboard_default_widget_instance( 'videopress-top-videos', 'jpa/videopress', 0, 3, 2 ), + get_dashboard_default_widget_instance( 'videopress-top-videos', 'videopress/top-videos', 0, 3, 2 ), ); }, ) @@ -140,7 +140,7 @@ add_filter( 'jetpack_premium_analytics_dashboard_default_layout', static function ( $layout, $section_id ) { if ( 'analytics/traffic' === $section_id ) { - $layout[] = get_dashboard_default_widget_instance( 'videopress-top-videos', 'jpa/videopress', 8, 1, 2 ); + $layout[] = get_dashboard_default_widget_instance( 'videopress-top-videos', 'videopress/top-videos', 8, 1, 2 ); } return $layout; diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/index.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/index.ts index ae9ef4df2475..5a73feafaf6f 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/index.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/index.ts @@ -64,7 +64,6 @@ export { } from './build-csv'; export { sharePercentage } from './share-percentage'; export { getCombinedPeriodMax } from './get-combined-period-max'; -export { getVideoKey, getVideoLabel } from './video-plays'; export { describeError } from './describe-error'; export { summaryCount } from './summary-count'; export { toDay } from './to-day'; diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/index.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/index.ts index aad30ba2b8fc..5d5caf4ab269 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/index.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/index.ts @@ -236,8 +236,6 @@ export { type CsvDateRange, getCombinedPeriodMax, sharePercentage, - getVideoKey, - getVideoLabel, describeError, summaryCount, toDay, diff --git a/projects/packages/premium-analytics/src/default-dashboard-sections.php b/projects/packages/premium-analytics/src/default-dashboard-sections.php index d3c5b09814e0..0bdef2a2d269 100644 --- a/projects/packages/premium-analytics/src/default-dashboard-sections.php +++ b/projects/packages/premium-analytics/src/default-dashboard-sections.php @@ -136,7 +136,7 @@ function get_traffic_section_default_layout() { 1, 2 ), - // Row 4: UTM insights + clicks + VideoPress (sites running VideoPress only). + // Row 4: UTM insights + clicks; the VideoPress package seeds Top videos at order 8. get_dashboard_default_widget_instance( 'default-utm-insights-widget-instance', 'jpa/utm-insights', @@ -154,13 +154,6 @@ function get_traffic_section_default_layout() { 1, 2 ), - get_dashboard_default_widget_instance( - 'default-videopress-widget-instance', - 'jpa/videopress', - 8, - 1, - 2 - ), // Row 5: authors + search terms + file downloads (Simple only). get_dashboard_default_widget_instance( 'default-authors-widget-instance', diff --git a/projects/packages/premium-analytics/src/widget-type-support.php b/projects/packages/premium-analytics/src/widget-type-support.php index 5cddcf903c59..10b07240bc0b 100644 --- a/projects/packages/premium-analytics/src/widget-type-support.php +++ b/projects/packages/premium-analytics/src/widget-type-support.php @@ -19,10 +19,10 @@ } /** - * Widget types that only have data on a site running VideoPress. + * Widget types that only have data on a site running VideoPress. The Top videos widget is not + * listed: the VideoPress package registers it, and decides where. */ const VIDEOPRESS_WIDGET_TYPES = array( - 'jpa/videopress', 'jpa/video-detail-views-performance', 'jpa/video-detail-embeds', ); diff --git a/projects/packages/premium-analytics/tests/groups/widgets-no-mocks.test.tsx b/projects/packages/premium-analytics/tests/groups/widgets-no-mocks.test.tsx index 4563488be906..fdb6c138aca3 100644 --- a/projects/packages/premium-analytics/tests/groups/widgets-no-mocks.test.tsx +++ b/projects/packages/premium-analytics/tests/groups/widgets-no-mocks.test.tsx @@ -4,4 +4,3 @@ import '../../widgets/authors/__tests__/build-top-authors-data.test'; import '../../widgets/popular-days/__tests__/bucket-views-by-weekday.test'; import '../../widgets/shares/__tests__/use-share-views.test'; import '../../widgets/stories/preset-for-story-interval.test'; -import '../../widgets/videopress/__tests__/build-video-plays-data.test'; diff --git a/projects/packages/premium-analytics/tests/groups/widgets-shared-route-mock-part2.test.tsx b/projects/packages/premium-analytics/tests/groups/widgets-shared-route-mock-part2.test.tsx index f11e8cf3e6b5..087ae975f1c3 100644 --- a/projects/packages/premium-analytics/tests/groups/widgets-shared-route-mock-part2.test.tsx +++ b/projects/packages/premium-analytics/tests/groups/widgets-shared-route-mock-part2.test.tsx @@ -8,4 +8,3 @@ import '../../widgets/subscriber-highlights/__tests__/subscriber-highlights.test import '../../widgets/subscribers-list/__tests__/subscribers-list.test'; import '../../widgets/tags/__tests__/tags.test'; import '../../widgets/video-detail-embeds/__tests__/video-detail-embeds.test'; -import '../../widgets/videopress/__tests__/videopress.test'; diff --git a/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php b/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php index c16cc7a352f5..f0dc1876bdcc 100644 --- a/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php +++ b/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php @@ -171,19 +171,10 @@ public function test_traffic_default_excludes_simple_only_widgets_on_self_hosted } /** - * The Top videos instance follows VideoPress, which this test env lacks. + * Nothing here seeds Top videos: the VideoPress package appends it at order 8. */ - public function test_traffic_default_excludes_videopress_widget_without_videopress() { - $this->assertNotContains( 'jpa/videopress', $this->served_layout_types( 'analytics/traffic' ), 'Top videos must not be part of the default layout without VideoPress.' ); - } - - /** - * With VideoPress, the Top videos instance is back in the default layout. - */ - public function test_traffic_default_keeps_videopress_widget_with_videopress() { - add_filter( VIDEOPRESS_AVAILABLE_FILTER, '__return_true' ); - - $this->assertContains( 'jpa/videopress', $this->served_layout_types( 'analytics/traffic' ) ); + public function test_traffic_default_leaves_top_videos_to_the_videopress_package() { + $this->assertNotContains( 8, array_column( array_column( get_traffic_section_default_layout(), 'placement' ), 'order' ) ); } /** @@ -437,7 +428,6 @@ public function test_traffic_section_declares_the_bundled_widgets() { 'default-top-platforms-widget-instance' => array( 'jpa/top-platforms', 1, 2, 5 ), 'default-utm-insights-widget-instance' => array( 'jpa/utm-insights', 1, 2, 6 ), 'default-clicks-widget-instance' => array( 'jpa/clicks', 1, 2, 7 ), - 'default-videopress-widget-instance' => array( 'jpa/videopress', 1, 2, 8 ), 'default-authors-widget-instance' => array( 'jpa/authors', 1, 2, 9 ), 'default-search-terms-widget-instance' => array( 'jpa/search-terms', 1, 2, 10 ), 'default-file-downloads-widget-instance' => array( 'jpa/file-downloads', 1, 2, 11 ), @@ -484,7 +474,6 @@ public function test_insights_section_declares_the_bundled_widgets() { ); $this->assertNotContains( 'jpa/authors', $layout_types ); - $this->assertNotContains( 'jpa/videopress', $layout_types ); // Emails is not an Insights module — it lives on the Subscribers tab. $this->assertNotContains( 'jpa/stats-emails', $layout_types ); // The Comments module ships as two focused widgets, not one toggled widget. diff --git a/projects/packages/premium-analytics/tests/php/Widget_Availability_Test.php b/projects/packages/premium-analytics/tests/php/Widget_Availability_Test.php index b30dca36e33f..f789e27647bf 100644 --- a/projects/packages/premium-analytics/tests/php/Widget_Availability_Test.php +++ b/projects/packages/premium-analytics/tests/php/Widget_Availability_Test.php @@ -75,7 +75,7 @@ private function widget_candidates() { 'category' => 'traffic', ), array( - 'name' => 'jpa/videopress', + 'name' => 'jpa/video-detail-embeds', 'category' => 'stats', ), array( @@ -256,7 +256,7 @@ static function ( $name ) { public function test_type_policy_keeps_video_widgets_with_videopress() { $names = $this->available_names( false, true ); - $this->assertContains( 'jpa/videopress', $names ); + $this->assertContains( 'jpa/video-detail-embeds', $names ); $this->assertContains( 'jpa/video-detail-views-performance', $names ); } @@ -342,7 +342,7 @@ public function test_registry_callback_removes_video_widgets_without_videopress( 'name' ); - $this->assertNotContains( 'jpa/videopress', $names ); + $this->assertNotContains( 'jpa/video-detail-views-performance', $names ); } /** @@ -360,7 +360,7 @@ public function test_registry_callback_follows_the_plan_feature_on_atomic() { 'name' ); - $this->assertNotContains( 'jpa/videopress', $names, 'An active module does not stand in for the plan feature on Atomic.' ); + $this->assertNotContains( 'jpa/video-detail-views-performance', $names, 'An active module does not stand in for the plan feature on Atomic.' ); $GLOBALS['jpa_test_wpcom_features'] = array( 'videopress' ); @@ -369,7 +369,7 @@ public function test_registry_callback_follows_the_plan_feature_on_atomic() { 'name' ); - $this->assertContains( 'jpa/videopress', $names, 'The plan feature brings the video widgets back on Atomic.' ); + $this->assertContains( 'jpa/video-detail-views-performance', $names, 'The plan feature brings the video widgets back on Atomic.' ); } /** @@ -383,7 +383,7 @@ public function test_registry_callback_keeps_video_widgets_with_videopress() { 'name' ); - $this->assertContains( 'jpa/videopress', $names ); + $this->assertContains( 'jpa/video-detail-views-performance', $names ); } /** diff --git a/projects/packages/premium-analytics/widgets/videopress/__tests__/build-video-plays-data.test.ts b/projects/packages/premium-analytics/widgets/videopress/__tests__/build-video-plays-data.test.ts deleted file mode 100644 index b7d19aee97dd..000000000000 --- a/projects/packages/premium-analytics/widgets/videopress/__tests__/build-video-plays-data.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -/** - * Internal dependencies - */ -import { toVideoPlaysRows } from '../build-video-plays-data'; -import { mergeStatsVideoPlaysComparisonRows } from '@jetpack-premium-analytics/data'; -import type { StatsNormalizedReport, StatsVideoPlaysItem } from '@jetpack-premium-analytics/data'; - -const report = ( - items: Array< Partial< StatsVideoPlaysItem > > -): StatsNormalizedReport< StatsVideoPlaysItem > => - ( { - summary: {}, - data: [ { date: '2026-06-16', items } ], - } ) as unknown as StatsNormalizedReport< StatsVideoPlaysItem >; - -// The widget consumes rows the data layer has already matched across periods; -// run the real merge here so the tests exercise the same pipeline. -const buildRows = ( - primary: StatsNormalizedReport< StatsVideoPlaysItem > | undefined, - comparison: StatsNormalizedReport< StatsVideoPlaysItem > | undefined, - maxRows?: number -) => toVideoPlaysRows( mergeStatsVideoPlaysComparisonRows( primary, comparison, maxRows ).rows ); - -describe( 'toVideoPlaysRows', () => { - it( 'matches comparison plays by stable video id, not by row order', () => { - const rows = buildRows( - report( [ - { id: 101, label: 'Walkthrough', link: 'https://example.com/a/', plays: 100 }, - { id: 102, label: 'Launch', link: 'https://example.com/b/', plays: 50 }, - ] ), - // Reversed order, and only one overlapping video. - report( [ { id: 102, label: 'Launch', link: 'https://example.com/b/', plays: 80 } ] ) - ); - - expect( rows ).toEqual( [ - expect.objectContaining( { key: '101', plays: 100, previousPlays: undefined } ), - expect.objectContaining( { key: '102', plays: 50, previousPlays: 80 } ), - ] ); - } ); - - it( 'keeps previousPlays undefined (not zero) for videos missing from the comparison period', () => { - const rows = buildRows( - report( [ { id: 101, label: 'Walkthrough', link: null, plays: 100 } ] ), - report( [] ) - ); - - expect( rows[ 0 ].previousPlays ).toBeUndefined(); - } ); - - it( 'treats a real comparison value of zero as data, not as missing', () => { - const rows = buildRows( - report( [ { id: 101, label: 'Walkthrough', link: null, plays: 100 } ] ), - report( [ { id: 101, label: 'Walkthrough', link: null, plays: 0 } ] ) - ); - - expect( rows[ 0 ].previousPlays ).toBe( 0 ); - } ); - - it( 'carries the video link and falls back to an untitled label', () => { - const rows = buildRows( - report( [ { id: 107, label: '', link: 'https://example.com/video/107/', plays: 10 } ] ), - undefined - ); - - expect( rows[ 0 ] ).toEqual( { - id: 107, - key: '107', - label: 'Untitled video', - link: 'https://example.com/video/107/', - plays: 10, - previousPlays: undefined, - } ); - } ); - - it( 'keys untitled videos without an id by their link so they do not collapse', () => { - const rows = buildRows( - report( [ - { label: '', link: 'https://example.com/video/1/', plays: 10 }, - { label: '', link: 'https://example.com/video/2/', plays: 5 }, - ] ), - undefined - ); - - expect( rows.map( row => row.key ) ).toEqual( [ - 'https://example.com/video/1/', - 'https://example.com/video/2/', - ] ); - } ); - - it( 'limits rows to maxRows before matching, so hidden rows cannot enable comparison', () => { - const merged = mergeStatsVideoPlaysComparisonRows( - report( [ - { id: 101, label: 'Walkthrough', link: null, plays: 100 }, - { id: 102, label: 'Launch', link: null, plays: 50 }, - ] ), - // Only the second (hidden once maxRows applies) video overlaps. - report( [ { id: 102, label: 'Launch', link: null, plays: 80 } ] ), - 1 - ); - - expect( merged.hasComparison ).toBe( false ); - expect( toVideoPlaysRows( merged.rows ) ).toEqual( [ - expect.objectContaining( { key: '101', plays: 100, previousPlays: undefined } ), - ] ); - } ); -} ); diff --git a/projects/packages/premium-analytics/widgets/videopress/__tests__/videopress.test.tsx b/projects/packages/premium-analytics/widgets/videopress/__tests__/videopress.test.tsx deleted file mode 100644 index acb63d154bdf..000000000000 --- a/projects/packages/premium-analytics/widgets/videopress/__tests__/videopress.test.tsx +++ /dev/null @@ -1,187 +0,0 @@ -/** - * External dependencies - */ -import { GlobalErrorProvider, queryClient } from '@jetpack-premium-analytics/data'; -import { render, screen } from '@testing-library/react'; -import apiFetch from '@wordpress/api-fetch'; -import type { ReactElement } from 'react'; -/** - * Internal dependencies - */ -import VideoPressWidget from '../render'; - -jest.mock( '@wordpress/api-fetch', () => jest.fn() ); - -// WidgetRoot reads URL search params as a fallback for report params; outside -// a matched route the real hook warns and throws. -jest.mock( '@wordpress/route', () => jest.requireActual( '../../test-utils' ).mockWordPressRoute ); - -const mockApiFetch = apiFetch as unknown as jest.Mock; - -// Build a raw Stats "video-plays" response that satisfies both the summarized -// (multi-day) and single-day read paths of `sanitizeStatsVideoPlaysResponse`. -const buildResponse = ( - videos: Array< { post_id?: number; title: string; plays: number; url?: string | null } > -) => { - const date = '2026-06-16'; - const rows = videos.map( video => ( { - post_id: video.post_id, - title: video.title, - url: video.url === undefined ? `https://example.com/video/${ video.post_id }/` : video.url, - plays: video.plays, - impressions: video.plays * 2, - watch_time: video.plays * 10, - retention_rate: 60, - } ) ); - - return { date, period: 'day', summary: { plays: rows }, days: { [ date ]: { plays: rows } } }; -}; - -const VIDEO_PLAYS_RESPONSE = buildResponse( [ - { post_id: 101, title: 'Getting Started Walkthrough', plays: 3820 }, - { post_id: 102, title: 'Product Launch Highlights', plays: 2640 }, -] ); - -// The dashboard wraps widgets in a GlobalErrorProvider, so mirror it here to -// render the widget as it runs in product. -const renderInDashboard = ( ui: ReactElement ) => - render( { ui } ); - -describe( 'VideoPressWidget', () => { - beforeEach( () => { - // The data package's query client is a module-level singleton; drop its - // cache so each test starts from a fresh fetch. - queryClient.clear(); - mockApiFetch.mockReset(); - mockApiFetch.mockResolvedValue( VIDEO_PLAYS_RESPONSE ); - } ); - - it( 'renders the fetched videos as leaderboard rows', async () => { - renderInDashboard( - - ); - - await expect( screen.findByText( 'Getting Started Walkthrough' ) ).resolves.toBeInTheDocument(); - expect( screen.getByText( 'Product Launch Highlights' ) ).toBeInTheDocument(); - } ); - - it( 'links each ID-backed title internally with the shared date window and no icon link', async () => { - renderInDashboard( - - ); - - const detailLink = await screen.findByRole( 'link', { - name: 'Getting Started Walkthrough', - } ); - expect( detailLink ).toHaveAttribute( - 'href', - '/video/101?from=2026-06-01&to=2026-06-16&interval=day&date_type=created' - ); - expect( detailLink ).not.toHaveAttribute( 'target' ); - expect( detailLink ).toHaveAttribute( 'title', 'Getting Started Walkthrough' ); - expect( - screen.queryByRole( 'link', { - name: /Open Getting Started Walkthrough in a new tab/, - } ) - ).not.toBeInTheDocument(); - } ); - - it( 'keeps the external title link when a row has no numeric ID', async () => { - mockApiFetch.mockResolvedValue( - buildResponse( [ - { - title: 'Legacy video', - plays: 12, - url: 'https://example.com/video/legacy/', - }, - ] ) - ); - - renderInDashboard( - - ); - - const link = await screen.findByRole( 'link', { name: /Legacy video/ } ); - expect( link ).toHaveAttribute( 'href', 'https://example.com/video/legacy/' ); - expect( link ).toHaveAttribute( 'target', '_blank' ); - expect( link ).toHaveAttribute( 'rel', 'noopener noreferrer' ); - expect( link ).toHaveAttribute( 'title', 'Legacy video' ); - expect( - screen.queryByRole( 'link', { name: /Open Legacy video in a new tab/ } ) - ).not.toBeInTheDocument(); - } ); - - it( 'keeps the title tooltip when a row has neither an ID nor a URL', async () => { - mockApiFetch.mockResolvedValue( - buildResponse( [ { title: 'Unlinked video', plays: 8, url: null } ] ) - ); - - renderInDashboard( - - ); - - const title = await screen.findByText( 'Unlinked video' ); - expect( title ).not.toHaveRole( 'link' ); - // The tooltip lives on the plain-branch wrapper; the label itself sits in - // the inner text span shared by every branch. - expect( screen.getByTitle( 'Unlinked video' ) ).toBeInTheDocument(); - } ); - - it( 'requests the dashboard date range from report params', async () => { - renderInDashboard( - - ); - - await expect( screen.findByText( 'Getting Started Walkthrough' ) ).resolves.toBeInTheDocument(); - - const requestedPath = mockApiFetch.mock.calls[ 0 ]?.[ 0 ]?.path ?? ''; - expect( requestedPath ).toContain( 'stats/video-plays' ); - // The query factory derives the Stats date params from `reportParams`: - // `from` becomes `start_date` and `to` becomes the end `date`. - expect( requestedPath ).toContain( 'start_date=2026-03-01' ); - expect( requestedPath ).toContain( 'date=2026-03-10' ); - expect( requestedPath ).not.toContain( 'days=' ); - } ); - - it( 'links to the Videos report', () => { - renderInDashboard( - - ); - - expect( screen.getByRole( 'link', { name: 'View all' } ) ).toHaveAttribute( - 'href', - expect.stringContaining( '/reports/videos' ) - ); - } ); - - it( 'shows the generic empty state and keeps the View all link when the period has no video plays', async () => { - mockApiFetch.mockResolvedValue( buildResponse( [] ) ); - - renderInDashboard( - - ); - - await expect( - screen.findByText( 'We couldn’t find results for this time period.' ) - ).resolves.toBeInTheDocument(); - expect( screen.getByRole( 'link', { name: 'View all' } ) ).toHaveAttribute( - 'href', - expect.stringContaining( '/reports/videos' ) - ); - } ); - - it( 'shows the error state with a retry action when the request fails', async () => { - // Reject with a non-retryable (403) error so React Query surfaces the - // error state immediately instead of retrying with backoff. - mockApiFetch.mockRejectedValue( { status: 403, message: 'Forbidden' } ); - - renderInDashboard( - - ); - - await expect( - screen.findByText( "We couldn't load video plays. Please try again in a moment." ) - ).resolves.toBeInTheDocument(); - expect( screen.getByRole( 'button', { name: 'Retry' } ) ).toBeInTheDocument(); - } ); -} ); diff --git a/projects/packages/premium-analytics/widgets/videopress/package.json b/projects/packages/premium-analytics/widgets/videopress/package.json deleted file mode 100644 index f44320854098..000000000000 --- a/projects/packages/premium-analytics/widgets/videopress/package.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "@automattic/jetpack-premium-analytics-widget-videopress", - "version": "0.1.0-alpha", - "private": true, - "type": "module", - "dependencies": { - "@jetpack-premium-analytics/data": "link:../../packages/data", - "@jetpack-premium-analytics/routing": "link:../../packages/routing", - "@jetpack-premium-analytics/widgets-toolkit": "link:../../packages/widgets-toolkit", - "@wordpress/i18n": "^6.9.0", - "@wordpress/icons": "^16.0.0", - "@wordpress/route": "0.21.0", - "@wordpress/ui": "0.22.0", - "@wordpress/widget-primitives": "0.7.0", - "react": "18.3.1" - } -} diff --git a/projects/packages/premium-analytics/widgets/videopress/stories/videopress-widget.stories.tsx b/projects/packages/premium-analytics/widgets/videopress/stories/videopress-widget.stories.tsx deleted file mode 100644 index 30901fbe6285..000000000000 --- a/projects/packages/premium-analytics/widgets/videopress/stories/videopress-widget.stories.tsx +++ /dev/null @@ -1,174 +0,0 @@ -/** - * External dependencies - */ -import { getDefaultQueryParams, type PresetType } from '@jetpack-premium-analytics/data'; -/** - * Internal dependencies - */ -import { - registerReportMocks, - setReportMockState, -} from '../../../packages/widgets-toolkit/src/stories/mocks/register-report-mocks'; -import { - DEFAULT_WIDGET_DASHBOARD_STORY_ARGS, - WidgetDashboardWithWidget as WidgetDashboardWithWidgetStory, - widgetDashboardWithWidgetArgTypes, - type WidgetDashboardWithWidgetControls, -} from '../../stories/widget-dashboard-with-widget'; -import { withStoryRouter } from '../../stories/with-story-router'; -import { createStoryWidgetType } from '../../stories/create-story-widget-type'; -import { withWidgetCanvas } from '../../stories/with-widget-canvas'; -import VideoPressRender from '../render'; -import widgetDefinition from '../widget'; -import widgetManifest from '../widget.json'; -import type { Meta, StoryObj } from '@storybook/react'; -import type { WidgetRenderProps } from '@wordpress/widget-primitives'; -import type { ComponentProps, ComponentType } from 'react'; - -registerReportMocks(); - -const VIDEOPRESS_RENDER_MODULE = 'storybook/videopress'; - -// Widget-specific story control: toggles the previous-period comparison. -interface VideoPressStoryControls { - /** - * Whether to request the previous-period comparison. - */ - withComparison: boolean; -} - -/** - * Render the data-connected VideoPress widget with report params derived from - * the `withComparison` control, so the close-up stories exercise the real data - * flow (served by `registerReportMocks`). - */ -function renderVideoPress( { withComparison }: VideoPressStoryControls ) { - return ( - - ); -} - -// Distinct preset → own query-cache entry; see forceStatsMockState. -function renderVideoPressOnPreset( preset: PresetType ) { - return ( - - ); -} - -const meta = { - title: 'Packages/Premium Analytics/Widgets/VideoPress', - component: VideoPressRender, - tags: [ 'autodocs' ], - argTypes: { - withComparison: { control: 'boolean' }, - }, - parameters: { - docs: { - description: { - component: - "Dashboard widget showing the site's most played VideoPress videos as a leaderboard, with internal video-detail links and optional period-over-period comparison. It is sourced from the Jetpack Stats `video-plays` module via `useStatsVideoPlays`; in Storybook the data is served by `registerReportMocks`.", - }, - }, - }, -} satisfies Meta< ComponentProps< typeof VideoPressRender > & VideoPressStoryControls >; - -export default meta; - -type Story = StoryObj< VideoPressStoryControls >; - -/** - * The widget on its own, current period only. - */ -export const Default: Story = { - render: renderVideoPress, - args: { withComparison: false }, - decorators: [ withWidgetCanvas, withStoryRouter ], -}; - -/** - * Same close-up with each video's period-over-period delta (green for gains, - * red for losses) driven by the mocked comparison window. - */ -export const WithComparison: Story = { - render: renderVideoPress, - args: { withComparison: true }, - decorators: [ withWidgetCanvas, withStoryRouter ], -}; - -/** - * First load: the fetch is in flight, so the widget shows its loading state. The - * mock is forced to never resolve for the duration of this story. - */ -export const Loading: Story = { - render: () => renderVideoPressOnPreset( 'last-90-days' ), - // Off the shared autodocs page — path-keyed override; see forceStatsMockState. - tags: [ '!autodocs' ], - decorators: [ withWidgetCanvas, withStoryRouter ], - beforeEach: () => { - setReportMockState( 'stats/video-plays', 'loading' ); - return () => setReportMockState( 'stats/video-plays', null ); - }, -}; - -/** - * The fetch failed: the widget shows its error state with a Retry action (which - * re-runs the query — still mocked as failing while this story is active). - */ -export const Error: Story = { - render: () => renderVideoPressOnPreset( 'last-7-days' ), - tags: [ '!autodocs' ], - decorators: [ withWidgetCanvas, withStoryRouter ], - beforeEach: () => { - setReportMockState( 'stats/video-plays', 'error' ); - return () => setReportMockState( 'stats/video-plays', null ); - }, -}; - -/** - * Resolved with no rows: the widget shows the generic empty state (the magnifier - * glyph and "We couldn’t find results for this time period."). - */ -export const Empty: Story = { - render: () => renderVideoPressOnPreset( 'last-365-days' ), - tags: [ '!autodocs' ], - decorators: [ withWidgetCanvas, withStoryRouter ], - beforeEach: () => { - setReportMockState( 'stats/video-plays', 'empty' ); - return () => setReportMockState( 'stats/video-plays', null ); - }, -}; - -interface VideoPressDashboardStoryProps - extends WidgetDashboardWithWidgetControls, VideoPressStoryControls {} - -/** - * Renders the real registered widget through the shared dashboard harness, so - * it appears exactly as it does in product, inheriting the size / edit-mode / - * host-environment controls. - */ -function VideoPressDashboardStory( { - withComparison, - ...dashboardArgs -}: VideoPressDashboardStoryProps ) { - return ( - > } - attributes={ { reportParams: getDefaultQueryParams( withComparison ) } } - /> - ); -} - -export const WidgetDashboardWithWidget: StoryObj< VideoPressDashboardStoryProps > = { - render: args => , - args: { - ...DEFAULT_WIDGET_DASHBOARD_STORY_ARGS, - withComparison: true, - }, - argTypes: { - ...widgetDashboardWithWidgetArgTypes, - withComparison: { control: 'boolean' }, - }, -}; diff --git a/projects/packages/videopress/.gitattributes b/projects/packages/videopress/.gitattributes index 6db015def6a6..9e4405bfdf56 100644 --- a/projects/packages/videopress/.gitattributes +++ b/projects/packages/videopress/.gitattributes @@ -19,3 +19,4 @@ global.d.ts production-exclude packages/** production-exclude routes/** production-exclude /wordpress-augmentations.d.ts production-exclude +widgets/** production-exclude diff --git a/projects/packages/videopress/README.md b/projects/packages/videopress/README.md index 1873fbc5faed..a86f55b840f1 100644 --- a/projects/packages/videopress/README.md +++ b/projects/packages/videopress/README.md @@ -63,6 +63,12 @@ jetpack watch packages/videopress If you plan on using this package in your WordPress plugin, we would recommend that you use [Jetpack Autoloader](https://packagist.org/packages/automattic/jetpack-autoloader) as your autoloader. This will allow for maximum interoperability with other plugins that use this package as well. +## Premium Analytics dashboard + +The package owns the Top videos widget of the Premium Analytics dashboard: `widgets/top-videos/`, built here with wp-build against the dashboard's SDK (`@automattic/jetpack-premium-analytics-sdk`) and registered as `videopress/top-videos` when the dashboard's widget registry hydrates. The registrant also seeds the widget into the Traffic section's default layout. + +The package decides nothing about who gets the widget. `Initializer` calls `Analytics_Dashboard::init()` where VideoPress is active outside the WordPress.com platform; `jetpack-mu-wpcom` calls the registrants on Simple and Atomic where the plan includes VideoPress. Both are inert on a site without the dashboard. + ## Security Need to report a security vulnerability? Go to [https://automattic.com/security/](https://automattic.com/security/) or directly to our security bug bounty site [https://hackerone.com/automattic](https://hackerone.com/automattic). diff --git a/projects/packages/videopress/changelog/update-pa-extensibility-videopress-top-videos b/projects/packages/videopress/changelog/update-pa-extensibility-videopress-top-videos new file mode 100644 index 000000000000..83aed4761d61 --- /dev/null +++ b/projects/packages/videopress/changelog/update-pa-extensibility-videopress-top-videos @@ -0,0 +1,4 @@ +Significance: minor +Type: added + +Register the Top videos widget of the Premium Analytics dashboard from this package. diff --git a/projects/packages/videopress/composer.json b/projects/packages/videopress/composer.json index cdfc9b6a0272..100489807f2e 100644 --- a/projects/packages/videopress/composer.json +++ b/projects/packages/videopress/composer.json @@ -17,7 +17,8 @@ "yoast/phpunit-polyfills": "^4.0.0", "automattic/jetpack-test-environment": "@dev", "brain/monkey": "^2.6.2", - "automattic/phpunit-select-config": "@dev" + "automattic/phpunit-select-config": "@dev", + "automattic/jetpack-premium-analytics": "@dev" }, "suggest": { "automattic/jetpack-autoloader": "Allow for better interoperability with other plugins that use this package." @@ -69,7 +70,12 @@ "version-constants": { "::PACKAGE_VERSION": "src/class-package-version.php" }, - "textdomain": "jetpack-videopress-pkg" + "textdomain": "jetpack-videopress-pkg", + "dependencies": { + "test-only": [ + "packages/premium-analytics" + ] + } }, "config": { "allow-plugins": { diff --git a/projects/packages/videopress/package.json b/projects/packages/videopress/package.json index c33531cb1140..13b89324217f 100644 --- a/projects/packages/videopress/package.json +++ b/projects/packages/videopress/package.json @@ -39,6 +39,7 @@ "@automattic/jetpack-api": "workspace:*", "@automattic/jetpack-components": "workspace:*", "@automattic/jetpack-connection": "workspace:*", + "@automattic/jetpack-premium-analytics-sdk": "workspace:*", "@automattic/jetpack-script-data": "workspace:*", "@jetpack-videopress/init": "link:packages/init", "@tanstack/react-query": "5.102.8", @@ -68,6 +69,7 @@ "@wordpress/theme": "2.1.0", "@wordpress/ui": "0.22.0", "@wordpress/url": "4.55.0", + "@wordpress/widget-primitives": "0.7.0", "clsx": "2.1.1", "debug": "4.4.3", "filesize": "10.1.6", @@ -118,6 +120,12 @@ "scriptGlobal": "jetpackVideoPress", "packageNamespace": "jetpack-videopress", "handlePrefix": "jetpack-videopress", + "externalNamespaces": { + "automattic": { + "global": "automattic", + "handlePrefix": "automattic" + } + }, "pages": [ { "id": "jetpack-videopress-dashboard", diff --git a/projects/packages/videopress/src/class-analytics-dashboard.php b/projects/packages/videopress/src/class-analytics-dashboard.php new file mode 100644 index 000000000000..da89610c916c --- /dev/null +++ b/projects/packages/videopress/src/class-analytics-dashboard.php @@ -0,0 +1,215 @@ +is_wpcom_platform() ) { + return; + } + + add_action( self::REGISTER_WIDGET_TYPES_ACTION, array( __CLASS__, 'register_widget_types' ), 20 ); + add_filter( self::DEFAULT_LAYOUT_FILTER, array( __CLASS__, 'add_default_layout_instance' ), 10, 2 ); + } + + /** + * Register the widget types from the package's build manifest. + * + * Loads the generated build first: after `init` it registers the widget script modules on the + * spot, so they reach the page import map the same request. + * + * @param object $registry The widget type registry being hydrated. + * @return void + */ + public static function register_widget_types( $registry ) { + if ( ! self::widget_contract_is_supported() ) { + return; + } + + $widgets = self::get_widget_manifest(); + if ( ! $widgets ) { + return; + } + + register_widget_types_from_manifest( + $widgets, + array( + 'textdomain' => self::TEXTDOMAIN, + 'i18n_manifest' => add_query_arg( 'ver', Package_Version::PACKAGE_VERSION, plugins_url( 'i18n-manifest.json', self::build_dir() . '/build.php' ) ), + 'former_names' => array( self::TOP_VIDEOS_TYPE => self::TOP_VIDEOS_FORMER_NAMES ), + ), + $registry + ); + } + + /** + * Seed the Top videos instance into the Traffic section's default layout. + * + * Order 8 keeps the place the dashboard seeded it in before the widget moved here. A layout + * that already holds the instance, under this name or a former one, is left alone; and one + * seeded on a site where the type never registers loses it to the dashboard's own policy. + * + * @param array $layout The section's default widget instances. + * @param string $section_id Namespaced section identifier. + * @return array + */ + public static function add_default_layout_instance( $layout, $section_id ) { + if ( self::TRAFFIC_SECTION_ID !== $section_id || ! is_array( $layout ) ) { + return $layout; + } + + foreach ( $layout as $item ) { + if ( ! is_array( $item ) ) { + continue; + } + if ( self::TOP_VIDEOS_INSTANCE_UUID === ( $item['uuid'] ?? null ) || self::is_top_videos_type( $item['type'] ?? null ) ) { + return $layout; + } + } + + $layout[] = get_dashboard_default_widget_instance( self::TOP_VIDEOS_INSTANCE_UUID, self::TOP_VIDEOS_TYPE, 8, 1, 2 ); + + return $layout; + } + + /** + * Whether a widget type name is the Top videos type, current or former. + * + * @param mixed $type A widget type name. + * @return bool + */ + private static function is_top_videos_type( $type ) { + return is_string( $type ) && ( self::TOP_VIDEOS_TYPE === $type || in_array( $type, self::TOP_VIDEOS_FORMER_NAMES, true ) ); + } + + /** + * Whether the dashboard's widget contract is one this build works against. + * + * Undefined is a request that never loaded the dashboard's widget types, such as the sections + * REST route: the widgets wait for one that does. + * + * @return bool + */ + private static function widget_contract_is_supported() { + if ( ! defined( 'Automattic\\Jetpack\\PremiumAnalytics\\WIDGET_API_VERSION' ) ) { + return false; + } + + $version = \Automattic\Jetpack\PremiumAnalytics\WIDGET_API_VERSION; + + return version_compare( $version, self::MIN_WIDGET_API_VERSION, '>=' ) && version_compare( $version, '2', '<' ); + } + + /** + * The widget manifest the package registers from: what its build generated, unless filtered. + * + * @return array[] Manifest entries, as `jetpack_videopress_get_registered_widget_modules()` returns them. + */ + private static function get_widget_manifest() { + self::load_build(); + $widgets = function_exists( 'jetpack_videopress_get_registered_widget_modules' ) ? jetpack_videopress_get_registered_widget_modules() : array(); + + /** + * Filters the widget manifest the package registers on the Premium Analytics dashboard. + * + * @since $$next-version$$ + * + * @param array[] $widgets Manifest entries, each with a `name`. + */ + return (array) apply_filters( self::WIDGET_MANIFEST_FILTER, $widgets ); + } + + /** + * Load the generated build once. Guarded by symbol, not by path: on WordPress.com two copies of + * the package can share a request. + * + * @return void + */ + private static function load_build() { + if ( function_exists( 'jetpack_videopress_get_registered_widget_modules' ) ) { + return; + } + $loader = self::build_dir() . '/build.php'; + if ( file_exists( $loader ) ) { + require_once $loader; + } + } + + /** + * Directory of the wp-build output. + * + * @return string + */ + private static function build_dir() { + return dirname( __DIR__ ) . '/build'; + } +} diff --git a/projects/packages/videopress/src/class-initializer.php b/projects/packages/videopress/src/class-initializer.php index 6970256b07d5..58c9b41eeba1 100644 --- a/projects/packages/videopress/src/class-initializer.php +++ b/projects/packages/videopress/src/class-initializer.php @@ -205,6 +205,7 @@ private static function active_initialization() { XMLRPC::init(); Block_Editor_Content::init(); Playlist_Index::init(); + Analytics_Dashboard::init(); /* * These endpoints only add their routes on REST init, so defer calling diff --git a/projects/packages/videopress/tests/php/Analytics_Dashboard_Test.php b/projects/packages/videopress/tests/php/Analytics_Dashboard_Test.php new file mode 100644 index 000000000000..a511b9629b90 --- /dev/null +++ b/projects/packages/videopress/tests/php/Analytics_Dashboard_Test.php @@ -0,0 +1,188 @@ +setAccessible( true ); + } + $instance->setValue( null, null ); + } + + Constants::clear_constants(); + // Host::is_wpcom_platform() memoizes `is_woa_site` past Constants::clear_constants(). + Cache::clear(); + + parent::tear_down(); + } + + /** + * A manifest path that does not exist. + * + * @return string + */ + public function use_absent_widget_manifest() { + return __DIR__ . '/no-such-widgets.php'; + } + + /** + * The registrant hooks after the dashboard package's own, the seed before the dashboard's policy. + */ + public function test_init_hooks_the_registrant_and_the_layout_seed() { + Analytics_Dashboard::init(); + + $this->assertSame( 20, has_action( Analytics_Dashboard::REGISTER_WIDGET_TYPES_ACTION, array( Analytics_Dashboard::class, 'register_widget_types' ) ) ); + $this->assertSame( 10, has_filter( Analytics_Dashboard::DEFAULT_LAYOUT_FILTER, array( Analytics_Dashboard::class, 'add_default_layout_instance' ) ) ); + } + + /** + * Simple and Atomic register by plan feature from jetpack-mu-wpcom instead. + */ + public function test_init_skips_on_the_wordpress_com_platform() { + Constants::set_constant( 'IS_WPCOM', true ); + + Analytics_Dashboard::init(); + + $this->assertFalse( has_action( Analytics_Dashboard::REGISTER_WIDGET_TYPES_ACTION, array( Analytics_Dashboard::class, 'register_widget_types' ) ) ); + $this->assertFalse( has_filter( Analytics_Dashboard::DEFAULT_LAYOUT_FILTER, array( Analytics_Dashboard::class, 'add_default_layout_instance' ) ) ); + } + + /** + * The manifest type registers with the package's text domain, manifest URL and former name. + */ + public function test_registers_the_top_videos_type_from_the_manifest() { + $registry = new Widget_Type_Registry(); + + Analytics_Dashboard::register_widget_types( $registry ); + + $top_videos = $registry->get_registered( Analytics_Dashboard::TOP_VIDEOS_TYPE ); + $this->assertNotNull( $top_videos ); + $this->assertSame( 'jetpack-videopress/widgets/top-videos/render', $top_videos->render_module ); + $this->assertSame( Analytics_Dashboard::TEXTDOMAIN, $top_videos->textdomain ); + $this->assertStringContainsString( 'build/i18n-manifest.json?ver=' . Package_Version::PACKAGE_VERSION, $top_videos->i18n_manifest ); + $this->assertSame( array( 'jpa/videopress' ), $top_videos->former_names ); + $this->assertSame( Analytics_Dashboard::TOP_VIDEOS_TYPE, $registry->resolve_name( 'jpa/videopress' ) ); + } + + /** + * The Traffic section serves the instance where the dashboard used to seed it. + */ + public function test_seeds_the_top_videos_instance_into_the_traffic_default_layout() { + register_default_dashboard_sections(); + Analytics_Dashboard::init(); + + $layout = get_registered_dashboard_section( DASHBOARD_NAME, Analytics_Dashboard::TRAFFIC_SECTION_ID )->get_default_layout(); + $instances = array_column( $layout, null, 'uuid' ); + + $this->assertArrayHasKey( Analytics_Dashboard::TOP_VIDEOS_INSTANCE_UUID, $instances ); + $this->assertSame( Analytics_Dashboard::TOP_VIDEOS_TYPE, $instances[ Analytics_Dashboard::TOP_VIDEOS_INSTANCE_UUID ]['type'] ); + $this->assertSame( + array( + 'width' => 1, + 'height' => 2, + 'order' => 8, + ), + $instances[ Analytics_Dashboard::TOP_VIDEOS_INSTANCE_UUID ]['placement'] + ); + } + + /** + * Other sections keep their layouts. + */ + public function test_leaves_the_layouts_of_other_sections_alone() { + $layout = array( + array( + 'uuid' => 'other', + 'type' => 'jpa/other', + ), + ); + + $this->assertSame( $layout, Analytics_Dashboard::add_default_layout_instance( $layout, 'analytics/insights' ) ); + } + + /** + * A layout that carries the instance already, under the current name or a former one, keeps one copy. + */ + public function test_does_not_seed_twice() { + $current = array( + array( + 'uuid' => 'x', + 'type' => Analytics_Dashboard::TOP_VIDEOS_TYPE, + ), + ); + $former = array( + array( + 'uuid' => 'y', + 'type' => 'jpa/videopress', + ), + ); + $by_uuid = array( + array( + 'uuid' => Analytics_Dashboard::TOP_VIDEOS_INSTANCE_UUID, + 'type' => 'jpa/something-else', + ), + ); + + foreach ( array( $current, $former, $by_uuid ) as $layout ) { + $this->assertSame( $layout, Analytics_Dashboard::add_default_layout_instance( $layout, Analytics_Dashboard::TRAFFIC_SECTION_ID ) ); + } + } + + /** + * A malformed layout passes through untouched. + */ + public function test_passes_a_non_array_layout_through() { + $this->assertSame( 'not-a-layout', Analytics_Dashboard::add_default_layout_instance( 'not-a-layout', Analytics_Dashboard::TRAFFIC_SECTION_ID ) ); + } +} diff --git a/projects/packages/videopress/tests/php/Analytics_Dashboard_Without_Widget_Types_Test.php b/projects/packages/videopress/tests/php/Analytics_Dashboard_Without_Widget_Types_Test.php new file mode 100644 index 000000000000..f0fb1249f4f2 --- /dev/null +++ b/projects/packages/videopress/tests/php/Analytics_Dashboard_Without_Widget_Types_Test.php @@ -0,0 +1,58 @@ +assertFalse( defined( 'Automattic\\Jetpack\\PremiumAnalytics\\WIDGET_API_VERSION' ) ); + $registry = new Widget_Type_Registry(); + + Analytics_Dashboard::register_widget_types( $registry ); + + $this->assertSame( array(), $registry->get_all_registered() ); + } + + public function test_the_layout_seed_does_not_wait() { + $this->assertFalse( defined( 'Automattic\\Jetpack\\PremiumAnalytics\\WIDGET_API_VERSION' ) ); + + $layout = Analytics_Dashboard::add_default_layout_instance( array(), Analytics_Dashboard::TRAFFIC_SECTION_ID ); + + $this->assertSame( array( Analytics_Dashboard::TOP_VIDEOS_TYPE ), array_column( $layout, 'type' ) ); + } +} diff --git a/projects/packages/videopress/tests/php/mocks/analytics-dashboard-manifest-fixture.php b/projects/packages/videopress/tests/php/mocks/analytics-dashboard-manifest-fixture.php new file mode 100644 index 000000000000..351aa713632a --- /dev/null +++ b/projects/packages/videopress/tests/php/mocks/analytics-dashboard-manifest-fixture.php @@ -0,0 +1,27 @@ + 'videopress/top-videos', + 'dir_name' => 'top-videos', + 'title' => 'Top videos', + 'category' => 'stats', + 'presentation' => 'framed', + 'render_module' => 'jetpack-videopress/widgets/top-videos/render', + 'widget_module' => 'jetpack-videopress/widgets/top-videos/widget', + 'textdomain' => null, + ), + ); +} diff --git a/projects/packages/videopress/tsconfig.json b/projects/packages/videopress/tsconfig.json index 51f36d7a55cf..3d083abc2bda 100644 --- a/projects/packages/videopress/tsconfig.json +++ b/projects/packages/videopress/tsconfig.json @@ -5,6 +5,7 @@ "./src/client", "./src/dashboard", "routes/**/*", + "widgets/**/*", "./declarations.d.ts", "./wordpress-augmentations.d.ts" ], diff --git a/projects/packages/premium-analytics/widgets/videopress/build-video-plays-data.ts b/projects/packages/videopress/widgets/top-videos/build-video-plays-data.ts similarity index 77% rename from projects/packages/premium-analytics/widgets/videopress/build-video-plays-data.ts rename to projects/packages/videopress/widgets/top-videos/build-video-plays-data.ts index b27cfe17caf1..014195f1ee07 100644 --- a/projects/packages/premium-analytics/widgets/videopress/build-video-plays-data.ts +++ b/projects/packages/videopress/widgets/top-videos/build-video-plays-data.ts @@ -1,8 +1,8 @@ /** - * External dependencies + * Internal dependencies */ -import { getVideoKey, getVideoLabel } from '@jetpack-premium-analytics/widgets-toolkit'; -import type { StatsVideoPlaysComparisonItem } from '@jetpack-premium-analytics/data'; +import { getVideoKey, getVideoLabel } from './video-plays'; +import type { StatsVideoPlaysComparisonItem } from '@automattic/jetpack-premium-analytics-sdk'; /** * A single video row with its presentation fields resolved, built from the @@ -10,7 +10,7 @@ import type { StatsVideoPlaysComparisonItem } from '@jetpack-premium-analytics/d */ export type VideoPlaysRow = { /** - * Attachment post ID used by the internal video-detail route. + * Attachment post ID used by the dashboard's video detail route. */ id?: number; /** @@ -32,7 +32,7 @@ export type VideoPlaysRow = { plays: number; /** * Play count for the comparison period. `undefined` when the video has no - * matching comparison row — distinct from a real zero, so the chart can + * matching comparison row, distinct from a real zero, so the chart can * suppress the row's delta instead of fabricating one. */ previousPlays: number | undefined; @@ -42,6 +42,9 @@ export type VideoPlaysRow = { * Maps merged video-plays rows from the Stats data layer onto normalized rows * ready for the leaderboard. Comparison matching already happened in the data * layer; this only resolves the display key, label, and link. + * + * @param videos - Merged video-plays rows. + * @return Rows ready for the leaderboard. */ export function toVideoPlaysRows( videos: StatsVideoPlaysComparisonItem[] = [] ): VideoPlaysRow[] { return videos.map( video => { diff --git a/projects/packages/videopress/widgets/top-videos/package.json b/projects/packages/videopress/widgets/top-videos/package.json new file mode 100644 index 000000000000..962c3fc8e6dd --- /dev/null +++ b/projects/packages/videopress/widgets/top-videos/package.json @@ -0,0 +1,13 @@ +{ + "name": "@automattic/jetpack-videopress-widget-top-videos", + "version": "0.1.0-alpha", + "private": true, + "type": "module", + "dependencies": { + "@automattic/jetpack-premium-analytics-sdk": "workspace:*", + "@wordpress/i18n": "^6.9.0", + "@wordpress/icons": "^16.0.0", + "@wordpress/widget-primitives": "0.7.0", + "react": "18.3.1" + } +} diff --git a/projects/packages/premium-analytics/widgets/videopress/render.tsx b/projects/packages/videopress/widgets/top-videos/render.tsx similarity index 77% rename from projects/packages/premium-analytics/widgets/videopress/render.tsx rename to projects/packages/videopress/widgets/top-videos/render.tsx index 7e3d53ed4e3d..6705a14bf0a9 100644 --- a/projects/packages/premium-analytics/widgets/videopress/render.tsx +++ b/projects/packages/videopress/widgets/top-videos/render.tsx @@ -1,7 +1,6 @@ /** * External dependencies */ -import { useStatsVideoPlays } from '@jetpack-premium-analytics/data'; import { LeaderboardChart, LeaderboardSkeleton, @@ -14,11 +13,12 @@ import { calculateDelta, getCombinedPeriodMax, sharePercentage, + useStatsVideoPlays, useWidgetNavigationSearch, useWidgetRootContext, type LeaderboardChartData, type ReportParamsFieldAttributes, -} from '@jetpack-premium-analytics/widgets-toolkit'; +} from '@automattic/jetpack-premium-analytics-sdk'; import { __ } from '@wordpress/i18n'; import { useMemo } from 'react'; /** @@ -26,15 +26,15 @@ import { useMemo } from 'react'; */ import { toVideoPlaysRows, type VideoPlaysRow } from './build-video-plays-data'; import styles from './style.module.css'; -import type { VideoPressAttributes } from './widget'; +import type { TopVideosAttributes } from './widget'; import type { WidgetRenderProps } from '@wordpress/widget-primitives'; import type { ComponentProps } from 'react'; // The dashboard injects its date range and comparison state through // `reportParams`; the widget has no settings of its own. -type VideoPressRenderAttributes = VideoPressAttributes & Partial< ReportParamsFieldAttributes >; +type TopVideosRenderAttributes = TopVideosAttributes & Partial< ReportParamsFieldAttributes >; -type VideoPressWidgetProps = WidgetRenderProps< VideoPressRenderAttributes > & { +type TopVideosWidgetProps = WidgetRenderProps< TopVideosRenderAttributes > & { /** * Dashboard error handler. */ @@ -45,6 +45,10 @@ type VideoPressWidgetProps = WidgetRenderProps< VideoPressRenderAttributes > & { * Maps normalized video rows to `LeaderboardChart` shape. Shares are computed * against the largest value of either period; rows without a comparison match * keep fields undefined so the chart doesn't fabricate deltas. + * + * @param rows - Normalized video rows. + * @param detailSearch - Search params carrying the dashboard's date window to the detail route. + * @return The leaderboard rows. */ function buildLeaderboardData( rows: VideoPlaysRow[], @@ -73,10 +77,12 @@ function buildLeaderboardData( } /** - * Fetches the video-plays report through the Jetpack Stats hook, builds the + * Fetches the video-plays report through the dashboard's Stats hook, builds the * leaderboard rows, and renders them through the shared widget content states. + * + * @return The widget content. */ -function VideoPressReport() { +function TopVideosReport() { const { reportParams } = useWidgetRootContext(); const detailSearch = useWidgetNavigationSearch(); const statsParams = useMemo( @@ -110,9 +116,9 @@ function VideoPressReport() { error={ { description: __( "We couldn't load video plays. Please try again in a moment.", - 'jetpack-premium-analytics-pkg' + 'jetpack-videopress-pkg' ), - actions: [ { label: __( 'Retry', 'jetpack-premium-analytics-pkg' ), onClick: refetch } ], + actions: [ { label: __( 'Retry', 'jetpack-videopress-pkg' ), onClick: refetch } ], } } renderLoading={ } > @@ -130,12 +136,20 @@ function VideoPressReport() { ); } -export default function VideoPress( { attributes = {}, setError }: VideoPressWidgetProps ) { +/** + * The Top videos widget: a leaderboard of the site's most played VideoPress videos. + * + * @param props - Widget render props. + * @param props.attributes - Widget attributes, with the report params the dashboard injects. + * @param props.setError - Dashboard error handler. + * @return The widget. + */ +export default function TopVideos( { attributes = {}, setError }: TopVideosWidgetProps ) { return (
- +
diff --git a/projects/packages/premium-analytics/widgets/videopress/style.module.css b/projects/packages/videopress/widgets/top-videos/style.module.css similarity index 100% rename from projects/packages/premium-analytics/widgets/videopress/style.module.css rename to projects/packages/videopress/widgets/top-videos/style.module.css diff --git a/projects/packages/videopress/widgets/top-videos/test/build-video-plays-data.test.ts b/projects/packages/videopress/widgets/top-videos/test/build-video-plays-data.test.ts new file mode 100644 index 000000000000..c1a77fe4e724 --- /dev/null +++ b/projects/packages/videopress/widgets/top-videos/test/build-video-plays-data.test.ts @@ -0,0 +1,97 @@ +import { toVideoPlaysRows } from '../build-video-plays-data'; +import { getVideoKey, getVideoLabel } from '../video-plays'; + +const video = ( fields: Record< string, unknown > ) => ( { + id: undefined, + label: '', + link: null, + plays: 0, + impressions: 0, + watchTime: 0, + retentionRate: 0, + ...fields, +} ); + +describe( 'toVideoPlaysRows', () => { + it( 'carries the id, key, label, link and both play counts of a matched row', () => { + expect( + toVideoPlaysRows( [ + video( { + id: 101, + label: 'Walkthrough', + link: 'https://example.com/a/', + plays: 100, + previousPlays: 80, + } ), + ] ) + ).toEqual( [ + { + id: 101, + key: '101', + label: 'Walkthrough', + link: 'https://example.com/a/', + plays: 100, + previousPlays: 80, + }, + ] ); + } ); + + it( 'keeps previousPlays undefined, not zero, when the row has no comparison match', () => { + const [ row ] = toVideoPlaysRows( [ video( { id: 101, label: 'Walkthrough', plays: 100 } ) ] ); + + expect( row.previousPlays ).toBeUndefined(); + } ); + + it( 'treats a real comparison value of zero as data, not as missing', () => { + const [ row ] = toVideoPlaysRows( [ + video( { id: 101, label: 'Walkthrough', plays: 100, previousPlays: 0 } ), + ] ); + + expect( row.previousPlays ).toBe( 0 ); + } ); + + it( 'falls back to an untitled label and drops an id that is not a positive integer', () => { + expect( + toVideoPlaysRows( [ video( { id: 0, link: 'https://example.com/video/0/', plays: 10 } ) ] ) + ).toEqual( [ + { + key: '0', + label: 'Untitled video', + link: 'https://example.com/video/0/', + plays: 10, + previousPlays: undefined, + }, + ] ); + } ); + + it( 'keys untitled videos without an id by their link so they do not collapse', () => { + const rows = toVideoPlaysRows( [ + video( { link: 'https://example.com/video/1/', plays: 10 } ), + video( { link: 'https://example.com/video/2/', plays: 5 } ), + ] ); + + expect( rows.map( row => row.key ) ).toEqual( [ + 'https://example.com/video/1/', + 'https://example.com/video/2/', + ] ); + } ); +} ); + +describe( 'getVideoKey and getVideoLabel', () => { + it( 'prefers the post id, then the link, then the label', () => { + expect( getVideoKey( video( { id: 7, link: 'https://example.com/', label: 'A' } ) ) ).toBe( + '7' + ); + expect( getVideoKey( video( { link: 'https://example.com/', label: 'A' } ) ) ).toBe( + 'https://example.com/' + ); + expect( getVideoKey( video( { label: 'A' } ) ) ).toBe( 'A' ); + expect( getVideoKey( video( {} ) ) ).toBe( 'Untitled video' ); + } ); + + it( 'labels a video without a title as untitled', () => { + expect( getVideoLabel( video( { label: 'Launch' } ) ) ).toBe( 'Launch' ); + expect( getVideoLabel( video( { label: '' } ) ) ).toBe( 'Untitled video' ); + expect( getVideoLabel( video( { label: null } ) ) ).toBe( 'Untitled video' ); + } ); +} ); diff --git a/projects/packages/videopress/widgets/top-videos/video-plays.ts b/projects/packages/videopress/widgets/top-videos/video-plays.ts new file mode 100644 index 000000000000..682b3df8028f --- /dev/null +++ b/projects/packages/videopress/widgets/top-videos/video-plays.ts @@ -0,0 +1,34 @@ +/** + * External dependencies + */ +import { __ } from '@wordpress/i18n'; +import type { StatsVideoPlaysComparisonItem } from '@automattic/jetpack-premium-analytics-sdk'; + +/** + * Resolve a display label for a video, falling back to a translated + * "Untitled video" label when the API provides none. + * + * @param video - The video-plays item. + * @return The video's display label. + */ +export function getVideoLabel( video: StatsVideoPlaysComparisonItem ): string { + return typeof video.label === 'string' && video.label + ? video.label + : __( 'Untitled video', 'jetpack-videopress-pkg' ); +} + +/** + * Resolve the key identifying a video's leaderboard row. Prefers the stable + * post ID, then the video URL, and only falls back to the display label when + * the API omits both, so multiple untitled videos don't collapse onto one key. + * + * @param video - The video-plays item. + * @return The row key. + */ +export function getVideoKey( video: StatsVideoPlaysComparisonItem ): string { + if ( video.id != null ) { + return String( video.id ); + } + + return video.link || getVideoLabel( video ); +} diff --git a/projects/packages/premium-analytics/widgets/videopress/widget.json b/projects/packages/videopress/widgets/top-videos/widget.json similarity index 77% rename from projects/packages/premium-analytics/widgets/videopress/widget.json rename to projects/packages/videopress/widgets/top-videos/widget.json index c5173cd07c33..b3e549716246 100644 --- a/projects/packages/premium-analytics/widgets/videopress/widget.json +++ b/projects/packages/videopress/widgets/top-videos/widget.json @@ -1,5 +1,5 @@ { - "name": "jpa/videopress", + "name": "videopress/top-videos", "title": "Top videos", "description": "Your most played VideoPress videos, sourced from Jetpack Stats.", "help": { @@ -12,5 +12,6 @@ ] }, "category": "stats", - "presentation": "framed" + "presentation": "framed", + "textdomain": "jetpack-videopress-pkg" } diff --git a/projects/packages/premium-analytics/widgets/videopress/widget.ts b/projects/packages/videopress/widgets/top-videos/widget.ts similarity index 70% rename from projects/packages/premium-analytics/widgets/videopress/widget.ts rename to projects/packages/videopress/widgets/top-videos/widget.ts index 58a78f6d82d4..9c83bd8cd177 100644 --- a/projects/packages/premium-analytics/widgets/videopress/widget.ts +++ b/projects/packages/videopress/widgets/top-videos/widget.ts @@ -5,11 +5,11 @@ import { video } from '@wordpress/icons'; import type { WidgetAttributeField } from '@wordpress/widget-primitives'; /** No configurable attributes; the empty record allows host-provided fields. */ -export type VideoPressAttributes = Record< never, never >; +export type TopVideosAttributes = Record< never, never >; export default { icon: video, - attributes: [] as WidgetAttributeField< VideoPressAttributes >[], + attributes: [] as WidgetAttributeField< TopVideosAttributes >[], example: { attributes: {}, }, diff --git a/projects/plugins/jetpack/changelog/update-pa-extensibility-videopress-top-videos b/projects/plugins/jetpack/changelog/update-pa-extensibility-videopress-top-videos new file mode 100644 index 000000000000..1ed8b086576c --- /dev/null +++ b/projects/plugins/jetpack/changelog/update-pa-extensibility-videopress-top-videos @@ -0,0 +1,4 @@ +Significance: minor +Type: other + +VideoPress: Register the Top videos widget of the Premium Analytics dashboard from the VideoPress package. diff --git a/projects/plugins/jetpack/composer.lock b/projects/plugins/jetpack/composer.lock index 93d1a49f9be4..eaa801da6728 100644 --- a/projects/plugins/jetpack/composer.lock +++ b/projects/plugins/jetpack/composer.lock @@ -4147,7 +4147,7 @@ "dist": { "type": "path", "url": "../../packages/videopress", - "reference": "7229e66e2384e40ae199c35a46a8f5b2296decef" + "reference": "8ee4c55ac17ade44301c621f26c82578194316e0" }, "require": { "automattic/jetpack-admin-ui": "@dev", @@ -4160,6 +4160,7 @@ "php": ">=7.4" }, "require-dev": { + "automattic/jetpack-premium-analytics": "@dev", "automattic/jetpack-test-environment": "@dev", "automattic/phpunit-select-config": "@dev", "brain/monkey": "^2.6.2", @@ -4181,7 +4182,12 @@ "version-constants": { "::PACKAGE_VERSION": "src/class-package-version.php" }, - "textdomain": "jetpack-videopress-pkg" + "textdomain": "jetpack-videopress-pkg", + "dependencies": { + "test-only": [ + "packages/premium-analytics" + ] + } }, "autoload": { "classmap": [ diff --git a/projects/plugins/premium-analytics/changelog/update-pa-extensibility-videopress-top-videos b/projects/plugins/premium-analytics/changelog/update-pa-extensibility-videopress-top-videos new file mode 100644 index 000000000000..057024be0cf7 --- /dev/null +++ b/projects/plugins/premium-analytics/changelog/update-pa-extensibility-videopress-top-videos @@ -0,0 +1,4 @@ +Significance: minor +Type: removed + +Remove the Top videos widget from the dashboard; it ships with VideoPress now. diff --git a/projects/plugins/videopress/changelog/update-pa-extensibility-videopress-top-videos b/projects/plugins/videopress/changelog/update-pa-extensibility-videopress-top-videos new file mode 100644 index 000000000000..019fd38e157c --- /dev/null +++ b/projects/plugins/videopress/changelog/update-pa-extensibility-videopress-top-videos @@ -0,0 +1,3 @@ +Significance: patch +Type: changed +Comment: Update composer.lock: the VideoPress package lists Premium Analytics as a test-only dependency. diff --git a/projects/plugins/videopress/composer.lock b/projects/plugins/videopress/composer.lock index 3b6493780642..2c67efeccc88 100644 --- a/projects/plugins/videopress/composer.lock +++ b/projects/plugins/videopress/composer.lock @@ -1896,7 +1896,7 @@ "dist": { "type": "path", "url": "../../packages/videopress", - "reference": "7229e66e2384e40ae199c35a46a8f5b2296decef" + "reference": "8ee4c55ac17ade44301c621f26c82578194316e0" }, "require": { "automattic/jetpack-admin-ui": "@dev", @@ -1909,6 +1909,7 @@ "php": ">=7.4" }, "require-dev": { + "automattic/jetpack-premium-analytics": "@dev", "automattic/jetpack-test-environment": "@dev", "automattic/phpunit-select-config": "@dev", "brain/monkey": "^2.6.2", @@ -1930,7 +1931,12 @@ "version-constants": { "::PACKAGE_VERSION": "src/class-package-version.php" }, - "textdomain": "jetpack-videopress-pkg" + "textdomain": "jetpack-videopress-pkg", + "dependencies": { + "test-only": [ + "packages/premium-analytics" + ] + } }, "autoload": { "classmap": [ From 24ff4ea13800ac493d7244b113cff8ab05899d14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dami=C3=A1n=20Su=C3=A1rez?= Date: Tue, 29 Sep 2026 08:27:07 +0100 Subject: [PATCH 08/22] register Top videos on wpcom by plan feature jetpack-mu-wpcom calls the VideoPress registrants on Simple and Atomic --- ...ate-pa-extensibility-videopress-top-videos | 4 + .../packages/jetpack-mu-wpcom/composer.json | 6 +- .../src/class-jetpack-mu-wpcom.php | 14 +++ .../premium-analytics/videopress-widgets.php | 63 ++++++++++ .../Videopress_Widgets_Test.php | 112 ++++++++++++++++++ ...ate-pa-extensibility-videopress-top-videos | 3 + .../plugins/mu-wpcom-plugin/composer.lock | 6 +- ...ate-pa-extensibility-videopress-top-videos | 3 + projects/plugins/wpcomsh/composer.lock | 6 +- 9 files changed, 211 insertions(+), 6 deletions(-) create mode 100644 projects/packages/jetpack-mu-wpcom/changelog/update-pa-extensibility-videopress-top-videos create mode 100644 projects/packages/jetpack-mu-wpcom/src/features/premium-analytics/videopress-widgets.php create mode 100644 projects/packages/jetpack-mu-wpcom/tests/php/features/premium-analytics/Videopress_Widgets_Test.php create mode 100644 projects/plugins/mu-wpcom-plugin/changelog/update-pa-extensibility-videopress-top-videos create mode 100644 projects/plugins/wpcomsh/changelog/update-pa-extensibility-videopress-top-videos diff --git a/projects/packages/jetpack-mu-wpcom/changelog/update-pa-extensibility-videopress-top-videos b/projects/packages/jetpack-mu-wpcom/changelog/update-pa-extensibility-videopress-top-videos new file mode 100644 index 000000000000..3dbed6da6012 --- /dev/null +++ b/projects/packages/jetpack-mu-wpcom/changelog/update-pa-extensibility-videopress-top-videos @@ -0,0 +1,4 @@ +Significance: minor +Type: changed + +Premium Analytics: Register the Top videos widget on Simple and Atomic from the VideoPress package. diff --git a/projects/packages/jetpack-mu-wpcom/composer.json b/projects/packages/jetpack-mu-wpcom/composer.json index a45ed84a4afb..01b466e4ff01 100644 --- a/projects/packages/jetpack-mu-wpcom/composer.json +++ b/projects/packages/jetpack-mu-wpcom/composer.json @@ -39,7 +39,8 @@ "brain/monkey": "^2.6.2", "automattic/phpunit-select-config": "@dev", "automattic/jetpack-premium-analytics": "@dev", - "automattic/jetpack-ads": "@dev" + "automattic/jetpack-ads": "@dev", + "automattic/jetpack-videopress": "@dev" }, "suggest": { "automattic/jetpack-autoloader": "Allow for better interoperability with other plugins that use this package." @@ -98,7 +99,8 @@ "dependencies": { "test-only": [ "packages/premium-analytics", - "packages/ads" + "packages/ads", + "packages/videopress" ] } }, diff --git a/projects/packages/jetpack-mu-wpcom/src/class-jetpack-mu-wpcom.php b/projects/packages/jetpack-mu-wpcom/src/class-jetpack-mu-wpcom.php index 6a482615817b..122159804da9 100644 --- a/projects/packages/jetpack-mu-wpcom/src/class-jetpack-mu-wpcom.php +++ b/projects/packages/jetpack-mu-wpcom/src/class-jetpack-mu-wpcom.php @@ -129,6 +129,9 @@ public static function init() { // Premium Analytics offers the Ads tab wherever the plan includes WordAds, on Simple and Atomic. add_action( 'plugins_loaded', array( __CLASS__, 'load_premium_analytics_wordads_section' ) ); + // Premium Analytics seeds the Top videos widget wherever the plan includes VideoPress, on Simple and Atomic. + add_action( 'plugins_loaded', array( __CLASS__, 'load_premium_analytics_videopress_widgets' ) ); + // Unified navigation fix for changes in WordPress 6.2. add_action( 'admin_enqueue_scripts', array( __CLASS__, 'unbind_focusout_on_wp_admin_bar_menu_toggle' ) ); @@ -901,6 +904,17 @@ public static function load_premium_analytics_wordads_section() { require_once __DIR__ . '/features/premium-analytics/wordads-section.php'; } + /** + * Register the Top videos widget of the Premium Analytics dashboard by plan feature. + * + * Same seam as the Ads tab: inert on a site without the dashboard. + * + * @since $$next-version$$ + */ + public static function load_premium_analytics_videopress_widgets() { + require_once __DIR__ . '/features/premium-analytics/videopress-widgets.php'; + } + /** * Load the Jetpack Custom CSS feature. */ diff --git a/projects/packages/jetpack-mu-wpcom/src/features/premium-analytics/videopress-widgets.php b/projects/packages/jetpack-mu-wpcom/src/features/premium-analytics/videopress-widgets.php new file mode 100644 index 000000000000..6da944b44878 --- /dev/null +++ b/projects/packages/jetpack-mu-wpcom/src/features/premium-analytics/videopress-widgets.php @@ -0,0 +1,63 @@ + Analytics_Dashboard::TOP_VIDEOS_TYPE, + 'dir_name' => 'top-videos', + 'title' => 'Top videos', + 'category' => 'stats', + 'presentation' => 'framed', + 'render_module' => 'jetpack-videopress/widgets/top-videos/render', + 'widget_module' => 'jetpack-videopress/widgets/top-videos/widget', + 'textdomain' => null, + ), + ); + } + + /** + * Reset the widget registry between tests. + */ + public function tear_down() { + remove_filter( Analytics_Dashboard::WIDGET_MANIFEST_FILTER, array( $this, 'widget_manifest' ) ); + $instance = new ReflectionProperty( Widget_Type_Registry::class, 'instance' ); + if ( PHP_VERSION_ID < 80100 ) { + $instance->setAccessible( true ); + } + $instance->setValue( null, null ); + + parent::tear_down(); + } + + public function test_registrants_hook_after_the_package_registrant_and_before_the_layout_policy() { + $this->assertSame( 20, has_action( 'jetpack_premium_analytics_register_widget_types', 'wpcom_premium_analytics_register_videopress_widget_types' ) ); + $this->assertSame( 10, has_filter( 'jetpack_premium_analytics_dashboard_default_layout', 'wpcom_premium_analytics_seed_videopress_default_layout' ) ); + } + + public function test_registers_the_widget_type_with_the_plan_feature() { + Functions\when( 'wpcom_site_has_feature' )->justReturn( true ); + $registry = new Widget_Type_Registry(); + + wpcom_premium_analytics_register_videopress_widget_types( $registry ); + + $this->assertNotNull( $registry->get_registered( Analytics_Dashboard::TOP_VIDEOS_TYPE ) ); + $this->assertSame( Analytics_Dashboard::TOP_VIDEOS_TYPE, $registry->resolve_name( 'jpa/videopress' ) ); + } + + public function test_skips_the_widget_type_without_the_plan_feature() { + Functions\when( 'wpcom_site_has_feature' )->justReturn( false ); + $registry = new Widget_Type_Registry(); + + wpcom_premium_analytics_register_videopress_widget_types( $registry ); + + $this->assertNull( $registry->get_registered( Analytics_Dashboard::TOP_VIDEOS_TYPE ) ); + } + + public function test_seeds_the_traffic_default_layout_with_the_plan_feature() { + Functions\when( 'wpcom_site_has_feature' )->justReturn( true ); + + $layout = wpcom_premium_analytics_seed_videopress_default_layout( array(), Analytics_Dashboard::TRAFFIC_SECTION_ID ); + + $this->assertSame( array( Analytics_Dashboard::TOP_VIDEOS_TYPE ), array_column( $layout, 'type' ) ); + } + + public function test_leaves_the_traffic_default_layout_alone_without_the_plan_feature() { + Functions\when( 'wpcom_site_has_feature' )->justReturn( false ); + + $this->assertSame( array(), wpcom_premium_analytics_seed_videopress_default_layout( array(), Analytics_Dashboard::TRAFFIC_SECTION_ID ) ); + } +} diff --git a/projects/plugins/mu-wpcom-plugin/changelog/update-pa-extensibility-videopress-top-videos b/projects/plugins/mu-wpcom-plugin/changelog/update-pa-extensibility-videopress-top-videos new file mode 100644 index 000000000000..88a6bb04302e --- /dev/null +++ b/projects/plugins/mu-wpcom-plugin/changelog/update-pa-extensibility-videopress-top-videos @@ -0,0 +1,3 @@ +Significance: patch +Type: changed +Comment: Update composer.lock: jetpack-mu-wpcom lists the VideoPress package as a test-only dependency. diff --git a/projects/plugins/mu-wpcom-plugin/composer.lock b/projects/plugins/mu-wpcom-plugin/composer.lock index ad7e3d8c341b..321abb0b3049 100644 --- a/projects/plugins/mu-wpcom-plugin/composer.lock +++ b/projects/plugins/mu-wpcom-plugin/composer.lock @@ -1486,7 +1486,7 @@ "dist": { "type": "path", "url": "../../packages/jetpack-mu-wpcom", - "reference": "eb1f0d903d2c44a2f9e7204655ce68e57c52009c" + "reference": "7d4219c9eb55f85610f28c8de29e728fc6ce28b5" }, "require": { "automattic/block-delimiter": "@dev", @@ -1519,6 +1519,7 @@ "automattic/jetpack-podcast": "@dev", "automattic/jetpack-premium-analytics": "@dev", "automattic/jetpack-test-environment": "@dev", + "automattic/jetpack-videopress": "@dev", "automattic/phpunit-select-config": "@dev", "brain/monkey": "^2.6.2", "yoast/phpunit-polyfills": "^4.0.0" @@ -1543,7 +1544,8 @@ "dependencies": { "test-only": [ "packages/premium-analytics", - "packages/ads" + "packages/ads", + "packages/videopress" ] } }, diff --git a/projects/plugins/wpcomsh/changelog/update-pa-extensibility-videopress-top-videos b/projects/plugins/wpcomsh/changelog/update-pa-extensibility-videopress-top-videos new file mode 100644 index 000000000000..88a6bb04302e --- /dev/null +++ b/projects/plugins/wpcomsh/changelog/update-pa-extensibility-videopress-top-videos @@ -0,0 +1,3 @@ +Significance: patch +Type: changed +Comment: Update composer.lock: jetpack-mu-wpcom lists the VideoPress package as a test-only dependency. diff --git a/projects/plugins/wpcomsh/composer.lock b/projects/plugins/wpcomsh/composer.lock index 2971d3de4001..bf10622f9b46 100644 --- a/projects/plugins/wpcomsh/composer.lock +++ b/projects/plugins/wpcomsh/composer.lock @@ -1673,7 +1673,7 @@ "dist": { "type": "path", "url": "../../packages/jetpack-mu-wpcom", - "reference": "bffd63a4d600796f31106b3902106b27f0e09421" + "reference": "3af71c2be76736ddfd94ced7bd8a144834fa31ad" }, "require": { "automattic/block-delimiter": "@dev", @@ -1706,6 +1706,7 @@ "automattic/jetpack-podcast": "@dev", "automattic/jetpack-premium-analytics": "@dev", "automattic/jetpack-test-environment": "@dev", + "automattic/jetpack-videopress": "@dev", "automattic/phpunit-select-config": "@dev", "brain/monkey": "^2.6.2", "yoast/phpunit-polyfills": "^4.0.0" @@ -1730,7 +1731,8 @@ "dependencies": { "test-only": [ "packages/premium-analytics", - "packages/ads" + "packages/ads", + "packages/videopress" ] } }, From 7dd1ca8c06357b5a909a20686b0107c3a61085a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dami=C3=A1n=20Su=C3=A1rez?= Date: Tue, 29 Sep 2026 08:37:45 +0100 Subject: [PATCH 09/22] normalize former names in the registry a keyed list reached the client as an object; the client renames stored layouts only --- .../config/widget-type-renames.test.ts | 8 +++++ .../dashboard/config/widget-type-renames.ts | 6 +++- .../use-dashboard-section-layout.ts | 11 +++--- .../src/class-widget-type-registry.php | 35 ++++++++++++++++--- .../premium-analytics/src/widget-types.php | 22 +----------- .../tests/php/Widget_Modules_Test.php | 22 ++++++++++++ .../tests/php/Widget_Type_Registry_Test.php | 25 +++++++++---- 7 files changed, 90 insertions(+), 39 deletions(-) diff --git a/projects/packages/premium-analytics/routes/dashboard/config/widget-type-renames.test.ts b/projects/packages/premium-analytics/routes/dashboard/config/widget-type-renames.test.ts index 1fed53a85b6e..5c0636f57650 100644 --- a/projects/packages/premium-analytics/routes/dashboard/config/widget-type-renames.test.ts +++ b/projects/packages/premium-analytics/routes/dashboard/config/widget-type-renames.test.ts @@ -24,6 +24,14 @@ describe( 'buildWidgetTypeRenames', () => { expect( buildWidgetTypeRenames( null ) ).toBe( NO_WIDGET_TYPE_RENAMES ); expect( buildWidgetTypeRenames( [ { name: 'jpa/clicks' } ] ) ).toBe( NO_WIDGET_TYPE_RENAMES ); } ); + + it( 'ignores a record whose former names are not a list', () => { + const keyed = { 0: 'jpa/videopress', 2: 'jpa/videos' } as unknown as string[]; + + expect( + buildWidgetTypeRenames( [ { name: 'videopress/top-videos', former_names: keyed } ] ) + ).toBe( NO_WIDGET_TYPE_RENAMES ); + } ); } ); describe( 'resolveLayoutTypes', () => { diff --git a/projects/packages/premium-analytics/routes/dashboard/config/widget-type-renames.ts b/projects/packages/premium-analytics/routes/dashboard/config/widget-type-renames.ts index 111e30c87d67..20af4682eb36 100644 --- a/projects/packages/premium-analytics/routes/dashboard/config/widget-type-renames.ts +++ b/projects/packages/premium-analytics/routes/dashboard/config/widget-type-renames.ts @@ -33,7 +33,11 @@ export function buildWidgetTypeRenames( const renames = new Map< string, WidgetTypeName >(); for ( const record of records ) { - for ( const formerName of record.former_names ?? [] ) { + // A record whose former names are not a list, whatever the server sent, renames nothing. + if ( ! Array.isArray( record.former_names ) ) { + continue; + } + for ( const formerName of record.former_names ) { renames.set( formerName, record.name as WidgetTypeName ); } } diff --git a/projects/packages/premium-analytics/routes/dashboard/hooks/use-dashboard-section-layout/use-dashboard-section-layout.ts b/projects/packages/premium-analytics/routes/dashboard/hooks/use-dashboard-section-layout/use-dashboard-section-layout.ts index b42255e0e571..9cf2b079507d 100644 --- a/projects/packages/premium-analytics/routes/dashboard/hooks/use-dashboard-section-layout/use-dashboard-section-layout.ts +++ b/projects/packages/premium-analytics/routes/dashboard/hooks/use-dashboard-section-layout/use-dashboard-section-layout.ts @@ -30,9 +30,10 @@ type PreferencesActions = { * snapshot would shadow the entity default forever, pinning users who asked to * follow the default to whatever it happened to be at reset time. * - * A layout saved under a former widget type name renders the current type: the items are + * A layout saved under a former widget type name renders the current type: the stored items are * renamed through `renames` on the way out, with no write-back, so the current name persists - * with the section's next commit. + * with the section's next commit. The default needs no renaming: the server resolves former + * names in it before it reaches the record. * * @param activeSectionId - Currently active section slug. * @param sections - The available sections, carrying their defaults. @@ -66,10 +67,10 @@ export function useDashboardSectionLayout( const [ resetCount, setResetCount ] = useState( 0 ); const layout = useMemo( () => { if ( Object.hasOwn( sectionLayouts, activeSectionId ) ) { - return resolveLayoutTypes( sectionLayouts[ activeSectionId ] ?? sectionDefault, renames ); + const stored = sectionLayouts[ activeSectionId ]; + return stored ? resolveLayoutTypes( stored, renames ) : sectionDefault; } - const fallback = resolveLayoutTypes( sectionDefault, renames ); - return resetCount ? [ ...fallback ] : fallback; + return resetCount ? [ ...sectionDefault ] : sectionDefault; }, [ sectionLayouts, activeSectionId, sectionDefault, resetCount, renames ] ); const setLayout = useCallback( diff --git a/projects/packages/premium-analytics/src/class-widget-type-registry.php b/projects/packages/premium-analytics/src/class-widget-type-registry.php index 53f3224e4675..87f75b3a84a5 100644 --- a/projects/packages/premium-analytics/src/class-widget-type-registry.php +++ b/projects/packages/premium-analytics/src/class-widget-type-registry.php @@ -125,10 +125,16 @@ public function register( $name, $args = array() ) { return false; } - $former_names = $widget_type ? $widget_type->former_names : ( $args['former_names'] ?? null ); + $former_names = self::normalize_former_names( $widget_type ? $widget_type->former_names : ( $args['former_names'] ?? null ) ); if ( null !== $former_names && ! $this->former_names_are_free( $name, $former_names ) ) { return false; } + // The type keeps the normalized list: it is what the REST record publishes. + if ( $widget_type ) { + $widget_type->former_names = $former_names; + } else { + $args['former_names'] = $former_names; + } if ( ! $widget_type ) { $widget_type = new Widget_Type( $name, $args ); @@ -142,6 +148,25 @@ public function register( $name, $args = array() ) { return $widget_type; } + /** + * Normalizes declared former names to a list of distinct values, or null when there are none. + * + * A keyed array, say what `array_unique()` leaves behind, would reach the client as an object + * instead of a list. Anything but an array passes through for `former_names_are_free()` to refuse. + * + * @param mixed $former_names The declared former names. + * @return mixed + */ + private static function normalize_former_names( $former_names ) { + if ( ! is_array( $former_names ) ) { + return $former_names; + } + + $former_names = array_values( array_unique( $former_names, SORT_REGULAR ) ); + + return $former_names ? $former_names : null; + } + /** * Whether a widget type may claim the given former names. * @@ -153,11 +178,11 @@ public function register( $name, $args = array() ) { * @return bool */ private function former_names_are_free( $name, $former_names ) { - $taken = ''; + $taken = null; if ( is_array( $former_names ) ) { foreach ( $former_names as $former_name ) { if ( ! is_string( $former_name ) || ! preg_match( '/^[a-z0-9-]+\/[a-z0-9-]+$/', $former_name ) || $former_name === $name ) { - $taken = is_string( $former_name ) ? $former_name : ''; + $taken = is_string( $former_name ) ? $former_name : gettype( $former_name ); break; } $owner = $this->former_names[ $former_name ] ?? null; @@ -167,10 +192,10 @@ private function former_names_are_free( $name, $former_names ) { } } } else { - $taken = (string) $former_names; + $taken = is_scalar( $former_names ) ? (string) $former_names : gettype( $former_names ); } - if ( '' === $taken && is_array( $former_names ) ) { + if ( null === $taken ) { return true; } diff --git a/projects/packages/premium-analytics/src/widget-types.php b/projects/packages/premium-analytics/src/widget-types.php index 263fe18eda02..a792c93f4f40 100644 --- a/projects/packages/premium-analytics/src/widget-types.php +++ b/projects/packages/premium-analytics/src/widget-types.php @@ -350,32 +350,12 @@ function register_widget_types_from_manifest( array $widgets, array $args = arra 'keywords' => $widget['keywords'] ?? null, 'textdomain' => $widget['textdomain'] ?? null, 'i18n_manifest' => $widget['i18n_manifest'] ?? null, - 'former_names' => sanitize_widget_former_names( $widget['former_names'] ?? null ), + 'former_names' => $widget['former_names'] ?? null, ) ); } } -/** - * Normalizes a candidate's former names to a list of strings, or null when it has none. - * - * The registry validates the names themselves when the type registers. - * - * @since $$next-version$$ - * - * @param mixed $former_names The declared former names. - * @return string[]|null - */ -function sanitize_widget_former_names( $former_names ) { - if ( ! is_array( $former_names ) ) { - return null; - } - - $names = array_values( array_unique( array_filter( $former_names, 'is_string' ) ) ); - - return $names ? $names : null; -} - /** * Registers the package's own widget types from its build manifest. * diff --git a/projects/packages/premium-analytics/tests/php/Widget_Modules_Test.php b/projects/packages/premium-analytics/tests/php/Widget_Modules_Test.php index 3cc3c1549636..88bebe931dc6 100644 --- a/projects/packages/premium-analytics/tests/php/Widget_Modules_Test.php +++ b/projects/packages/premium-analytics/tests/php/Widget_Modules_Test.php @@ -129,4 +129,26 @@ public function test_records_carry_the_former_names() { $this->assertNull( $records['plugin/never-renamed']['former_names'] ); $this->assertArrayNotHasKey( 'plugin/old-name', $records ); } + + /** + * The former names reach the client as a list, whatever shape the registrant passed: a keyed array + * would serialize as an object and break the rename map. + */ + public function test_records_publish_the_former_names_as_a_list() { + register_widget_type( + 'plugin/renamed-twice', + array( + 'render_module' => 'plugin/widgets/renamed-twice/render', + 'former_names' => array( + 5 => 'plugin/old-a', + 9 => 'plugin/old-a', + 2 => 'plugin/old-b', + ), + ) + ); + + $records = array_column( get_widget_modules_response()->get_data(), null, 'name' ); + + $this->assertSame( array( 'plugin/old-a', 'plugin/old-b' ), $records['plugin/renamed-twice']['former_names'] ); + } } diff --git a/projects/packages/premium-analytics/tests/php/Widget_Type_Registry_Test.php b/projects/packages/premium-analytics/tests/php/Widget_Type_Registry_Test.php index 580cd4359dc5..28ecc1a4d13f 100644 --- a/projects/packages/premium-analytics/tests/php/Widget_Type_Registry_Test.php +++ b/projects/packages/premium-analytics/tests/php/Widget_Type_Registry_Test.php @@ -440,6 +440,8 @@ public function test_former_names_cannot_collide_with_registered_or_claimed_name $this->assertFalse( register_widget_type( 'plugin/another', array( 'former_names' => array( 'plugin/old' ) ) ) ); $this->assertFalse( register_widget_type( 'plugin/old' ) ); $this->assertFalse( register_widget_type( 'plugin/shouty', array( 'former_names' => array( 'Plugin/Old' ) ) ) ); + $this->assertFalse( register_widget_type( 'plugin/numeric', array( 'former_names' => array( 42 ) ) ) ); + $this->assertFalse( register_widget_type( 'plugin/scalar', array( 'former_names' => 'plugin/old-scalar' ) ) ); $this->assertSame( array( @@ -447,6 +449,8 @@ public function test_former_names_cannot_collide_with_registered_or_claimed_name Widget_Type_Registry::class . '::former_names_are_free', Widget_Type_Registry::class . '::register', Widget_Type_Registry::class . '::former_names_are_free', + Widget_Type_Registry::class . '::former_names_are_free', + Widget_Type_Registry::class . '::former_names_are_free', ), $this->doing_it_wrong ); @@ -467,13 +471,20 @@ public function test_unregister_releases_the_former_names() { } /** - * The sanitizer keeps a list of distinct strings, and nothing else. + * The registry stores former names as a list of distinct names, whatever shape the caller passed: + * a keyed array would reach the client as an object. */ - public function test_sanitize_widget_former_names_keeps_distinct_strings_only() { - $this->assertNull( sanitize_widget_former_names( null ) ); - $this->assertNull( sanitize_widget_former_names( 'jpa/old' ) ); - $this->assertNull( sanitize_widget_former_names( array( 42, null ) ) ); - $this->assertSame( array( 'jpa/old', 'jpa/older' ), sanitize_widget_former_names( array( 'jpa/old', 42, 'jpa/old', 'jpa/older' ) ) ); + public function test_register_normalizes_the_former_names_into_a_list() { + $registry = Widget_Type_Registry::get_instance(); + + $keyed = $registry->register( 'plugin/keyed', array( 'former_names' => array_unique( array( 'plugin/old', 'plugin/old', 'plugin/older' ) ) ) ); + $this->assertSame( array( 'plugin/old', 'plugin/older' ), $keyed->former_names ); + $this->assertSame( 'plugin/keyed', $registry->resolve_name( 'plugin/older' ) ); + + $this->assertNull( $registry->register( 'plugin/none', array( 'former_names' => array() ) )->former_names ); + + $instance = new Widget_Type( 'plugin/instance', array( 'former_names' => array( 3 => 'plugin/third' ) ) ); + $this->assertSame( array( 'plugin/third' ), $registry->register( $instance )->former_names ); } /** @@ -489,7 +500,7 @@ public function test_manifest_helper_stamps_the_former_names_onto_the_type() { array( 'name' => 'plugin/second', 'render_module' => 'plugin/second/render', - 'former_names' => array( 'jpa/second', 'jpa/second', 42 ), + 'former_names' => array( 'jpa/second', 'jpa/second' ), ), ), array( From 700bbecb8e7f3451288e4697351b6f20f17fbfd5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dami=C3=A1n=20Su=C3=A1rez?= Date: Mon, 28 Sep 2026 20:06:02 +0100 Subject: [PATCH 10/22] expose the leaderboard primitives through the SDK the video plays hook too, provisional; widget contract 1.2.0; the facade must be fully declared --- ...pdate-pa-extensibility-videopress-sdk-exports | 4 ++++ .../premium-analytics-sdk/src/index.d.ts | 16 ++++++++++++++++ ...pdate-pa-extensibility-videopress-sdk-exports | 4 ++++ .../premium-analytics/docs/dashboard-widgets.md | 2 +- .../packages/sdk/src/conformance.ts | 5 +++++ .../premium-analytics/packages/sdk/src/index.ts | 9 +++++++++ .../premium-analytics/src/widget-types.php | 2 +- 7 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 projects/js-packages/premium-analytics-sdk/changelog/update-pa-extensibility-videopress-sdk-exports create mode 100644 projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-sdk-exports diff --git a/projects/js-packages/premium-analytics-sdk/changelog/update-pa-extensibility-videopress-sdk-exports b/projects/js-packages/premium-analytics-sdk/changelog/update-pa-extensibility-videopress-sdk-exports new file mode 100644 index 000000000000..8e6215da4de5 --- /dev/null +++ b/projects/js-packages/premium-analytics-sdk/changelog/update-pa-extensibility-videopress-sdk-exports @@ -0,0 +1,4 @@ +Significance: minor +Type: added + +Declare the leaderboard primitives and the video plays hook. diff --git a/projects/js-packages/premium-analytics-sdk/src/index.d.ts b/projects/js-packages/premium-analytics-sdk/src/index.d.ts index 42875bb70386..77c15c8bb5b2 100644 --- a/projects/js-packages/premium-analytics-sdk/src/index.d.ts +++ b/projects/js-packages/premium-analytics-sdk/src/index.d.ts @@ -27,6 +27,17 @@ export type DataFormat = any; export type CountLabel = any; export type ChartDisplayChartType = any; +// Leaderboards: the chart, its rows and the helpers that size and compare them. +export declare const LeaderboardChart: AnyComponent; +export declare const LeaderboardSkeleton: AnyComponent; +export declare const WIDGET_ROW_LIMIT: number; +export declare function buildLeaderboardRow( ...args: any[] ): any; +export declare function calculateDelta( ...args: any[] ): any; +export declare function getCombinedPeriodMax( ...args: any[] ): any; +export declare function sharePercentage( ...args: any[] ): any; +export declare function useWidgetNavigationSearch( ...args: any[] ): any; +export type LeaderboardChartData = any; + // Widget attributes. export declare function reportParamsAttributeField< Attributes = any >( options?: any ): any; export declare function chartTypeAttributeField< Attributes = any >( options?: any ): any; @@ -50,6 +61,11 @@ export declare function useStatsWordAdsEarnings( ...args: any[] ): any; export type StatsWordAdsResponse = any; export type StatsWordAdsEarningsResponse = any; +// The video plays hook is provisional the same way: shared with the dashboard's Videos report until +// that report moves to the VideoPress package. +export declare function useStatsVideoPlays( ...args: any[] ): any; +export type StatsVideoPlaysComparisonItem = any; + // Ads earnings history, provisional too: shared with the dashboard's Earnings report until that report // moves to the Ads package. export declare const EarningsHistoryList: AnyComponent; diff --git a/projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-sdk-exports b/projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-sdk-exports new file mode 100644 index 000000000000..f08b5cc598c4 --- /dev/null +++ b/projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-sdk-exports @@ -0,0 +1,4 @@ +Significance: minor +Type: added + +Dashboard: Expose the leaderboard primitives and the video plays hook through the SDK; the widget contract is 1.2.0. diff --git a/projects/packages/premium-analytics/docs/dashboard-widgets.md b/projects/packages/premium-analytics/docs/dashboard-widgets.md index 4545877b46be..3576d2bac054 100644 --- a/projects/packages/premium-analytics/docs/dashboard-widgets.md +++ b/projects/packages/premium-analytics/docs/dashboard-widgets.md @@ -211,7 +211,7 @@ It reads the package's fixed list and, once the registry can answer, the registr `WIDGET_API_VERSION` names the contract a widget is built against: the `@automattic/jetpack-premium-analytics-sdk` module and the exports it declares, the dashboard modules the facade re-exports from (`@jetpack-premium-analytics/widgets-toolkit`, `data`, `fields`, `datetime`, `externals`), and the `Widget_Type` fields the client reads. -The major changes when a widget built against the previous contract stops working; the minor when a consumer can rely on something new. +The major changes when a widget built against the previous contract stops working; the minor when a consumer can rely on something new. So far, 1.1.0 added `former_names` and 1.2.0 the leaderboard primitives and `useStatsVideoPlays`. Inside `plugins/jetpack` the package and a consumer module ship together, so the check is a formality. With the standalone `plugins/premium-analytics` next to another plugin, each brings its own copy, and the check is what keeps a widget built against 1.x from registering on a 2.x package. diff --git a/projects/packages/premium-analytics/packages/sdk/src/conformance.ts b/projects/packages/premium-analytics/packages/sdk/src/conformance.ts index 1e7d9114c7b4..fe81afc579d6 100644 --- a/projects/packages/premium-analytics/packages/sdk/src/conformance.ts +++ b/projects/packages/premium-analytics/packages/sdk/src/conformance.ts @@ -5,3 +5,8 @@ import type * as Api from '@automattic/jetpack-premium-analytics-sdk'; type MissingFromFacade = Exclude< keyof typeof Api, keyof typeof Facade >; export const isComplete: [ MissingFromFacade ] extends [ never ] ? true : MissingFromFacade = true; + +// And when the facade exports a value the API contract does not declare: a consumer could not import it. +type MissingFromApi = Exclude< keyof typeof Facade, keyof typeof Api >; + +export const isDeclared: [ MissingFromApi ] extends [ never ] ? true : MissingFromApi = true; diff --git a/projects/packages/premium-analytics/packages/sdk/src/index.ts b/projects/packages/premium-analytics/packages/sdk/src/index.ts index aff7994c6d2c..ff6f713d1255 100644 --- a/projects/packages/premium-analytics/packages/sdk/src/index.ts +++ b/projects/packages/premium-analytics/packages/sdk/src/index.ts @@ -6,22 +6,31 @@ export { ChartEmptyState, EarningsHistoryList, + LeaderboardChart, + LeaderboardSkeleton, MetricTabsChart, MetricTabsChartSkeleton, MetricTileGrid, MetricTileGridSkeleton, ReportLink, + WIDGET_ROW_LIMIT, WidgetFooter, WidgetRoot, WidgetState, + buildLeaderboardRow, buildMetricTab, + calculateDelta, chartTypeAttributeField, flattenEarningsBreakdown, + getCombinedPeriodMax, + sharePercentage, + useWidgetNavigationSearch, useWidgetRootContext, } from '@jetpack-premium-analytics/widgets-toolkit'; export { ReportScopeProvider, chartInterval, + useStatsVideoPlays, useStatsWordAdsEarnings, useStatsWordAdsStats, } from '@jetpack-premium-analytics/data'; diff --git a/projects/packages/premium-analytics/src/widget-types.php b/projects/packages/premium-analytics/src/widget-types.php index fcce8ebb221e..df870b137e32 100644 --- a/projects/packages/premium-analytics/src/widget-types.php +++ b/projects/packages/premium-analytics/src/widget-types.php @@ -45,7 +45,7 @@ * * @since 0.9.0 */ -const WIDGET_API_VERSION = '1.1.0'; +const WIDGET_API_VERSION = '1.2.0'; /** * Returns the i18n schema describing which widget metadata fields are From c76b93e9215647f4c948f87e80ee9b072de72ced Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dami=C3=A1n=20Su=C3=A1rez?= Date: Mon, 28 Sep 2026 20:06:02 +0100 Subject: [PATCH 11/22] expose the leaderboard primitives through the SDK the video plays hook too, provisional; widget contract 1.2.0; the facade must be fully declared --- ...pdate-pa-extensibility-videopress-sdk-exports | 4 ++++ .../premium-analytics-sdk/src/index.d.ts | 16 ++++++++++++++++ ...pdate-pa-extensibility-videopress-sdk-exports | 4 ++++ .../premium-analytics/docs/dashboard-widgets.md | 2 +- .../packages/sdk/src/conformance.ts | 5 +++++ .../premium-analytics/packages/sdk/src/index.ts | 9 +++++++++ .../premium-analytics/src/widget-types.php | 2 +- 7 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 projects/js-packages/premium-analytics-sdk/changelog/update-pa-extensibility-videopress-sdk-exports create mode 100644 projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-sdk-exports diff --git a/projects/js-packages/premium-analytics-sdk/changelog/update-pa-extensibility-videopress-sdk-exports b/projects/js-packages/premium-analytics-sdk/changelog/update-pa-extensibility-videopress-sdk-exports new file mode 100644 index 000000000000..8e6215da4de5 --- /dev/null +++ b/projects/js-packages/premium-analytics-sdk/changelog/update-pa-extensibility-videopress-sdk-exports @@ -0,0 +1,4 @@ +Significance: minor +Type: added + +Declare the leaderboard primitives and the video plays hook. diff --git a/projects/js-packages/premium-analytics-sdk/src/index.d.ts b/projects/js-packages/premium-analytics-sdk/src/index.d.ts index 42875bb70386..77c15c8bb5b2 100644 --- a/projects/js-packages/premium-analytics-sdk/src/index.d.ts +++ b/projects/js-packages/premium-analytics-sdk/src/index.d.ts @@ -27,6 +27,17 @@ export type DataFormat = any; export type CountLabel = any; export type ChartDisplayChartType = any; +// Leaderboards: the chart, its rows and the helpers that size and compare them. +export declare const LeaderboardChart: AnyComponent; +export declare const LeaderboardSkeleton: AnyComponent; +export declare const WIDGET_ROW_LIMIT: number; +export declare function buildLeaderboardRow( ...args: any[] ): any; +export declare function calculateDelta( ...args: any[] ): any; +export declare function getCombinedPeriodMax( ...args: any[] ): any; +export declare function sharePercentage( ...args: any[] ): any; +export declare function useWidgetNavigationSearch( ...args: any[] ): any; +export type LeaderboardChartData = any; + // Widget attributes. export declare function reportParamsAttributeField< Attributes = any >( options?: any ): any; export declare function chartTypeAttributeField< Attributes = any >( options?: any ): any; @@ -50,6 +61,11 @@ export declare function useStatsWordAdsEarnings( ...args: any[] ): any; export type StatsWordAdsResponse = any; export type StatsWordAdsEarningsResponse = any; +// The video plays hook is provisional the same way: shared with the dashboard's Videos report until +// that report moves to the VideoPress package. +export declare function useStatsVideoPlays( ...args: any[] ): any; +export type StatsVideoPlaysComparisonItem = any; + // Ads earnings history, provisional too: shared with the dashboard's Earnings report until that report // moves to the Ads package. export declare const EarningsHistoryList: AnyComponent; diff --git a/projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-sdk-exports b/projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-sdk-exports new file mode 100644 index 000000000000..f08b5cc598c4 --- /dev/null +++ b/projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-sdk-exports @@ -0,0 +1,4 @@ +Significance: minor +Type: added + +Dashboard: Expose the leaderboard primitives and the video plays hook through the SDK; the widget contract is 1.2.0. diff --git a/projects/packages/premium-analytics/docs/dashboard-widgets.md b/projects/packages/premium-analytics/docs/dashboard-widgets.md index 4545877b46be..3576d2bac054 100644 --- a/projects/packages/premium-analytics/docs/dashboard-widgets.md +++ b/projects/packages/premium-analytics/docs/dashboard-widgets.md @@ -211,7 +211,7 @@ It reads the package's fixed list and, once the registry can answer, the registr `WIDGET_API_VERSION` names the contract a widget is built against: the `@automattic/jetpack-premium-analytics-sdk` module and the exports it declares, the dashboard modules the facade re-exports from (`@jetpack-premium-analytics/widgets-toolkit`, `data`, `fields`, `datetime`, `externals`), and the `Widget_Type` fields the client reads. -The major changes when a widget built against the previous contract stops working; the minor when a consumer can rely on something new. +The major changes when a widget built against the previous contract stops working; the minor when a consumer can rely on something new. So far, 1.1.0 added `former_names` and 1.2.0 the leaderboard primitives and `useStatsVideoPlays`. Inside `plugins/jetpack` the package and a consumer module ship together, so the check is a formality. With the standalone `plugins/premium-analytics` next to another plugin, each brings its own copy, and the check is what keeps a widget built against 1.x from registering on a 2.x package. diff --git a/projects/packages/premium-analytics/packages/sdk/src/conformance.ts b/projects/packages/premium-analytics/packages/sdk/src/conformance.ts index 1e7d9114c7b4..fe81afc579d6 100644 --- a/projects/packages/premium-analytics/packages/sdk/src/conformance.ts +++ b/projects/packages/premium-analytics/packages/sdk/src/conformance.ts @@ -5,3 +5,8 @@ import type * as Api from '@automattic/jetpack-premium-analytics-sdk'; type MissingFromFacade = Exclude< keyof typeof Api, keyof typeof Facade >; export const isComplete: [ MissingFromFacade ] extends [ never ] ? true : MissingFromFacade = true; + +// And when the facade exports a value the API contract does not declare: a consumer could not import it. +type MissingFromApi = Exclude< keyof typeof Facade, keyof typeof Api >; + +export const isDeclared: [ MissingFromApi ] extends [ never ] ? true : MissingFromApi = true; diff --git a/projects/packages/premium-analytics/packages/sdk/src/index.ts b/projects/packages/premium-analytics/packages/sdk/src/index.ts index aff7994c6d2c..ff6f713d1255 100644 --- a/projects/packages/premium-analytics/packages/sdk/src/index.ts +++ b/projects/packages/premium-analytics/packages/sdk/src/index.ts @@ -6,22 +6,31 @@ export { ChartEmptyState, EarningsHistoryList, + LeaderboardChart, + LeaderboardSkeleton, MetricTabsChart, MetricTabsChartSkeleton, MetricTileGrid, MetricTileGridSkeleton, ReportLink, + WIDGET_ROW_LIMIT, WidgetFooter, WidgetRoot, WidgetState, + buildLeaderboardRow, buildMetricTab, + calculateDelta, chartTypeAttributeField, flattenEarningsBreakdown, + getCombinedPeriodMax, + sharePercentage, + useWidgetNavigationSearch, useWidgetRootContext, } from '@jetpack-premium-analytics/widgets-toolkit'; export { ReportScopeProvider, chartInterval, + useStatsVideoPlays, useStatsWordAdsEarnings, useStatsWordAdsStats, } from '@jetpack-premium-analytics/data'; diff --git a/projects/packages/premium-analytics/src/widget-types.php b/projects/packages/premium-analytics/src/widget-types.php index fcce8ebb221e..df870b137e32 100644 --- a/projects/packages/premium-analytics/src/widget-types.php +++ b/projects/packages/premium-analytics/src/widget-types.php @@ -45,7 +45,7 @@ * * @since 0.9.0 */ -const WIDGET_API_VERSION = '1.1.0'; +const WIDGET_API_VERSION = '1.2.0'; /** * Returns the i18n schema describing which widget metadata fields are From 41513e7ac6ff2cd16ee508cd3cd16859eea2ef86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dami=C3=A1n=20Su=C3=A1rez?= Date: Wed, 30 Sep 2026 09:47:05 +0100 Subject: [PATCH 12/22] fix phan on the VideoPress registrant if-guard the generated accessor; drop suppressions the test-only dep made unused --- .../src/features/wpcom-admin-menu/wpcom-admin-menu.php | 1 - .../src/features/wpcom-videopress/wpcom-videopress.php | 2 -- .../videopress/src/class-analytics-dashboard.php | 9 ++++++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/projects/packages/jetpack-mu-wpcom/src/features/wpcom-admin-menu/wpcom-admin-menu.php b/projects/packages/jetpack-mu-wpcom/src/features/wpcom-admin-menu/wpcom-admin-menu.php index 06bd1eda0670..a34e9e5eb954 100644 --- a/projects/packages/jetpack-mu-wpcom/src/features/wpcom-admin-menu/wpcom-admin-menu.php +++ b/projects/packages/jetpack-mu-wpcom/src/features/wpcom-admin-menu/wpcom-admin-menu.php @@ -456,7 +456,6 @@ function_exists( 'wpcom_site_has_feature' ) && class_exists( '\WPCOM_Features' ) && wpcom_site_has_feature( \WPCOM_Features::VIDEOPRESS ) ) { - // @phan-suppress-next-line PhanUndeclaredClassMethod -- class_exists guarded above; provided by sibling autoloader. \Automattic\Jetpack\VideoPress\Admin_UI::add_wp_admin_submenu(); } diff --git a/projects/packages/jetpack-mu-wpcom/src/features/wpcom-videopress/wpcom-videopress.php b/projects/packages/jetpack-mu-wpcom/src/features/wpcom-videopress/wpcom-videopress.php index 81a056eca2ef..6e15a513b9f2 100644 --- a/projects/packages/jetpack-mu-wpcom/src/features/wpcom-videopress/wpcom-videopress.php +++ b/projects/packages/jetpack-mu-wpcom/src/features/wpcom-videopress/wpcom-videopress.php @@ -56,12 +56,10 @@ function wpcom_videopress_init_admin_ui() { return; } - // @phan-suppress-next-line PhanUndeclaredClassMethod -- class_exists guarded above; provided by the sibling autoloader (bundled Jetpack on Simple). \Automattic\Jetpack\VideoPress\Admin_UI::init(); // Emit the JPVIDEOPRESS_INITIAL_STATE boot payload the wp-build dashboard hydrates from. if ( class_exists( '\Automattic\Jetpack\VideoPress\Initial_State' ) ) { - // @phan-suppress-next-line PhanUndeclaredClassMethod -- class_exists guarded above; provided by the sibling autoloader (bundled Jetpack on Simple). \Automattic\Jetpack\VideoPress\Initial_State::init(); } } diff --git a/projects/packages/videopress/src/class-analytics-dashboard.php b/projects/packages/videopress/src/class-analytics-dashboard.php index da89610c916c..b7e87f158b30 100644 --- a/projects/packages/videopress/src/class-analytics-dashboard.php +++ b/projects/packages/videopress/src/class-analytics-dashboard.php @@ -118,9 +118,9 @@ public static function register_widget_types( $registry ) { * that already holds the instance, under this name or a former one, is left alone; and one * seeded on a site where the type never registers loses it to the dashboard's own policy. * - * @param array $layout The section's default widget instances. + * @param mixed $layout The section's default widget instances; anything but an array passes through. * @param string $section_id Namespaced section identifier. - * @return array + * @return mixed The layout, with the instance appended when it is an array. */ public static function add_default_layout_instance( $layout, $section_id ) { if ( self::TRAFFIC_SECTION_ID !== $section_id || ! is_array( $layout ) ) { @@ -176,7 +176,10 @@ private static function widget_contract_is_supported() { */ private static function get_widget_manifest() { self::load_build(); - $widgets = function_exists( 'jetpack_videopress_get_registered_widget_modules' ) ? jetpack_videopress_get_registered_widget_modules() : array(); + $widgets = array(); + if ( function_exists( 'jetpack_videopress_get_registered_widget_modules' ) ) { + $widgets = jetpack_videopress_get_registered_widget_modules(); + } /** * Filters the widget manifest the package registers on the Premium Analytics dashboard. From 629974b79df90d85fd3614fbeb7e9de2cf85f3c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dami=C3=A1n=20Su=C3=A1rez?= Date: Wed, 30 Sep 2026 11:43:02 +0100 Subject: [PATCH 13/22] stub the generated manifest accessor for phan wp-build writes it into build/, which phan does not parse --- .../videopress/.phan/stubs/wp-build-stubs.php | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 projects/packages/videopress/.phan/stubs/wp-build-stubs.php diff --git a/projects/packages/videopress/.phan/stubs/wp-build-stubs.php b/projects/packages/videopress/.phan/stubs/wp-build-stubs.php new file mode 100644 index 000000000000..d961c1024515 --- /dev/null +++ b/projects/packages/videopress/.phan/stubs/wp-build-stubs.php @@ -0,0 +1,16 @@ + Date: Wed, 30 Sep 2026 11:43:31 +0100 Subject: [PATCH 14/22] give the phan stub a body phpcs accepts --- projects/packages/videopress/.phan/stubs/wp-build-stubs.php | 1 + 1 file changed, 1 insertion(+) diff --git a/projects/packages/videopress/.phan/stubs/wp-build-stubs.php b/projects/packages/videopress/.phan/stubs/wp-build-stubs.php index d961c1024515..8fc5d8281924 100644 --- a/projects/packages/videopress/.phan/stubs/wp-build-stubs.php +++ b/projects/packages/videopress/.phan/stubs/wp-build-stubs.php @@ -13,4 +13,5 @@ * @return array[] Manifest entries, each with a `name`. */ function jetpack_videopress_get_registered_widget_modules() { + return array(); } From 0774978b0c1036a2e2c97cd01e0c5efc8ae9dba2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dami=C3=A1n=20Su=C3=A1rez?= Date: Wed, 30 Sep 2026 16:19:31 +0100 Subject: [PATCH 15/22] expose Leaderboard through the SDK, not its pieces with describeError and the row limit; the video plays hook stays provisional --- ...pdate-pa-extensibility-videopress-sdk-exports | 2 +- .../premium-analytics-sdk/src/index.d.ts | 16 +++++++--------- ...pdate-pa-extensibility-videopress-sdk-exports | 2 +- .../premium-analytics/docs/dashboard-widgets.md | 2 +- .../premium-analytics/packages/sdk/src/index.ts | 9 ++------- 5 files changed, 12 insertions(+), 19 deletions(-) diff --git a/projects/js-packages/premium-analytics-sdk/changelog/update-pa-extensibility-videopress-sdk-exports b/projects/js-packages/premium-analytics-sdk/changelog/update-pa-extensibility-videopress-sdk-exports index 8e6215da4de5..078b69d84864 100644 --- a/projects/js-packages/premium-analytics-sdk/changelog/update-pa-extensibility-videopress-sdk-exports +++ b/projects/js-packages/premium-analytics-sdk/changelog/update-pa-extensibility-videopress-sdk-exports @@ -1,4 +1,4 @@ Significance: minor Type: added -Declare the leaderboard primitives and the video plays hook. +Declare the Leaderboard component, the error mapper, the widget row limit and the video plays hook. diff --git a/projects/js-packages/premium-analytics-sdk/src/index.d.ts b/projects/js-packages/premium-analytics-sdk/src/index.d.ts index 77c15c8bb5b2..c3bb7fd207b4 100644 --- a/projects/js-packages/premium-analytics-sdk/src/index.d.ts +++ b/projects/js-packages/premium-analytics-sdk/src/index.d.ts @@ -15,6 +15,7 @@ export declare function useWidgetRootContext(): any; export declare const WidgetState: AnyComponent; export declare const WidgetFooter: AnyComponent; export declare const ReportLink: AnyComponent; +export declare function describeError( ...args: any[] ): any; // Charts and metrics. export declare const ChartEmptyState: AnyComponent; @@ -27,16 +28,13 @@ export type DataFormat = any; export type CountLabel = any; export type ChartDisplayChartType = any; -// Leaderboards: the chart, its rows and the helpers that size and compare them. -export declare const LeaderboardChart: AnyComponent; -export declare const LeaderboardSkeleton: AnyComponent; +// Leaderboards: ranked rows in, with their states, comparison and drill-down handled. +export declare const Leaderboard: AnyComponent; export declare const WIDGET_ROW_LIMIT: number; -export declare function buildLeaderboardRow( ...args: any[] ): any; -export declare function calculateDelta( ...args: any[] ): any; -export declare function getCombinedPeriodMax( ...args: any[] ): any; -export declare function sharePercentage( ...args: any[] ): any; -export declare function useWidgetNavigationSearch( ...args: any[] ): any; -export type LeaderboardChartData = any; +export type LeaderboardProps = any; +export type LeaderboardRowInput = any; +export type LeaderboardStatus = any; +export type LeaderboardDrillDown = any; // Widget attributes. export declare function reportParamsAttributeField< Attributes = any >( options?: any ): any; diff --git a/projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-sdk-exports b/projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-sdk-exports index f08b5cc598c4..3ed259db09fc 100644 --- a/projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-sdk-exports +++ b/projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-sdk-exports @@ -1,4 +1,4 @@ Significance: minor Type: added -Dashboard: Expose the leaderboard primitives and the video plays hook through the SDK; the widget contract is 1.2.0. +Dashboard: Expose the Leaderboard component, the error mapper and the video plays hook through the SDK; the widget contract is 1.2.0. diff --git a/projects/packages/premium-analytics/docs/dashboard-widgets.md b/projects/packages/premium-analytics/docs/dashboard-widgets.md index 3576d2bac054..5f1f051cb3ef 100644 --- a/projects/packages/premium-analytics/docs/dashboard-widgets.md +++ b/projects/packages/premium-analytics/docs/dashboard-widgets.md @@ -211,7 +211,7 @@ It reads the package's fixed list and, once the registry can answer, the registr `WIDGET_API_VERSION` names the contract a widget is built against: the `@automattic/jetpack-premium-analytics-sdk` module and the exports it declares, the dashboard modules the facade re-exports from (`@jetpack-premium-analytics/widgets-toolkit`, `data`, `fields`, `datetime`, `externals`), and the `Widget_Type` fields the client reads. -The major changes when a widget built against the previous contract stops working; the minor when a consumer can rely on something new. So far, 1.1.0 added `former_names` and 1.2.0 the leaderboard primitives and `useStatsVideoPlays`. +The major changes when a widget built against the previous contract stops working; the minor when a consumer can rely on something new. So far, 1.1.0 added `former_names` and 1.2.0 `Leaderboard`, `describeError()`, the widget row limit and `useStatsVideoPlays`. Inside `plugins/jetpack` the package and a consumer module ship together, so the check is a formality. With the standalone `plugins/premium-analytics` next to another plugin, each brings its own copy, and the check is what keeps a widget built against 1.x from registering on a 2.x package. diff --git a/projects/packages/premium-analytics/packages/sdk/src/index.ts b/projects/packages/premium-analytics/packages/sdk/src/index.ts index ff6f713d1255..42fb638bd24e 100644 --- a/projects/packages/premium-analytics/packages/sdk/src/index.ts +++ b/projects/packages/premium-analytics/packages/sdk/src/index.ts @@ -6,8 +6,7 @@ export { ChartEmptyState, EarningsHistoryList, - LeaderboardChart, - LeaderboardSkeleton, + Leaderboard, MetricTabsChart, MetricTabsChartSkeleton, MetricTileGrid, @@ -17,14 +16,10 @@ export { WidgetFooter, WidgetRoot, WidgetState, - buildLeaderboardRow, buildMetricTab, - calculateDelta, chartTypeAttributeField, + describeError, flattenEarningsBreakdown, - getCombinedPeriodMax, - sharePercentage, - useWidgetNavigationSearch, useWidgetRootContext, } from '@jetpack-premium-analytics/widgets-toolkit'; export { From d1126993d62a681a6a46113bcd05678aee1c6466 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dami=C3=A1n=20Su=C3=A1rez?= Date: Wed, 30 Sep 2026 16:26:12 +0100 Subject: [PATCH 16/22] remove the orphaned video helpers from the toolkit they moved to the VideoPress package with the widget --- .../src/helpers/video-plays.ts | 41 ------------------- 1 file changed, 41 deletions(-) delete mode 100644 projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/video-plays.ts diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/video-plays.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/video-plays.ts deleted file mode 100644 index c06d340e28c2..000000000000 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/video-plays.ts +++ /dev/null @@ -1,41 +0,0 @@ -/** - * External dependencies - */ -import { __ } from '@wordpress/i18n'; -import type { StatsVideoPlaysItem } from '@jetpack-premium-analytics/data'; - -/** - * Shared helpers for widgets built on the Stats `video-plays` report - * (`jpa/videopress`). Comparison-row matching lives in the data layer - * (`mergeStatsVideoPlaysComparisonRows`); these cover the presentation - * concerns widgets resolve per row. - */ - -/** - * Resolve a display label for a video, falling back to a translated - * "Untitled video" label when the API provides none. - * - * @param video - The video-plays item. - * @return The video's display label. - */ -export function getVideoLabel( video: StatsVideoPlaysItem ) { - return typeof video.label === 'string' && video.label - ? video.label - : __( 'Untitled video', 'jetpack-premium-analytics-pkg' ); -} - -/** - * Resolve the key identifying a video's leaderboard row. Prefers the stable - * post ID, then the video URL, and only falls back to the display label when - * the API omits both — so multiple untitled videos don't collapse onto one key. - * - * @param video - The video-plays item. - * @return The row key. - */ -export function getVideoKey( video: StatsVideoPlaysItem ) { - if ( video.id != null ) { - return String( video.id ); - } - - return video.link || getVideoLabel( video ); -} From 938146e135d188a6ce868f23b93f3d787ad8e45e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dami=C3=A1n=20Su=C3=A1rez?= Date: Wed, 30 Sep 2026 16:54:54 +0100 Subject: [PATCH 17/22] test the Top videos render against a stand-in SDK covers the rows, the status, the error copy and the footer link --- .../widgets/top-videos/package.json | 3 + .../widgets/top-videos/test/render.test.tsx | 160 ++++++++++++++++++ 2 files changed, 163 insertions(+) create mode 100644 projects/packages/videopress/widgets/top-videos/test/render.test.tsx diff --git a/projects/packages/videopress/widgets/top-videos/package.json b/projects/packages/videopress/widgets/top-videos/package.json index 962c3fc8e6dd..c524ec7068e5 100644 --- a/projects/packages/videopress/widgets/top-videos/package.json +++ b/projects/packages/videopress/widgets/top-videos/package.json @@ -9,5 +9,8 @@ "@wordpress/icons": "^16.0.0", "@wordpress/widget-primitives": "0.7.0", "react": "18.3.1" + }, + "devDependencies": { + "@testing-library/react": "16.3.3" } } diff --git a/projects/packages/videopress/widgets/top-videos/test/render.test.tsx b/projects/packages/videopress/widgets/top-videos/test/render.test.tsx new file mode 100644 index 000000000000..8ff420b5fe71 --- /dev/null +++ b/projects/packages/videopress/widgets/top-videos/test/render.test.tsx @@ -0,0 +1,160 @@ +/** + * External dependencies + */ +import { render, screen } from '@testing-library/react'; +/** + * Internal dependencies + */ +import TopVideos from '../render'; +import type { ReactNode } from 'react'; + +const mockLeaderboard = jest.fn(); +const mockWidgetRoot = jest.fn(); +const mockUseStatsVideoPlays = jest.fn(); +const mockDescribeError = jest.fn(); + +// The SDK has no implementation outside the dashboard, so the suite stands in for it. +jest.mock( '@automattic/jetpack-premium-analytics-sdk', () => ( { + WIDGET_ROW_LIMIT: 7, + Leaderboard: ( props: { footer?: ReactNode } ) => { + mockLeaderboard( props ); + return
{ props.footer }
; + }, + ReportLink: ( { report }: { report: string } ) => View all, + WidgetRoot: ( { children, ...props }: { children: ReactNode } ) => { + mockWidgetRoot( props ); + return children; + }, + describeError: ( ...args: unknown[] ) => mockDescribeError( ...args ), + useStatsVideoPlays: ( ...args: unknown[] ) => mockUseStatsVideoPlays( ...args ), + useWidgetRootContext: () => ( { reportParams: { from: '2026-06-01', to: '2026-06-16' } } ), +} ) ); + +const refetch = jest.fn(); + +const videoPlays = ( overrides: Record< string, unknown > = {} ) => ( { + primary: { isPending: false }, + comparisonRows: { + rows: [ + { + id: 101, + label: 'Walkthrough', + link: 'https://example.com/a/', + plays: 100, + previousPlays: 80, + }, + { id: 102, label: 'Teaser', link: null, plays: 40 }, + ], + }, + hasComparison: true, + isLoading: false, + isFetching: false, + isError: false, + error: null, + refetch, + ...overrides, +} ); + +const leaderboardProps = () => mockLeaderboard.mock.lastCall?.[ 0 ]; + +describe( 'Top videos widget', () => { + beforeEach( () => { + jest.clearAllMocks(); + mockUseStatsVideoPlays.mockReturnValue( videoPlays() ); + mockDescribeError.mockReturnValue( { description: 'Described.' } ); + } ); + + it( 'requests the dashboard window, capped at the row limit', () => { + render( ); + + expect( mockUseStatsVideoPlays ).toHaveBeenCalledWith( + { from: '2026-06-01', to: '2026-06-16', max: 7 }, + { maxRows: 7 } + ); + } ); + + it( 'hands the host attributes and error handler to the widget root', () => { + const attributes = { reportParams: { from: '2026-06-01', to: '2026-06-16' } }; + const setError = jest.fn(); + + render( ); + + expect( mockWidgetRoot ).toHaveBeenCalledWith( { attributes, setError } ); + } ); + + it( 'turns each video into a row that links to its detail page', () => { + render( ); + + expect( leaderboardProps().rows ).toEqual( [ + { + id: '101', + label: 'Walkthrough', + value: 100, + previousValue: 80, + action: { kind: 'videoLink', id: 101, href: 'https://example.com/a/' }, + }, + { + id: '102', + label: 'Teaser', + value: 40, + previousValue: undefined, + action: { kind: 'videoLink', id: 102, href: null }, + }, + ] ); + } ); + + it( 'passes the request status through', () => { + mockUseStatsVideoPlays.mockReturnValue( videoPlays( { isFetching: true } ) ); + + render( ); + + expect( leaderboardProps().status ).toEqual( { + isLoading: false, + isFetching: true, + isError: false, + hasComparison: true, + refetch, + } ); + } ); + + it( 'counts a pending query as loading', () => { + mockUseStatsVideoPlays.mockReturnValue( + videoPlays( { primary: { isPending: true }, comparisonRows: undefined } ) + ); + + render( ); + + expect( leaderboardProps().status.isLoading ).toBe( true ); + expect( leaderboardProps().rows ).toEqual( [] ); + } ); + + it( 'keeps a failed refetch quiet while rows are on screen', () => { + mockUseStatsVideoPlays.mockReturnValue( videoPlays( { isError: true } ) ); + + render( ); + + expect( leaderboardProps().status.isError ).toBe( false ); + } ); + + it( 'reports the failure when there are no rows to show', () => { + const error = { status: 500 }; + mockUseStatsVideoPlays.mockReturnValue( + videoPlays( { isError: true, error, comparisonRows: { rows: [] } } ) + ); + + render( ); + + expect( leaderboardProps().status.isError ).toBe( true ); + expect( mockDescribeError ).toHaveBeenCalledWith( error, { + retryDescription: "We couldn't load video plays. Please try again in a moment.", + onRetry: refetch, + } ); + expect( leaderboardProps().error ).toEqual( { description: 'Described.' } ); + } ); + + it( 'links the footer to the Videos report', () => { + render( ); + + expect( screen.getByRole( 'link', { name: 'View all' } ) ).toHaveAttribute( 'href', '#videos' ); + } ); +} ); From 970e2e1e28ca900e6aad074992f044f1d1c9359a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dami=C3=A1n=20Su=C3=A1rez?= Date: Wed, 30 Sep 2026 16:59:02 +0100 Subject: [PATCH 18/22] test the video plays hook directly the widget suite that exercised it left the package --- .../__tests__/use-stats-video-plays.test.tsx | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 projects/packages/premium-analytics/packages/data/src/hooks/__tests__/use-stats-video-plays.test.tsx diff --git a/projects/packages/premium-analytics/packages/data/src/hooks/__tests__/use-stats-video-plays.test.tsx b/projects/packages/premium-analytics/packages/data/src/hooks/__tests__/use-stats-video-plays.test.tsx new file mode 100644 index 000000000000..b397ca3a5ef1 --- /dev/null +++ b/projects/packages/premium-analytics/packages/data/src/hooks/__tests__/use-stats-video-plays.test.tsx @@ -0,0 +1,83 @@ +/** + * External dependencies + */ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { renderHook, waitFor } from '@testing-library/react'; +import apiFetch from '@wordpress/api-fetch'; +/** + * Internal dependencies + */ +import { useStatsVideoPlays } from '../use-stats-video-plays'; +import type { ReactNode } from 'react'; + +jest.mock( '@wordpress/api-fetch', () => jest.fn() ); + +const mockApiFetch = apiFetch as unknown as jest.Mock; + +// The default fetcher serves the parked comparison query, as the dashboard's own client does. +const queryClient = new QueryClient( { + defaultOptions: { queries: { retry: false, queryFn: async () => null } }, +} ); + +function wrapper( { children }: { children: ReactNode } ) { + return { children }; +} + +const plays = [ + { + post_id: 101, + title: 'Walkthrough', + url: 'https://example.com/video/101/', + plays: 100, + impressions: 200, + watch_time: 1000, + retention_rate: 60, + }, +]; + +const RESPONSE = { + date: '2026-03-10', + period: 'day', + summary: { plays }, + days: { '2026-03-10': { plays } }, +}; + +const RANGE = { from: '2026-03-01', to: '2026-03-10', interval: 'day' } as const; + +const countQueries = ( name: string ) => + queryClient.getQueryCache().findAll( { queryKey: [ 'stats', name, '1.1' ] } ).length; + +describe( 'useStatsVideoPlays', () => { + beforeEach( () => { + queryClient.clear(); + mockApiFetch.mockReset(); + mockApiFetch.mockResolvedValue( RESPONSE ); + } ); + + it( 'reads the report window through the video plays query', async () => { + const { result } = renderHook( () => useStatsVideoPlays( RANGE, { maxRows: 10 } ), { + wrapper, + } ); + + await waitFor( () => expect( result.current.comparisonRows?.rows ).toHaveLength( 1 ) ); + + expect( countQueries( 'video-plays' ) ).toBe( 1 ); + expect( countQueries( 'video-plays-summary' ) ).toBe( 0 ); + expect( result.current.comparisonRows?.rows[ 0 ] ).toMatchObject( { + id: 101, + label: 'Walkthrough', + plays: 100, + } ); + } ); + + it( 'switches to the exact-range summary query for summarized complete stats', async () => { + renderHook( () => useStatsVideoPlays( { ...RANGE, complete_stats: 1, summarize: 1 } ), { + wrapper, + } ); + + await waitFor( () => expect( mockApiFetch ).toHaveBeenCalled() ); + + expect( countQueries( 'video-plays-summary' ) ).toBe( 1 ); + expect( countQueries( 'video-plays' ) ).toBe( 0 ); + } ); +} ); From 459dd3a8b8088c77442da21a8af5303849d24f8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dami=C3=A1n=20Su=C3=A1rez?= Date: Wed, 30 Sep 2026 17:27:03 +0100 Subject: [PATCH 19/22] keep the widget row limit out of the SDK the Leaderboard caps its rows; a consumer sizes its own request --- .../changelog/update-pa-extensibility-videopress-sdk-exports | 2 +- projects/js-packages/premium-analytics-sdk/src/index.d.ts | 1 - projects/packages/premium-analytics/docs/dashboard-widgets.md | 2 +- projects/packages/premium-analytics/packages/sdk/src/index.ts | 1 - 4 files changed, 2 insertions(+), 4 deletions(-) diff --git a/projects/js-packages/premium-analytics-sdk/changelog/update-pa-extensibility-videopress-sdk-exports b/projects/js-packages/premium-analytics-sdk/changelog/update-pa-extensibility-videopress-sdk-exports index 078b69d84864..8f891e63ca14 100644 --- a/projects/js-packages/premium-analytics-sdk/changelog/update-pa-extensibility-videopress-sdk-exports +++ b/projects/js-packages/premium-analytics-sdk/changelog/update-pa-extensibility-videopress-sdk-exports @@ -1,4 +1,4 @@ Significance: minor Type: added -Declare the Leaderboard component, the error mapper, the widget row limit and the video plays hook. +Declare the Leaderboard component, the error mapper and the video plays hook. diff --git a/projects/js-packages/premium-analytics-sdk/src/index.d.ts b/projects/js-packages/premium-analytics-sdk/src/index.d.ts index c3bb7fd207b4..8d2e722feeaf 100644 --- a/projects/js-packages/premium-analytics-sdk/src/index.d.ts +++ b/projects/js-packages/premium-analytics-sdk/src/index.d.ts @@ -30,7 +30,6 @@ export type ChartDisplayChartType = any; // Leaderboards: ranked rows in, with their states, comparison and drill-down handled. export declare const Leaderboard: AnyComponent; -export declare const WIDGET_ROW_LIMIT: number; export type LeaderboardProps = any; export type LeaderboardRowInput = any; export type LeaderboardStatus = any; diff --git a/projects/packages/premium-analytics/docs/dashboard-widgets.md b/projects/packages/premium-analytics/docs/dashboard-widgets.md index 5f1f051cb3ef..3f186f083e63 100644 --- a/projects/packages/premium-analytics/docs/dashboard-widgets.md +++ b/projects/packages/premium-analytics/docs/dashboard-widgets.md @@ -211,7 +211,7 @@ It reads the package's fixed list and, once the registry can answer, the registr `WIDGET_API_VERSION` names the contract a widget is built against: the `@automattic/jetpack-premium-analytics-sdk` module and the exports it declares, the dashboard modules the facade re-exports from (`@jetpack-premium-analytics/widgets-toolkit`, `data`, `fields`, `datetime`, `externals`), and the `Widget_Type` fields the client reads. -The major changes when a widget built against the previous contract stops working; the minor when a consumer can rely on something new. So far, 1.1.0 added `former_names` and 1.2.0 `Leaderboard`, `describeError()`, the widget row limit and `useStatsVideoPlays`. +The major changes when a widget built against the previous contract stops working; the minor when a consumer can rely on something new. So far, 1.1.0 added `former_names` and 1.2.0 `Leaderboard`, `describeError()` and `useStatsVideoPlays`. Inside `plugins/jetpack` the package and a consumer module ship together, so the check is a formality. With the standalone `plugins/premium-analytics` next to another plugin, each brings its own copy, and the check is what keeps a widget built against 1.x from registering on a 2.x package. diff --git a/projects/packages/premium-analytics/packages/sdk/src/index.ts b/projects/packages/premium-analytics/packages/sdk/src/index.ts index 42fb638bd24e..efa3f8b72148 100644 --- a/projects/packages/premium-analytics/packages/sdk/src/index.ts +++ b/projects/packages/premium-analytics/packages/sdk/src/index.ts @@ -12,7 +12,6 @@ export { MetricTileGrid, MetricTileGridSkeleton, ReportLink, - WIDGET_ROW_LIMIT, WidgetFooter, WidgetRoot, WidgetState, From f62bfb81cf5d387522e47a9eb1aed8dd185fb40b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dami=C3=A1n=20Su=C3=A1rez?= Date: Wed, 30 Sep 2026 17:27:54 +0100 Subject: [PATCH 20/22] size the Top videos request in the widget the SDK no longer exposes the dashboard's row limit --- .../packages/videopress/widgets/top-videos/render.tsx | 8 +++++--- .../videopress/widgets/top-videos/test/render.test.tsx | 7 +++---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/projects/packages/videopress/widgets/top-videos/render.tsx b/projects/packages/videopress/widgets/top-videos/render.tsx index 09d2e69a1fc4..8caf5aa6972c 100644 --- a/projects/packages/videopress/widgets/top-videos/render.tsx +++ b/projects/packages/videopress/widgets/top-videos/render.tsx @@ -4,7 +4,6 @@ import { Leaderboard, ReportLink, - WIDGET_ROW_LIMIT, WidgetRoot, describeError, useStatsVideoPlays, @@ -22,6 +21,9 @@ import type { TopVideosAttributes } from './widget'; import type { WidgetRenderProps } from '@wordpress/widget-primitives'; import type { ComponentProps } from 'react'; +// Videos the widget asks for. The leaderboard applies the dashboard's own cap to what it shows. +const TOP_VIDEOS_LIMIT = 10; + // The dashboard injects its date range and comparison state through // `reportParams`; the widget has no settings of its own. type TopVideosRenderAttributes = TopVideosAttributes & Partial< ReportParamsFieldAttributes >; @@ -58,14 +60,14 @@ function toLeaderboardRow( row: VideoPlaysRow ): LeaderboardRowInput { function TopVideosReport() { const { reportParams } = useWidgetRootContext(); const statsParams = useMemo( - () => ( { ...reportParams, max: WIDGET_ROW_LIMIT } ), + () => ( { ...reportParams, max: TOP_VIDEOS_LIMIT } ), [ reportParams ] ); // The hook merges comparison rows and gates `hasComparison` on at least one // visible row having a match, so the chart never fabricates vs-zero deltas. const { primary, comparisonRows, hasComparison, isLoading, isFetching, isError, error, refetch } = - useStatsVideoPlays( statsParams, { maxRows: WIDGET_ROW_LIMIT } ); + useStatsVideoPlays( statsParams, { maxRows: TOP_VIDEOS_LIMIT } ); const rows = useMemo( () => toVideoPlaysRows( comparisonRows?.rows ?? [] ).map( toLeaderboardRow ), diff --git a/projects/packages/videopress/widgets/top-videos/test/render.test.tsx b/projects/packages/videopress/widgets/top-videos/test/render.test.tsx index 8ff420b5fe71..8bd190d8e3a3 100644 --- a/projects/packages/videopress/widgets/top-videos/test/render.test.tsx +++ b/projects/packages/videopress/widgets/top-videos/test/render.test.tsx @@ -15,7 +15,6 @@ const mockDescribeError = jest.fn(); // The SDK has no implementation outside the dashboard, so the suite stands in for it. jest.mock( '@automattic/jetpack-premium-analytics-sdk', () => ( { - WIDGET_ROW_LIMIT: 7, Leaderboard: ( props: { footer?: ReactNode } ) => { mockLeaderboard( props ); return
{ props.footer }
; @@ -64,12 +63,12 @@ describe( 'Top videos widget', () => { mockDescribeError.mockReturnValue( { description: 'Described.' } ); } ); - it( 'requests the dashboard window, capped at the row limit', () => { + it( 'requests its own number of videos for the dashboard window', () => { render( ); expect( mockUseStatsVideoPlays ).toHaveBeenCalledWith( - { from: '2026-06-01', to: '2026-06-16', max: 7 }, - { maxRows: 7 } + { from: '2026-06-01', to: '2026-06-16', max: 10 }, + { maxRows: 10 } ); } ); From 7af01a56ecd50e2b3fb6b001d185682a5d7fdd50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dami=C3=A1n=20Su=C3=A1rez?= Date: Thu, 1 Oct 2026 14:40:42 +0100 Subject: [PATCH 21/22] feed the test manifest through the host filter drops the package's own hook; the availability docblock stops naming the widget --- .../Videopress_Widgets_Test.php | 5 ++-- .../src/videopress-availability.php | 4 +-- .../src/class-analytics-dashboard.php | 30 ++++--------------- .../tests/php/Analytics_Dashboard_Test.php | 5 ++-- ...cs_Dashboard_Without_Widget_Types_Test.php | 6 ---- .../analytics-dashboard-manifest-fixture.php | 4 +-- 6 files changed, 16 insertions(+), 38 deletions(-) diff --git a/projects/packages/jetpack-mu-wpcom/tests/php/features/premium-analytics/Videopress_Widgets_Test.php b/projects/packages/jetpack-mu-wpcom/tests/php/features/premium-analytics/Videopress_Widgets_Test.php index 54049e7074cb..b0863c786612 100644 --- a/projects/packages/jetpack-mu-wpcom/tests/php/features/premium-analytics/Videopress_Widgets_Test.php +++ b/projects/packages/jetpack-mu-wpcom/tests/php/features/premium-analytics/Videopress_Widgets_Test.php @@ -10,6 +10,7 @@ use Automattic\Jetpack\VideoPress\Analytics_Dashboard; use Brain\Monkey\Functions; use PHPUnit\Framework\Attributes\CoversFunction; +use const Automattic\Jetpack\PremiumAnalytics\REGISTRABLE_WIDGET_TYPES_FILTER; // Required by path, like the section API below: the vendored classmap predates these classes. require_once Jetpack_Mu_Wpcom::PKG_DIR . 'vendor/automattic/jetpack-premium-analytics/src/class-capabilities.php'; @@ -35,7 +36,7 @@ class Videopress_Widgets_Test extends \WorDBless\BaseTestCase { */ public function set_up() { parent::set_up(); - add_filter( Analytics_Dashboard::WIDGET_MANIFEST_FILTER, array( $this, 'widget_manifest' ) ); + add_filter( REGISTRABLE_WIDGET_TYPES_FILTER, array( $this, 'widget_manifest' ) ); } /** @@ -62,7 +63,7 @@ public function widget_manifest() { * Reset the widget registry between tests. */ public function tear_down() { - remove_filter( Analytics_Dashboard::WIDGET_MANIFEST_FILTER, array( $this, 'widget_manifest' ) ); + remove_filter( REGISTRABLE_WIDGET_TYPES_FILTER, array( $this, 'widget_manifest' ) ); $instance = new ReflectionProperty( Widget_Type_Registry::class, 'instance' ); if ( PHP_VERSION_ID < 80100 ) { $instance->setAccessible( true ); diff --git a/projects/packages/premium-analytics/src/videopress-availability.php b/projects/packages/premium-analytics/src/videopress-availability.php index 156dab5ec2c9..87ec377f048b 100644 --- a/projects/packages/premium-analytics/src/videopress-availability.php +++ b/projects/packages/premium-analytics/src/videopress-availability.php @@ -54,8 +54,8 @@ function is_videopress_available() { /** * Filters whether Premium Analytics treats VideoPress as available. * - * Hides the Top videos widget, the Videos report, and the video detail page - * when false. + * Hides the Videos report and the video detail page when false. The Top videos + * widget is the VideoPress package's call: it registers the widget. * * @param bool $is_available Whether VideoPress was detected in the current request. */ diff --git a/projects/packages/videopress/src/class-analytics-dashboard.php b/projects/packages/videopress/src/class-analytics-dashboard.php index b7e87f158b30..23b535c693d3 100644 --- a/projects/packages/videopress/src/class-analytics-dashboard.php +++ b/projects/packages/videopress/src/class-analytics-dashboard.php @@ -53,16 +53,11 @@ class Analytics_Dashboard { const TEXTDOMAIN = 'jetpack-videopress-pkg'; /** - * Lowest widget contract the build works against: the leaderboard primitives and the video + * Lowest widget contract the build works against: the Leaderboard component and the video * plays hook the widget imports reached the SDK in 1.2.0. */ const MIN_WIDGET_API_VERSION = '1.2.0'; - /** - * Filter over the manifest the package registers from. - */ - const WIDGET_MANIFEST_FILTER = 'jetpack_videopress_analytics_dashboard_widget_manifest'; - /** * Hook the registrant on the dashboard's registry action and the seed on its layout filter. * @@ -95,13 +90,8 @@ public static function register_widget_types( $registry ) { return; } - $widgets = self::get_widget_manifest(); - if ( ! $widgets ) { - return; - } - register_widget_types_from_manifest( - $widgets, + self::get_widget_manifest(), array( 'textdomain' => self::TEXTDOMAIN, 'i18n_manifest' => add_query_arg( 'ver', Package_Version::PACKAGE_VERSION, plugins_url( 'i18n-manifest.json', self::build_dir() . '/build.php' ) ), @@ -170,25 +160,17 @@ private static function widget_contract_is_supported() { } /** - * The widget manifest the package registers from: what its build generated, unless filtered. + * The widget manifest the package registers from: what its build generated, none without a build. * * @return array[] Manifest entries, as `jetpack_videopress_get_registered_widget_modules()` returns them. */ private static function get_widget_manifest() { self::load_build(); - $widgets = array(); - if ( function_exists( 'jetpack_videopress_get_registered_widget_modules' ) ) { - $widgets = jetpack_videopress_get_registered_widget_modules(); + if ( ! function_exists( 'jetpack_videopress_get_registered_widget_modules' ) ) { + return array(); } - /** - * Filters the widget manifest the package registers on the Premium Analytics dashboard. - * - * @since $$next-version$$ - * - * @param array[] $widgets Manifest entries, each with a `name`. - */ - return (array) apply_filters( self::WIDGET_MANIFEST_FILTER, $widgets ); + return (array) jetpack_videopress_get_registered_widget_modules(); } /** diff --git a/projects/packages/videopress/tests/php/Analytics_Dashboard_Test.php b/projects/packages/videopress/tests/php/Analytics_Dashboard_Test.php index a511b9629b90..55060559a684 100644 --- a/projects/packages/videopress/tests/php/Analytics_Dashboard_Test.php +++ b/projects/packages/videopress/tests/php/Analytics_Dashboard_Test.php @@ -16,6 +16,7 @@ use function Automattic\Jetpack\PremiumAnalytics\get_registered_dashboard_section; use function Automattic\Jetpack\PremiumAnalytics\register_default_dashboard_sections; use const Automattic\Jetpack\PremiumAnalytics\DASHBOARD_NAME; +use const Automattic\Jetpack\PremiumAnalytics\REGISTRABLE_WIDGET_TYPES_FILTER; // Required by path, like the consumers do: the dashboard API is not autoloaded. require_once __DIR__ . '/../../vendor/automattic/jetpack-premium-analytics/src/class-capabilities.php'; @@ -40,7 +41,7 @@ public function set_up() { parent::set_up(); add_filter( 'jetpack_premium_analytics_widgets_manifest_path', array( $this, 'use_absent_widget_manifest' ) ); - add_filter( Analytics_Dashboard::WIDGET_MANIFEST_FILTER, 'jetpack_videopress_test_widget_manifest' ); + add_filter( REGISTRABLE_WIDGET_TYPES_FILTER, 'jetpack_videopress_test_widget_manifest' ); } /** @@ -50,7 +51,7 @@ public function tear_down() { remove_action( Analytics_Dashboard::REGISTER_WIDGET_TYPES_ACTION, array( Analytics_Dashboard::class, 'register_widget_types' ), 20 ); remove_filter( Analytics_Dashboard::DEFAULT_LAYOUT_FILTER, array( Analytics_Dashboard::class, 'add_default_layout_instance' ), 10 ); remove_filter( 'jetpack_premium_analytics_widgets_manifest_path', array( $this, 'use_absent_widget_manifest' ) ); - remove_filter( Analytics_Dashboard::WIDGET_MANIFEST_FILTER, 'jetpack_videopress_test_widget_manifest' ); + remove_filter( REGISTRABLE_WIDGET_TYPES_FILTER, 'jetpack_videopress_test_widget_manifest' ); foreach ( array( Dashboard_Section_Registry::class, Widget_Type_Registry::class ) as $class ) { $instance = new \ReflectionProperty( $class, 'instance' ); diff --git a/projects/packages/videopress/tests/php/Analytics_Dashboard_Without_Widget_Types_Test.php b/projects/packages/videopress/tests/php/Analytics_Dashboard_Without_Widget_Types_Test.php index f0fb1249f4f2..58d5483e6e4d 100644 --- a/projects/packages/videopress/tests/php/Analytics_Dashboard_Without_Widget_Types_Test.php +++ b/projects/packages/videopress/tests/php/Analytics_Dashboard_Without_Widget_Types_Test.php @@ -17,7 +17,6 @@ require_once __DIR__ . '/../../vendor/automattic/jetpack-premium-analytics/src/class-capabilities.php'; require_once __DIR__ . '/../../vendor/automattic/jetpack-premium-analytics/src/class-enablement-setting.php'; require_once __DIR__ . '/../../vendor/automattic/jetpack-premium-analytics/src/dashboard-sections.php'; -require_once __DIR__ . '/mocks/analytics-dashboard-manifest-fixture.php'; /** * Without the widget contract version, the widget type waits and the layout seed still lands: the @@ -34,11 +33,6 @@ #[PreserveGlobalState( false )] class Analytics_Dashboard_Without_Widget_Types_Test extends BaseTestCase { - public function set_up() { - parent::set_up(); - add_filter( Analytics_Dashboard::WIDGET_MANIFEST_FILTER, 'jetpack_videopress_test_widget_manifest' ); - } - public function test_the_widget_type_waits_for_the_widget_contract_version() { $this->assertFalse( defined( 'Automattic\\Jetpack\\PremiumAnalytics\\WIDGET_API_VERSION' ) ); $registry = new Widget_Type_Registry(); diff --git a/projects/packages/videopress/tests/php/mocks/analytics-dashboard-manifest-fixture.php b/projects/packages/videopress/tests/php/mocks/analytics-dashboard-manifest-fixture.php index 351aa713632a..55a67c7508ff 100644 --- a/projects/packages/videopress/tests/php/mocks/analytics-dashboard-manifest-fixture.php +++ b/projects/packages/videopress/tests/php/mocks/analytics-dashboard-manifest-fixture.php @@ -1,7 +1,7 @@ Date: Fri, 2 Oct 2026 09:13:41 +0100 Subject: [PATCH 22/22] expose the CSV download action through the SDK the button takes the linked report by id, contract 1.3.0; the parity test drops the moved widget --- ...ate-pa-extensibility-videopress-top-videos | 4 +++ .../premium-analytics-sdk/src/index.d.ts | 1 + ...pa-extensibility-videopress-top-videos-sdk | 4 +++ .../docs/dashboard-widgets.md | 2 +- .../packages/sdk/src/index.ts | 1 + .../download-csv/csv-download-action.ts | 7 ++-- .../exporter-csv-download-button.tsx | 24 +++++++++++-- .../src/report-exports/by-report.ts | 34 +++++++++++++++++++ .../premium-analytics/src/widget-types.php | 2 +- .../js/widget-report-csv-parity.test.tsx | 24 ++----------- .../src/class-analytics-dashboard.php | 6 ++-- .../videopress/widgets/top-videos/render.tsx | 3 +- .../widgets/top-videos/test/render.test.tsx | 18 +++++++++- 13 files changed, 96 insertions(+), 34 deletions(-) create mode 100644 projects/js-packages/premium-analytics-sdk/changelog/update-pa-extensibility-videopress-top-videos create mode 100644 projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-top-videos-sdk create mode 100644 projects/packages/premium-analytics/packages/widgets-toolkit/src/report-exports/by-report.ts diff --git a/projects/js-packages/premium-analytics-sdk/changelog/update-pa-extensibility-videopress-top-videos b/projects/js-packages/premium-analytics-sdk/changelog/update-pa-extensibility-videopress-top-videos new file mode 100644 index 000000000000..b741c2f08c03 --- /dev/null +++ b/projects/js-packages/premium-analytics-sdk/changelog/update-pa-extensibility-videopress-top-videos @@ -0,0 +1,4 @@ +Significance: minor +Type: added + +Declare the CSV download action of the linked report. diff --git a/projects/js-packages/premium-analytics-sdk/src/index.d.ts b/projects/js-packages/premium-analytics-sdk/src/index.d.ts index 8d2e722feeaf..910aeb8c3246 100644 --- a/projects/js-packages/premium-analytics-sdk/src/index.d.ts +++ b/projects/js-packages/premium-analytics-sdk/src/index.d.ts @@ -15,6 +15,7 @@ export declare function useWidgetRootContext(): any; export declare const WidgetState: AnyComponent; export declare const WidgetFooter: AnyComponent; export declare const ReportLink: AnyComponent; +export declare const ExporterCsvDownloadButton: AnyComponent; export declare function describeError( ...args: any[] ): any; // Charts and metrics. diff --git a/projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-top-videos-sdk b/projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-top-videos-sdk new file mode 100644 index 000000000000..d5a68942e578 --- /dev/null +++ b/projects/packages/premium-analytics/changelog/update-pa-extensibility-videopress-top-videos-sdk @@ -0,0 +1,4 @@ +Significance: minor +Type: added + +Dashboard: Expose the CSV download action of the linked report through the SDK; the widget contract is 1.3.0. diff --git a/projects/packages/premium-analytics/docs/dashboard-widgets.md b/projects/packages/premium-analytics/docs/dashboard-widgets.md index 3f186f083e63..4865bbf858ad 100644 --- a/projects/packages/premium-analytics/docs/dashboard-widgets.md +++ b/projects/packages/premium-analytics/docs/dashboard-widgets.md @@ -211,7 +211,7 @@ It reads the package's fixed list and, once the registry can answer, the registr `WIDGET_API_VERSION` names the contract a widget is built against: the `@automattic/jetpack-premium-analytics-sdk` module and the exports it declares, the dashboard modules the facade re-exports from (`@jetpack-premium-analytics/widgets-toolkit`, `data`, `fields`, `datetime`, `externals`), and the `Widget_Type` fields the client reads. -The major changes when a widget built against the previous contract stops working; the minor when a consumer can rely on something new. So far, 1.1.0 added `former_names` and 1.2.0 `Leaderboard`, `describeError()` and `useStatsVideoPlays`. +The major changes when a widget built against the previous contract stops working; the minor when a consumer can rely on something new. So far, 1.1.0 added `former_names` and 1.2.0 `Leaderboard`, `describeError()` and `useStatsVideoPlays`, and 1.3.0 `ExporterCsvDownloadButton`, which takes the linked report by id. Inside `plugins/jetpack` the package and a consumer module ship together, so the check is a formality. With the standalone `plugins/premium-analytics` next to another plugin, each brings its own copy, and the check is what keeps a widget built against 1.x from registering on a 2.x package. diff --git a/projects/packages/premium-analytics/packages/sdk/src/index.ts b/projects/packages/premium-analytics/packages/sdk/src/index.ts index efa3f8b72148..1f51fa99a8a8 100644 --- a/projects/packages/premium-analytics/packages/sdk/src/index.ts +++ b/projects/packages/premium-analytics/packages/sdk/src/index.ts @@ -6,6 +6,7 @@ export { ChartEmptyState, EarningsHistoryList, + ExporterCsvDownloadButton, Leaderboard, MetricTabsChart, MetricTabsChartSkeleton, diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/download-csv/csv-download-action.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/download-csv/csv-download-action.ts index a6700b56f7ea..d6046fe196c8 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/download-csv/csv-download-action.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/download-csv/csv-download-action.ts @@ -43,7 +43,8 @@ function useCsvDownloadAction( } export type UseExporterCsvActionOptions< TItem, TRow > = { - exporter: ReportCsvExporter< TItem, TRow >; + /** Without one there is no download to offer. */ + exporter?: ReportCsvExporter< TItem, TRow >; /** The widget's request state for the active range; the error is the primary period's alone. */ status: ReportCsvExportStatus; /** How many rows the widget shows; an empty widget offers no download. */ @@ -59,7 +60,9 @@ export function useExporterCsvAction< TItem, TRow >( { const { reportParams } = useWidgetRootContext(); return useCsvDownloadAction( - isReportCsvReady( status, rowCount ) ? () => downloadReportCsv( exporter, reportParams ) : null + exporter && isReportCsvReady( status, rowCount ) + ? () => downloadReportCsv( exporter, reportParams ) + : null ); } diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/download-csv/exporter-csv-download-button.tsx b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/download-csv/exporter-csv-download-button.tsx index 659de5f70f98..e3986ef5ef84 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/download-csv/exporter-csv-download-button.tsx +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/components/download-csv/exporter-csv-download-button.tsx @@ -1,23 +1,43 @@ /** * Internal dependencies */ +import { + eraseExporterRowTypes, + reportCsvExporters, + type ExportableReport, +} from '../../report-exports/by-report'; import { useExporterCsvAction, type UseExporterCsvActionOptions } from './csv-download-action'; import { CsvDownloadButton, type CsvDownloadButtonProps } from './csv-download-button'; +import type { ReportCsvExporter } from '../../report-exports/types'; type ExporterCsvDownloadButtonProps< TItem, TRow > = Omit< CsvDownloadButtonProps, 'onDownload' | 'label' | 'icon' > & - UseExporterCsvActionOptions< TItem, TRow >; + Omit< UseExporterCsvActionOptions< TItem, TRow >, 'exporter' > & { + /** + * The linked report's exporter. A widget outside the dashboard names the report instead. + */ + exporter?: ReportCsvExporter< TItem, TRow >; + /** + * Id of the linked report, e.g. `videos`, for a widget that holds no exporter. + */ + report?: ExportableReport; + }; /** Widget action that downloads the linked report's full CSV once the widget's rows settle. */ export function ExporterCsvDownloadButton< TItem, TRow >( { exporter, + report, status, rowCount, ...buttonProps }: ExporterCsvDownloadButtonProps< TItem, TRow > ) { - const action = useExporterCsvAction( { exporter, status, rowCount } ); + const action = useExporterCsvAction( { + exporter: exporter ? eraseExporterRowTypes( exporter ) : report && reportCsvExporters[ report ], + status, + rowCount, + } ); if ( ! action ) { return null; diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/report-exports/by-report.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/report-exports/by-report.ts new file mode 100644 index 000000000000..a92e86d1c8cc --- /dev/null +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/report-exports/by-report.ts @@ -0,0 +1,34 @@ +/** + * Internal dependencies + */ +import { authorsCsvExporter } from './authors'; +import { clicksCsvExporter } from './clicks'; +import { fileDownloadsCsvExporter } from './file-downloads'; +import { referrersCsvExporter } from './referrers'; +import { searchTermsCsvExporter } from './search-terms'; +import { videosCsvExporter } from './videos'; +import type { ReportCsvExporter } from './types'; + +/** + * Erase an exporter's row types: a widget names the report, the exporter keeps its rows to itself. + * + * @param exporter - A report's CSV exporter. + * @return The same exporter, untyped. + */ +export function eraseExporterRowTypes< TItem, TRow >( + exporter: ReportCsvExporter< TItem, TRow > +): ReportCsvExporter< unknown, unknown > { + return exporter as unknown as ReportCsvExporter< unknown, unknown >; +} + +/** The CSV of each report a widget can name by id. Posts has one per tab, so it is not here. */ +export const reportCsvExporters = { + authors: eraseExporterRowTypes( authorsCsvExporter ), + clicks: eraseExporterRowTypes( clicksCsvExporter ), + downloads: eraseExporterRowTypes( fileDownloadsCsvExporter ), + referrers: eraseExporterRowTypes( referrersCsvExporter ), + 'search-terms': eraseExporterRowTypes( searchTermsCsvExporter ), + videos: eraseExporterRowTypes( videosCsvExporter ), +}; + +export type ExportableReport = keyof typeof reportCsvExporters; diff --git a/projects/packages/premium-analytics/src/widget-types.php b/projects/packages/premium-analytics/src/widget-types.php index df870b137e32..f1e6cc0eb4cf 100644 --- a/projects/packages/premium-analytics/src/widget-types.php +++ b/projects/packages/premium-analytics/src/widget-types.php @@ -45,7 +45,7 @@ * * @since 0.9.0 */ -const WIDGET_API_VERSION = '1.2.0'; +const WIDGET_API_VERSION = '1.3.0'; /** * Returns the i18n schema describing which widget metadata fields are diff --git a/projects/packages/premium-analytics/tests/js/widget-report-csv-parity.test.tsx b/projects/packages/premium-analytics/tests/js/widget-report-csv-parity.test.tsx index f9fdca62e7fd..f9d8be24334c 100644 --- a/projects/packages/premium-analytics/tests/js/widget-report-csv-parity.test.tsx +++ b/projects/packages/premium-analytics/tests/js/widget-report-csv-parity.test.tsx @@ -19,7 +19,6 @@ import DownloadsReportPage from '../../routes/reports/downloads/page'; import PostsReportPage from '../../routes/reports/posts/page'; import ReferrersReportPage from '../../routes/reports/referrers/page'; import SearchTermsReportPage from '../../routes/reports/search-terms/page'; -import VideosReportPage from '../../routes/reports/videos/page'; import AuthorsWidget from '../../widgets/authors/render'; import ClicksWidget from '../../widgets/clicks/render'; import FileDownloadsWidget from '../../widgets/file-downloads/render'; @@ -27,7 +26,6 @@ import ReferrersWidget from '../../widgets/referrers/render'; import SearchTermsWidget from '../../widgets/search-terms/render'; import { captureCsvDownloads } from '../../widgets/test-utils'; import TopPostsWidget from '../../widgets/top-posts/render'; -import VideoPressWidget from '../../widgets/videopress/render'; import { setMockRouteSearch } from './route-test-utils'; import type { ComponentType, ReactElement, ReactNode } from 'react'; @@ -130,21 +128,7 @@ const RESPONSES: Record< string, unknown > = { encrypted_search_terms: 6, }, }, - 'stats/video-plays': { - date: '2026-03-10', - period: 'day', - summary: { - plays: Array.from( { length: 12 }, ( _, index ) => ( { - post_id: index + 1, - title: `Video ${ index + 1 }`, - url: `https://example.com/video/${ index + 1 }/`, - plays: ( ( index * 5 ) % 12 ) + 1, - impressions: 20, - watch_time: 1.5, - retention_rate: 40, - } ) ), - }, - }, + 'stats/clicks': { date: '2026-03-10', days: {}, @@ -225,11 +209,7 @@ const CASES: { Page: SearchTermsReportPage, widget: reportParams => , }, - { - name: 'Videos', - Page: VideosReportPage, - widget: reportParams => , - }, + { name: 'Clicks', Page: ClicksReportPage, diff --git a/projects/packages/videopress/src/class-analytics-dashboard.php b/projects/packages/videopress/src/class-analytics-dashboard.php index 23b535c693d3..7ba204652c23 100644 --- a/projects/packages/videopress/src/class-analytics-dashboard.php +++ b/projects/packages/videopress/src/class-analytics-dashboard.php @@ -53,10 +53,10 @@ class Analytics_Dashboard { const TEXTDOMAIN = 'jetpack-videopress-pkg'; /** - * Lowest widget contract the build works against: the Leaderboard component and the video - * plays hook the widget imports reached the SDK in 1.2.0. + * Lowest widget contract the build works against: the CSV download action the widget imports + * reached the SDK in 1.3.0. */ - const MIN_WIDGET_API_VERSION = '1.2.0'; + const MIN_WIDGET_API_VERSION = '1.3.0'; /** * Hook the registrant on the dashboard's registry action and the seed on its layout filter. diff --git a/projects/packages/videopress/widgets/top-videos/render.tsx b/projects/packages/videopress/widgets/top-videos/render.tsx index e994b50c101f..f5a9e4d57a93 100644 --- a/projects/packages/videopress/widgets/top-videos/render.tsx +++ b/projects/packages/videopress/widgets/top-videos/render.tsx @@ -9,7 +9,6 @@ import { describeError, useStatsVideoPlays, useWidgetRootContext, - videosCsvExporter, type LeaderboardRowInput, type ReportParamsFieldAttributes, } from '@automattic/jetpack-premium-analytics-sdk'; @@ -102,7 +101,7 @@ function TopVideosReport() { <> diff --git a/projects/packages/videopress/widgets/top-videos/test/render.test.tsx b/projects/packages/videopress/widgets/top-videos/test/render.test.tsx index 8bd190d8e3a3..9b6d49a82e9a 100644 --- a/projects/packages/videopress/widgets/top-videos/test/render.test.tsx +++ b/projects/packages/videopress/widgets/top-videos/test/render.test.tsx @@ -9,6 +9,7 @@ import TopVideos from '../render'; import type { ReactNode } from 'react'; const mockLeaderboard = jest.fn(); +const mockDownloadButton = jest.fn(); const mockWidgetRoot = jest.fn(); const mockUseStatsVideoPlays = jest.fn(); const mockDescribeError = jest.fn(); @@ -20,6 +21,10 @@ jest.mock( '@automattic/jetpack-premium-analytics-sdk', () => ( { return
{ props.footer }
; }, ReportLink: ( { report }: { report: string } ) => View all, + ExporterCsvDownloadButton: ( props: Record< string, unknown > ) => { + mockDownloadButton( props ); + return ; + }, WidgetRoot: ( { children, ...props }: { children: ReactNode } ) => { mockWidgetRoot( props ); return children; @@ -32,7 +37,7 @@ jest.mock( '@automattic/jetpack-premium-analytics-sdk', () => ( { const refetch = jest.fn(); const videoPlays = ( overrides: Record< string, unknown > = {} ) => ( { - primary: { isPending: false }, + primary: { isPending: false, isError: false }, comparisonRows: { rows: [ { @@ -156,4 +161,15 @@ describe( 'Top videos widget', () => { expect( screen.getByRole( 'link', { name: 'View all' } ) ).toHaveAttribute( 'href', '#videos' ); } ); + + it( 'offers the Videos report CSV from the footer, by report id', () => { + render( ); + + expect( screen.getByRole( 'button', { name: 'Download CSV' } ) ).toBeInTheDocument(); + expect( mockDownloadButton ).toHaveBeenCalledWith( { + report: 'videos', + status: { isLoading: false, isFetching: false, isError: false }, + rowCount: 2, + } ); + } ); } );