import { __ } from "@wordpress/i18n"; import { InspectorControls } from "@wordpress/block-editor"; import { useState } from "@wordpress/element"; import { FocalPointPicker, PanelBody, SelectControl, Button, Modal, TextControl, } from "@wordpress/components"; export default function focusPointsControl({ focusPoints, coverUrl, setAttributes, }) { const [isModalOpen, setIsModalOpen] = useState(false); const focusPointsDefaultValue = { titre: "pas de titre", x: 0.5, y: 0.5, }; const [selectedOptionIndex, setSelectedOptionIndex] = useState(null); const [currentEditedFocusPoint, setCurrentEditedFocusPoint] = useState( focusPointsDefaultValue, ); let [isAdding, setIsAdding] = useState(true); let [isEditing, setIsEditing] = useState(false); function buildOptions() { // HANDLE OPTIONS const focusPointsOptions = focusPoints.map((point, arrayIndex) => { return { label: `#${point.titre}`, value: arrayIndex, }; }); focusPointsOptions.unshift({ label: "Nouveau point", value: "addpoint", selected: true, // disabled: true, }); return focusPointsOptions; } function handleChangeOption(selectedValue) { setIsEditing(false); setIsAdding(false); if (selectedValue === "addpoint") { setIsAdding(true); setIsEditing(false); return; } if (selectedValue !== null && selectedValue !== "") { setIsEditing(true); setSelectedOptionIndex(selectedValue); setCurrentEditedFocusPoint(focusPoints[selectedValue]); return; } } function createFocusPoint() { const newFocusPoints = [...focusPoints]; newFocusPoints.push(currentEditedFocusPoint); setAttributes({ focusPoints: newFocusPoints }); setCurrentEditedFocusPoint(focusPointsDefaultValue); } function editFocusPoint() { setIsModalOpen(!isModalOpen); setCurrentEditedFocusPoint(focusPoints[selectedOptionIndex]); } function updateFocusPoint() { const newFocusPoints = [...focusPoints]; newFocusPoints[selectedOptionIndex] = currentEditedFocusPoint; setAttributes({ focusPoints: newFocusPoints }); setCurrentEditedFocusPoint(focusPointsDefaultValue); setIsEditing(false); } function deleteFocusPoint() { const newFocusPoints = [...focusPoints]; newFocusPoints.splice(selectedOptionIndex, 1); setAttributes({ focusPoints: newFocusPoints }); setIsEditing(false); } const focusPointsOptions = buildOptions(); return ( {coverUrl && ( <> { handleChangeOption(selectValue); }} /> {isAdding && ( )} {isEditing && ( <> )} {/* Popover */} {isModalOpen && ( setIsModalOpen(false)} > { setCurrentEditedFocusPoint({ ...currentEditedFocusPoint, titre: value, }); }} /> { setCurrentEditedFocusPoint({ ...currentEditedFocusPoint, x: focalPoint.x, y: focalPoint.y, }); }} /> {isAdding && ( )} {isEditing && ( <> )} )} )} ); }