2 var FilterGroup
= require( './FilterGroup.js' ),
3 FilterItem
= require( './FilterItem.js' ),
7 * View model for the filters selection and display
9 * @class mw.rcfilters.dm.FiltersViewModel
10 * @mixins OO.EventEmitter
11 * @mixins OO.EmitterList
15 FiltersViewModel
= function MwRcfiltersDmFiltersViewModel() {
17 OO
.EventEmitter
.call( this );
18 OO
.EmitterList
.call( this );
21 this.defaultParams
= {};
22 this.highlightEnabled
= false;
23 this.parameterMap
= {};
24 this.emptyParameterState
= null;
27 this.currentView
= 'default';
28 this.searchQuery
= null;
31 this.aggregate( { update
: 'filterItemUpdate' } );
32 this.connect( this, { filterItemUpdate
: [ 'emit', 'itemUpdate' ] } );
36 OO
.initClass( FiltersViewModel
);
37 OO
.mixinClass( FiltersViewModel
, OO
.EventEmitter
);
38 OO
.mixinClass( FiltersViewModel
, OO
.EmitterList
);
45 * Filter list is initialized
51 * Model has been updated
56 * @param {mw.rcfilters.dm.FilterItem} item Filter item updated
58 * Filter item has changed
62 * @event highlightChange
63 * @param {boolean} Highlight feature is enabled
65 * Highlight feature has been toggled enabled or disabled
71 * Re-assess the states of filter items based on the interactions between them
73 * @param {mw.rcfilters.dm.FilterItem} [item] Changed item. If not given, the
74 * method will go over the state of all items
76 FiltersViewModel
.prototype.reassessFilterInteractions = function ( item
) {
79 iterationItems
= item
!== undefined ? [ item
] : this.getItems();
81 iterationItems
.forEach( function ( checkedItem
) {
82 var allCheckedItems
= checkedItem
.getSubset().concat( [ checkedItem
.getName() ] ),
83 groupModel
= checkedItem
.getGroupModel();
85 // Check for subsets (included filters) plus the item itself:
86 allCheckedItems
.forEach( function ( filterItemName
) {
87 var itemInSubset
= model
.getItemByName( filterItemName
);
89 itemInSubset
.toggleIncluded(
90 // If any of itemInSubset's supersets are selected, this item
92 itemInSubset
.getSuperset().some( function ( supersetName
) {
93 return ( model
.getItemByName( supersetName
).isSelected() );
98 // Update coverage for the changed group
99 if ( groupModel
.isFullCoverage() ) {
100 allSelected
= groupModel
.areAllSelected();
101 groupModel
.getItems().forEach( function ( filterItem
) {
102 filterItem
.toggleFullyCovered( allSelected
);
107 // Check for conflicts
108 // In this case, we must go over all items, since
109 // conflicts are bidirectional and depend not only on
110 // individual items, but also on the selected states of
111 // the groups they're in.
112 this.getItems().forEach( function ( filterItem
) {
113 var inConflict
= false,
114 filterItemGroup
= filterItem
.getGroupModel();
116 // For each item, see if that item is still conflicting
117 // eslint-disable-next-line jquery/no-each-util
118 $.each( model
.groups
, function ( groupName
, groupModel
) {
119 if ( filterItem
.getGroupName() === groupName
) {
120 // Check inside the group
121 inConflict
= groupModel
.areAnySelectedInConflictWith( filterItem
);
123 // According to the spec, if two items conflict from two different
124 // groups, the conflict only lasts if the groups **only have selected
125 // items that are conflicting**. If a group has selected items that
126 // are conflicting and non-conflicting, the scope of the result has
127 // expanded enough to completely remove the conflict.
129 // For example, see two groups with conflicts:
132 // name: 'experienced',
133 // conflicts: [ 'unregistered' ]
138 // name: 'registered',
141 // name: 'unregistered',
144 // If we select 'experienced', then 'unregistered' is in conflict (and vice versa),
145 // because, inherently, 'experienced' filter only includes registered users, and so
146 // both filters are in conflict with one another.
147 // However, the minute we select 'registered', the scope of our results
148 // has expanded to no longer have a conflict with 'experienced' filter, and
149 // so the conflict is removed.
151 // In our case, we need to check if the entire group conflicts with
152 // the entire item's group, so we follow the above spec
154 // The foreign group is in conflict with this item
155 groupModel
.areAllSelectedInConflictWith( filterItem
) &&
156 // Every selected member of the item's own group is also
157 // in conflict with the other group
158 filterItemGroup
.findSelectedItems().every( function ( otherGroupItem
) {
159 return groupModel
.areAllSelectedInConflictWith( otherGroupItem
);
164 // If we're in conflict, this will return 'false' which
165 // will break the loop. Otherwise, we're not in conflict
166 // and the loop continues
170 // Toggle the item state
171 filterItem
.toggleConflicted( inConflict
);
176 * Get whether the model has any conflict in its items
178 * @return {boolean} There is a conflict
180 FiltersViewModel
.prototype.hasConflict = function () {
181 return this.getItems().some( function ( filterItem
) {
182 return filterItem
.isSelected() && filterItem
.isConflicted();
187 * Get the first item with a current conflict
189 * @return {mw.rcfilters.dm.FilterItem} Conflicted item
191 FiltersViewModel
.prototype.getFirstConflictedItem = function () {
194 this.getItems().forEach( function ( filterItem
) {
195 if ( filterItem
.isSelected() && filterItem
.isConflicted() ) {
196 conflictedItem
= filterItem
;
201 return conflictedItem
;
205 * Set filters and preserve a group relationship based on
206 * the definition given by an object
208 * @param {Array} filterGroups Filters definition
209 * @param {Object} [views] Extra views definition
210 * Expected in the following format:
213 * label: 'namespaces', // Message key
218 * name: 'namespaces' // Parameter name
219 * title: 'namespaces' // Message key
220 * type: 'string_options',
222 * labelPrefixKey: { 'default': 'rcfilters-tag-prefix-namespace', inverted: 'rcfilters-tag-prefix-namespace-inverted' },
230 FiltersViewModel
.prototype.initializeFilters = function ( filterGroups
, views
) {
231 var filterConflictResult
, groupConflictResult
,
235 groupConflictMap
= {},
236 filterConflictMap
= {},
238 * Expand a conflict definition from group name to
239 * the list of all included filters in that group.
240 * We do this so that the direct relationship in the
241 * models are consistently item->items rather than
242 * mixing item->group with item->item.
244 * @param {Object} obj Conflict definition
245 * @return {Object} Expanded conflict definition
247 expandConflictDefinitions = function ( obj
) {
250 // eslint-disable-next-line jquery/no-each-util
251 $.each( obj
, function ( key
, conflicts
) {
253 adjustedConflicts
= {};
255 conflicts
.forEach( function ( conflict
) {
258 if ( conflict
.filter
) {
259 filterName
= model
.groups
[ conflict
.group
].getPrefixedName( conflict
.filter
);
260 filter
= model
.getItemByName( filterName
);
263 adjustedConflicts
[ filterName
] = $.extend(
272 // This conflict is for an entire group. Split it up to
273 // represent each filter
275 // Get the relevant group items
276 model
.groups
[ conflict
.group
].getItems().forEach( function ( groupItem
) {
277 // Rebuild the conflict
278 adjustedConflicts
[ groupItem
.getName() ] = $.extend(
282 filter
: groupItem
.getName(),
290 result
[ key
] = adjustedConflicts
;
302 filterGroups
= OO
.copy( filterGroups
);
304 // Normalize definition from the server
305 filterGroups
.forEach( function ( data
) {
307 // What's this information needs to be normalized
309 body
: data
.whatsThisBody
,
310 header
: data
.whatsThisHeader
,
311 linkText
: data
.whatsThisLinkText
,
312 url
: data
.whatsThisUrl
315 // Title is a msg-key
316 data
.title
= data
.title
? mw
.msg( data
.title
) : data
.name
;
318 // Filters are given to us with msg-keys, we need
319 // to translate those before we hand them off
320 for ( i
= 0; i
< data
.filters
.length
; i
++ ) {
321 data
.filters
[ i
].label
= data
.filters
[ i
].label
? mw
.msg( data
.filters
[ i
].label
) : data
.filters
[ i
].name
;
322 data
.filters
[ i
].description
= data
.filters
[ i
].description
? mw
.msg( data
.filters
[ i
].description
) : '';
327 allViews
= $.extend( true, {
329 title
: mw
.msg( 'rcfilters-filterlist-title' ),
335 // eslint-disable-next-line jquery/no-each-util
336 $.each( allViews
, function ( viewName
, viewData
) {
338 model
.views
[ viewName
] = {
340 title
: viewData
.title
,
341 trigger
: viewData
.trigger
345 viewData
.groups
.forEach( function ( groupData
) {
346 var group
= groupData
.name
;
348 if ( !model
.groups
[ group
] ) {
349 model
.groups
[ group
] = new FilterGroup(
351 $.extend( true, {}, groupData
, { view
: viewName
} )
355 model
.groups
[ group
].initializeFilters( groupData
.filters
, groupData
.default );
356 items
= items
.concat( model
.groups
[ group
].getItems() );
359 if ( groupData
.conflicts
) {
361 groupConflictMap
[ group
] = groupData
.conflicts
;
364 groupData
.filters
.forEach( function ( itemData
) {
365 var filterItem
= model
.groups
[ group
].getItemByParamName( itemData
.name
);
367 if ( itemData
.conflicts
) {
368 filterConflictMap
[ filterItem
.getName() ] = itemData
.conflicts
;
374 // Add item references to the model, for lookup
375 this.addItems( items
);
378 groupConflictResult
= expandConflictDefinitions( groupConflictMap
);
379 filterConflictResult
= expandConflictDefinitions( filterConflictMap
);
381 // Set conflicts for groups
382 // eslint-disable-next-line jquery/no-each-util
383 $.each( groupConflictResult
, function ( group
, conflicts
) {
384 model
.groups
[ group
].setConflicts( conflicts
);
387 // Set conflicts for items
388 // eslint-disable-next-line jquery/no-each-util
389 $.each( filterConflictResult
, function ( filterName
, conflicts
) {
390 var filterItem
= model
.getItemByName( filterName
);
391 // set conflicts for items in the group
392 filterItem
.setConflicts( conflicts
);
395 // Create a map between known parameters and their models
396 // eslint-disable-next-line jquery/no-each-util
397 $.each( this.groups
, function ( group
, groupModel
) {
399 groupModel
.getType() === 'send_unselected_if_any' ||
400 groupModel
.getType() === 'boolean' ||
401 groupModel
.getType() === 'any_value'
403 // Individual filters
404 groupModel
.getItems().forEach( function ( filterItem
) {
405 model
.parameterMap
[ filterItem
.getParamName() ] = filterItem
;
408 groupModel
.getType() === 'string_options' ||
409 groupModel
.getType() === 'single_option'
412 model
.parameterMap
[ groupModel
.getName() ] = groupModel
;
416 this.setSearch( '' );
418 this.updateHighlightedState();
420 // Finish initialization
421 this.emit( 'initialize' );
425 * Update filter view model state based on a parameter object
427 * @param {Object} params Parameters object
429 FiltersViewModel
.prototype.updateStateFromParams = function ( params
) {
431 // For arbitrary numeric single_option values make sure the values
432 // are normalized to fit within the limits
433 // eslint-disable-next-line jquery/no-each-util
434 $.each( this.getFilterGroups(), function ( groupName
, groupModel
) {
435 params
[ groupName
] = groupModel
.normalizeArbitraryValue( params
[ groupName
] );
438 // Update filter values
439 filtersValue
= this.getFiltersFromParameters( params
);
440 Object
.keys( filtersValue
).forEach( function ( filterName
) {
441 this.getItemByName( filterName
).setValue( filtersValue
[ filterName
] );
444 // Update highlight state
445 this.getItemsSupportingHighlights().forEach( function ( filterItem
) {
446 var color
= params
[ filterItem
.getName() + '_color' ];
448 filterItem
.setHighlightColor( color
);
450 filterItem
.clearHighlightColor();
453 this.updateHighlightedState();
455 // Check all filter interactions
456 this.reassessFilterInteractions();
460 * Get a representation of an empty (falsey) parameter state
462 * @return {Object} Empty parameter state
464 FiltersViewModel
.prototype.getEmptyParameterState = function () {
465 if ( !this.emptyParameterState
) {
466 this.emptyParameterState
= $.extend(
469 this.getParametersFromFilters( {} ),
470 this.getEmptyHighlightParameters()
473 return this.emptyParameterState
;
477 * Get a representation of only the non-falsey parameters
479 * @param {Object} [parameters] A given parameter state to minimize. If not given the current
480 * state of the system will be used.
481 * @return {Object} Empty parameter state
483 FiltersViewModel
.prototype.getMinimizedParamRepresentation = function ( parameters
) {
486 parameters
= parameters
? $.extend( true, {}, parameters
) : this.getCurrentParameterState();
489 // eslint-disable-next-line jquery/no-each-util
490 $.each( this.getEmptyParameterState(), function ( param
, value
) {
491 if ( parameters
[ param
] !== undefined && parameters
[ param
] !== value
) {
492 result
[ param
] = parameters
[ param
];
497 Object
.keys( this.getEmptyHighlightParameters() ).forEach( function ( param
) {
498 if ( parameters
[ param
] ) {
499 // If a highlight parameter is not undefined and not null
500 // add it to the result
501 result
[ param
] = parameters
[ param
];
509 * Get a representation of the full parameter list, including all base values
511 * @return {Object} Full parameter representation
513 FiltersViewModel
.prototype.getExpandedParamRepresentation = function () {
517 this.getEmptyParameterState(),
518 this.getCurrentParameterState()
523 * Get a parameter representation of the current state of the model
525 * @param {boolean} [removeStickyParams] Remove sticky filters from final result
526 * @return {Object} Parameter representation of the current state of the model
528 FiltersViewModel
.prototype.getCurrentParameterState = function ( removeStickyParams
) {
529 var state
= this.getMinimizedParamRepresentation( $.extend(
532 this.getParametersFromFilters( this.getSelectedState() ),
533 this.getHighlightParameters()
536 if ( removeStickyParams
) {
537 state
= this.removeStickyParams( state
);
544 * Delete sticky parameters from given object.
546 * @param {Object} paramState Parameter state
547 * @return {Object} Parameter state without sticky parameters
549 FiltersViewModel
.prototype.removeStickyParams = function ( paramState
) {
550 this.getStickyParams().forEach( function ( paramName
) {
551 delete paramState
[ paramName
];
558 * Turn the highlight feature on or off
560 FiltersViewModel
.prototype.updateHighlightedState = function () {
561 this.toggleHighlight( this.getHighlightedItems().length
> 0 );
565 * Get the object that defines groups by their name.
567 * @return {Object} Filter groups
569 FiltersViewModel
.prototype.getFilterGroups = function () {
574 * Get the object that defines groups that match a certain view by their name.
576 * @param {string} [view] Requested view. If not given, uses current view
577 * @return {Object} Filter groups matching a display group
579 FiltersViewModel
.prototype.getFilterGroupsByView = function ( view
) {
582 view
= view
|| this.getCurrentView();
584 // eslint-disable-next-line jquery/no-each-util
585 $.each( this.groups
, function ( groupName
, groupModel
) {
586 if ( groupModel
.getView() === view
) {
587 result
[ groupName
] = groupModel
;
595 * Get an array of filters matching the given display group.
597 * @param {string} [view] Requested view. If not given, uses current view
598 * @return {mw.rcfilters.dm.FilterItem} Filter items matching the group
600 FiltersViewModel
.prototype.getFiltersByView = function ( view
) {
604 view
= view
|| this.getCurrentView();
606 groups
= this.getFilterGroupsByView( view
);
608 // eslint-disable-next-line jquery/no-each-util
609 $.each( groups
, function ( groupName
, groupModel
) {
610 result
= result
.concat( groupModel
.getItems() );
617 * Get the trigger for the requested view.
619 * @param {string} view View name
620 * @return {string} View trigger, if exists
622 FiltersViewModel
.prototype.getViewTrigger = function ( view
) {
623 return ( this.views
[ view
] && this.views
[ view
].trigger
) || '';
627 * Get the value of a specific parameter
629 * @param {string} name Parameter name
630 * @return {number|string} Parameter value
632 FiltersViewModel
.prototype.getParamValue = function ( name
) {
633 return this.parameters
[ name
];
637 * Get the current selected state of the filters
639 * @param {boolean} [onlySelected] return an object containing only the filters with a value
640 * @return {Object} Filters selected state
642 FiltersViewModel
.prototype.getSelectedState = function ( onlySelected
) {
644 items
= this.getItems(),
647 for ( i
= 0; i
< items
.length
; i
++ ) {
648 if ( !onlySelected
|| items
[ i
].getValue() ) {
649 result
[ items
[ i
].getName() ] = items
[ i
].getValue();
657 * Get the current full state of the filters
659 * @return {Object} Filters full state
661 FiltersViewModel
.prototype.getFullState = function () {
663 items
= this.getItems(),
666 for ( i
= 0; i
< items
.length
; i
++ ) {
667 result
[ items
[ i
].getName() ] = {
668 selected
: items
[ i
].isSelected(),
669 conflicted
: items
[ i
].isConflicted(),
670 included
: items
[ i
].isIncluded()
678 * Get an object representing default parameters state
680 * @return {Object} Default parameter values
682 FiltersViewModel
.prototype.getDefaultParams = function () {
685 // Get default filter state
686 // eslint-disable-next-line jquery/no-each-util
687 $.each( this.groups
, function ( name
, model
) {
688 if ( !model
.isSticky() ) {
689 $.extend( true, result
, model
.getDefaultParams() );
697 * Get a parameter representation of all sticky parameters
699 * @return {Object} Sticky parameter values
701 FiltersViewModel
.prototype.getStickyParams = function () {
704 // eslint-disable-next-line jquery/no-each-util
705 $.each( this.groups
, function ( name
, model
) {
706 if ( model
.isSticky() ) {
707 if ( model
.isPerGroupRequestParameter() ) {
710 // Each filter is its own param
711 result
= result
.concat( model
.getItems().map( function ( filterItem
) {
712 return filterItem
.getParamName();
722 * Get a parameter representation of all sticky parameters
724 * @return {Object} Sticky parameter values
726 FiltersViewModel
.prototype.getStickyParamsValues = function () {
729 // eslint-disable-next-line jquery/no-each-util
730 $.each( this.groups
, function ( name
, model
) {
731 if ( model
.isSticky() ) {
732 $.extend( true, result
, model
.getParamRepresentation() );
740 * Analyze the groups and their filters and output an object representing
741 * the state of the parameters they represent.
743 * @param {Object} [filterDefinition] An object defining the filter values,
744 * keyed by filter names.
745 * @return {Object} Parameter state object
747 FiltersViewModel
.prototype.getParametersFromFilters = function ( filterDefinition
) {
748 var groupItemDefinition
,
750 groupItems
= this.getFilterGroups();
752 if ( filterDefinition
) {
753 groupItemDefinition
= {};
754 // Filter definition is "flat", but in effect
755 // each group needs to tell us its result based
756 // on the values in it. We need to split this list
757 // back into groupings so we can "feed" it to the
758 // loop below, and we need to expand it so it includes
759 // all filters (set to false)
760 this.getItems().forEach( function ( filterItem
) {
761 groupItemDefinition
[ filterItem
.getGroupName() ] = groupItemDefinition
[ filterItem
.getGroupName() ] || {};
762 groupItemDefinition
[ filterItem
.getGroupName() ][ filterItem
.getName() ] = filterItem
.coerceValue( filterDefinition
[ filterItem
.getName() ] );
766 // eslint-disable-next-line jquery/no-each-util
767 $.each( groupItems
, function ( group
, model
) {
770 model
.getParamRepresentation(
771 groupItemDefinition
?
772 groupItemDefinition
[ group
] : null
781 * This is the opposite of the #getParametersFromFilters method; this goes over
782 * the given parameters and translates into a selected/unselected value in the filters.
784 * @param {Object} params Parameters query object
785 * @return {Object} Filter state object
787 FiltersViewModel
.prototype.getFiltersFromParameters = function ( params
) {
792 // Go over the given parameters, break apart to groupings
793 // The resulting object represents the group with its parameter
794 // values. For example:
801 // group2: "param4|param5"
803 // eslint-disable-next-line jquery/no-each-util
804 $.each( params
, function ( paramName
, paramValue
) {
806 itemOrGroup
= model
.parameterMap
[ paramName
];
809 groupName
= itemOrGroup
instanceof FilterItem
?
810 itemOrGroup
.getGroupName() : itemOrGroup
.getName();
812 groupMap
[ groupName
] = groupMap
[ groupName
] || {};
813 groupMap
[ groupName
][ paramName
] = paramValue
;
817 // Go over all groups, so we make sure we get the complete output
818 // even if the parameters don't include a certain group
819 // eslint-disable-next-line jquery/no-each-util
820 $.each( this.groups
, function ( groupName
, groupModel
) {
821 result
= $.extend( true, {}, result
, groupModel
.getFilterRepresentation( groupMap
[ groupName
] ) );
828 * Get the highlight parameters based on current filter configuration
830 * @return {Object} Object where keys are `<filter name>_color` and values
831 * are the selected highlight colors.
833 FiltersViewModel
.prototype.getHighlightParameters = function () {
834 var highlightEnabled
= this.isHighlightEnabled(),
837 this.getItems().forEach( function ( filterItem
) {
838 if ( filterItem
.isHighlightSupported() ) {
839 result
[ filterItem
.getName() + '_color' ] = highlightEnabled
&& filterItem
.isHighlighted() ?
840 filterItem
.getHighlightColor() :
849 * Get an object representing the complete empty state of highlights
851 * @return {Object} Object containing all the highlight parameters set to their negative value
853 FiltersViewModel
.prototype.getEmptyHighlightParameters = function () {
856 this.getItems().forEach( function ( filterItem
) {
857 if ( filterItem
.isHighlightSupported() ) {
858 result
[ filterItem
.getName() + '_color' ] = null;
866 * Get an array of currently applied highlight colors
868 * @return {string[]} Currently applied highlight colors
870 FiltersViewModel
.prototype.getCurrentlyUsedHighlightColors = function () {
873 if ( this.isHighlightEnabled() ) {
874 this.getHighlightedItems().forEach( function ( filterItem
) {
875 var color
= filterItem
.getHighlightColor();
877 if ( result
.indexOf( color
) === -1 ) {
878 result
.push( color
);
887 * Sanitize value group of a string_option groups type
888 * Remove duplicates and make sure to only use valid
892 * @param {string} groupName Group name
893 * @param {string[]} valueArray Array of values
894 * @return {string[]} Array of valid values
896 FiltersViewModel
.prototype.sanitizeStringOptionGroup = function ( groupName
, valueArray
) {
897 var validNames
= this.getGroupFilters( groupName
).map( function ( filterItem
) {
898 return filterItem
.getParamName();
901 return mw
.rcfilters
.utils
.normalizeParamOptions( valueArray
, validNames
);
905 * Check whether no visible filter is selected.
907 * Filter groups that are hidden or sticky are not shown in the
908 * active filters area and therefore not included in this check.
910 * @return {boolean} No visible filter is selected
912 FiltersViewModel
.prototype.areVisibleFiltersEmpty = function () {
913 // Check if there are either any selected items or any items
914 // that have highlight enabled
915 return !this.getItems().some( function ( filterItem
) {
916 var visible
= !filterItem
.getGroupModel().isSticky() && !filterItem
.getGroupModel().isHidden(),
917 active
= ( filterItem
.isSelected() || filterItem
.isHighlighted() );
918 return visible
&& active
;
923 * Check whether the invert state is a valid one. A valid invert state is one where
924 * there are actual namespaces selected.
926 * This is done to compare states to previous ones that may have had the invert model
927 * selected but effectively had no namespaces, so are not effectively different than
928 * ones where invert is not selected.
930 * @return {boolean} Invert is effectively selected
932 FiltersViewModel
.prototype.areNamespacesEffectivelyInverted = function () {
933 return this.getInvertModel().isSelected() &&
934 this.findSelectedItems().some( function ( itemModel
) {
935 return itemModel
.getGroupModel().getName() === 'namespace';
940 * Get the item that matches the given name
942 * @param {string} name Filter name
943 * @return {mw.rcfilters.dm.FilterItem} Filter item
945 FiltersViewModel
.prototype.getItemByName = function ( name
) {
946 return this.getItems().filter( function ( item
) {
947 return name
=== item
.getName();
952 * Set all filters to false or empty/all
953 * This is equivalent to display all.
955 FiltersViewModel
.prototype.emptyAllFilters = function () {
956 this.getItems().forEach( function ( filterItem
) {
957 if ( !filterItem
.getGroupModel().isSticky() ) {
958 this.toggleFilterSelected( filterItem
.getName(), false );
964 * Toggle selected state of one item
966 * @param {string} name Name of the filter item
967 * @param {boolean} [isSelected] Filter selected state
969 FiltersViewModel
.prototype.toggleFilterSelected = function ( name
, isSelected
) {
970 var item
= this.getItemByName( name
);
973 item
.toggleSelected( isSelected
);
978 * Toggle selected state of items by their names
980 * @param {Object} filterDef Filter definitions
982 FiltersViewModel
.prototype.toggleFiltersSelected = function ( filterDef
) {
983 Object
.keys( filterDef
).forEach( function ( name
) {
984 this.toggleFilterSelected( name
, filterDef
[ name
] );
989 * Get a group model from its name
991 * @param {string} groupName Group name
992 * @return {mw.rcfilters.dm.FilterGroup} Group model
994 FiltersViewModel
.prototype.getGroup = function ( groupName
) {
995 return this.groups
[ groupName
];
999 * Get all filters within a specified group by its name
1001 * @param {string} groupName Group name
1002 * @return {mw.rcfilters.dm.FilterItem[]} Filters belonging to this group
1004 FiltersViewModel
.prototype.getGroupFilters = function ( groupName
) {
1005 return ( this.getGroup( groupName
) && this.getGroup( groupName
).getItems() ) || [];
1009 * Find items whose labels match the given string
1011 * @param {string} query Search string
1012 * @param {boolean} [returnFlat] Return a flat array. If false, the result
1013 * is an object whose keys are the group names and values are an array of
1014 * filters per group. If set to true, returns an array of filters regardless
1016 * @return {Object} An object of items to show
1017 * arranged by their group names
1019 FiltersViewModel
.prototype.findMatches = function ( query
, returnFlat
) {
1020 var i
, searchIsEmpty
,
1024 view
= this.getViewByTrigger( query
.substr( 0, 1 ) ),
1025 items
= this.getFiltersByView( view
);
1027 // Normalize so we can search strings regardless of case and view
1028 query
= query
.trim().toLowerCase();
1029 if ( view
!== 'default' ) {
1030 query
= query
.substr( 1 );
1032 // Trim again to also intercept cases where the spaces were after the trigger
1034 query
= query
.trim();
1036 // Check if the search if actually empty; this can be a problem when
1037 // we use prefixes to denote different views
1038 searchIsEmpty
= query
.length
=== 0;
1040 // item label starting with the query string
1041 for ( i
= 0; i
< items
.length
; i
++ ) {
1044 items
[ i
].getLabel().toLowerCase().indexOf( query
) === 0 ||
1046 // For tags, we want the parameter name to be included in the search
1048 items
[ i
].getParamName().toLowerCase().indexOf( query
) > -1
1051 result
[ items
[ i
].getGroupName() ] = result
[ items
[ i
].getGroupName() ] || [];
1052 result
[ items
[ i
].getGroupName() ].push( items
[ i
] );
1053 flatResult
.push( items
[ i
] );
1057 if ( $.isEmptyObject( result
) ) {
1058 // item containing the query string in their label, description, or group title
1059 for ( i
= 0; i
< items
.length
; i
++ ) {
1060 groupTitle
= items
[ i
].getGroupModel().getTitle();
1063 items
[ i
].getLabel().toLowerCase().indexOf( query
) > -1 ||
1064 items
[ i
].getDescription().toLowerCase().indexOf( query
) > -1 ||
1065 groupTitle
.toLowerCase().indexOf( query
) > -1 ||
1067 // For tags, we want the parameter name to be included in the search
1069 items
[ i
].getParamName().toLowerCase().indexOf( query
) > -1
1072 result
[ items
[ i
].getGroupName() ] = result
[ items
[ i
].getGroupName() ] || [];
1073 result
[ items
[ i
].getGroupName() ].push( items
[ i
] );
1074 flatResult
.push( items
[ i
] );
1079 return returnFlat
? flatResult
: result
;
1083 * Get items that are highlighted
1085 * @return {mw.rcfilters.dm.FilterItem[]} Highlighted items
1087 FiltersViewModel
.prototype.getHighlightedItems = function () {
1088 return this.getItems().filter( function ( filterItem
) {
1089 return filterItem
.isHighlightSupported() &&
1090 filterItem
.getHighlightColor();
1095 * Get items that allow highlights even if they're not currently highlighted
1097 * @return {mw.rcfilters.dm.FilterItem[]} Items supporting highlights
1099 FiltersViewModel
.prototype.getItemsSupportingHighlights = function () {
1100 return this.getItems().filter( function ( filterItem
) {
1101 return filterItem
.isHighlightSupported();
1106 * Get all selected items
1108 * @return {mw.rcfilters.dm.FilterItem[]} Selected items
1110 FiltersViewModel
.prototype.findSelectedItems = function () {
1111 var allSelected
= [];
1113 // eslint-disable-next-line jquery/no-each-util
1114 $.each( this.getFilterGroups(), function ( groupName
, groupModel
) {
1115 allSelected
= allSelected
.concat( groupModel
.findSelectedItems() );
1122 * Get the current view
1124 * @return {string} Current view
1126 FiltersViewModel
.prototype.getCurrentView = function () {
1127 return this.currentView
;
1131 * Get the label for the current view
1133 * @param {string} viewName View name
1134 * @return {string} Label for the current view
1136 FiltersViewModel
.prototype.getViewTitle = function ( viewName
) {
1137 viewName
= viewName
|| this.getCurrentView();
1139 return this.views
[ viewName
] && this.views
[ viewName
].title
;
1143 * Get the view that fits the given trigger
1145 * @param {string} trigger Trigger
1146 * @return {string} Name of view
1148 FiltersViewModel
.prototype.getViewByTrigger = function ( trigger
) {
1149 var result
= 'default';
1151 // eslint-disable-next-line jquery/no-each-util
1152 $.each( this.views
, function ( name
, data
) {
1153 if ( data
.trigger
=== trigger
) {
1162 * Return a version of the given string that is without any
1165 * @param {string} str Given string
1166 * @return {string} Result
1168 FiltersViewModel
.prototype.removeViewTriggers = function ( str
) {
1169 if ( this.getViewFromString( str
) !== 'default' ) {
1170 str
= str
.substr( 1 );
1177 * Get the view from the given string by a trigger, if it exists
1179 * @param {string} str Given string
1180 * @return {string} View name
1182 FiltersViewModel
.prototype.getViewFromString = function ( str
) {
1183 return this.getViewByTrigger( str
.substr( 0, 1 ) );
1187 * Set the current search for the system.
1188 * This also dictates what items and groups are visible according
1189 * to the search in #findMatches
1191 * @param {string} searchQuery Search query, including triggers
1192 * @fires searchChange
1194 FiltersViewModel
.prototype.setSearch = function ( searchQuery
) {
1195 var visibleGroups
, visibleGroupNames
;
1197 if ( this.searchQuery
!== searchQuery
) {
1198 // Check if the view changed
1199 this.switchView( this.getViewFromString( searchQuery
) );
1201 visibleGroups
= this.findMatches( searchQuery
);
1202 visibleGroupNames
= Object
.keys( visibleGroups
);
1204 // Update visibility of items and groups
1205 // eslint-disable-next-line jquery/no-each-util
1206 $.each( this.getFilterGroups(), function ( groupName
, groupModel
) {
1207 // Check if the group is visible at all
1208 groupModel
.toggleVisible( visibleGroupNames
.indexOf( groupName
) !== -1 );
1209 groupModel
.setVisibleItems( visibleGroups
[ groupName
] || [] );
1212 this.searchQuery
= searchQuery
;
1213 this.emit( 'searchChange', this.searchQuery
);
1218 * Get the current search
1220 * @return {string} Current search query
1222 FiltersViewModel
.prototype.getSearch = function () {
1223 return this.searchQuery
;
1227 * Switch the current view
1230 * @param {string} view View name
1232 FiltersViewModel
.prototype.switchView = function ( view
) {
1233 if ( this.views
[ view
] && this.currentView
!== view
) {
1234 this.currentView
= view
;
1239 * Toggle the highlight feature on and off.
1240 * Propagate the change to filter items.
1242 * @param {boolean} enable Highlight should be enabled
1243 * @fires highlightChange
1245 FiltersViewModel
.prototype.toggleHighlight = function ( enable
) {
1246 enable
= enable
=== undefined ? !this.highlightEnabled
: enable
;
1248 if ( this.highlightEnabled
!== enable
) {
1249 this.highlightEnabled
= enable
;
1250 this.emit( 'highlightChange', this.highlightEnabled
);
1255 * Check if the highlight feature is enabled
1258 FiltersViewModel
.prototype.isHighlightEnabled = function () {
1259 return !!this.highlightEnabled
;
1263 * Toggle the inverted namespaces property on and off.
1264 * Propagate the change to namespace filter items.
1266 * @param {boolean} enable Inverted property is enabled
1268 FiltersViewModel
.prototype.toggleInvertedNamespaces = function ( enable
) {
1269 this.toggleFilterSelected( this.getInvertModel().getName(), enable
);
1273 * Get the model object that represents the 'invert' filter
1275 * @return {mw.rcfilters.dm.FilterItem}
1277 FiltersViewModel
.prototype.getInvertModel = function () {
1278 return this.getGroup( 'invertGroup' ).getItemByParamName( 'invert' );
1282 * Set highlight color for a specific filter item
1284 * @param {string} filterName Name of the filter item
1285 * @param {string} color Selected color
1287 FiltersViewModel
.prototype.setHighlightColor = function ( filterName
, color
) {
1288 this.getItemByName( filterName
).setHighlightColor( color
);
1292 * Clear highlight for a specific filter item
1294 * @param {string} filterName Name of the filter item
1296 FiltersViewModel
.prototype.clearHighlightColor = function ( filterName
) {
1297 this.getItemByName( filterName
).clearHighlightColor();
1300 module
.exports
= FiltersViewModel
;