Merge "Chinese Conversion Table Update 2017-6"
[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.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 $.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 groupModel.getType() === 'any_value'
391 ) {
392 // Individual filters
393 groupModel.getItems().forEach( function ( filterItem ) {
394 model.parameterMap[ filterItem.getParamName() ] = filterItem;
395 } );
396 } else if (
397 groupModel.getType() === 'string_options' ||
398 groupModel.getType() === 'single_option'
399 ) {
400 // Group
401 model.parameterMap[ groupModel.getName() ] = groupModel;
402 }
403 } );
404
405 this.setSearch( '' );
406
407 this.updateHighlightedState();
408
409 // Finish initialization
410 this.emit( 'initialize' );
411 };
412
413 /**
414 * Update filter view model state based on a parameter object
415 *
416 * @param {Object} params Parameters object
417 */
418 mw.rcfilters.dm.FiltersViewModel.prototype.updateStateFromParams = function ( params ) {
419 var filtersValue;
420 // For arbitrary numeric single_option values make sure the values
421 // are normalized to fit within the limits
422 $.each( this.getFilterGroups(), function ( groupName, groupModel ) {
423 params[ groupName ] = groupModel.normalizeArbitraryValue( params[ groupName ] );
424 } );
425
426 // Update filter values
427 filtersValue = this.getFiltersFromParameters( params );
428 Object.keys( filtersValue ).forEach( function ( filterName ) {
429 this.getItemByName( filterName ).setValue( filtersValue[ filterName ] );
430 }.bind( this ) );
431
432 // Update highlight state
433 this.getItemsSupportingHighlights().forEach( function ( filterItem ) {
434 var color = params[ filterItem.getName() + '_color' ];
435 if ( color ) {
436 filterItem.setHighlightColor( color );
437 } else {
438 filterItem.clearHighlightColor();
439 }
440 } );
441 this.updateHighlightedState();
442
443 // Check all filter interactions
444 this.reassessFilterInteractions();
445 };
446
447 /**
448 * Get a representation of an empty (falsey) parameter state
449 *
450 * @return {Object} Empty parameter state
451 */
452 mw.rcfilters.dm.FiltersViewModel.prototype.getEmptyParameterState = function () {
453 if ( !this.emptyParameterState ) {
454 this.emptyParameterState = $.extend(
455 true,
456 {},
457 this.getParametersFromFilters( {} ),
458 this.getEmptyHighlightParameters()
459 );
460 }
461 return this.emptyParameterState;
462 };
463
464 /**
465 * Get a representation of only the non-falsey parameters
466 *
467 * @param {Object} [parameters] A given parameter state to minimize. If not given the current
468 * state of the system will be used.
469 * @return {Object} Empty parameter state
470 */
471 mw.rcfilters.dm.FiltersViewModel.prototype.getMinimizedParamRepresentation = function ( parameters ) {
472 var result = {};
473
474 parameters = parameters ? $.extend( true, {}, parameters ) : this.getCurrentParameterState();
475
476 // Params
477 $.each( this.getEmptyParameterState(), function ( param, value ) {
478 if ( parameters[ param ] !== undefined && parameters[ param ] !== value ) {
479 result[ param ] = parameters[ param ];
480 }
481 } );
482
483 // Highlights
484 Object.keys( this.getEmptyHighlightParameters() ).forEach( function ( param ) {
485 if ( parameters[ param ] ) {
486 // If a highlight parameter is not undefined and not null
487 // add it to the result
488 result[ param ] = parameters[ param ];
489 }
490 } );
491
492 return result;
493 };
494
495 /**
496 * Get a representation of the full parameter list, including all base values
497 *
498 * @return {Object} Full parameter representation
499 */
500 mw.rcfilters.dm.FiltersViewModel.prototype.getExpandedParamRepresentation = function () {
501 return $.extend(
502 true,
503 {},
504 this.getEmptyParameterState(),
505 this.getCurrentParameterState()
506 );
507 };
508
509 /**
510 * Get a parameter representation of the current state of the model
511 *
512 * @param {boolean} [removeStickyParams] Remove sticky filters from final result
513 * @return {Object} Parameter representation of the current state of the model
514 */
515 mw.rcfilters.dm.FiltersViewModel.prototype.getCurrentParameterState = function ( removeStickyParams ) {
516 var state = this.getMinimizedParamRepresentation( $.extend(
517 true,
518 {},
519 this.getParametersFromFilters( this.getSelectedState() ),
520 this.getHighlightParameters()
521 ) );
522
523 if ( removeStickyParams ) {
524 state = this.removeStickyParams( state );
525 }
526
527 return state;
528 };
529
530 /**
531 * Delete sticky parameters from given object.
532 *
533 * @param {Object} paramState Parameter state
534 * @return {Object} Parameter state without sticky parameters
535 */
536 mw.rcfilters.dm.FiltersViewModel.prototype.removeStickyParams = function ( paramState ) {
537 this.getStickyParams().forEach( function ( paramName ) {
538 delete paramState[ paramName ];
539 } );
540
541 return paramState;
542 };
543
544 /**
545 * Turn the highlight feature on or off
546 */
547 mw.rcfilters.dm.FiltersViewModel.prototype.updateHighlightedState = function () {
548 this.toggleHighlight( this.getHighlightedItems().length > 0 );
549 };
550
551 /**
552 * Get the object that defines groups by their name.
553 *
554 * @return {Object} Filter groups
555 */
556 mw.rcfilters.dm.FiltersViewModel.prototype.getFilterGroups = function () {
557 return this.groups;
558 };
559
560 /**
561 * Get the object that defines groups that match a certain view by their name.
562 *
563 * @param {string} [view] Requested view. If not given, uses current view
564 * @return {Object} Filter groups matching a display group
565 */
566 mw.rcfilters.dm.FiltersViewModel.prototype.getFilterGroupsByView = function ( view ) {
567 var result = {};
568
569 view = view || this.getCurrentView();
570
571 $.each( this.groups, function ( groupName, groupModel ) {
572 if ( groupModel.getView() === view ) {
573 result[ groupName ] = groupModel;
574 }
575 } );
576
577 return result;
578 };
579
580 /**
581 * Get an array of filters matching the given display group.
582 *
583 * @param {string} [view] Requested view. If not given, uses current view
584 * @return {mw.rcfilters.dm.FilterItem} Filter items matching the group
585 */
586 mw.rcfilters.dm.FiltersViewModel.prototype.getFiltersByView = function ( view ) {
587 var groups,
588 result = [];
589
590 view = view || this.getCurrentView();
591
592 groups = this.getFilterGroupsByView( view );
593
594 $.each( groups, function ( groupName, groupModel ) {
595 result = result.concat( groupModel.getItems() );
596 } );
597
598 return result;
599 };
600
601 /**
602 * Get the trigger for the requested view.
603 *
604 * @param {string} view View name
605 * @return {string} View trigger, if exists
606 */
607 mw.rcfilters.dm.FiltersViewModel.prototype.getViewTrigger = function ( view ) {
608 return ( this.views[ view ] && this.views[ view ].trigger ) || '';
609 };
610
611 /**
612 * Get the value of a specific parameter
613 *
614 * @param {string} name Parameter name
615 * @return {number|string} Parameter value
616 */
617 mw.rcfilters.dm.FiltersViewModel.prototype.getParamValue = function ( name ) {
618 return this.parameters[ name ];
619 };
620
621 /**
622 * Get the current selected state of the filters
623 *
624 * @param {boolean} [onlySelected] return an object containing only the filters with a value
625 * @return {Object} Filters selected state
626 */
627 mw.rcfilters.dm.FiltersViewModel.prototype.getSelectedState = function ( onlySelected ) {
628 var i,
629 items = this.getItems(),
630 result = {};
631
632 for ( i = 0; i < items.length; i++ ) {
633 if ( !onlySelected || items[ i ].getValue() ) {
634 result[ items[ i ].getName() ] = items[ i ].getValue();
635 }
636 }
637
638 return result;
639 };
640
641 /**
642 * Get the current full state of the filters
643 *
644 * @return {Object} Filters full state
645 */
646 mw.rcfilters.dm.FiltersViewModel.prototype.getFullState = function () {
647 var i,
648 items = this.getItems(),
649 result = {};
650
651 for ( i = 0; i < items.length; i++ ) {
652 result[ items[ i ].getName() ] = {
653 selected: items[ i ].isSelected(),
654 conflicted: items[ i ].isConflicted(),
655 included: items[ i ].isIncluded()
656 };
657 }
658
659 return result;
660 };
661
662 /**
663 * Get an object representing default parameters state
664 *
665 * @return {Object} Default parameter values
666 */
667 mw.rcfilters.dm.FiltersViewModel.prototype.getDefaultParams = function () {
668 var result = {};
669
670 // Get default filter state
671 $.each( this.groups, function ( name, model ) {
672 if ( !model.isSticky() ) {
673 $.extend( true, result, model.getDefaultParams() );
674 }
675 } );
676
677 return result;
678 };
679
680 /**
681 * Get a parameter representation of all sticky parameters
682 *
683 * @return {Object} Sticky parameter values
684 */
685 mw.rcfilters.dm.FiltersViewModel.prototype.getStickyParams = function () {
686 var result = [];
687
688 $.each( this.groups, function ( name, model ) {
689 if ( model.isSticky() ) {
690 if ( model.isPerGroupRequestParameter() ) {
691 result.push( name );
692 } else {
693 // Each filter is its own param
694 result = result.concat( model.getItems().map( function ( filterItem ) {
695 return filterItem.getParamName();
696 } ) );
697 }
698 }
699 } );
700
701 return result;
702 };
703
704 /**
705 * Get a parameter representation of all sticky parameters
706 *
707 * @return {Object} Sticky parameter values
708 */
709 mw.rcfilters.dm.FiltersViewModel.prototype.getStickyParamsValues = function () {
710 var result = {};
711
712 $.each( this.groups, function ( name, model ) {
713 if ( model.isSticky() ) {
714 $.extend( true, result, model.getParamRepresentation() );
715 }
716 } );
717
718 return result;
719 };
720
721 /**
722 * Analyze the groups and their filters and output an object representing
723 * the state of the parameters they represent.
724 *
725 * @param {Object} [filterDefinition] An object defining the filter values,
726 * keyed by filter names.
727 * @return {Object} Parameter state object
728 */
729 mw.rcfilters.dm.FiltersViewModel.prototype.getParametersFromFilters = function ( filterDefinition ) {
730 var groupItemDefinition,
731 result = {},
732 groupItems = this.getFilterGroups();
733
734 if ( filterDefinition ) {
735 groupItemDefinition = {};
736 // Filter definition is "flat", but in effect
737 // each group needs to tell us its result based
738 // on the values in it. We need to split this list
739 // back into groupings so we can "feed" it to the
740 // loop below, and we need to expand it so it includes
741 // all filters (set to false)
742 this.getItems().forEach( function ( filterItem ) {
743 groupItemDefinition[ filterItem.getGroupName() ] = groupItemDefinition[ filterItem.getGroupName() ] || {};
744 groupItemDefinition[ filterItem.getGroupName() ][ filterItem.getName() ] = filterItem.coerceValue( filterDefinition[ filterItem.getName() ] );
745 } );
746 }
747
748 $.each( groupItems, function ( group, model ) {
749 $.extend(
750 result,
751 model.getParamRepresentation(
752 groupItemDefinition ?
753 groupItemDefinition[ group ] : null
754 )
755 );
756 } );
757
758 return result;
759 };
760
761 /**
762 * This is the opposite of the #getParametersFromFilters method; this goes over
763 * the given parameters and translates into a selected/unselected value in the filters.
764 *
765 * @param {Object} params Parameters query object
766 * @return {Object} Filter state object
767 */
768 mw.rcfilters.dm.FiltersViewModel.prototype.getFiltersFromParameters = function ( params ) {
769 var groupMap = {},
770 model = this,
771 result = {};
772
773 // Go over the given parameters, break apart to groupings
774 // The resulting object represents the group with its parameter
775 // values. For example:
776 // {
777 // group1: {
778 // param1: "1",
779 // param2: "0",
780 // param3: "1"
781 // },
782 // group2: "param4|param5"
783 // }
784 $.each( params, function ( paramName, paramValue ) {
785 var groupName,
786 itemOrGroup = model.parameterMap[ paramName ];
787
788 if ( itemOrGroup ) {
789 groupName = itemOrGroup instanceof mw.rcfilters.dm.FilterItem ?
790 itemOrGroup.getGroupName() : itemOrGroup.getName();
791
792 groupMap[ groupName ] = groupMap[ groupName ] || {};
793 groupMap[ groupName ][ paramName ] = paramValue;
794 }
795 } );
796
797 // Go over all groups, so we make sure we get the complete output
798 // even if the parameters don't include a certain group
799 $.each( this.groups, function ( groupName, groupModel ) {
800 result = $.extend( true, {}, result, groupModel.getFilterRepresentation( groupMap[ groupName ] ) );
801 } );
802
803 return result;
804 };
805
806 /**
807 * Get the highlight parameters based on current filter configuration
808 *
809 * @return {Object} Object where keys are `<filter name>_color` and values
810 * are the selected highlight colors.
811 */
812 mw.rcfilters.dm.FiltersViewModel.prototype.getHighlightParameters = function () {
813 var highlightEnabled = this.isHighlightEnabled(),
814 result = {};
815
816 this.getItems().forEach( function ( filterItem ) {
817 if ( filterItem.isHighlightSupported() ) {
818 result[ filterItem.getName() + '_color' ] = highlightEnabled && filterItem.isHighlighted() ?
819 filterItem.getHighlightColor() :
820 null;
821 }
822 } );
823
824 return result;
825 };
826
827 /**
828 * Get an object representing the complete empty state of highlights
829 *
830 * @return {Object} Object containing all the highlight parameters set to their negative value
831 */
832 mw.rcfilters.dm.FiltersViewModel.prototype.getEmptyHighlightParameters = function () {
833 var result = {};
834
835 this.getItems().forEach( function ( filterItem ) {
836 if ( filterItem.isHighlightSupported() ) {
837 result[ filterItem.getName() + '_color' ] = null;
838 }
839 } );
840
841 return result;
842 };
843
844 /**
845 * Get an array of currently applied highlight colors
846 *
847 * @return {string[]} Currently applied highlight colors
848 */
849 mw.rcfilters.dm.FiltersViewModel.prototype.getCurrentlyUsedHighlightColors = function () {
850 var result = [];
851
852 if ( this.isHighlightEnabled() ) {
853 this.getHighlightedItems().forEach( function ( filterItem ) {
854 var color = filterItem.getHighlightColor();
855
856 if ( result.indexOf( color ) === -1 ) {
857 result.push( color );
858 }
859 } );
860 }
861
862 return result;
863 };
864
865 /**
866 * Sanitize value group of a string_option groups type
867 * Remove duplicates and make sure to only use valid
868 * values.
869 *
870 * @private
871 * @param {string} groupName Group name
872 * @param {string[]} valueArray Array of values
873 * @return {string[]} Array of valid values
874 */
875 mw.rcfilters.dm.FiltersViewModel.prototype.sanitizeStringOptionGroup = function ( groupName, valueArray ) {
876 var validNames = this.getGroupFilters( groupName ).map( function ( filterItem ) {
877 return filterItem.getParamName();
878 } );
879
880 return mw.rcfilters.utils.normalizeParamOptions( valueArray, validNames );
881 };
882
883 /**
884 * Check whether no visible filter is selected.
885 *
886 * Filter groups that are hidden or sticky are not shown in the
887 * active filters area and therefore not included in this check.
888 *
889 * @return {boolean} No visible filter is selected
890 */
891 mw.rcfilters.dm.FiltersViewModel.prototype.areVisibleFiltersEmpty = function () {
892 // Check if there are either any selected items or any items
893 // that have highlight enabled
894 return !this.getItems().some( function ( filterItem ) {
895 var visible = !filterItem.getGroupModel().isSticky() && !filterItem.getGroupModel().isHidden(),
896 active = ( filterItem.isSelected() || filterItem.isHighlighted() );
897 return visible && active;
898 } );
899 };
900
901 /**
902 * Check whether the invert state is a valid one. A valid invert state is one where
903 * there are actual namespaces selected.
904 *
905 * This is done to compare states to previous ones that may have had the invert model
906 * selected but effectively had no namespaces, so are not effectively different than
907 * ones where invert is not selected.
908 *
909 * @return {boolean} Invert is effectively selected
910 */
911 mw.rcfilters.dm.FiltersViewModel.prototype.areNamespacesEffectivelyInverted = function () {
912 return this.getInvertModel().isSelected() &&
913 this.getSelectedItems().some( function ( itemModel ) {
914 return itemModel.getGroupModel().getView() === 'namespace';
915 } );
916 };
917
918 /**
919 * Get the item that matches the given name
920 *
921 * @param {string} name Filter name
922 * @return {mw.rcfilters.dm.FilterItem} Filter item
923 */
924 mw.rcfilters.dm.FiltersViewModel.prototype.getItemByName = function ( name ) {
925 return this.getItems().filter( function ( item ) {
926 return name === item.getName();
927 } )[ 0 ];
928 };
929
930 /**
931 * Set all filters to false or empty/all
932 * This is equivalent to display all.
933 */
934 mw.rcfilters.dm.FiltersViewModel.prototype.emptyAllFilters = function () {
935 this.getItems().forEach( function ( filterItem ) {
936 if ( !filterItem.getGroupModel().isSticky() ) {
937 this.toggleFilterSelected( filterItem.getName(), false );
938 }
939 }.bind( this ) );
940 };
941
942 /**
943 * Toggle selected state of one item
944 *
945 * @param {string} name Name of the filter item
946 * @param {boolean} [isSelected] Filter selected state
947 */
948 mw.rcfilters.dm.FiltersViewModel.prototype.toggleFilterSelected = function ( name, isSelected ) {
949 var item = this.getItemByName( name );
950
951 if ( item ) {
952 item.toggleSelected( isSelected );
953 }
954 };
955
956 /**
957 * Toggle selected state of items by their names
958 *
959 * @param {Object} filterDef Filter definitions
960 */
961 mw.rcfilters.dm.FiltersViewModel.prototype.toggleFiltersSelected = function ( filterDef ) {
962 Object.keys( filterDef ).forEach( function ( name ) {
963 this.toggleFilterSelected( name, filterDef[ name ] );
964 }.bind( this ) );
965 };
966
967 /**
968 * Get a group model from its name
969 *
970 * @param {string} groupName Group name
971 * @return {mw.rcfilters.dm.FilterGroup} Group model
972 */
973 mw.rcfilters.dm.FiltersViewModel.prototype.getGroup = function ( groupName ) {
974 return this.groups[ groupName ];
975 };
976
977 /**
978 * Get all filters within a specified group by its name
979 *
980 * @param {string} groupName Group name
981 * @return {mw.rcfilters.dm.FilterItem[]} Filters belonging to this group
982 */
983 mw.rcfilters.dm.FiltersViewModel.prototype.getGroupFilters = function ( groupName ) {
984 return ( this.getGroup( groupName ) && this.getGroup( groupName ).getItems() ) || [];
985 };
986
987 /**
988 * Find items whose labels match the given string
989 *
990 * @param {string} query Search string
991 * @param {boolean} [returnFlat] Return a flat array. If false, the result
992 * is an object whose keys are the group names and values are an array of
993 * filters per group. If set to true, returns an array of filters regardless
994 * of their groups.
995 * @return {Object} An object of items to show
996 * arranged by their group names
997 */
998 mw.rcfilters.dm.FiltersViewModel.prototype.findMatches = function ( query, returnFlat ) {
999 var i, searchIsEmpty,
1000 groupTitle,
1001 result = {},
1002 flatResult = [],
1003 view = this.getViewByTrigger( query.substr( 0, 1 ) ),
1004 items = this.getFiltersByView( view );
1005
1006 // Normalize so we can search strings regardless of case and view
1007 query = query.trim().toLowerCase();
1008 if ( view !== 'default' ) {
1009 query = query.substr( 1 );
1010 }
1011 // Trim again to also intercept cases where the spaces were after the trigger
1012 // eg: '# str'
1013 query = query.trim();
1014
1015 // Check if the search if actually empty; this can be a problem when
1016 // we use prefixes to denote different views
1017 searchIsEmpty = query.length === 0;
1018
1019 // item label starting with the query string
1020 for ( i = 0; i < items.length; i++ ) {
1021 if (
1022 searchIsEmpty ||
1023 items[ i ].getLabel().toLowerCase().indexOf( query ) === 0 ||
1024 (
1025 // For tags, we want the parameter name to be included in the search
1026 view === 'tags' &&
1027 items[ i ].getParamName().toLowerCase().indexOf( query ) > -1
1028 )
1029 ) {
1030 result[ items[ i ].getGroupName() ] = result[ items[ i ].getGroupName() ] || [];
1031 result[ items[ i ].getGroupName() ].push( items[ i ] );
1032 flatResult.push( items[ i ] );
1033 }
1034 }
1035
1036 if ( $.isEmptyObject( result ) ) {
1037 // item containing the query string in their label, description, or group title
1038 for ( i = 0; i < items.length; i++ ) {
1039 groupTitle = items[ i ].getGroupModel().getTitle();
1040 if (
1041 searchIsEmpty ||
1042 items[ i ].getLabel().toLowerCase().indexOf( query ) > -1 ||
1043 items[ i ].getDescription().toLowerCase().indexOf( query ) > -1 ||
1044 groupTitle.toLowerCase().indexOf( query ) > -1 ||
1045 (
1046 // For tags, we want the parameter name to be included in the search
1047 view === 'tags' &&
1048 items[ i ].getParamName().toLowerCase().indexOf( query ) > -1
1049 )
1050 ) {
1051 result[ items[ i ].getGroupName() ] = result[ items[ i ].getGroupName() ] || [];
1052 result[ items[ i ].getGroupName() ].push( items[ i ] );
1053 flatResult.push( items[ i ] );
1054 }
1055 }
1056 }
1057
1058 return returnFlat ? flatResult : result;
1059 };
1060
1061 /**
1062 * Get items that are highlighted
1063 *
1064 * @return {mw.rcfilters.dm.FilterItem[]} Highlighted items
1065 */
1066 mw.rcfilters.dm.FiltersViewModel.prototype.getHighlightedItems = function () {
1067 return this.getItems().filter( function ( filterItem ) {
1068 return filterItem.isHighlightSupported() &&
1069 filterItem.getHighlightColor();
1070 } );
1071 };
1072
1073 /**
1074 * Get items that allow highlights even if they're not currently highlighted
1075 *
1076 * @return {mw.rcfilters.dm.FilterItem[]} Items supporting highlights
1077 */
1078 mw.rcfilters.dm.FiltersViewModel.prototype.getItemsSupportingHighlights = function () {
1079 return this.getItems().filter( function ( filterItem ) {
1080 return filterItem.isHighlightSupported();
1081 } );
1082 };
1083
1084 /**
1085 * Get all selected items
1086 *
1087 * @return {mw.rcfilters.dm.FilterItem[]} Selected items
1088 */
1089 mw.rcfilters.dm.FiltersViewModel.prototype.getSelectedItems = function () {
1090 var allSelected = [];
1091
1092 $.each( this.getFilterGroups(), function ( groupName, groupModel ) {
1093 allSelected = allSelected.concat( groupModel.getSelectedItems() );
1094 } );
1095
1096 return allSelected;
1097 };
1098
1099 /**
1100 * Get the current view
1101 *
1102 * @return {string} Current view
1103 */
1104 mw.rcfilters.dm.FiltersViewModel.prototype.getCurrentView = function () {
1105 return this.currentView;
1106 };
1107
1108 /**
1109 * Get the label for the current view
1110 *
1111 * @param {string} viewName View name
1112 * @return {string} Label for the current view
1113 */
1114 mw.rcfilters.dm.FiltersViewModel.prototype.getViewTitle = function ( viewName ) {
1115 viewName = viewName || this.getCurrentView();
1116
1117 return this.views[ viewName ] && this.views[ viewName ].title;
1118 };
1119
1120 /**
1121 * Get the view that fits the given trigger
1122 *
1123 * @param {string} trigger Trigger
1124 * @return {string} Name of view
1125 */
1126 mw.rcfilters.dm.FiltersViewModel.prototype.getViewByTrigger = function ( trigger ) {
1127 var result = 'default';
1128
1129 $.each( this.views, function ( name, data ) {
1130 if ( data.trigger === trigger ) {
1131 result = name;
1132 }
1133 } );
1134
1135 return result;
1136 };
1137
1138 /**
1139 * Return a version of the given string that is without any
1140 * view triggers.
1141 *
1142 * @param {string} str Given string
1143 * @return {string} Result
1144 */
1145 mw.rcfilters.dm.FiltersViewModel.prototype.removeViewTriggers = function ( str ) {
1146 if ( this.getViewFromString( str ) !== 'default' ) {
1147 str = str.substr( 1 );
1148 }
1149
1150 return str;
1151 };
1152
1153 /**
1154 * Get the view from the given string by a trigger, if it exists
1155 *
1156 * @param {string} str Given string
1157 * @return {string} View name
1158 */
1159 mw.rcfilters.dm.FiltersViewModel.prototype.getViewFromString = function ( str ) {
1160 return this.getViewByTrigger( str.substr( 0, 1 ) );
1161 };
1162
1163 /**
1164 * Set the current search for the system.
1165 * This also dictates what items and groups are visible according
1166 * to the search in #findMatches
1167 *
1168 * @param {string} searchQuery Search query, including triggers
1169 * @fires searchChange
1170 */
1171 mw.rcfilters.dm.FiltersViewModel.prototype.setSearch = function ( searchQuery ) {
1172 var visibleGroups, visibleGroupNames;
1173
1174 if ( this.searchQuery !== searchQuery ) {
1175 // Check if the view changed
1176 this.switchView( this.getViewFromString( searchQuery ) );
1177
1178 visibleGroups = this.findMatches( searchQuery );
1179 visibleGroupNames = Object.keys( visibleGroups );
1180
1181 // Update visibility of items and groups
1182 $.each( this.getFilterGroups(), function ( groupName, groupModel ) {
1183 // Check if the group is visible at all
1184 groupModel.toggleVisible( visibleGroupNames.indexOf( groupName ) !== -1 );
1185 groupModel.setVisibleItems( visibleGroups[ groupName ] || [] );
1186 } );
1187
1188 this.searchQuery = searchQuery;
1189 this.emit( 'searchChange', this.searchQuery );
1190 }
1191 };
1192
1193 /**
1194 * Get the current search
1195 *
1196 * @return {string} Current search query
1197 */
1198 mw.rcfilters.dm.FiltersViewModel.prototype.getSearch = function () {
1199 return this.searchQuery;
1200 };
1201
1202 /**
1203 * Switch the current view
1204 *
1205 * @private
1206 * @param {string} view View name
1207 */
1208 mw.rcfilters.dm.FiltersViewModel.prototype.switchView = function ( view ) {
1209 if ( this.views[ view ] && this.currentView !== view ) {
1210 this.currentView = view;
1211 }
1212 };
1213
1214 /**
1215 * Toggle the highlight feature on and off.
1216 * Propagate the change to filter items.
1217 *
1218 * @param {boolean} enable Highlight should be enabled
1219 * @fires highlightChange
1220 */
1221 mw.rcfilters.dm.FiltersViewModel.prototype.toggleHighlight = function ( enable ) {
1222 enable = enable === undefined ? !this.highlightEnabled : enable;
1223
1224 if ( this.highlightEnabled !== enable ) {
1225 this.highlightEnabled = enable;
1226 this.emit( 'highlightChange', this.highlightEnabled );
1227 }
1228 };
1229
1230 /**
1231 * Check if the highlight feature is enabled
1232 * @return {boolean}
1233 */
1234 mw.rcfilters.dm.FiltersViewModel.prototype.isHighlightEnabled = function () {
1235 return !!this.highlightEnabled;
1236 };
1237
1238 /**
1239 * Toggle the inverted namespaces property on and off.
1240 * Propagate the change to namespace filter items.
1241 *
1242 * @param {boolean} enable Inverted property is enabled
1243 */
1244 mw.rcfilters.dm.FiltersViewModel.prototype.toggleInvertedNamespaces = function ( enable ) {
1245 this.toggleFilterSelected( this.getInvertModel().getName(), enable );
1246 };
1247
1248 /**
1249 * Get the model object that represents the 'invert' filter
1250 *
1251 * @return {mw.rcfilters.dm.FilterItem}
1252 */
1253 mw.rcfilters.dm.FiltersViewModel.prototype.getInvertModel = function () {
1254 return this.getGroup( 'invertGroup' ).getItemByParamName( 'invert' );
1255 };
1256
1257 /**
1258 * Set highlight color for a specific filter item
1259 *
1260 * @param {string} filterName Name of the filter item
1261 * @param {string} color Selected color
1262 */
1263 mw.rcfilters.dm.FiltersViewModel.prototype.setHighlightColor = function ( filterName, color ) {
1264 this.getItemByName( filterName ).setHighlightColor( color );
1265 };
1266
1267 /**
1268 * Clear highlight for a specific filter item
1269 *
1270 * @param {string} filterName Name of the filter item
1271 */
1272 mw.rcfilters.dm.FiltersViewModel.prototype.clearHighlightColor = function ( filterName ) {
1273 this.getItemByName( filterName ).clearHighlightColor();
1274 };
1275
1276 }( mediaWiki, jQuery ) );