UNPKG

@wordpress/block-library

Version:
86 lines (73 loc) 2.51 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = PostCommentsCountEdit; var _element = require("@wordpress/element"); var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _classnames = _interopRequireDefault(require("classnames")); var _blockEditor = require("@wordpress/block-editor"); var _apiFetch = _interopRequireDefault(require("@wordpress/api-fetch")); var _url = require("@wordpress/url"); var _i18n = require("@wordpress/i18n"); /** * External dependencies */ /** * WordPress dependencies */ function PostCommentsCountEdit(_ref) { var _blockProps$style; let { attributes, context, setAttributes } = _ref; const { textAlign } = attributes; const { postId } = context; const [commentsCount, setCommentsCount] = (0, _element.useState)(); const blockProps = (0, _blockEditor.useBlockProps)({ className: (0, _classnames.default)({ [`has-text-align-${textAlign}`]: textAlign }) }); (0, _element.useEffect)(() => { if (!postId) { return; } const currentPostId = postId; (0, _apiFetch.default)({ path: (0, _url.addQueryArgs)('/wp/v2/comments', { post: postId }), parse: false }).then(res => { // Stale requests will have the `currentPostId` of an older closure. if (currentPostId === postId) { setCommentsCount(res.headers.get('X-WP-Total')); } }); }, [postId]); const hasPostAndComments = postId && commentsCount !== undefined; const blockStyles = { ...blockProps.style, textDecoration: hasPostAndComments ? (_blockProps$style = blockProps.style) === null || _blockProps$style === void 0 ? void 0 : _blockProps$style.textDecoration : undefined }; return (0, _element.createElement)(_element.Fragment, null, (0, _element.createElement)(_blockEditor.BlockControls, { group: "block" }, (0, _element.createElement)(_blockEditor.AlignmentControl, { value: textAlign, onChange: nextAlign => { setAttributes({ textAlign: nextAlign }); } })), (0, _element.createElement)("div", (0, _extends2.default)({}, blockProps, { style: blockStyles }), hasPostAndComments ? commentsCount : (0, _element.createElement)(_blockEditor.Warning, null, (0, _i18n.__)('Post Comments Count block: post not found.')))); } //# sourceMappingURL=edit.js.map