diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index bdabf8cad06b..7b7c24ee48a1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -5113,6 +5113,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 @@ -5200,6 +5203,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 @@ -30939,6 +30945,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/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/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 d6b12285a18e..bda4fa1b2595 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 @@ -140,6 +140,9 @@ public static function init() { // Premium Analytics offers the Ads tab on Simple and Atomic sites whose plan includes WordAds and that have it on. 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' ) ); @@ -925,6 +928,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( REGISTRABLE_WIDGET_TYPES_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/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/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-sections.md b/projects/packages/premium-analytics/docs/dashboard-sections.md index cf9e185a7a03..e36a64d01452 100644 --- a/projects/packages/premium-analytics/docs/dashboard-sections.md +++ b/projects/packages/premium-analytics/docs/dashboard-sections.md @@ -80,7 +80,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 ), ); }, ) @@ -139,7 +139,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/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/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 ); + } ); +} ); 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/helpers/index.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/index.ts index 3445c33da0aa..bec05e26130e 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 @@ -63,7 +63,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 3b1394ce6663..f528c384fb6e 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/index.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/index.ts @@ -272,8 +272,6 @@ export { type CsvDateRange, getCombinedPeriodMax, sharePercentage, - getVideoKey, - getVideoLabel, describeError, summaryCount, toDay, 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/default-dashboard-sections.php b/projects/packages/premium-analytics/src/default-dashboard-sections.php index 453d95aa09c7..11400e69d85a 100644 --- a/projects/packages/premium-analytics/src/default-dashboard-sections.php +++ b/projects/packages/premium-analytics/src/default-dashboard-sections.php @@ -154,7 +154,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', @@ -172,13 +172,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/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/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/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/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/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/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 bb2f3c12390e..000000000000 --- a/projects/packages/premium-analytics/widgets/videopress/__tests__/videopress.test.tsx +++ /dev/null @@ -1,200 +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( 'says the data is off limits, without a retry, when the request is denied', async () => { - mockApiFetch.mockRejectedValue( { status: 403, message: 'Forbidden' } ); - - renderInDashboard( - - ); - - await expect( - screen.findByText( "You don't have access to this data." ) - ).resolves.toBeInTheDocument(); - expect( screen.queryByRole( 'button', { name: 'Retry' } ) ).not.toBeInTheDocument(); - } ); - - it( 'shows the error state with a retry action when the request fails', async () => { - // A 404 is not retried automatically, so React Query surfaces the error state - // immediately, and it is worth a manual retry. - mockApiFetch.mockRejectedValue( { status: 404, message: 'Not found' } ); - - 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/.phan/stubs/wp-build-stubs.php b/projects/packages/videopress/.phan/stubs/wp-build-stubs.php new file mode 100644 index 000000000000..8fc5d8281924 --- /dev/null +++ b/projects/packages/videopress/.phan/stubs/wp-build-stubs.php @@ -0,0 +1,17 @@ +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; + } + + register_widget_types_from_manifest( + 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' ) ), + '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 mixed $layout The section's default widget instances; anything but an array passes through. + * @param string $section_id Namespaced section identifier. + * @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 ) ) { + 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, 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(); + if ( ! function_exists( 'jetpack_videopress_get_registered_widget_modules' ) ) { + return array(); + } + + return (array) jetpack_videopress_get_registered_widget_modules(); + } + + /** + * 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 df4b7583a782..4d571395f47a 100644 --- a/projects/packages/videopress/src/class-initializer.php +++ b/projects/packages/videopress/src/class-initializer.php @@ -206,6 +206,7 @@ private static function active_initialization() { Block_Editor_Content::init(); Channel::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..55060559a684 --- /dev/null +++ b/projects/packages/videopress/tests/php/Analytics_Dashboard_Test.php @@ -0,0 +1,189 @@ +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..58d5483e6e4d --- /dev/null +++ b/projects/packages/videopress/tests/php/Analytics_Dashboard_Without_Widget_Types_Test.php @@ -0,0 +1,52 @@ +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..55a67c7508ff --- /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..c524ec7068e5 --- /dev/null +++ b/projects/packages/videopress/widgets/top-videos/package.json @@ -0,0 +1,16 @@ +{ + "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" + }, + "devDependencies": { + "@testing-library/react": "16.3.3" + } +} diff --git a/projects/packages/premium-analytics/widgets/videopress/render.tsx b/projects/packages/videopress/widgets/top-videos/render.tsx similarity index 65% rename from projects/packages/premium-analytics/widgets/videopress/render.tsx rename to projects/packages/videopress/widgets/top-videos/render.tsx index 5023086efdea..f5a9e4d57a93 100644 --- a/projects/packages/premium-analytics/widgets/videopress/render.tsx +++ b/projects/packages/videopress/widgets/top-videos/render.tsx @@ -1,40 +1,47 @@ /** * External dependencies */ -import { useStatsVideoPlays } from '@jetpack-premium-analytics/data'; import { ExporterCsvDownloadButton, Leaderboard, ReportLink, - WIDGET_ROW_LIMIT, WidgetRoot, describeError, + useStatsVideoPlays, useWidgetRootContext, - videosCsvExporter, type LeaderboardRowInput, type ReportParamsFieldAttributes, -} from '@jetpack-premium-analytics/widgets-toolkit'; +} from '@automattic/jetpack-premium-analytics-sdk'; import { __ } from '@wordpress/i18n'; import { useMemo } from 'react'; /** * Internal dependencies */ import { toVideoPlaysRows, type VideoPlaysRow } from './build-video-plays-data'; -import type { VideoPressAttributes } from './widget'; +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 VideoPressRenderAttributes = VideoPressAttributes & Partial< ReportParamsFieldAttributes >; +type TopVideosRenderAttributes = TopVideosAttributes & Partial< ReportParamsFieldAttributes >; -type VideoPressWidgetProps = WidgetRenderProps< VideoPressRenderAttributes > & { +type TopVideosWidgetProps = WidgetRenderProps< TopVideosRenderAttributes > & { /** * Dashboard error handler. */ setError?: ComponentProps< typeof WidgetRoot >[ 'setError' ]; }; +/** + * Maps a normalized video row to a leaderboard row. + * + * @param row - Normalized video row. + * @return The leaderboard row. + */ function toLeaderboardRow( row: VideoPlaysRow ): LeaderboardRowInput { return { id: row.key, @@ -46,20 +53,22 @@ function toLeaderboardRow( row: VideoPlaysRow ): LeaderboardRowInput { } /** - * Fetches the video-plays report through the Jetpack Stats hook and renders the + * Fetches the video-plays report through the dashboard's Stats hook and renders the * rows as a leaderboard. + * + * @return The widget content. */ -function VideoPressReport() { +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 ), @@ -84,7 +93,7 @@ function VideoPressReport() { error={ describeError( error, { retryDescription: __( "We couldn't load video plays. Please try again in a moment.", - 'jetpack-premium-analytics-pkg' + 'jetpack-videopress-pkg' ), onRetry: refetch, } ) } @@ -92,7 +101,7 @@ function VideoPressReport() { <> @@ -102,10 +111,18 @@ 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/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/test/render.test.tsx b/projects/packages/videopress/widgets/top-videos/test/render.test.tsx new file mode 100644 index 000000000000..9b6d49a82e9a --- /dev/null +++ b/projects/packages/videopress/widgets/top-videos/test/render.test.tsx @@ -0,0 +1,175 @@ +/** + * 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 mockDownloadButton = 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', () => ( { + Leaderboard: ( props: { footer?: ReactNode } ) => { + mockLeaderboard( props ); + 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; + }, + 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, isError: 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 its own number of videos for the dashboard window', () => { + render( ); + + expect( mockUseStatsVideoPlays ).toHaveBeenCalledWith( + { from: '2026-06-01', to: '2026-06-16', max: 10 }, + { maxRows: 10 } + ); + } ); + + 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' ); + } ); + + 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, + } ); + } ); +} ); diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/video-plays.ts b/projects/packages/videopress/widgets/top-videos/video-plays.ts similarity index 53% rename from projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/video-plays.ts rename to projects/packages/videopress/widgets/top-videos/video-plays.ts index c06d340e28c2..682b3df8028f 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/video-plays.ts +++ b/projects/packages/videopress/widgets/top-videos/video-plays.ts @@ -2,14 +2,7 @@ * 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. - */ +import type { StatsVideoPlaysComparisonItem } from '@automattic/jetpack-premium-analytics-sdk'; /** * Resolve a display label for a video, falling back to a translated @@ -18,21 +11,21 @@ import type { StatsVideoPlaysItem } from '@jetpack-premium-analytics/data'; * @param video - The video-plays item. * @return The video's display label. */ -export function getVideoLabel( video: StatsVideoPlaysItem ) { +export function getVideoLabel( video: StatsVideoPlaysComparisonItem ): string { return typeof video.label === 'string' && video.label ? video.label - : __( 'Untitled video', 'jetpack-premium-analytics-pkg' ); + : __( '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. + * 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 ) { +export function getVideoKey( video: StatsVideoPlaysComparisonItem ): string { if ( video.id != null ) { return String( video.id ); } 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 6907b90e959f..53c4dc20a5e3 100644 --- a/projects/plugins/jetpack/composer.lock +++ b/projects/plugins/jetpack/composer.lock @@ -4147,7 +4147,7 @@ "dist": { "type": "path", "url": "../../packages/videopress", - "reference": "b41b2aa518bd9ebee255bdbda9653810dee4e89a" + "reference": "038eab668c04c4527c2342a335ec059f00411465" }, "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/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 150ee74d7199..2fc011fcebbd 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/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 11c07ace86f7..251d0431687b 100644 --- a/projects/plugins/videopress/composer.lock +++ b/projects/plugins/videopress/composer.lock @@ -1896,7 +1896,7 @@ "dist": { "type": "path", "url": "../../packages/videopress", - "reference": "b41b2aa518bd9ebee255bdbda9653810dee4e89a" + "reference": "038eab668c04c4527c2342a335ec059f00411465" }, "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": [ 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 c17503f0df49..824f56ee7a32 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" ] } },