diff --git a/projects/packages/videopress/changelog/update-videopress-playlist-blocks-for-channels b/projects/packages/videopress/changelog/update-videopress-playlist-blocks-for-channels new file mode 100644 index 000000000000..d4edc931f08d --- /dev/null +++ b/projects/packages/videopress/changelog/update-videopress-playlist-blocks-for-channels @@ -0,0 +1,4 @@ +Significance: minor +Type: added + +Video Playlist block: Add a source setting to show a playlist published on the site, picked from a list and previewed in the editor. All Playlists block: Add a "Recently updated" order and an option to show each playlist's last update and length. diff --git a/projects/packages/videopress/src/class-all-playlists-block.php b/projects/packages/videopress/src/class-all-playlists-block.php index 95ce091dace2..d591fc8a3823 100644 --- a/projects/packages/videopress/src/class-all-playlists-block.php +++ b/projects/packages/videopress/src/class-all-playlists-block.php @@ -35,7 +35,7 @@ class All_Playlists_Block { * * @var string[] */ - const ORDERS = array( 'newest', 'oldest', 'title' ); + const ORDERS = array( 'newest', 'oldest', 'title', 'updated' ); /** * Supported pagination styles, the first being the default. @@ -108,7 +108,7 @@ public static function register( $metadata_file = null ) { * * @param mixed $block_attributes Block attributes; anything but an array counts as none. * - * @return array{layout: string, columns: int, per_page: int, order_by: string, show_description: bool, show_video_count: bool, pagination: string} + * @return array{layout: string, columns: int, per_page: int, order_by: string, show_description: bool, show_video_count: bool, pagination: string, show_updated: bool} */ public static function settings( $block_attributes ) { $block_attributes = is_array( $block_attributes ) ? $block_attributes : array(); @@ -135,6 +135,7 @@ public static function settings( $block_attributes ) { 'show_description' => $flag( 'showDescription', true ), 'show_video_count' => $flag( 'showVideoCount', true ), 'pagination' => $pick( 'pagination', self::PAGINATIONS ), + 'show_updated' => $flag( 'showUpdated', false ), ); } @@ -186,9 +187,12 @@ function ( $a, $b ) { } ); } else { - // Newest first by the source post's publish date; playlists without a post go last. - $date_of = function ( $playlist ) { - return $playlist['post'] ? $playlist['post']->post_date_gmt : ''; + // By the source post's publish ( or, for "updated", modified ) date; playlists without a post go last. + $date_of = function ( $playlist ) use ( $order_by ) { + if ( ! $playlist['post'] ) { + return ''; + } + return 'updated' === $order_by ? $playlist['post']->post_modified_gmt : $playlist['post']->post_date_gmt; }; usort( $playlists, @@ -198,7 +202,7 @@ function ( $a, $b ) use ( $date_of, $order_by ) { if ( '' === $date_a || '' === $date_b ) { $result = strcmp( $date_b, $date_a ); } else { - $result = 'newest' === $order_by ? strcmp( $date_b, $date_a ) : strcmp( $date_a, $date_b ); + $result = 'oldest' === $order_by ? strcmp( $date_a, $date_b ) : strcmp( $date_b, $date_a ); } return 0 !== $result ? $result : strcmp( $a['key'], $b['key'] ); } @@ -473,6 +477,12 @@ private static function render_item( $playlist, $settings, $page, $hidden ) { if ( $settings['show_description'] && '' !== $playlist['description'] ) { $body .= sprintf( '

%s

', esc_html( $playlist['description'] ) ); } + if ( $settings['show_updated'] ) { + $meta = self::updated_meta( $playlist ); + if ( '' !== $meta ) { + $body .= sprintf( '%s', esc_html( $meta ) ); + } + } $body .= sprintf( '%s', esc_html__( 'First video is private or was deleted.', 'jetpack-videopress-pkg' ) @@ -496,6 +506,33 @@ private static function render_item( $playlist, $settings, $page, $hidden ) { ); } + /** + * "Updated 2 weeks ago · 1 hr 12 min" for a card. + * + * @param array $playlist A record from ordered_playlists(). + * + * @return string + */ + public static function updated_meta( $playlist ) { + $parts = array(); + if ( $playlist['post'] instanceof WP_Post ) { + $ago = Channel_Data::ago( (int) strtotime( $playlist['post']->post_modified_gmt . ' UTC' ) ); + if ( '' !== $ago ) { + /* translators: %s: how long ago, e.g. "2 weeks ago". */ + $parts[] = sprintf( __( 'Updated %s', 'jetpack-videopress-pkg' ), $ago ); + } + } + $total_ms = 0; + foreach ( Initializer::sanitize_playlist_entries( $playlist['videos'] ) as $entry ) { + $total_ms += $entry['durationMs']; + } + $runtime = Initializer::playlist_runtime_label( $total_ms ); + if ( '' !== $runtime ) { + $parts[] = $runtime; + } + return implode( ' · ', $parts ); + } + /** * Render the numbered pagination. * diff --git a/projects/packages/videopress/src/class-channel-blocks.php b/projects/packages/videopress/src/class-channel-blocks.php new file mode 100644 index 000000000000..629370a8c760 --- /dev/null +++ b/projects/packages/videopress/src/class-channel-blocks.php @@ -0,0 +1,72 @@ +is_registered( Playlist_Index::BLOCK_NAME ) ) { + return; + } + if ( ! has_filter( 'render_block_data', array( Channel::class, 'playlist_source_block' ) ) ) { + add_filter( 'render_block_data', array( Channel::class, 'playlist_source_block' ) ); + } + if ( ! has_action( 'enqueue_block_editor_assets', array( __CLASS__, 'enqueue_editor_data' ) ) ) { + add_action( 'enqueue_block_editor_assets', array( __CLASS__, 'enqueue_editor_data' ) ); + } + } + + /** + * Hand the editor the site's playlists, most recently updated first, for the playlist pickers + * of the blocks that show one and for their canvas previews. An inline script rather than a + * REST route, so WordPress.com Simple's editor gets it too. + * + * @return void + */ + public static function enqueue_editor_data() { + if ( ! current_user_can( 'edit_posts' ) ) { + return; + } + $handle = ''; + foreach ( array( Playlist_Index::BLOCK_NAME ) as $name ) { + $block_type = \WP_Block_Type_Registry::get_instance()->get_registered( $name ); + if ( $block_type && ! empty( $block_type->editor_script_handles ) ) { + $handle = $block_type->editor_script_handles[0]; + break; + } + } + if ( '' === $handle ) { + return; + } + + $playlists = array(); + foreach ( Channel::playlists() as $playlist ) { + $playlists[] = array( + 'key' => $playlist['key'], + 'title' => $playlist['title'], + 'videos' => $playlist['videos'], + ); + } + wp_add_inline_script( + $handle, + 'window.videopressChannelEditor = ' . wp_json_encode( array( 'playlists' => $playlists ), JSON_HEX_TAG | JSON_UNESCAPED_SLASHES ) . ';', + 'before' + ); + } +} diff --git a/projects/packages/videopress/src/class-channel.php b/projects/packages/videopress/src/class-channel.php index d095435592f8..ad513f2dd732 100644 --- a/projects/packages/videopress/src/class-channel.php +++ b/projects/packages/videopress/src/class-channel.php @@ -24,10 +24,11 @@ */ class Channel { - const MIME_TYPE = 'video/videopress'; - const ENDPOINT = 'videopress'; - const QUERY_VAR = 'videopress_video'; - const TEMPLATE = 'videopress-video'; + const MIME_TYPE = 'video/videopress'; + const ENDPOINT = 'videopress'; + const QUERY_VAR = 'videopress_video'; + const TEMPLATE = 'videopress-video'; + const PLAYLIST_SOURCES = array( 'own', 'index' ); /** * Whether the feature has been wired up in this request. @@ -335,4 +336,115 @@ public static function queried_guid() { $post = self::current_video(); return $post instanceof WP_Post ? self::guid( $post ) : ''; } + + /** + * One indexed playlist with its key, or null. + * + * @param string $key Playlist key. + * @return array|null Record with key, title, description, videos and post_id. + */ + public static function playlist_record( $key ) { + $key = is_string( $key ) ? sanitize_key( $key ) : ''; + if ( '' === $key ) { + return null; + } + $index = Playlist_Index::get_playlists(); + if ( ! isset( $index[ $key ] ) || ! is_array( $index[ $key ] ) ) { + return null; + } + return self::normalize_record( $key, $index[ $key ] ); + } + + /** + * Every indexed playlist whose source post is published, most recently updated first. + * + * @return array[] Records as playlist_record() returns them, plus `updated` ( unix time ). + */ + public static function playlists() { + $playlists = array(); + foreach ( Playlist_Index::get_playlists() as $key => $record ) { + if ( ! is_array( $record ) ) { + continue; + } + $record = self::normalize_record( (string) $key, $record ); + $post = $record['post_id'] ? get_post( $record['post_id'] ) : null; + if ( ! $post instanceof WP_Post || 'publish' !== $post->post_status ) { + continue; + } + $record['updated'] = (int) strtotime( $post->post_modified_gmt . ' UTC' ); + $playlists[] = $record; + } + usort( + $playlists, + function ( $a, $b ) { + return $b['updated'] !== $a['updated'] ? $b['updated'] - $a['updated'] : strcmp( $a['key'], $b['key'] ); + } + ); + return $playlists; + } + + /** + * Normalize an index record. + * + * @param string $key Playlist key. + * @param array $record Index record. + * @return array + */ + private static function normalize_record( $key, array $record ) { + return array( + 'key' => $key, + 'title' => isset( $record['title'] ) && is_string( $record['title'] ) ? $record['title'] : '', + 'description' => isset( $record['description'] ) && is_string( $record['description'] ) ? $record['description'] : '', + 'videos' => Initializer::sanitize_playlist_entries( $record['videos'] ?? null ), + 'post_id' => isset( $record['post_id'] ) ? absint( $record['post_id'] ) : 0, + ); + } + + /** + * The playlist a block shows: an indexed one by key ( the most recently + * updated when no key is set ). + * + * @param string $source One of PLAYLIST_SOURCES. + * @param string $key Playlist key for the `index` source. + * @return array|null + */ + public static function source_playlist( $source, $key = '' ) { + if ( 'index' !== $source ) { + return null; + } + if ( is_string( $key ) && '' !== $key ) { + return self::playlist_record( $key ); + } + $playlists = self::playlists(); + return $playlists ? $playlists[0] : null; + } + + /** + * A Video Playlist block whose `source` is `index` shows that playlist. Hooked by + * Channel_Blocks::register() on every site with the block, channel theme or not. + * + * @param array $parsed_block The block being rendered. + * @return array + */ + public static function playlist_source_block( $parsed_block ) { + if ( ! isset( $parsed_block['blockName'] ) || Playlist_Index::BLOCK_NAME !== $parsed_block['blockName'] ) { + return $parsed_block; + } + $attrs = isset( $parsed_block['attrs'] ) && is_array( $parsed_block['attrs'] ) ? $parsed_block['attrs'] : array(); + $source = isset( $attrs['source'] ) && in_array( $attrs['source'], self::PLAYLIST_SOURCES, true ) ? $attrs['source'] : 'own'; + if ( 'own' === $source ) { + return $parsed_block; + } + + $playlist = self::source_playlist( $source, isset( $attrs['sourcePlaylistId'] ) ? (string) $attrs['sourcePlaylistId'] : '' ); + if ( ! $playlist ) { + $parsed_block['attrs']['videos'] = array(); + return $parsed_block; + } + + $parsed_block['attrs']['videos'] = $playlist['videos']; + $parsed_block['attrs']['playlistTitle'] = $playlist['title']; + $parsed_block['attrs']['playlistDescription'] = $playlist['description']; + return $parsed_block; + } } diff --git a/projects/packages/videopress/src/class-initializer.php b/projects/packages/videopress/src/class-initializer.php index 4d02e46e90bd..6d163fb8f11c 100644 --- a/projects/packages/videopress/src/class-initializer.php +++ b/projects/packages/videopress/src/class-initializer.php @@ -295,6 +295,9 @@ public static function register_videopress_blocks() { // Register All Playlists block. self::register_videopress_all_playlists_block(); + + // Register the channel blocks' shared pieces: the playlist block's `source` and the editor data its picker reads. + Channel_Blocks::register(); } /** @@ -828,7 +831,7 @@ private static function playlist_timecode( $duration_ms ) { * * @return string Runtime label, or an empty string when the duration is unknown. */ - private static function playlist_runtime_label( $duration_ms ) { + public static function playlist_runtime_label( $duration_ms ) { if ( $duration_ms <= 0 ) { return ''; } diff --git a/projects/packages/videopress/src/class-playlist-index.php b/projects/packages/videopress/src/class-playlist-index.php index 0cb30484416b..a536716a1ed6 100644 --- a/projects/packages/videopress/src/class-playlist-index.php +++ b/projects/packages/videopress/src/class-playlist-index.php @@ -289,7 +289,12 @@ private static function find_playlist_blocks( array $blocks ) { } if ( self::BLOCK_NAME === ( $block['blockName'] ?? null ) ) { - $found[] = isset( $block['attrs'] ) && is_array( $block['attrs'] ) ? $block['attrs'] : array(); + $attrs = isset( $block['attrs'] ) && is_array( $block['attrs'] ) ? $block['attrs'] : array(); + // A block that shows another playlist ( any `source` but own ) is not one itself. + if ( isset( $attrs['source'] ) && 'own' !== $attrs['source'] ) { + continue; + } + $found[] = $attrs; } if ( ! empty( $block['innerBlocks'] ) && is_array( $block['innerBlocks'] ) ) { diff --git a/projects/packages/videopress/src/client/block-editor/blocks/all-playlists/block.json b/projects/packages/videopress/src/client/block-editor/blocks/all-playlists/block.json index 276865de5cc9..a0856c3c2645 100644 --- a/projects/packages/videopress/src/client/block-editor/blocks/all-playlists/block.json +++ b/projects/packages/videopress/src/client/block-editor/blocks/all-playlists/block.json @@ -52,7 +52,7 @@ }, "orderBy": { "type": "string", - "enum": [ "newest", "oldest", "title" ], + "enum": [ "newest", "oldest", "title", "updated" ], "default": "newest" }, "showDescription": { @@ -67,6 +67,10 @@ "type": "string", "enum": [ "numbered", "load-more" ], "default": "numbered" + }, + "showUpdated": { + "type": "boolean", + "default": false } }, "editorScript": "file:./index.js", diff --git a/projects/packages/videopress/src/client/block-editor/blocks/all-playlists/edit.tsx b/projects/packages/videopress/src/client/block-editor/blocks/all-playlists/edit.tsx index b6494f9e6326..d46eef7c8510 100644 --- a/projects/packages/videopress/src/client/block-editor/blocks/all-playlists/edit.tsx +++ b/projects/packages/videopress/src/client/block-editor/blocks/all-playlists/edit.tsx @@ -73,8 +73,16 @@ export default function AllPlaylistsEdit( { attributes, setAttributes, }: BlockEditProps< AllPlaylistsAttributes > ) { - const { layout, columns, perPage, orderBy, showDescription, showVideoCount, pagination } = - attributes; + const { + layout, + columns, + perPage, + orderBy, + showDescription, + showVideoCount, + pagination, + showUpdated, + } = attributes; const { status, html, summary } = useRenderedPreview( attributes ); const styleVars = blockStyleVars( attributes ); @@ -170,6 +178,7 @@ export default function AllPlaylistsEdit( { { value: 'newest', label: __( 'Newest first', 'jetpack-videopress-pkg' ) }, { value: 'oldest', label: __( 'Oldest first', 'jetpack-videopress-pkg' ) }, { value: 'title', label: __( 'Title A–Z', 'jetpack-videopress-pkg' ) }, + { value: 'updated', label: __( 'Recently updated', 'jetpack-videopress-pkg' ) }, ] } onChange={ ( value: string ) => setAttributes( { orderBy: value as AllPlaylistsOrder } ) } /> @@ -188,6 +197,12 @@ export default function AllPlaylistsEdit( { checked={ showVideoCount } onChange={ ( value: boolean ) => setAttributes( { showVideoCount: value } ) } /> + setAttributes( { showUpdated: value } ) } + /> diff --git a/projects/packages/videopress/src/client/block-editor/blocks/all-playlists/test/edit.test.tsx b/projects/packages/videopress/src/client/block-editor/blocks/all-playlists/test/edit.test.tsx index 7ecfbb91884c..d67d05bb761e 100644 --- a/projects/packages/videopress/src/client/block-editor/blocks/all-playlists/test/edit.test.tsx +++ b/projects/packages/videopress/src/client/block-editor/blocks/all-playlists/test/edit.test.tsx @@ -178,4 +178,20 @@ describe( 'AllPlaylistsEdit', () => { await userEvent.click( screen.getByRole( 'radio', { name: '“Load more” button' } ) ); expect( setAttributes ).toHaveBeenLastCalledWith( { pagination: 'load-more' } ); } ); + + it( 'sorts by last update and shows it on the cards', async () => { + apiFetchMock.mockResolvedValue( { rendered: '' } ); + const setAttributes = jest.fn(); + + renderEdit( { orderBy: 'updated', showUpdated: true }, setAttributes ); + await waitFor( () => expect( apiFetchMock ).toHaveBeenCalled() ); + + const path = decodeURIComponent( apiFetchMock.mock.calls[ 0 ][ 0 ].path ); + expect( path ).toContain( 'attributes[orderBy]=updated' ); + expect( path ).toContain( 'attributes[showUpdated]=true' ); + expect( screen.getByRole( 'combobox', { name: 'Order by' } ) ).toHaveValue( 'updated' ); + + await userEvent.click( screen.getByRole( 'checkbox', { name: 'Last update and length' } ) ); + expect( setAttributes ).toHaveBeenLastCalledWith( { showUpdated: false } ); + } ); } ); diff --git a/projects/packages/videopress/src/client/block-editor/blocks/all-playlists/types.ts b/projects/packages/videopress/src/client/block-editor/blocks/all-playlists/types.ts index e8dd0e0f41ed..50a7957b56e4 100644 --- a/projects/packages/videopress/src/client/block-editor/blocks/all-playlists/types.ts +++ b/projects/packages/videopress/src/client/block-editor/blocks/all-playlists/types.ts @@ -1,5 +1,5 @@ export type AllPlaylistsLayout = 'gallery' | 'list'; -export type AllPlaylistsOrder = 'newest' | 'oldest' | 'title'; +export type AllPlaylistsOrder = 'newest' | 'oldest' | 'title' | 'updated'; export type AllPlaylistsPagination = 'numbered' | 'load-more'; /** @@ -24,6 +24,8 @@ export type AllPlaylistsAttributes = BlockStyleAttributes & { showDescription: boolean; showVideoCount: boolean; pagination: AllPlaylistsPagination; + // "Updated 2 weeks ago · 1 hr 12 min" under each card. + showUpdated?: boolean; }; /** diff --git a/projects/packages/videopress/src/client/block-editor/blocks/all-playlists/use-rendered-preview.ts b/projects/packages/videopress/src/client/block-editor/blocks/all-playlists/use-rendered-preview.ts index dfb3b13485a6..42cefb015123 100644 --- a/projects/packages/videopress/src/client/block-editor/blocks/all-playlists/use-rendered-preview.ts +++ b/projects/packages/videopress/src/client/block-editor/blocks/all-playlists/use-rendered-preview.ts @@ -53,8 +53,16 @@ export function splitRenderedPreview( html: string ): Pick< RenderedPreview, 'ht * @return The rendered markup, the index totals and the loading state. */ export default function useRenderedPreview( attributes: AllPlaylistsAttributes ): RenderedPreview { - const { layout, columns, perPage, orderBy, showDescription, showVideoCount, pagination } = - attributes; + const { + layout, + columns, + perPage, + orderBy, + showDescription, + showVideoCount, + pagination, + showUpdated, + } = attributes; const [ preview, setPreview ] = useState< RenderedPreview >( { status: 'loading', html: '', @@ -76,6 +84,7 @@ export default function useRenderedPreview( attributes: AllPlaylistsAttributes ) showDescription, showVideoCount, pagination, + showUpdated, }, } ), } ) @@ -93,7 +102,16 @@ export default function useRenderedPreview( attributes: AllPlaylistsAttributes ) return () => { cancelled = true; }; - }, [ layout, columns, perPage, orderBy, showDescription, showVideoCount, pagination ] ); + }, [ + layout, + columns, + perPage, + orderBy, + showDescription, + showVideoCount, + pagination, + showUpdated, + ] ); return preview; } 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 620cb295f6f5..ce69396adc9e 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 @@ -101,6 +101,15 @@ "entryTitleFontFamily": { "type": "string", "default": "" + }, + "source": { + "type": "string", + "enum": [ "own", "index" ], + "default": "own" + }, + "sourcePlaylistId": { + "type": "string", + "default": "" } }, "editorScript": "file:./index.js", diff --git a/projects/packages/videopress/src/client/block-editor/blocks/playlist/index.tsx b/projects/packages/videopress/src/client/block-editor/blocks/playlist/index.tsx index 9c8a78569d31..155f05d794dd 100644 --- a/projects/packages/videopress/src/client/block-editor/blocks/playlist/index.tsx +++ b/projects/packages/videopress/src/client/block-editor/blocks/playlist/index.tsx @@ -11,15 +11,40 @@ import '../../set-webpack-public-path'; import { VideoPressIcon as icon } from '../video/components/icons'; import metadata from './block.json'; import Edit from './edit'; +import { PlaylistSourcePanel, SourcedPlaylistEdit } from './source-controls'; /** * Types */ import type { PlaylistAttributes } from './types'; +import type { BlockEditProps } from '@wordpress/blocks'; export const { name, title, description, attributes, category } = metadata; +/** + * Edit the block's own videos, or configure a playlist that shows another one. + * + * @param props - Block edit props. + * @return Edit component. + */ +function PlaylistBlockEdit( props: BlockEditProps< PlaylistAttributes > ) { + const isSourced = !! props.attributes.source && 'own' !== props.attributes.source; + return ( + <> + + { isSourced ? ( + + ) : ( + + ) } + + ); +} + registerBlockType< PlaylistAttributes >( name, { - edit: Edit, + edit: PlaylistBlockEdit, category, title, icon, 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 new file mode 100644 index 000000000000..f9985a19e9da --- /dev/null +++ b/projects/packages/videopress/src/client/block-editor/blocks/playlist/source-controls.tsx @@ -0,0 +1,141 @@ +/** + * WordPress dependencies + */ +import { InspectorControls, useBlockProps } from '@wordpress/block-editor'; +import { PanelBody, Placeholder, SelectControl } from '@wordpress/components'; +import { useState } from '@wordpress/element'; +import { __ } from '@wordpress/i18n'; +/** + * Internal dependencies + */ +import { editorSourcePlaylist, PlaylistPicker } from '../../channel/editor-controls'; +import { VideoPressIcon } from '../video/components/icons'; +import { PlaylistSettingsPanels, PlaylistStylesControls } from './inspector-controls'; +import PlaylistPreview from './preview'; +import usePlaylistLiveMetadata from './use-live-metadata'; +import { playlistFontVariables, playlistWrapperClasses } from './utils'; +/** + * Types + */ +import type { PlaylistAttributes, PlaylistEntry, PlaylistSource } from './types'; +import type { BlockEditProps } from '@wordpress/blocks'; + +type Props = Pick< BlockEditProps< PlaylistAttributes >, 'attributes' | 'setAttributes' >; + +/** + * Sidebar panel choosing where the playlist's videos come from. + * + * @param props - Component props. + * @param props.attributes - Block attributes. + * @param props.setAttributes - Attribute setter. + * @return The panel. + */ +export function PlaylistSourcePanel( { attributes, setAttributes }: Props ) { + const source = attributes.source ?? 'own'; + return ( + + + setAttributes( { source: value as PlaylistSource } ) } + /> + { 'index' === source && ( + setAttributes( { sourcePlaylistId: value } ) } + /> + ) } + + + ); +} + +// Stable, so the live metadata effect does not rerun while there are no videos. +const NO_VIDEOS: PlaylistEntry[] = []; + +/** + * Canvas of a playlist that shows another playlist: a preview of that playlist's videos, as the + * site renders them, with the display settings of this block. + * + * @param props - Component props. + * @param props.attributes - Block attributes. + * @param props.setAttributes - Attribute setter. + * @return Edit component. + */ +export function SourcedPlaylistEdit( { attributes, setAttributes }: Props ) { + const playlist = editorSourcePlaylist( attributes.sourcePlaylistId ?? '' ); + const videos = playlist?.videos?.length ? playlist.videos : NO_VIDEOS; + const { liveMetadata } = usePlaylistLiveMetadata( videos ); + const [ previewIndex, setPreviewIndex ] = useState( 0 ); + const currentIndex = Math.min( previewIndex, Math.max( 0, videos.length - 1 ) ); + + const blockProps = useBlockProps( { + className: videos.length + ? playlistWrapperClasses( attributes ) + : 'videopress-playlist is-empty', + style: playlistFontVariables( attributes.entryTitleFontFamily ), + } ); + const controls = ( + <> + + + + + + ); + + if ( ! videos.length ) { + // Kept as separate statements so the minifier can't merge the __() calls. + const unknownLabel = __( 'Shows a playlist published on this site.', 'jetpack-videopress-pkg' ); + const noneLabel = __( + 'No playlists yet. Publish a Video Playlist block with a title and it will show up here.', + 'jetpack-videopress-pkg' + ); + const missingLabel = __( + 'This playlist is no longer published. Pick another one in the block settings.', + 'jetpack-videopress-pkg' + ); + const emptyLabel = __( 'This playlist has no videos yet.', 'jetpack-videopress-pkg' ); + + let instructions: string = unknownLabel; + if ( null === playlist ) { + instructions = attributes.sourcePlaylistId ? missingLabel : noneLabel; + } else if ( playlist ) { + instructions = emptyLabel; + } + + return ( +
+ { controls } + +
+ ); + } + + return ( +
+ { controls } + +
+ ); +} diff --git a/projects/packages/videopress/src/client/block-editor/blocks/playlist/test/block-edit.test.tsx b/projects/packages/videopress/src/client/block-editor/blocks/playlist/test/block-edit.test.tsx new file mode 100644 index 000000000000..b973d4c28ebb --- /dev/null +++ b/projects/packages/videopress/src/client/block-editor/blocks/playlist/test/block-edit.test.tsx @@ -0,0 +1,48 @@ +import { render, screen } from '@testing-library/react'; +import { registerBlockType } from '@wordpress/blocks'; +import '../index'; +import type { PlaylistAttributes } from '../types'; + +jest.mock( '@wordpress/blocks', () => ( { + registerBlockType: jest.fn(), +} ) ); +jest.mock( '@wordpress/block-editor', () => ( { + InnerBlocks: { Content: () => null }, +} ) ); +jest.mock( '../edit', () => ( { + __esModule: true, + default: () =>
, +} ) ); +jest.mock( '../source-controls', () => ( { + PlaylistSourcePanel: () =>
, + SourcedPlaylistEdit: () =>
, +} ) ); + +const registerBlockTypeMock = registerBlockType as jest.Mock; + +/** + * Render the registered edit component. + * + * @param attributes - Block attributes. + */ +function renderEdit( attributes: Partial< PlaylistAttributes > ) { + const { edit: Edit } = registerBlockTypeMock.mock.calls[ 0 ][ 1 ]; + render( ); +} + +describe( 'playlist block edit', () => { + it( 'edits the block’s own videos by default', () => { + renderEdit( { videos: [] } ); + + expect( screen.getByTestId( 'source-panel' ) ).toBeInTheDocument(); + expect( screen.getByTestId( 'own-videos-edit' ) ).toBeInTheDocument(); + expect( screen.queryByTestId( 'sourced-edit' ) ).not.toBeInTheDocument(); + } ); + + it( 'shows the sourced placeholder for a playlist that shows another one', () => { + renderEdit( { videos: [], source: 'index' } ); + + expect( screen.getByTestId( 'sourced-edit' ) ).toBeInTheDocument(); + expect( screen.queryByTestId( 'own-videos-edit' ) ).not.toBeInTheDocument(); + } ); +} ); diff --git a/projects/packages/videopress/src/client/block-editor/blocks/playlist/test/source-controls.test.tsx b/projects/packages/videopress/src/client/block-editor/blocks/playlist/test/source-controls.test.tsx new file mode 100644 index 000000000000..c5da35cb1156 --- /dev/null +++ b/projects/packages/videopress/src/client/block-editor/blocks/playlist/test/source-controls.test.tsx @@ -0,0 +1,169 @@ +import { render, screen, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { PlaylistSourcePanel, SourcedPlaylistEdit } from '../source-controls'; +import type { PlaylistAttributes } from '../types'; + +jest.mock( '@wordpress/block-editor', () => ( { + useBlockProps: ( props: Record< string, unknown > = {} ) => props, + InspectorControls: ( { children }: { children: React.ReactNode } ) => ( +
{ children }
+ ), +} ) ); + +// The display settings have their own tests with the playlist edit component. +jest.mock( '../inspector-controls', () => ( { + PlaylistSettingsPanels: () =>
, + PlaylistStylesControls: () =>
, +} ) ); + +// The preview and the live metadata have their own tests; here, only which videos reach them. +const mockUseLiveMetadata = jest.fn< { liveMetadata: object }, [ unknown ] >( () => ( { + liveMetadata: {}, +} ) ); +jest.mock( '../use-live-metadata', () => ( { + __esModule: true, + default: ( videos: Array< { guid: string } > ) => mockUseLiveMetadata( videos ), +} ) ); +jest.mock( '../preview', () => ( { + __esModule: true, + default: ( { videos }: { videos: Array< { guid: string } > } ) => ( +
    + { videos.map( video => ( +
  1. { video.guid }
  2. + ) ) } +
+ ), +} ) ); + +/** + * Attributes of a playlist block, with overrides. + * + * @param overrides - Attribute overrides. + * @return Attributes. + */ +function attributes( overrides: Partial< PlaylistAttributes > = {} ) { + return { videos: [], showPlaylistTitle: true, ...overrides } as PlaylistAttributes; +} + +afterEach( () => { + delete window.videopressChannelEditor; +} ); + +describe( 'PlaylistSourcePanel', () => { + it( 'defaults to the block’s own videos and switches the source', async () => { + const setAttributes = jest.fn(); + render( ); + + // Collapsed until the block shows another playlist. + expect( screen.queryByRole( 'combobox', { name: 'Videos' } ) ).not.toBeInTheDocument(); + await userEvent.click( screen.getByRole( 'button', { name: 'Source' } ) ); + const select = screen.getByRole( 'combobox', { name: 'Videos' } ); + expect( select ).toHaveValue( 'own' ); + expect( screen.queryByRole( 'textbox', { name: 'Playlist ID' } ) ).not.toBeInTheDocument(); + + await userEvent.selectOptions( select, 'index' ); + expect( setAttributes ).toHaveBeenCalledWith( { source: 'index' } ); + } ); + + it( 'picks the playlist to show for the index source', async () => { + window.videopressChannelEditor = { playlists: [ { key: 'mc', title: 'Molten Core' } ] }; + const setAttributes = jest.fn(); + render( + + ); + + await userEvent.selectOptions( screen.getByRole( 'combobox', { name: 'Playlist' } ), 'mc' ); + expect( setAttributes ).toHaveBeenCalledWith( { sourcePlaylistId: 'mc' } ); + } ); +} ); + +describe( 'SourcedPlaylistEdit', () => { + const playlists = [ + { + key: 'road', + title: 'The road to 60', + videos: [ { guid: 'ghiJKL34', durationMs: 1000, height: 1080 } ], + }, + { + key: 'mc', + title: 'Molten Core progression', + videos: [ { guid: 'abcDEF12' }, { guid: 'ghiJKL34' } ], + }, + { key: 'new', title: 'Coming soon', videos: [] }, + ]; + + /** + * Render the canvas of an `index` playlist block. + * + * @param sourcePlaylistId - Picked playlist key. + */ + function renderSourced( sourcePlaylistId?: string ) { + render( + + ); + } + + /** + * GUIDs the preview lists. + * + * @return GUIDs. + */ + function previewGuids() { + return within( screen.getByTestId( 'playlist-preview' ) ) + .getAllByRole( 'listitem' ) + .map( item => item.textContent ); + } + + it( 'previews the picked playlist with the block’s display settings', () => { + window.videopressChannelEditor = { playlists }; + renderSourced( 'mc' ); + + expect( previewGuids() ).toEqual( [ 'abcDEF12', 'ghiJKL34' ] ); + expect( mockUseLiveMetadata ).toHaveBeenLastCalledWith( playlists[ 1 ].videos ); + expect( screen.getByRole( 'figure' ) ).toHaveClass( 'videopress-playlist', 'is-layout-grid' ); + expect( screen.getByTestId( 'settings-panels' ) ).toBeInTheDocument(); + expect( screen.getByTestId( 'styles-controls' ) ).toBeInTheDocument(); + } ); + + it( 'previews the most recently updated playlist when none is picked', () => { + window.videopressChannelEditor = { playlists }; + renderSourced(); + + expect( previewGuids() ).toEqual( [ 'ghiJKL34' ] ); + } ); + + it.each( [ + [ 'a playlist without videos', { playlists }, 'new', 'This playlist has no videos yet.' ], + [ + 'a playlist that is no longer published', + { playlists }, + 'gone', + 'This playlist is no longer published. Pick another one in the block settings.', + ], + [ + 'a site without playlists', + { playlists: [] }, + '', + 'No playlists yet. Publish a Video Playlist block with a title and it will show up here.', + ], + [ + 'an editor without the playlist list', + undefined, + 'mc', + 'Shows a playlist published on this site.', + ], + ] )( 'shows a placeholder for %s', ( _case, data, key, instructions ) => { + window.videopressChannelEditor = data; + renderSourced( key ); + + expect( screen.queryByTestId( 'playlist-preview' ) ).not.toBeInTheDocument(); + expect( screen.getAllByText( instructions ).length ).toBeGreaterThan( 0 ); + expect( screen.getByTestId( 'settings-panels' ) ).toBeInTheDocument(); + } ); +} ); 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 d93232e636da..e4e6b9eb1741 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 @@ -66,4 +66,12 @@ export type PlaylistAttributes = PlaylistDisplayAttributes & { // Renders the title as a Heading inner block above the playlist. showPlaylistTitle: boolean; videos: PlaylistEntry[]; + /* + * Where the videos come from: the block's own list, or an indexed + * playlist ( sourcePlaylistId, empty = latest ). + */ + source?: PlaylistSource; + sourcePlaylistId?: string; }; + +export type PlaylistSource = 'own' | 'index'; diff --git a/projects/packages/videopress/src/client/block-editor/channel/editor-controls.tsx b/projects/packages/videopress/src/client/block-editor/channel/editor-controls.tsx new file mode 100644 index 000000000000..301755ec132d --- /dev/null +++ b/projects/packages/videopress/src/client/block-editor/channel/editor-controls.tsx @@ -0,0 +1,101 @@ +/** + * WordPress dependencies + */ +import { SelectControl, TextControl } from '@wordpress/components'; +import { __, sprintf } from '@wordpress/i18n'; +/** + * Types + */ +import type { PlaylistEntry } from '../blocks/playlist/types'; + +export type ChannelPlaylist = { + key: string; + title: string; + videos?: PlaylistEntry[]; +}; + +type ChannelEditorData = { + // The site's published playlists, most recently updated first. + playlists?: ChannelPlaylist[]; +}; + +declare global { + interface Window { + videopressChannelEditor?: ChannelEditorData; + } +} + +/** + * The playlist a block with the `index` source shows, as the server resolves it: the one with the + * key, or the most recently updated one when no key is set. + * + * @param key - Selected playlist key; empty for the most recently updated. + * @return The playlist; null when there is no such playlist; undefined when the editor was not given the list. + */ +export function editorSourcePlaylist( key = '' ): ChannelPlaylist | null | undefined { + const playlists = window.videopressChannelEditor?.playlists; + if ( ! Array.isArray( playlists ) ) { + return undefined; + } + return ( key ? playlists.find( playlist => playlist.key === key ) : playlists[ 0 ] ) ?? null; +} + +type PlaylistPickerProps = { + value?: string; + onChange: ( value: string ) => void; +}; + +/** + * Pick one of the site's playlists, or the most recently updated one. Falls back to typing the + * playlist ID when the editor was not given the list. + * + * @param props - Component props. + * @param props.value - Selected playlist key; empty for the most recently updated. + * @param props.onChange - Key setter. + * @return The control. + */ +export function PlaylistPicker( { value = '', onChange }: PlaylistPickerProps ) { + const playlists = window.videopressChannelEditor?.playlists; + + if ( ! Array.isArray( playlists ) ) { + return ( + + ); + } + + const options = [ + { value: '', label: __( 'Most recently updated', 'jetpack-videopress-pkg' ) }, + ...playlists.map( playlist => ( { + value: playlist.key, + label: playlist.title || __( 'Untitled playlist', 'jetpack-videopress-pkg' ), + } ) ), + ]; + if ( value && ! playlists.some( playlist => playlist.key === value ) ) { + options.push( { + value, + /* translators: %s: playlist ID that no longer matches a published playlist. */ + label: sprintf( __( 'Missing playlist (%s)', 'jetpack-videopress-pkg' ), value ), + } ); + } + + return ( + + ); +} diff --git a/projects/packages/videopress/src/client/block-editor/channel/test/editor-controls.test.tsx b/projects/packages/videopress/src/client/block-editor/channel/test/editor-controls.test.tsx new file mode 100644 index 000000000000..78203dbca9ba --- /dev/null +++ b/projects/packages/videopress/src/client/block-editor/channel/test/editor-controls.test.tsx @@ -0,0 +1,72 @@ +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { editorSourcePlaylist, PlaylistPicker } from '../editor-controls'; + +afterEach( () => { + delete window.videopressChannelEditor; +} ); + +describe( 'PlaylistPicker', () => { + it( 'falls back to typing the playlist ID when the editor has no playlist list', async () => { + const onChange = jest.fn(); + render( ); + + const input = screen.getByRole( 'textbox', { name: 'Playlist ID' } ); + expect( + screen.getByText( 'Leave empty for the most recently updated playlist.' ) + ).toBeInTheDocument(); + await userEvent.type( input, 'a' ); + expect( onChange ).toHaveBeenLastCalledWith( 'a' ); + } ); + + it( 'lists the site playlists after the most recently updated one', async () => { + window.videopressChannelEditor = { + playlists: [ + { key: 'mc', title: 'Molten Core' }, + { key: 'road', title: '' }, + ], + }; + const onChange = jest.fn(); + render( ); + + const select = screen.getByRole( 'combobox', { name: 'Playlist' } ); + expect( + Array.from( ( select as HTMLSelectElement ).options ).map( option => [ + option.value, + option.text, + ] ) + ).toEqual( [ + [ '', 'Most recently updated' ], + [ 'mc', 'Molten Core' ], + [ 'road', 'Untitled playlist' ], + ] ); + expect( select ).toHaveValue( '' ); + + await userEvent.selectOptions( select, 'mc' ); + expect( onChange.mock.lastCall[ 0 ] ).toBe( 'mc' ); + } ); + + it( 'keeps a picked playlist that is no longer published', () => { + window.videopressChannelEditor = { playlists: [ { key: 'mc', title: 'Molten Core' } ] }; + render( ); + + expect( screen.getByRole( 'combobox', { name: 'Playlist' } ) ).toHaveValue( 'gone' ); + expect( screen.getByRole( 'option', { name: 'Missing playlist (gone)' } ) ).toBeInTheDocument(); + } ); +} ); + +describe( 'editorSourcePlaylist', () => { + it( 'resolves the picked playlist, or the most recently updated one', () => { + expect( editorSourcePlaylist( 'mc' ) ).toBeUndefined(); + + const road = { key: 'road', title: 'The road to 60' }; + const mc = { key: 'mc', title: 'Molten Core' }; + window.videopressChannelEditor = { playlists: [ road, mc ] }; + expect( editorSourcePlaylist( 'mc' ) ).toBe( mc ); + expect( editorSourcePlaylist() ).toBe( road ); + expect( editorSourcePlaylist( 'gone' ) ).toBeNull(); + + window.videopressChannelEditor = { playlists: [] }; + expect( editorSourcePlaylist() ).toBeNull(); + } ); +} ); diff --git a/projects/packages/videopress/tests/php/All_Playlists_Block_Test.php b/projects/packages/videopress/tests/php/All_Playlists_Block_Test.php index abec23df3528..8c09df4f0602 100644 --- a/projects/packages/videopress/tests/php/All_Playlists_Block_Test.php +++ b/projects/packages/videopress/tests/php/All_Playlists_Block_Test.php @@ -103,6 +103,19 @@ private function create_post( $date = '2026-01-01 10:00:00' ) { ); } + /** + * Set a post's last modified date. + * + * @param int $post_id Post id. + * @param string $date Modified date, Y-m-d H:i:s GMT. + */ + private function set_modified( $post_id, $date ) { + // wp_insert_post() stamps the modified date itself. + $post = get_post( $post_id ); + $post->post_modified_gmt = $date; + wp_cache_replace( $post_id, $post, 'posts' ); + } + /** * Build an index record. * @@ -192,6 +205,7 @@ public function test_settings_normalizes_attributes() { 'show_description' => true, 'show_video_count' => true, 'pagination' => 'numbered', + 'show_updated' => false, ), All_Playlists_Block::settings( 'nope' ) ); @@ -374,6 +388,58 @@ public function test_render_orders_playlists() { } } + /** + * The `updated` order lists the playlist whose post was modified last first. + */ + public function test_render_orders_playlists_by_last_update() { + $alpha = $this->create_post( '2026-01-01 10:00:00' ); + $bravo = $this->create_post( '2026-03-01 10:00:00' ); + $this->set_modified( $alpha, '2026-04-01 10:00:00' ); + $this->set_modified( $bravo, '2026-03-01 10:00:00' ); + $this->seed_index( + array( + 'a' => $this->record( 'Alpha', $alpha ), + 'b' => $this->record( 'Bravo', $bravo ), + 'z' => $this->record( 'Zulu', 999999 ), + ) + ); + + $this->assertSame( + array( 'Bravo', 'Alpha' ), + $this->titles_in( All_Playlists_Block::render( array() ) ) + ); + $this->assertSame( + array( 'Alpha', 'Bravo' ), + $this->titles_in( All_Playlists_Block::render( array( 'orderBy' => 'updated' ) ) ) + ); + } + + /** + * `showUpdated` adds when the playlist was last updated and its total length. + */ + public function test_render_shows_the_last_update_and_length() { + $post = $this->create_post(); + $this->set_modified( $post, gmdate( 'Y-m-d H:i:s', time() - 2 * WEEK_IN_SECONDS ) ); + $this->seed_index( array( 'one' => $this->record( 'One', $post, 7 ) ) ); + + $this->assertStringNotContainsString( 'videopress-all-playlists__meta', All_Playlists_Block::render( array() ) ); + $this->assertStringContainsString( + 'Updated 2 weeks ago · 1 hr 10 min', + All_Playlists_Block::render( array( 'showUpdated' => true ) ) + ); + + // Without a post or a known length there is nothing to say. + $this->assertSame( + '', + All_Playlists_Block::updated_meta( + array( + 'post' => null, + 'videos' => array( array( 'guid' => 'abcDEF12' ) ), + ) + ) + ); + } + /** * Numbered pagination renders one page of cards plus the page links, and * follows the page query argument. diff --git a/projects/packages/videopress/tests/php/Channel_Blocks_Test.php b/projects/packages/videopress/tests/php/Channel_Blocks_Test.php new file mode 100644 index 000000000000..e042897a7aea --- /dev/null +++ b/projects/packages/videopress/tests/php/Channel_Blocks_Test.php @@ -0,0 +1,213 @@ + + */ + private $videos = array(); + + /** + * Three videos and one playlist holding the last two, on a channel site. + */ + protected function set_up() { + require_once __DIR__ . '/../../src/utility-functions.php'; + add_filter( 'videopress_channel_enabled', '__return_true' ); + Channel::register(); + \WP_Block_Supports::$block_to_render = array( + 'blockName' => 'videopress/channel-details', + 'attrs' => array(), + ); + + foreach ( array( + 'aaaaaaa1' => 'Northshire', + 'bbbbbbb2' => 'Goldshire', + 'ccccccc3' => 'Deadmines', + ) as $guid => $title ) { + $id = wp_insert_post( + array( + 'post_type' => 'attachment', + 'post_status' => 'inherit', + 'post_mime_type' => Channel::MIME_TYPE, + 'post_title' => $title, + ) + ); + update_post_meta( $id, 'videopress_guid', $guid ); + set_transient( 'videopress_get_post_id_by_guid_' . $guid, $id, HOUR_IN_SECONDS ); + set_transient( + 'jetpack_videopress_' . $guid, + (object) array( + 'guid' => $guid, + 'title' => $title . ' episode', + 'description' => 'About ' . $title . '.', + 'poster' => 'https://videos.files.wordpress.com/' . $guid . '/poster.jpg', + ), + HOUR_IN_SECONDS + ); + $this->videos[ $guid ] = $id; + } + + $records = array(); + foreach ( array_reverse( $this->videos, true ) as $guid => $id ) { + $records[] = array( + 'id' => $id, + 'guid' => $guid, + 'durationMs' => 600000, + 'height' => 1080, + 'publishedAt' => time() - $id, + ); + } + add_filter( + 'videopress_channel_videos', + function () use ( $records ) { + return $records; + } + ); + add_filter( + 'videopress_channel_video_views', + function () { + return array( $this->videos['ccccccc3'] => 1500 ); + } + ); + + $source = wp_insert_post( + array( + 'post_title' => 'Dungeons', + 'post_status' => 'publish', + ) + ); + update_option( + 'videopress_playlist_index', + array( + 'dungeons' => array( + 'title' => 'Classic dungeons', + 'description' => 'Full clears.', + 'videos' => array( + array( + 'guid' => 'bbbbbbb2', + 'durationMs' => 600000, + ), + array( + 'guid' => 'ccccccc3', + 'durationMs' => 600000, + ), + ), + 'post_id' => $source, + ), + ) + ); + } + + /** + * Reset globals. + */ + protected function tear_down() { + \WP_Block_Supports::$block_to_render = null; + unset( $GLOBALS['post'] ); + Channel_Data::reset(); + } + + /** + * The playlist source and the editor data are only wired up where the Video Playlist block is. + */ + public function test_register_requires_the_playlist_block() { + Channel_Blocks::register(); + $this->assertFalse( has_action( 'enqueue_block_editor_assets', array( Channel_Blocks::class, 'enqueue_editor_data' ) ) ); + $this->assertFalse( has_filter( 'render_block_data', array( Channel::class, 'playlist_source_block' ) ) ); + + register_block_type( 'videopress/playlist', array() ); + Channel_Blocks::register(); + $this->assertSame( 10, has_action( 'enqueue_block_editor_assets', array( Channel_Blocks::class, 'enqueue_editor_data' ) ) ); + $this->assertSame( 10, has_filter( 'render_block_data', array( Channel::class, 'playlist_source_block' ) ) ); + + // Without an editor script there is nothing to attach the data to. + wp_set_current_user( + wp_insert_user( + array( + 'user_login' => 'channel-author', + 'user_pass' => 'password', + 'role' => 'author', + ) + ) + ); + Channel_Blocks::enqueue_editor_data(); + $this->assertStringNotContainsString( 'videopressChannelEditor', wp_json_encode( wp_scripts()->registered, JSON_UNESCAPED_SLASHES ) ); + unregister_block_type( 'videopress/playlist' ); + } + + /** + * A Video Playlist block showing a playlist from the site renders that playlist's videos on any + * theme, not only a channel theme. + */ + public function test_source_playlist_renders_without_a_channel_theme() { + // Undo what set_up() hooked as a channel site. + remove_all_filters( 'videopress_channel_enabled' ); + remove_filter( 'render_block_data', array( Channel::class, 'playlist_source_block' ) ); + $this->assertFalse( Channel::is_enabled() ); + register_block_type( + 'videopress/playlist', + array( + 'render_callback' => function ( $attributes ) { + return implode( ',', array_column( $attributes['videos'] ?? array(), 'guid' ) ); + }, + ) + ); + Channel_Blocks::register(); + + $this->assertSame( 'bbbbbbb2,ccccccc3', do_blocks( '' ) ); + $this->assertSame( 'bbbbbbb2,ccccccc3', do_blocks( '' ) ); + $this->assertSame( 'aaaaaaa1', do_blocks( '' ) ); + unregister_block_type( 'videopress/playlist' ); + } + + /** + * The editor gets the playlists ( key, title and videos ) for the pickers and the canvas + * previews, before the playlist block's script. + */ + public function test_editor_data_lists_the_playlists() { + wp_register_script( 'videopress-playlist-editor-test', 'https://example.org/editor.js', array(), '1', true ); + register_block_type( 'videopress/playlist', array( 'editor_script_handles' => array( 'videopress-playlist-editor-test' ) ) ); + + Channel_Blocks::enqueue_editor_data(); + $this->assertFalse( wp_scripts()->get_data( 'videopress-playlist-editor-test', 'before' ), 'Only for people who can edit posts.' ); + + wp_set_current_user( + wp_insert_user( + array( + 'user_login' => 'channel-editor', + 'user_pass' => 'password', + 'role' => 'editor', + ) + ) + ); + Channel_Blocks::enqueue_editor_data(); + $this->assertContains( + 'window.videopressChannelEditor = {"playlists":[{"key":"dungeons","title":"Classic dungeons","videos":[{"guid":"bbbbbbb2","durationMs":600000,"height":0},{"guid":"ccccccc3","durationMs":600000,"height":0}]}]};', + (array) wp_scripts()->get_data( 'videopress-playlist-editor-test', 'before' ) + ); + } +} diff --git a/projects/packages/videopress/tests/php/Channel_Test.php b/projects/packages/videopress/tests/php/Channel_Test.php index f6b35302348f..3c0b26fb3245 100644 --- a/projects/packages/videopress/tests/php/Channel_Test.php +++ b/projects/packages/videopress/tests/php/Channel_Test.php @@ -40,6 +40,66 @@ protected function tear_down() { remove_filter( 'videopress_channel_enabled', '__return_true' ); $_GET = array(); unset( $GLOBALS['post'] ); + delete_option( 'videopress_playlist_index' ); + } + + /** + * Index two playlists held by published posts, the second updated last. + * + * @return array{mc: int, road: int} Source post IDs. + */ + private function index_playlists() { + $mc = wp_insert_post( + array( + 'post_title' => 'Molten Core', + 'post_status' => 'publish', + 'post_modified_gmt' => '2026-01-01 00:00:00', + ) + ); + $road = wp_insert_post( + array( + 'post_type' => 'page', + 'post_title' => 'Road', + 'post_status' => 'publish', + 'post_modified_gmt' => '2026-02-01 00:00:00', + ) + ); + update_option( + 'videopress_playlist_index', + array( + 'mc' => array( + 'title' => 'Molten Core progression', + 'description' => 'Attunement to Ragnaros.', + 'videos' => array( + array( + 'guid' => 'abcDEF12', + 'durationMs' => 1000, + ), + array( 'guid' => 'ghiJKL34' ), + ), + 'post_id' => $mc, + ), + 'road' => array( + 'title' => 'The road to 60', + 'description' => '', + 'videos' => array( array( 'guid' => 'ghiJKL34' ) ), + 'post_id' => $road, + ), + ) + ); + // wp_insert_post() stamps the modified date itself. + foreach ( array( + $mc => '2026-01-01 00:00:00', + $road => '2026-02-01 00:00:00', + ) as $id => $date ) { + $post = get_post( $id ); + $post->post_modified_gmt = $date; + wp_cache_replace( $id, $post, 'posts' ); + } + return array( + 'mc' => $mc, + 'road' => $road, + ); } /** @@ -235,4 +295,96 @@ public function test_queried_video_block() { ); $this->assertSame( '', $none['attrs']['guid'] ); } + + /** + * A playlist block with a `source` shows an indexed playlist ( the most + * recently updated by default ). + */ + public function test_playlist_source_block() { + $this->index_playlists(); + $block = function ( $attrs ) { + return Channel::playlist_source_block( + array( + 'blockName' => 'videopress/playlist', + 'attrs' => $attrs, + ) + )['attrs']; + }; + + $own = array( + 'videos' => array( array( 'guid' => 'zzzzzzzz' ) ), + ); + $this->assertSame( $own, $block( $own ) ); + + $latest = $block( array( 'source' => 'index' ) ); + $this->assertSame( 'The road to 60', $latest['playlistTitle'] ); + + $picked = $block( + array( + 'source' => 'index', + 'sourcePlaylistId' => 'mc', + ) + ); + $this->assertSame( array( 'abcDEF12', 'ghiJKL34' ), array_column( $picked['videos'], 'guid' ) ); + $this->assertSame( 'Attunement to Ragnaros.', $picked['playlistDescription'] ); + + // A playlist that is gone shows nothing; other blocks are left alone. + $missing = $block( + array( + 'source' => 'index', + 'sourcePlaylistId' => 'nope', + 'videos' => array( array( 'guid' => 'zzzzzzzz' ) ), + ) + ); + $this->assertSame( array(), $missing['videos'] ); + $paragraph = array( + 'blockName' => 'core/paragraph', + 'attrs' => array( 'source' => 'index' ), + ); + $this->assertSame( $paragraph, Channel::playlist_source_block( $paragraph ) ); + } + + /** + * Playlist records: only published playlists are listed, and lookups of + * unknown keys or sources come back empty. + */ + public function test_playlist_records() { + $posts = $this->index_playlists(); + $draft = wp_insert_post( + array( + 'post_title' => 'Draft', + 'post_status' => 'draft', + ) + ); + + $index = get_option( 'videopress_playlist_index' ); + $index['draft'] = array( + 'title' => 'Not yet', + 'post_id' => $draft, + ); + $index['broken'] = 'nope'; + update_option( 'videopress_playlist_index', $index ); + + $this->assertSame( array( 'road', 'mc' ), array_column( Channel::playlists(), 'key' ) ); + $this->assertSame( + array( + 'key' => 'draft', + 'title' => 'Not yet', + 'description' => '', + 'videos' => array(), + 'post_id' => $draft, + ), + Channel::playlist_record( 'draft' ) + ); + $mc = Channel::playlist_record( 'mc' ); + $this->assertNotNull( $mc ); + $this->assertSame( $posts['mc'], $mc['post_id'] ); + $this->assertNull( Channel::playlist_record( '' ) ); + $this->assertNull( Channel::playlist_record( 'broken' ) ); + $this->assertNull( Channel::source_playlist( 'own', 'mc' ) ); + $this->assertNull( Channel::source_playlist( 'index', 'nope' ) ); + + delete_option( 'videopress_playlist_index' ); + $this->assertNull( Channel::source_playlist( 'index' ) ); + } } diff --git a/projects/packages/videopress/tests/php/Playlist_Index_Test.php b/projects/packages/videopress/tests/php/Playlist_Index_Test.php index 122beebbdfee..37805b24f3d6 100644 --- a/projects/packages/videopress/tests/php/Playlist_Index_Test.php +++ b/projects/packages/videopress/tests/php/Playlist_Index_Test.php @@ -168,14 +168,20 @@ public function test_extract_records_falls_back_to_positional_keys() { } /** - * A Latest Videos Playlist block, and the Video Playlist block it wraps as - * its canvas, are not independent playlists and stay out of the index. + * A Latest Videos Playlist block, the Video Playlist block it wraps as its + * canvas, and a playlist block showing another playlist stay out of the index. */ public function test_extract_records_skips_dynamic_playlists() { $post = $this->create_post( '' . $this->playlist_block( array( 'playlistId' => 'inner' ) ) . '' . + $this->playlist_block( + array( + 'playlistId' => 'queue', + 'source' => 'index', + ) + ) . $this->playlist_block( array( 'playlistId' => 'standalone', diff --git a/projects/plugins/jetpack/changelog/update-videopress-playlist-blocks-for-channels b/projects/plugins/jetpack/changelog/update-videopress-playlist-blocks-for-channels new file mode 100644 index 000000000000..c12693908de0 --- /dev/null +++ b/projects/plugins/jetpack/changelog/update-videopress-playlist-blocks-for-channels @@ -0,0 +1,4 @@ +Significance: minor +Type: enhancement + +VideoPress: Let the Video Playlist block show a playlist published on the site, and let the All Playlists block sort by last update and show each playlist's last update and length. diff --git a/projects/plugins/jetpack/extensions/extended-blocks/videopress-video/videopress-video.php b/projects/plugins/jetpack/extensions/extended-blocks/videopress-video/videopress-video.php index f29c09ff6f63..a0900c67787d 100644 --- a/projects/plugins/jetpack/extensions/extended-blocks/videopress-video/videopress-video.php +++ b/projects/plugins/jetpack/extensions/extended-blocks/videopress-video/videopress-video.php @@ -8,6 +8,7 @@ namespace Automattic\Jetpack\Extensions\VideoPress_Video; use Automattic\Jetpack\VideoPress\Channel as VideoPress_Pkg_Channel; +use Automattic\Jetpack\VideoPress\Channel_Blocks as VideoPress_Pkg_Channel_Blocks; use Automattic\Jetpack\VideoPress\Initializer as VideoPress_Pkg_Initializer; if ( ! defined( 'ABSPATH' ) ) { @@ -56,6 +57,11 @@ function register_videopress_blocks( $playlist_metadata_file = null, $latest_vid if ( method_exists( 'Automattic\Jetpack\VideoPress\Initializer', 'register_videopress_all_playlists_block' ) ) { VideoPress_Pkg_Initializer::register_videopress_all_playlists_block(); } + + // The channel blocks' shared pieces ( the playlist block's `source`, the editor data its picker reads ) also need the playlist block. + if ( method_exists( 'Automattic\Jetpack\VideoPress\Channel_Blocks', 'register' ) ) { + VideoPress_Pkg_Channel_Blocks::register(); + } } // Ignore the empty argument supplied by do_action( 'init' ) so metadata uses the package default. add_action( 'init', __NAMESPACE__ . '\register_videopress_blocks', 10, 0 ); diff --git a/projects/plugins/videopress/changelog/update-videopress-playlist-blocks-for-channels b/projects/plugins/videopress/changelog/update-videopress-playlist-blocks-for-channels new file mode 100644 index 000000000000..3ec664cf0782 --- /dev/null +++ b/projects/plugins/videopress/changelog/update-videopress-playlist-blocks-for-channels @@ -0,0 +1,4 @@ +Significance: minor +Type: added + +Let the Video Playlist block show a playlist published on the site, and let the All Playlists block sort by last update and show each playlist's last update and length.