Skip to content

Commit

Permalink
[Mobile] Fix crash when appending media (Android) (#56791)
Browse files Browse the repository at this point in the history
* Mobile - Fix subscribeMediaAppend to skip adding unsupported types of files, it currently supports images and video only

* Mock requestMediaImport

* Mobile - Edit Post tests - Remove old unsupported block test and adds tests for subscribeMediaAppend

* Update Changelog
  • Loading branch information
Gerardo Pacheco authored Dec 11, 2023
1 parent d1b2abf commit c0b18b0
Show file tree
Hide file tree
Showing 5 changed files with 139 additions and 68 deletions.
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', () => {
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(
__( '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 packages/react-native-editor/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ For each user feature we should also add a importance categorization label to i
- [*] [internal] Move InserterButton from components package to block-editor package [#56494]
- [*] [internal] Move ImageLinkDestinationsScreen from components package to block-editor package [#56775]
- [*] Guard against an Image block styles crash due to null block values [#56903]
- [**] Fix crash when sharing unsupported media types on Android [#56791]

## 1.109.2
- [**] Fix issue related to text color format and receiving in rare cases an undefined ref from `RichText` component [#56686]
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

1 comment on commit c0b18b0

@github-actions
Copy link

Choose a reason for hiding this comment

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

Flaky tests detected in c0b18b0.
Some tests passed with failed attempts. The failures may not be related to this commit but are still reported for visibility. See the documentation for more information.

🔍 Workflow run URL: https://github.com/WordPress/gutenberg/actions/runs/7169395074
📝 Reported issues:

Please sign in to comment.