@wordpress/block-editor
Version:
115 lines (112 loc) • 3.21 kB
JavaScript
;
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
const messages = {
crop: (0, _i18n.__)('Image cropped.'),
rotate: (0, _i18n.__)('Image rotated.'),
cropAndRotate: (0, _i18n.__)('Image cropped and rotated.')
};
function useSaveImage({
crop,
rotation,
url,
id,
onSaveImage,
onFinishEditing
}) {
const {
createErrorNotice,
createSuccessNotice
} = (0, _data.useDispatch)(_notices.store);
const [isInProgress, setIsInProgress] = (0, _element.useState)(false);
const cancel = (0, _element.useCallback)(() => {
setIsInProgress(false);
onFinishEditing();
}, [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
}
});
}
if (modifiers.length === 0) {
// No changes to apply.
setIsInProgress(false);
onFinishEditing();
return;
}
const modifierType = modifiers.length === 1 ? modifiers[0].type : 'cropAndRotate';
(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
});
createSuccessNotice(messages[modifierType], {
type: 'snackbar',
actions: [{
label: (0, _i18n.__)('Undo'),
onClick: () => {
onSaveImage({
id,
url
});
}
}]
});
}).catch(error => {
createErrorNotice((0, _i18n.sprintf)(/* translators: %s: Error message. */
(0, _i18n.__)('Could not edit image. %s'), (0, _dom.__unstableStripHTML)(error.message)), {
id: 'image-editing-error',
type: 'snackbar'
});
}).finally(() => {
setIsInProgress(false);
onFinishEditing();
});
}, [crop, rotation, id, url, onSaveImage, createErrorNotice, createSuccessNotice, onFinishEditing]);
return (0, _element.useMemo)(() => ({
isInProgress,
apply,
cancel
}), [isInProgress, apply, cancel]);
}
//# sourceMappingURL=use-save-image.js.map