UNPKG

@wordpress/block-editor

Version:
104 lines (91 loc) 2.67 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = useSaveImage; var _apiFetch = _interopRequireDefault(require("@wordpress/api-fetch")); var _data = require("@wordpress/data"); var _element = require("@wordpress/element"); var _i18n = require("@wordpress/i18n"); var _notices = require("@wordpress/notices"); var _dom = require("@wordpress/dom"); /** * WordPress dependencies */ // Disable Reason: Needs to be refactored. // eslint-disable-next-line no-restricted-imports function useSaveImage({ crop, rotation, height, width, aspect, url, id, onSaveImage, onFinishEditing }) { const { createErrorNotice } = (0, _data.useDispatch)(_notices.store); const [isInProgress, setIsInProgress] = (0, _element.useState)(false); const cancel = (0, _element.useCallback)(() => { setIsInProgress(false); onFinishEditing(); }, [setIsInProgress, onFinishEditing]); const apply = (0, _element.useCallback)(() => { setIsInProgress(true); const modifiers = []; if (rotation > 0) { modifiers.push({ type: 'rotate', args: { angle: rotation } }); } // The crop script may return some very small, sub-pixel values when the image was not cropped. // Crop only when the new size has changed by more than 0.1%. if (crop.width < 99.9 || crop.height < 99.9) { modifiers.push({ type: 'crop', args: { left: crop.x, top: crop.y, width: crop.width, height: crop.height } }); } (0, _apiFetch.default)({ path: `/wp/v2/media/${id}/edit`, method: 'POST', data: { src: url, modifiers } }).then(response => { onSaveImage({ id: response.id, url: response.source_url, height: height && width ? width / aspect : undefined }); }).catch(error => { createErrorNotice((0, _i18n.sprintf)( /* translators: 1. Error message */ (0, _i18n.__)('Could not edit image. %s'), (0, _dom.__unstableStripHTML)(error.message)), { id: 'image-editing-error', type: 'snackbar' }); }).finally(() => { setIsInProgress(false); onFinishEditing(); }); }, [setIsInProgress, crop, rotation, height, width, aspect, url, onSaveImage, createErrorNotice, setIsInProgress, onFinishEditing]); return (0, _element.useMemo)(() => ({ isInProgress, apply, cancel }), [isInProgress, apply, cancel]); } //# sourceMappingURL=use-save-image.js.map