-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
hooks.js
95 lines (89 loc) · 2.49 KB
/
hooks.js
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/**
* WordPress dependencies
*/
import { store as blockEditorStore } from '@wordpress/block-editor';
import { store as coreStore, useEntityProp } from '@wordpress/core-data';
import { __, sprintf } from '@wordpress/i18n';
import { useSelect } from '@wordpress/data';
function getAvatarSizes( sizes ) {
const minSize = sizes ? sizes[ 0 ] : 24;
const maxSize = sizes ? sizes[ sizes.length - 1 ] : 96;
const maxSizeBuffer = Math.floor( maxSize * 2.5 );
return {
minSize,
maxSize: maxSizeBuffer,
};
}
function useDefaultAvatar() {
const { avatarURL: defaultAvatarUrl } = useSelect( ( select ) => {
const { getSettings } = select( blockEditorStore );
const { __experimentalDiscussionSettings } = getSettings();
return __experimentalDiscussionSettings;
} );
return defaultAvatarUrl;
}
export function useCommentAvatar( { commentId } ) {
const [ avatars ] = useEntityProp(
'root',
'comment',
'author_avatar_urls',
commentId
);
const [ authorName ] = useEntityProp(
'root',
'comment',
'author_name',
commentId
);
const avatarUrls = avatars ? Object.values( avatars ) : null;
const sizes = avatars ? Object.keys( avatars ) : null;
const { minSize, maxSize } = getAvatarSizes( sizes );
const defaultAvatar = useDefaultAvatar();
return {
src: avatarUrls ? avatarUrls[ avatarUrls.length - 1 ] : defaultAvatar,
minSize,
maxSize,
alt: authorName
? // translators: %s: Author name.
sprintf( __( '%s Avatar' ), authorName )
: __( 'Default Avatar' ),
};
}
export function useUserAvatar( { userId, postId, postType } ) {
const { authorDetails } = useSelect(
( select ) => {
const { getEditedEntityRecord, getUser } = select( coreStore );
if ( userId ) {
return {
authorDetails: getUser( userId ),
};
}
const _authorId = getEditedEntityRecord(
'postType',
postType,
postId
)?.author;
return {
authorDetails: _authorId ? getUser( _authorId ) : null,
};
},
[ postType, postId, userId ]
);
const avatarUrls = authorDetails?.avatar_urls
? Object.values( authorDetails.avatar_urls )
: null;
const sizes = authorDetails?.avatar_urls
? Object.keys( authorDetails.avatar_urls )
: null;
const { minSize, maxSize } = getAvatarSizes( sizes );
const defaultAvatar = useDefaultAvatar();
return {
src: avatarUrls ? avatarUrls[ avatarUrls.length - 1 ] : defaultAvatar,
minSize,
maxSize,
alt: authorDetails
? // translators: %s: Author name.
sprintf( __( '%s Avatar' ), authorDetails?.name )
: __( 'Default Avatar' ),
};
}