-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
91 lines (76 loc) · 2 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
/**
* Multiple post selector for Gutenberg components
* [email protected] since 27.8.2019
*
* Usage:
<PostCheckboxes
post_type="sht_custom_post_type"
attributes={this.props.attributes}
setAttributes={this.props.setAttributes}
emptyText={ _x('No posts available', 'Post checkbox component warning', 'sha') }
/>
*/
const { CheckboxControl } = wp.components;
const { withState } = wp.compose;
const { select, withSelect } = wp.data;
const { Component, Fragment } = wp.element;
const { _x } = wp.i18n;
class PostCheckboxes extends Component {
constructor(props) {
super(...arguments);
this.props = props;
}
render() {
const { attributes, checkboxes, setAttributes, emptyText } = this.props;
const { posts } = attributes;
let empty_text = emptyText;
if(!empty_text){
empty_text = _x('No posts available', 'Post checkbox component warning', 'sha');
}
return (
<Fragment>
{
!checkboxes && empty_text &&
<p>{ empty_text }</p>
}
{
checkboxes && checkboxes.map(checkbox => {
return (
<CheckboxControl
label={checkbox.label}
checked={posts.indexOf(checkbox.value) !== -1} // checks if the checkbox key is in the posts array
onChange={isChecked => {
if (isChecked) {
// add checkbox key to posts array
setAttributes({ posts: posts.concat(checkbox.value) });
} else {
// remove checkbox key from posts array
setAttributes({ posts: posts.filter(item => item !== checkbox.value) });
}
}}
/>
)
})
}
</Fragment>
);
}
}
export default withSelect( ( select, props ) => {
const { getEntityRecords } = select( 'core' );
let posts = getEntityRecords( 'postType', props.post_type, {
per_page: -1,
orderby: 'title',
order: 'asc'
} );
if ( !posts ) {
return posts;
}
let checkboxes = [];
posts.map( post => {
checkboxes.push( { value: post.id, label: post.title.raw } );
} );
return {
checkboxes: checkboxes
};
} )( PostCheckboxes );