-
Notifications
You must be signed in to change notification settings - Fork 43
/
index.tsx
76 lines (60 loc) · 2.18 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { Children } from '@wordpress/element';
import { store as coreStore } from '@wordpress/core-data';
import { Spinner } from '@wordpress/components';
import { useSelect } from '@wordpress/data';
import { usePost } from '../../hooks';
import { Name, FirstName, LastName, Avatar, Bio, Email } from '../author';
import { AuthorContext } from '../author/context';
import type { Author } from '../author/context';
interface PostAuthorProps {
children?: React.ReactNode | ((author: Author) => React.ReactNode);
[key: string]: unknown;
}
export const PostAuthor: React.FC<PostAuthorProps> & {
Name: typeof Name;
FirstName: typeof FirstName;
LastName: typeof LastName;
Avatar: typeof Avatar;
Bio: typeof Bio;
Email: typeof Email;
} = (props) => {
const { children, ...rest } = props;
const { postId, postType } = usePost();
const [author, hasResolved] = useSelect(
(select) => {
// @ts-ignore-next-line - The type definitions for the core store are incomplete.
const { getEditedEntityRecord, getUser, hasFinishedResolution } = select(coreStore);
const postQuery = ['postType', postType, postId as number] as const;
const post = getEditedEntityRecord(...postQuery);
const hasResolvedPost = hasFinishedResolution('getEditedEntityRecord', postQuery);
// @ts-ignore-next-line - The type definitions for the core store are incomplete.
const _authorId = hasResolvedPost ? post?.author : undefined;
const author = getUser(_authorId);
const hasResolvedAuthor = hasFinishedResolution('getUser', [_authorId]);
return [author, hasResolvedAuthor && hasResolvedPost];
},
[postType, postId],
);
const hasRenderCallback = typeof children === 'function';
const hasChildComponents = !hasRenderCallback && Children.count(children);
if (!hasResolved) {
return <Spinner />;
}
if (hasChildComponents) {
return (
<AuthorContext.Provider value={author}>
<div {...rest}>{children}</div>
</AuthorContext.Provider>
);
}
if (hasRenderCallback) {
return children(author);
}
return <Name {...rest} />;
};
PostAuthor.Name = Name;
PostAuthor.FirstName = FirstName;
PostAuthor.LastName = LastName;
PostAuthor.Avatar = Avatar;
PostAuthor.Bio = Bio;
PostAuthor.Email = Email;