Skip to content

Instantly share code, notes, and snippets.

@espenmn
Last active October 19, 2023 10:52
Show Gist options
  • Select an option

  • Save espenmn/899d09f756f8b90fcf3b701c5b957fae to your computer and use it in GitHub Desktop.

Select an option

Save espenmn/899d09f756f8b90fcf3b701c5b957fae to your computer and use it in GitHub Desktop.
/**
* Retrieves the translation of text.
*
* @see https://developer.wordpress.org/block-editor/reference-guides/packages/packages-i18n/
*/
import { __ } from '@wordpress/i18n';
/**
* React hook that is used to mark the block wrapper element.
* It provides all the necessary props like the class name.
*
* @see https://developer.wordpress.org/block-editor/reference-guides/packages/packages-block-editor/#useblockprops
*/
import { useBlockProps, RichText, InspectorControls } from '@wordpress/block-editor';
import { Panel, PanelBody, PanelRow, ToggleControl, SelectControl } from '@wordpress/components';
import { useState } from 'react';
import { Editor } from '@tinymce/tinymce-react';
import { Button } from '@wordpress/components';
import { MediaUpload, MediaUploadCheck } from '@wordpress/block-editor';
import { select } from '@wordpress/data';
import { useEffect } from "@wordpress/element";
import './editor.scss';
import metadata from './block.json';
export default function Edit( { attributes, setAttributes, isSelected } ) {
const ALLOWED_MEDIA_TYPES = [ 'image' ];
const [mediaOptions, setMediaOptions] = useState([
]);
const setImage = (media) => {
console.log(media);
const sizes = Object.keys(media.sizes);
const options = sizes.map((size) => ({
label: size,
value: size,
}));
setAttributes({mediaUrl: media.url,
mediaSizeUrl: media.sizes.full.url ,
mediaWidth:media.sizes.full.width,
mediaHeight: media.sizes.full.height,
mediaId: media.id,
// mediaSize: 'full',
mediaSizes: options
}) ;
setMediaOptions(media);
// setSize('full'); // Optionally set the size to 'full'
};
return (
<div { ...useBlockProps() }>
<MediaUploadCheck>
<MediaUpload
onSelect={ ( media ) => {
console.log(media);
setImage( media ) ;
// and maybe more
} }
allowedTypes={ ALLOWED_MEDIA_TYPES }
value={ attributes.mediaId }
render={ ( { open } ) => (
<Button variant="primary"
onClick={ open }>Add / Change Image</Button>
) }
/>
</MediaUploadCheck>
{ attributes.mediaId && (
<SelectControl
label="Image Scale"
value={ attributes.mediaSize }
options={ attributes.mediaSizes }
onChange={ ( newsize ) => {
setAttributes({ mediaSizeUrl: mediaOptions.sizes[newsize].url ,
mediaWidth: mediaOptions.sizes[newsize].width,
mediaHeight: mediaOptions.sizes[newsize].height,
mediaSize: newsize }) ;
} }
/>
) }
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment