build: Update eslint-config-wikimedia to 0.10.0
[lhc/web/wiklou.git] / resources / src / mediawiki.rcfilters / dm / mw.rcfilters.dm.FiltersViewModel.js
1 ( function () {
2 /**
3 * View model for the filters selection and display
4 *
5 * @mixins OO.EventEmitter
6 * @mixins OO.EmitterList
7 *
8 * @constructor
9 */
10 mw.rcfilters.dm.FiltersViewModel = function MwRcfiltersDmFiltersViewModel() {
11 // Mixin constructor
12 OO.EventEmitter.call( this );
13 OO.EmitterList.call( this );
14
15 this.groups = {};
16 this.defaultParams = {};
17 this.highlightEnabled = false;
18 this.parameterMap = {};
19 this.emptyParameterState = null;
20
21 this.views = {};
22 this.currentView = 'default';
23 this.searchQuery = null;
24
25 // Events
26 this.aggregate( { update: 'filterItemUpdate' } );
27 this.connect( this, { filterItemUpdate: [ 'emit', 'itemUpdate' ] } );
28 };
29
30 /* Initialization */
31 OO.initClass( mw.rcfilters.dm.FiltersViewModel );
32 OO.mixinClass( mw.rcfilters.dm.FiltersViewModel, OO.EventEmitter );
33 OO.mixinClass( mw.rcfilters.dm.FiltersViewModel, OO.EmitterList );
34
35 /* Events */
36
37 /**
38 * @event initialize
39 *
40 * Filter list is initialized
41 */
42
43 /**
44 * @event update
45 *
46 * Model has been updated
47 */
48
49 /**
50 * @event itemUpdate
51 * @param {mw.rcfilters.dm.FilterItem} item Filter item updated
52 *
53 * Filter item has changed
54 */
55
56 /**
57 * @event highlightChange
58 * @param {boolean} Highlight feature is enabled
59 *
60 * Highlight feature has been toggled enabled or disabled
61 */
62
63 /* Methods */
64
65 /**
66 * Re-assess the states of filter items based on the interactions between them
67 *
68 * @param {mw.rcfilters.dm.FilterItem} [item] Changed item. If not given, the
69 * method will go over the state of all items
70 */
71 mw.rcfilters.dm.FiltersViewModel.prototype.reassessFilterInteractions = function ( item ) {
72 var allSelected,
73 model = this,
74 iterationItems = item !== undefined ? [ item ] : this.getItems();
75
76 iterationItems.forEach( function ( checkedItem ) {
77 var allCheckedItems = checkedItem.getSubset().concat( [ checkedItem.getName() ] ),
78 groupModel = checkedItem.getGroupModel();
79
80 // Check for subsets (included filters) plus the item itself:
81 allCheckedItems.forEach( function ( filterItemName ) {
82 var itemInSubset = model.getItemByName( filterItemName );
83
84 itemInSubset.toggleIncluded(
85 // If any of itemInSubset's supersets are selected, this item
86 // is included
87 itemInSubset.getSuperset().some( function ( supersetName ) {
88 return ( model.getItemByName( supersetName ).isSelected() );
89 } )
90 );
91 } );
92
93 // Update coverage for the changed group
94 if ( groupModel.isFullCoverage() ) {
95 allSelected = groupModel.areAllSelected();
96 groupModel.getItems().forEach( function ( filterItem ) {
97 filterItem.toggleFullyCovered( allSelected );
98 } );
99 }
100 } );
101
102 // Check for conflicts
103 // In this case, we must go over all items, since
104 // conflicts are bidirectional and depend not only on
105 // individual items, but also on the selected states of
106 // the groups they're in.
107 this.getItems().forEach( function ( filterItem ) {
108 var inConflict = false,
109 filterItemGroup = filterItem.getGroupModel();
110
111 // For each item, see if that item is still conflicting
112 // eslint-disable-next-line jquery/no-each-util
113 $.each( model.groups, function ( groupName, groupModel ) {
114 if ( filterItem.getGroupName() === groupName ) {
115 // Check inside the group
116 inConflict = groupModel.areAnySelectedInConflictWith( filterItem );
117 } else {
118 // According to the spec, if two items conflict from two different
119 // groups, the conflict only lasts if the groups **only have selected
120 // items that are conflicting**. If a group has selected items that
121 // are conflicting and non-conflicting, the scope of the result has
122 // expanded enough to completely remove the conflict.
123
124 // For example, see two groups with conflicts:
125 // userExpLevel: [
126 // {
127 // name: 'experienced',
128 // conflicts: [ 'unregistered' ]
129 // }
130 // ],
131 // registration: [
132 // {
133 // name: 'registered',
134 // },
135 // {
136 // name: 'unregistered',
137 // }
138 // ]
139 // If we select 'experienced', then 'unregistered' is in conflict (and vice versa),
140 // because, inherently, 'experienced' filter only includes registered users, and so
141 // both filters are in conflict with one another.
142 // However, the minute we select 'registered', the scope of our results
143 // has expanded to no longer have a conflict with 'experienced' filter, and
144 // so the conflict is removed.
145
146 // In our case, we need to check if the entire group conflicts with
147 // the entire item's group, so we follow the above spec
148 inConflict = (
149 // The foreign group is in conflict with this item
150 groupModel.areAllSelectedInConflictWith( filterItem ) &&
151 // Every selected member of the item's own group is also
152 // in conflict with the other group
153 filterItemGroup.findSelectedItems().every( function ( otherGroupItem ) {
154 return groupModel.areAllSelectedInConflictWith( otherGroupItem );
155 } )
156 );
157 }
158
159 // If we're in conflict, this will return 'false' which
160 // will break the loop. Otherwise, we're not in conflict
161 // and the loop continues
162 return !inConflict;
163 } );
164
165 // Toggle the item state
166 filterItem.toggleConflicted( inConflict );
167 } );
168 };
169
170 /**
171 * Get whether the model has any conflict in its items
172 *
173 * @return {boolean} There is a conflict
174 */
175 mw.rcfilters.dm.FiltersViewModel.prototype.hasConflict = function () {
176 return this.getItems().some( function ( filterItem ) {
177 return filterItem.isSelected() && filterItem.isConflicted();
178 } );
179 };
180
181 /**
182 * Get the first item with a current conflict
183 *
184 * @return {mw.rcfilters.dm.FilterItem} Conflicted item
185 */
186 mw.rcfilters.dm.FiltersViewModel.prototype.getFirstConflictedItem = function () {
187 var conflictedItem;
188
189 this.getItems().forEach( function ( filterItem ) {
190 if ( filterItem.isSelected() && filterItem.isConflicted() ) {
191 conflictedItem = filterItem;
192 return false;
193 }
194 } );
195
196 return conflictedItem;
197 };
198
199 /**
200 * Set filters and preserve a group relationship based on
201 * the definition given by an object
202 *
203 * @param {Array} filterGroups Filters definition
204 * @param {Object} [views] Extra views definition
205 * Expected in the following format:
206 * {
207 * namespaces: {
208 * label: 'namespaces', // Message key
209 * trigger: ':',
210 * groups: [
211 * {
212 * // Group info
213 * name: 'namespaces' // Parameter name
214 * title: 'namespaces' // Message key
215 * type: 'string_options',
216 * separator: ';',
217 * labelPrefixKey: { 'default': 'rcfilters-tag-prefix-namespace', inverted: 'rcfilters-tag-prefix-namespace-inverted' },
218 * fullCoverage: true
219 * items: []
220 * }
221 * ]
222 * }
223 * }
224 */
225 mw.rcfilters.dm.FiltersViewModel.prototype.initializeFilters = function ( filterGroups, views ) {
226 var filterConflictResult, groupConflictResult,
227 allViews = {},
228 model = this,
229 items = [],
230 groupConflictMap = {},
231 filterConflictMap = {},
232 /*!
233 * Expand a conflict definition from group name to
234 * the list of all included filters in that group.
235 * We do this so that the direct relationship in the
236 * models are consistently item->items rather than
237 * mixing item->group with item->item.
238 *
239 * @param {Object} obj Conflict definition
240 * @return {Object} Expanded conflict definition
241 */
242 expandConflictDefinitions = function ( obj ) {
243 var result = {};
244
245 // eslint-disable-next-line jquery/no-each-util
246 $.each( obj, function ( key, conflicts ) {
247 var filterName,
248 adjustedConflicts = {};
249
250 conflicts.forEach( function ( conflict ) {
251 var filter;
252
253 if ( conflict.filter ) {
254 filterName = model.groups[ conflict.group ].getPrefixedName( conflict.filter );
255 filter = model.getItemByName( filterName );
256
257 // Rename
258 adjustedConflicts[ filterName ] = $.extend(
259 {},
260 conflict,
261 {
262 filter: filterName,
263 item: filter
264 }
265 );
266 } else {
267 // This conflict is for an entire group. Split it up to
268 // represent each filter
269
270 // Get the relevant group items
271 model.groups[ conflict.group ].getItems().forEach( function ( groupItem ) {
272 // Rebuild the conflict
273 adjustedConflicts[ groupItem.getName() ] = $.extend(
274 {},
275 conflict,
276 {
277 filter: groupItem.getName(),
278 item: groupItem
279 }
280 );
281 } );
282 }
283 } );
284
285 result[ key ] = adjustedConflicts;
286 } );
287
288 return result;
289 };
290
291 // Reset
292 this.clearItems();
293 this.groups = {};
294 this.views = {};
295
296 // Clone
297 filterGroups = OO.copy( filterGroups );
298
299 // Normalize definition from the server
300 filterGroups.forEach( function ( data ) {
301 var i;
302 // What's this information needs to be normalized
303 data.whatsThis = {
304 body: data.whatsThisBody,
305 header: data.whatsThisHeader,
306 linkText: data.whatsThisLinkText,
307 url: data.whatsThisUrl
308 };
309
310 // Title is a msg-key
311 data.title = data.title ? mw.msg( data.title ) : data.name;
312
313 // Filters are given to us with msg-keys, we need
314 // to translate those before we hand them off
315 for ( i = 0; i < data.filters.length; i++ ) {
316 data.filters[ i ].label = data.filters[ i ].label ? mw.msg( data.filters[ i ].label ) : data.filters[ i ].name;
317 data.filters[ i ].description = data.filters[ i ].description ? mw.msg( data.filters[ i ].description ) : '';
318 }
319 } );
320
321 // Collect views
322 allViews = $.extend( true, {
323 default: {
324 title: mw.msg( 'rcfilters-filterlist-title' ),
325 groups: filterGroups
326 }
327 }, views );
328
329 // Go over all views
330 // eslint-disable-next-line jquery/no-each-util
331 $.each( allViews, function ( viewName, viewData ) {
332 // Define the view
333 model.views[ viewName ] = {
334 name: viewData.name,
335 title: viewData.title,
336 trigger: viewData.trigger
337 };
338
339 // Go over groups
340 viewData.groups.forEach( function ( groupData ) {
341 var group = groupData.name;
342
343 if ( !model.groups[ group ] ) {
344 model.groups[ group ] = new mw.rcfilters.dm.FilterGroup(
345 group,
346 $.extend( true, {}, groupData, { view: viewName } )
347 );
348 }
349
350 model.groups[ group ].initializeFilters( groupData.filters, groupData.default );
351 items = items.concat( model.groups[ group ].getItems() );
352
353 // Prepare conflicts
354 if ( groupData.conflicts ) {
355 // Group conflicts
356 groupConflictMap[ group ] = groupData.conflicts;
357 }
358
359 groupData.filters.forEach( function ( itemData ) {
360 var filterItem = model.groups[ group ].getItemByParamName( itemData.name );
361 // Filter conflicts
362 if ( itemData.conflicts ) {
363 filterConflictMap[ filterItem.getName() ] = itemData.conflicts;
364 }
365 } );
366 } );
367 } );
368
369 // Add item references to the model, for lookup
370 this.addItems( items );
371
372 // Expand conflicts
373 groupConflictResult = expandConflictDefinitions( groupConflictMap );
374 filterConflictResult = expandConflictDefinitions( filterConflictMap );
375
376 // Set conflicts for groups
377 // eslint-disable-next-line jquery/no-each-util
378 $.each( groupConflictResult, function ( group, conflicts ) {
379 model.groups[ group ].setConflicts( conflicts );
380 } );
381
382 // Set conflicts for items
383 // eslint-disable-next-line jquery/no-each-util
384 $.each( filterConflictResult, function ( filterName, conflicts ) {
385 var filterItem = model.getItemByName( filterName );
386 // set conflicts for items in the group
387 filterItem.setConflicts( conflicts );
388 } );
389
390 // Create a map between known parameters and their models
391 // eslint-disable-next-line jquery/no-each-util
392 $.each( this.groups, function ( group, groupModel ) {
393 if (
394 groupModel.getType() === 'send_unselected_if_any' ||
395 groupModel.getType() === 'boolean' ||
396 groupModel.getType() === 'any_value'
397 ) {
398 // Individual filters
399 groupModel.getItems().forEach( function ( filterItem ) {
400 model.parameterMap[ filterItem.getParamName() ] = filterItem;
401 } );
402 } else if (
403 groupModel.getType() === 'string_options' ||
404 groupModel.getType() === 'single_option'
405 ) {
406 // Group
407 model.parameterMap[ groupModel.getName() ] = groupModel;
408 }
409 } );
410
411 this.setSearch( '' );
412
413 this.updateHighlightedState();
414
415 // Finish initialization
416 this.emit( 'initialize' );
417 };
418
419 /**
420 * Update filter view model state based on a parameter object
421 *
422 * @param {Object} params Parameters object
423 */
424 mw.rcfilters.dm.FiltersViewModel.prototype.updateStateFromParams = function ( params ) {
425 var filtersValue;
426 // For arbitrary numeric single_option values make sure the values
427 // are normalized to fit within the limits
428 // eslint-disable-next-line jquery/no-each-util
429 $.each( this.getFilterGroups(), function ( groupName, groupModel ) {
430 params[ groupName ] = groupModel.normalizeArbitraryValue( params[ groupName ] );
431 } );
432
433 // Update filter values
434 filtersValue = this.getFiltersFromParameters( params );
435 Object.keys( filtersValue ).forEach( function ( filterName ) {
436 this.getItemByName( filterName ).setValue( filtersValue[ filterName ] );
437 }.bind( this ) );
438
439 // Update highlight state
440 this.getItemsSupportingHighlights().forEach( function ( filterItem ) {
441 var color = params[ filterItem.getName() + '_color' ];
442 if ( color ) {
443 filterItem.setHighlightColor( color );
444 } else {
445 filterItem.clearHighlightColor();
446 }
447 } );
448 this.updateHighlightedState();
449
450 // Check all filter interactions
451 this.reassessFilterInteractions();
452 };
453
454 /**
455 * Get a representation of an empty (falsey) parameter state
456 *
457 * @return {Object} Empty parameter state
458 */
459 mw.rcfilters.dm.FiltersViewModel.prototype.getEmptyParameterState = function () {
460 if ( !this.emptyParameterState ) {
461 this.emptyParameterState = $.extend(
462 true,
463 {},
464 this.getParametersFromFilters( {} ),
465 this.getEmptyHighlightParameters()
466 );
467 }
468 return this.emptyParameterState;
469 };
470
471 /**
472 * Get a representation of only the non-falsey parameters
473 *
474 * @param {Object} [parameters] A given parameter state to minimize. If not given the current
475 * state of the system will be used.
476 * @return {Object} Empty parameter state
477 */
478 mw.rcfilters.dm.FiltersViewModel.prototype.getMinimizedParamRepresentation = function ( parameters ) {
479 var result = {};
480
481 parameters = parameters ? $.extend( true, {}, parameters ) : this.getCurrentParameterState();
482
483 // Params
484 // eslint-disable-next-line jquery/no-each-util
485 $.each( this.getEmptyParameterState(), function ( param, value ) {
486 if ( parameters[ param ] !== undefined && parameters[ param ] !== value ) {
487 result[ param ] = parameters[ param ];
488 }
489 } );
490
491 // Highlights
492 Object.keys( this.getEmptyHighlightParameters() ).forEach( function ( param ) {
493 if ( parameters[ param ] ) {
494 // If a highlight parameter is not undefined and not null
495 // add it to the result
496 result[ param ] = parameters[ param ];
497 }
498 } );
499
500 return result;
501 };
502
503 /**
504 * Get a representation of the full parameter list, including all base values
505 *
506 * @return {Object} Full parameter representation
507 */
508 mw.rcfilters.dm.FiltersViewModel.prototype.getExpandedParamRepresentation = function () {
509 return $.extend(
510 true,
511 {},
512 this.getEmptyParameterState(),
513 this.getCurrentParameterState()
514 );
515 };
516
517 /**
518 * Get a parameter representation of the current state of the model
519 *
520 * @param {boolean} [removeStickyParams] Remove sticky filters from final result
521 * @return {Object} Parameter representation of the current state of the model
522 */
523 mw.rcfilters.dm.FiltersViewModel.prototype.getCurrentParameterState = function ( removeStickyParams ) {
524 var state = this.getMinimizedParamRepresentation( $.extend(
525 true,
526 {},
527 this.getParametersFromFilters( this.getSelectedState() ),
528 this.getHighlightParameters()
529 ) );
530
531 if ( removeStickyParams ) {
532 state = this.removeStickyParams( state );
533 }
534
535 return state;
536 };
537
538 /**
539 * Delete sticky parameters from given object.
540 *
541 * @param {Object} paramState Parameter state
542 * @return {Object} Parameter state without sticky parameters
543 */
544 mw.rcfilters.dm.FiltersViewModel.prototype.removeStickyParams = function ( paramState ) {
545 this.getStickyParams().forEach( function ( paramName ) {
546 delete paramState[ paramName ];
547 } );
548
549 return paramState;
550 };
551
552 /**
553 * Turn the highlight feature on or off
554 */
555 mw.rcfilters.dm.FiltersViewModel.prototype.updateHighlightedState = function () {
556 this.toggleHighlight( this.getHighlightedItems().length > 0 );
557 };
558
559 /**
560 * Get the object that defines groups by their name.
561 *
562 * @return {Object} Filter groups
563 */
564 mw.rcfilters.dm.FiltersViewModel.prototype.getFilterGroups = function () {
565 return this.groups;
566 };
567
568 /**
569 * Get the object that defines groups that match a certain view by their name.
570 *
571 * @param {string} [view] Requested view. If not given, uses current view
572 * @return {Object} Filter groups matching a display group
573 */
574 mw.rcfilters.dm.FiltersViewModel.prototype.getFilterGroupsByView = function ( view ) {
575 var result = {};
576
577 view = view || this.getCurrentView();
578
579 // eslint-disable-next-line jquery/no-each-util
580 $.each( this.groups, function ( groupName, groupModel ) {
581 if ( groupModel.getView() === view ) {
582 result[ groupName ] = groupModel;
583 }
584 } );
585
586 return result;
587 };
588
589 /**
590 * Get an array of filters matching the given display group.
591 *
592 * @param {string} [view] Requested view. If not given, uses current view
593 * @return {mw.rcfilters.dm.FilterItem} Filter items matching the group
594 */
595 mw.rcfilters.dm.FiltersViewModel.prototype.getFiltersByView = function ( view ) {
596 var groups,
597 result = [];
598
599 view = view || this.getCurrentView();
600
601 groups = this.getFilterGroupsByView( view );
602
603 // eslint-disable-next-line jquery/no-each-util
604 $.each( groups, function ( groupName, groupModel ) {
605 result = result.concat( groupModel.getItems() );
606 } );
607
608 return result;
609 };
610
611 /**
612 * Get the trigger for the requested view.
613 *
614 * @param {string} view View name
615 * @return {string} View trigger, if exists
616 */
617 mw.rcfilters.dm.FiltersViewModel.prototype.getViewTrigger = function ( view ) {
618 return ( this.views[ view ] && this.views[ view ].trigger ) || '';
619 };
620
621 /**
622 * Get the value of a specific parameter
623 *
624 * @param {string} name Parameter name
625 * @return {number|string} Parameter value
626 */
627 mw.rcfilters.dm.FiltersViewModel.prototype.getParamValue = function ( name ) {
628 return this.parameters[ name ];
629 };
630
631 /**
632 * Get the current selected state of the filters
633 *
634 * @param {boolean} [onlySelected] return an object containing only the filters with a value
635 * @return {Object} Filters selected state
636 */
637 mw.rcfilters.dm.FiltersViewModel.prototype.getSelectedState = function ( onlySelected ) {
638 var i,
639 items = this.getItems(),
640 result = {};
641
642 for ( i = 0; i < items.length; i++ ) {
643 if ( !onlySelected || items[ i ].getValue() ) {
644 result[ items[ i ].getName() ] = items[ i ].getValue();
645 }
646 }
647
648 return result;
649 };
650
651 /**
652 * Get the current full state of the filters
653 *
654 * @return {Object} Filters full state
655 */
656 mw.rcfilters.dm.FiltersViewModel.prototype.getFullState = function () {
657 var i,
658 items = this.getItems(),
659 result = {};
660
661 for ( i = 0; i < items.length; i++ ) {
662 result[ items[ i ].getName() ] = {
663 selected: items[ i ].isSelected(),
664 conflicted: items[ i ].isConflicted(),
665 included: items[ i ].isIncluded()
666 };
667 }
668
669 return result;
670 };
671
672 /**
673 * Get an object representing default parameters state
674 *
675 * @return {Object} Default parameter values
676 */
677 mw.rcfilters.dm.FiltersViewModel.prototype.getDefaultParams = function () {
678 var result = {};
679
680 // Get default filter state
681 // eslint-disable-next-line jquery/no-each-util
682 $.each( this.groups, function ( name, model ) {
683 if ( !model.isSticky() ) {
684 $.extend( true, result, model.getDefaultParams() );
685 }
686 } );
687
688 return result;
689 };
690
691 /**
692 * Get a parameter representation of all sticky parameters
693 *
694 * @return {Object} Sticky parameter values
695 */
696 mw.rcfilters.dm.FiltersViewModel.prototype.getStickyParams = function () {
697 var result = [];
698
699 // eslint-disable-next-line jquery/no-each-util
700 $.each( this.groups, function ( name, model ) {
701 if ( model.isSticky() ) {
702 if ( model.isPerGroupRequestParameter() ) {
703 result.push( name );
704 } else {
705 // Each filter is its own param
706 result = result.concat( model.getItems().map( function ( filterItem ) {
707 return filterItem.getParamName();
708 } ) );
709 }
710 }
711 } );
712
713 return result;
714 };
715
716 /**
717 * Get a parameter representation of all sticky parameters
718 *
719 * @return {Object} Sticky parameter values
720 */
721 mw.rcfilters.dm.FiltersViewModel.prototype.getStickyParamsValues = function () {
722 var result = {};
723
724 // eslint-disable-next-line jquery/no-each-util
725 $.each( this.groups, function ( name, model ) {
726 if ( model.isSticky() ) {
727 $.extend( true, result, model.getParamRepresentation() );
728 }
729 } );
730
731 return result;
732 };
733
734 /**
735 * Analyze the groups and their filters and output an object representing
736 * the state of the parameters they represent.
737 *
738 * @param {Object} [filterDefinition] An object defining the filter values,
739 * keyed by filter names.
740 * @return {Object} Parameter state object
741 */
742 mw.rcfilters.dm.FiltersViewModel.prototype.getParametersFromFilters = function ( filterDefinition ) {
743 var groupItemDefinition,
744 result = {},
745 groupItems = this.getFilterGroups();
746
747 if ( filterDefinition ) {
748 groupItemDefinition = {};
749 // Filter definition is "flat", but in effect
750 // each group needs to tell us its result based
751 // on the values in it. We need to split this list
752 // back into groupings so we can "feed" it to the
753 // loop below, and we need to expand it so it includes
754 // all filters (set to false)
755 this.getItems().forEach( function ( filterItem ) {
756 groupItemDefinition[ filterItem.getGroupName() ] = groupItemDefinition[ filterItem.getGroupName() ] || {};
757 groupItemDefinition[ filterItem.getGroupName() ][ filterItem.getName() ] = filterItem.coerceValue( filterDefinition[ filterItem.getName() ] );
758 } );
759 }
760
761 // eslint-disable-next-line jquery/no-each-util
762 $.each( groupItems, function ( group, model ) {
763 $.extend(
764 result,
765 model.getParamRepresentation(
766 groupItemDefinition ?
767 groupItemDefinition[ group ] : null
768 )
769 );
770 } );
771
772 return result;
773 };
774
775 /**
776 * This is the opposite of the #getParametersFromFilters method; this goes over
777 * the given parameters and translates into a selected/unselected value in the filters.
778 *
779 * @param {Object} params Parameters query object
780 * @return {Object} Filter state object
781 */
782 mw.rcfilters.dm.FiltersViewModel.prototype.getFiltersFromParameters = function ( params ) {
783 var groupMap = {},
784 model = this,
785 result = {};
786
787 // Go over the given parameters, break apart to groupings
788 // The resulting object represents the group with its parameter
789 // values. For example:
790 // {
791 // group1: {
792 // param1: "1",
793 // param2: "0",
794 // param3: "1"
795 // },
796 // group2: "param4|param5"
797 // }
798 // eslint-disable-next-line jquery/no-each-util
799 $.each( params, function ( paramName, paramValue ) {
800 var groupName,
801 itemOrGroup = model.parameterMap[ paramName ];
802
803 if ( itemOrGroup ) {
804 groupName = itemOrGroup instanceof mw.rcfilters.dm.FilterItem ?
805 itemOrGroup.getGroupName() : itemOrGroup.getName();
806
807 groupMap[ groupName ] = groupMap[ groupName ] || {};
808 groupMap[ groupName ][ paramName ] = paramValue;
809 }
810 } );
811
812 // Go over all groups, so we make sure we get the complete output
813 // even if the parameters don't include a certain group
814 // eslint-disable-next-line jquery/no-each-util
815 $.each( this.groups, function ( groupName, groupModel ) {
816 result = $.extend( true, {}, result, groupModel.getFilterRepresentation( groupMap[ groupName ] ) );
817 } );
818
819 return result;
820 };
821
822 /**
823 * Get the highlight parameters based on current filter configuration
824 *
825 * @return {Object} Object where keys are `<filter name>_color` and values
826 * are the selected highlight colors.
827 */
828 mw.rcfilters.dm.FiltersViewModel.prototype.getHighlightParameters = function () {
829 var highlightEnabled = this.isHighlightEnabled(),
830 result = {};
831
832 this.getItems().forEach( function ( filterItem ) {
833 if ( filterItem.isHighlightSupported() ) {
834 result[ filterItem.getName() + '_color' ] = highlightEnabled && filterItem.isHighlighted() ?
835 filterItem.getHighlightColor() :
836 null;
837 }
838 } );
839
840 return result;
841 };
842
843 /**
844 * Get an object representing the complete empty state of highlights
845 *
846 * @return {Object} Object containing all the highlight parameters set to their negative value
847 */
848 mw.rcfilters.dm.FiltersViewModel.prototype.getEmptyHighlightParameters = function () {
849 var result = {};
850
851 this.getItems().forEach( function ( filterItem ) {
852 if ( filterItem.isHighlightSupported() ) {
853 result[ filterItem.getName() + '_color' ] = null;
854 }
855 } );
856
857 return result;
858 };
859
860 /**
861 * Get an array of currently applied highlight colors
862 *
863 * @return {string[]} Currently applied highlight colors
864 */
865 mw.rcfilters.dm.FiltersViewModel.prototype.getCurrentlyUsedHighlightColors = function () {
866 var result = [];
867
868 if ( this.isHighlightEnabled() ) {
869 this.getHighlightedItems().forEach( function ( filterItem ) {
870 var color = filterItem.getHighlightColor();
871
872 if ( result.indexOf( color ) === -1 ) {
873 result.push( color );
874 }
875 } );
876 }
877
878 return result;
879 };
880
881 /**
882 * Sanitize value group of a string_option groups type
883 * Remove duplicates and make sure to only use valid
884 * values.
885 *
886 * @private
887 * @param {string} groupName Group name
888 * @param {string[]} valueArray Array of values
889 * @return {string[]} Array of valid values
890 */
891 mw.rcfilters.dm.FiltersViewModel.prototype.sanitizeStringOptionGroup = function ( groupName, valueArray ) {
892 var validNames = this.getGroupFilters( groupName ).map( function ( filterItem ) {
893 return filterItem.getParamName();
894 } );
895
896 return mw.rcfilters.utils.normalizeParamOptions( valueArray, validNames );
897 };
898
899 /**
900 * Check whether no visible filter is selected.
901 *
902 * Filter groups that are hidden or sticky are not shown in the
903 * active filters area and therefore not included in this check.
904 *
905 * @return {boolean} No visible filter is selected
906 */
907 mw.rcfilters.dm.FiltersViewModel.prototype.areVisibleFiltersEmpty = function () {
908 // Check if there are either any selected items or any items
909 // that have highlight enabled
910 return !this.getItems().some( function ( filterItem ) {
911 var visible = !filterItem.getGroupModel().isSticky() && !filterItem.getGroupModel().isHidden(),
912 active = ( filterItem.isSelected() || filterItem.isHighlighted() );
913 return visible && active;
914 } );
915 };
916
917 /**
918 * Check whether the invert state is a valid one. A valid invert state is one where
919 * there are actual namespaces selected.
920 *
921 * This is done to compare states to previous ones that may have had the invert model
922 * selected but effectively had no namespaces, so are not effectively different than
923 * ones where invert is not selected.
924 *
925 * @return {boolean} Invert is effectively selected
926 */
927 mw.rcfilters.dm.FiltersViewModel.prototype.areNamespacesEffectivelyInverted = function () {
928 return this.getInvertModel().isSelected() &&
929 this.findSelectedItems().some( function ( itemModel ) {
930 return itemModel.getGroupModel().getName() === 'namespace';
931 } );
932 };
933
934 /**
935 * Get the item that matches the given name
936 *
937 * @param {string} name Filter name
938 * @return {mw.rcfilters.dm.FilterItem} Filter item
939 */
940 mw.rcfilters.dm.FiltersViewModel.prototype.getItemByName = function ( name ) {
941 return this.getItems().filter( function ( item ) {
942 return name === item.getName();
943 } )[ 0 ];
944 };
945
946 /**
947 * Set all filters to false or empty/all
948 * This is equivalent to display all.
949 */
950 mw.rcfilters.dm.FiltersViewModel.prototype.emptyAllFilters = function () {
951 this.getItems().forEach( function ( filterItem ) {
952 if ( !filterItem.getGroupModel().isSticky() ) {
953 this.toggleFilterSelected( filterItem.getName(), false );
954 }
955 }.bind( this ) );
956 };
957
958 /**
959 * Toggle selected state of one item
960 *
961 * @param {string} name Name of the filter item
962 * @param {boolean} [isSelected] Filter selected state
963 */
964 mw.rcfilters.dm.FiltersViewModel.prototype.toggleFilterSelected = function ( name, isSelected ) {
965 var item = this.getItemByName( name );
966
967 if ( item ) {
968 item.toggleSelected( isSelected );
969 }
970 };
971
972 /**
973 * Toggle selected state of items by their names
974 *
975 * @param {Object} filterDef Filter definitions
976 */
977 mw.rcfilters.dm.FiltersViewModel.prototype.toggleFiltersSelected = function ( filterDef ) {
978 Object.keys( filterDef ).forEach( function ( name ) {
979 this.toggleFilterSelected( name, filterDef[ name ] );
980 }.bind( this ) );
981 };
982
983 /**
984 * Get a group model from its name
985 *
986 * @param {string} groupName Group name
987 * @return {mw.rcfilters.dm.FilterGroup} Group model
988 */
989 mw.rcfilters.dm.FiltersViewModel.prototype.getGroup = function ( groupName ) {
990 return this.groups[ groupName ];
991 };
992
993 /**
994 * Get all filters within a specified group by its name
995 *
996 * @param {string} groupName Group name
997 * @return {mw.rcfilters.dm.FilterItem[]} Filters belonging to this group
998 */
999 mw.rcfilters.dm.FiltersViewModel.prototype.getGroupFilters = function ( groupName ) {
1000 return ( this.getGroup( groupName ) && this.getGroup( groupName ).getItems() ) || [];
1001 };
1002
1003 /**
1004 * Find items whose labels match the given string
1005 *
1006 * @param {string} query Search string
1007 * @param {boolean} [returnFlat] Return a flat array. If false, the result
1008 * is an object whose keys are the group names and values are an array of
1009 * filters per group. If set to true, returns an array of filters regardless
1010 * of their groups.
1011 * @return {Object} An object of items to show
1012 * arranged by their group names
1013 */
1014 mw.rcfilters.dm.FiltersViewModel.prototype.findMatches = function ( query, returnFlat ) {
1015 var i, searchIsEmpty,
1016 groupTitle,
1017 result = {},
1018 flatResult = [],
1019 view = this.getViewByTrigger( query.substr( 0, 1 ) ),
1020 items = this.getFiltersByView( view );
1021
1022 // Normalize so we can search strings regardless of case and view
1023 query = query.trim().toLowerCase();
1024 if ( view !== 'default' ) {
1025 query = query.substr( 1 );
1026 }
1027 // Trim again to also intercept cases where the spaces were after the trigger
1028 // eg: '# str'
1029 query = query.trim();
1030
1031 // Check if the search if actually empty; this can be a problem when
1032 // we use prefixes to denote different views
1033 searchIsEmpty = query.length === 0;
1034
1035 // item label starting with the query string
1036 for ( i = 0; i < items.length; i++ ) {
1037 if (
1038 searchIsEmpty ||
1039 items[ i ].getLabel().toLowerCase().indexOf( query ) === 0 ||
1040 (
1041 // For tags, we want the parameter name to be included in the search
1042 view === 'tags' &&
1043 items[ i ].getParamName().toLowerCase().indexOf( query ) > -1
1044 )
1045 ) {
1046 result[ items[ i ].getGroupName() ] = result[ items[ i ].getGroupName() ] || [];
1047 result[ items[ i ].getGroupName() ].push( items[ i ] );
1048 flatResult.push( items[ i ] );
1049 }
1050 }
1051
1052 if ( $.isEmptyObject( result ) ) {
1053 // item containing the query string in their label, description, or group title
1054 for ( i = 0; i < items.length; i++ ) {
1055 groupTitle = items[ i ].getGroupModel().getTitle();
1056 if (
1057 searchIsEmpty ||
1058 items[ i ].getLabel().toLowerCase().indexOf( query ) > -1 ||
1059 items[ i ].getDescription().toLowerCase().indexOf( query ) > -1 ||
1060 groupTitle.toLowerCase().indexOf( query ) > -1 ||
1061 (
1062 // For tags, we want the parameter name to be included in the search
1063 view === 'tags' &&
1064 items[ i ].getParamName().toLowerCase().indexOf( query ) > -1
1065 )
1066 ) {
1067 result[ items[ i ].getGroupName() ] = result[ items[ i ].getGroupName() ] || [];
1068 result[ items[ i ].getGroupName() ].push( items[ i ] );
1069 flatResult.push( items[ i ] );
1070 }
1071 }
1072 }
1073
1074 return returnFlat ? flatResult : result;
1075 };
1076
1077 /**
1078 * Get items that are highlighted
1079 *
1080 * @return {mw.rcfilters.dm.FilterItem[]} Highlighted items
1081 */
1082 mw.rcfilters.dm.FiltersViewModel.prototype.getHighlightedItems = function () {
1083 return this.getItems().filter( function ( filterItem ) {
1084 return filterItem.isHighlightSupported() &&
1085 filterItem.getHighlightColor();
1086 } );
1087 };
1088
1089 /**
1090 * Get items that allow highlights even if they're not currently highlighted
1091 *
1092 * @return {mw.rcfilters.dm.FilterItem[]} Items supporting highlights
1093 */
1094 mw.rcfilters.dm.FiltersViewModel.prototype.getItemsSupportingHighlights = function () {
1095 return this.getItems().filter( function ( filterItem ) {
1096 return filterItem.isHighlightSupported();
1097 } );
1098 };
1099
1100 /**
1101 * Get all selected items
1102 *
1103 * @return {mw.rcfilters.dm.FilterItem[]} Selected items
1104 */
1105 mw.rcfilters.dm.FiltersViewModel.prototype.findSelectedItems = function () {
1106 var allSelected = [];
1107
1108 // eslint-disable-next-line jquery/no-each-util
1109 $.each( this.getFilterGroups(), function ( groupName, groupModel ) {
1110 allSelected = allSelected.concat( groupModel.findSelectedItems() );
1111 } );
1112
1113 return allSelected;
1114 };
1115
1116 /**
1117 * Get the current view
1118 *
1119 * @return {string} Current view
1120 */
1121 mw.rcfilters.dm.FiltersViewModel.prototype.getCurrentView = function () {
1122 return this.currentView;
1123 };
1124
1125 /**
1126 * Get the label for the current view
1127 *
1128 * @param {string} viewName View name
1129 * @return {string} Label for the current view
1130 */
1131 mw.rcfilters.dm.FiltersViewModel.prototype.getViewTitle = function ( viewName ) {
1132 viewName = viewName || this.getCurrentView();
1133
1134 return this.views[ viewName ] && this.views[ viewName ].title;
1135 };
1136
1137 /**
1138 * Get the view that fits the given trigger
1139 *
1140 * @param {string} trigger Trigger
1141 * @return {string} Name of view
1142 */
1143 mw.rcfilters.dm.FiltersViewModel.prototype.getViewByTrigger = function ( trigger ) {
1144 var result = 'default';
1145
1146 // eslint-disable-next-line jquery/no-each-util
1147 $.each( this.views, function ( name, data ) {
1148 if ( data.trigger === trigger ) {
1149 result = name;
1150 }
1151 } );
1152
1153 return result;
1154 };
1155
1156 /**
1157 * Return a version of the given string that is without any
1158 * view triggers.
1159 *
1160 * @param {string} str Given string
1161 * @return {string} Result
1162 */
1163 mw.rcfilters.dm.FiltersViewModel.prototype.removeViewTriggers = function ( str ) {
1164 if ( this.getViewFromString( str ) !== 'default' ) {
1165 str = str.substr( 1 );
1166 }
1167
1168 return str;
1169 };
1170
1171 /**
1172 * Get the view from the given string by a trigger, if it exists
1173 *
1174 * @param {string} str Given string
1175 * @return {string} View name
1176 */
1177 mw.rcfilters.dm.FiltersViewModel.prototype.getViewFromString = function ( str ) {
1178 return this.getViewByTrigger( str.substr( 0, 1 ) );
1179 };
1180
1181 /**
1182 * Set the current search for the system.
1183 * This also dictates what items and groups are visible according
1184 * to the search in #findMatches
1185 *
1186 * @param {string} searchQuery Search query, including triggers
1187 * @fires searchChange
1188 */
1189 mw.rcfilters.dm.FiltersViewModel.prototype.setSearch = function ( searchQuery ) {
1190 var visibleGroups, visibleGroupNames;
1191
1192 if ( this.searchQuery !== searchQuery ) {
1193 // Check if the view changed
1194 this.switchView( this.getViewFromString( searchQuery ) );
1195
1196 visibleGroups = this.findMatches( searchQuery );
1197 visibleGroupNames = Object.keys( visibleGroups );
1198
1199 // Update visibility of items and groups
1200 // eslint-disable-next-line jquery/no-each-util
1201 $.each( this.getFilterGroups(), function ( groupName, groupModel ) {
1202 // Check if the group is visible at all
1203 groupModel.toggleVisible( visibleGroupNames.indexOf( groupName ) !== -1 );
1204 groupModel.setVisibleItems( visibleGroups[ groupName ] || [] );
1205 } );
1206
1207 this.searchQuery = searchQuery;
1208 this.emit( 'searchChange', this.searchQuery );
1209 }
1210 };
1211
1212 /**
1213 * Get the current search
1214 *
1215 * @return {string} Current search query
1216 */
1217 mw.rcfilters.dm.FiltersViewModel.prototype.getSearch = function () {
1218 return this.searchQuery;
1219 };
1220
1221 /**
1222 * Switch the current view
1223 *
1224 * @private
1225 * @param {string} view View name
1226 */
1227 mw.rcfilters.dm.FiltersViewModel.prototype.switchView = function ( view ) {
1228 if ( this.views[ view ] && this.currentView !== view ) {
1229 this.currentView = view;
1230 }
1231 };
1232
1233 /**
1234 * Toggle the highlight feature on and off.
1235 * Propagate the change to filter items.
1236 *
1237 * @param {boolean} enable Highlight should be enabled
1238 * @fires highlightChange
1239 */
1240 mw.rcfilters.dm.FiltersViewModel.prototype.toggleHighlight = function ( enable ) {
1241 enable = enable === undefined ? !this.highlightEnabled : enable;
1242
1243 if ( this.highlightEnabled !== enable ) {
1244 this.highlightEnabled = enable;
1245 this.emit( 'highlightChange', this.highlightEnabled );
1246 }
1247 };
1248
1249 /**
1250 * Check if the highlight feature is enabled
1251 * @return {boolean}
1252 */
1253 mw.rcfilters.dm.FiltersViewModel.prototype.isHighlightEnabled = function () {
1254 return !!this.highlightEnabled;
1255 };
1256
1257 /**
1258 * Toggle the inverted namespaces property on and off.
1259 * Propagate the change to namespace filter items.
1260 *
1261 * @param {boolean} enable Inverted property is enabled
1262 */
1263 mw.rcfilters.dm.FiltersViewModel.prototype.toggleInvertedNamespaces = function ( enable ) {
1264 this.toggleFilterSelected( this.getInvertModel().getName(), enable );
1265 };
1266
1267 /**
1268 * Get the model object that represents the 'invert' filter
1269 *
1270 * @return {mw.rcfilters.dm.FilterItem}
1271 */
1272 mw.rcfilters.dm.FiltersViewModel.prototype.getInvertModel = function () {
1273 return this.getGroup( 'invertGroup' ).getItemByParamName( 'invert' );
1274 };
1275
1276 /**
1277 * Set highlight color for a specific filter item
1278 *
1279 * @param {string} filterName Name of the filter item
1280 * @param {string} color Selected color
1281 */
1282 mw.rcfilters.dm.FiltersViewModel.prototype.setHighlightColor = function ( filterName, color ) {
1283 this.getItemByName( filterName ).setHighlightColor( color );
1284 };
1285
1286 /**
1287 * Clear highlight for a specific filter item
1288 *
1289 * @param {string} filterName Name of the filter item
1290 */
1291 mw.rcfilters.dm.FiltersViewModel.prototype.clearHighlightColor = function ( filterName ) {
1292 this.getItemByName( filterName ).clearHighlightColor();
1293 };
1294
1295 }() );