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( + '
%2$s

%3$s

', + get_block_wrapper_attributes( array( 'class' => 'videopress-playlist is-layout-' . esc_attr( $block_attributes['layout'] ?? 'grid' ) . ' is-empty' ) ), + $before, + esc_html__( 'No videos match these filters.', 'jetpack-videopress-pkg' ) + ); + } + + return $markup; + } + + /** + * The Videos page controls: search, sort and length, submitted as a GET form. + * + * @param array $state Browsing state from Channel_Data::browse_request(). + * @param array $results Page from Channel_Data::browse(). + * @param int $per_page Page size. + * + * @return string Markup. + */ + private static function render_video_browser_controls( array $state, array $results, $per_page ) { + $own_args = array( Channel_Data::QUERY_ARG_SEARCH, Channel_Data::QUERY_ARG_SORT, Channel_Data::QUERY_ARG_LENGTH, Channel_Data::QUERY_ARG_PAGE ); + $action = strtok( remove_query_arg( $own_args ), '?' ); + + // A GET form drops the action's query string, so the page's other arguments ride along as fields. + $hidden = ''; + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only echoed back as hidden fields. + foreach ( $_GET as $name => $value ) { + if ( is_string( $name ) && is_string( $value ) && ! in_array( $name, $own_args, true ) ) { + $hidden .= sprintf( '', esc_attr( $name ), esc_attr( sanitize_text_field( wp_unslash( $value ) ) ) ); + } + } + + $sorts = array( + 'newest' => __( 'Latest', 'jetpack-videopress-pkg' ), + 'popular' => __( 'Popular', 'jetpack-videopress-pkg' ), + 'oldest' => __( 'Oldest', 'jetpack-videopress-pkg' ), + ); + $sort_buttons = ''; + foreach ( $sorts as $value => $label ) { + $is_current = $value === $state['sort']; + $sort_buttons .= sprintf( + '', + $is_current ? ' is-current' : '', + esc_attr( Channel_Data::QUERY_ARG_SORT ), + esc_attr( 'newest' === $value ? 'latest' : $value ), + $is_current ? 'true' : 'false', + esc_html( $label ) + ); + } + + $lengths = array( + 'any' => __( 'Any length', 'jetpack-videopress-pkg' ), + 'short' => __( 'Under 20 min', 'jetpack-videopress-pkg' ), + 'mid' => __( '20 to 45 min', 'jetpack-videopress-pkg' ), + 'long' => __( 'Over 45 min', 'jetpack-videopress-pkg' ), + ); + $options = ''; + foreach ( $lengths as $value => $label ) { + $options .= sprintf( '', esc_attr( $value ), selected( $value, $state['length'], false ), esc_html( $label ) ); + } + + if ( $results['total'] > 0 ) { + $summary = sprintf( + /* translators: 1: first video shown. 2: last video shown. 3: number of matching videos. */ + _n( 'Showing %1$s–%2$s of %3$s video', 'Showing %1$s–%2$s of %3$s videos', $results['total'], 'jetpack-videopress-pkg' ), + number_format_i18n( $results['start'] + 1 ), + number_format_i18n( min( $results['start'] + $per_page, $results['total'] ) ), + number_format_i18n( $results['total'] ) + ); + } else { + $summary = __( '0 videos', 'jetpack-videopress-pkg' ); + } + + return sprintf( + '' . + '

%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( '
  • %1$s' . '%2$s%3$s%4$s%5$s' . - '%6$s' . + '%6$s%11$s' . '%9$s
  • ', $entry_open, $number_markup, @@ -1060,7 +1232,8 @@ public static function render_videopress_playlist_block( $block_attributes, $con $resolution_markup, $duration_markup, $entry_close, - ! $has_player && '' !== $current_guid && $entry['guid'] === $current_guid ? ' is-current' : '' + ! $has_player && '' !== $current_guid && $entry['guid'] === $current_guid ? ' is-current' : '', + $stats_markup ); } @@ -1175,11 +1348,13 @@ public static function render_videopress_playlist_block( $block_attributes, $con : ''; return sprintf( - '
    %2$s
    %3$s%4$s
    ', + '
    %2$s%5$s
    %3$s%4$s
    %6$s
    ', $wrapper_attributes, $heading_markup, $stage_markup, - $list_markup + $list_markup, + $before, + $after ); } diff --git a/projects/packages/videopress/src/client/block-editor/blocks/latest-videos-playlist/block.json b/projects/packages/videopress/src/client/block-editor/blocks/latest-videos-playlist/block.json index 714fca2f6f22..212a7109acce 100644 --- a/projects/packages/videopress/src/client/block-editor/blocks/latest-videos-playlist/block.json +++ b/projects/packages/videopress/src/client/block-editor/blocks/latest-videos-playlist/block.json @@ -80,6 +80,28 @@ "entryTitleFontFamily": { "type": "string", "default": "" + }, + "orderBy": { + "type": "string", + "enum": [ "newest", "oldest", "popular" ], + "default": "newest" + }, + "showBrowseControls": { + "type": "boolean", + "default": false + }, + "pagination": { + "type": "string", + "enum": [ "none", "numbered" ], + "default": "none" + }, + "excludeCurrent": { + "type": "boolean", + "default": false + }, + "showMeta": { + "type": "boolean", + "default": false } }, "editorScript": "file:./index.js", diff --git a/projects/packages/videopress/src/client/block-editor/blocks/latest-videos-playlist/edit.tsx b/projects/packages/videopress/src/client/block-editor/blocks/latest-videos-playlist/edit.tsx index 49bdc34dcc53..a0634166d083 100644 --- a/projects/packages/videopress/src/client/block-editor/blocks/latest-videos-playlist/edit.tsx +++ b/projects/packages/videopress/src/client/block-editor/blocks/latest-videos-playlist/edit.tsx @@ -7,18 +7,20 @@ import { useBlockProps, useInnerBlocksProps, } from '@wordpress/block-editor'; -import { PanelBody, RangeControl } from '@wordpress/components'; +import { PanelBody, RangeControl, SelectControl, ToggleControl } from '@wordpress/components'; import { useEffect, useMemo, useState } from '@wordpress/element'; -import { __ } from '@wordpress/i18n'; +import { __, _x } from '@wordpress/i18n'; /** * Internal dependencies */ +import ServerPreview from '../../channel/server-preview'; import { PlaylistSettingsPanels, PlaylistStylesControls } from '../playlist/inspector-controls'; import usePublishTracking from '../playlist/use-publish-tracking'; import { LATEST_VIDEOS_PLAYLIST_CONTEXT } from './context'; import { clampVideoCount, fetchLatestVideos, + MAX_PAGED_VIDEO_COUNT, MAX_VIDEO_COUNT, MIN_VIDEO_COUNT, } from './fetch-latest-videos'; @@ -26,7 +28,7 @@ import { * Types */ import type { LatestVideosPlaylistContext, LatestVideosStatus } from './context'; -import type { LatestVideosPlaylistAttributes } from './types'; +import type { LatestVideosOrder, LatestVideosPlaylistAttributes } from './types'; import type { PlaylistEntry } from '../playlist/types'; import type { BlockEditProps } from '@wordpress/blocks'; @@ -52,7 +54,16 @@ export default function LatestVideosPlaylistEdit( { setAttributes, clientId, }: BlockEditProps< LatestVideosPlaylistAttributes > ) { - const { count, layout } = attributes; + const { count, layout, orderBy, showBrowseControls, pagination, excludeCurrent, showMeta } = + attributes; + const maxCount = 'numbered' === pagination ? MAX_PAGED_VIDEO_COUNT : MAX_VIDEO_COUNT; + // The canvas only knows the newest videos; anything else previews the site's own render. + const isServerPreview = + ( !! orderBy && 'newest' !== orderBy ) || + !! showBrowseControls || + 'numbered' === pagination || + !! excludeCurrent || + !! showMeta; const [ videos, setVideos ] = useState< PlaylistEntry[] >( [] ); const [ status, setStatus ] = useState< LatestVideosStatus >( 'loading' ); @@ -93,7 +104,7 @@ export default function LatestVideosPlaylistEdit( { [ videos, status, attributes ] ); - const innerBlocksProps = useInnerBlocksProps( + const { children: innerBlocks, ...wrapperProps } = useInnerBlocksProps( useBlockProps( { className: 'videopress-latest-videos-playlist' } ), { template: TEMPLATE, templateLock: 'all', renderAppender: false } ); @@ -105,11 +116,62 @@ export default function LatestVideosPlaylistEdit( { setAttributes( { count: clampVideoCount( value ) } ) } + max={ maxCount } + value={ clampVideoCount( count, maxCount ) } + onChange={ ( value?: number ) => + setAttributes( { count: clampVideoCount( value, maxCount ) } ) + } + /> + setAttributes( { orderBy: value as LatestVideosOrder } ) } + /> + setAttributes( { showBrowseControls: value } ) } + /> + + setAttributes( { + pagination: value ? 'numbered' : 'none', + count: clampVideoCount( count, value ? MAX_PAGED_VIDEO_COUNT : MAX_VIDEO_COUNT ), + } ) + } + /> + setAttributes( { showMeta: value } ) } + /> + setAttributes( { excludeCurrent: value } ) } />

    { __( @@ -124,7 +186,21 @@ export default function LatestVideosPlaylistEdit( { -

    +
    + { isServerPreview && ( + + ) } + { /* The locked inner playlist stays in the tree so the saved markup keeps it. */ } + +
    ); diff --git a/projects/packages/videopress/src/client/block-editor/blocks/latest-videos-playlist/fetch-latest-videos.ts b/projects/packages/videopress/src/client/block-editor/blocks/latest-videos-playlist/fetch-latest-videos.ts index b6b7c34eaa07..538674fbfc4b 100644 --- a/projects/packages/videopress/src/client/block-editor/blocks/latest-videos-playlist/fetch-latest-videos.ts +++ b/projects/packages/videopress/src/client/block-editor/blocks/latest-videos-playlist/fetch-latest-videos.ts @@ -15,6 +15,8 @@ import type { PlaylistEntry } from '../playlist/types'; // Bounds of the "Number of videos" control; the PHP render clamps to the same range. export const MIN_VIDEO_COUNT = 1; export const MAX_VIDEO_COUNT = 20; +// Page size limit when the block paginates; the PHP render clamps to the same value. +export const MAX_PAGED_VIDEO_COUNT = 48; export const DEFAULT_VIDEO_COUNT = 5; /** @@ -39,14 +41,15 @@ const GUID_PATTERN = /^[a-zA-Z0-9]{8}$/; * Clamp a requested count to the range the block supports. * * @param count - Requested number of videos. + * @param max - Upper bound: MAX_PAGED_VIDEO_COUNT when the block paginates. * @return The count within bounds; the default when it isn't a number. */ -export function clampVideoCount( count: unknown ): number { +export function clampVideoCount( count: unknown, max: number = MAX_VIDEO_COUNT ): number { const value = Number( count ); if ( ! Number.isFinite( value ) ) { return DEFAULT_VIDEO_COUNT; } - return Math.min( MAX_VIDEO_COUNT, Math.max( MIN_VIDEO_COUNT, Math.round( value ) ) ); + return Math.min( max, Math.max( MIN_VIDEO_COUNT, Math.round( value ) ) ); } /** diff --git a/projects/packages/videopress/src/client/block-editor/blocks/latest-videos-playlist/test/edit.test.tsx b/projects/packages/videopress/src/client/block-editor/blocks/latest-videos-playlist/test/edit.test.tsx index 86d71b1a1903..3bda446fc9a2 100644 --- a/projects/packages/videopress/src/client/block-editor/blocks/latest-videos-playlist/test/edit.test.tsx +++ b/projects/packages/videopress/src/client/block-editor/blocks/latest-videos-playlist/test/edit.test.tsx @@ -202,6 +202,60 @@ describe( 'LatestVideosPlaylistEdit', () => { expect( setAttributes ).toHaveBeenCalledWith( { showPlayer: false } ); } ); + it.each( [ + { orderBy: 'popular' }, + { showBrowseControls: true }, + { pagination: 'numbered' }, + { excludeCurrent: true }, + { showMeta: true }, + ] as Partial< LatestVideosPlaylistAttributes >[] )( + 'previews the site render for %o, which the canvas cannot show', + async overrides => { + const newest = apiFetchMock.getMockImplementation(); + apiFetchMock.mockImplementation( ( { path }: { path: string } ) => + path.startsWith( '/wp/v2/block-renderer/' ) + ? Promise.resolve( { rendered: '

    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 && ( + setAttributes( { showMeta: value } ) } + /> + ) } ); diff --git a/projects/packages/videopress/src/client/block-editor/blocks/playlist/types.ts b/projects/packages/videopress/src/client/block-editor/blocks/playlist/types.ts index 9997096d1be4..00d4ee7fe13d 100644 --- a/projects/packages/videopress/src/client/block-editor/blocks/playlist/types.ts +++ b/projects/packages/videopress/src/client/block-editor/blocks/playlist/types.ts @@ -72,6 +72,8 @@ export type PlaylistAttributes = PlaylistDisplayAttributes & { */ source?: PlaylistSource; sourcePlaylistId?: string; + // "12K views · 3 days ago" under each entry, for sourced playlists. + showMeta?: boolean; }; export type PlaylistSource = 'own' | 'queried' | 'index'; diff --git a/projects/packages/videopress/src/client/block-editor/channel/server-preview.tsx b/projects/packages/videopress/src/client/block-editor/channel/server-preview.tsx new file mode 100644 index 000000000000..9ed268bc8338 --- /dev/null +++ b/projects/packages/videopress/src/client/block-editor/channel/server-preview.tsx @@ -0,0 +1,66 @@ +/** + * WordPress dependencies + */ +import apiFetch from '@wordpress/api-fetch'; +import { Placeholder, Spinner } from '@wordpress/components'; +import { RawHTML, useEffect, useState } from '@wordpress/element'; +import { addQueryArgs } from '@wordpress/url'; +/** + * Internal dependencies + */ +import { VideoPressIcon } from '../blocks/video/components/icons'; + +type ServerPreviewProps = { + // Block name, e.g. `videopress/channel-details`. + block: string; + attributes: Record< string, unknown >; + label: string; + // Shown when the server renders nothing, e.g. outside a video page. + emptyInstructions: string; +}; + +/** + * Show a channel block as the server renders it, through core's block renderer endpoint. + * + * @param props - Component props. + * @param props.block - Block name. + * @param props.attributes - Attributes to render with. + * @param props.label - Placeholder label. + * @param props.emptyInstructions - Placeholder text when there is nothing to show. + * @return The preview. + */ +export default function ServerPreview( { + block, + attributes, + label, + emptyInstructions, +}: ServerPreviewProps ) { + const [ html, setHtml ] = useState< string | null >( null ); + const serialized = JSON.stringify( attributes ); + + useEffect( () => { + let cancelled = false; + setHtml( null ); + apiFetch< { rendered?: string } >( { + path: addQueryArgs( `/wp/v2/block-renderer/${ block }`, { + context: 'edit', + attributes: JSON.parse( serialized ), + } ), + } ) + .then( response => ! cancelled && setHtml( response?.rendered ?? '' ) ) + .catch( () => ! cancelled && setHtml( '' ) ); + return () => { + cancelled = true; + }; + }, [ block, serialized ] ); + + if ( null === html ) { + return ; + } + if ( '' === html.trim() ) { + return ( + + ); + } + return { html }; +} diff --git a/projects/packages/videopress/src/client/block-editor/channel/test/server-preview.test.tsx b/projects/packages/videopress/src/client/block-editor/channel/test/server-preview.test.tsx new file mode 100644 index 000000000000..11636f961a32 --- /dev/null +++ b/projects/packages/videopress/src/client/block-editor/channel/test/server-preview.test.tsx @@ -0,0 +1,63 @@ +import { render, screen } from '@testing-library/react'; +import apiFetch from '@wordpress/api-fetch'; +import ServerPreview from '../server-preview'; + +jest.mock( '@wordpress/api-fetch', () => ( { + __esModule: true, + default: jest.fn(), +} ) ); + +const apiFetchMock = apiFetch as unknown as jest.Mock; + +/** + * Render a preview of the Latest Videos Playlist block. + * + * @return The render result. + */ +function renderPreview() { + return render( + + ); +} + +beforeEach( () => { + apiFetchMock.mockReset(); +} ); + +describe( 'ServerPreview', () => { + it( 'shows the block as the server renders it with its attributes', async () => { + apiFetchMock.mockResolvedValue( { rendered: '

    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( '
    assertStringContainsString( '', $markup ); + $this->assertStringContainsString( 'class="videopress-video-browser__sort is-current" name="videos-sort" value="oldest" aria-pressed="true"', $markup ); + $this->assertStringContainsString( '

    Showing 3–3 of 3 videos

    ', $markup ); + $this->assertStringContainsString( 'data-guid="newest03"', $markup ); + $this->assertStringNotContainsString( 'data-guid="oldest01"', $markup ); + $this->assertStringContainsString( '2', $markup ); + $this->assertStringContainsString( 'videopress-video-browser__page--next is-disabled', $markup ); + $this->assertStringNotContainsString( 'videopress-playlist__entry-stats', $markup ); + + $_GET = array( 'videos-length' => 'long' ); + $markup = VideoPress_Initializer::render_videopress_latest_videos_playlist_block( + array( + 'count' => 2, + 'showBrowseControls' => true, + ) + ); + $this->assertStringContainsString( 'assertStringContainsString( 'No videos match these filters.', $markup ); + $_GET = array(); + } + /** * The newest VideoPress videos come back first, capped at the count, with * only the numeric metadata; other attachments are ignored. diff --git a/projects/packages/videopress/tests/php/Playlist_Block_Test.php b/projects/packages/videopress/tests/php/Playlist_Block_Test.php index a7b24bcb4adf..897cd93b1dc5 100644 --- a/projects/packages/videopress/tests/php/Playlist_Block_Test.php +++ b/projects/packages/videopress/tests/php/Playlist_Block_Test.php @@ -375,6 +375,20 @@ function ( $url, $guid ) { $this->assertSame( 1, substr_count( $markup, 'target="_blank"' ) ); } + /** + * Entries carrying views and an upload time get the meta line; stored entries do not. + */ + public function test_render_entry_stats() { + $videos = $this->attributes()['videos']; + $videos[0]['views'] = 12345; + $videos[0]['publishedAt'] = time() - 3 * DAY_IN_SECONDS; + + $markup = VideoPress_Initializer::render_videopress_playlist_block( $this->attributes( array( 'videos' => $videos ) ) ); + + $this->assertStringContainsString( '12K views · 3 days ago', $markup ); + $this->assertSame( 1, substr_count( $markup, 'videopress-playlist__entry-stats' ) ); + } + /** * A VideoPress attachment whose GUID lookup is pre-cached. * diff --git a/projects/plugins/jetpack/changelog/add-videopress-latest-videos-browse b/projects/plugins/jetpack/changelog/add-videopress-latest-videos-browse new file mode 100644 index 000000000000..8527b22a4b1e --- /dev/null +++ b/projects/plugins/jetpack/changelog/add-videopress-latest-videos-browse @@ -0,0 +1,4 @@ +Significance: minor +Type: enhancement + +VideoPress: Let the Latest Videos Playlist block sort, search, filter by length and paginate, and show view counts. diff --git a/projects/plugins/jetpack/changelog/fix-sync-test-core-after-insert-post-callback b/projects/plugins/jetpack/changelog/fix-sync-test-core-after-insert-post-callback new file mode 100644 index 000000000000..32e879d17fc0 --- /dev/null +++ b/projects/plugins/jetpack/changelog/fix-sync-test-core-after-insert-post-callback @@ -0,0 +1,5 @@ +Significance: patch +Type: other +Comment: Tests: keep a WordPress trunk callback out of a Sync test that passes invalid post arguments. + + diff --git a/projects/plugins/jetpack/tests/php/sync/Jetpack_Sync_Post_Test.php b/projects/plugins/jetpack/tests/php/sync/Jetpack_Sync_Post_Test.php index 2f1229169632..0e829c8f57cf 100644 --- a/projects/plugins/jetpack/tests/php/sync/Jetpack_Sync_Post_Test.php +++ b/projects/plugins/jetpack/tests/php/sync/Jetpack_Sync_Post_Test.php @@ -1473,6 +1473,8 @@ public static function provider_jetpack_published_post_no_action() { #[DataProvider( 'provider_jetpack_published_post_no_action' )] public function test_sync_jetpack_published_post_no_action( $post_ID, $post ) { $this->server_event_storage->reset(); + // Only the Sync listener is under test; core's typed callback throws on these invalid arguments. + remove_action( 'wp_after_insert_post', 'wp_random_content_flush_rewrite_rules_for_post' ); do_action( 'wp_after_insert_post', $post_ID, $post, false, null ); $this->sender->do_sync(); diff --git a/projects/plugins/videopress/changelog/add-videopress-latest-videos-browse b/projects/plugins/videopress/changelog/add-videopress-latest-videos-browse new file mode 100644 index 000000000000..fdb7b839e02d --- /dev/null +++ b/projects/plugins/videopress/changelog/add-videopress-latest-videos-browse @@ -0,0 +1,4 @@ +Significance: minor +Type: added + +Let the Latest Videos Playlist block sort, search, filter by length and paginate, and show view counts.