forked from algolia/algoliasearch-helper-flutter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
facet_list.dart
364 lines (323 loc) · 10.4 KB
/
facet_list.dart
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
import 'dart:async';
import 'package:algolia_insights/algolia_insights.dart';
import 'package:collection/collection.dart';
import 'package:logging/logging.dart';
import 'package:meta/meta.dart';
import 'package:rxdart/rxdart.dart';
import 'disposable.dart';
import 'disposable_mixin.dart';
import 'extensions.dart';
import 'filter.dart';
import 'filter_group.dart';
import 'filter_state.dart';
import 'filters.dart';
import 'logger.dart';
import 'model/facet.dart';
import 'searcher/hits_searcher.dart';
import 'selectable_item.dart';
/// FacetList (refinement list) is a filtering components that displays facets,
/// and lets the user refine their search results by filtering on specific
/// values.
///
/// ## Create Facet List
///
/// Create [FacetList] with given [HitsSearcher] and [FilterState] components :
///
/// ```dart
/// // Create a HitsSearcher
/// final searcher = HitsSearcher(
/// applicationID: 'MY_APPLICATION_ID',
/// apiKey: 'MY_API_KEY',
/// indexName: 'MY_INDEX_NAME',
/// );
///
/// // Create a FilterState
/// final filterState = FilterState();
///
/// // Create a FacetList
/// final facetList = FacetList(
/// searcher: searcher,
/// filterState: filterState,
/// attribute: 'MY_ATTRIBUTE',
/// );
/// ```
///
/// ## Get selectable facet lists
///
/// Get selectable facets changes by listening to [facets] submissions:
///
/// ```dart
/// facetList.facets.listen((facets) {
/// for (var facet in facets) {
/// print("${facet.item} ${facet.isSelected ? 'x' : '-'}");
/// }
/// });
/// ```
///
/// ### Toggle facet
///
/// Call [toggle] to selected/deselect a facet value:
///
/// ```dart
/// facetList.toggle('MY_FACET_VALUE');
/// ```
///
/// ## Dispose
///
/// Call [dispose] to release underlying resources:
///
/// ```dart
/// facetList.dispose();
/// ```
@experimental
@sealed
abstract class FacetList implements Disposable {
/// Create [FacetList] instance.
factory FacetList({
required HitsSearcher searcher,
required FilterState filterState,
required String attribute,
FilterOperator operator = FilterOperator.or,
SelectionMode selectionMode = SelectionMode.multiple,
bool persistent = false,
}) =>
_FacetList(
searcher: searcher,
filterState: filterState,
attribute: attribute,
groupID: FilterGroupID(attribute, operator),
selectionMode: selectionMode,
persistent: persistent,
eventTracker: FilterEventTracker(
searcher.eventTracker.tracker,
searcher,
attribute,
),
);
/// Create [FacetList] instance.
factory FacetList.create({
required HitsSearcher searcher,
required FilterState filterState,
required String attribute,
required FilterGroupID groupID,
SelectionMode selectionMode = SelectionMode.multiple,
bool persistent = false,
}) =>
_FacetList(
searcher: searcher,
filterState: filterState,
attribute: attribute,
groupID: groupID,
selectionMode: selectionMode,
persistent: persistent,
eventTracker: FilterEventTracker(
searcher.eventTracker.tracker,
searcher,
attribute,
),
);
/// Insights events tracking component
FilterEventTracker get eventTracker;
/// Facet filter attribute
String get attribute;
/// Stream of [Facet] list with selection status.
Stream<List<SelectableFacet>> get facets;
/// Snapshot of the latest [facets] value.
List<SelectableFacet>? snapshot();
/// Select/deselect the provided facet value depending on the current
/// selection state.
void toggle(String value);
}
/// Elements selection mode.
enum SelectionMode { single, multiple }
/// [Facet] with selection status.
typedef SelectableFacet = SelectableItem<Facet>;
/// Default implementation of [FacetList].
class _FacetList with DisposableMixin implements FacetList {
/// Create [_FacetList] instance.
_FacetList({
required this.searcher,
required this.filterState,
required this.attribute,
required this.groupID,
required this.selectionMode,
required this.persistent,
required this.eventTracker,
}) {
if (searcher.isDisposed) {
_log.warning('creating an instance with disposed searcher');
}
if (filterState.isDisposed) {
_log.warning('creating an instance with disposed filter state');
}
// Setup search state by adding `attribute` to the search state
searcher.applyState(
(state) => state.copyWith(
facets: List.from((state.facets ?? [])..add(attribute)),
disjunctiveFacets: groupID.operator == FilterOperator.or
? {...?state.disjunctiveFacets, attribute}
: state.disjunctiveFacets,
),
);
_subscriptions
..add(_facets.connect())
..add(_responseFacets.connect())
..add(_selections.connect());
}
/// Hits Searcher component
final HitsSearcher searcher;
/// FilterState component.
final FilterState filterState;
@override
final FilterEventTracker eventTracker;
@override
final String attribute;
/// Filter group ID.
final FilterGroupID groupID;
/// Whether the facets can have single or multiple selections.
final SelectionMode selectionMode;
/// Should the selection be kept even if it does not match current results.
final bool persistent;
/// Events logger
final Logger _log = algoliaLogger('FacetList');
/// Selectable facets lists stream.
late final _facets = _selectableFacetsStream()
.distinct(const DeepCollectionEquality().equals)
.publishValue();
/// List of facets lists values from search responses.
late final _responseFacets = _searcherFacetsStream().publishValue();
/// Set of selected facet values from the filter state.
late final _selections = _filtersSelectionsStream().publishValue();
/// Streams subscriptions composite.
final CompositeSubscription _subscriptions = CompositeSubscription();
@override
Stream<List<SelectableFacet>> get facets => _facets;
@override
List<SelectableFacet>? snapshot() => _facets.valueOrNull;
/// Create stream of [SelectableFacet] lists from
/// [_responseFacets] and [_selections].
Stream<List<SelectableFacet>> _selectableFacetsStream() => Rx.combineLatest2(
_responseFacets,
_selections,
(List<Facet> facets, Set<String> selections) {
final facetsList = _buildSelectableFacets(facets, selections);
return persistent
? _buildPersistentSelectableFacets(facetsList, selections)
: facetsList;
},
);
/// Builds a list of [SelectableFacet] from [facets] and [selections].
List<SelectableFacet> _buildSelectableFacets(
List<Facet> facets,
Set<String> selections,
) =>
facets
.map(
(facet) => SelectableFacet(
item: facet,
isSelected: selections.contains(facet.value),
),
)
.toList();
/// Builds a list of [SelectableFacet] with persistent selections
/// from [facetsList] and [selections].
List<SelectableFacet> _buildPersistentSelectableFacets(
List<SelectableItem<Facet>> facetsList,
Set<String> selections,
) =>
selections
.where(
(selection) => facetsList.every(
(selectableFacet) => selectableFacet.item.value != selection,
),
)
.map(
(selection) => SelectableFacet(
item: Facet(selection, 0),
isSelected: true,
),
)
.toList()
..addAll(facetsList);
/// Build facets lists stream from [searcher].
Stream<List<Facet>> _searcherFacetsStream() => searcher.responses.map(
(response) =>
response.disjunctiveFacets[attribute] ??
response.facets[attribute] ??
[],
);
/// Build selections stream from [filterState] filters updates.
Stream<Set<String>> _filtersSelectionsStream() => filterState.filters.map(
(filters) =>
filters
.getFacetFilters(groupID)
?.map((e) => e.value.toString())
.toSet() ??
{},
);
@override
void toggle(String value) {
_trackClickIfNeeded(value);
_selectionsSet(value).then((selections) {
filterState.modify((filters) async {
final filtersSet =
selections.map((value) => Filter.facet(attribute, value)).toSet();
filters = await _clearFilters(filters);
return filters.add(groupID, filtersSet);
});
});
}
void _trackClickIfNeeded(String selection) {
_selections.first.then((selections) {
if (!selections.contains(selection)) {
eventTracker.clickedFilters(
eventName: 'Filter Applied',
values: [selection],
);
}
});
}
/// Get new set of selection after a selection operation.
/// We use async operation here since [_selections] can take some time to get
/// current filters (just after initialization).
Future<Set<String>> _selectionsSet(String selection) async {
final current = await _selections.first;
_log.finest('current facet selections: $current -> $selection selected');
switch (selectionMode) {
case SelectionMode.single:
return current.contains(selection) ? {} : {selection};
case SelectionMode.multiple:
final set = current.modifiable();
return current.contains(selection)
? (set..remove(selection))
: (set..add(selection));
}
}
/// Clear filters from [StatelessFilters] depending
Future<StatelessFilters> _clearFilters(StatelessFilters filters) async {
switch (selectionMode) {
case SelectionMode.single:
return filters.clear([groupID]);
case SelectionMode.multiple:
final filtersToRemove = _facetsToRemove();
return filters.remove(groupID, await filtersToRemove);
}
}
/// Get the set of facets to remove in case of multiple selection mode.
/// In case of persistent selection, current selections are kept.
Future<Set<FilterFacet>> _facetsToRemove() async {
final currentFilters = (await _responseFacets.first)
.map((facet) => Filter.facet(attribute, facet.value))
.toSet();
if (!persistent) return currentFilters;
final currentSelections = (await _selections.first)
.map((selection) => Filter.facet(attribute, selection))
.toSet();
return {...currentFilters, ...currentSelections};
}
@override
void doDispose() {
_log.finest('FacetList disposed');
_subscriptions.cancel();
}
}