Merge "Fix \n handling for HTMLUsersMultiselectField"
[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 ( groupModel.getType() === 'send_unselected_if_any' ) {
400 // Individual filters
401 groupModel.getItems().forEach( function ( filterItem ) {
402 model.parameterMap[ filterItem.getParamName() ] = filterItem;
403 } );
404 } else if (
405 groupModel.getType() === 'string_options' ||
406 groupModel.getType() === 'single_option'
407 ) {
408 // Group
409 model.parameterMap[ groupModel.getName() ] = groupModel;
410 }
411 } );
412
413 this.currentView = 'default';
414
415 // Finish initialization
416 this.emit( 'initialize' );
417 };
418
419 /**
420 * Get the names of all available filters
421 *
422 * @return {string[]} An array of filter names
423 */
424 mw.rcfilters.dm.FiltersViewModel.prototype.getFilterNames = function () {
425 return this.getItems().map( function ( item ) { return item.getName(); } );
426 };
427
428 /**
429 * Get the object that defines groups by their name.
430 *
431 * @return {Object} Filter groups
432 */
433 mw.rcfilters.dm.FiltersViewModel.prototype.getFilterGroups = function () {
434 return this.groups;
435 };
436
437 /**
438 * Get the object that defines groups that match a certain view by their name.
439 *
440 * @param {string} [view] Requested view. If not given, uses current view
441 * @return {Object} Filter groups matching a display group
442 */
443 mw.rcfilters.dm.FiltersViewModel.prototype.getFilterGroupsByView = function ( view ) {
444 var result = {};
445
446 view = view || this.getCurrentView();
447
448 $.each( this.groups, function ( groupName, groupModel ) {
449 if ( groupModel.getView() === view ) {
450 result[ groupName ] = groupModel;
451 }
452 } );
453
454 return result;
455 };
456
457 /**
458 * Get an array of filters matching the given display group.
459 *
460 * @param {string} [view] Requested view. If not given, uses current view
461 * @return {mw.rcfilters.dm.FilterItem} Filter items matching the group
462 */
463 mw.rcfilters.dm.FiltersViewModel.prototype.getFiltersByView = function ( view ) {
464 var groups,
465 result = [];
466
467 view = view || this.getCurrentView();
468
469 groups = this.getFilterGroupsByView( view );
470
471 $.each( groups, function ( groupName, groupModel ) {
472 result = result.concat( groupModel.getItems() );
473 } );
474
475 return result;
476 };
477
478 /**
479 * Get the trigger for the requested view.
480 *
481 * @param {string} view View name
482 * @return {string} View trigger, if exists
483 */
484 mw.rcfilters.dm.FiltersViewModel.prototype.getViewTrigger = function ( view ) {
485 return ( this.views[ view ] && this.views[ view ].trigger ) || '';
486 };
487 /**
488 * Get the value of a specific parameter
489 *
490 * @param {string} name Parameter name
491 * @return {number|string} Parameter value
492 */
493 mw.rcfilters.dm.FiltersViewModel.prototype.getParamValue = function ( name ) {
494 return this.parameters[ name ];
495 };
496
497 /**
498 * Get the current selected state of the filters
499 *
500 * @return {Object} Filters selected state
501 */
502 mw.rcfilters.dm.FiltersViewModel.prototype.getSelectedState = function () {
503 var i,
504 items = this.getItems(),
505 result = {};
506
507 for ( i = 0; i < items.length; i++ ) {
508 result[ items[ i ].getName() ] = items[ i ].isSelected();
509 }
510
511 return result;
512 };
513
514 /**
515 * Get the current full state of the filters
516 *
517 * @return {Object} Filters full state
518 */
519 mw.rcfilters.dm.FiltersViewModel.prototype.getFullState = function () {
520 var i,
521 items = this.getItems(),
522 result = {};
523
524 for ( i = 0; i < items.length; i++ ) {
525 result[ items[ i ].getName() ] = {
526 selected: items[ i ].isSelected(),
527 conflicted: items[ i ].isConflicted(),
528 included: items[ i ].isIncluded()
529 };
530 }
531
532 return result;
533 };
534
535 /**
536 * Get an object representing default parameters state
537 *
538 * @return {Object} Default parameter values
539 */
540 mw.rcfilters.dm.FiltersViewModel.prototype.getDefaultParams = function () {
541 var result = {};
542
543 // Get default filter state
544 $.each( this.groups, function ( name, model ) {
545 $.extend( true, result, model.getDefaultParams() );
546 } );
547
548 return result;
549 };
550
551 /**
552 * Analyze the groups and their filters and output an object representing
553 * the state of the parameters they represent.
554 *
555 * @param {Object} [filterDefinition] An object defining the filter values,
556 * keyed by filter names.
557 * @return {Object} Parameter state object
558 */
559 mw.rcfilters.dm.FiltersViewModel.prototype.getParametersFromFilters = function ( filterDefinition ) {
560 var groupItemDefinition,
561 result = {},
562 groupItems = this.getFilterGroups();
563
564 if ( filterDefinition ) {
565 groupItemDefinition = {};
566 // Filter definition is "flat", but in effect
567 // each group needs to tell us its result based
568 // on the values in it. We need to split this list
569 // back into groupings so we can "feed" it to the
570 // loop below, and we need to expand it so it includes
571 // all filters (set to false)
572 this.getItems().forEach( function ( filterItem ) {
573 groupItemDefinition[ filterItem.getGroupName() ] = groupItemDefinition[ filterItem.getGroupName() ] || {};
574 groupItemDefinition[ filterItem.getGroupName() ][ filterItem.getName() ] = !!filterDefinition[ filterItem.getName() ];
575 } );
576 }
577
578 $.each( groupItems, function ( group, model ) {
579 $.extend(
580 result,
581 model.getParamRepresentation(
582 groupItemDefinition ?
583 groupItemDefinition[ group ] : null
584 )
585 );
586 } );
587
588 return result;
589 };
590
591 /**
592 * This is the opposite of the #getParametersFromFilters method; this goes over
593 * the given parameters and translates into a selected/unselected value in the filters.
594 *
595 * @param {Object} params Parameters query object
596 * @return {Object} Filter state object
597 */
598 mw.rcfilters.dm.FiltersViewModel.prototype.getFiltersFromParameters = function ( params ) {
599 var groupMap = {},
600 model = this,
601 result = {};
602
603 // Go over the given parameters, break apart to groupings
604 // The resulting object represents the group with its parameter
605 // values. For example:
606 // {
607 // group1: {
608 // param1: "1",
609 // param2: "0",
610 // param3: "1"
611 // },
612 // group2: "param4|param5"
613 // }
614 $.each( params, function ( paramName, paramValue ) {
615 var itemOrGroup = model.parameterMap[ paramName ];
616
617 if ( itemOrGroup instanceof mw.rcfilters.dm.FilterItem ) {
618 groupMap[ itemOrGroup.getGroupName() ] = groupMap[ itemOrGroup.getGroupName() ] || {};
619 groupMap[ itemOrGroup.getGroupName() ][ itemOrGroup.getParamName() ] = paramValue;
620 } else if ( itemOrGroup instanceof mw.rcfilters.dm.FilterGroup ) {
621 // This parameter represents a group (values are the filters)
622 // this is equivalent to checking if the group is 'string_options'
623 groupMap[ itemOrGroup.getName() ] = groupMap[ itemOrGroup.getName() ] || {};
624 groupMap[ itemOrGroup.getName() ] = paramValue;
625 }
626 } );
627
628 // Go over all groups, so we make sure we get the complete output
629 // even if the parameters don't include a certain group
630 $.each( this.groups, function ( groupName, groupModel ) {
631 result = $.extend( true, {}, result, groupModel.getFilterRepresentation( groupMap[ groupName ] ) );
632 } );
633
634 return result;
635 };
636
637 /**
638 * Get the highlight parameters based on current filter configuration
639 *
640 * @return {Object} Object where keys are "<filter name>_color" and values
641 * are the selected highlight colors.
642 */
643 mw.rcfilters.dm.FiltersViewModel.prototype.getHighlightParameters = function () {
644 var result = {};
645
646 this.getItems().forEach( function ( filterItem ) {
647 result[ filterItem.getName() + '_color' ] = filterItem.getHighlightColor() || null;
648 } );
649 result.highlight = String( Number( this.isHighlightEnabled() ) );
650
651 return result;
652 };
653
654 /**
655 * Extract the highlight values from given object. Since highlights are
656 * the same for filter and parameters, it doesn't matter which one is
657 * given; values will be returned with a full list of the highlights
658 * with colors or null values.
659 *
660 * @param {Object} representation Object containing representation of
661 * some or all highlight values
662 * @return {Object} Object where keys are "<filter name>_color" and values
663 * are the selected highlight colors. The returned object
664 * contains all available filters either with a color value
665 * or with null.
666 */
667 mw.rcfilters.dm.FiltersViewModel.prototype.extractHighlightValues = function ( representation ) {
668 var result = {};
669
670 this.getItems().forEach( function ( filterItem ) {
671 var highlightName = filterItem.getName() + '_color';
672 result[ highlightName ] = representation[ highlightName ] || null;
673 } );
674
675 return result;
676 };
677
678 /**
679 * Sanitize value group of a string_option groups type
680 * Remove duplicates and make sure to only use valid
681 * values.
682 *
683 * @private
684 * @param {string} groupName Group name
685 * @param {string[]} valueArray Array of values
686 * @return {string[]} Array of valid values
687 */
688 mw.rcfilters.dm.FiltersViewModel.prototype.sanitizeStringOptionGroup = function ( groupName, valueArray ) {
689 var validNames = this.getGroupFilters( groupName ).map( function ( filterItem ) {
690 return filterItem.getParamName();
691 } );
692
693 return mw.rcfilters.utils.normalizeParamOptions( valueArray, validNames );
694 };
695
696 /**
697 * Check whether the current filter state is set to all false.
698 *
699 * @return {boolean} Current filters are all empty
700 */
701 mw.rcfilters.dm.FiltersViewModel.prototype.areCurrentFiltersEmpty = function () {
702 // Check if there are either any selected items or any items
703 // that have highlight enabled
704 return !this.getItems().some( function ( filterItem ) {
705 return filterItem.isSelected() || filterItem.isHighlighted();
706 } );
707 };
708
709 /**
710 * Check whether the default values of the filters are all false.
711 *
712 * @return {boolean} Default filters are all false
713 */
714 mw.rcfilters.dm.FiltersViewModel.prototype.areDefaultFiltersEmpty = function () {
715 var defaultFilters;
716
717 if ( this.defaultFiltersEmpty !== null ) {
718 // We only need to do this test once,
719 // because defaults are set once per session
720 defaultFilters = this.getFiltersFromParameters( this.getDefaultParams() );
721 this.defaultFiltersEmpty = Object.keys( defaultFilters ).every( function ( filterName ) {
722 return !defaultFilters[ filterName ];
723 } );
724 }
725
726 return this.defaultFiltersEmpty;
727 };
728
729 /**
730 * Get the item that matches the given name
731 *
732 * @param {string} name Filter name
733 * @return {mw.rcfilters.dm.FilterItem} Filter item
734 */
735 mw.rcfilters.dm.FiltersViewModel.prototype.getItemByName = function ( name ) {
736 return this.getItems().filter( function ( item ) {
737 return name === item.getName();
738 } )[ 0 ];
739 };
740
741 /**
742 * Set all filters to false or empty/all
743 * This is equivalent to display all.
744 */
745 mw.rcfilters.dm.FiltersViewModel.prototype.emptyAllFilters = function () {
746 this.getItems().forEach( function ( filterItem ) {
747 this.toggleFilterSelected( filterItem.getName(), false );
748 }.bind( this ) );
749 };
750
751 /**
752 * Toggle selected state of one item
753 *
754 * @param {string} name Name of the filter item
755 * @param {boolean} [isSelected] Filter selected state
756 */
757 mw.rcfilters.dm.FiltersViewModel.prototype.toggleFilterSelected = function ( name, isSelected ) {
758 var item = this.getItemByName( name );
759
760 if ( item ) {
761 item.toggleSelected( isSelected );
762 }
763 };
764
765 /**
766 * Toggle selected state of items by their names
767 *
768 * @param {Object} filterDef Filter definitions
769 */
770 mw.rcfilters.dm.FiltersViewModel.prototype.toggleFiltersSelected = function ( filterDef ) {
771 Object.keys( filterDef ).forEach( function ( name ) {
772 this.toggleFilterSelected( name, filterDef[ name ] );
773 }.bind( this ) );
774 };
775
776 /**
777 * Get a group model from its name
778 *
779 * @param {string} groupName Group name
780 * @return {mw.rcfilters.dm.FilterGroup} Group model
781 */
782 mw.rcfilters.dm.FiltersViewModel.prototype.getGroup = function ( groupName ) {
783 return this.groups[ groupName ];
784 };
785
786 /**
787 * Get all filters within a specified group by its name
788 *
789 * @param {string} groupName Group name
790 * @return {mw.rcfilters.dm.FilterItem[]} Filters belonging to this group
791 */
792 mw.rcfilters.dm.FiltersViewModel.prototype.getGroupFilters = function ( groupName ) {
793 return ( this.getGroup( groupName ) && this.getGroup( groupName ).getItems() ) || [];
794 };
795
796 /**
797 * Find items whose labels match the given string
798 *
799 * @param {string} query Search string
800 * @param {boolean} [returnFlat] Return a flat array. If false, the result
801 * is an object whose keys are the group names and values are an array of
802 * filters per group. If set to true, returns an array of filters regardless
803 * of their groups.
804 * @return {Object} An object of items to show
805 * arranged by their group names
806 */
807 mw.rcfilters.dm.FiltersViewModel.prototype.findMatches = function ( query, returnFlat ) {
808 var i, searchIsEmpty,
809 groupTitle,
810 result = {},
811 flatResult = [],
812 view = this.getViewByTrigger( query.substr( 0, 1 ) ),
813 items = this.getFiltersByView( view );
814
815 // Normalize so we can search strings regardless of case and view
816 query = query.toLowerCase();
817 if ( view !== 'default' ) {
818 query = query.substr( 1 );
819 }
820
821 // Check if the search if actually empty; this can be a problem when
822 // we use prefixes to denote different views
823 searchIsEmpty = query.length === 0;
824
825 // item label starting with the query string
826 for ( i = 0; i < items.length; i++ ) {
827 if (
828 searchIsEmpty ||
829 items[ i ].getLabel().toLowerCase().indexOf( query ) === 0 ||
830 (
831 // For tags, we want the parameter name to be included in the search
832 view === 'tags' &&
833 items[ i ].getParamName().toLowerCase().indexOf( query ) > -1
834 )
835 ) {
836 result[ items[ i ].getGroupName() ] = result[ items[ i ].getGroupName() ] || [];
837 result[ items[ i ].getGroupName() ].push( items[ i ] );
838 flatResult.push( items[ i ] );
839 }
840 }
841
842 if ( $.isEmptyObject( result ) ) {
843 // item containing the query string in their label, description, or group title
844 for ( i = 0; i < items.length; i++ ) {
845 groupTitle = items[ i ].getGroupModel().getTitle();
846 if (
847 searchIsEmpty ||
848 items[ i ].getLabel().toLowerCase().indexOf( query ) > -1 ||
849 items[ i ].getDescription().toLowerCase().indexOf( query ) > -1 ||
850 groupTitle.toLowerCase().indexOf( query ) > -1 ||
851 (
852 // For tags, we want the parameter name to be included in the search
853 view === 'tags' &&
854 items[ i ].getParamName().toLowerCase().indexOf( query ) > -1
855 )
856 ) {
857 result[ items[ i ].getGroupName() ] = result[ items[ i ].getGroupName() ] || [];
858 result[ items[ i ].getGroupName() ].push( items[ i ] );
859 flatResult.push( items[ i ] );
860 }
861 }
862 }
863
864 return returnFlat ? flatResult : result;
865 };
866
867 /**
868 * Get items that are highlighted
869 *
870 * @return {mw.rcfilters.dm.FilterItem[]} Highlighted items
871 */
872 mw.rcfilters.dm.FiltersViewModel.prototype.getHighlightedItems = function () {
873 return this.getItems().filter( function ( filterItem ) {
874 return filterItem.isHighlightSupported() &&
875 filterItem.getHighlightColor();
876 } );
877 };
878
879 /**
880 * Get items that allow highlights even if they're not currently highlighted
881 *
882 * @return {mw.rcfilters.dm.FilterItem[]} Items supporting highlights
883 */
884 mw.rcfilters.dm.FiltersViewModel.prototype.getItemsSupportingHighlights = function () {
885 return this.getItems().filter( function ( filterItem ) {
886 return filterItem.isHighlightSupported();
887 } );
888 };
889
890 /**
891 * Switch the current view
892 *
893 * @param {string} view View name
894 * @fires update
895 */
896 mw.rcfilters.dm.FiltersViewModel.prototype.switchView = function ( view ) {
897 if ( this.views[ view ] && this.currentView !== view ) {
898 this.currentView = view;
899 this.emit( 'update' );
900 }
901 };
902
903 /**
904 * Get the current view
905 *
906 * @return {string} Current view
907 */
908 mw.rcfilters.dm.FiltersViewModel.prototype.getCurrentView = function () {
909 return this.currentView;
910 };
911
912 /**
913 * Get the label for the current view
914 *
915 * @param {string} viewName View name
916 * @return {string} Label for the current view
917 */
918 mw.rcfilters.dm.FiltersViewModel.prototype.getViewTitle = function ( viewName ) {
919 viewName = viewName || this.getCurrentView();
920
921 return this.views[ viewName ] && this.views[ viewName ].title;
922 };
923
924 /**
925 * Get an array of all available view names
926 *
927 * @return {string} Available view names
928 */
929 mw.rcfilters.dm.FiltersViewModel.prototype.getAvailableViews = function () {
930 return Object.keys( this.views );
931 };
932
933 /**
934 * Get the view that fits the given trigger
935 *
936 * @param {string} trigger Trigger
937 * @return {string} Name of view
938 */
939 mw.rcfilters.dm.FiltersViewModel.prototype.getViewByTrigger = function ( trigger ) {
940 var result = 'default';
941
942 $.each( this.views, function ( name, data ) {
943 if ( data.trigger === trigger ) {
944 result = name;
945 }
946 } );
947
948 return result;
949 };
950
951 /**
952 * Toggle the highlight feature on and off.
953 * Propagate the change to filter items.
954 *
955 * @param {boolean} enable Highlight should be enabled
956 * @fires highlightChange
957 */
958 mw.rcfilters.dm.FiltersViewModel.prototype.toggleHighlight = function ( enable ) {
959 enable = enable === undefined ? !this.highlightEnabled : enable;
960
961 if ( this.highlightEnabled !== enable ) {
962 this.highlightEnabled = enable;
963
964 this.getItems().forEach( function ( filterItem ) {
965 filterItem.toggleHighlight( this.highlightEnabled );
966 }.bind( this ) );
967
968 this.emit( 'highlightChange', this.highlightEnabled );
969 }
970 };
971
972 /**
973 * Check if the highlight feature is enabled
974 * @return {boolean}
975 */
976 mw.rcfilters.dm.FiltersViewModel.prototype.isHighlightEnabled = function () {
977 return !!this.highlightEnabled;
978 };
979
980 /**
981 * Toggle the inverted namespaces property on and off.
982 * Propagate the change to namespace filter items.
983 *
984 * @param {boolean} enable Inverted property is enabled
985 * @fires invertChange
986 */
987 mw.rcfilters.dm.FiltersViewModel.prototype.toggleInvertedNamespaces = function ( enable ) {
988 enable = enable === undefined ? !this.invertedNamespaces : enable;
989
990 if ( this.invertedNamespaces !== enable ) {
991 this.invertedNamespaces = enable;
992
993 this.getFiltersByView( 'namespaces' ).forEach( function ( filterItem ) {
994 filterItem.toggleInverted( this.invertedNamespaces );
995 }.bind( this ) );
996
997 this.emit( 'invertChange', this.invertedNamespaces );
998 }
999 };
1000
1001 /**
1002 * Check if the namespaces selection is set to be inverted
1003 * @return {boolean}
1004 */
1005 mw.rcfilters.dm.FiltersViewModel.prototype.areNamespacesInverted = function () {
1006 return !!this.invertedNamespaces;
1007 };
1008
1009 /**
1010 * Set highlight color for a specific filter item
1011 *
1012 * @param {string} filterName Name of the filter item
1013 * @param {string} color Selected color
1014 */
1015 mw.rcfilters.dm.FiltersViewModel.prototype.setHighlightColor = function ( filterName, color ) {
1016 this.getItemByName( filterName ).setHighlightColor( color );
1017 };
1018
1019 /**
1020 * Clear highlight for a specific filter item
1021 *
1022 * @param {string} filterName Name of the filter item
1023 */
1024 mw.rcfilters.dm.FiltersViewModel.prototype.clearHighlightColor = function ( filterName ) {
1025 this.getItemByName( filterName ).clearHighlightColor();
1026 };
1027
1028 /**
1029 * Clear highlight for all filter items
1030 */
1031 mw.rcfilters.dm.FiltersViewModel.prototype.clearAllHighlightColors = function () {
1032 this.getItems().forEach( function ( filterItem ) {
1033 filterItem.clearHighlightColor();
1034 } );
1035 };
1036
1037 /**
1038 * Return a version of the given string that is without any
1039 * view triggers.
1040 *
1041 * @param {string} str Given string
1042 * @return {string} Result
1043 */
1044 mw.rcfilters.dm.FiltersViewModel.prototype.removeViewTriggers = function ( str ) {
1045 if ( this.getViewByTrigger( str.substr( 0, 1 ) ) !== 'default' ) {
1046 str = str.substr( 1 );
1047 }
1048
1049 return str;
1050 };
1051 }( mediaWiki, jQuery ) );