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