3 * View model for the filters selection and display
5 * @mixins OO.EventEmitter
6 * @mixins OO.EmitterList
10 mw
.rcfilters
.dm
.FiltersViewModel
= function MwRcfiltersDmFiltersViewModel() {
12 OO
.EventEmitter
.call( this );
13 OO
.EmitterList
.call( this );
16 this.defaultParams
= {};
17 this.defaultFiltersEmpty
= null;
18 this.highlightEnabled
= false;
21 this.aggregate( { update
: 'filterItemUpdate' } );
22 this.connect( this, { filterItemUpdate
: [ 'emit', 'itemUpdate' ] } );
26 OO
.initClass( mw
.rcfilters
.dm
.FiltersViewModel
);
27 OO
.mixinClass( mw
.rcfilters
.dm
.FiltersViewModel
, OO
.EventEmitter
);
28 OO
.mixinClass( mw
.rcfilters
.dm
.FiltersViewModel
, OO
.EmitterList
);
35 * Filter list is initialized
40 * @param {mw.rcfilters.dm.FilterItem} item Filter item updated
42 * Filter item has changed
46 * @event highlightChange
47 * @param {boolean} Highlight feature is enabled
49 * Highlight feature has been toggled enabled or disabled
55 * Re-assess the states of filter items based on the interactions between them
57 * @param {mw.rcfilters.dm.FilterItem} [item] Changed item. If not given, the
58 * method will go over the state of all items
60 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.reassessFilterInteractions = function ( item
) {
63 iterationItems
= item
!== undefined ? [ item
] : this.getItems();
65 iterationItems
.forEach( function ( checkedItem
) {
66 var allCheckedItems
= checkedItem
.getSubset().concat( [ checkedItem
.getName() ] ),
67 groupModel
= checkedItem
.getGroupModel();
69 // Check for subsets (included filters) plus the item itself:
70 allCheckedItems
.forEach( function ( filterItemName
) {
71 var itemInSubset
= model
.getItemByName( filterItemName
);
73 itemInSubset
.toggleIncluded(
74 // If any of itemInSubset's supersets are selected, this item
76 itemInSubset
.getSuperset().some( function ( supersetName
) {
77 return ( model
.getItemByName( supersetName
).isSelected() );
82 // Update coverage for the changed group
83 if ( groupModel
.isFullCoverage() ) {
84 allSelected
= groupModel
.areAllSelected();
85 groupModel
.getItems().forEach( function ( filterItem
) {
86 filterItem
.toggleFullyCovered( allSelected
);
91 // Check for conflicts
92 // In this case, we must go over all items, since
93 // conflicts are bidirectional and depend not only on
94 // individual items, but also on the selected states of
95 // the groups they're in.
96 this.getItems().forEach( function ( filterItem
) {
97 var inConflict
= false,
98 filterItemGroup
= filterItem
.getGroupModel();
100 // For each item, see if that item is still conflicting
101 $.each( model
.groups
, function ( groupName
, groupModel
) {
102 if ( filterItem
.getGroupName() === groupName
) {
103 // Check inside the group
104 inConflict
= groupModel
.areAnySelectedInConflictWith( filterItem
);
106 // According to the spec, if two items conflict from two different
107 // groups, the conflict only lasts if the groups **only have selected
108 // items that are conflicting**. If a group has selected items that
109 // are conflicting and non-conflicting, the scope of the result has
110 // expanded enough to completely remove the conflict.
112 // For example, see two groups with conflicts:
115 // name: 'experienced',
116 // conflicts: [ 'unregistered' ]
121 // name: 'registered',
124 // name: 'unregistered',
127 // If we select 'experienced', then 'unregistered' is in conflict (and vice versa),
128 // because, inherently, 'experienced' filter only includes registered users, and so
129 // both filters are in conflict with one another.
130 // However, the minute we select 'registered', the scope of our results
131 // has expanded to no longer have a conflict with 'experienced' filter, and
132 // so the conflict is removed.
134 // In our case, we need to check if the entire group conflicts with
135 // the entire item's group, so we follow the above spec
137 // The foreign group is in conflict with this item
138 groupModel
.areAllSelectedInConflictWith( filterItem
) &&
139 // Every selected member of the item's own group is also
140 // in conflict with the other group
141 filterItemGroup
.getSelectedItems().every( function ( otherGroupItem
) {
142 return groupModel
.areAllSelectedInConflictWith( otherGroupItem
);
147 // If we're in conflict, this will return 'false' which
148 // will break the loop. Otherwise, we're not in conflict
149 // and the loop continues
153 // Toggle the item state
154 filterItem
.toggleConflicted( inConflict
);
159 * Set filters and preserve a group relationship based on
160 * the definition given by an object
162 * @param {Object} filters Filter group definition
164 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.initializeFilters = function ( filters
) {
165 var i
, filterItem
, selectedFilterNames
,
168 addArrayElementsUnique = function ( arr
, elements
) {
169 elements
= Array
.isArray( elements
) ? elements
: [ elements
];
171 elements
.forEach( function ( element
) {
172 if ( arr
.indexOf( element
) === -1 ) {
186 $.each( filters
, function ( group
, data
) {
187 if ( !model
.groups
[ group
] ) {
188 model
.groups
[ group
] = new mw
.rcfilters
.dm
.FilterGroup( group
, {
191 separator
: data
.separator
,
192 fullCoverage
: !!data
.fullCoverage
196 selectedFilterNames
= [];
197 for ( i
= 0; i
< data
.filters
.length
; i
++ ) {
198 filterItem
= new mw
.rcfilters
.dm
.FilterItem( data
.filters
[ i
].name
, model
.groups
[ group
], {
200 label
: data
.filters
[ i
].label
,
201 description
: data
.filters
[ i
].description
,
202 subset
: data
.filters
[ i
].subset
,
203 cssClass
: data
.filters
[ i
].class
206 // For convenience, we should store each filter's "supersets" -- these are
207 // the filters that have that item in their subset list. This will just
208 // make it easier to go through whether the item has any other items
209 // that affect it (and are selected) at any given time
210 if ( data
.filters
[ i
].subset
) {
211 data
.filters
[ i
].subset
.forEach( function ( subsetFilterName
) { // eslint-disable-line no-loop-func
212 supersetMap
[ subsetFilterName
] = supersetMap
[ subsetFilterName
] || [];
213 addArrayElementsUnique(
214 supersetMap
[ subsetFilterName
],
220 // Conflicts are bi-directional, which means FilterA can define having
221 // a conflict with FilterB, and this conflict should appear in **both**
222 // filter definitions.
223 // We need to remap all the 'conflicts' so they reflect the entire state
224 // in either direction regardless of which filter defined the other as conflicting.
225 if ( data
.filters
[ i
].conflicts
) {
226 conflictMap
[ filterItem
.getName() ] = conflictMap
[ filterItem
.getName() ] || [];
227 addArrayElementsUnique(
228 conflictMap
[ filterItem
.getName() ],
229 data
.filters
[ i
].conflicts
232 data
.filters
[ i
].conflicts
.forEach( function ( conflictingFilterName
) { // eslint-disable-line no-loop-func
233 // Add this filter to the conflicts of each of the filters in its list
234 conflictMap
[ conflictingFilterName
] = conflictMap
[ conflictingFilterName
] || [];
235 addArrayElementsUnique(
236 conflictMap
[ conflictingFilterName
],
242 if ( data
.type
=== 'send_unselected_if_any' ) {
243 // Store the default parameter state
244 // For this group type, parameter values are direct
245 model
.defaultParams
[ data
.filters
[ i
].name
] = Number( !!data
.filters
[ i
].default );
247 data
.type
=== 'string_options' &&
248 data
.filters
[ i
].default
250 selectedFilterNames
.push( data
.filters
[ i
].name
);
253 model
.groups
[ group
].addItems( filterItem
);
254 items
.push( filterItem
);
257 if ( data
.type
=== 'string_options' ) {
258 // Store the default parameter group state
259 // For this group, the parameter is group name and value is the names
261 model
.defaultParams
[ group
] = model
.sanitizeStringOptionGroup( group
, selectedFilterNames
).join( model
.groups
[ group
].getSeparator() );
265 items
.forEach( function ( filterItem
) {
266 // Apply conflict map to the items
267 // Now that we mapped all items and conflicts bi-directionally
268 // we need to apply the definition to each filter again
269 filterItem
.setConflicts( conflictMap
[ filterItem
.getName() ] );
271 // Apply the superset map
272 filterItem
.setSuperset( supersetMap
[ filterItem
.getName() ] );
275 // Add items to the model
276 this.addItems( items
);
278 this.emit( 'initialize' );
282 * Get the names of all available filters
284 * @return {string[]} An array of filter names
286 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getFilterNames = function () {
287 return this.getItems().map( function ( item
) { return item
.getName(); } );
291 * Get the object that defines groups by their name.
293 * @return {Object} Filter groups
295 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getFilterGroups = function () {
300 * Get the value of a specific parameter
302 * @param {string} name Parameter name
303 * @return {number|string} Parameter value
305 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getParamValue = function ( name
) {
306 return this.parameters
[ name
];
310 * Get the current selected state of the filters
312 * @return {Object} Filters selected state
314 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getSelectedState = function () {
316 items
= this.getItems(),
319 for ( i
= 0; i
< items
.length
; i
++ ) {
320 result
[ items
[ i
].getName() ] = items
[ i
].isSelected();
327 * Get the current full state of the filters
329 * @return {Object} Filters full state
331 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getFullState = function () {
333 items
= this.getItems(),
336 for ( i
= 0; i
< items
.length
; i
++ ) {
337 result
[ items
[ i
].getName() ] = {
338 selected
: items
[ i
].isSelected(),
339 conflicted
: items
[ i
].isConflicted(),
340 included
: items
[ i
].isIncluded()
348 * Get the default parameters object
350 * @return {Object} Default parameter values
352 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getDefaultParams = function () {
353 return this.defaultParams
;
357 * Set all filter states to default values
359 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.setFiltersToDefaults = function () {
360 var defaultFilterStates
= this.getFiltersFromParameters( this.getDefaultParams() );
362 this.toggleFiltersSelected( defaultFilterStates
);
366 * Analyze the groups and their filters and output an object representing
367 * the state of the parameters they represent.
369 * @param {Object} [filterGroups] An object defining the filter groups to
370 * translate to parameters. Its structure must follow that of this.groups
371 * see #getFilterGroups
372 * @return {Object} Parameter state object
374 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getParametersFromFilters = function ( filterGroups
) {
375 var i
, filterItems
, anySelected
, values
,
377 groupItems
= filterGroups
|| this.getFilterGroups();
379 $.each( groupItems
, function ( group
, model
) {
380 filterItems
= model
.getItems();
382 if ( model
.getType() === 'send_unselected_if_any' ) {
383 // First, check if any of the items are selected at all.
384 // If none is selected, we're treating it as if they are
386 anySelected
= filterItems
.some( function ( filterItem
) {
387 return filterItem
.isSelected();
390 // Go over the items and define the correct values
391 for ( i
= 0; i
< filterItems
.length
; i
++ ) {
392 result
[ filterItems
[ i
].getName() ] = anySelected
?
393 Number( !filterItems
[ i
].isSelected() ) : 0;
395 } else if ( model
.getType() === 'string_options' ) {
397 for ( i
= 0; i
< filterItems
.length
; i
++ ) {
398 if ( filterItems
[ i
].isSelected() ) {
399 values
.push( filterItems
[ i
].getName() );
403 if ( values
.length
=== 0 || values
.length
=== filterItems
.length
) {
404 result
[ group
] = 'all';
406 result
[ group
] = values
.join( model
.getSeparator() );
415 * Get the highlight parameters based on current filter configuration
417 * @return {object} Object where keys are "<filter name>_color" and values
418 * are the selected highlight colors.
420 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getHighlightParameters = function () {
421 var result
= { highlight
: Number( this.isHighlightEnabled() ) };
423 this.getItems().forEach( function ( filterItem
) {
424 result
[ filterItem
.getName() + '_color' ] = filterItem
.getHighlightColor();
430 * Sanitize value group of a string_option groups type
431 * Remove duplicates and make sure to only use valid
435 * @param {string} groupName Group name
436 * @param {string[]} valueArray Array of values
437 * @return {string[]} Array of valid values
439 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.sanitizeStringOptionGroup = function( groupName
, valueArray
) {
441 validNames
= this.getGroupFilters( groupName
).map( function ( filterItem
) {
442 return filterItem
.getName();
445 if ( valueArray
.indexOf( 'all' ) > -1 ) {
446 // If anywhere in the values there's 'all', we
447 // treat it as if only 'all' was selected.
448 // Example: param=valid1,valid2,all
453 // Get rid of any dupe and invalid parameter, only output
455 // Example: param=valid1,valid2,invalid1,valid1
456 // Result: param=valid1,valid2
457 valueArray
.forEach( function ( value
) {
459 validNames
.indexOf( value
) > -1 &&
460 result
.indexOf( value
) === -1
462 result
.push( value
);
470 * Check whether the current filter state is set to all false.
472 * @return {boolean} Current filters are all empty
474 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.areCurrentFiltersEmpty = function () {
475 // Check if there are either any selected items or any items
476 // that have highlight enabled
477 return !this.getItems().some( function ( filterItem
) {
478 return filterItem
.isSelected() || filterItem
.isHighlighted();
483 * Check whether the default values of the filters are all false.
485 * @return {boolean} Default filters are all false
487 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.areDefaultFiltersEmpty = function () {
490 if ( this.defaultFiltersEmpty
!== null ) {
491 // We only need to do this test once,
492 // because defaults are set once per session
493 defaultFilters
= this.getFiltersFromParameters();
494 this.defaultFiltersEmpty
= Object
.keys( defaultFilters
).every( function ( filterName
) {
495 return !defaultFilters
[ filterName
];
499 return this.defaultFiltersEmpty
;
503 * This is the opposite of the #getParametersFromFilters method; this goes over
504 * the given parameters and translates into a selected/unselected value in the filters.
506 * @param {Object} params Parameters query object
507 * @return {Object} Filter state object
509 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getFiltersFromParameters = function ( params
) {
513 base
= this.getDefaultParams(),
516 params
= $.extend( {}, base
, params
);
518 $.each( params
, function ( paramName
, paramValue
) {
519 // Find the filter item
520 filterItem
= model
.getItemByName( paramName
);
521 // Ignore if no filter item exists
523 groupMap
[ filterItem
.getGroupName() ] = groupMap
[ filterItem
.getGroupName() ] || {};
525 // Mark the group if it has any items that are selected
526 groupMap
[ filterItem
.getGroupName() ].hasSelected
= (
527 groupMap
[ filterItem
.getGroupName() ].hasSelected
||
528 !!Number( paramValue
)
531 // Add the relevant filter into the group map
532 groupMap
[ filterItem
.getGroupName() ].filters
= groupMap
[ filterItem
.getGroupName() ].filters
|| [];
533 groupMap
[ filterItem
.getGroupName() ].filters
.push( filterItem
);
534 } else if ( model
.groups
.hasOwnProperty( paramName
) ) {
535 // This parameter represents a group (values are the filters)
536 // this is equivalent to checking if the group is 'string_options'
537 groupMap
[ paramName
] = { filters
: model
.groups
[ paramName
].getItems() };
541 // Now that we know the groups' selection states, we need to go over
542 // the filters in the groups and mark their selected states appropriately
543 $.each( groupMap
, function ( group
, data
) {
544 var paramValues
, filterItem
,
545 allItemsInGroup
= data
.filters
;
547 if ( model
.groups
[ group
].getType() === 'send_unselected_if_any' ) {
548 for ( i
= 0; i
< allItemsInGroup
.length
; i
++ ) {
549 filterItem
= allItemsInGroup
[ i
];
551 result
[ filterItem
.getName() ] = data
.hasSelected
?
552 // Flip the definition between the parameter
553 // state and the filter state
554 // This is what the 'toggleSelected' value of the filter is
555 !Number( params
[ filterItem
.getName() ] ) :
556 // Otherwise, there are no selected items in the
557 // group, which means the state is false
560 } else if ( model
.groups
[ group
].getType() === 'string_options' ) {
561 paramValues
= model
.sanitizeStringOptionGroup( group
, params
[ group
].split( model
.groups
[ group
].getSeparator() ) );
563 for ( i
= 0; i
< allItemsInGroup
.length
; i
++ ) {
564 filterItem
= allItemsInGroup
[ i
];
566 result
[ filterItem
.getName() ] = (
567 // If it is the word 'all'
568 paramValues
.length
=== 1 && paramValues
[ 0 ] === 'all' ||
569 // All values are written
570 paramValues
.length
=== model
.groups
[ group
].getItemCount()
572 // All true (either because all values are written or the term 'all' is written)
573 // is the same as all filters set to false
575 // Otherwise, the filter is selected only if it appears in the parameter values
576 paramValues
.indexOf( filterItem
.getName() ) > -1;
584 * Get the item that matches the given name
586 * @param {string} name Filter name
587 * @return {mw.rcfilters.dm.FilterItem} Filter item
589 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getItemByName = function ( name
) {
590 return this.getItems().filter( function ( item
) {
591 return name
=== item
.getName();
596 * Set all filters to false or empty/all
597 * This is equivalent to display all.
599 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.emptyAllFilters = function () {
600 this.getItems().forEach( function ( filterItem
) {
601 this.toggleFilterSelected( filterItem
.getName(), false );
606 * Toggle selected state of one item
608 * @param {string} name Name of the filter item
609 * @param {boolean} [isSelected] Filter selected state
611 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.toggleFilterSelected = function ( name
, isSelected
) {
612 this.getItemByName( name
).toggleSelected( isSelected
);
616 * Toggle selected state of items by their names
618 * @param {Object} filterDef Filter definitions
620 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.toggleFiltersSelected = function ( filterDef
) {
621 Object
.keys( filterDef
).forEach( function ( name
) {
622 this.toggleFilterSelected( name
, filterDef
[ name
] );
627 * Get a group model from its name
629 * @param {string} groupName Group name
630 * @return {mw.rcfilters.dm.FilterGroup} Group model
632 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getGroup = function ( groupName
) {
633 return this.groups
[ groupName
];
637 * Get all filters within a specified group by its name
639 * @param {string} groupName Group name
640 * @return {mw.rcfilters.dm.FilterItem[]} Filters belonging to this group
642 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getGroupFilters = function ( groupName
) {
643 return ( this.getGroup( groupName
) && this.getGroup( groupName
).getItems() ) || [];
647 * Find items whose labels match the given string
649 * @param {string} query Search string
650 * @return {Object} An object of items to show
651 * arranged by their group names
653 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.findMatches = function ( query
) {
657 items
= this.getItems();
659 // Normalize so we can search strings regardless of case
660 query
= query
.toLowerCase();
662 // item label starting with the query string
663 for ( i
= 0; i
< items
.length
; i
++ ) {
664 if ( items
[ i
].getLabel().toLowerCase().indexOf( query
) === 0 ) {
665 result
[ items
[ i
].getGroupName() ] = result
[ items
[ i
].getGroupName() ] || [];
666 result
[ items
[ i
].getGroupName() ].push( items
[ i
] );
670 if ( $.isEmptyObject( result
) ) {
671 // item containing the query string in their label, description, or group title
672 for ( i
= 0; i
< items
.length
; i
++ ) {
673 groupTitle
= items
[ i
].getGroupModel().getTitle();
675 items
[ i
].getLabel().toLowerCase().indexOf( query
) > -1 ||
676 items
[ i
].getDescription().toLowerCase().indexOf( query
) > -1 ||
677 groupTitle
.toLowerCase().indexOf( query
) > -1
679 result
[ items
[ i
].getGroupName() ] = result
[ items
[ i
].getGroupName() ] || [];
680 result
[ items
[ i
].getGroupName() ].push( items
[ i
] );
689 * Get items that are highlighted
691 * @return {mw.rcfilters.dm.FilterItem[]} Highlighted items
693 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getHighlightedItems = function () {
694 return this.getItems().filter( function ( filterItem
) {
695 return filterItem
.isHighlightSupported() &&
696 filterItem
.getHighlightColor();
701 * Toggle the highlight feature on and off.
702 * Propagate the change to filter items.
704 * @param {boolean} enable Highlight should be enabled
705 * @fires highlightChange
707 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.toggleHighlight = function ( enable
) {
708 enable
= enable
=== undefined ? !this.highlightEnabled
: enable
;
710 if ( this.highlightEnabled
!== enable
) {
711 this.highlightEnabled
= enable
;
713 this.getItems().forEach( function ( filterItem
) {
714 filterItem
.toggleHighlight( this.highlightEnabled
);
717 this.emit( 'highlightChange', this.highlightEnabled
);
722 * Check if the highlight feature is enabled
725 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.isHighlightEnabled = function () {
726 return !!this.highlightEnabled
;
730 * Set highlight color for a specific filter item
732 * @param {string} filterName Name of the filter item
733 * @param {string} color Selected color
735 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.setHighlightColor = function ( filterName
, color
) {
736 this.getItemByName( filterName
).setHighlightColor( color
);
740 * Clear highlight for a specific filter item
742 * @param {string} filterName Name of the filter item
744 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.clearHighlightColor = function ( filterName
) {
745 this.getItemByName( filterName
).clearHighlightColor();
749 * Clear highlight for all filter items
751 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.clearAllHighlightColors = function () {
752 this.getItems().forEach( function ( filterItem
) {
753 filterItem
.clearHighlightColor();
756 }( mediaWiki
, jQuery
) );