Merge "parserTests: Use "fallback" skin unless otherwise specified"
[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.invertedNamespaces = false;
20 this.parameterMap = {};
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 /**
64 * @event invertChange
65 * @param {boolean} isInverted Namespace selected is inverted
66 *
67 * Namespace selection is inverted or straight forward
68 */
69
70 /* Methods */
71
72 /**
73 * Re-assess the states of filter items based on the interactions between them
74 *
75 * @param {mw.rcfilters.dm.FilterItem} [item] Changed item. If not given, the
76 * method will go over the state of all items
77 */
78 mw.rcfilters.dm.FiltersViewModel.prototype.reassessFilterInteractions = function ( item ) {
79 var allSelected,
80 model = this,
81 iterationItems = item !== undefined ? [ item ] : this.getItems();
82
83 iterationItems.forEach( function ( checkedItem ) {
84 var allCheckedItems = checkedItem.getSubset().concat( [ checkedItem.getName() ] ),
85 groupModel = checkedItem.getGroupModel();
86
87 // Check for subsets (included filters) plus the item itself:
88 allCheckedItems.forEach( function ( filterItemName ) {
89 var itemInSubset = model.getItemByName( filterItemName );
90
91 itemInSubset.toggleIncluded(
92 // If any of itemInSubset's supersets are selected, this item
93 // is included
94 itemInSubset.getSuperset().some( function ( supersetName ) {
95 return ( model.getItemByName( supersetName ).isSelected() );
96 } )
97 );
98 } );
99
100 // Update coverage for the changed group
101 if ( groupModel.isFullCoverage() ) {
102 allSelected = groupModel.areAllSelected();
103 groupModel.getItems().forEach( function ( filterItem ) {
104 filterItem.toggleFullyCovered( allSelected );
105 } );
106 }
107 } );
108
109 // Check for conflicts
110 // In this case, we must go over all items, since
111 // conflicts are bidirectional and depend not only on
112 // individual items, but also on the selected states of
113 // the groups they're in.
114 this.getItems().forEach( function ( filterItem ) {
115 var inConflict = false,
116 filterItemGroup = filterItem.getGroupModel();
117
118 // For each item, see if that item is still conflicting
119 $.each( model.groups, function ( groupName, groupModel ) {
120 if ( filterItem.getGroupName() === groupName ) {
121 // Check inside the group
122 inConflict = groupModel.areAnySelectedInConflictWith( filterItem );
123 } else {
124 // According to the spec, if two items conflict from two different
125 // groups, the conflict only lasts if the groups **only have selected
126 // items that are conflicting**. If a group has selected items that
127 // are conflicting and non-conflicting, the scope of the result has
128 // expanded enough to completely remove the conflict.
129
130 // For example, see two groups with conflicts:
131 // userExpLevel: [
132 // {
133 // name: 'experienced',
134 // conflicts: [ 'unregistered' ]
135 // }
136 // ],
137 // registration: [
138 // {
139 // name: 'registered',
140 // },
141 // {
142 // name: 'unregistered',
143 // }
144 // ]
145 // If we select 'experienced', then 'unregistered' is in conflict (and vice versa),
146 // because, inherently, 'experienced' filter only includes registered users, and so
147 // both filters are in conflict with one another.
148 // However, the minute we select 'registered', the scope of our results
149 // has expanded to no longer have a conflict with 'experienced' filter, and
150 // so the conflict is removed.
151
152 // In our case, we need to check if the entire group conflicts with
153 // the entire item's group, so we follow the above spec
154 inConflict = (
155 // The foreign group is in conflict with this item
156 groupModel.areAllSelectedInConflictWith( filterItem ) &&
157 // Every selected member of the item's own group is also
158 // in conflict with the other group
159 filterItemGroup.getSelectedItems().every( function ( otherGroupItem ) {
160 return groupModel.areAllSelectedInConflictWith( otherGroupItem );
161 } )
162 );
163 }
164
165 // If we're in conflict, this will return 'false' which
166 // will break the loop. Otherwise, we're not in conflict
167 // and the loop continues
168 return !inConflict;
169 } );
170
171 // Toggle the item state
172 filterItem.toggleConflicted( inConflict );
173 } );
174 };
175
176 /**
177 * Get whether the model has any conflict in its items
178 *
179 * @return {boolean} There is a conflict
180 */
181 mw.rcfilters.dm.FiltersViewModel.prototype.hasConflict = function () {
182 return this.getItems().some( function ( filterItem ) {
183 return filterItem.isSelected() && filterItem.isConflicted();
184 } );
185 };
186
187 /**
188 * Get the first item with a current conflict
189 *
190 * @return {mw.rcfilters.dm.FilterItem} Conflicted item
191 */
192 mw.rcfilters.dm.FiltersViewModel.prototype.getFirstConflictedItem = function () {
193 var conflictedItem;
194
195 $.each( this.getItems(), function ( index, filterItem ) {
196 if ( filterItem.isSelected() && filterItem.isConflicted() ) {
197 conflictedItem = filterItem;
198 return false;
199 }
200 } );
201
202 return conflictedItem;
203 };
204
205 /**
206 * Set filters and preserve a group relationship based on
207 * the definition given by an object
208 *
209 * @param {Array} filterGroups Filters definition
210 * @param {Object} [views] Extra views definition
211 * Expected in the following format:
212 * {
213 * namespaces: {
214 * label: 'namespaces', // Message key
215 * trigger: ':',
216 * groups: [
217 * {
218 * // Group info
219 * name: 'namespaces' // Parameter name
220 * title: 'namespaces' // Message key
221 * type: 'string_options',
222 * separator: ';',
223 * labelPrefixKey: { 'default': 'rcfilters-tag-prefix-namespace', inverted: 'rcfilters-tag-prefix-namespace-inverted' },
224 * fullCoverage: true
225 * items: []
226 * }
227 * ]
228 * }
229 * }
230 */
231 mw.rcfilters.dm.FiltersViewModel.prototype.initializeFilters = function ( filterGroups, views ) {
232 var filterConflictResult, groupConflictResult,
233 allViews = {},
234 model = this,
235 items = [],
236 groupConflictMap = {},
237 filterConflictMap = {},
238 /*!
239 * Expand a conflict definition from group name to
240 * the list of all included filters in that group.
241 * We do this so that the direct relationship in the
242 * models are consistently item->items rather than
243 * mixing item->group with item->item.
244 *
245 * @param {Object} obj Conflict definition
246 * @return {Object} Expanded conflict definition
247 */
248 expandConflictDefinitions = function ( obj ) {
249 var result = {};
250
251 $.each( obj, function ( key, conflicts ) {
252 var filterName,
253 adjustedConflicts = {};
254
255 conflicts.forEach( function ( conflict ) {
256 var filter;
257
258 if ( conflict.filter ) {
259 filterName = model.groups[ conflict.group ].getPrefixedName( conflict.filter );
260 filter = model.getItemByName( filterName );
261
262 // Rename
263 adjustedConflicts[ filterName ] = $.extend(
264 {},
265 conflict,
266 {
267 filter: filterName,
268 item: filter
269 }
270 );
271 } else {
272 // This conflict is for an entire group. Split it up to
273 // represent each filter
274
275 // Get the relevant group items
276 model.groups[ conflict.group ].getItems().forEach( function ( groupItem ) {
277 // Rebuild the conflict
278 adjustedConflicts[ groupItem.getName() ] = $.extend(
279 {},
280 conflict,
281 {
282 filter: groupItem.getName(),
283 item: groupItem
284 }
285 );
286 } );
287 }
288 } );
289
290 result[ key ] = adjustedConflicts;
291 } );
292
293 return result;
294 };
295
296 // Reset
297 this.clearItems();
298 this.groups = {};
299 this.views = {};
300
301 // Clone
302 filterGroups = OO.copy( filterGroups );
303
304 // Normalize definition from the server
305 filterGroups.forEach( function ( data ) {
306 var i;
307 // What's this information needs to be normalized
308 data.whatsThis = {
309 body: data.whatsThisBody,
310 header: data.whatsThisHeader,
311 linkText: data.whatsThisLinkText,
312 url: data.whatsThisUrl
313 };
314
315 // Title is a msg-key
316 data.title = data.title ? mw.msg( data.title ) : data.name;
317
318 // Filters are given to us with msg-keys, we need
319 // to translate those before we hand them off
320 for ( i = 0; i < data.filters.length; i++ ) {
321 data.filters[ i ].label = data.filters[ i ].label ? mw.msg( data.filters[ i ].label ) : data.filters[ i ].name;
322 data.filters[ i ].description = data.filters[ i ].description ? mw.msg( data.filters[ i ].description ) : '';
323 }
324 } );
325
326 // Collect views
327 allViews = {
328 'default': {
329 title: mw.msg( 'rcfilters-filterlist-title' ),
330 groups: filterGroups
331 }
332 };
333
334 if ( views && mw.config.get( 'wgStructuredChangeFiltersEnableExperimentalViews' ) ) {
335 // If we have extended views, add them in
336 $.extend( true, allViews, views );
337 }
338
339 // Go over all views
340 $.each( allViews, function ( viewName, viewData ) {
341 // Define the view
342 model.views[ viewName ] = {
343 name: viewData.name,
344 title: viewData.title,
345 trigger: viewData.trigger
346 };
347
348 // Go over groups
349 viewData.groups.forEach( function ( groupData ) {
350 var group = groupData.name;
351
352 if ( !model.groups[ group ] ) {
353 model.groups[ group ] = new mw.rcfilters.dm.FilterGroup(
354 group,
355 $.extend( true, {}, groupData, { view: viewName } )
356 );
357 }
358
359 model.groups[ group ].initializeFilters( groupData.filters, groupData.default );
360 items = items.concat( model.groups[ group ].getItems() );
361
362 // Prepare conflicts
363 if ( groupData.conflicts ) {
364 // Group conflicts
365 groupConflictMap[ group ] = groupData.conflicts;
366 }
367
368 groupData.filters.forEach( function ( itemData ) {
369 var filterItem = model.groups[ group ].getItemByParamName( itemData.name );
370 // Filter conflicts
371 if ( itemData.conflicts ) {
372 filterConflictMap[ filterItem.getName() ] = itemData.conflicts;
373 }
374 } );
375 } );
376 } );
377
378 // Add item references to the model, for lookup
379 this.addItems( items );
380
381 // Expand conflicts
382 groupConflictResult = expandConflictDefinitions( groupConflictMap );
383 filterConflictResult = expandConflictDefinitions( filterConflictMap );
384
385 // Set conflicts for groups
386 $.each( groupConflictResult, function ( group, conflicts ) {
387 model.groups[ group ].setConflicts( conflicts );
388 } );
389
390 // Set conflicts for items
391 $.each( filterConflictResult, function ( filterName, conflicts ) {
392 var filterItem = model.getItemByName( filterName );
393 // set conflicts for items in the group
394 filterItem.setConflicts( conflicts );
395 } );
396
397 // Create a map between known parameters and their models
398 $.each( this.groups, function ( group, groupModel ) {
399 if (
400 groupModel.getType() === 'send_unselected_if_any' ||
401 groupModel.getType() === 'boolean'
402 ) {
403 // Individual filters
404 groupModel.getItems().forEach( function ( filterItem ) {
405 model.parameterMap[ filterItem.getParamName() ] = filterItem;
406 } );
407 } else if (
408 groupModel.getType() === 'string_options' ||
409 groupModel.getType() === 'single_option'
410 ) {
411 // Group
412 model.parameterMap[ groupModel.getName() ] = groupModel;
413 }
414 } );
415
416 this.currentView = 'default';
417
418 // Finish initialization
419 this.emit( 'initialize' );
420 };
421
422 /**
423 * Get the names of all available filters
424 *
425 * @return {string[]} An array of filter names
426 */
427 mw.rcfilters.dm.FiltersViewModel.prototype.getFilterNames = function () {
428 return this.getItems().map( function ( item ) { return item.getName(); } );
429 };
430
431 /**
432 * Get the object that defines groups by their name.
433 *
434 * @return {Object} Filter groups
435 */
436 mw.rcfilters.dm.FiltersViewModel.prototype.getFilterGroups = function () {
437 return this.groups;
438 };
439
440 /**
441 * Get the object that defines groups that match a certain view by their name.
442 *
443 * @param {string} [view] Requested view. If not given, uses current view
444 * @return {Object} Filter groups matching a display group
445 */
446 mw.rcfilters.dm.FiltersViewModel.prototype.getFilterGroupsByView = function ( view ) {
447 var result = {};
448
449 view = view || this.getCurrentView();
450
451 $.each( this.groups, function ( groupName, groupModel ) {
452 if ( groupModel.getView() === view ) {
453 result[ groupName ] = groupModel;
454 }
455 } );
456
457 return result;
458 };
459
460 /**
461 * Get an array of filters matching the given display group.
462 *
463 * @param {string} [view] Requested view. If not given, uses current view
464 * @return {mw.rcfilters.dm.FilterItem} Filter items matching the group
465 */
466 mw.rcfilters.dm.FiltersViewModel.prototype.getFiltersByView = function ( view ) {
467 var groups,
468 result = [];
469
470 view = view || this.getCurrentView();
471
472 groups = this.getFilterGroupsByView( view );
473
474 $.each( groups, function ( groupName, groupModel ) {
475 result = result.concat( groupModel.getItems() );
476 } );
477
478 return result;
479 };
480
481 /**
482 * Get the trigger for the requested view.
483 *
484 * @param {string} view View name
485 * @return {string} View trigger, if exists
486 */
487 mw.rcfilters.dm.FiltersViewModel.prototype.getViewTrigger = function ( view ) {
488 return ( this.views[ view ] && this.views[ view ].trigger ) || '';
489 };
490 /**
491 * Get the value of a specific parameter
492 *
493 * @param {string} name Parameter name
494 * @return {number|string} Parameter value
495 */
496 mw.rcfilters.dm.FiltersViewModel.prototype.getParamValue = function ( name ) {
497 return this.parameters[ name ];
498 };
499
500 /**
501 * Get the current selected state of the filters
502 *
503 * @return {Object} Filters selected state
504 */
505 mw.rcfilters.dm.FiltersViewModel.prototype.getSelectedState = function () {
506 var i,
507 items = this.getItems(),
508 result = {};
509
510 for ( i = 0; i < items.length; i++ ) {
511 result[ items[ i ].getName() ] = items[ i ].isSelected();
512 }
513
514 return result;
515 };
516
517 /**
518 * Get the current full state of the filters
519 *
520 * @return {Object} Filters full state
521 */
522 mw.rcfilters.dm.FiltersViewModel.prototype.getFullState = function () {
523 var i,
524 items = this.getItems(),
525 result = {};
526
527 for ( i = 0; i < items.length; i++ ) {
528 result[ items[ i ].getName() ] = {
529 selected: items[ i ].isSelected(),
530 conflicted: items[ i ].isConflicted(),
531 included: items[ i ].isIncluded()
532 };
533 }
534
535 return result;
536 };
537
538 /**
539 * Get an object representing default parameters state
540 *
541 * @return {Object} Default parameter values
542 */
543 mw.rcfilters.dm.FiltersViewModel.prototype.getDefaultParams = function () {
544 var result = {};
545
546 // Get default filter state
547 $.each( this.groups, function ( name, model ) {
548 $.extend( true, result, model.getDefaultParams() );
549 } );
550
551 return result;
552 };
553
554 /**
555 * Analyze the groups and their filters and output an object representing
556 * the state of the parameters they represent.
557 *
558 * @param {Object} [filterDefinition] An object defining the filter values,
559 * keyed by filter names.
560 * @return {Object} Parameter state object
561 */
562 mw.rcfilters.dm.FiltersViewModel.prototype.getParametersFromFilters = function ( filterDefinition ) {
563 var groupItemDefinition,
564 result = {},
565 groupItems = this.getFilterGroups();
566
567 if ( filterDefinition ) {
568 groupItemDefinition = {};
569 // Filter definition is "flat", but in effect
570 // each group needs to tell us its result based
571 // on the values in it. We need to split this list
572 // back into groupings so we can "feed" it to the
573 // loop below, and we need to expand it so it includes
574 // all filters (set to false)
575 this.getItems().forEach( function ( filterItem ) {
576 groupItemDefinition[ filterItem.getGroupName() ] = groupItemDefinition[ filterItem.getGroupName() ] || {};
577 groupItemDefinition[ filterItem.getGroupName() ][ filterItem.getName() ] = !!filterDefinition[ filterItem.getName() ];
578 } );
579 }
580
581 $.each( groupItems, function ( group, model ) {
582 $.extend(
583 result,
584 model.getParamRepresentation(
585 groupItemDefinition ?
586 groupItemDefinition[ group ] : null
587 )
588 );
589 } );
590
591 return result;
592 };
593
594 /**
595 * This is the opposite of the #getParametersFromFilters method; this goes over
596 * the given parameters and translates into a selected/unselected value in the filters.
597 *
598 * @param {Object} params Parameters query object
599 * @return {Object} Filter state object
600 */
601 mw.rcfilters.dm.FiltersViewModel.prototype.getFiltersFromParameters = function ( params ) {
602 var groupMap = {},
603 model = this,
604 result = {};
605
606 // Go over the given parameters, break apart to groupings
607 // The resulting object represents the group with its parameter
608 // values. For example:
609 // {
610 // group1: {
611 // param1: "1",
612 // param2: "0",
613 // param3: "1"
614 // },
615 // group2: "param4|param5"
616 // }
617 $.each( params, function ( paramName, paramValue ) {
618 var groupName,
619 itemOrGroup = model.parameterMap[ paramName ];
620
621 if ( itemOrGroup ) {
622 groupName = itemOrGroup instanceof mw.rcfilters.dm.FilterItem ?
623 itemOrGroup.getGroupName() : itemOrGroup.getName();
624
625 groupMap[ groupName ] = groupMap[ groupName ] || {};
626 groupMap[ groupName ][ paramName ] = paramValue;
627 }
628 } );
629
630 // Go over all groups, so we make sure we get the complete output
631 // even if the parameters don't include a certain group
632 $.each( this.groups, function ( groupName, groupModel ) {
633 result = $.extend( true, {}, result, groupModel.getFilterRepresentation( groupMap[ groupName ] ) );
634 } );
635
636 return result;
637 };
638
639 /**
640 * Get the highlight parameters based on current filter configuration
641 *
642 * @return {Object} Object where keys are "<filter name>_color" and values
643 * are the selected highlight colors.
644 */
645 mw.rcfilters.dm.FiltersViewModel.prototype.getHighlightParameters = function () {
646 var result = {};
647
648 this.getItems().forEach( function ( filterItem ) {
649 result[ filterItem.getName() + '_color' ] = filterItem.getHighlightColor() || null;
650 } );
651 result.highlight = String( Number( this.isHighlightEnabled() ) );
652
653 return result;
654 };
655
656 /**
657 * Extract the highlight values from given object. Since highlights are
658 * the same for filter and parameters, it doesn't matter which one is
659 * given; values will be returned with a full list of the highlights
660 * with colors or null values.
661 *
662 * @param {Object} representation Object containing representation of
663 * some or all highlight values
664 * @return {Object} Object where keys are "<filter name>_color" and values
665 * are the selected highlight colors. The returned object
666 * contains all available filters either with a color value
667 * or with null.
668 */
669 mw.rcfilters.dm.FiltersViewModel.prototype.extractHighlightValues = function ( representation ) {
670 var result = {};
671
672 this.getItems().forEach( function ( filterItem ) {
673 var highlightName = filterItem.getName() + '_color';
674 result[ highlightName ] = representation[ highlightName ] || null;
675 } );
676
677 return result;
678 };
679
680 /**
681 * Sanitize value group of a string_option groups type
682 * Remove duplicates and make sure to only use valid
683 * values.
684 *
685 * @private
686 * @param {string} groupName Group name
687 * @param {string[]} valueArray Array of values
688 * @return {string[]} Array of valid values
689 */
690 mw.rcfilters.dm.FiltersViewModel.prototype.sanitizeStringOptionGroup = function ( groupName, valueArray ) {
691 var validNames = this.getGroupFilters( groupName ).map( function ( filterItem ) {
692 return filterItem.getParamName();
693 } );
694
695 return mw.rcfilters.utils.normalizeParamOptions( valueArray, validNames );
696 };
697
698 /**
699 * Check whether the current filter state is set to all false.
700 *
701 * @return {boolean} Current filters are all empty
702 */
703 mw.rcfilters.dm.FiltersViewModel.prototype.areCurrentFiltersEmpty = function () {
704 // Check if there are either any selected items or any items
705 // that have highlight enabled
706 return !this.getItems().some( function ( filterItem ) {
707 return !filterItem.getGroupModel().isHidden() && ( filterItem.isSelected() || filterItem.isHighlighted() );
708 } );
709 };
710
711 /**
712 * Check whether the default values of the filters are all false.
713 *
714 * @return {boolean} Default filters are all false
715 */
716 mw.rcfilters.dm.FiltersViewModel.prototype.areDefaultFiltersEmpty = function () {
717 var defaultFilters;
718
719 if ( this.defaultFiltersEmpty !== null ) {
720 // We only need to do this test once,
721 // because defaults are set once per session
722 defaultFilters = this.getFiltersFromParameters( this.getDefaultParams() );
723 this.defaultFiltersEmpty = Object.keys( defaultFilters ).every( function ( filterName ) {
724 return !defaultFilters[ filterName ];
725 } );
726 }
727
728 return this.defaultFiltersEmpty;
729 };
730
731 /**
732 * Get the item that matches the given name
733 *
734 * @param {string} name Filter name
735 * @return {mw.rcfilters.dm.FilterItem} Filter item
736 */
737 mw.rcfilters.dm.FiltersViewModel.prototype.getItemByName = function ( name ) {
738 return this.getItems().filter( function ( item ) {
739 return name === item.getName();
740 } )[ 0 ];
741 };
742
743 /**
744 * Set all filters to false or empty/all
745 * This is equivalent to display all.
746 */
747 mw.rcfilters.dm.FiltersViewModel.prototype.emptyAllFilters = function () {
748 this.getItems().forEach( function ( filterItem ) {
749 this.toggleFilterSelected( filterItem.getName(), false );
750 }.bind( this ) );
751 };
752
753 /**
754 * Toggle selected state of one item
755 *
756 * @param {string} name Name of the filter item
757 * @param {boolean} [isSelected] Filter selected state
758 */
759 mw.rcfilters.dm.FiltersViewModel.prototype.toggleFilterSelected = function ( name, isSelected ) {
760 var item = this.getItemByName( name );
761
762 if ( item ) {
763 item.toggleSelected( isSelected );
764 }
765 };
766
767 /**
768 * Toggle selected state of items by their names
769 *
770 * @param {Object} filterDef Filter definitions
771 */
772 mw.rcfilters.dm.FiltersViewModel.prototype.toggleFiltersSelected = function ( filterDef ) {
773 Object.keys( filterDef ).forEach( function ( name ) {
774 this.toggleFilterSelected( name, filterDef[ name ] );
775 }.bind( this ) );
776 };
777
778 /**
779 * Get a group model from its name
780 *
781 * @param {string} groupName Group name
782 * @return {mw.rcfilters.dm.FilterGroup} Group model
783 */
784 mw.rcfilters.dm.FiltersViewModel.prototype.getGroup = function ( groupName ) {
785 return this.groups[ groupName ];
786 };
787
788 /**
789 * Get all filters within a specified group by its name
790 *
791 * @param {string} groupName Group name
792 * @return {mw.rcfilters.dm.FilterItem[]} Filters belonging to this group
793 */
794 mw.rcfilters.dm.FiltersViewModel.prototype.getGroupFilters = function ( groupName ) {
795 return ( this.getGroup( groupName ) && this.getGroup( groupName ).getItems() ) || [];
796 };
797
798 /**
799 * Find items whose labels match the given string
800 *
801 * @param {string} query Search string
802 * @param {boolean} [returnFlat] Return a flat array. If false, the result
803 * is an object whose keys are the group names and values are an array of
804 * filters per group. If set to true, returns an array of filters regardless
805 * of their groups.
806 * @return {Object} An object of items to show
807 * arranged by their group names
808 */
809 mw.rcfilters.dm.FiltersViewModel.prototype.findMatches = function ( query, returnFlat ) {
810 var i, searchIsEmpty,
811 groupTitle,
812 result = {},
813 flatResult = [],
814 view = this.getViewByTrigger( query.substr( 0, 1 ) ),
815 items = this.getFiltersByView( view );
816
817 // Normalize so we can search strings regardless of case and view
818 query = query.toLowerCase();
819 if ( view !== 'default' ) {
820 query = query.substr( 1 );
821 }
822
823 // Check if the search if actually empty; this can be a problem when
824 // we use prefixes to denote different views
825 searchIsEmpty = query.length === 0;
826
827 // item label starting with the query string
828 for ( i = 0; i < items.length; i++ ) {
829 if (
830 searchIsEmpty ||
831 items[ i ].getLabel().toLowerCase().indexOf( query ) === 0 ||
832 (
833 // For tags, we want the parameter name to be included in the search
834 view === 'tags' &&
835 items[ i ].getParamName().toLowerCase().indexOf( query ) > -1
836 )
837 ) {
838 result[ items[ i ].getGroupName() ] = result[ items[ i ].getGroupName() ] || [];
839 result[ items[ i ].getGroupName() ].push( items[ i ] );
840 flatResult.push( items[ i ] );
841 }
842 }
843
844 if ( $.isEmptyObject( result ) ) {
845 // item containing the query string in their label, description, or group title
846 for ( i = 0; i < items.length; i++ ) {
847 groupTitle = items[ i ].getGroupModel().getTitle();
848 if (
849 searchIsEmpty ||
850 items[ i ].getLabel().toLowerCase().indexOf( query ) > -1 ||
851 items[ i ].getDescription().toLowerCase().indexOf( query ) > -1 ||
852 groupTitle.toLowerCase().indexOf( query ) > -1 ||
853 (
854 // For tags, we want the parameter name to be included in the search
855 view === 'tags' &&
856 items[ i ].getParamName().toLowerCase().indexOf( query ) > -1
857 )
858 ) {
859 result[ items[ i ].getGroupName() ] = result[ items[ i ].getGroupName() ] || [];
860 result[ items[ i ].getGroupName() ].push( items[ i ] );
861 flatResult.push( items[ i ] );
862 }
863 }
864 }
865
866 return returnFlat ? flatResult : result;
867 };
868
869 /**
870 * Get items that are highlighted
871 *
872 * @return {mw.rcfilters.dm.FilterItem[]} Highlighted items
873 */
874 mw.rcfilters.dm.FiltersViewModel.prototype.getHighlightedItems = function () {
875 return this.getItems().filter( function ( filterItem ) {
876 return filterItem.isHighlightSupported() &&
877 filterItem.getHighlightColor();
878 } );
879 };
880
881 /**
882 * Get items that allow highlights even if they're not currently highlighted
883 *
884 * @return {mw.rcfilters.dm.FilterItem[]} Items supporting highlights
885 */
886 mw.rcfilters.dm.FiltersViewModel.prototype.getItemsSupportingHighlights = function () {
887 return this.getItems().filter( function ( filterItem ) {
888 return filterItem.isHighlightSupported();
889 } );
890 };
891
892 /**
893 * Get all selected items
894 *
895 * @return {mw.rcfilters.dm.FilterItem[]} Selected items
896 */
897 mw.rcfilters.dm.FiltersViewModel.prototype.getSelectedItems = function () {
898 var allSelected = [];
899
900 $.each( this.getFilterGroups(), function ( groupName, groupModel ) {
901 allSelected = allSelected.concat( groupModel.getSelectedItems() );
902 } );
903
904 return allSelected;
905 };
906 /**
907 * Switch the current view
908 *
909 * @param {string} view View name
910 * @fires update
911 */
912 mw.rcfilters.dm.FiltersViewModel.prototype.switchView = function ( view ) {
913 if ( this.views[ view ] && this.currentView !== view ) {
914 this.currentView = view;
915 this.emit( 'update' );
916 }
917 };
918
919 /**
920 * Get the current view
921 *
922 * @return {string} Current view
923 */
924 mw.rcfilters.dm.FiltersViewModel.prototype.getCurrentView = function () {
925 return this.currentView;
926 };
927
928 /**
929 * Get the label for the current view
930 *
931 * @param {string} viewName View name
932 * @return {string} Label for the current view
933 */
934 mw.rcfilters.dm.FiltersViewModel.prototype.getViewTitle = function ( viewName ) {
935 viewName = viewName || this.getCurrentView();
936
937 return this.views[ viewName ] && this.views[ viewName ].title;
938 };
939
940 /**
941 * Get an array of all available view names
942 *
943 * @return {string} Available view names
944 */
945 mw.rcfilters.dm.FiltersViewModel.prototype.getAvailableViews = function () {
946 return Object.keys( this.views );
947 };
948
949 /**
950 * Get the view that fits the given trigger
951 *
952 * @param {string} trigger Trigger
953 * @return {string} Name of view
954 */
955 mw.rcfilters.dm.FiltersViewModel.prototype.getViewByTrigger = function ( trigger ) {
956 var result = 'default';
957
958 $.each( this.views, function ( name, data ) {
959 if ( data.trigger === trigger ) {
960 result = name;
961 }
962 } );
963
964 return result;
965 };
966
967 /**
968 * Toggle the highlight feature on and off.
969 * Propagate the change to filter items.
970 *
971 * @param {boolean} enable Highlight should be enabled
972 * @fires highlightChange
973 */
974 mw.rcfilters.dm.FiltersViewModel.prototype.toggleHighlight = function ( enable ) {
975 enable = enable === undefined ? !this.highlightEnabled : enable;
976
977 if ( this.highlightEnabled !== enable ) {
978 this.highlightEnabled = enable;
979
980 this.getItems().forEach( function ( filterItem ) {
981 filterItem.toggleHighlight( this.highlightEnabled );
982 }.bind( this ) );
983
984 this.emit( 'highlightChange', this.highlightEnabled );
985 }
986 };
987
988 /**
989 * Check if the highlight feature is enabled
990 * @return {boolean}
991 */
992 mw.rcfilters.dm.FiltersViewModel.prototype.isHighlightEnabled = function () {
993 return !!this.highlightEnabled;
994 };
995
996 /**
997 * Toggle the inverted namespaces property on and off.
998 * Propagate the change to namespace filter items.
999 *
1000 * @param {boolean} enable Inverted property is enabled
1001 * @fires invertChange
1002 */
1003 mw.rcfilters.dm.FiltersViewModel.prototype.toggleInvertedNamespaces = function ( enable ) {
1004 enable = enable === undefined ? !this.invertedNamespaces : enable;
1005
1006 if ( this.invertedNamespaces !== enable ) {
1007 this.invertedNamespaces = enable;
1008
1009 this.getFiltersByView( 'namespaces' ).forEach( function ( filterItem ) {
1010 filterItem.toggleInverted( this.invertedNamespaces );
1011 }.bind( this ) );
1012
1013 this.emit( 'invertChange', this.invertedNamespaces );
1014 }
1015 };
1016
1017 /**
1018 * Check if the namespaces selection is set to be inverted
1019 * @return {boolean}
1020 */
1021 mw.rcfilters.dm.FiltersViewModel.prototype.areNamespacesInverted = function () {
1022 return !!this.invertedNamespaces;
1023 };
1024
1025 /**
1026 * Set highlight color for a specific filter item
1027 *
1028 * @param {string} filterName Name of the filter item
1029 * @param {string} color Selected color
1030 */
1031 mw.rcfilters.dm.FiltersViewModel.prototype.setHighlightColor = function ( filterName, color ) {
1032 this.getItemByName( filterName ).setHighlightColor( color );
1033 };
1034
1035 /**
1036 * Clear highlight for a specific filter item
1037 *
1038 * @param {string} filterName Name of the filter item
1039 */
1040 mw.rcfilters.dm.FiltersViewModel.prototype.clearHighlightColor = function ( filterName ) {
1041 this.getItemByName( filterName ).clearHighlightColor();
1042 };
1043
1044 /**
1045 * Clear highlight for all filter items
1046 */
1047 mw.rcfilters.dm.FiltersViewModel.prototype.clearAllHighlightColors = function () {
1048 this.getItems().forEach( function ( filterItem ) {
1049 filterItem.clearHighlightColor();
1050 } );
1051 };
1052
1053 /**
1054 * Return a version of the given string that is without any
1055 * view triggers.
1056 *
1057 * @param {string} str Given string
1058 * @return {string} Result
1059 */
1060 mw.rcfilters.dm.FiltersViewModel.prototype.removeViewTriggers = function ( str ) {
1061 if ( this.getViewByTrigger( str.substr( 0, 1 ) ) !== 'default' ) {
1062 str = str.substr( 1 );
1063 }
1064
1065 return str;
1066 };
1067 }( mediaWiki, jQuery ) );