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