Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Mobile] Fix crash when appending media (Android) #56791

Merged
merged 5 commits into from
Dec 11, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions packages/edit-post/src/test/__snapshots__/editor.native.js.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Editor appends media correctly for allowed types 1`] = `
"<!-- wp:image -->
<figure class="wp-block-image"><img src="https://test-site.files.wordpress.com/local-image-1.jpeg" alt=""/></figure>
<!-- /wp:image -->

<!-- wp:image -->
<figure class="wp-block-image"><img src="https://test-site.files.wordpress.com/local-image-3.jpeg" alt=""/></figure>
<!-- /wp:image -->"
`;

exports[`Editor appends media correctly for allowed types and skips unsupported ones 1`] = `
"<!-- wp:image -->
<figure class="wp-block-image"><img src="https://test-site.files.wordpress.com/local-image-1.jpeg" alt=""/></figure>
<!-- /wp:image -->

<!-- wp:video -->
<figure class="wp-block-video"><video controls src="file:///local-video-4.mp4"></video></figure>
<!-- /wp:video -->"
`;
146 changes: 90 additions & 56 deletions packages/edit-post/src/test/editor.native.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,93 +6,127 @@ import {
addBlock,
fireEvent,
getBlock,
getEditorHtml,
initializeEditor,
render,
screen,
setupCoreBlocks,
} from 'test/helpers';

/**
* WordPress dependencies
*/
import RNReactNativeGutenbergBridge, {
import {
requestMediaImport,
subscribeMediaAppend,
subscribeParentToggleHTMLMode,
} from '@wordpress/react-native-bridge';
// Force register 'core/editor' store.
import { store } from '@wordpress/editor'; // eslint-disable-line no-unused-vars

/**
* Internal dependencies
*/
import '..';
import Editor from '../editor';

const unsupportedBlock = `
<!-- wp:notablock -->
<p>Not supported</p>
<!-- /wp:notablock -->
`;
setupCoreBlocks();

beforeAll( () => {
jest.useFakeTimers( { legacyFakeTimers: true } );
let toggleModeCallback;
subscribeParentToggleHTMLMode.mockImplementation( ( callback ) => {
toggleModeCallback = callback;
} );

afterAll( () => {
jest.runOnlyPendingTimers();
jest.useRealTimers();
let mediaAppendCallback;
subscribeMediaAppend.mockImplementation( ( callback ) => {
mediaAppendCallback = callback;
} );

setupCoreBlocks();
const MEDIA = [
{
localId: 1,
mediaUrl: 'file:///local-image-1.jpeg',
mediaType: 'image',
serverId: 2000,
serverUrl: 'https://test-site.files.wordpress.com/local-image-1.jpeg',
},
{
localId: 2,
mediaUrl: 'file:///local-file-1.pdf',
mediaType: 'other',
serverId: 2001,
serverUrl: 'https://test-site.files.wordpress.com/local-file-1.pdf',
},
{
localId: 3,
mediaUrl: 'file:///local-image-3.jpeg',
mediaType: 'image',
serverId: 2002,
serverUrl: 'https://test-site.files.wordpress.com/local-image-3.jpeg',
},
{
localId: 4,
mediaUrl: 'file:///local-video-4.mp4',
mediaType: 'video',
serverId: 2003,
serverUrl: 'https://test-site.files.wordpress.com/local-video-4.mp4',
},
];

describe( 'Editor', () => {
it( 'detects unsupported block and sends hasUnsupportedBlocks true to native', () => {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've removed this test because we have others that cover the Unsupported blocks functionality

RNReactNativeGutenbergBridge.editorDidMount = jest.fn();

const appContainer = renderEditorWith( unsupportedBlock );
// For some reason resetEditorBlocks() is asynchronous when dispatching editEntityRecord.
act( () => {
jest.runAllTicks();
} );
appContainer.unmount();

expect(
RNReactNativeGutenbergBridge.editorDidMount
).toHaveBeenCalledTimes( 1 );
expect(
RNReactNativeGutenbergBridge.editorDidMount
).toHaveBeenCalledWith( [ 'core/notablock' ] );
afterEach( () => {
jest.clearAllMocks();
} );

it( 'toggles the editor from Visual to HTML mode', async () => {
// Arrange
let toggleMode;
subscribeParentToggleHTMLMode.mockImplementation( ( callback ) => {
toggleMode = callback;
} );
const screen = await initializeEditor();
await initializeEditor();
await addBlock( screen, 'Paragraph' );

// Act
const paragraphBlock = getBlock( screen, 'Paragraph' );
fireEvent.press( paragraphBlock );
act( () => {
toggleMode();
toggleModeCallback();
} );

// Assert
const htmlEditor = screen.getByLabelText( 'html-view-content' );
expect( htmlEditor ).toBeVisible();

act( () => {
toggleModeCallback();
} );
} );
} );

// Utilities.
const renderEditorWith = ( content ) => {
return render(
<Editor
initialHtml={ content }
initialHtmlModeEnabled={ false }
initialTitle={ '' }
postType="post"
postId="1"
/>
);
};
it( 'appends media correctly for allowed types', async () => {
// Arrange
requestMediaImport
.mockImplementationOnce( ( _, callback ) =>
callback( MEDIA[ 0 ].id, MEDIA[ 0 ].serverUrl )
)
.mockImplementationOnce( ( _, callback ) =>
callback( MEDIA[ 2 ].id, MEDIA[ 2 ].serverUrl )
);
await initializeEditor();

// Act
await act( () => mediaAppendCallback( MEDIA[ 0 ] ) );
await act( () => mediaAppendCallback( MEDIA[ 2 ] ) );

// Assert
expect( getEditorHtml() ).toMatchSnapshot();
} );

it( 'appends media correctly for allowed types and skips unsupported ones', async () => {
// Arrange
requestMediaImport
.mockImplementationOnce( ( _, callback ) =>
callback( MEDIA[ 0 ].id, MEDIA[ 0 ].serverUrl )
)
.mockImplementationOnce( ( _, callback ) =>
callback( MEDIA[ 3 ].id, MEDIA[ 3 ].serverUrl )
);
await initializeEditor();

// Act
await act( () => mediaAppendCallback( MEDIA[ 0 ] ) );
// Unsupported type (PDF file)
await act( () => mediaAppendCallback( MEDIA[ 1 ] ) );
await act( () => mediaAppendCallback( MEDIA[ 3 ] ) );

// Assert
expect( getEditorHtml() ).toMatchSnapshot();
} );
} );
38 changes: 26 additions & 12 deletions packages/editor/src/components/provider/index.native.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
parse,
serialize,
getUnregisteredTypeHandlerName,
getBlockType,
createBlock,
} from '@wordpress/blocks';
import { withDispatch, withSelect } from '@wordpress/data';
Expand All @@ -35,6 +36,7 @@ import { applyFilters } from '@wordpress/hooks';
import { store as blockEditorStore } from '@wordpress/block-editor';
import { getGlobalStyles, getColorsAndGradients } from '@wordpress/components';
import { NEW_BLOCK_TYPES } from '@wordpress/block-library';
import { __ } from '@wordpress/i18n';

const postTypeEntities = [
{ name: 'post', baseURL: '/wp/v2/posts' },
Expand Down Expand Up @@ -94,6 +96,7 @@ class NativeEditorProvider extends Component {
componentDidMount() {
const {
capabilities,
createErrorNotice,
locale,
hostAppNamespace,
updateEditorSettings,
Expand Down Expand Up @@ -136,17 +139,26 @@ class NativeEditorProvider extends Component {
this.subscriptionParentMediaAppend = subscribeMediaAppend(
( payload ) => {
const blockName = 'core/' + payload.mediaType;
const newBlock = createBlock( blockName, {
id: payload.mediaId,
[ payload.mediaType === 'image' ? 'url' : 'src' ]:
payload.mediaUrl,
} );

const indexAfterSelected = this.props.selectedBlockIndex + 1;
const insertionIndex =
indexAfterSelected || this.props.blockCount;

this.props.insertBlock( newBlock, insertionIndex );
const blockType = getBlockType( blockName );

if ( blockType && blockType?.name ) {
const newBlock = createBlock( blockType.name, {
id: payload.mediaId,
[ payload.mediaType === 'image' ? 'url' : 'src' ]:
payload.mediaUrl,
} );

const indexAfterSelected =
this.props.selectedBlockIndex + 1;
const insertionIndex =
indexAfterSelected || this.props.blockCount;

this.props.insertBlock( newBlock, insertionIndex );
} else {
createErrorNotice(
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will serve as a fallback, a few changes were done in wordpress-mobile/WordPress-Android#19754 to prevent passing unsupported files when sharing files to the editor.

__( 'File type not supported as a media file.' )
);
}
}
);

Expand Down Expand Up @@ -389,14 +401,16 @@ const ComposedNativeProvider = compose( [
dispatch( blockEditorStore );
const { switchEditorMode } = dispatch( editPostStore );
const { addEntities, receiveEntityRecords } = dispatch( coreStore );
const { createSuccessNotice } = dispatch( noticesStore );
const { createSuccessNotice, createErrorNotice } =
dispatch( noticesStore );

return {
updateBlockEditorSettings: updateSettings,
updateEditorSettings,
addEntities,
insertBlock,
createSuccessNotice,
createErrorNotice,
editTitle( title ) {
editPost( { title } );
},
Expand Down
1 change: 1 addition & 0 deletions test/native/setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ jest.mock( '@wordpress/react-native-bridge', () => {
requestImageUploadCancelDialog: jest.fn(),
requestMediaEditor: jest.fn(),
requestMediaPicker: jest.fn(),
requestMediaImport: jest.fn(),
requestUnsupportedBlockFallback: jest.fn(),
subscribeReplaceBlock: jest.fn(),
mediaSources: {
Expand Down
Loading