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