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.updateFilters( 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
: 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 () {
477 // Check if there are either any selected items or any items
478 // that have highlight enabled
479 return !this.getItems().some( function ( filterItem
) {
481 filterItem
.isSelected() ||
482 ( model
.isHighlightEnabled() && filterItem
.getHighlightColor() )
488 * Check whether the default values of the filters are all false.
490 * @return {boolean} Default filters are all false
492 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.areDefaultFiltersEmpty = function () {
495 if ( this.defaultFiltersEmpty
!== null ) {
496 // We only need to do this test once,
497 // because defaults are set once per session
498 defaultFilters
= this.getFiltersFromParameters();
499 this.defaultFiltersEmpty
= Object
.keys( defaultFilters
).every( function ( filterName
) {
500 return !defaultFilters
[ filterName
];
504 return this.defaultFiltersEmpty
;
508 * This is the opposite of the #getParametersFromFilters method; this goes over
509 * the given parameters and translates into a selected/unselected value in the filters.
511 * @param {Object} params Parameters query object
512 * @return {Object} Filter state object
514 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getFiltersFromParameters = function ( params
) {
518 base
= this.getDefaultParams(),
521 params
= $.extend( {}, base
, params
);
523 $.each( params
, function ( paramName
, paramValue
) {
524 // Find the filter item
525 filterItem
= model
.getItemByName( paramName
);
526 // Ignore if no filter item exists
528 groupMap
[ filterItem
.getGroupName() ] = groupMap
[ filterItem
.getGroupName() ] || {};
530 // Mark the group if it has any items that are selected
531 groupMap
[ filterItem
.getGroupName() ].hasSelected
= (
532 groupMap
[ filterItem
.getGroupName() ].hasSelected
||
533 !!Number( paramValue
)
536 // Add the relevant filter into the group map
537 groupMap
[ filterItem
.getGroupName() ].filters
= groupMap
[ filterItem
.getGroupName() ].filters
|| [];
538 groupMap
[ filterItem
.getGroupName() ].filters
.push( filterItem
);
539 } else if ( model
.groups
.hasOwnProperty( paramName
) ) {
540 // This parameter represents a group (values are the filters)
541 // this is equivalent to checking if the group is 'string_options'
542 groupMap
[ paramName
] = { filters
: model
.groups
[ paramName
].getItems() };
546 // Now that we know the groups' selection states, we need to go over
547 // the filters in the groups and mark their selected states appropriately
548 $.each( groupMap
, function ( group
, data
) {
549 var paramValues
, filterItem
,
550 allItemsInGroup
= data
.filters
;
552 if ( model
.groups
[ group
].getType() === 'send_unselected_if_any' ) {
553 for ( i
= 0; i
< allItemsInGroup
.length
; i
++ ) {
554 filterItem
= allItemsInGroup
[ i
];
556 result
[ filterItem
.getName() ] = data
.hasSelected
?
557 // Flip the definition between the parameter
558 // state and the filter state
559 // This is what the 'toggleSelected' value of the filter is
560 !Number( params
[ filterItem
.getName() ] ) :
561 // Otherwise, there are no selected items in the
562 // group, which means the state is false
565 } else if ( model
.groups
[ group
].getType() === 'string_options' ) {
566 paramValues
= model
.sanitizeStringOptionGroup( group
, params
[ group
].split( model
.groups
[ group
].getSeparator() ) );
568 for ( i
= 0; i
< allItemsInGroup
.length
; i
++ ) {
569 filterItem
= allItemsInGroup
[ i
];
571 result
[ filterItem
.getName() ] = (
572 // If it is the word 'all'
573 paramValues
.length
=== 1 && paramValues
[ 0 ] === 'all' ||
574 // All values are written
575 paramValues
.length
=== model
.groups
[ group
].getItemCount()
577 // All true (either because all values are written or the term 'all' is written)
578 // is the same as all filters set to false
580 // Otherwise, the filter is selected only if it appears in the parameter values
581 paramValues
.indexOf( filterItem
.getName() ) > -1;
589 * Get the item that matches the given name
591 * @param {string} name Filter name
592 * @return {mw.rcfilters.dm.FilterItem} Filter item
594 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getItemByName = function ( name
) {
595 return this.getItems().filter( function ( item
) {
596 return name
=== item
.getName();
601 * Set all filters to false or empty/all
602 * This is equivalent to display all.
604 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.emptyAllFilters = function () {
607 this.getItems().forEach( function ( filterItem
) {
608 filters
[ filterItem
.getName() ] = false;
612 this.updateFilters( filters
);
616 * Toggle selected state of items by their names
618 * @param {Object} filterDef Filter definitions
620 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.updateFilters = function ( filterDef
) {
621 var name
, filterItem
;
623 for ( name
in filterDef
) {
624 filterItem
= this.getItemByName( name
);
625 filterItem
.toggleSelected( filterDef
[ name
] );
630 * Get a group model from its name
632 * @param {string} groupName Group name
633 * @return {mw.rcfilters.dm.FilterGroup} Group model
635 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getGroup = function ( groupName
) {
636 return this.groups
[ groupName
];
640 * Get all filters within a specified group by its name
642 * @param {string} groupName Group name
643 * @return {mw.rcfilters.dm.FilterItem[]} Filters belonging to this group
645 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getGroupFilters = function ( groupName
) {
646 return ( this.getGroup( groupName
) && this.getGroup( groupName
).getItems() ) || [];
650 * Find items whose labels match the given string
652 * @param {string} query Search string
653 * @return {Object} An object of items to show
654 * arranged by their group names
656 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.findMatches = function ( query
) {
660 items
= this.getItems();
662 // Normalize so we can search strings regardless of case
663 query
= query
.toLowerCase();
665 // item label starting with the query string
666 for ( i
= 0; i
< items
.length
; i
++ ) {
667 if ( items
[ i
].getLabel().toLowerCase().indexOf( query
) === 0 ) {
668 result
[ items
[ i
].getGroupName() ] = result
[ items
[ i
].getGroupName() ] || [];
669 result
[ items
[ i
].getGroupName() ].push( items
[ i
] );
673 if ( $.isEmptyObject( result
) ) {
674 // item containing the query string in their label, description, or group title
675 for ( i
= 0; i
< items
.length
; i
++ ) {
676 groupTitle
= items
[ i
].getGroupModel().getTitle();
678 items
[ i
].getLabel().toLowerCase().indexOf( query
) > -1 ||
679 items
[ i
].getDescription().toLowerCase().indexOf( query
) > -1 ||
680 groupTitle
.toLowerCase().indexOf( query
) > -1
682 result
[ items
[ i
].getGroupName() ] = result
[ items
[ i
].getGroupName() ] || [];
683 result
[ items
[ i
].getGroupName() ].push( items
[ i
] );
692 * Get items that are highlighted
694 * @return {mw.rcfilters.dm.FilterItem[]} Highlighted items
696 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getHighlightedItems = function () {
697 return this.getItems().filter( function ( filterItem
) {
698 return filterItem
.isHighlightSupported() &&
699 filterItem
.getHighlightColor();
704 * Toggle the highlight feature on and off.
705 * Propagate the change to filter items.
707 * @param {boolean} enable Highlight should be enabled
708 * @fires highlightChange
710 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.toggleHighlight = function ( enable
) {
711 enable
= enable
=== undefined ? !this.highlightEnabled
: enable
;
713 if ( this.highlightEnabled
!== enable
) {
714 this.highlightEnabled
= enable
;
716 this.getItems().forEach( function ( filterItem
) {
717 filterItem
.toggleHighlight( this.highlightEnabled
);
720 this.emit( 'highlightChange', this.highlightEnabled
);
725 * Check if the highlight feature is enabled
728 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.isHighlightEnabled = function () {
729 return this.highlightEnabled
;
733 * Set highlight color for a specific filter item
735 * @param {string} filterName Name of the filter item
736 * @param {string} color Selected color
738 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.setHighlightColor = function ( filterName
, color
) {
739 this.getItemByName( filterName
).setHighlightColor( color
);
743 * Clear highlight for a specific filter item
745 * @param {string} filterName Name of the filter item
747 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.clearHighlightColor = function ( filterName
) {
748 this.getItemByName( filterName
).clearHighlightColor();
752 * Clear highlight for all filter items
754 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.clearAllHighlightColors = function () {
755 this.getItems().forEach( function ( filterItem
) {
756 filterItem
.clearHighlightColor();
759 }( mediaWiki
, jQuery
) );