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;
19 this.parameterMap
= {};
22 this.aggregate( { update
: 'filterItemUpdate' } );
23 this.connect( this, { filterItemUpdate
: [ 'emit', 'itemUpdate' ] } );
27 OO
.initClass( mw
.rcfilters
.dm
.FiltersViewModel
);
28 OO
.mixinClass( mw
.rcfilters
.dm
.FiltersViewModel
, OO
.EventEmitter
);
29 OO
.mixinClass( mw
.rcfilters
.dm
.FiltersViewModel
, OO
.EmitterList
);
36 * Filter list is initialized
41 * @param {mw.rcfilters.dm.FilterItem} item Filter item updated
43 * Filter item has changed
47 * @event highlightChange
48 * @param {boolean} Highlight feature is enabled
50 * Highlight feature has been toggled enabled or disabled
56 * Re-assess the states of filter items based on the interactions between them
58 * @param {mw.rcfilters.dm.FilterItem} [item] Changed item. If not given, the
59 * method will go over the state of all items
61 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.reassessFilterInteractions = function ( item
) {
64 iterationItems
= item
!== undefined ? [ item
] : this.getItems();
66 iterationItems
.forEach( function ( checkedItem
) {
67 var allCheckedItems
= checkedItem
.getSubset().concat( [ checkedItem
.getName() ] ),
68 groupModel
= checkedItem
.getGroupModel();
70 // Check for subsets (included filters) plus the item itself:
71 allCheckedItems
.forEach( function ( filterItemName
) {
72 var itemInSubset
= model
.getItemByName( filterItemName
);
74 itemInSubset
.toggleIncluded(
75 // If any of itemInSubset's supersets are selected, this item
77 itemInSubset
.getSuperset().some( function ( supersetName
) {
78 return ( model
.getItemByName( supersetName
).isSelected() );
83 // Update coverage for the changed group
84 if ( groupModel
.isFullCoverage() ) {
85 allSelected
= groupModel
.areAllSelected();
86 groupModel
.getItems().forEach( function ( filterItem
) {
87 filterItem
.toggleFullyCovered( allSelected
);
92 // Check for conflicts
93 // In this case, we must go over all items, since
94 // conflicts are bidirectional and depend not only on
95 // individual items, but also on the selected states of
96 // the groups they're in.
97 this.getItems().forEach( function ( filterItem
) {
98 var inConflict
= false,
99 filterItemGroup
= filterItem
.getGroupModel();
101 // For each item, see if that item is still conflicting
102 $.each( model
.groups
, function ( groupName
, groupModel
) {
103 if ( filterItem
.getGroupName() === groupName
) {
104 // Check inside the group
105 inConflict
= groupModel
.areAnySelectedInConflictWith( filterItem
);
107 // According to the spec, if two items conflict from two different
108 // groups, the conflict only lasts if the groups **only have selected
109 // items that are conflicting**. If a group has selected items that
110 // are conflicting and non-conflicting, the scope of the result has
111 // expanded enough to completely remove the conflict.
113 // For example, see two groups with conflicts:
116 // name: 'experienced',
117 // conflicts: [ 'unregistered' ]
122 // name: 'registered',
125 // name: 'unregistered',
128 // If we select 'experienced', then 'unregistered' is in conflict (and vice versa),
129 // because, inherently, 'experienced' filter only includes registered users, and so
130 // both filters are in conflict with one another.
131 // However, the minute we select 'registered', the scope of our results
132 // has expanded to no longer have a conflict with 'experienced' filter, and
133 // so the conflict is removed.
135 // In our case, we need to check if the entire group conflicts with
136 // the entire item's group, so we follow the above spec
138 // The foreign group is in conflict with this item
139 groupModel
.areAllSelectedInConflictWith( filterItem
) &&
140 // Every selected member of the item's own group is also
141 // in conflict with the other group
142 filterItemGroup
.getSelectedItems().every( function ( otherGroupItem
) {
143 return groupModel
.areAllSelectedInConflictWith( otherGroupItem
);
148 // If we're in conflict, this will return 'false' which
149 // will break the loop. Otherwise, we're not in conflict
150 // and the loop continues
154 // Toggle the item state
155 filterItem
.toggleConflicted( inConflict
);
160 * Set filters and preserve a group relationship based on
161 * the definition given by an object
163 * @param {Array} filters Filter group definition
165 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.initializeFilters = function ( filters
) {
166 var i
, filterItem
, selectedFilterNames
, filterConflictResult
, groupConflictResult
, subsetNames
,
170 groupConflictMap
= {},
171 filterConflictMap
= {},
172 addArrayElementsUnique = function ( arr
, elements
) {
173 elements
= Array
.isArray( elements
) ? elements
: [ elements
];
175 elements
.forEach( function ( element
) {
176 if ( arr
.indexOf( element
) === -1 ) {
183 expandConflictDefinitions = function ( obj
) {
186 $.each( obj
, function ( key
, conflicts
) {
188 adjustedConflicts
= {};
190 conflicts
.forEach( function ( conflict
) {
191 if ( conflict
.filter
) {
192 filterName
= model
.groups
[ conflict
.group
].getNamePrefix() + conflict
.filter
;
195 adjustedConflicts
[ filterName
] = $.extend(
198 { filter
: filterName
}
201 // This conflict is for an entire group. Split it up to
202 // represent each filter
204 // Get the relevant group items
205 model
.groups
[ conflict
.group
].getItems().forEach( function ( groupItem
) {
206 // Rebuild the conflict
207 adjustedConflicts
[ groupItem
.getName() ] = $.extend(
210 { filter
: groupItem
.getName() }
216 result
[ key
] = adjustedConflicts
;
226 filters
.forEach( function ( data
) {
227 var group
= data
.name
;
229 if ( !model
.groups
[ group
] ) {
230 model
.groups
[ group
] = new mw
.rcfilters
.dm
.FilterGroup( group
, {
232 title
: mw
.msg( data
.title
),
233 separator
: data
.separator
,
234 fullCoverage
: !!data
.fullCoverage
238 if ( data
.conflicts
) {
239 groupConflictMap
[ group
] = data
.conflicts
;
242 selectedFilterNames
= [];
243 for ( i
= 0; i
< data
.filters
.length
; i
++ ) {
244 data
.filters
[ i
].subset
= data
.filters
[ i
].subset
|| [];
245 data
.filters
[ i
].subset
= data
.filters
[ i
].subset
.map( function ( el
) {
249 filterItem
= new mw
.rcfilters
.dm
.FilterItem( data
.filters
[ i
].name
, model
.groups
[ group
], {
251 label
: mw
.msg( data
.filters
[ i
].label
),
252 description
: mw
.msg( data
.filters
[ i
].description
),
253 cssClass
: data
.filters
[ i
].cssClass
256 if ( data
.filters
[ i
].subset
) {
258 data
.filters
[ i
].subset
.forEach( function ( subsetFilterName
) { // eslint-disable-line no-loop-func
259 var subsetName
= model
.groups
[ group
].getNamePrefix() + subsetFilterName
;
260 // For convenience, we should store each filter's "supersets" -- these are
261 // the filters that have that item in their subset list. This will just
262 // make it easier to go through whether the item has any other items
263 // that affect it (and are selected) at any given time
264 supersetMap
[ subsetName
] = supersetMap
[ subsetName
] || [];
265 addArrayElementsUnique(
266 supersetMap
[ subsetName
],
270 // Translate subset param name to add the group name, so we
271 // get consistent naming. We know that subsets are only within
273 subsetNames
.push( subsetName
);
276 // Set translated subset
277 filterItem
.setSubset( subsetNames
);
281 if ( data
.filters
[ i
].conflicts
) {
282 filterConflictMap
[ filterItem
.getName() ] = data
.filters
[ i
].conflicts
;
285 if ( data
.type
=== 'send_unselected_if_any' ) {
286 // Store the default parameter state
287 // For this group type, parameter values are direct
288 model
.defaultParams
[ data
.filters
[ i
].name
] = Number( !!data
.filters
[ i
].default );
290 data
.type
=== 'string_options' &&
291 data
.filters
[ i
].default
293 selectedFilterNames
.push( data
.filters
[ i
].name
);
296 model
.groups
[ group
].addItems( filterItem
);
297 items
.push( filterItem
);
300 if ( data
.type
=== 'string_options' ) {
301 // Store the default parameter group state
302 // For this group, the parameter is group name and value is the names
304 model
.defaultParams
[ group
] = model
.sanitizeStringOptionGroup( group
, selectedFilterNames
).join( model
.groups
[ group
].getSeparator() );
309 groupConflictResult
= expandConflictDefinitions( groupConflictMap
);
310 filterConflictResult
= expandConflictDefinitions( filterConflictMap
);
312 // Set conflicts for groups
313 $.each( groupConflictResult
, function ( group
, conflicts
) {
314 model
.groups
[ group
].setConflicts( conflicts
);
317 items
.forEach( function ( filterItem
) {
318 // Apply the superset map
319 filterItem
.setSuperset( supersetMap
[ filterItem
.getName() ] );
321 // set conflicts for item
322 if ( filterConflictResult
[ filterItem
.getName() ] ) {
323 filterItem
.setConflicts( filterConflictResult
[ filterItem
.getName() ] );
327 // Create a map between known parameters and their models
328 $.each( this.groups
, function ( group
, groupModel
) {
329 if ( groupModel
.getType() === 'send_unselected_if_any' ) {
330 // Individual filters
331 groupModel
.getItems().forEach( function ( filterItem
) {
332 model
.parameterMap
[ filterItem
.getParamName() ] = filterItem
;
334 } else if ( groupModel
.getType() === 'string_options' ) {
336 model
.parameterMap
[ groupModel
.getName() ] = groupModel
;
340 // Add items to the model
341 this.addItems( items
);
343 this.emit( 'initialize' );
347 * Get the names of all available filters
349 * @return {string[]} An array of filter names
351 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getFilterNames = function () {
352 return this.getItems().map( function ( item
) { return item
.getName(); } );
356 * Get the object that defines groups by their name.
358 * @return {Object} Filter groups
360 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getFilterGroups = function () {
365 * Get the value of a specific parameter
367 * @param {string} name Parameter name
368 * @return {number|string} Parameter value
370 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getParamValue = function ( name
) {
371 return this.parameters
[ name
];
375 * Get the current selected state of the filters
377 * @return {Object} Filters selected state
379 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getSelectedState = function () {
381 items
= this.getItems(),
384 for ( i
= 0; i
< items
.length
; i
++ ) {
385 result
[ items
[ i
].getName() ] = items
[ i
].isSelected();
392 * Get the current full state of the filters
394 * @return {Object} Filters full state
396 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getFullState = function () {
398 items
= this.getItems(),
401 for ( i
= 0; i
< items
.length
; i
++ ) {
402 result
[ items
[ i
].getName() ] = {
403 selected
: items
[ i
].isSelected(),
404 conflicted
: items
[ i
].isConflicted(),
405 included
: items
[ i
].isIncluded()
413 * Get the default parameters object
415 * @return {Object} Default parameter values
417 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getDefaultParams = function () {
418 return this.defaultParams
;
422 * Set all filter states to default values
424 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.setFiltersToDefaults = function () {
425 var defaultFilterStates
= this.getFiltersFromParameters( this.getDefaultParams() );
427 this.toggleFiltersSelected( defaultFilterStates
);
431 * Analyze the groups and their filters and output an object representing
432 * the state of the parameters they represent.
434 * @param {Object} [filterGroups] An object defining the filter groups to
435 * translate to parameters. Its structure must follow that of this.groups
436 * see #getFilterGroups
437 * @return {Object} Parameter state object
439 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getParametersFromFilters = function ( filterGroups
) {
441 groupItems
= filterGroups
|| this.getFilterGroups();
443 $.each( groupItems
, function ( group
, model
) {
444 $.extend( result
, model
.getParamRepresentation() );
451 * Get the highlight parameters based on current filter configuration
453 * @return {object} Object where keys are "<filter name>_color" and values
454 * are the selected highlight colors.
456 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getHighlightParameters = function () {
457 var result
= { highlight
: Number( this.isHighlightEnabled() ) };
459 this.getItems().forEach( function ( filterItem
) {
460 result
[ filterItem
.getName() + '_color' ] = filterItem
.getHighlightColor();
466 * Sanitize value group of a string_option groups type
467 * Remove duplicates and make sure to only use valid
471 * @param {string} groupName Group name
472 * @param {string[]} valueArray Array of values
473 * @return {string[]} Array of valid values
475 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.sanitizeStringOptionGroup = function( groupName
, valueArray
) {
477 validNames
= this.getGroupFilters( groupName
).map( function ( filterItem
) {
478 return filterItem
.getParamName();
481 if ( valueArray
.indexOf( 'all' ) > -1 ) {
482 // If anywhere in the values there's 'all', we
483 // treat it as if only 'all' was selected.
484 // Example: param=valid1,valid2,all
489 // Get rid of any dupe and invalid parameter, only output
491 // Example: param=valid1,valid2,invalid1,valid1
492 // Result: param=valid1,valid2
493 valueArray
.forEach( function ( value
) {
495 validNames
.indexOf( value
) > -1 &&
496 result
.indexOf( value
) === -1
498 result
.push( value
);
506 * Check whether the current filter state is set to all false.
508 * @return {boolean} Current filters are all empty
510 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.areCurrentFiltersEmpty = function () {
511 // Check if there are either any selected items or any items
512 // that have highlight enabled
513 return !this.getItems().some( function ( filterItem
) {
514 return filterItem
.isSelected() || filterItem
.isHighlighted();
519 * Check whether the default values of the filters are all false.
521 * @return {boolean} Default filters are all false
523 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.areDefaultFiltersEmpty = function () {
526 if ( this.defaultFiltersEmpty
!== null ) {
527 // We only need to do this test once,
528 // because defaults are set once per session
529 defaultFilters
= this.getFiltersFromParameters();
530 this.defaultFiltersEmpty
= Object
.keys( defaultFilters
).every( function ( filterName
) {
531 return !defaultFilters
[ filterName
];
535 return this.defaultFiltersEmpty
;
539 * This is the opposite of the #getParametersFromFilters method; this goes over
540 * the given parameters and translates into a selected/unselected value in the filters.
542 * @param {Object} params Parameters query object
543 * @return {Object} Filter state object
545 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getFiltersFromParameters = function ( params
) {
549 base
= this.getDefaultParams(),
552 params
= $.extend( {}, base
, params
);
554 // Go over the given parameters
555 $.each( params
, function ( paramName
, paramValue
) {
556 var itemOrGroup
= model
.parameterMap
[ paramName
];
558 if ( itemOrGroup
instanceof mw
.rcfilters
.dm
.FilterItem
) {
559 // Mark the group if it has any items that are selected
560 groupMap
[ itemOrGroup
.getGroupName() ] = groupMap
[ itemOrGroup
.getGroupName() ] || {};
561 groupMap
[ itemOrGroup
.getGroupName() ].hasSelected
= (
562 groupMap
[ itemOrGroup
.getGroupName() ].hasSelected
||
563 !!Number( paramValue
)
567 groupMap
[ itemOrGroup
.getGroupName() ].filters
= groupMap
[ itemOrGroup
.getGroupName() ].filters
|| [];
568 groupMap
[ itemOrGroup
.getGroupName() ].filters
.push( itemOrGroup
);
569 } else if ( itemOrGroup
instanceof mw
.rcfilters
.dm
.FilterGroup
) {
570 groupMap
[ itemOrGroup
.getName() ] = groupMap
[ itemOrGroup
.getName() ] || {};
571 // This parameter represents a group (values are the filters)
572 // this is equivalent to checking if the group is 'string_options'
573 groupMap
[ itemOrGroup
.getName() ].filters
= itemOrGroup
.getItems();
577 // Now that we know the groups' selection states, we need to go over
578 // the filters in the groups and mark their selected states appropriately
579 $.each( groupMap
, function ( group
, data
) {
580 var paramValues
, filterItem
,
581 allItemsInGroup
= data
.filters
;
583 if ( model
.groups
[ group
].getType() === 'send_unselected_if_any' ) {
584 for ( i
= 0; i
< allItemsInGroup
.length
; i
++ ) {
585 filterItem
= allItemsInGroup
[ i
];
587 result
[ filterItem
.getName() ] = groupMap
[ filterItem
.getGroupName() ].hasSelected
?
588 // Flip the definition between the parameter
589 // state and the filter state
590 // This is what the 'toggleSelected' value of the filter is
591 !Number( params
[ filterItem
.getParamName() ] ) :
592 // Otherwise, there are no selected items in the
593 // group, which means the state is false
596 } else if ( model
.groups
[ group
].getType() === 'string_options' ) {
597 paramValues
= model
.sanitizeStringOptionGroup(
599 params
[ group
].split(
600 model
.groups
[ group
].getSeparator()
604 for ( i
= 0; i
< allItemsInGroup
.length
; i
++ ) {
605 filterItem
= allItemsInGroup
[ i
];
607 result
[ filterItem
.getName() ] = (
608 // If it is the word 'all'
609 paramValues
.length
=== 1 && paramValues
[ 0 ] === 'all' ||
610 // All values are written
611 paramValues
.length
=== model
.groups
[ group
].getItemCount()
613 // All true (either because all values are written or the term 'all' is written)
614 // is the same as all filters set to false
616 // Otherwise, the filter is selected only if it appears in the parameter values
617 paramValues
.indexOf( filterItem
.getParamName() ) > -1;
626 * Get the item that matches the given name
628 * @param {string} name Filter name
629 * @return {mw.rcfilters.dm.FilterItem} Filter item
631 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getItemByName = function ( name
) {
632 return this.getItems().filter( function ( item
) {
633 return name
=== item
.getName();
638 * Set all filters to false or empty/all
639 * This is equivalent to display all.
641 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.emptyAllFilters = function () {
642 this.getItems().forEach( function ( filterItem
) {
643 this.toggleFilterSelected( filterItem
.getName(), false );
648 * Toggle selected state of one item
650 * @param {string} name Name of the filter item
651 * @param {boolean} [isSelected] Filter selected state
653 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.toggleFilterSelected = function ( name
, isSelected
) {
654 var item
= this.getItemByName( name
);
657 item
.toggleSelected( isSelected
);
662 * Toggle selected state of items by their names
664 * @param {Object} filterDef Filter definitions
666 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.toggleFiltersSelected = function ( filterDef
) {
667 Object
.keys( filterDef
).forEach( function ( name
) {
668 this.toggleFilterSelected( name
, filterDef
[ name
] );
673 * Get a group model from its name
675 * @param {string} groupName Group name
676 * @return {mw.rcfilters.dm.FilterGroup} Group model
678 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getGroup = function ( groupName
) {
679 return this.groups
[ groupName
];
683 * Get all filters within a specified group by its name
685 * @param {string} groupName Group name
686 * @return {mw.rcfilters.dm.FilterItem[]} Filters belonging to this group
688 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getGroupFilters = function ( groupName
) {
689 return ( this.getGroup( groupName
) && this.getGroup( groupName
).getItems() ) || [];
693 * Find items whose labels match the given string
695 * @param {string} query Search string
696 * @return {Object} An object of items to show
697 * arranged by their group names
699 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.findMatches = function ( query
) {
703 items
= this.getItems();
705 // Normalize so we can search strings regardless of case
706 query
= query
.toLowerCase();
708 // item label starting with the query string
709 for ( i
= 0; i
< items
.length
; i
++ ) {
710 if ( items
[ i
].getLabel().toLowerCase().indexOf( query
) === 0 ) {
711 result
[ items
[ i
].getGroupName() ] = result
[ items
[ i
].getGroupName() ] || [];
712 result
[ items
[ i
].getGroupName() ].push( items
[ i
] );
716 if ( $.isEmptyObject( result
) ) {
717 // item containing the query string in their label, description, or group title
718 for ( i
= 0; i
< items
.length
; i
++ ) {
719 groupTitle
= items
[ i
].getGroupModel().getTitle();
721 items
[ i
].getLabel().toLowerCase().indexOf( query
) > -1 ||
722 items
[ i
].getDescription().toLowerCase().indexOf( query
) > -1 ||
723 groupTitle
.toLowerCase().indexOf( query
) > -1
725 result
[ items
[ i
].getGroupName() ] = result
[ items
[ i
].getGroupName() ] || [];
726 result
[ items
[ i
].getGroupName() ].push( items
[ i
] );
735 * Get items that are highlighted
737 * @return {mw.rcfilters.dm.FilterItem[]} Highlighted items
739 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getHighlightedItems = function () {
740 return this.getItems().filter( function ( filterItem
) {
741 return filterItem
.isHighlightSupported() &&
742 filterItem
.getHighlightColor();
747 * Toggle the highlight feature on and off.
748 * Propagate the change to filter items.
750 * @param {boolean} enable Highlight should be enabled
751 * @fires highlightChange
753 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.toggleHighlight = function ( enable
) {
754 enable
= enable
=== undefined ? !this.highlightEnabled
: enable
;
756 if ( this.highlightEnabled
!== enable
) {
757 this.highlightEnabled
= enable
;
759 this.getItems().forEach( function ( filterItem
) {
760 filterItem
.toggleHighlight( this.highlightEnabled
);
763 this.emit( 'highlightChange', this.highlightEnabled
);
768 * Check if the highlight feature is enabled
771 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.isHighlightEnabled = function () {
772 return !!this.highlightEnabled
;
776 * Set highlight color for a specific filter item
778 * @param {string} filterName Name of the filter item
779 * @param {string} color Selected color
781 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.setHighlightColor = function ( filterName
, color
) {
782 this.getItemByName( filterName
).setHighlightColor( color
);
786 * Clear highlight for a specific filter item
788 * @param {string} filterName Name of the filter item
790 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.clearHighlightColor = function ( filterName
) {
791 this.getItemByName( filterName
).clearHighlightColor();
795 * Clear highlight for all filter items
797 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.clearAllHighlightColors = function () {
798 this.getItems().forEach( function ( filterItem
) {
799 filterItem
.clearHighlightColor();
802 }( mediaWiki
, jQuery
) );