-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathindex.js
106 lines (93 loc) · 2.48 KB
/
index.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
102
103
104
105
106
/**
* Internal dependencies
*/
import './style.scss';
import { registerBlock, query } from 'api';
import Editable from 'components/editable';
const { attr, children } = query;
/**
* Returns an attribute setter with behavior that if the target value is
* already the assigned attribute value, it will be set to undefined.
*
* @param {string} align Alignment value
* @return {Function} Attribute setter
*/
function applyOrUnset( align ) {
return ( attributes, setAttributes ) => {
const nextAlign = attributes.align === align ? undefined : align;
setAttributes( { align: nextAlign } );
};
}
registerBlock( 'core/image', {
title: wp.i18n.__( 'Image' ),
icon: 'format-image',
category: 'common',
attributes: {
url: attr( 'img', 'src' ),
alt: attr( 'img', 'alt' ),
caption: children( 'figcaption' ),
align: ( node ) => ( node.className.match( /\balign(\S+)/ ) || [] )[ 1 ]
},
controls: [
{
icon: 'align-left',
title: wp.i18n.__( 'Align left' ),
isActive: ( { align } ) => 'left' === align,
onClick: applyOrUnset( 'left' )
},
{
icon: 'align-center',
title: wp.i18n.__( 'Align center' ),
isActive: ( { align } ) => 'center' === align,
onClick: applyOrUnset( 'center' )
},
{
icon: 'align-right',
title: wp.i18n.__( 'Align right' ),
isActive: ( { align } ) => 'right' === align,
onClick: applyOrUnset( 'right' )
},
{
icon: 'align-none',
title: wp.i18n.__( 'No alignment' ),
isActive: ( { align } ) => ! align || 'none' === align,
onClick: applyOrUnset( 'none' )
}
],
getEditWrapperProps( attributes ) {
const { align } = attributes;
if ( 'left' === align || 'right' === align ) {
return { 'data-align': align };
}
},
edit( { attributes, setAttributes, focus, setFocus } ) {
const { url, alt, caption } = attributes;
return (
<figure className="blocks-image">
<img src={ url } alt={ alt } />
{ caption || !! focus ? (
<Editable
tagName="figcaption"
placeholder={ wp.i18n.__( 'Write caption…' ) }
value={ caption }
focus={ focus }
onFocus={ setFocus }
onChange={ ( value ) => setAttributes( { caption: value } ) } />
) : null }
</figure>
);
},
save( { attributes } ) {
const { url, alt, caption, align = 'none' } = attributes;
const img = <img src={ url } alt={ alt } className={ `align${ align }` } />;
if ( ! caption ) {
return img;
}
return (
<figure>
{ img }
<figcaption>{ caption }</figcaption>
</figure>
);
}
} );