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