This repository has been archived by the owner on Aug 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 67
/
block.js
364 lines (331 loc) · 9.32 KB
/
block.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
/**
* External dependencies
*/
import { __, sprintf } from '@wordpress/i18n';
import { speak } from '@wordpress/a11y';
import {
useCollection,
useQueryStateByKey,
useQueryStateByContext,
useCollectionData,
useShallowEqual,
} from '@woocommerce/base-hooks';
import {
useCallback,
Fragment,
useEffect,
useState,
useMemo,
} from '@wordpress/element';
import CheckboxList from '@woocommerce/base-components/checkbox-list';
import DropdownSelector from '@woocommerce/base-components/dropdown-selector';
import FilterSubmitButton from '@woocommerce/base-components/filter-submit-button';
import isShallowEqual from '@wordpress/is-shallow-equal';
import { decodeEntities } from '@wordpress/html-entities';
/**
* Internal dependencies
*/
import { getAttributeFromID } from '../../utils/attributes';
import { updateAttributeFilter } from '../../utils/attributes-query';
import Label from './label';
import { previewAttributeObject, previewOptions } from './preview';
import './style.scss';
/**
* Component displaying an attribute filter.
*/
const AttributeFilterBlock = ( {
attributes: blockAttributes,
isEditor = false,
} ) => {
const attributeObject =
blockAttributes.isPreview && ! blockAttributes.attributeId
? previewAttributeObject
: getAttributeFromID( blockAttributes.attributeId );
const [ checked, setChecked ] = useState( [] );
const [ displayedOptions, setDisplayedOptions ] = useState(
blockAttributes.isPreview && ! blockAttributes.attributeId
? previewOptions
: []
);
const [ queryState ] = useQueryStateByContext();
const [
productAttributesQuery,
setProductAttributesQuery,
] = useQueryStateByKey( 'attributes', [] );
const {
results: attributeTerms,
isLoading: attributeTermsLoading,
} = useCollection( {
namespace: '/wc/store',
resourceName: 'products/attributes/terms',
resourceValues: [ attributeObject.id ],
shouldSelect: blockAttributes.attributeId > 0,
} );
const filterAvailableTerms =
blockAttributes.displayStyle !== 'dropdown' &&
blockAttributes.queryType === 'and';
const {
results: filteredCounts,
isLoading: filteredCountsLoading,
} = useCollectionData( {
queryAttribute: {
taxonomy: attributeObject.taxonomy,
queryType: blockAttributes.queryType,
},
queryState: {
...queryState,
attributes: filterAvailableTerms ? queryState.attributes : null,
},
} );
/**
* Get count data about a given term by ID.
*/
const getFilteredTerm = useCallback(
( id ) => {
if ( ! filteredCounts.attribute_counts ) {
return null;
}
return filteredCounts.attribute_counts.find(
( { term } ) => term === id
);
},
[ filteredCounts ]
);
/**
* Compare intersection of all terms and filtered counts to get a list of options to display.
*/
useEffect( () => {
/**
* Checks if a term slug is in the query state.
*
* @param {string} termSlug The term of the slug to check.
*/
const isTermInQueryState = ( termSlug ) => {
if ( ! queryState || ! queryState.attributes ) {
return false;
}
return queryState.attributes.some(
( { attribute, slug = [] } ) =>
attribute === attributeObject.taxonomy &&
slug.includes( termSlug )
);
};
if ( attributeTermsLoading || filteredCountsLoading ) {
return;
}
const newOptions = attributeTerms
.map( ( term ) => {
const filteredTerm = getFilteredTerm( term.id );
// If there is no match this term doesn't match the current product collection - only render if checked.
if (
! filteredTerm &&
! checked.includes( term.slug ) &&
! isTermInQueryState( term.slug )
) {
return null;
}
const count = filteredTerm ? filteredTerm.count : 0;
return {
value: term.slug,
name: decodeEntities( term.name ),
label: (
<Label
name={ decodeEntities( term.name ) }
count={ blockAttributes.showCounts ? count : null }
/>
),
};
} )
.filter( Boolean );
setDisplayedOptions( newOptions );
}, [
attributeObject.taxonomy,
attributeTerms,
attributeTermsLoading,
blockAttributes.showCounts,
filteredCountsLoading,
getFilteredTerm,
checked,
queryState.attributes,
] );
// Track checked STATE changes - if state changes, update the query.
useEffect(
() => {
if ( ! blockAttributes.showFilterButton ) {
onSubmit();
}
},
// There is no need to add blockAttributes.showFilterButton as a dependency.
// It will only change in the editor and there we don't need to call onSubmit in any case.
[ checked, onSubmit ]
);
const checkedQuery = useMemo( () => {
return productAttributesQuery
.filter(
( { attribute } ) => attribute === attributeObject.taxonomy
)
.flatMap( ( { slug } ) => slug );
}, [ productAttributesQuery, attributeObject.taxonomy ] );
const currentCheckedQuery = useShallowEqual( checkedQuery );
// Track ATTRIBUTES QUERY changes so the block reflects current filters.
useEffect(
() => {
if ( ! isShallowEqual( checked, checkedQuery ) ) {
setChecked( checkedQuery );
}
},
// We only want to apply this effect when the query changes, so we are intentionally leaving `checked` out of the dependencies.
[ currentCheckedQuery ]
);
/**
* Returns an array of term objects that have been chosen via the checkboxes.
*/
const getSelectedTerms = useCallback(
( newChecked ) => {
return attributeTerms.reduce( ( acc, term ) => {
if ( newChecked.includes( term.slug ) ) {
acc.push( term );
}
return acc;
}, [] );
},
[ attributeTerms ]
);
const onSubmit = () => {
if ( isEditor ) {
return;
}
updateAttributeFilter(
productAttributesQuery,
setProductAttributesQuery,
attributeObject,
getSelectedTerms( checked ),
blockAttributes.queryType === 'or' ? 'in' : 'and'
);
};
const multiple =
blockAttributes.displayStyle !== 'dropdown' ||
blockAttributes.queryType === 'or';
/**
* When a checkbox in the list changes, update state.
*/
const onChange = useCallback(
( checkedValue ) => {
const getFilterNameFromValue = ( filterValue ) => {
const { name } = displayedOptions.find(
( option ) => option.value === filterValue
);
return name;
};
const announceFilterChange = ( { filterAdded, filterRemoved } ) => {
const filterAddedName = filterAdded
? getFilterNameFromValue( filterAdded )
: null;
const filterRemovedName = filterRemoved
? getFilterNameFromValue( filterRemoved )
: null;
if ( filterAddedName && filterRemovedName ) {
speak(
sprintf(
__(
// translators: %s attribute terms (for example: 'red', 'blue', 'large'...)
'%s filter replaced with %s.',
'woo-gutenberg-products-block'
),
filterAddedName,
filterRemovedName
)
);
} else if ( filterAddedName ) {
speak(
sprintf(
// translators: %s attribute term (for example: 'red', 'blue', 'large'...)
__(
'%s filter added.',
'woo-gutenberg-products-block'
),
filterAddedName
)
);
} else if ( filterRemovedName ) {
speak(
sprintf(
// translators: %s attribute term (for example: 'red', 'blue', 'large'...)
__(
'%s filter removed.',
'woo-gutenberg-products-block'
),
filterRemovedName
)
);
}
};
const previouslyChecked = checked.includes( checkedValue );
let newChecked;
if ( ! multiple ) {
newChecked = previouslyChecked ? [] : [ checkedValue ];
const filterAdded = previouslyChecked ? null : checkedValue;
const filterRemoved =
checked.length === 1 ? checked[ 0 ] : null;
announceFilterChange( { filterAdded, filterRemoved } );
} else {
newChecked = checked.filter(
( value ) => value !== checkedValue
);
if ( ! previouslyChecked ) {
newChecked.push( checkedValue );
newChecked.sort();
announceFilterChange( { filterAdded: checkedValue } );
} else {
announceFilterChange( { filterRemoved: checkedValue } );
}
}
setChecked( newChecked );
},
[ checked, displayedOptions, multiple ]
);
if ( displayedOptions.length === 0 && ! attributeTermsLoading ) {
return null;
}
const TagName = `h${ blockAttributes.headingLevel }`;
const isLoading = ! blockAttributes.isPreview && attributeTermsLoading;
const isDisabled = ! blockAttributes.isPreview && filteredCountsLoading;
return (
<Fragment>
{ ! isEditor && blockAttributes.heading && (
<TagName>{ blockAttributes.heading }</TagName>
) }
<div className="wc-block-attribute-filter">
{ blockAttributes.displayStyle === 'dropdown' ? (
<DropdownSelector
attributeLabel={ attributeObject.label }
checked={ checked }
className={ 'wc-block-attribute-filter-dropdown' }
inputLabel={ blockAttributes.heading }
isLoading={ isLoading }
multiple={ multiple }
onChange={ onChange }
options={ displayedOptions }
/>
) : (
<CheckboxList
className={ 'wc-block-attribute-filter-list' }
options={ displayedOptions }
checked={ checked }
onChange={ onChange }
isLoading={ isLoading }
isDisabled={ isDisabled }
/>
) }
{ blockAttributes.showFilterButton && (
<FilterSubmitButton
className="wc-block-attribute-filter__button"
disabled={ isLoading || isDisabled }
onClick={ onSubmit }
/>
) }
</div>
</Fragment>
);
};
export default AttributeFilterBlock;