diff --git a/projects/packages/videopress/changelog/add-videopress-latest-videos-browse b/projects/packages/videopress/changelog/add-videopress-latest-videos-browse
new file mode 100644
index 000000000000..53e72823640d
--- /dev/null
+++ b/projects/packages/videopress/changelog/add-videopress-latest-videos-browse
@@ -0,0 +1,4 @@
+Significance: minor
+Type: added
+
+Latest Videos Playlist: Add sorting, search and length filters, numbered pages, an option to leave out the video being viewed, and view counts with upload dates.
diff --git a/projects/packages/videopress/src/class-channel.php b/projects/packages/videopress/src/class-channel.php
index 7f4d0b261511..d7e9b5256145 100644
--- a/projects/packages/videopress/src/class-channel.php
+++ b/projects/packages/videopress/src/class-channel.php
@@ -515,6 +515,29 @@ public static function source_playlist( $source, $key = '' ) {
return $playlists ? $playlists[0] : null;
}
+ /**
+ * Add views and upload time to playlist entries, for their meta line.
+ *
+ * @param array[] $entries Sanitized playlist entries.
+ * @return array[]
+ */
+ public static function entries_with_meta( array $entries ) {
+ $views = Channel_Data::video_views();
+ foreach ( $entries as &$entry ) {
+ $id = self::attachment_id( $entry['guid'] );
+ $post = $id ? get_post( $id ) : null;
+ $entry = array_merge(
+ $entry,
+ array(
+ 'views' => $views[ $id ] ?? 0,
+ 'publishedAt' => $post instanceof WP_Post ? (int) strtotime( $post->post_date_gmt . ' UTC' ) : 0,
+ )
+ );
+ }
+ unset( $entry );
+ return $entries;
+ }
+
/**
* A Video Playlist block whose `source` is `queried` or `index` shows that
* playlist; its entries then open their video pages within the playlist.
@@ -540,7 +563,7 @@ public static function playlist_source_block( $parsed_block ) {
return $parsed_block;
}
- $parsed_block['attrs']['videos'] = $playlist['videos'];
+ $parsed_block['attrs']['videos'] = ! empty( $attrs['showMeta'] ) ? self::entries_with_meta( $playlist['videos'] ) : $playlist['videos'];
$parsed_block['attrs']['playlistTitle'] = $playlist['title'];
$parsed_block['attrs']['playlistDescription'] = $playlist['description'];
$parsed_block['attrs']['videopressListKey'] = $playlist['key'];
diff --git a/projects/packages/videopress/src/class-initializer.php b/projects/packages/videopress/src/class-initializer.php
index 8e6dbbe9dbd5..956a320589ed 100644
--- a/projects/packages/videopress/src/class-initializer.php
+++ b/projects/packages/videopress/src/class-initializer.php
@@ -19,6 +19,7 @@ class Initializer {
const LATEST_VIDEOS_PLAYLIST_MIN_COUNT = 1;
const LATEST_VIDEOS_PLAYLIST_MAX_COUNT = 20;
const LATEST_VIDEOS_PLAYLIST_DEFAULT_COUNT = 5;
+ const LATEST_VIDEOS_PLAYLIST_MAX_PAGED = 48;
const JETPACK_VIDEOPRESS_IFRAME_API_HANDLER = 'jetpack-videopress-iframe-api';
@@ -724,17 +725,174 @@ public static function register_videopress_latest_videos_playlist_block( $metada
* @return string Block markup, or an empty string when the site has no VideoPress videos.
*/
public static function render_videopress_latest_videos_playlist_block( $block_attributes, $content = '', $block = null ) {
- $count = isset( $block_attributes['count'] ) && is_numeric( $block_attributes['count'] )
+ $order = isset( $block_attributes['orderBy'] ) && in_array( $block_attributes['orderBy'], Channel_Data::BROWSE_SORTS, true ) ? $block_attributes['orderBy'] : 'newest';
+ $controls = ! empty( $block_attributes['showBrowseControls'] );
+ $paginated = isset( $block_attributes['pagination'] ) && 'numbered' === $block_attributes['pagination'];
+ $exclude = ! empty( $block_attributes['excludeCurrent'] ) ? array_filter( array( Channel::queried_guid() ) ) : array();
+ $show_meta = ! empty( $block_attributes['showMeta'] );
+ $max_count = $paginated ? self::LATEST_VIDEOS_PLAYLIST_MAX_PAGED : self::LATEST_VIDEOS_PLAYLIST_MAX_COUNT;
+ $count = isset( $block_attributes['count'] ) && is_numeric( $block_attributes['count'] )
? (int) $block_attributes['count']
: self::LATEST_VIDEOS_PLAYLIST_DEFAULT_COUNT;
- $count = max( self::LATEST_VIDEOS_PLAYLIST_MIN_COUNT, min( self::LATEST_VIDEOS_PLAYLIST_MAX_COUNT, $count ) );
-
- $block_attributes['videos'] = Data::get_latest_videopress_playlist_entries( $count );
+ $count = max( self::LATEST_VIDEOS_PLAYLIST_MIN_COUNT, min( $max_count, $count ) );
+ $is_browsed = 'newest' !== $order || $controls || $paginated || $exclude || $show_meta;
// Dynamic playlists have no title of their own, so no heading either.
unset( $block_attributes['playlistTitle'], $block_attributes['showPlaylistTitle'] );
- return self::render_videopress_playlist_block( $block_attributes, '', $block );
+ if ( ! $is_browsed ) {
+ $block_attributes['videos'] = Data::get_latest_videopress_playlist_entries( $count );
+ return self::render_videopress_playlist_block( $block_attributes, '', $block );
+ }
+
+ $state = Channel_Data::browse_request( $controls, $paginated, $order );
+ $results = Channel_Data::browse( $state, $count, $exclude, $show_meta );
+
+ $block_attributes['videos'] = $show_meta
+ ? $results['entries']
+ : array_map(
+ function ( $entry ) {
+ return array_diff_key( $entry, array_flip( array( 'views', 'publishedAt' ) ) );
+ },
+ $results['entries']
+ );
+ $before = $controls ? self::render_video_browser_controls( $state, $results, $count ) : '';
+ $after = $paginated && $results['pages'] > 1 ? self::render_video_browser_pagination( $results['page'], $results['pages'] ) : '';
+ $markup = self::render_videopress_playlist_block( $block_attributes, '', $block, $before, $after );
+
+ if ( '' === $markup && $controls ) {
+ // Keep the controls when nothing matches, so the filters can be changed back.
+ $markup = sprintf(
+ ' %3$s
%14$s
', + esc_url( $action ), + $hidden, + esc_attr( Channel_Data::QUERY_ARG_SORT ), + esc_attr( 'newest' === $state['sort'] ? 'latest' : $state['sort'] ), + esc_attr( Channel_Data::QUERY_ARG_SEARCH ), + esc_attr( $state['search'] ), + esc_attr__( 'Search this channel', 'jetpack-videopress-pkg' ), + esc_html__( 'Search', 'jetpack-videopress-pkg' ), + esc_attr__( 'Sort videos', 'jetpack-videopress-pkg' ), + $sort_buttons, + esc_attr( Channel_Data::QUERY_ARG_LENGTH ), + esc_attr__( 'Video length', 'jetpack-videopress-pkg' ), + $options, + esc_html( $summary ) + ); + } + + /** + * The Videos page's numbered pagination. + * + * @param int $current Current page. + * @param int $pages Number of pages. + * + * @return string Markup. + */ + private static function render_video_browser_pagination( $current, $pages ) { + $url_for = function ( $page ) { + return 1 === $page ? remove_query_arg( Channel_Data::QUERY_ARG_PAGE ) : add_query_arg( Channel_Data::QUERY_ARG_PAGE, $page ); + }; + $step = function ( $page, $enabled, $modifier, $label ) use ( $url_for ) { + return $enabled + ? sprintf( '%3$s', $modifier, esc_url( $url_for( $page ) ), esc_html( $label ) ) + : sprintf( '%2$s', $modifier, esc_html( $label ) ); + }; + + $links = $step( $current - 1, $current > 1, 'prev', __( '← Previous', 'jetpack-videopress-pkg' ) ); + for ( $page = 1; $page <= $pages; $page++ ) { + $links .= $page === $current + ? sprintf( '%d', $page ) + : sprintf( '%2$d', esc_url( $url_for( $page ) ), $page ); + } + $links .= $step( $current + 1, $current < $pages, 'next', __( 'Next →', 'jetpack-videopress-pkg' ) ); + + return sprintf( + '', + esc_attr__( 'Videos pagination', 'jetpack-videopress-pkg' ), + $links + ); } /** @@ -765,11 +923,18 @@ public static function sanitize_playlist_entries( $videos ) { * metadata (title, poster) is always live: the view script reads it * from the video data after the page loads. */ - $entries[] = array( + $entry = array( 'guid' => $video['guid'], 'durationMs' => isset( $video['durationMs'] ) && is_numeric( $video['durationMs'] ) ? max( 0, (int) $video['durationMs'] ) : 0, 'height' => isset( $video['height'] ) && is_numeric( $video['height'] ) ? max( 0, (int) $video['height'] ) : 0, ); + // Render-time extras for the meta line; never saved with the block. + foreach ( array( 'views', 'publishedAt' ) as $extra ) { + if ( isset( $video[ $extra ] ) && is_numeric( $video[ $extra ] ) ) { + $entry[ $extra ] = max( 0, (int) $video[ $extra ] ); + } + } + $entries[] = $entry; } return $entries; @@ -875,10 +1040,12 @@ private static function playlist_resolution_label( $height ) { * @param array $block_attributes Block attributes. * @param string $content Rendered inner blocks: the title heading, when there is one. * @param \WP_Block|null $block Current block. + * @param string $before Markup placed above the playlist body, e.g. browse controls. + * @param string $after Markup placed below the playlist body, e.g. pagination. * * @return string Block markup, or an empty string when the playlist has no playable entries. */ - public static function render_videopress_playlist_block( $block_attributes, $content = '', $block = null ) { + public static function render_videopress_playlist_block( $block_attributes, $content = '', $block = null, $before = '', $after = '' ) { $entries = self::sanitize_playlist_entries( $block_attributes['videos'] ?? null ); if ( ! $entries ) { @@ -1001,6 +1168,11 @@ public static function render_videopress_playlist_block( $block_attributes, $con ? sprintf( '%s', esc_html( $timecode ) ) : ''; + $stats_label = Channel_Data::views_and_age( array_intersect_key( $entry, array_flip( array( 'views', 'publishedAt' ) ) ) ); + $stats_markup = '' !== $stats_label + ? sprintf( '%s', esc_html( $stats_label ) ) + : ''; + if ( $has_player ) { $is_current = $show_player && 0 === $index; $entry_open = sprintf( @@ -1049,7 +1221,7 @@ public static function render_videopress_playlist_block( $block_attributes, $con $items .= sprintf( '
{ __(
@@ -124,7 +186,21 @@ export default function LatestVideosPlaylistEdit( {
Server render
' } ) + : newest?.( { path } ) + ); + renderEdit( overrides ); + + await expect( screen.findByText( 'Server render' ) ).resolves.toBeInTheDocument(); + expect( screen.getByTestId( 'inner-blocks' ) ).not.toBeVisible(); + } + ); + + it( 'stores the browse settings and clamps the count when pages are turned off', async () => { + const setAttributes = jest.fn(); + renderEdit( { pagination: 'numbered', count: 40 }, setAttributes ); + + await userEvent.selectOptions( screen.getByRole( 'combobox', { name: 'Order' } ), 'popular' ); + expect( setAttributes ).toHaveBeenLastCalledWith( { orderBy: 'popular' } ); + + for ( const [ name, attribute ] of [ + [ 'Search, sort and length filters', 'showBrowseControls' ], + [ 'Views and upload date', 'showMeta' ], + [ 'Hide the video being viewed', 'excludeCurrent' ], + ] ) { + await userEvent.click( screen.getByRole( 'checkbox', { name } ) ); + expect( setAttributes ).toHaveBeenLastCalledWith( { [ attribute ]: true } ); + } + + await userEvent.click( screen.getByRole( 'checkbox', { name: 'Numbered pages' } ) ); + expect( setAttributes ).toHaveBeenLastCalledWith( { pagination: 'none', count: 20 } ); + } ); + + it( 'keeps the canvas for the newest videos', async () => { + renderEdit( { orderBy: 'newest' } ); + await waitFor( () => expect( providedContext?.status ).toBe( 'ready' ) ); + + expect( screen.getByTestId( 'inner-blocks' ) ).toBeVisible(); + expect( + apiFetchMock.mock.calls.some( ( [ { path } ] ) => + path.startsWith( '/wp/v2/block-renderer/' ) + ) + ).toBe( false ); + } ); + it( 'offers the click behavior with the player off and hands it to the canvas', async () => { const setAttributes = jest.fn(); renderEdit( { showPlayer: false, entryClickAction: 'show-player' }, setAttributes ); diff --git a/projects/packages/videopress/src/client/block-editor/blocks/latest-videos-playlist/types.ts b/projects/packages/videopress/src/client/block-editor/blocks/latest-videos-playlist/types.ts index 8d1bc3e75732..0970b82eb948 100644 --- a/projects/packages/videopress/src/client/block-editor/blocks/latest-videos-playlist/types.ts +++ b/projects/packages/videopress/src/client/block-editor/blocks/latest-videos-playlist/types.ts @@ -1,6 +1,16 @@ import type { PlaylistDisplayAttributes } from '../playlist/types'; +export type LatestVideosOrder = 'newest' | 'oldest' | 'popular'; + export type LatestVideosPlaylistAttributes = PlaylistDisplayAttributes & { - // How many of the site's newest VideoPress videos to show. + // How many of the site's newest VideoPress videos to show; the page size when paginated. count: number; + orderBy?: LatestVideosOrder; + // Search, sort and length controls above the list, read from the page URL. + showBrowseControls?: boolean; + pagination?: 'none' | 'numbered'; + // Leave out the video a channel video page is showing. + excludeCurrent?: boolean; + // "12K views · 3 days ago" under each entry. + showMeta?: boolean; }; diff --git a/projects/packages/videopress/src/client/block-editor/blocks/playlist/block.json b/projects/packages/videopress/src/client/block-editor/blocks/playlist/block.json index ed9b94bf3362..71245cff27eb 100644 --- a/projects/packages/videopress/src/client/block-editor/blocks/playlist/block.json +++ b/projects/packages/videopress/src/client/block-editor/blocks/playlist/block.json @@ -110,6 +110,10 @@ "sourcePlaylistId": { "type": "string", "default": "" + }, + "showMeta": { + "type": "boolean", + "default": false } }, "editorScript": "file:./index.js", diff --git a/projects/packages/videopress/src/client/block-editor/blocks/playlist/source-controls.tsx b/projects/packages/videopress/src/client/block-editor/blocks/playlist/source-controls.tsx index bc715450090e..2d83ca275ba8 100644 --- a/projects/packages/videopress/src/client/block-editor/blocks/playlist/source-controls.tsx +++ b/projects/packages/videopress/src/client/block-editor/blocks/playlist/source-controls.tsx @@ -2,7 +2,7 @@ * WordPress dependencies */ import { InspectorControls, useBlockProps } from '@wordpress/block-editor'; -import { PanelBody, Placeholder, SelectControl } from '@wordpress/components'; +import { PanelBody, Placeholder, SelectControl, ToggleControl } from '@wordpress/components'; import { useState } from '@wordpress/element'; import { __ } from '@wordpress/i18n'; /** @@ -59,6 +59,14 @@ export function PlaylistSourcePanel( { attributes, setAttributes }: Props ) { onChange={ value => setAttributes( { sourcePlaylistId: value } ) } /> ) } + { 'own' !== source && ( +Most viewed
' } ); + renderPreview(); + + await expect( screen.findByText( 'Most viewed' ) ).resolves.toBeInTheDocument(); + const { path } = apiFetchMock.mock.calls[ 0 ][ 0 ]; + expect( path.split( '?' )[ 0 ] ).toBe( + '/wp/v2/block-renderer/videopress/latest-videos-playlist' + ); + expect( Object.fromEntries( new URLSearchParams( path.split( '?' )[ 1 ] ) ) ).toMatchObject( { + context: 'edit', + 'attributes[count]': '3', + 'attributes[orderBy]': 'popular', + } ); + } ); + + it.each( [ + [ 'renders nothing', () => apiFetchMock.mockResolvedValue( { rendered: ' ' } ) ], + [ 'fails', () => apiFetchMock.mockRejectedValue( new Error( 'rest_forbidden' ) ) ], + ] )( 'explains what the block shows when the server %s', async ( _, respond ) => { + respond(); + renderPreview(); + + await expect( + screen.findByText( 'Upload a VideoPress video to see it here.', { + ignore: '.a11y-speak-region', + } ) + ).resolves.toBeInTheDocument(); + expect( screen.getByText( 'Latest Videos Playlist' ) ).toBeInTheDocument(); + } ); +} ); diff --git a/projects/packages/videopress/tests/php/Channel_Test.php b/projects/packages/videopress/tests/php/Channel_Test.php index 83fa99ac78ff..e013fb8d0c32 100644 --- a/projects/packages/videopress/tests/php/Channel_Test.php +++ b/projects/packages/videopress/tests/php/Channel_Test.php @@ -8,6 +8,7 @@ namespace Automattic\Jetpack; use Automattic\Jetpack\VideoPress\Channel; +use Automattic\Jetpack\VideoPress\Channel_Data; use PHPUnit\Framework\Attributes\PreserveGlobalState; use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses; use WorDBless\BaseTestCase; @@ -398,6 +399,42 @@ public function test_playlist_source_block() { $this->assertSame( 'mc', $block( array( 'source' => 'queried' ) )['videopressListKey'] ); } + /** + * With `showMeta`, a sourced playlist's entries carry their plays and upload + * time; entries without a local attachment get zeros. + */ + public function test_playlist_source_block_entry_meta() { + $this->index_playlists(); + $id = $this->video( 'abcDEF12' ); + Channel_Data::reset(); + add_filter( + 'videopress_channel_video_views', + function () use ( $id ) { + return array( $id => 42 ); + } + ); + $videos = function ( $attrs ) { + return Channel::playlist_source_block( + array( + 'blockName' => 'videopress/playlist', + 'attrs' => $attrs + array( + 'source' => 'index', + 'sourcePlaylistId' => 'mc', + ), + ) + )['attrs']['videos']; + }; + + $with_meta = $videos( array( 'showMeta' => true ) ); + $this->assertSame( 42, $with_meta[0]['views'] ); + $this->assertSame( strtotime( get_post( $id )->post_date_gmt . ' UTC' ), $with_meta[0]['publishedAt'] ); + $this->assertSame( 1000, $with_meta[0]['durationMs'] ); + $this->assertSame( 0, $with_meta[1]['views'] ); + $this->assertSame( 0, $with_meta[1]['publishedAt'] ); + + $this->assertArrayNotHasKey( 'views', $videos( array() )[0] ); + } + /** * Playlist records: only published playlists are listed, and lookups of * unknown keys or sources come back empty. diff --git a/projects/packages/videopress/tests/php/Latest_Videos_Playlist_Block_Test.php b/projects/packages/videopress/tests/php/Latest_Videos_Playlist_Block_Test.php index 2b80c3b768ac..d9f40560d3c6 100644 --- a/projects/packages/videopress/tests/php/Latest_Videos_Playlist_Block_Test.php +++ b/projects/packages/videopress/tests/php/Latest_Videos_Playlist_Block_Test.php @@ -218,6 +218,52 @@ private function create_video( $guid, $date, $duration = 0, $height = 0 ) { return $this->create_attachment( 'video/videopress', $date, $guid, $duration, $height ); } + /** + * Browse controls and numbered pagination render around the requested page, + * and an empty result keeps the controls. + */ + public function test_render_browse_controls_and_pagination() { + \Automattic\Jetpack\VideoPress\Channel_Data::reset(); + $this->create_video( 'oldest01', '2024-01-01 10:00:00', 60000 ); + $this->create_video( 'middle02', '2024-02-01 10:00:00', 120000 ); + $this->create_video( 'newest03', '2024-03-01 10:00:00', 180000 ); + $_GET = array( + 'videos-sort' => 'oldest', + 'videos-page' => '2', + 'keep' => 'me', + ); + + $markup = VideoPress_Initializer::render_videopress_latest_videos_playlist_block( + array( + 'count' => 2, + 'showPlayer' => false, + 'showBrowseControls' => true, + 'pagination' => 'numbered', + ) + ); + + $this->assertStringContainsString( '