@wordpress/block-library
Version:
Block library for the WordPress editor.
72 lines (68 loc) • 2.13 kB
JavaScript
import _extends from "@babel/runtime/helpers/esm/extends";
import { createElement, Fragment } from "@wordpress/element";
/**
* External dependencies
*/
import classnames from 'classnames';
/**
* WordPress dependencies
*/
import { AlignmentControl, BlockControls, Warning, useBlockProps } from '@wordpress/block-editor';
import { useState, useEffect } from '@wordpress/element';
import apiFetch from '@wordpress/api-fetch';
import { addQueryArgs } from '@wordpress/url';
import { __ } from '@wordpress/i18n';
export default function PostCommentsCountEdit(_ref) {
var _blockProps$style;
let {
attributes,
context,
setAttributes
} = _ref;
const {
textAlign
} = attributes;
const {
postId
} = context;
const [commentsCount, setCommentsCount] = useState();
const blockProps = useBlockProps({
className: classnames({
[`has-text-align-${textAlign}`]: textAlign
})
});
useEffect(() => {
if (!postId) {
return;
}
const currentPostId = postId;
apiFetch({
path: 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 createElement(Fragment, null, createElement(BlockControls, {
group: "block"
}, createElement(AlignmentControl, {
value: textAlign,
onChange: nextAlign => {
setAttributes({
textAlign: nextAlign
});
}
})), createElement("div", _extends({}, blockProps, {
style: blockStyles
}), hasPostAndComments ? commentsCount : createElement(Warning, null, __('Post Comments Count block: post not found.'))));
}
//# sourceMappingURL=edit.js.map