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 {Array} filters Filter group definition
164 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.initializeFilters = function ( filters
) {
165 var i
, filterItem
, selectedFilterNames
, filterConflictResult
, groupConflictResult
,
169 groupConflictMap
= {},
170 filterConflictMap
= {},
171 addArrayElementsUnique = function ( arr
, elements
) {
172 elements
= Array
.isArray( elements
) ? elements
: [ elements
];
174 elements
.forEach( function ( element
) {
175 if ( arr
.indexOf( element
) === -1 ) {
182 expandConflictDefinitions = function ( obj
) {
185 $.each( obj
, function ( group
, conflicts
) {
186 var adjustedConflicts
= {};
187 conflicts
.forEach( function ( conflict
) {
188 if ( conflict
.filter
) {
189 adjustedConflicts
[ conflict
.filter
] = conflict
;
191 // This conflict is for an entire group. Split it up to
192 // represent each filter
194 // Get the relevant group items
195 model
.groups
[ conflict
.group
].getItems().forEach( function ( groupItem
) {
196 // Rebuild the conflict
197 adjustedConflicts
[ groupItem
.getName() ] = $.extend( {}, conflict
, { filter
: groupItem
.getName() } );
202 result
[ group
] = adjustedConflicts
;
212 filters
.forEach( function ( data
) {
213 var group
= data
.name
;
215 if ( !model
.groups
[ group
] ) {
216 model
.groups
[ group
] = new mw
.rcfilters
.dm
.FilterGroup( group
, {
218 title
: mw
.msg( data
.title
),
219 separator
: data
.separator
,
220 fullCoverage
: !!data
.fullCoverage
224 if ( data
.conflicts
) {
225 groupConflictMap
[ group
] = data
.conflicts
;
228 selectedFilterNames
= [];
229 for ( i
= 0; i
< data
.filters
.length
; i
++ ) {
230 data
.filters
[ i
].subset
= data
.filters
[ i
].subset
|| [];
231 data
.filters
[ i
].subset
= data
.filters
[ i
].subset
.map( function ( el
) {
235 filterItem
= new mw
.rcfilters
.dm
.FilterItem( data
.filters
[ i
].name
, model
.groups
[ group
], {
237 label
: mw
.msg( data
.filters
[ i
].label
),
238 description
: mw
.msg( data
.filters
[ i
].description
),
239 subset
: data
.filters
[ i
].subset
,
240 cssClass
: data
.filters
[ i
].cssClass
243 // For convenience, we should store each filter's "supersets" -- these are
244 // the filters that have that item in their subset list. This will just
245 // make it easier to go through whether the item has any other items
246 // that affect it (and are selected) at any given time
247 if ( data
.filters
[ i
].subset
) {
248 data
.filters
[ i
].subset
.forEach( function ( subsetFilterName
) { // eslint-disable-line no-loop-func
249 supersetMap
[ subsetFilterName
] = supersetMap
[ subsetFilterName
] || [];
250 addArrayElementsUnique(
251 supersetMap
[ subsetFilterName
],
258 if ( data
.filters
[ i
].conflicts
) {
259 filterConflictMap
[ data
.filters
[ i
].name
] = data
.filters
[ i
].conflicts
;
262 if ( data
.type
=== 'send_unselected_if_any' ) {
263 // Store the default parameter state
264 // For this group type, parameter values are direct
265 model
.defaultParams
[ data
.filters
[ i
].name
] = Number( !!data
.filters
[ i
].default );
267 data
.type
=== 'string_options' &&
268 data
.filters
[ i
].default
270 selectedFilterNames
.push( data
.filters
[ i
].name
);
273 model
.groups
[ group
].addItems( filterItem
);
274 items
.push( filterItem
);
277 if ( data
.type
=== 'string_options' ) {
278 // Store the default parameter group state
279 // For this group, the parameter is group name and value is the names
281 model
.defaultParams
[ group
] = model
.sanitizeStringOptionGroup( group
, selectedFilterNames
).join( model
.groups
[ group
].getSeparator() );
286 groupConflictResult
= expandConflictDefinitions( groupConflictMap
);
287 filterConflictResult
= expandConflictDefinitions( filterConflictMap
);
289 // Set conflicts for groups
290 $.each( groupConflictResult
, function ( group
, conflicts
) {
291 model
.groups
[ group
].setConflicts( conflicts
);
294 items
.forEach( function ( filterItem
) {
295 // Apply the superset map
296 filterItem
.setSuperset( supersetMap
[ filterItem
.getName() ] );
298 // set conflicts for item
299 if ( filterConflictResult
[ filterItem
.getName() ] ) {
300 filterItem
.setConflicts( filterConflictResult
[ filterItem
.getName() ] );
304 // Add items to the model
305 this.addItems( items
);
307 this.emit( 'initialize' );
311 * Get the names of all available filters
313 * @return {string[]} An array of filter names
315 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getFilterNames = function () {
316 return this.getItems().map( function ( item
) { return item
.getName(); } );
320 * Get the object that defines groups by their name.
322 * @return {Object} Filter groups
324 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getFilterGroups = function () {
329 * Get the value of a specific parameter
331 * @param {string} name Parameter name
332 * @return {number|string} Parameter value
334 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getParamValue = function ( name
) {
335 return this.parameters
[ name
];
339 * Get the current selected state of the filters
341 * @return {Object} Filters selected state
343 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getSelectedState = function () {
345 items
= this.getItems(),
348 for ( i
= 0; i
< items
.length
; i
++ ) {
349 result
[ items
[ i
].getName() ] = items
[ i
].isSelected();
356 * Get the current full state of the filters
358 * @return {Object} Filters full state
360 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getFullState = function () {
362 items
= this.getItems(),
365 for ( i
= 0; i
< items
.length
; i
++ ) {
366 result
[ items
[ i
].getName() ] = {
367 selected
: items
[ i
].isSelected(),
368 conflicted
: items
[ i
].isConflicted(),
369 included
: items
[ i
].isIncluded()
377 * Get the default parameters object
379 * @return {Object} Default parameter values
381 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getDefaultParams = function () {
382 return this.defaultParams
;
386 * Set all filter states to default values
388 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.setFiltersToDefaults = function () {
389 var defaultFilterStates
= this.getFiltersFromParameters( this.getDefaultParams() );
391 this.toggleFiltersSelected( defaultFilterStates
);
395 * Analyze the groups and their filters and output an object representing
396 * the state of the parameters they represent.
398 * @param {Object} [filterGroups] An object defining the filter groups to
399 * translate to parameters. Its structure must follow that of this.groups
400 * see #getFilterGroups
401 * @return {Object} Parameter state object
403 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getParametersFromFilters = function ( filterGroups
) {
404 var i
, filterItems
, anySelected
, values
,
406 groupItems
= filterGroups
|| this.getFilterGroups();
408 $.each( groupItems
, function ( group
, model
) {
409 filterItems
= model
.getItems();
411 if ( model
.getType() === 'send_unselected_if_any' ) {
412 // First, check if any of the items are selected at all.
413 // If none is selected, we're treating it as if they are
415 anySelected
= filterItems
.some( function ( filterItem
) {
416 return filterItem
.isSelected();
419 // Go over the items and define the correct values
420 for ( i
= 0; i
< filterItems
.length
; i
++ ) {
421 result
[ filterItems
[ i
].getName() ] = anySelected
?
422 Number( !filterItems
[ i
].isSelected() ) : 0;
424 } else if ( model
.getType() === 'string_options' ) {
426 for ( i
= 0; i
< filterItems
.length
; i
++ ) {
427 if ( filterItems
[ i
].isSelected() ) {
428 values
.push( filterItems
[ i
].getName() );
432 if ( values
.length
=== filterItems
.length
) {
433 result
[ group
] = 'all';
435 result
[ group
] = values
.join( model
.getSeparator() );
444 * Get the highlight parameters based on current filter configuration
446 * @return {object} Object where keys are "<filter name>_color" and values
447 * are the selected highlight colors.
449 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getHighlightParameters = function () {
450 var result
= { highlight
: Number( this.isHighlightEnabled() ) };
452 this.getItems().forEach( function ( filterItem
) {
453 result
[ filterItem
.getName() + '_color' ] = filterItem
.getHighlightColor();
459 * Sanitize value group of a string_option groups type
460 * Remove duplicates and make sure to only use valid
464 * @param {string} groupName Group name
465 * @param {string[]} valueArray Array of values
466 * @return {string[]} Array of valid values
468 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.sanitizeStringOptionGroup = function( groupName
, valueArray
) {
470 validNames
= this.getGroupFilters( groupName
).map( function ( filterItem
) {
471 return filterItem
.getName();
474 if ( valueArray
.indexOf( 'all' ) > -1 ) {
475 // If anywhere in the values there's 'all', we
476 // treat it as if only 'all' was selected.
477 // Example: param=valid1,valid2,all
482 // Get rid of any dupe and invalid parameter, only output
484 // Example: param=valid1,valid2,invalid1,valid1
485 // Result: param=valid1,valid2
486 valueArray
.forEach( function ( value
) {
488 validNames
.indexOf( value
) > -1 &&
489 result
.indexOf( value
) === -1
491 result
.push( value
);
499 * Check whether the current filter state is set to all false.
501 * @return {boolean} Current filters are all empty
503 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.areCurrentFiltersEmpty = function () {
504 // Check if there are either any selected items or any items
505 // that have highlight enabled
506 return !this.getItems().some( function ( filterItem
) {
507 return filterItem
.isSelected() || filterItem
.isHighlighted();
512 * Check whether the default values of the filters are all false.
514 * @return {boolean} Default filters are all false
516 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.areDefaultFiltersEmpty = function () {
519 if ( this.defaultFiltersEmpty
!== null ) {
520 // We only need to do this test once,
521 // because defaults are set once per session
522 defaultFilters
= this.getFiltersFromParameters();
523 this.defaultFiltersEmpty
= Object
.keys( defaultFilters
).every( function ( filterName
) {
524 return !defaultFilters
[ filterName
];
528 return this.defaultFiltersEmpty
;
532 * This is the opposite of the #getParametersFromFilters method; this goes over
533 * the given parameters and translates into a selected/unselected value in the filters.
535 * @param {Object} params Parameters query object
536 * @return {Object} Filter state object
538 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getFiltersFromParameters = function ( params
) {
542 base
= this.getDefaultParams(),
545 params
= $.extend( {}, base
, params
);
547 $.each( params
, function ( paramName
, paramValue
) {
548 // Find the filter item
549 filterItem
= model
.getItemByName( paramName
);
550 // Ignore if no filter item exists
552 groupMap
[ filterItem
.getGroupName() ] = groupMap
[ filterItem
.getGroupName() ] || {};
554 // Mark the group if it has any items that are selected
555 groupMap
[ filterItem
.getGroupName() ].hasSelected
= (
556 groupMap
[ filterItem
.getGroupName() ].hasSelected
||
557 !!Number( paramValue
)
560 // Add the relevant filter into the group map
561 groupMap
[ filterItem
.getGroupName() ].filters
= groupMap
[ filterItem
.getGroupName() ].filters
|| [];
562 groupMap
[ filterItem
.getGroupName() ].filters
.push( filterItem
);
563 } else if ( model
.groups
.hasOwnProperty( paramName
) ) {
564 // This parameter represents a group (values are the filters)
565 // this is equivalent to checking if the group is 'string_options'
566 groupMap
[ paramName
] = { filters
: model
.groups
[ paramName
].getItems() };
570 // Now that we know the groups' selection states, we need to go over
571 // the filters in the groups and mark their selected states appropriately
572 $.each( groupMap
, function ( group
, data
) {
573 var paramValues
, filterItem
,
574 allItemsInGroup
= data
.filters
;
576 if ( model
.groups
[ group
].getType() === 'send_unselected_if_any' ) {
577 for ( i
= 0; i
< allItemsInGroup
.length
; i
++ ) {
578 filterItem
= allItemsInGroup
[ i
];
580 result
[ filterItem
.getName() ] = data
.hasSelected
?
581 // Flip the definition between the parameter
582 // state and the filter state
583 // This is what the 'toggleSelected' value of the filter is
584 !Number( params
[ filterItem
.getName() ] ) :
585 // Otherwise, there are no selected items in the
586 // group, which means the state is false
589 } else if ( model
.groups
[ group
].getType() === 'string_options' ) {
590 paramValues
= model
.sanitizeStringOptionGroup( group
, params
[ group
].split( model
.groups
[ group
].getSeparator() ) );
592 for ( i
= 0; i
< allItemsInGroup
.length
; i
++ ) {
593 filterItem
= allItemsInGroup
[ i
];
595 result
[ filterItem
.getName() ] = (
596 // If it is the word 'all'
597 paramValues
.length
=== 1 && paramValues
[ 0 ] === 'all' ||
598 // All values are written
599 paramValues
.length
=== model
.groups
[ group
].getItemCount()
601 // All true (either because all values are written or the term 'all' is written)
602 // is the same as all filters set to false
604 // Otherwise, the filter is selected only if it appears in the parameter values
605 paramValues
.indexOf( filterItem
.getName() ) > -1;
613 * Get the item that matches the given name
615 * @param {string} name Filter name
616 * @return {mw.rcfilters.dm.FilterItem} Filter item
618 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getItemByName = function ( name
) {
619 return this.getItems().filter( function ( item
) {
620 return name
=== item
.getName();
625 * Set all filters to false or empty/all
626 * This is equivalent to display all.
628 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.emptyAllFilters = function () {
629 this.getItems().forEach( function ( filterItem
) {
630 this.toggleFilterSelected( filterItem
.getName(), false );
635 * Toggle selected state of one item
637 * @param {string} name Name of the filter item
638 * @param {boolean} [isSelected] Filter selected state
640 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.toggleFilterSelected = function ( name
, isSelected
) {
641 this.getItemByName( name
).toggleSelected( isSelected
);
645 * Toggle selected state of items by their names
647 * @param {Object} filterDef Filter definitions
649 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.toggleFiltersSelected = function ( filterDef
) {
650 Object
.keys( filterDef
).forEach( function ( name
) {
651 this.toggleFilterSelected( name
, filterDef
[ name
] );
656 * Get a group model from its name
658 * @param {string} groupName Group name
659 * @return {mw.rcfilters.dm.FilterGroup} Group model
661 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getGroup = function ( groupName
) {
662 return this.groups
[ groupName
];
666 * Get all filters within a specified group by its name
668 * @param {string} groupName Group name
669 * @return {mw.rcfilters.dm.FilterItem[]} Filters belonging to this group
671 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getGroupFilters = function ( groupName
) {
672 return ( this.getGroup( groupName
) && this.getGroup( groupName
).getItems() ) || [];
676 * Find items whose labels match the given string
678 * @param {string} query Search string
679 * @return {Object} An object of items to show
680 * arranged by their group names
682 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.findMatches = function ( query
) {
686 items
= this.getItems();
688 // Normalize so we can search strings regardless of case
689 query
= query
.toLowerCase();
691 // item label starting with the query string
692 for ( i
= 0; i
< items
.length
; i
++ ) {
693 if ( items
[ i
].getLabel().toLowerCase().indexOf( query
) === 0 ) {
694 result
[ items
[ i
].getGroupName() ] = result
[ items
[ i
].getGroupName() ] || [];
695 result
[ items
[ i
].getGroupName() ].push( items
[ i
] );
699 if ( $.isEmptyObject( result
) ) {
700 // item containing the query string in their label, description, or group title
701 for ( i
= 0; i
< items
.length
; i
++ ) {
702 groupTitle
= items
[ i
].getGroupModel().getTitle();
704 items
[ i
].getLabel().toLowerCase().indexOf( query
) > -1 ||
705 items
[ i
].getDescription().toLowerCase().indexOf( query
) > -1 ||
706 groupTitle
.toLowerCase().indexOf( query
) > -1
708 result
[ items
[ i
].getGroupName() ] = result
[ items
[ i
].getGroupName() ] || [];
709 result
[ items
[ i
].getGroupName() ].push( items
[ i
] );
718 * Get items that are highlighted
720 * @return {mw.rcfilters.dm.FilterItem[]} Highlighted items
722 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.getHighlightedItems = function () {
723 return this.getItems().filter( function ( filterItem
) {
724 return filterItem
.isHighlightSupported() &&
725 filterItem
.getHighlightColor();
730 * Toggle the highlight feature on and off.
731 * Propagate the change to filter items.
733 * @param {boolean} enable Highlight should be enabled
734 * @fires highlightChange
736 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.toggleHighlight = function ( enable
) {
737 enable
= enable
=== undefined ? !this.highlightEnabled
: enable
;
739 if ( this.highlightEnabled
!== enable
) {
740 this.highlightEnabled
= enable
;
742 this.getItems().forEach( function ( filterItem
) {
743 filterItem
.toggleHighlight( this.highlightEnabled
);
746 this.emit( 'highlightChange', this.highlightEnabled
);
751 * Check if the highlight feature is enabled
754 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.isHighlightEnabled = function () {
755 return !!this.highlightEnabled
;
759 * Set highlight color for a specific filter item
761 * @param {string} filterName Name of the filter item
762 * @param {string} color Selected color
764 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.setHighlightColor = function ( filterName
, color
) {
765 this.getItemByName( filterName
).setHighlightColor( color
);
769 * Clear highlight for a specific filter item
771 * @param {string} filterName Name of the filter item
773 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.clearHighlightColor = function ( filterName
) {
774 this.getItemByName( filterName
).clearHighlightColor();
778 * Clear highlight for all filter items
780 mw
.rcfilters
.dm
.FiltersViewModel
.prototype.clearAllHighlightColors = function () {
781 this.getItems().forEach( function ( filterItem
) {
782 filterItem
.clearHighlightColor();
785 }( mediaWiki
, jQuery
) );