Skip to content

Commit

Permalink
Editor: Move media upload from utils
Browse files Browse the repository at this point in the history
  • Loading branch information
aduth committed Jul 18, 2018
1 parent 362fa23 commit cc763bf
Show file tree
Hide file tree
Showing 7 changed files with 66 additions and 45 deletions.
3 changes: 3 additions & 0 deletions docs/reference/deprecated.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ Gutenberg's deprecation policy is intended to support backwards-compatibility fo
- `wp.utils.decodeEntities` has been removed. Please use `wp.htmlEntities.decodeEntities` instead.
- All references to a block's `uid` have been replaced with equivalent props and selectors for `clientId`.
- The `MediaPlaceholder` component `onSelectUrl` prop has been renamed to `onSelectURL`.
- `wp.utils.getMimeTypesArray` has been removed.
- `wp.utils.mediaUpload` has been removed. Please use `wp.editor.editorMediaUpload` instead.
- `wp.utils.preloadImage` has been removed.

## 3.4.0

Expand Down
6 changes: 6 additions & 0 deletions editor/store/defaults.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,10 @@ export const EDITOR_SETTINGS_DEFAULTS = {

// Allowed block types for the editor, defaulting to true (all supported).
allowedBlockTypes: true,

// Maximum upload size in bytes allowed for the site.
maxUploadFileSize: 0,

// List of allowed mime types and file extensions.
allowedMimeTypes: null,
};
17 changes: 13 additions & 4 deletions editor/utils/editor-media-upload/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,18 @@ import { noop } from 'lodash';
* WordPress dependencies
*/
import { select } from '@wordpress/data';
import { mediaUpload } from '@wordpress/utils';

/**
* Internal dependencies
*/
import { mediaUpload } from './media-upload';

/**
* Upload a media file when the file upload button is activated.
* Wrapper around mediaUpload() that injects the current post ID.
*
* @param {Object} $0 Parameters object passed to the function.
* @param {string} $0.allowedType The type of media that can be uploaded, or '*' to allow all.
* @param {?Object} $0.additionalData Additional data to include in the request.
* @param {Array} $0.filesList List of files.
* @param {?number} $0.maxUploadFileSize Maximum upload size in bytes allowed for the site.
* @param {Function} $0.onError Function called when an error happens.
Expand All @@ -28,16 +31,22 @@ export default function editorMediaUpload( {
onError = noop,
onFileChange,
} ) {
const postId = select( 'core/editor' ).getCurrentPostId();
const {
getCurrentPostId,
getEditorSettings,
} = select( 'core/editor' );
const allowedMimeTypes = getEditorSettings().allowedMimeTypes;
maxUploadFileSize = maxUploadFileSize || getEditorSettings().maxUploadFileSize;

mediaUpload( {
allowedType,
filesList,
onFileChange,
additionalData: {
post: postId,
post: getCurrentPostId(),
},
maxUploadFileSize,
onError: ( { message } ) => onError( message ),
allowedMimeTypes,
} );
}
53 changes: 24 additions & 29 deletions editor/utils/editor-media-upload/media-upload.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,7 @@ import { compact, flatMap, forEach, get, has, includes, map, noop, startsWith }
* WordPress dependencies
*/
import { __, sprintf } from '@wordpress/i18n';

/**
* WordPress dependencies
*/
import apiRequest from '@wordpress/api-request';
import apiFetch from '@wordpress/api-fetch';

/**
* Browsers may use unexpected mime types, and they differ from browser to browser.
Expand All @@ -38,26 +34,28 @@ export function getMimeTypesArray( wpMimeTypesObject ) {
}

/**
* Media Upload is used by audio, image, gallery, video, and file blocks to
* handle uploading a media file when a file upload button is activated.
* Media Upload is used by audio, image, gallery, video, and file blocks to
* handle uploading a media file when a file upload button is activated.
*
* TODO: future enhancement to add an upload indicator.
* TODO: future enhancement to add an upload indicator.
*
* @param {Object} $0 Parameters object passed to the function.
* @param {string} $0.allowedType The type of media that can be uploaded, or '*' to allow all.
* @param {?Object} $0.additionalData Additional data to include in the request.
* @param {Array} $0.filesList List of files.
* @param {?number} $0.maxUploadFileSize Maximum upload size in bytes allowed for the site.
* @param {Function} $0.onError Function called when an error happens.
* @param {Function} $0.onFileChange Function called each time a file or a temporary representation of the file is available.
* @param {Object} $0 Parameters object passed to the function.
* @param {string} $0.allowedType The type of media that can be uploaded, or '*' to allow all.
* @param {?Object} $0.additionalData Additional data to include in the request.
* @param {Array} $0.filesList List of files.
* @param {?number} $0.maxUploadFileSize Maximum upload size in bytes allowed for the site.
* @param {Function} $0.onError Function called when an error happens.
* @param {Function} $0.onFileChange Function called each time a file or a temporary representation of the file is available.
* @param {?Object} $0.allowedMimeTypes List of allowed mime types and file extensions.
*/
export function mediaUpload( {
allowedType,
additionalData = {},
filesList,
maxUploadFileSize = get( window, [ '_wpMediaSettings', 'maxUploadSize' ], 0 ),
maxUploadFileSize,
onError = noop,
onFileChange,
allowedMimeTypes = null,
} ) {
// Cast filesList to array
const files = [ ...filesList ];
Expand All @@ -74,7 +72,7 @@ export function mediaUpload( {
};

// Allowed types for the current WP_User
const allowedMimeTypesForUser = getMimeTypesArray( get( window, [ '_wpMediaSettings', 'allowedMimeTypes' ] ) );
const allowedMimeTypesForUser = getMimeTypesArray( allowedMimeTypes );
const isAllowedMimeTypeForUser = ( fileType ) => {
return includes( allowedMimeTypesForUser, fileType );
};
Expand Down Expand Up @@ -113,8 +111,8 @@ export function mediaUpload( {
filesSet.push( { url: window.URL.createObjectURL( mediaFile ) } );
onFileChange( filesSet );

return createMediaFromFile( mediaFile, additionalData ).then(
( savedMedia ) => {
return createMediaFromFile( mediaFile, additionalData )
.then( ( savedMedia ) => {
const mediaObject = {
alt: savedMedia.alt_text,
caption: get( savedMedia, [ 'caption', 'raw' ], '' ),
Expand All @@ -128,13 +126,13 @@ export function mediaUpload( {
mediaObject.mediaDetails.sizes = get( savedMedia, [ 'media_details', 'sizes' ], {} );
}
setAndUpdateFiles( idx, mediaObject );
},
( response ) => {
} )
.catch( ( error ) => {
// Reset to empty on failure.
setAndUpdateFiles( idx, null );
let message;
if ( has( response, [ 'responseJSON', 'message' ] ) ) {
message = get( response, [ 'responseJSON', 'message' ] );
if ( has( error, [ 'message' ] ) ) {
message = get( error, [ 'message' ] );
} else {
message = sprintf(
// translators: %s: file name
Expand All @@ -147,8 +145,7 @@ export function mediaUpload( {
message,
file: mediaFile,
} );
}
);
} );
} );
}

Expand All @@ -163,11 +160,9 @@ function createMediaFromFile( file, additionalData ) {
const data = new window.FormData();
data.append( 'file', file, file.name || file.type.replace( '/', '.' ) );
forEach( additionalData, ( ( value, key ) => data.append( key, value ) ) );
return apiRequest( {
return apiFetch( {
path: '/wp/v2/media',
data,
contentType: false,
processData: false,
body: data,
method: 'POST',
} );
}
7 changes: 4 additions & 3 deletions editor/utils/editor-media-upload/test/media-upload.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ describe( 'mediaUpload', () => {

it( 'should call error handler with the correct error object if file size is greater than the maximum', () => {
const onError = jest.fn();

mediaUpload( {
allowedType: 'image',
filesList: [ validMediaObj ],
Expand All @@ -46,14 +47,14 @@ describe( 'mediaUpload', () => {

it( 'should call error handler with the correct error object if file type is not allowed for user', () => {
const onError = jest.fn();
global._wpMediaSettings = {
allowedMimeTypes: { aac: 'audio/aac' },
};
const allowedMimeTypes = { aac: 'audio/aac' };

mediaUpload( {
allowedType: 'image',
filesList: [ validMediaObj ],
onFileChange: onFileChangeSpy,
onError,
allowedMimeTypes,
} );
expect( onError ).toBeCalledWith( {
code: 'MIME_TYPE_NOT_ALLOWED_FOR_USER',
Expand Down
14 changes: 11 additions & 3 deletions lib/client-assets.php
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,15 @@ function gutenberg_register_scripts_and_styles() {
wp_register_script(
'wp-utils',
gutenberg_url( 'build/utils/index.js' ),
array( 'lodash', 'wp-api-fetch', 'wp-deprecated', 'wp-html-entities', 'wp-i18n', 'wp-keycodes' ),
array(
'lodash',
'wp-api-fetch',
'wp-deprecated',
'wp-html-entities',
'wp-i18n',
'wp-keycodes',
'wp-editor',
),
filemtime( gutenberg_dir_path() . 'build/utils/index.js' ),
true
);
Expand Down Expand Up @@ -430,7 +438,6 @@ function gutenberg_register_scripts_and_styles() {
'wp-keycodes',
'wp-element',
'wp-plugins',
'wp-utils',
'wp-viewport',
'wp-tinymce',
'tinymce-latest-lists',
Expand Down Expand Up @@ -1065,6 +1072,7 @@ function gutenberg_editor_scripts_and_styles( $hook ) {
// https://github.com/WordPress/gutenberg/issues/5667.
add_filter( 'user_can_richedit', '__return_true' );

wp_enqueue_script( 'wp-utils' );
wp_enqueue_script( 'wp-edit-post' );

global $post;
Expand Down Expand Up @@ -1226,7 +1234,7 @@ function gutenberg_editor_scripts_and_styles( $hook ) {
'bodyPlaceholder' => apply_filters( 'write_your_story', __( 'Write your story', 'gutenberg' ), $post ),
'isRTL' => is_rtl(),
'autosaveInterval' => 10,
'maxUploadSize' => $max_upload_size,
'maxUploadFileSize' => $max_upload_size,
'allowedMimeTypes' => get_allowed_mime_types(),
);

Expand Down
11 changes: 5 additions & 6 deletions utils/mediaupload.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,7 @@ import { compact, flatMap, forEach, get, has, includes, map, noop, startsWith }
*/
import deprecated from '@wordpress/deprecated';
import { __, sprintf } from '@wordpress/i18n';

/**
* WordPress dependencies
*/
import { select } from '@wordpress/data';
import apiFetch from '@wordpress/api-fetch';

/**
Expand All @@ -32,6 +29,7 @@ export function getMimeTypesArray( wpMimeTypesObject ) {
version: '3.5',
plugin: 'Gutenberg',
} );

if ( ! wpMimeTypesObject ) {
return wpMimeTypesObject;
}
Expand Down Expand Up @@ -70,7 +68,8 @@ export function mediaUpload( {
plugin: 'Gutenberg',
} );

maxUploadFileSize = maxUploadFileSize || get( window, [ '_wpMediaSettings', 'maxUploadSize' ], 0 );
const editorSettings = select( 'core/editor' ).getSettings();
maxUploadFileSize = maxUploadFileSize || editorSettings.maxUploadFileSize;

// Cast filesList to array
const files = [ ...filesList ];
Expand All @@ -87,7 +86,7 @@ export function mediaUpload( {
};

// Allowed types for the current WP_User
const allowedMimeTypesForUser = getMimeTypesArray( get( window, [ '_wpMediaSettings', 'allowedMimeTypes' ] ) );
const allowedMimeTypesForUser = getMimeTypesArray( editorSettings.allowedMimeTypes );
const isAllowedMimeTypeForUser = ( fileType ) => {
return includes( allowedMimeTypesForUser, fileType );
};
Expand Down

0 comments on commit cc763bf

Please sign in to comment.