Merge "maintenance: Consistently use hasOption() for boolean options"
[lhc/web/wiklou.git] / resources / src / mediawiki.rcfilters / dm / mw.rcfilters.dm.FilterGroup.js
1 ( function ( mw ) {
2 /**
3 * View model for a filter group
4 *
5 * @mixins OO.EventEmitter
6 * @mixins OO.EmitterList
7 *
8 * @constructor
9 * @param {string} name Group name
10 * @param {Object} [config] Configuration options
11 * @cfg {string} [type='send_unselected_if_any'] Group type
12 * @cfg {string} [view='default'] Name of the display group this group
13 * is a part of.
14 * @cfg {string} [title] Group title
15 * @cfg {boolean} [hidden] This group is hidden from the regular menu views
16 * @cfg {boolean} [allowArbitrary] Allows for an arbitrary value to be added to the
17 * group from the URL, even if it wasn't initially set up.
18 * @cfg {string} [separator='|'] Value separator for 'string_options' groups
19 * @cfg {boolean} [active] Group is active
20 * @cfg {boolean} [fullCoverage] This filters in this group collectively cover all results
21 * @cfg {Object} [conflicts] Defines the conflicts for this filter group
22 * @cfg {string|Object} [labelPrefixKey] An i18n key defining the prefix label for this
23 * group. If the prefix has 'invert' state, the parameter is expected to be an object
24 * with 'default' and 'inverted' as keys.
25 * @cfg {Object} [whatsThis] Defines the messages that should appear for the 'what's this' popup
26 * @cfg {string} [whatsThis.header] The header of the whatsThis popup message
27 * @cfg {string} [whatsThis.body] The body of the whatsThis popup message
28 * @cfg {string} [whatsThis.url] The url for the link in the whatsThis popup message
29 * @cfg {string} [whatsThis.linkMessage] The text for the link in the whatsThis popup message
30 */
31 mw.rcfilters.dm.FilterGroup = function MwRcfiltersDmFilterGroup( name, config ) {
32 config = config || {};
33
34 // Mixin constructor
35 OO.EventEmitter.call( this );
36 OO.EmitterList.call( this );
37
38 this.name = name;
39 this.type = config.type || 'send_unselected_if_any';
40 this.view = config.view || 'default';
41 this.title = config.title || name;
42 this.hidden = !!config.hidden;
43 this.allowArbitrary = !!config.allowArbitrary;
44 this.separator = config.separator || '|';
45 this.labelPrefixKey = config.labelPrefixKey;
46
47 this.currSelected = null;
48 this.active = !!config.active;
49 this.fullCoverage = !!config.fullCoverage;
50
51 this.whatsThis = config.whatsThis || {};
52
53 this.conflicts = config.conflicts || {};
54 this.defaultParams = {};
55
56 this.aggregate( { update: 'filterItemUpdate' } );
57 this.connect( this, { filterItemUpdate: 'onFilterItemUpdate' } );
58 };
59
60 /* Initialization */
61 OO.initClass( mw.rcfilters.dm.FilterGroup );
62 OO.mixinClass( mw.rcfilters.dm.FilterGroup, OO.EventEmitter );
63 OO.mixinClass( mw.rcfilters.dm.FilterGroup, OO.EmitterList );
64
65 /* Events */
66
67 /**
68 * @event update
69 *
70 * Group state has been updated
71 */
72
73 /* Methods */
74
75 /**
76 * Initialize the group and create its filter items
77 *
78 * @param {Object} filterDefinition Filter definition for this group
79 * @param {string|Object} [groupDefault] Definition of the group default
80 */
81 mw.rcfilters.dm.FilterGroup.prototype.initializeFilters = function ( filterDefinition, groupDefault ) {
82 var defaultParam,
83 supersetMap = {},
84 model = this,
85 items = [];
86
87 filterDefinition.forEach( function ( filter ) {
88 // Instantiate an item
89 var subsetNames = [],
90 filterItem = new mw.rcfilters.dm.FilterItem( filter.name, model, {
91 group: model.getName(),
92 label: filter.label || filter.name,
93 description: filter.description || '',
94 labelPrefixKey: model.labelPrefixKey,
95 cssClass: filter.cssClass,
96 identifiers: filter.identifiers
97 } );
98
99 if ( filter.subset ) {
100 filter.subset = filter.subset.map( function ( el ) {
101 return el.filter;
102 } );
103
104 subsetNames = [];
105
106 filter.subset.forEach( function ( subsetFilterName ) { // eslint-disable-line no-loop-func
107 // Subsets (unlike conflicts) are always inside the same group
108 // We can re-map the names of the filters we are getting from
109 // the subsets with the group prefix
110 var subsetName = model.getPrefixedName( subsetFilterName );
111 // For convenience, we should store each filter's "supersets" -- these are
112 // the filters that have that item in their subset list. This will just
113 // make it easier to go through whether the item has any other items
114 // that affect it (and are selected) at any given time
115 supersetMap[ subsetName ] = supersetMap[ subsetName ] || [];
116 mw.rcfilters.utils.addArrayElementsUnique(
117 supersetMap[ subsetName ],
118 filterItem.getName()
119 );
120
121 // Translate subset param name to add the group name, so we
122 // get consistent naming. We know that subsets are only within
123 // the same group
124 subsetNames.push( subsetName );
125 } );
126
127 // Set translated subset
128 filterItem.setSubset( subsetNames );
129 }
130
131 items.push( filterItem );
132
133 // Store default parameter state; in this case, default is defined per filter
134 if ( model.getType() === 'send_unselected_if_any' ) {
135 // Store the default parameter state
136 // For this group type, parameter values are direct
137 // We need to convert from a boolean to a string ('1' and '0')
138 model.defaultParams[ filter.name ] = String( Number( !!filter.default ) );
139 }
140 } );
141
142 // Add items
143 this.addItems( items );
144
145 // Now that we have all items, we can apply the superset map
146 this.getItems().forEach( function ( filterItem ) {
147 filterItem.setSuperset( supersetMap[ filterItem.getName() ] );
148 } );
149
150 // Store default parameter state; in this case, default is defined per the
151 // entire group, given by groupDefault method parameter
152 if ( this.getType() === 'string_options' ) {
153 // Store the default parameter group state
154 // For this group, the parameter is group name and value is the names
155 // of selected items
156 this.defaultParams[ this.getName() ] = mw.rcfilters.utils.normalizeParamOptions(
157 // Current values
158 groupDefault ?
159 groupDefault.split( this.getSeparator() ) :
160 [],
161 // Legal values
162 this.getItems().map( function ( item ) {
163 return item.getParamName();
164 } )
165 ).join( this.getSeparator() );
166 } else if ( this.getType() === 'single_option' ) {
167 defaultParam = groupDefault !== undefined ?
168 groupDefault : this.getItems()[ 0 ].getParamName();
169
170 // For this group, the parameter is the group name,
171 // and a single item can be selected: default or first item
172 this.defaultParams[ this.getName() ] = defaultParam;
173
174 // Single option means there must be a single option
175 // selected, so we have to either select the default
176 // or select the first option
177 this.selectItemByParamName( defaultParam );
178 }
179 };
180
181 /**
182 * Respond to filterItem update event
183 *
184 * @param {mw.rcfilters.dm.FilterItem} item Updated filter item
185 * @fires update
186 */
187 mw.rcfilters.dm.FilterGroup.prototype.onFilterItemUpdate = function ( item ) {
188 // Update state
189 var active = this.areAnySelected();
190
191 if (
192 item.isSelected() &&
193 this.getType() === 'single_option' &&
194 this.currSelected &&
195 this.currSelected !== item
196 ) {
197 this.currSelected.toggleSelected( false );
198 }
199
200 if (
201 this.active !== active ||
202 this.currSelected !== item
203 ) {
204 this.active = active;
205 this.currSelected = item;
206
207 this.emit( 'update' );
208 }
209 };
210
211 /**
212 * Get group active state
213 *
214 * @return {boolean} Active state
215 */
216 mw.rcfilters.dm.FilterGroup.prototype.isActive = function () {
217 return this.active;
218 };
219
220 /**
221 * Get group hidden state
222 *
223 * @return {boolean} Hidden state
224 */
225 mw.rcfilters.dm.FilterGroup.prototype.isHidden = function () {
226 return this.hidden;
227 };
228
229 /**
230 * Get group allow arbitrary state
231 *
232 * @return {boolean} Group allows an arbitrary value from the URL
233 */
234 mw.rcfilters.dm.FilterGroup.prototype.isAllowArbitrary = function () {
235 return this.allowArbitrary;
236 };
237
238 /**
239 * Get group name
240 *
241 * @return {string} Group name
242 */
243 mw.rcfilters.dm.FilterGroup.prototype.getName = function () {
244 return this.name;
245 };
246
247 /**
248 * Get the default param state of this group
249 *
250 * @return {Object} Default param state
251 */
252 mw.rcfilters.dm.FilterGroup.prototype.getDefaultParams = function () {
253 return this.defaultParams;
254 };
255
256 /**
257 * This is for a single_option and string_options group types
258 * it returns the value of the default
259 *
260 * @return {string} Value of the default
261 */
262 mw.rcfilters.dm.FilterGroup.prototype.getDefaulParamValue = function () {
263 return this.defaultParams[ this.getName() ];
264 };
265 /**
266 * Get the messags defining the 'whats this' popup for this group
267 *
268 * @return {Object} What's this messages
269 */
270 mw.rcfilters.dm.FilterGroup.prototype.getWhatsThis = function () {
271 return this.whatsThis;
272 };
273
274 /**
275 * Check whether this group has a 'what's this' message
276 *
277 * @return {boolean} This group has a what's this message
278 */
279 mw.rcfilters.dm.FilterGroup.prototype.hasWhatsThis = function () {
280 return !!this.whatsThis.body;
281 };
282
283 /**
284 * Get the conflicts associated with the entire group.
285 * Conflict object is set up by filter name keys and conflict
286 * definition. For example:
287 * [
288 * {
289 * filterName: {
290 * filter: filterName,
291 * group: group1
292 * }
293 * },
294 * {
295 * filterName2: {
296 * filter: filterName2,
297 * group: group2
298 * }
299 * }
300 * ]
301 * @return {Object} Conflict definition
302 */
303 mw.rcfilters.dm.FilterGroup.prototype.getConflicts = function () {
304 return this.conflicts;
305 };
306
307 /**
308 * Set conflicts for this group. See #getConflicts for the expected
309 * structure of the definition.
310 *
311 * @param {Object} conflicts Conflicts for this group
312 */
313 mw.rcfilters.dm.FilterGroup.prototype.setConflicts = function ( conflicts ) {
314 this.conflicts = conflicts;
315 };
316
317 /**
318 * Set conflicts for each filter item in the group based on the
319 * given conflict map
320 *
321 * @param {Object} conflicts Object representing the conflict map,
322 * keyed by the item name, where its value is an object for all its conflicts
323 */
324 mw.rcfilters.dm.FilterGroup.prototype.setFilterConflicts = function ( conflicts ) {
325 this.getItems().forEach( function ( filterItem ) {
326 if ( conflicts[ filterItem.getName() ] ) {
327 filterItem.setConflicts( conflicts[ filterItem.getName() ] );
328 }
329 } );
330 };
331
332 /**
333 * Check whether this item has a potential conflict with the given item
334 *
335 * This checks whether the given item is in the list of conflicts of
336 * the current item, but makes no judgment about whether the conflict
337 * is currently at play (either one of the items may not be selected)
338 *
339 * @param {mw.rcfilters.dm.FilterItem} filterItem Filter item
340 * @return {boolean} This item has a conflict with the given item
341 */
342 mw.rcfilters.dm.FilterGroup.prototype.existsInConflicts = function ( filterItem ) {
343 return Object.prototype.hasOwnProperty.call( this.getConflicts(), filterItem.getName() );
344 };
345
346 /**
347 * Check whether there are any items selected
348 *
349 * @return {boolean} Any items in the group are selected
350 */
351 mw.rcfilters.dm.FilterGroup.prototype.areAnySelected = function () {
352 return this.getItems().some( function ( filterItem ) {
353 return filterItem.isSelected();
354 } );
355 };
356
357 /**
358 * Check whether all items selected
359 *
360 * @return {boolean} All items are selected
361 */
362 mw.rcfilters.dm.FilterGroup.prototype.areAllSelected = function () {
363 var selected = [],
364 unselected = [];
365
366 this.getItems().forEach( function ( filterItem ) {
367 if ( filterItem.isSelected() ) {
368 selected.push( filterItem );
369 } else {
370 unselected.push( filterItem );
371 }
372 } );
373
374 if ( unselected.length === 0 ) {
375 return true;
376 }
377
378 // check if every unselected is a subset of a selected
379 return unselected.every( function ( unselectedFilterItem ) {
380 return selected.some( function ( selectedFilterItem ) {
381 return selectedFilterItem.existsInSubset( unselectedFilterItem.getName() );
382 } );
383 } );
384 };
385
386 /**
387 * Get all selected items in this group
388 *
389 * @param {mw.rcfilters.dm.FilterItem} [excludeItem] Item to exclude from the list
390 * @return {mw.rcfilters.dm.FilterItem[]} Selected items
391 */
392 mw.rcfilters.dm.FilterGroup.prototype.getSelectedItems = function ( excludeItem ) {
393 var excludeName = ( excludeItem && excludeItem.getName() ) || '';
394
395 return this.getItems().filter( function ( item ) {
396 return item.getName() !== excludeName && item.isSelected();
397 } );
398 };
399
400 /**
401 * Check whether all selected items are in conflict with the given item
402 *
403 * @param {mw.rcfilters.dm.FilterItem} filterItem Filter item to test
404 * @return {boolean} All selected items are in conflict with this item
405 */
406 mw.rcfilters.dm.FilterGroup.prototype.areAllSelectedInConflictWith = function ( filterItem ) {
407 var selectedItems = this.getSelectedItems( filterItem );
408
409 return selectedItems.length > 0 &&
410 (
411 // The group as a whole is in conflict with this item
412 this.existsInConflicts( filterItem ) ||
413 // All selected items are in conflict individually
414 selectedItems.every( function ( selectedFilter ) {
415 return selectedFilter.existsInConflicts( filterItem );
416 } )
417 );
418 };
419
420 /**
421 * Check whether any of the selected items are in conflict with the given item
422 *
423 * @param {mw.rcfilters.dm.FilterItem} filterItem Filter item to test
424 * @return {boolean} Any of the selected items are in conflict with this item
425 */
426 mw.rcfilters.dm.FilterGroup.prototype.areAnySelectedInConflictWith = function ( filterItem ) {
427 var selectedItems = this.getSelectedItems( filterItem );
428
429 return selectedItems.length > 0 && (
430 // The group as a whole is in conflict with this item
431 this.existsInConflicts( filterItem ) ||
432 // Any selected items are in conflict individually
433 selectedItems.some( function ( selectedFilter ) {
434 return selectedFilter.existsInConflicts( filterItem );
435 } )
436 );
437 };
438
439 /**
440 * Get the parameter representation from this group
441 *
442 * @param {Object} [filterRepresentation] An object defining the state
443 * of the filters in this group, keyed by their name and current selected
444 * state value.
445 * @return {Object} Parameter representation
446 */
447 mw.rcfilters.dm.FilterGroup.prototype.getParamRepresentation = function ( filterRepresentation ) {
448 var values,
449 areAnySelected = false,
450 buildFromCurrentState = !filterRepresentation,
451 result = {},
452 model = this,
453 filterParamNames = {},
454 getSelectedParameter = function ( filters ) {
455 var item,
456 selected = [];
457
458 // Find if any are selected
459 $.each( filters, function ( name, value ) {
460 if ( value ) {
461 selected.push( name );
462 }
463 } );
464
465 item = model.getItemByName( selected[ 0 ] );
466 return ( item && item.getParamName() ) || '';
467 };
468
469 filterRepresentation = filterRepresentation || {};
470
471 // Create or complete the filterRepresentation definition
472 this.getItems().forEach( function ( item ) {
473 // Map filter names to their parameter names
474 filterParamNames[ item.getName() ] = item.getParamName();
475
476 if ( buildFromCurrentState ) {
477 // This means we have not been given a filter representation
478 // so we are building one based on current state
479 filterRepresentation[ item.getName() ] = item.isSelected();
480 } else if ( !filterRepresentation[ item.getName() ] ) {
481 // We are given a filter representation, but we have to make
482 // sure that we fill in the missing filters if there are any
483 // we will assume they are all falsey
484 filterRepresentation[ item.getName() ] = false;
485 }
486
487 if ( filterRepresentation[ item.getName() ] ) {
488 areAnySelected = true;
489 }
490 } );
491
492 // Build result
493 if ( this.getType() === 'send_unselected_if_any' ) {
494 // First, check if any of the items are selected at all.
495 // If none is selected, we're treating it as if they are
496 // all false
497
498 // Go over the items and define the correct values
499 $.each( filterRepresentation, function ( name, value ) {
500 // We must store all parameter values as strings '0' or '1'
501 result[ filterParamNames[ name ] ] = areAnySelected ?
502 String( Number( !value ) ) :
503 '0';
504 } );
505 } else if ( this.getType() === 'string_options' ) {
506 values = [];
507
508 $.each( filterRepresentation, function ( name, value ) {
509 // Collect values
510 if ( value ) {
511 values.push( filterParamNames[ name ] );
512 }
513 } );
514
515 result[ this.getName() ] = ( values.length === Object.keys( filterRepresentation ).length ) ?
516 'all' : values.join( this.getSeparator() );
517 } else if ( this.getType() === 'single_option' ) {
518 result[ this.getName() ] = getSelectedParameter( filterRepresentation );
519 }
520
521 return result;
522 };
523
524 /**
525 * Get the filter representation this group would provide
526 * based on given parameter states.
527 *
528 * @param {Object|string} [paramRepresentation] An object defining a parameter
529 * state to translate the filter state from. If not given, an object
530 * representing all filters as falsey is returned; same as if the parameter
531 * given were an empty object, or had some of the filters missing.
532 * @return {Object} Filter representation
533 */
534 mw.rcfilters.dm.FilterGroup.prototype.getFilterRepresentation = function ( paramRepresentation ) {
535 var areAnySelected, paramValues, defaultValue, item,
536 oneWasSelected = false,
537 model = this,
538 paramToFilterMap = {},
539 result = {};
540
541 if ( this.getType() === 'send_unselected_if_any' ) {
542 paramRepresentation = paramRepresentation || {};
543 // Expand param representation to include all filters in the group
544 this.getItems().forEach( function ( filterItem ) {
545 var paramName = filterItem.getParamName();
546
547 paramRepresentation[ paramName ] = paramRepresentation[ paramName ] || '0';
548 paramToFilterMap[ paramName ] = filterItem;
549
550 if ( Number( paramRepresentation[ filterItem.getParamName() ] ) ) {
551 areAnySelected = true;
552 }
553 } );
554
555 $.each( paramRepresentation, function ( paramName, paramValue ) {
556 var filterItem = paramToFilterMap[ paramName ];
557
558 // Flip the definition between the parameter
559 // state and the filter state
560 // This is what the 'toggleSelected' value of the filter is
561 result[ filterItem.getName() ] = areAnySelected ?
562 !Number( paramValue ) :
563 // Otherwise, there are no selected items in the
564 // group, which means the state is false
565 false;
566 } );
567 } else if ( this.getType() === 'string_options' ) {
568 paramRepresentation = paramRepresentation || '';
569
570 // Normalize the given parameter values
571 paramValues = mw.rcfilters.utils.normalizeParamOptions(
572 // Given
573 paramRepresentation.split(
574 this.getSeparator()
575 ),
576 // Allowed values
577 this.getItems().map( function ( filterItem ) {
578 return filterItem.getParamName();
579 } )
580 );
581 // Translate the parameter values into a filter selection state
582 this.getItems().forEach( function ( filterItem ) {
583 // All true (either because all values are written or the term 'all' is written)
584 // is the same as all filters set to true
585 result[ filterItem.getName() ] = (
586 // If it is the word 'all'
587 paramValues.length === 1 && paramValues[ 0 ] === 'all' ||
588 // All values are written
589 paramValues.length === model.getItemCount()
590 ) ?
591 true :
592 // Otherwise, the filter is selected only if it appears in the parameter values
593 paramValues.indexOf( filterItem.getParamName() ) > -1;
594 } );
595 } else if ( this.getType() === 'single_option' ) {
596 // There is parameter that fits a single filter and if not, get the default
597 this.getItems().forEach( function ( filterItem ) {
598 result[ filterItem.getName() ] = filterItem.getParamName() === paramRepresentation;
599 oneWasSelected = oneWasSelected || filterItem.getParamName() === paramRepresentation;
600 } );
601 }
602
603 // Go over result and make sure all filters are represented.
604 // If any filters are missing, they will get a falsey value
605 this.getItems().forEach( function ( filterItem ) {
606 result[ filterItem.getName() ] = !!result[ filterItem.getName() ];
607 oneWasSelected = oneWasSelected || !!result[ filterItem.getName() ];
608 } );
609
610 // Make sure that at least one option is selected in
611 // single_option groups, no matter what path was taken
612 // If none was selected by the given definition, then
613 // we need to select the one in the base state -- either
614 // the default given, or the first item
615 if (
616 this.getType() === 'single_option' &&
617 !oneWasSelected
618 ) {
619 defaultValue = this.getDefaultParams();
620 item = this.getItemByParamName( defaultValue[ this.getName() ] );
621 result[ item.getName() ] = true;
622 }
623
624 return result;
625 };
626
627 /**
628 * Get item by its filter name
629 *
630 * @param {string} filterName Filter name
631 * @return {mw.rcfilters.dm.FilterItem} Filter item
632 */
633 mw.rcfilters.dm.FilterGroup.prototype.getItemByName = function ( filterName ) {
634 return this.getItems().filter( function ( item ) {
635 return item.getName() === filterName;
636 } )[ 0 ];
637 };
638
639 /**
640 * Select an item by its parameter name
641 *
642 * @param {string} paramName Filter parameter name
643 */
644 mw.rcfilters.dm.FilterGroup.prototype.selectItemByParamName = function ( paramName ) {
645 this.getItems().forEach( function ( item ) {
646 item.toggleSelected( item.getParamName() === paramName );
647 } );
648 };
649
650 /**
651 * Get item by its parameter name
652 *
653 * @param {string} paramName Parameter name
654 * @return {mw.rcfilters.dm.FilterItem} Filter item
655 */
656 mw.rcfilters.dm.FilterGroup.prototype.getItemByParamName = function ( paramName ) {
657 return this.getItems().filter( function ( item ) {
658 return item.getParamName() === paramName;
659 } )[ 0 ];
660 };
661
662 /**
663 * Get group type
664 *
665 * @return {string} Group type
666 */
667 mw.rcfilters.dm.FilterGroup.prototype.getType = function () {
668 return this.type;
669 };
670
671 /**
672 * Get display group
673 *
674 * @return {string} Display group
675 */
676 mw.rcfilters.dm.FilterGroup.prototype.getView = function () {
677 return this.view;
678 };
679
680 /**
681 * Get the prefix used for the filter names inside this group.
682 *
683 * @param {string} [name] Filter name to prefix
684 * @return {string} Group prefix
685 */
686 mw.rcfilters.dm.FilterGroup.prototype.getNamePrefix = function () {
687 return this.getName() + '__';
688 };
689
690 /**
691 * Get a filter name with the prefix used for the filter names inside this group.
692 *
693 * @param {string} name Filter name to prefix
694 * @return {string} Group prefix
695 */
696 mw.rcfilters.dm.FilterGroup.prototype.getPrefixedName = function ( name ) {
697 return this.getNamePrefix() + name;
698 };
699
700 /**
701 * Get group's title
702 *
703 * @return {string} Title
704 */
705 mw.rcfilters.dm.FilterGroup.prototype.getTitle = function () {
706 return this.title;
707 };
708
709 /**
710 * Get group's values separator
711 *
712 * @return {string} Values separator
713 */
714 mw.rcfilters.dm.FilterGroup.prototype.getSeparator = function () {
715 return this.separator;
716 };
717
718 /**
719 * Check whether the group is defined as full coverage
720 *
721 * @return {boolean} Group is full coverage
722 */
723 mw.rcfilters.dm.FilterGroup.prototype.isFullCoverage = function () {
724 return this.fullCoverage;
725 };
726 }( mediaWiki ) );