Skip to content
Draft
171 changes: 171 additions & 0 deletions src/components/videopress-unsupported/index.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
import clsx from 'clsx';
import { useBlockProps } from '@wordpress/block-editor';
import { parse } from '@wordpress/block-serialization-default-parser';
import { Button, SandBox, Spinner } from '@wordpress/components';
import { store as coreStore } from '@wordpress/core-data';
import { useDispatch, useSelect } from '@wordpress/data';
import { useMemo, useState } from '@wordpress/element';
import { __, _x, sprintf } from '@wordpress/i18n';
import { Icon, info } from '@wordpress/icons';
import './style.scss';

/**
* Placeholder for a `videopress/video` block the editor doesn't allow.
*
* Shows a playable preview of the video and explains that its settings can't
* be edited. The block keeps its original markup.
*
* @param {Object} props Block edit props.
* @param {Object} props.attributes `core/missing` attributes, including the
* block's original markup.
* @param {boolean} props.isSelected Whether the block is selected.
*
* @return {Element} The placeholder.
*/
export default function VideoPressUnsupported( { attributes, isSelected } ) {
const blockProps = useBlockProps( {
className: 'gutenberg-kit-videopress-unsupported',
} );

// Like core embeds, an overlay takes the first tap so it selects the block;
// later taps reach the player until the block is deselected.
const [ isInteractive, setIsInteractive ] = useState( false );
if ( ! isSelected && isInteractive ) {
setIsInteractive( false );
}

const guid = useMemo(
() => getGuid( attributes.originalContent ),
[ attributes.originalContent ]
);
const url = guid ? `https://videopress.com/v/${ guid }` : undefined;

// Core-data fetches `/oembed/1.0/proxy` and caches the result, so moving
// the block or remounting it doesn't fetch again. A failed fetch is `false`
// and stays cached until invalidated, so failures offer a retry.
const { preview, isLoading } = useSelect(
( select ) => {
if ( ! url ) {
return { preview: false, isLoading: false };
}
const { getEmbedPreview, isResolving } = select( coreStore );
const result = getEmbedPreview( url );
return {
preview: result,
isLoading:
result === undefined ||
isResolving( 'getEmbedPreview', [ url ] ),
};
},
[ url ]
);
const { invalidateResolution } = useDispatch( coreStore );

return (
<figure { ...blockProps }>
{ preview?.html ? (
// Like core embeds, size the preview by the video's aspect ratio
// rather than its content height, which can exceed the player.
<div
className="gutenberg-kit-videopress-unsupported__preview"
style={ { aspectRatio: getAspectRatio( preview ) } }
>
<SandBox
allowSameOrigin
html={ preview.html }
scripts={ preview.scripts }
title={ sprintf(
// translators: %s: host providing embed content e.g: www.youtube.com
__( 'Embedded content from %s' ),
'videopress.com'
) }
type="wp-has-aspect-ratio"
onFocus={ () => setIsInteractive( true ) }
/>
{ ! isInteractive && (
// Pointer-only, as in core embeds: keyboard users focus
// the player directly, which also removes the overlay.
// eslint-disable-next-line jsx-a11y/no-static-element-interactions
<div
className="gutenberg-kit-videopress-unsupported__overlay"
onMouseUp={ () => setIsInteractive( true ) }
/>
) }
</div>
) : (
<div
className={ clsx(
'gutenberg-kit-videopress-unsupported__placeholder',
{ 'is-error': ! isLoading }
) }
>
{ isLoading ? (
<Spinner />
) : (
<>
{ /* Core embed strings, so existing translations apply. */ }
<p>
{ __(
'Sorry, this content could not be embedded.'
) }
</p>
{ url && (
<Button
__next40pxDefaultSize
variant="secondary"
onClick={ () =>
invalidateResolution(
'getEmbedPreview',
[ url ]
)
}
>
{ _x( 'Try again', 'button label' ) }
</Button>
) }
</>
) }
</div>
) }
<figcaption className="gutenberg-kit-videopress-unsupported__notice">
<Icon icon={ info } size={ 20 } />
<span>
{ __(
'Editing VideoPress settings is not yet supported in the app. To make changes, edit the post on the web.',
'gutenberg-kit'
) }
</span>
</figcaption>
</figure>
);
}

/**
* Reads the VideoPress guid from the block's original markup.
*
* @param {string} [originalContent] The block's original markup.
*
* @return {string|undefined} The guid, if valid.
*/
function getGuid( originalContent ) {
const [ block ] = parse( originalContent ?? '' );
const guid = block?.attrs?.guid;

// Guids are alphanumeric; anything else would alter the embed URL.
return typeof guid === 'string' && /^[a-z0-9]+$/i.test( guid )
? guid
: undefined;
}

/**
* Returns the CSS aspect ratio of an oEmbed preview.
*
* @param {Object} preview oEmbed response.
* @param {number} preview.width Embed width.
* @param {number} preview.height Embed height.
*
* @return {string} The aspect ratio, 16:9 when the size is unknown.
*/
function getAspectRatio( { width, height } ) {
return width > 0 && height > 0 ? `${ width } / ${ height }` : '16 / 9';
}
205 changes: 205 additions & 0 deletions src/components/videopress-unsupported/index.test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
import { useDispatch, useSelect } from '@wordpress/data';
import VideoPressUnsupported from '.';

vi.mock( '@wordpress/block-editor', () => ( {
useBlockProps: ( props ) => props,
} ) );

vi.mock( '@wordpress/components', () => ( {
Button: ( { children, onClick } ) => (
<button onClick={ onClick }>{ children }</button>
),
SandBox: ( { html } ) => <div data-testid="sandbox">{ html }</div>,
Spinner: () => <div data-testid="spinner" />,
} ) );

vi.mock( '@wordpress/core-data', () => ( { store: 'core' } ) );

vi.mock( '@wordpress/data', () => ( {
useDispatch: vi.fn(),
useSelect: vi.fn(),
} ) );

const ORIGINAL_CONTENT =
'<!-- wp:videopress/video {"guid":"AbC123xy","isPrivate":true} /-->';

describe( 'VideoPressUnsupported', () => {
let getEmbedPreview;
let isResolving;
let invalidateResolution;

beforeEach( () => {
getEmbedPreview = vi.fn();
isResolving = vi.fn().mockReturnValue( false );
invalidateResolution = vi.fn();
useSelect.mockImplementation( ( callback ) =>
callback( () => ( { getEmbedPreview, isResolving } ) )
);
useDispatch.mockReturnValue( { invalidateResolution } );
} );

it( "requests the preview for the block's guid", () => {
renderPlaceholder();

expect( getEmbedPreview ).toHaveBeenCalledWith(
'https://videopress.com/v/AbC123xy'
);
} );

it( 'shows a spinner while the preview loads', () => {
getEmbedPreview.mockReturnValue( undefined );

renderPlaceholder();

expect( screen.getByTestId( 'spinner' ) ).toBeInTheDocument();
expect( screen.queryByTestId( 'sandbox' ) ).not.toBeInTheDocument();
} );

it( 'renders the preview once loaded', () => {
getEmbedPreview.mockReturnValue( { html: '<iframe></iframe>' } );

renderPlaceholder();

expect( screen.getByTestId( 'sandbox' ) ).toHaveTextContent(
'<iframe></iframe>'
);
expect( screen.queryByTestId( 'spinner' ) ).not.toBeInTheDocument();
} );

it.each( [
[
"the video's aspect ratio",
{ width: 600, height: 338 },
'600 / 338',
],
[ '16:9 without a size', {}, '16 / 9' ],
] )( 'sizes the preview by %s', ( _, size, expected ) => {
getEmbedPreview.mockReturnValue( {
html: '<iframe></iframe>',
...size,
} );

renderPlaceholder();

expect(
screen.getByTestId( 'sandbox' ).parentElement.style.aspectRatio
).toBe( expected );
} );

it( 'explains a failed preview and offers a retry', () => {
getEmbedPreview.mockReturnValue( false );

renderPlaceholder();

expect( screen.queryByTestId( 'spinner' ) ).not.toBeInTheDocument();
expect( screen.queryByTestId( 'sandbox' ) ).not.toBeInTheDocument();
expect(
screen.getByText( 'Sorry, this content could not be embedded.' )
).toBeInTheDocument();

fireEvent.click( screen.getByRole( 'button', { name: 'Try again' } ) );

expect( invalidateResolution ).toHaveBeenCalledWith(
'getEmbedPreview',
[ 'https://videopress.com/v/AbC123xy' ]
);
} );

it( 'shows a spinner while retrying a failed preview', () => {
getEmbedPreview.mockReturnValue( false );
isResolving.mockReturnValue( true );

renderPlaceholder();

expect( screen.getByTestId( 'spinner' ) ).toBeInTheDocument();
expect(
screen.queryByRole( 'button', { name: 'Try again' } )
).not.toBeInTheDocument();
} );

it.each( [
[ 'no guid', '<!-- wp:videopress/video {"id":1} /-->' ],
[
'an invalid guid',
'<!-- wp:videopress/video {"guid":"a/../b"} /-->',
],
[ 'no markup', null ],
] )( 'skips the preview request for %s', ( _, originalContent ) => {
renderPlaceholder( originalContent );

expect( getEmbedPreview ).not.toHaveBeenCalled();
expect( screen.queryByTestId( 'spinner' ) ).not.toBeInTheDocument();
expect(
screen.getByText( 'Sorry, this content could not be embedded.' )
).toBeInTheDocument();
// Without a guid there is nothing to fetch, so a retry can't help.
expect(
screen.queryByRole( 'button', { name: 'Try again' } )
).not.toBeInTheDocument();
} );

it( 'captions the video to explain that its settings are not editable', () => {
renderPlaceholder();

expect(
screen.getByRole( 'figure' ).querySelector( 'figcaption' )
).toHaveTextContent(
'Editing VideoPress settings is not yet supported in the app.'
);
} );

describe( 'playback', () => {
beforeEach( () => {
getEmbedPreview.mockReturnValue( { html: '<iframe></iframe>' } );
} );

it( 'covers the player until the block is tapped', () => {
const { container } = renderPlaceholder();

expect( getOverlay( container ) ).toBeInTheDocument();
} );

it( 'uncovers the player after the tap that selects the block', () => {
const { container, rerender } = renderPlaceholder();

rerender( placeholder( ORIGINAL_CONTENT, true ) );
fireEvent.mouseUp( getOverlay( container ) );

expect( getOverlay( container ) ).not.toBeInTheDocument();
} );

it( 'covers the player again once the block is deselected', () => {
const { container, rerender } = renderPlaceholder();
rerender( placeholder( ORIGINAL_CONTENT, true ) );
fireEvent.mouseUp( getOverlay( container ) );

rerender( placeholder( ORIGINAL_CONTENT, false ) );

expect( getOverlay( container ) ).toBeInTheDocument();
} );
} );
} );

function renderPlaceholder( originalContent = ORIGINAL_CONTENT ) {
return render( placeholder( originalContent, false ) );
}

function placeholder( originalContent, isSelected ) {
return (
<VideoPressUnsupported
attributes={ {
originalName: 'videopress/video',
originalContent,
} }
isSelected={ isSelected }
/>
);
}

function getOverlay( container ) {
return container.querySelector(
'.gutenberg-kit-videopress-unsupported__overlay'
);
}
Loading
Loading