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

Add a File field, like for .pdf uploads #74

Merged
merged 18 commits into from
Jul 20, 2021
Merged
Show file tree
Hide file tree
Changes from 5 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
121 changes: 121 additions & 0 deletions js/src/block-editor/controls/file.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
/**
kienstra marked this conversation as resolved.
Show resolved Hide resolved
* External dependencies
*/
import * as React from 'react';

/**
* WordPress dependencies
*/
import { MediaUpload } from '@wordpress/block-editor';
import {
BaseControl,
Button,
Placeholder,
DropZone,
DropZoneProvider,
FormFileUpload,
Spinner,
} from '@wordpress/components';
import { __ } from '@wordpress/i18n';

/**
* Internal dependencies
*/
import { useMedia } from '../hooks';

const allowedTypes = [ 'application' ];
const defaultImgId = 0;

const GcbFileControl = ( props ) => {
const { field, getValue, instanceId, onChange } = props;
const fieldValue = getValue( props );
const {
mediaSrc,
isUploading,
onSelect,
removeMedia,
setIsUploading,
uploadFiles,
} = useMedia( fieldValue, onChange, allowedTypes );
const fileRegex = /[^\/]+\.[^\/]+$/;

return (
<BaseControl className="genesis-custom-blocks-media-controls" label={ field.label } id={ `gcb-file-${ instanceId }` }>
{ !! field.help
? <p className="components-base-control__help">{ field.help }</p>
: null
}
{ !! mediaSrc
? (
<>
{ mediaSrc.match( fileRegex )
? mediaSrc.match( fileRegex )[ 0 ]
: null
}
<Button
disabled={ !! isUploading }
className="gcb-image__remove"
onClick={ () => {
onChange( defaultImgId );
removeMedia();
} }
>
{ __( 'Remove', 'genesis-custom-blocks' ) }
</Button>
</>
) : (
<Placeholder className="gcb-image__placeholder" icon="format-image" label={ __( 'Image', 'genesis-custom-blocks' ) } instructions={ __( 'Drag an image, upload a new one or select a file from your library.', 'genesis-custom-blocks' ) }>
<DropZoneProvider>
<DropZone
onFilesDrop={ ( files ) => {
if ( files.length ) {
setIsUploading( true );
uploadFiles( files );
}
} }
/>
</DropZoneProvider>
{ isUploading
? <Spinner />
: (
<>
<FormFileUpload
disabled={ !! isUploading }
onChange={ ( event ) => {
setIsUploading( true );
uploadFiles( event.target.files );
} }
accept="application/*"
multiple={ false }
>
{ __( 'Upload', 'genesis-custom-blocks' ) }
</FormFileUpload>
<MediaUpload
gallery={ false }
multiple={ false }
onSelect={ onSelect }
allowedTypes={ allowedTypes }
value={ getValue( props ) }
render={ ( { open } ) => (
<div className="components-media-library-button">
<Button
disabled={ !! isUploading }
className="editor-media-placeholder__button"
onClick={ open }
>
{ __( 'Media Library', 'genesis-custom-blocks' ) }
</Button>
</div>
) }
/>
</>
)
}
</Placeholder>
)
}
</BaseControl>
);
};

export default GcbFileControl;
14 changes: 7 additions & 7 deletions js/src/block-editor/controls/image.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { __ } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import { useImage } from '../hooks';
import { useMedia } from '../hooks';

const allowedTypes = [ 'image' ];
const defaultImgId = 0;
Expand All @@ -30,25 +30,25 @@ const GcbImageControl = ( props ) => {
const { field, getValue, instanceId, onChange } = props;
const fieldValue = getValue( props );
const {
imageAlt,
imageSrc,
mediaAlt,
mediaSrc,
isUploading,
onSelect,
removeImage,
removeMedia: removeImage,
setIsUploading,
uploadFiles,
} = useImage( fieldValue, onChange, allowedTypes );
} = useMedia( fieldValue, onChange, allowedTypes );

return (
<BaseControl className="genesis-custom-blocks-media-controls" label={ field.label } id={ `gcb-image-${ instanceId }` }>
{ !! field.help
? <p className="components-base-control__help">{ field.help }</p>
: null
}
{ !! imageSrc
{ !! mediaSrc
? (
<>
<img className="gcb-image__img" src={ imageSrc } alt={ imageAlt } />
<img className="gcb-image__img" src={ mediaSrc } alt={ mediaAlt } />
<Button
disabled={ !! isUploading }
className="gcb-image__remove"
Expand Down
2 changes: 2 additions & 0 deletions js/src/block-editor/controls/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import GcbTextControl from './text';
import GcbTextareaControl from './textarea';
import GcbURLControl from './url';
import GcbEmailControl from './email';
import GcbFileControl from './file';
import GcbNumberControl from './number';
import GcbColorControl from './color';
import GcbImageControl from './image';
Expand All @@ -20,6 +21,7 @@ export default {
textarea: GcbTextareaControl,
url: GcbURLControl,
email: GcbEmailControl,
file: GcbFileControl,
number: GcbNumberControl,
color: GcbColorControl,
image: GcbImageControl,
Expand Down
45 changes: 45 additions & 0 deletions js/src/block-editor/controls/test/file.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/**
* External dependencies
*/
import { render } from '@testing-library/react';

/**
* Internal dependencies
*/
import GcbFileControl from '../file';

jest.mock( '@wordpress/api-fetch', () => {
return jest.fn( () => {
return Promise.resolve( {
json: () => Promise.resolve( {} ),
} );
} );
} );

// @todo: remove this when the console warning no longer appears.
// Expected mock function not to be called but it was called with:
// ["wp.components.DropZoneProvider is deprecated. Note: wp.component.DropZone no longer needs a provider. wp.components.DropZoneProvider is safe to remove from your code."]
// Core still has an older components file, so removing the provider now crashes the editor.
console.warn = jest.fn(); /* eslint-disable-line no-console */

/**
* Gets the props for the tested component.
*
* @return {Object} The props to pass to the component.
*/
const getProps = () => ( {
field: {
label: 'Here is a label',
help: 'And here is some text',
},
getValue: jest.fn(),
onChange: jest.fn(),
} );

test( 'file control', () => {
const props = getProps();
const { getByText } = render( <GcbFileControl { ...props } /> );

expect( getByText( props.field.label ) ).toBeInTheDocument();
expect( getByText( props.field.help ) ).toBeInTheDocument();
} );
1 change: 1 addition & 0 deletions js/src/block-editor/helpers/test/addControls.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ test( 'addControls', () => {
checkbox: expect.anything(),
color: expect.anything(),
email: expect.anything(),
file: expect.anything(),
image: expect.anything(),
multiselect: expect.anything(),
number: expect.anything(),
Expand Down
2 changes: 1 addition & 1 deletion js/src/block-editor/hooks/index.js
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export { default as useImage } from './useImage';
export { default as useMedia } from './useMedia';
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,12 @@ import { __, sprintf } from '@wordpress/i18n';
*/

/**
* @typedef {Object} UseImageReturn The return value of the hook.
* @property {string} imageAlt The alt attribute of the <img>.
* @property {string} imageSrc The src attribute of the <img>.
* @property {boolean} isUploading Whether the image is uploading.
* @typedef {Object} UseMediaReturn The return value of the hook.
* @property {string} mediaAlt The alt attribute of the <img>.
* @property {string} mediaSrc The src attribute of the media.
* @property {boolean} isUploading Whether the media is uploading.
* @property {OnSelect} onSelect Handler for selecting.
* @property {RemoveImage} removeImage Removes the image src.
* @property {RemoveImage} removeMedia Removes the media src.
* @property {SetIsUploading} setIsUploading Sets whether the image is uploading.
* @property {UploadFiles} uploadFiles Uploads the files.
*/
Expand All @@ -44,13 +44,13 @@ import { __, sprintf } from '@wordpress/i18n';
* @param {number|string} fieldValue The current field value.
* @param {(imageId: number) => void} onChange Handles changing the field value.
* @param {string[]} allowedTypes The allowed media types.
* @return {UseImageReturn} The return value of this hook.
* @return {UseMediaReturn} The return value of this hook.
*/
const useImage = ( fieldValue, onChange, allowedTypes ) => {
const useMedia = ( fieldValue, onChange, allowedTypes ) => {
const defaultImageSrc = '';
const [ imageSrc, setImageSrc ] = useState( defaultImageSrc );
const [ mediaSrc, setMediaSrc ] = useState( defaultImageSrc );
const [ isUploading, setIsUploading ] = useState( false );
const [ imageAlt, setImageAlt ] = useState( '' );
const [ mediaAlt, setImageAlt ] = useState( '' );

// @ts-ignore: type definition file is missing getMedia().
const { getMedia } = useSelect( ( select ) => {
Expand All @@ -61,10 +61,10 @@ const useImage = ( fieldValue, onChange, allowedTypes ) => {
const newImage = getMedia( fieldValue );

if ( newImage?.source_url ) { // eslint-disable-line camelcase
setImageSrc( newImage.source_url );
setMediaSrc( newImage.source_url );
} else if ( 'string' === typeof newImage ) {
// Backwards-compatibility: the fieldValue used to be the URL, not the ID.
setImageSrc( newImage );
setMediaSrc( newImage );
}

if ( newImage?.alt ) {
Expand All @@ -83,7 +83,7 @@ const useImage = ( fieldValue, onChange, allowedTypes ) => {
const updateImageSrc = ( image ) => {
if ( image?.id ) {
onChange( parseInt( image.id ) );
setImageSrc( image?.url );
setMediaSrc( image?.url );
}
};

Expand All @@ -102,7 +102,7 @@ const useImage = ( fieldValue, onChange, allowedTypes ) => {

/** @type {RemoveImage} */
const removeImage = () => {
setImageSrc( defaultImageSrc );
setMediaSrc( defaultImageSrc );
};

/** @type {UploadFiles} */
Expand All @@ -119,14 +119,14 @@ const useImage = ( fieldValue, onChange, allowedTypes ) => {
};

return {
imageAlt,
imageSrc,
mediaAlt,
mediaSrc,
isUploading,
onSelect,
removeImage,
removeMedia: removeImage,
setIsUploading,
uploadFiles,
};
};

export default useImage;
export default useMedia;
51 changes: 51 additions & 0 deletions php/Blocks/Controls/File.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php
/**
* File control.
*
* @package Genesis\CustomBlocks
* @copyright Copyright(c) 2021, Genesis Custom Blocks
* @license http://opensource.org/licenses/GPL-2.0 GNU General Public License, version 2 (GPL-2.0)
*/

namespace Genesis\CustomBlocks\Blocks\Controls;

/**
* Class File
*/
class File extends ControlAbstract {

/**
* Control name.
*
* @var string
*/
public $name = 'file';

/**
* Field variable type.
*
* @var string
*/
public $type = 'integer';

/**
* Text constructor.
*
* @return void
*/
public function __construct() {
parent::__construct();
$this->label = __( 'File', 'genesis-custom-blocks' );
}

/**
* Register settings.
*
* @return void
*/
public function register_settings() {
foreach ( [ 'location', 'width', 'help' ] as $setting ) {
$this->settings[] = new ControlSetting( $this->settings_config[ $setting ] );
}
}
}
1 change: 1 addition & 0 deletions php/PostTypes/BlockPost.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ public function register_controls() {
'textarea',
'url',
'email',
'file',
'number',
'color',
'image',
Expand Down
Loading