Debian Codegraph @

resources/src/mediawiki.rcfilters/dm/FiltersViewModel.js

raw symbols SCIP
1 const FilterGroup = require( './FilterGroup.js' ),
2 FilterItem = require( './FilterItem.js' ),
3 utils = require( '../utils.js' );
4
5 /**
6 * View model for the filters selection and display.
7 *
8 * @class mw.rcfilters.dm.FiltersViewModel
9 * @ignore
10 * @mixes OO.EventEmitter
11 * @mixes OO.EmitterList
12 */
13 const FiltersViewModel = function MwRcfiltersDmFiltersViewModel() {
14 // Mixin constructor
15 OO.EventEmitter.call( this );
16 OO.EmitterList.call( this );
17
18 this.groups = {};
19 this.defaultParams = {};
20 this.highlightEnabled = false;
21 this.parameterMap = {};
22 this.emptyParameterState = null;
23
24 this.views = {};
25 this.currentView = 'default';
26 this.searchQuery = null;
27
28 // Events
29 this.aggregate( { update: 'filterItemUpdate' } );
30 this.connect( this, { filterItemUpdate: [ 'emit', 'itemUpdate' ] } );
31 };
32
33 /* Initialization */
34 OO.initClass( FiltersViewModel );
35 OO.mixinClass( FiltersViewModel, OO.EventEmitter );
36 OO.mixinClass( FiltersViewModel, OO.EmitterList );
37
38 /* Events */
39
40 /**
41 * Filter list is initialized.
42 *
43 * @event initialize
44 * @ignore
45 */
46
47 /**
48 * Model has been updated.
49 *
50 * @event update
51 * @ignore
52 */
53
54 /**
55 * Filter item has changed.
56 *
57 * @event itemUpdate
58 * @param {mw.rcfilters.dm.FilterItem} item Filter item updated
59 * @ignore
60 */
61
62 /**
63 * Highlight feature has been toggled enabled or disabled.
64 *
65 * @event highlightChange
66 * @param {boolean} Highlight feature is enabled
67 * @ignore
68 */
69
70 /* Methods */
71
72 /**
73 * Re-assess the states of filter items based on the interactions between them
74 *
75 * @param {mw.rcfilters.dm.FilterItem} [item] Changed item. If not given, the
76 * method will go over the state of all items
77 */
78 FiltersViewModel.prototype.reassessFilterInteractions = function ( item ) {
79 const model = this,
80 iterationItems = item !== undefined ? [ item ] : this.getItems();
81
82 iterationItems.forEach( ( checkedItem ) => {
83 const allCheckedItems = checkedItem.getSubset().concat( [ checkedItem.getName() ] ),
84 groupModel = checkedItem.getGroupModel();
85
86 // Check for subsets (included filters) plus the item itself:
87 allCheckedItems.forEach( ( filterItemName ) => {
88 const itemInSubset = model.getItemByName( filterItemName );
89
90 itemInSubset.toggleIncluded(
91 // If any of itemInSubset's supersets are selected, this item
92 // is included
93 itemInSubset.getSuperset().some( ( supersetName ) => ( model.getItemByName( supersetName ).isSelected() ) )
94 );
95 } );
96
97 // Update coverage for the changed group
98 if ( groupModel.isFullCoverage() ) {
99 const allSelected = groupModel.areAllSelected();
100 groupModel.getItems().forEach( ( filterItem ) => {
101 filterItem.toggleFullyCovered( allSelected );
102 } );
103 }
104 } );
105
106 // Check for conflicts
107 // In this case, we must go over all items, since
108 // conflicts are bidirectional and depend not only on
109 // individual items, but also on the selected states of
110 // the groups they're in.
111 this.getItems().forEach( ( filterItem ) => {
112 let inConflict = false;
113 const filterItemGroup = filterItem.getGroupModel();
114
115 // For each item, see if that item is still conflicting
116 // eslint-disable-next-line no-jquery/no-each-util
117 $.each( model.groups, ( groupName, groupModel ) => {
118 if ( filterItem.getGroupName() === groupName ) {
119 // Check inside the group
120 inConflict = groupModel.areAnySelectedInConflictWith( filterItem );
121 } else {
122 // According to the spec, if two items conflict from two different
123 // groups, the conflict only lasts if the groups **only have selected
124 // items that are conflicting**. If a group has selected items that
125 // are conflicting and non-conflicting, the scope of the result has
126 // expanded enough to completely remove the conflict.
127
128 // For example, see two groups with conflicts:
129 // userExpLevel: [
130 // {
131 // name: 'experienced',
132 // conflicts: [ 'unregistered' ]
133 // }
134 // ],
135 // registration: [
136 // {
137 // name: 'registered',
138 // },
139 // {
140 // name: 'unregistered',
141 // }
142 // ]
143 // If we select 'experienced', then 'unregistered' is in conflict (and vice versa),
144 // because, inherently, 'experienced' filter only includes registered users, and so
145 // both filters are in conflict with one another.
146 // However, the minute we select 'registered', the scope of our results
147 // has expanded to no longer have a conflict with 'experienced' filter, and
148 // so the conflict is removed.
149
150 // In our case, we need to check if the entire group conflicts with
151 // the entire item's group, so we follow the above spec
152 inConflict = (
153 // The foreign group is in conflict with this item
154 groupModel.areAllSelectedInConflictWith( filterItem ) &&
155 // Every selected member of the item's own group is also
156 // in conflict with the other group
157 filterItemGroup.findSelectedItems().every( ( otherGroupItem ) => groupModel.areAllSelectedInConflictWith( otherGroupItem ) )
158 );
159 }
160
161 // If we're in conflict, this will return 'false' which
162 // will break the loop. Otherwise, we're not in conflict
163 // and the loop continues
164 return !inConflict;
165 } );
166
167 // Toggle the item state
168 filterItem.toggleConflicted( inConflict );
169 } );
170 };
171
172 /**
173 * Get whether the model has any conflict in its items
174 *
175 * @return {boolean} There is a conflict
176 */
177 FiltersViewModel.prototype.hasConflict = function () {
178 return this.getItems().some( ( filterItem ) => filterItem.isSelected() && filterItem.isConflicted() );
179 };
180
181 /**
182 * Get the first item with a current conflict
183 *
184 * @ignore
185 * @return {mw.rcfilters.dm.FilterItem|undefined} Conflicted item or undefined when not found
186 */
187 FiltersViewModel.prototype.getFirstConflictedItem = function () {
188 const items = this.getItems();
189 for ( let i = 0; i < items.length; i++ ) {
190 const filterItem = items[ i ];
191 if ( filterItem.isSelected() && filterItem.isConflicted() ) {
192 return filterItem;
193 }
194 }
195 };
196
197 /**
198 * Set filters and preserve a group relationship based on
199 * the definition given by an object
200 *
201 * @param {Array} filterGroups Filters definition
202 * @param {Object} [views] Extra views definition
203 * Expected in the following format:
204 * {
205 * namespaces: {
206 * label: 'namespaces', // Message key
207 * trigger: ':',
208 * groups: [
209 * {
210 * // Group info
211 * name: 'namespaces' // Parameter name
212 * title: 'namespaces' // Message key
213 * type: 'string_options',
214 * separator: ';',
215 * labelPrefixKey: { 'default': 'rcfilters-tag-prefix-namespace', inverted: 'rcfilters-tag-prefix-namespace-inverted' },
216 * fullCoverage: true
217 * items: []
218 * }
219 * ]
220 * }
221 * }
222 */
223 FiltersViewModel.prototype.initializeFilters = function ( filterGroups, views ) {
224 const model = this,
225 items = [],
226 groupConflictMap = {},
227 filterConflictMap = {},
228 /*!
229 * Expand a conflict definition from group name to
230 * the list of all included filters in that group.
231 * We do this so that the direct relationship in the
232 * models are consistently item->items rather than
233 * mixing item->group with item->item.
234 *
235 * @param {Object} obj Conflict definition
236 * @return {Object} Expanded conflict definition
237 */
238 expandConflictDefinitions = function ( obj ) {
239 const result = {};
240
241 // eslint-disable-next-line no-jquery/no-each-util
242 $.each( obj, ( key, conflicts ) => {
243 const adjustedConflicts = {};
244
245 conflicts.forEach( ( conflict ) => {
246 let filter;
247
248 if ( conflict.filter ) {
249 const filterName = model.groups[ conflict.group ].getPrefixedName( conflict.filter );
250 filter = model.getItemByName( filterName );
251
252 // Rename
253 adjustedConflicts[ filterName ] = Object.assign(
254 {},
255 conflict,
256 {
257 filter: filterName,
258 item: filter
259 }
260 );
261 } else {
262 // This conflict is for an entire group. Split it up to
263 // represent each filter
264
265 // Get the relevant group items
266 model.groups[ conflict.group ].getItems().forEach( ( groupItem ) => {
267 // Rebuild the conflict
268 adjustedConflicts[ groupItem.getName() ] = Object.assign(
269 {},
270 conflict,
271 {
272 filter: groupItem.getName(),
273 item: groupItem
274 }
275 );
276 } );
277 }
278 } );
279
280 result[ key ] = adjustedConflicts;
281 } );
282
283 return result;
284 };
285
286 // Reset
287 this.clearItems();
288 this.groups = {};
289 this.views = {};
290
291 // Clone
292 filterGroups = OO.copy( filterGroups );
293
294 // Normalize definition from the server
295 filterGroups.forEach( ( data ) => {
296 let i;
297 // What's this information needs to be normalized
298 data.whatsThis = {
299 body: data.whatsThisBody,
300 header: data.whatsThisHeader,
301 linkText: data.whatsThisLinkText,
302 url: data.whatsThisUrl
303 };
304
305 // Title is a msg-key
306 // eslint-disable-next-line mediawiki/msg-doc
307 data.title = data.title ? mw.msg( data.title ) : data.name;
308
309 // Filters are given to us with msg-keys, we need
310 // to translate those before we hand them off
311 for ( i = 0; i < data.filters.length; i++ ) {
312 // eslint-disable-next-line mediawiki/msg-doc
313 data.filters[ i ].label = data.filters[ i ].label ? mw.msg( data.filters[ i ].label ) : data.filters[ i ].name;
314 // eslint-disable-next-line mediawiki/msg-doc
315 data.filters[ i ].description = data.filters[ i ].description ? mw.msg( data.filters[ i ].description ) : '';
316 }
317 } );
318
319 // Collect views
320 const allViews = $.extend( true, {
321 default: {
322 title: mw.msg( 'rcfilters-filterlist-title' ),
323 groups: filterGroups
324 }
325 }, views );
326
327 // Go over all views
328 // eslint-disable-next-line no-jquery/no-each-util
329 $.each( allViews, ( viewName, viewData ) => {
330 // Define the view
331 model.views[ viewName ] = {
332 name: viewData.name,
333 title: viewData.title,
334 trigger: viewData.trigger
335 };
336
337 // Go over groups
338 viewData.groups.forEach( ( groupData ) => {
339 const group = groupData.name;
340
341 if ( !model.groups[ group ] ) {
342 model.groups[ group ] = new FilterGroup(
343 group,
344 $.extend( true, {}, groupData, { view: viewName } )
345 );
346 }
347
348 model.groups[ group ].initializeFilters( groupData.filters, groupData.default );
349 items.push( ...model.groups[ group ].getItems() );
350
351 // Prepare conflicts
352 if ( groupData.conflicts ) {
353 // Group conflicts
354 groupConflictMap[ group ] = groupData.conflicts;
355 }
356
357 groupData.filters.forEach( ( itemData ) => {
358 const filterItem = model.groups[ group ].getItemByParamName( itemData.name );
359 // Filter conflicts
360 if ( itemData.conflicts ) {
361 filterConflictMap[ filterItem.getName() ] = itemData.conflicts;
362 }
363 } );
364 } );
365 } );
366
367 // Add item references to the model, for lookup
368 this.addItems( items );
369
370 // Expand conflicts
371 const groupConflictResult = expandConflictDefinitions( groupConflictMap );
372 const filterConflictResult = expandConflictDefinitions( filterConflictMap );
373
374 // Set conflicts for groups
375 // eslint-disable-next-line no-jquery/no-each-util
376 $.each( groupConflictResult, ( group, conflicts ) => {
377 model.groups[ group ].setConflicts( conflicts );
378 } );
379
380 // Set conflicts for items
381 // eslint-disable-next-line no-jquery/no-each-util
382 $.each( filterConflictResult, ( filterName, conflicts ) => {
383 const filterItem = model.getItemByName( filterName );
384 // set conflicts for items in the group
385 filterItem.setConflicts( conflicts );
386 } );
387
388 // Create a map between known parameters and their models
389 // eslint-disable-next-line no-jquery/no-each-util
390 $.each( this.groups, ( group, groupModel ) => {
391 if (
392 groupModel.getType() === 'send_unselected_if_any' ||
393 groupModel.getType() === 'boolean' ||
394 groupModel.getType() === 'any_value'
395 ) {
396 // Individual filters
397 groupModel.getItems().forEach( ( filterItem ) => {
398 model.parameterMap[ filterItem.getParamName() ] = filterItem;
399 } );
400 } else if (
401 groupModel.getType() === 'string_options' ||
402 groupModel.getType() === 'single_option'
403 ) {
404 // Group
405 model.parameterMap[ groupModel.getName() ] = groupModel;
406 }
407 } );
408
409 this.setSearch( '' );
410
411 this.updateHighlightedState();
412
413 // Finish initialization
414 this.emit( 'initialize' );
415 };
416
417 /**
418 * Update filter view model state based on a parameter object
419 *
420 * @param {Object} params Parameters object
421 */
422 FiltersViewModel.prototype.updateStateFromParams = function ( params ) {
423 // For arbitrary numeric single_option values make sure the values
424 // are normalized to fit within the limits
425 // eslint-disable-next-line no-jquery/no-each-util
426 $.each( this.getFilterGroups(), ( groupName, groupModel ) => {
427 params[ groupName ] = groupModel.normalizeArbitraryValue( params[ groupName ] );
428 } );
429
430 // Update filter values
431 const filtersValue = this.getFiltersFromParameters( params );
432 Object.keys( filtersValue ).forEach( ( filterName ) => {
433 this.getItemByName( filterName ).setValue( filtersValue[ filterName ] );
434 } );
435
436 // Update highlight state
437 this.getItemsSupportingHighlights().forEach( ( filterItem ) => {
438 const color = params[ filterItem.getName() + '_color' ];
439 if ( color ) {
440 filterItem.setHighlightColor( color );
441 } else {
442 filterItem.clearHighlightColor();
443 }
444 } );
445 this.updateHighlightedState();
446
447 // Check all filter interactions
448 this.reassessFilterInteractions();
449 };
450
451 /**
452 * Get a representation of an empty (falsey) parameter state
453 *
454 * @return {Object} Empty parameter state
455 */
456 FiltersViewModel.prototype.getEmptyParameterState = function () {
457 if ( !this.emptyParameterState ) {
458 this.emptyParameterState = $.extend(
459 true,
460 {},
461 this.getParametersFromFilters( {} ),
462 this.getEmptyHighlightParameters()
463 );
464 }
465 return this.emptyParameterState;
466 };
467
468 /**
469 * Get a representation of only the non-falsey parameters
470 *
471 * @param {Object} [parameters] A given parameter state to minimize. If not given the current
472 * state of the system will be used.
473 * @return {Object} Empty parameter state
474 */
475 FiltersViewModel.prototype.getMinimizedParamRepresentation = function ( parameters ) {
476 const result = {};
477
478 parameters = parameters ? $.extend( true, {}, parameters ) : this.getCurrentParameterState();
479
480 // Params
481 // eslint-disable-next-line no-jquery/no-each-util
482 $.each( this.getEmptyParameterState(), ( param, value ) => {
483 if ( parameters[ param ] !== undefined && parameters[ param ] !== value ) {
484 result[ param ] = parameters[ param ];
485 }
486 } );
487
488 // Highlights
489 Object.keys( this.getEmptyHighlightParameters() ).forEach( ( param ) => {
490 if ( parameters[ param ] ) {
491 // If a highlight parameter is not undefined and not null
492 // add it to the result
493 result[ param ] = parameters[ param ];
494 }
495 } );
496
497 return result;
498 };
499
500 /**
501 * Get a representation of the full parameter list, including all base values
502 *
503 * @return {Object} Full parameter representation
504 */
505 FiltersViewModel.prototype.getExpandedParamRepresentation = function () {
506 return $.extend(
507 true,
508 {},
509 this.getEmptyParameterState(),
510 this.getCurrentParameterState()
511 );
512 };
513
514 /**
515 * Get a parameter representation of the current state of the model
516 *
517 * @param {boolean} [removeStickyParams] Remove sticky filters from final result
518 * @return {Object} Parameter representation of the current state of the model
519 */
520 FiltersViewModel.prototype.getCurrentParameterState = function ( removeStickyParams ) {
521 let state = this.getMinimizedParamRepresentation( $.extend(
522 true,
523 {},
524 this.getParametersFromFilters( this.getSelectedState() ),
525 this.getHighlightParameters()
526 ) );
527
528 if ( removeStickyParams ) {
529 state = this.removeStickyParams( state );
530 }
531
532 return state;
533 };
534
535 /**
536 * Delete sticky parameters from given object.
537 *
538 * @param {Object} paramState Parameter state
539 * @return {Object} Parameter state without sticky parameters
540 */
541 FiltersViewModel.prototype.removeStickyParams = function ( paramState ) {
542 this.getStickyParams().forEach( ( paramName ) => {
543 delete paramState[ paramName ];
544 } );
545
546 return paramState;
547 };
548
549 /**
550 * Turn the highlight feature on or off
551 */
552 FiltersViewModel.prototype.updateHighlightedState = function () {
553 this.toggleHighlight( this.getHighlightedItems().length > 0 );
554 };
555
556 /**
557 * Get the object that defines groups by their name.
558 *
559 * @return {Object} Filter groups
560 */
561 FiltersViewModel.prototype.getFilterGroups = function () {
562 return this.groups;
563 };
564
565 /**
566 * Get the object that defines groups that match a certain view by their name.
567 *
568 * @param {string} [view] Requested view. If not given, uses current view
569 * @return {Object} Filter groups matching a display group
570 */
571 FiltersViewModel.prototype.getFilterGroupsByView = function ( view ) {
572 const result = {};
573
574 view = view || this.getCurrentView();
575
576 // eslint-disable-next-line no-jquery/no-each-util
577 $.each( this.groups, ( groupName, groupModel ) => {
578 if ( groupModel.getView() === view ) {
579 result[ groupName ] = groupModel;
580 }
581 } );
582
583 return result;
584 };
585
586 /**
587 * Get an array of filters matching the given display group.
588 *
589 * @ignore
590 * @param {string} [view] Requested view. If not given, uses current view
591 * @return {mw.rcfilters.dm.FilterItem} Filter items matching the group
592 */
593 FiltersViewModel.prototype.getFiltersByView = function ( view ) {
594 const result = [];
595
596 view = view || this.getCurrentView();
597
598 const groups = this.getFilterGroupsByView( view );
599
600 // eslint-disable-next-line no-jquery/no-each-util
601 $.each( groups, ( groupName, groupModel ) => {
602 result.push( ...groupModel.getItems() );
603 } );
604
605 return result;
606 };
607
608 /**
609 * Get the trigger for the requested view.
610 *
611 * @param {string} view View name
612 * @return {string} View trigger, if exists
613 */
614 FiltersViewModel.prototype.getViewTrigger = function ( view ) {
615 return ( this.views[ view ] && this.views[ view ].trigger ) || '';
616 };
617
618 /**
619 * Get the value of a specific parameter
620 *
621 * @param {string} name Parameter name
622 * @return {number|string} Parameter value
623 */
624 FiltersViewModel.prototype.getParamValue = function ( name ) {
625 return this.parameters[ name ];
626 };
627
628 /**
629 * Get the current selected state of the filters
630 *
631 * @param {boolean} [onlySelected] return an object containing only the filters with a value
632 * @return {Object} Filters selected state
633 */
634 FiltersViewModel.prototype.getSelectedState = function ( onlySelected ) {
635 const items = this.getItems(),
636 result = {};
637
638 for ( let i = 0; i < items.length; i++ ) {
639 if ( !onlySelected || items[ i ].getValue() ) {
640 result[ items[ i ].getName() ] = items[ i ].getValue();
641 }
642 }
643
644 return result;
645 };
646
647 /**
648 * Get the current full state of the filters
649 *
650 * @return {Object} Filters full state
651 */
652 FiltersViewModel.prototype.getFullState = function () {
653 const items = this.getItems(),
654 result = {};
655
656 for ( let i = 0; i < items.length; i++ ) {
657 result[ items[ i ].getName() ] = {
658 selected: items[ i ].isSelected(),
659 conflicted: items[ i ].isConflicted(),
660 included: items[ i ].isIncluded()
661 };
662 }
663
664 return result;
665 };
666
667 /**
668 * Get an object representing default parameters state
669 *
670 * @return {Object} Default parameter values
671 */
672 FiltersViewModel.prototype.getDefaultParams = function () {
673 const result = {};
674
675 // Get default filter state
676 // eslint-disable-next-line no-jquery/no-each-util
677 $.each( this.groups, ( name, model ) => {
678 if ( !model.isSticky() ) {
679 $.extend( true, result, model.getDefaultParams() );
680 }
681 } );
682
683 return result;
684 };
685
686 /**
687 * Get a parameter representation of all sticky parameters
688 *
689 * @return {Object} Sticky parameter values
690 */
691 FiltersViewModel.prototype.getStickyParams = function () {
692 let result = [];
693
694 // eslint-disable-next-line no-jquery/no-each-util
695 $.each( this.groups, ( name, model ) => {
696 if ( model.isSticky() ) {
697 if ( model.isPerGroupRequestParameter() ) {
698 result.push( name );
699 } else {
700 // Each filter is its own param
701 result = result.concat( model.getItems().map( ( filterItem ) => filterItem.getParamName() ) );
702 }
703 }
704 } );
705
706 return result;
707 };
708
709 /**
710 * Get a parameter representation of all sticky parameters
711 *
712 * @return {Object} Sticky parameter values
713 */
714 FiltersViewModel.prototype.getStickyParamsValues = function () {
715 const result = {};
716
717 // eslint-disable-next-line no-jquery/no-each-util
718 $.each( this.groups, ( name, model ) => {
719 if ( model.isSticky() ) {
720 $.extend( true, result, model.getParamRepresentation() );
721 }
722 } );
723
724 return result;
725 };
726
727 /**
728 * Analyze the groups and their filters and output an object representing
729 * the state of the parameters they represent.
730 *
731 * @param {Object} [filterDefinition] An object defining the filter values,
732 * keyed by filter names.
733 * @return {Object} Parameter state object
734 */
735 FiltersViewModel.prototype.getParametersFromFilters = function ( filterDefinition ) {
736 let groupItemDefinition;
737 const result = {},
738 groupItems = this.getFilterGroups();
739
740 if ( filterDefinition ) {
741 groupItemDefinition = {};
742 // Filter definition is "flat", but in effect
743 // each group needs to tell us its result based
744 // on the values in it. We need to split this list
745 // back into groupings so we can "feed" it to the
746 // loop below, and we need to expand it so it includes
747 // all filters (set to false)
748 this.getItems().forEach( ( filterItem ) => {
749 groupItemDefinition[ filterItem.getGroupName() ] = groupItemDefinition[ filterItem.getGroupName() ] || {};
750 groupItemDefinition[ filterItem.getGroupName() ][ filterItem.getName() ] = filterItem.coerceValue( filterDefinition[ filterItem.getName() ] );
751 } );
752 }
753
754 // eslint-disable-next-line no-jquery/no-each-util
755 $.each( groupItems, ( group, model ) => {
756 Object.assign(
757 result,
758 model.getParamRepresentation(
759 groupItemDefinition ?
760 groupItemDefinition[ group ] : null
761 )
762 );
763 } );
764
765 return result;
766 };
767
768 /**
769 * This is the opposite of the #getParametersFromFilters method; this goes over
770 * the given parameters and translates into a selected/unselected value in the filters.
771 *
772 * @param {Object} params Parameters query object
773 * @return {Object} Filter state object
774 */
775 FiltersViewModel.prototype.getFiltersFromParameters = function ( params ) {
776 const groupMap = {},
777 model = this;
778 let result = {};
779
780 // Go over the given parameters, break apart to groupings
781 // The resulting object represents the group with its parameter
782 // values. For example:
783 // {
784 // group1: {
785 // param1: "1",
786 // param2: "0",
787 // param3: "1"
788 // },
789 // group2: "param4|param5"
790 // }
791 // eslint-disable-next-line no-jquery/no-each-util
792 $.each( params, ( paramName, paramValue ) => {
793 const itemOrGroup = model.parameterMap[ paramName ];
794
795 if ( itemOrGroup ) {
796 const groupName = itemOrGroup instanceof FilterItem ?
797 itemOrGroup.getGroupName() : itemOrGroup.getName();
798
799 groupMap[ groupName ] = groupMap[ groupName ] || {};
800 groupMap[ groupName ][ paramName ] = paramValue;
801 }
802 } );
803
804 // Go over all groups, so we make sure we get the complete output
805 // even if the parameters don't include a certain group
806 // eslint-disable-next-line no-jquery/no-each-util
807 $.each( this.groups, ( groupName, groupModel ) => {
808 result = $.extend( true, {}, result, groupModel.getFilterRepresentation( groupMap[ groupName ] ) );
809 } );
810
811 return result;
812 };
813
814 /**
815 * Get the highlight parameters based on current filter configuration
816 *
817 * @return {Object} Object where keys are `<filter name>_color` and values
818 * are the selected highlight colors.
819 */
820 FiltersViewModel.prototype.getHighlightParameters = function () {
821 const highlightEnabled = this.isHighlightEnabled(),
822 result = {};
823
824 this.getItems().forEach( ( filterItem ) => {
825 if ( filterItem.isHighlightSupported() ) {
826 result[ filterItem.getName() + '_color' ] = highlightEnabled && filterItem.isHighlighted() ?
827 filterItem.getHighlightColor() :
828 null;
829 }
830 } );
831
832 return result;
833 };
834
835 /**
836 * Get an object representing the complete empty state of highlights
837 *
838 * @return {Object} Object containing all the highlight parameters set to their negative value
839 */
840 FiltersViewModel.prototype.getEmptyHighlightParameters = function () {
841 const result = {};
842
843 this.getItems().forEach( ( filterItem ) => {
844 if ( filterItem.isHighlightSupported() ) {
845 result[ filterItem.getName() + '_color' ] = null;
846 }
847 } );
848
849 return result;
850 };
851
852 /**
853 * Get an array of currently applied highlight colors
854 *
855 * @return {string[]} Currently applied highlight colors
856 */
857 FiltersViewModel.prototype.getCurrentlyUsedHighlightColors = function () {
858 const result = [];
859
860 if ( this.isHighlightEnabled() ) {
861 this.getHighlightedItems().forEach( ( filterItem ) => {
862 const color = filterItem.getHighlightColor();
863
864 if ( result.indexOf( color ) === -1 ) {
865 result.push( color );
866 }
867 } );
868 }
869
870 return result;
871 };
872
873 /**
874 * Sanitize value group of a string_option groups type
875 * Remove duplicates and make sure to only use valid
876 * values.
877 *
878 * @private
879 * @param {string} groupName Group name
880 * @param {string[]} valueArray Array of values
881 * @return {string[]} Array of valid values
882 */
883 FiltersViewModel.prototype.sanitizeStringOptionGroup = function ( groupName, valueArray ) {
884 const validNames = this.getGroupFilters( groupName ).map( ( filterItem ) => filterItem.getParamName() );
885
886 return utils.normalizeParamOptions( valueArray, validNames );
887 };
888
889 /**
890 * Check whether no visible filter is selected.
891 *
892 * Filter groups that are hidden or sticky are not shown in the
893 * active filters area and therefore not included in this check.
894 *
895 * @return {boolean} No visible filter is selected
896 */
897 FiltersViewModel.prototype.areVisibleFiltersEmpty = function () {
898 // Check if there are either any selected items or any items
899 // that have highlight enabled
900 return !this.getItems().some( ( filterItem ) => {
901 const visible = !filterItem.getGroupModel().isSticky() && !filterItem.getGroupModel().isHidden(),
902 active = ( filterItem.isSelected() || filterItem.isHighlighted() );
903 return visible && active;
904 } );
905 };
906
907 /**
908 * Check whether the namespace invert state is a valid one. A valid invert state is one
909 * where there are actual namespaces selected.
910 *
911 * This is done to compare states to previous ones that may have had the invert model
912 * selected but effectively had no namespaces, so are not effectively different than
913 * ones where invert is not selected.
914 *
915 * @return {boolean} Invert is effectively selected
916 */
917 FiltersViewModel.prototype.areNamespacesEffectivelyInverted = function () {
918 return this.getNamespacesInvertModel().isSelected() &&
919 this.findSelectedItems().some( ( itemModel ) => itemModel.getGroupModel().getName() === 'namespace' );
920 };
921
922 /**
923 * Check whether the tag invert state is a valid one. A valid invert state is one
924 * where there are actual tags selected.
925 *
926 * This is done to compare states to previous ones that may have had the invert model
927 * selected but effectively had no tags, so are not effectively different than
928 * ones where invert is not selected.
929 *
930 * @return {boolean} Invert is effectively selected
931 */
932 FiltersViewModel.prototype.areTagsEffectivelyInverted = function () {
933 return this.getTagsInvertModel().isSelected() &&
934 this.findSelectedItems().some( ( itemModel ) => itemModel.getGroupModel().getName() === 'tagfilter' );
935 };
936
937 /**
938 * Get the item that matches the given name
939 *
940 * @ignore
941 * @param {string} name Filter name
942 * @return {mw.rcfilters.dm.FilterItem} Filter item
943 */
944 FiltersViewModel.prototype.getItemByName = function ( name ) {
945 return this.getItems().filter( ( item ) => name === item.getName() )[ 0 ];
946 };
947
948 /**
949 * Set all filters to false or empty/all
950 * This is equivalent to display all.
951 */
952 FiltersViewModel.prototype.emptyAllFilters = function () {
953 this.getItems().forEach( ( filterItem ) => {
954 if ( !filterItem.getGroupModel().isSticky() ) {
955 this.toggleFilterSelected( filterItem.getName(), false );
956 }
957 } );
958 };
959
960 /**
961 * Toggle selected state of one item
962 *
963 * @param {string} name Name of the filter item
964 * @param {boolean} [isSelected] Filter selected state
965 */
966 FiltersViewModel.prototype.toggleFilterSelected = function ( name, isSelected ) {
967 const item = this.getItemByName( name );
968
969 if ( item ) {
970 item.toggleSelected( isSelected );
971 }
972 };
973
974 /**
975 * Toggle selected state of items by their names
976 *
977 * @param {Object} filterDef Filter definitions
978 */
979 FiltersViewModel.prototype.toggleFiltersSelected = function ( filterDef ) {
980 Object.keys( filterDef ).forEach( ( name ) => {
981 this.toggleFilterSelected( name, filterDef[ name ] );
982 } );
983 };
984
985 /**
986 * Get a group model from its name
987 *
988 * @ignore
989 * @param {string} groupName Group name
990 * @return {mw.rcfilters.dm.FilterGroup} Group model
991 */
992 FiltersViewModel.prototype.getGroup = function ( groupName ) {
993 return this.groups[ groupName ];
994 };
995
996 /**
997 * Get all filters within a specified group by its name
998 *
999 * @ignore
1000 * @param {string} groupName Group name
1001 * @return {mw.rcfilters.dm.FilterItem[]} Filters belonging to this group
1002 */
1003 FiltersViewModel.prototype.getGroupFilters = function ( groupName ) {
1004 return ( this.getGroup( groupName ) && this.getGroup( groupName ).getItems() ) || [];
1005 };
1006
1007 /**
1008 * Find items whose labels match the given string
1009 *
1010 * @param {string} query Search string
1011 * @param {boolean} [returnFlat] Return a flat array. If false, the result
1012 * is an object whose keys are the group names and values are an array of
1013 * filters per group. If set to true, returns an array of filters regardless
1014 * of their groups.
1015 * @return {Object} An object of items to show
1016 * arranged by their group names
1017 */
1018 FiltersViewModel.prototype.findMatches = function ( query, returnFlat ) {
1019 const result = {},
1020 flatResult = [],
1021 view = this.getViewByTrigger( query.slice( 0, 1 ) ),
1022 items = this.getFiltersByView( view );
1023
1024 // Normalize so we can search strings regardless of case and view
1025 query = query.trim().toLowerCase();
1026 if ( view !== 'default' ) {
1027 query = query.slice( 1 );
1028 }
1029 // Trim again to also intercept cases where the spaces were after the trigger
1030 // eg: '# str'
1031 query = query.trim();
1032
1033 // Check if the search if actually empty; this can be a problem when
1034 // we use prefixes to denote different views
1035 const searchIsEmpty = query.length === 0;
1036
1037 // item label starting with the query string
1038 for ( let i = 0; i < items.length; i++ ) {
1039 if (
1040 searchIsEmpty ||
1041 items[ i ].getLabel().toLowerCase().indexOf( query ) === 0 ||
1042 (
1043 // For tags, we want the parameter name to be included in the search
1044 view === 'tags' &&
1045 items[ i ].getParamName().toLowerCase().indexOf( query ) > -1
1046 )
1047 ) {
1048 result[ items[ i ].getGroupName() ] = result[ items[ i ].getGroupName() ] || [];
1049 result[ items[ i ].getGroupName() ].push( items[ i ] );
1050 flatResult.push( items[ i ] );
1051 }
1052 }
1053
1054 if ( $.isEmptyObject( result ) ) {
1055 // item containing the query string in their label, description, or group title
1056 for ( let i = 0; i < items.length; i++ ) {
1057 const groupTitle = items[ i ].getGroupModel().getTitle();
1058 if (
1059 searchIsEmpty ||
1060 items[ i ].getLabel().toLowerCase().indexOf( query ) > -1 ||
1061 items[ i ].getDescription().toLowerCase().indexOf( query ) > -1 ||
1062 groupTitle.toLowerCase().indexOf( query ) > -1 ||
1063 (
1064 // For tags, we want the parameter name to be included in the search
1065 view === 'tags' &&
1066 items[ i ].getParamName().toLowerCase().indexOf( query ) > -1
1067 )
1068 ) {
1069 result[ items[ i ].getGroupName() ] = result[ items[ i ].getGroupName() ] || [];
1070 result[ items[ i ].getGroupName() ].push( items[ i ] );
1071 flatResult.push( items[ i ] );
1072 }
1073 }
1074 }
1075
1076 return returnFlat ? flatResult : result;
1077 };
1078
1079 /**
1080 * Get items that are highlighted
1081 *
1082 * @ignore
1083 * @return {mw.rcfilters.dm.FilterItem[]} Highlighted items
1084 */
1085 FiltersViewModel.prototype.getHighlightedItems = function () {
1086 return this.getItems().filter( ( filterItem ) => filterItem.isHighlightSupported() &&
1087 filterItem.getHighlightColor() );
1088 };
1089
1090 /**
1091 * Get items that allow highlights even if they're not currently highlighted
1092 *
1093 * @ignore
1094 * @return {mw.rcfilters.dm.FilterItem[]} Items supporting highlights
1095 */
1096 FiltersViewModel.prototype.getItemsSupportingHighlights = function () {
1097 return this.getItems().filter( ( filterItem ) => filterItem.isHighlightSupported() );
1098 };
1099
1100 /**
1101 * Get all selected items
1102 *
1103 * @ignore
1104 * @return {mw.rcfilters.dm.FilterItem[]} Selected items
1105 */
1106 FiltersViewModel.prototype.findSelectedItems = function () {
1107 let allSelected = [];
1108
1109 // eslint-disable-next-line no-jquery/no-each-util
1110 $.each( this.getFilterGroups(), ( groupName, groupModel ) => {
1111 allSelected = allSelected.concat( groupModel.findSelectedItems() );
1112 } );
1113
1114 return allSelected;
1115 };
1116
1117 /**
1118 * Get the current view
1119 *
1120 * @return {string} Current view
1121 */
1122 FiltersViewModel.prototype.getCurrentView = function () {
1123 return this.currentView;
1124 };
1125
1126 /**
1127 * Get the label for the current view
1128 *
1129 * @param {string} viewName View name
1130 * @return {string} Label for the current view
1131 */
1132 FiltersViewModel.prototype.getViewTitle = function ( viewName ) {
1133 viewName = viewName || this.getCurrentView();
1134
1135 return this.views[ viewName ] && this.views[ viewName ].title;
1136 };
1137
1138 /**
1139 * Get the view that fits the given trigger
1140 *
1141 * @param {string} trigger Trigger
1142 * @return {string} Name of view
1143 */
1144 FiltersViewModel.prototype.getViewByTrigger = function ( trigger ) {
1145 let result = 'default';
1146
1147 // eslint-disable-next-line no-jquery/no-each-util
1148 $.each( this.views, ( name, data ) => {
1149 if ( data.trigger === trigger ) {
1150 result = name;
1151 }
1152 } );
1153
1154 return result;
1155 };
1156
1157 /**
1158 * Return a version of the given string that is without any
1159 * view triggers.
1160 *
1161 * @param {string} str Given string
1162 * @return {string} Result
1163 */
1164 FiltersViewModel.prototype.removeViewTriggers = function ( str ) {
1165 if ( this.getViewFromString( str ) !== 'default' ) {
1166 str = str.slice( 1 );
1167 }
1168
1169 return str;
1170 };
1171
1172 /**
1173 * Get the view from the given string by a trigger, if it exists
1174 *
1175 * @param {string} str Given string
1176 * @return {string} View name
1177 */
1178 FiltersViewModel.prototype.getViewFromString = function ( str ) {
1179 return this.getViewByTrigger( str.slice( 0, 1 ) );
1180 };
1181
1182 /**
1183 * Set the current search for the system.
1184 * This also dictates what items and groups are visible according
1185 * to the search in #findMatches
1186 *
1187 * @param {string} searchQuery Search query, including triggers
1188 * @fires searchChange
1189 */
1190 FiltersViewModel.prototype.setSearch = function ( searchQuery ) {
1191 let visibleGroups, visibleGroupNames;
1192
1193 if ( this.searchQuery !== searchQuery ) {
1194 // Check if the view changed
1195 this.switchView( this.getViewFromString( searchQuery ) );
1196
1197 visibleGroups = this.findMatches( searchQuery );
1198 visibleGroupNames = Object.keys( visibleGroups );
1199
1200 // Update visibility of items and groups
1201 // eslint-disable-next-line no-jquery/no-each-util
1202 $.each( this.getFilterGroups(), ( groupName, groupModel ) => {
1203 // Check if the group is visible at all
1204 groupModel.toggleVisible( visibleGroupNames.indexOf( groupName ) !== -1 );
1205 groupModel.setVisibleItems( visibleGroups[ groupName ] || [] );
1206 } );
1207
1208 this.searchQuery = searchQuery;
1209 this.emit( 'searchChange', this.searchQuery );
1210 }
1211 };
1212
1213 /**
1214 * Get the current search
1215 *
1216 * @return {string} Current search query
1217 */
1218 FiltersViewModel.prototype.getSearch = function () {
1219 return this.searchQuery;
1220 };
1221
1222 /**
1223 * Switch the current view
1224 *
1225 * @private
1226 * @param {string} view View name
1227 */
1228 FiltersViewModel.prototype.switchView = function ( view ) {
1229 if ( this.views[ view ] && this.currentView !== view ) {
1230 this.currentView = view;
1231 }
1232 };
1233
1234 /**
1235 * Toggle the highlight feature on and off.
1236 * Propagate the change to filter items.
1237 *
1238 * @param {boolean} enable Highlight should be enabled
1239 * @fires highlightChange
1240 */
1241 FiltersViewModel.prototype.toggleHighlight = function ( enable ) {
1242 enable = enable === undefined ? !this.highlightEnabled : enable;
1243
1244 if ( this.highlightEnabled !== enable ) {
1245 this.highlightEnabled = enable;
1246 this.emit( 'highlightChange', this.highlightEnabled );
1247 }
1248 };
1249
1250 /**
1251 * Check if the highlight feature is enabled
1252 *
1253 * @return {boolean}
1254 */
1255 FiltersViewModel.prototype.isHighlightEnabled = function () {
1256 return !!this.highlightEnabled;
1257 };
1258
1259 /**
1260 * Toggle the inverted tags property on and off.
1261 * Propagate the change to tag filter items.
1262 *
1263 * @param {boolean} enable Inverted property is enabled
1264 */
1265 FiltersViewModel.prototype.toggleInvertedTags = function ( enable ) {
1266 this.toggleFilterSelected( this.getTagsInvertModel().getName(), enable );
1267 };
1268
1269 /**
1270 * Toggle the inverted namespaces property on and off.
1271 * Propagate the change to namespace filter items.
1272 *
1273 * @param {boolean} enable Inverted property is enabled
1274 */
1275 FiltersViewModel.prototype.toggleInvertedNamespaces = function ( enable ) {
1276 this.toggleFilterSelected( this.getNamespacesInvertModel().getName(), enable );
1277 };
1278
1279 /**
1280 * Get the model object that represents the 'invert' filter
1281 *
1282 * @ignore
1283 * @param {string} view
1284 * @return {mw.rcfilters.dm.FilterItem|null}
1285 */
1286 FiltersViewModel.prototype.getInvertModel = function ( view ) {
1287 if ( view === 'namespaces' ) {
1288 return this.getNamespacesInvertModel();
1289 }
1290 if ( view === 'tags' ) {
1291 return this.getTagsInvertModel();
1292 }
1293
1294 return null;
1295 };
1296
1297 /**
1298 * Get the model object that represents the 'invert' filter
1299 *
1300 * @ignore
1301 * @return {mw.rcfilters.dm.FilterItem}
1302 */
1303 FiltersViewModel.prototype.getNamespacesInvertModel = function () {
1304 return this.getGroup( 'invertGroup' ).getItemByParamName( 'invert' );
1305 };
1306
1307 /**
1308 * Get the model object that represents the 'invert' filter
1309 *
1310 * @ignore
1311 * @return {mw.rcfilters.dm.FilterItem}
1312 */
1313 FiltersViewModel.prototype.getTagsInvertModel = function () {
1314 return this.getGroup( 'invertTagsGroup' ).getItemByParamName( 'inverttags' );
1315 };
1316
1317 /**
1318 * Set highlight color for a specific filter item
1319 *
1320 * @param {string} filterName Name of the filter item
1321 * @param {string} color Selected color
1322 */
1323 FiltersViewModel.prototype.setHighlightColor = function ( filterName, color ) {
1324 this.getItemByName( filterName ).setHighlightColor( color );
1325 };
1326
1327 /**
1328 * Clear highlight for a specific filter item
1329 *
1330 * @param {string} filterName Name of the filter item
1331 */
1332 FiltersViewModel.prototype.clearHighlightColor = function ( filterName ) {
1333 this.getItemByName( filterName ).clearHighlightColor();
1334 };
1335
1336 module.exports = FiltersViewModel;