/
edit.js
101 lines (95 loc) · 2.23 KB
/
edit.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
96
97
98
99
100
101
/**
* WordPress dependencies
*/
import {
InspectorControls,
useBlockProps,
__experimentalGetSpacingClassesAndStyles as useSpacingProps,
} from '@wordpress/block-editor';
import { PanelBody, ResizableBox, RangeControl } from '@wordpress/components';
import { useEntityProp } from '@wordpress/core-data';
import { __, _x, isRTL } from '@wordpress/i18n';
export default function Edit( {
attributes,
context: { commentId },
setAttributes,
} ) {
const { height, width } = attributes;
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 = sizes ? sizes[ 0 ] : 24;
const maxSize = sizes ? sizes[ sizes.length - 1 ] : 96;
const blockProps = useBlockProps();
const spacingProps = useSpacingProps( attributes );
const maxSizeBuffer = Math.floor( maxSize * 2.5 );
const inspectorControls = (
<InspectorControls>
<PanelBody title={ __( 'Avatar Settings' ) }>
<RangeControl
label={ __( 'Image size' ) }
onChange={ ( newWidth ) =>
setAttributes( {
width: newWidth,
height: newWidth,
} )
}
min={ minSize }
max={ maxSizeBuffer }
initialPosition={ width }
value={ width }
/>
</PanelBody>
</InspectorControls>
);
const displayAvatar = avatarUrls ? (
<ResizableBox
size={ {
width,
height,
} }
onResizeStop={ ( event, direction, elt, delta ) => {
setAttributes( {
height: parseInt( height + delta.height, 10 ),
width: parseInt( width + delta.width, 10 ),
} );
} }
lockAspectRatio
enable={ {
top: false,
right: ! isRTL(),
bottom: true,
left: isRTL(),
} }
minWidth={ minSize }
maxWidth={ maxSizeBuffer }
>
<img
src={ avatarUrls[ avatarUrls.length - 1 ] }
alt={ `${ authorName } ${ __( 'Avatar' ) }` }
{ ...blockProps }
/>
</ResizableBox>
) : (
<p { ...blockProps }>
{ _x( 'Comment Author Avatar', 'block title' ) }
</p>
);
return (
<>
{ inspectorControls }
<div { ...spacingProps }>{ displayAvatar }</div>
</>
);
}