homegrade_blocks_production/blocks/labelled-picture/src/edit.js
2023-11-24 14:17:16 +01:00

127 lines
2.9 KiB
JavaScript

import { __ } from "@wordpress/i18n";
import "./editor.scss";
import {
useBlockProps,
MediaPlaceholder,
BlockControls,
InspectorControls,
MediaReplaceFlow,
} from "@wordpress/block-editor";
import {
Button,
ToolbarGroup,
ToolbarButton,
Spinner,
withNotices,
FocalPointPicker,
PanelBody,
Tip,
ToggleControl,
__experimentalToggleGroupControl as ToggleGroupControl,
__experimentalToggleGroupControlOption as ToggleGroupControlOption,
} from "@wordpress/components";
import { trash } from "@wordpress/icons";
export default function Edit({
attributes,
setAttributes,
noticeOperations,
noticeList,
noticeUI,
}) {
const { pictureUrl, pictureAlt, pictureId, pictureCaption } = attributes;
function removePictureImg() {
setAttributes({
pictureUrl: undefined,
pictureId: undefined,
pictureCaption: undefined,
pictureAlt: "",
});
}
function updatePictureImg(image) {
if (!image || !image.url) {
removePictureImg();
}
setAttributes({
pictureUrl: image.url,
pictureId: image.id,
pictureAlt: image.alt,
pictureCaption: image.caption,
});
}
function onUploadError(message) {
noticeOperations.removeAllNotices();
noticeOperations.createErrorNotice(message);
}
return (
<>
<InspectorControls>
<PanelBody
title="Source de l'image"
className="homegrade-blocks-components-image__panel-body "
>
{pictureUrl && <img src={pictureUrl} alt={pictureAlt} />}
<div className="media-replace-container">
<MediaReplaceFlow
mediaId={pictureId}
mediaUrl={pictureUrl}
allowedTypes={["image"]}
accept="image/*"
onSelect={updatePictureImg}
name={
!pictureUrl
? __("Ajouter", "homegrade-blocks__texte-backoffice")
: __("Remplacer", "homegrade-blocks__texte-backoffice")
}
/>
{pictureUrl && (
<div>
<Button
className="custom-flow-button"
variant="primary"
icon={trash}
label="Supprimer"
onClick={removePictureImg}
/>
</div>
)}
</div>
<Tip>
<p>
Le texte de votre Légende est automatiquement attribué depuis le
champ "Légende" de votre image dans la gallerie des médias
</p>
</Tip>
</PanelBody>
</InspectorControls>
<div>
{pictureUrl && (
<figure
{...useBlockProps({
className: `homegrade-blocks-labelled-picture`,
})}
>
<img src={pictureUrl} alt={pictureAlt} />
<figcaption>{pictureCaption}</figcaption>
</figure>
)}
{!pictureUrl && (
<MediaPlaceholder
disableMediaButtons={pictureUrl}
icon="admin-appearance"
onSelect={updatePictureImg}
accept="image/*" // On upload Allow only images
allowedTypes={["image"]} // Onlibrary Allow only images
notices={noticeUI} // En cas d'erreur d'upload
onError={onUploadError}
/>
)}
</div>
</>
);
}