RCFilters: Allow non-sticky filters to be excluded from saved queries
[lhc/web/wiklou.git] / resources / src / mediawiki.rcfilters / mw.rcfilters.Controller.js
1 ( function ( mw, $ ) {
2 /* eslint no-underscore-dangle: "off" */
3 /**
4 * Controller for the filters in Recent Changes
5 * @class
6 *
7 * @constructor
8 * @param {mw.rcfilters.dm.FiltersViewModel} filtersModel Filters view model
9 * @param {mw.rcfilters.dm.ChangesListViewModel} changesListModel Changes list view model
10 * @param {mw.rcfilters.dm.SavedQueriesModel} savedQueriesModel Saved queries model
11 */
12 mw.rcfilters.Controller = function MwRcfiltersController( filtersModel, changesListModel, savedQueriesModel ) {
13 this.filtersModel = filtersModel;
14 this.changesListModel = changesListModel;
15 this.savedQueriesModel = savedQueriesModel;
16 this.requestCounter = {};
17 this.baseFilterState = {};
18 this.uriProcessor = null;
19 this.initializing = false;
20
21 this.prevLoggedItems = [];
22
23 this.FILTER_CHANGE = 'filterChange';
24 this.SHOW_NEW_CHANGES = 'showNewChanges';
25 this.LIVE_UPDATE = 'liveUpdate';
26 };
27
28 /* Initialization */
29 OO.initClass( mw.rcfilters.Controller );
30
31 /**
32 * Initialize the filter and parameter states
33 *
34 * @param {Array} filterStructure Filter definition and structure for the model
35 * @param {Object} [namespaceStructure] Namespace definition
36 * @param {Object} [tagList] Tag definition
37 */
38 mw.rcfilters.Controller.prototype.initialize = function ( filterStructure, namespaceStructure, tagList ) {
39 var parsedSavedQueries, limitDefault,
40 displayConfig = mw.config.get( 'StructuredChangeFiltersDisplayConfig' ),
41 controller = this,
42 views = {},
43 items = [],
44 uri = new mw.Uri(),
45 $changesList = $( '.mw-changeslist' ).first().contents();
46
47 // Prepare views
48 if ( namespaceStructure ) {
49 items = [];
50 $.each( namespaceStructure, function ( namespaceID, label ) {
51 // Build and clean up the individual namespace items definition
52 items.push( {
53 name: namespaceID,
54 label: label || mw.msg( 'blanknamespace' ),
55 description: '',
56 identifiers: [
57 ( namespaceID < 0 || namespaceID % 2 === 0 ) ?
58 'subject' : 'talk'
59 ],
60 cssClass: 'mw-changeslist-ns-' + namespaceID
61 } );
62 } );
63
64 views.namespaces = {
65 title: mw.msg( 'namespaces' ),
66 trigger: ':',
67 groups: [ {
68 // Group definition (single group)
69 name: 'namespace', // parameter name is singular
70 type: 'string_options',
71 title: mw.msg( 'namespaces' ),
72 labelPrefixKey: { 'default': 'rcfilters-tag-prefix-namespace', inverted: 'rcfilters-tag-prefix-namespace-inverted' },
73 separator: ';',
74 fullCoverage: true,
75 filters: items
76 } ]
77 };
78 }
79 if ( tagList ) {
80 views.tags = {
81 title: mw.msg( 'rcfilters-view-tags' ),
82 trigger: '#',
83 groups: [ {
84 // Group definition (single group)
85 name: 'tagfilter', // Parameter name
86 type: 'string_options',
87 title: 'rcfilters-view-tags', // Message key
88 labelPrefixKey: 'rcfilters-tag-prefix-tags',
89 separator: '|',
90 fullCoverage: false,
91 filters: tagList
92 } ]
93 };
94 }
95
96 // Convert the default from the old preference
97 // since the limit preference actually affects more
98 // than just the RecentChanges page
99 limitDefault = Number( mw.user.options.get( 'rclimit', '50' ) );
100
101 // Add parameter range operations
102 views.range = {
103 groups: [
104 {
105 name: 'limit',
106 type: 'single_option',
107 title: '', // Because it's a hidden group, this title actually appears nowhere
108 hidden: true,
109 allowArbitrary: true,
110 validate: $.isNumeric,
111 range: {
112 min: 0, // The server normalizes negative numbers to 0 results
113 max: 1000
114 },
115 sortFunc: function ( a, b ) { return Number( a.name ) - Number( b.name ); },
116 'default': String( limitDefault ),
117 // Temporarily making this not sticky until we resolve the problem
118 // with the misleading preference. Note that if this is to be permanent
119 // we should remove all sticky behavior methods completely
120 // See T172156
121 // isSticky: true,
122 excludedFromSavedQueries: true,
123 filters: displayConfig.limitArray.map( function ( num ) {
124 return controller._createFilterDataFromNumber( num, num );
125 } )
126 },
127 {
128 name: 'days',
129 type: 'single_option',
130 title: '', // Because it's a hidden group, this title actually appears nowhere
131 hidden: true,
132 allowArbitrary: true,
133 validate: $.isNumeric,
134 range: {
135 min: 0,
136 max: displayConfig.maxDays
137 },
138 sortFunc: function ( a, b ) { return Number( a.name ) - Number( b.name ); },
139 numToLabelFunc: function ( i ) {
140 return Number( i ) < 1 ?
141 ( Number( i ) * 24 ).toFixed( 2 ) :
142 Number( i );
143 },
144 'default': mw.user.options.get( 'rcdays', '30' ),
145 // Temporarily making this not sticky while limit is not sticky, see above
146 // isSticky: true,
147 excludedFromSavedQueries: true,
148 filters: [
149 // Hours (1, 2, 6, 12)
150 0.04166, 0.0833, 0.25, 0.5
151 // Days
152 ].concat( displayConfig.daysArray )
153 .map( function ( num ) {
154 return controller._createFilterDataFromNumber(
155 num,
156 // Convert fractions of days to number of hours for the labels
157 num < 1 ? Math.round( num * 24 ) : num
158 );
159 } )
160 }
161 ]
162 };
163
164 views.display = {
165 groups: [
166 {
167 name: 'display',
168 type: 'boolean',
169 title: '', // Because it's a hidden group, this title actually appears nowhere
170 hidden: true,
171 isSticky: true,
172 filters: [
173 {
174 name: 'enhanced',
175 'default': String( mw.user.options.get( 'usenewrc', 0 ) )
176 }
177 ]
178 }
179 ]
180 };
181
182 // Before we do anything, we need to see if we require additional items in the
183 // groups that have 'AllowArbitrary'. For the moment, those are only single_option
184 // groups; if we ever expand it, this might need further generalization:
185 $.each( views, function ( viewName, viewData ) {
186 viewData.groups.forEach( function ( groupData ) {
187 var extraValues = [];
188 if ( groupData.allowArbitrary ) {
189 // If the value in the URI isn't in the group, add it
190 if ( uri.query[ groupData.name ] !== undefined ) {
191 extraValues.push( uri.query[ groupData.name ] );
192 }
193 // If the default value isn't in the group, add it
194 if ( groupData.default !== undefined ) {
195 extraValues.push( String( groupData.default ) );
196 }
197 controller.addNumberValuesToGroup( groupData, extraValues );
198 }
199 } );
200 } );
201
202 // Initialize the model
203 this.filtersModel.initializeFilters( filterStructure, views );
204
205 this._buildBaseFilterState();
206
207 this.uriProcessor = new mw.rcfilters.UriProcessor(
208 this.filtersModel
209 );
210
211 try {
212 parsedSavedQueries = JSON.parse( mw.user.options.get( 'rcfilters-saved-queries' ) || '{}' );
213 } catch ( err ) {
214 parsedSavedQueries = {};
215 }
216
217 // The queries are saved in a minimized state, so we need
218 // to send over the base state so the saved queries model
219 // can normalize them per each query item
220 this.savedQueriesModel.initialize(
221 parsedSavedQueries,
222 this._getBaseFilterState(),
223 // This is for backwards compatibility - delete all excluded filter states
224 Object.keys( this.filtersModel.getExcludedFiltersState() )
225 );
226
227 // Check whether we need to load defaults.
228 // We do this by checking whether the current URI query
229 // contains any parameters recognized by the system.
230 // If it does, we load the given state.
231 // If it doesn't, we have no values at all, and we assume
232 // the user loads the base-page and we load defaults.
233 // Defaults should only be applied on load (if necessary)
234 // or on request
235 this.initializing = true;
236 if (
237 this.savedQueriesModel.getDefault() &&
238 !this.uriProcessor.doesQueryContainRecognizedParams( uri.query )
239 ) {
240 // We have defaults from a saved query.
241 // We will load them straight-forward (as if
242 // they were clicked in the menu) so we trigger
243 // a full ajax request and change of URL
244 this.applySavedQuery( this.savedQueriesModel.getDefault() );
245 } else {
246 // There are either recognized parameters in the URL
247 // or there are none, but there is also no default
248 // saved query (so defaults are from the backend)
249 // We want to update the state but not fetch results
250 // again
251 this.updateStateFromUrl( false );
252
253 // Update the changes list with the existing data
254 // so it gets processed
255 this.changesListModel.update(
256 $changesList.length ? $changesList : 'NO_RESULTS',
257 $( 'fieldset.rcoptions' ).first(),
258 true // We're using existing DOM elements
259 );
260 }
261
262 this.initializing = false;
263 this.switchView( 'default' );
264
265 this._scheduleLiveUpdate();
266 };
267
268 /**
269 * Create filter data from a number, for the filters that are numerical value
270 *
271 * @param {Number} num Number
272 * @param {Number} numForDisplay Number for the label
273 * @return {Object} Filter data
274 */
275 mw.rcfilters.Controller.prototype._createFilterDataFromNumber = function ( num, numForDisplay ) {
276 return {
277 name: String( num ),
278 label: mw.language.convertNumber( numForDisplay )
279 };
280 };
281
282 /**
283 * Add an arbitrary values to groups that allow arbitrary values
284 *
285 * @param {Object} groupData Group data
286 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
287 */
288 mw.rcfilters.Controller.prototype.addNumberValuesToGroup = function ( groupData, arbitraryValues ) {
289 var controller = this,
290 normalizeWithinRange = function ( range, val ) {
291 if ( val < range.min ) {
292 return range.min; // Min
293 } else if ( val >= range.max ) {
294 return range.max; // Max
295 }
296 return val;
297 };
298
299 arbitraryValues = Array.isArray( arbitraryValues ) ? arbitraryValues : [ arbitraryValues ];
300
301 // Normalize the arbitrary values and the default value for a range
302 if ( groupData.range ) {
303 arbitraryValues = arbitraryValues.map( function ( val ) {
304 return normalizeWithinRange( groupData.range, val );
305 } );
306
307 // Normalize the default, since that's user defined
308 if ( groupData.default !== undefined ) {
309 groupData.default = String( normalizeWithinRange( groupData.range, groupData.default ) );
310 }
311 }
312
313 // This is only true for single_option group
314 // We assume these are the only groups that will allow for
315 // arbitrary, since it doesn't make any sense for the other
316 // groups.
317 arbitraryValues.forEach( function ( val ) {
318 if (
319 // If the group allows for arbitrary data
320 groupData.allowArbitrary &&
321 // and it is single_option (or string_options, but we
322 // don't have cases of those yet, nor do we plan to)
323 groupData.type === 'single_option' &&
324 // and, if there is a validate method and it passes on
325 // the data
326 ( !groupData.validate || groupData.validate( val ) ) &&
327 // but if that value isn't already in the definition
328 groupData.filters
329 .map( function ( filterData ) {
330 return String( filterData.name );
331 } )
332 .indexOf( String( val ) ) === -1
333 ) {
334 // Add the filter information
335 groupData.filters.push( controller._createFilterDataFromNumber(
336 val,
337 groupData.numToLabelFunc ?
338 groupData.numToLabelFunc( val ) :
339 val
340 ) );
341
342 // If there's a sort function set up, re-sort the values
343 if ( groupData.sortFunc ) {
344 groupData.filters.sort( groupData.sortFunc );
345 }
346 }
347 } );
348 };
349
350 /**
351 * Switch the view of the filters model
352 *
353 * @param {string} view Requested view
354 */
355 mw.rcfilters.Controller.prototype.switchView = function ( view ) {
356 this.filtersModel.switchView( view );
357 };
358
359 /**
360 * Reset to default filters
361 */
362 mw.rcfilters.Controller.prototype.resetToDefaults = function () {
363 this.uriProcessor.updateModelBasedOnQuery( this._getDefaultParams() );
364
365 this.updateChangesList();
366 };
367
368 /**
369 * Empty all selected filters
370 */
371 mw.rcfilters.Controller.prototype.emptyFilters = function () {
372 var highlightedFilterNames = this.filtersModel
373 .getHighlightedItems()
374 .map( function ( filterItem ) { return { name: filterItem.getName() }; } );
375
376 this.filtersModel.emptyAllFilters();
377 this.filtersModel.clearAllHighlightColors();
378 // Check all filter interactions
379 this.filtersModel.reassessFilterInteractions();
380
381 this.updateChangesList();
382
383 if ( highlightedFilterNames ) {
384 this._trackHighlight( 'clearAll', highlightedFilterNames );
385 }
386 };
387
388 /**
389 * Update the selected state of a filter
390 *
391 * @param {string} filterName Filter name
392 * @param {boolean} [isSelected] Filter selected state
393 */
394 mw.rcfilters.Controller.prototype.toggleFilterSelect = function ( filterName, isSelected ) {
395 var filterItem = this.filtersModel.getItemByName( filterName );
396
397 if ( !filterItem ) {
398 // If no filter was found, break
399 return;
400 }
401
402 isSelected = isSelected === undefined ? !filterItem.isSelected() : isSelected;
403
404 if ( filterItem.isSelected() !== isSelected ) {
405 this.filtersModel.toggleFilterSelected( filterName, isSelected );
406
407 this.updateChangesList();
408
409 // Check filter interactions
410 this.filtersModel.reassessFilterInteractions( filterItem );
411 }
412 };
413
414 /**
415 * Clear both highlight and selection of a filter
416 *
417 * @param {string} filterName Name of the filter item
418 */
419 mw.rcfilters.Controller.prototype.clearFilter = function ( filterName ) {
420 var filterItem = this.filtersModel.getItemByName( filterName ),
421 isHighlighted = filterItem.isHighlighted();
422
423 if ( filterItem.isSelected() || isHighlighted ) {
424 this.filtersModel.clearHighlightColor( filterName );
425 this.filtersModel.toggleFilterSelected( filterName, false );
426 this.updateChangesList();
427 this.filtersModel.reassessFilterInteractions( filterItem );
428
429 // Log filter grouping
430 this.trackFilterGroupings( 'removefilter' );
431 }
432
433 if ( isHighlighted ) {
434 this._trackHighlight( 'clear', filterName );
435 }
436 };
437
438 /**
439 * Toggle the highlight feature on and off
440 */
441 mw.rcfilters.Controller.prototype.toggleHighlight = function () {
442 this.filtersModel.toggleHighlight();
443 this._updateURL();
444
445 if ( this.filtersModel.isHighlightEnabled() ) {
446 mw.hook( 'RcFilters.highlight.enable' ).fire();
447 }
448 };
449
450 /**
451 * Toggle the namespaces inverted feature on and off
452 */
453 mw.rcfilters.Controller.prototype.toggleInvertedNamespaces = function () {
454 this.filtersModel.toggleInvertedNamespaces();
455
456 if (
457 this.filtersModel.getFiltersByView( 'namespaces' )
458 .filter( function ( filterItem ) {
459 return filterItem.isSelected();
460 } )
461 .length
462 ) {
463 // Only re-fetch results if there are namespace items that are actually selected
464 this.updateChangesList();
465 }
466 };
467
468 /**
469 * Set the highlight color for a filter item
470 *
471 * @param {string} filterName Name of the filter item
472 * @param {string} color Selected color
473 */
474 mw.rcfilters.Controller.prototype.setHighlightColor = function ( filterName, color ) {
475 this.filtersModel.setHighlightColor( filterName, color );
476 this._updateURL();
477 this._trackHighlight( 'set', { name: filterName, color: color } );
478 };
479
480 /**
481 * Clear highlight for a filter item
482 *
483 * @param {string} filterName Name of the filter item
484 */
485 mw.rcfilters.Controller.prototype.clearHighlightColor = function ( filterName ) {
486 this.filtersModel.clearHighlightColor( filterName );
487 this._updateURL();
488 this._trackHighlight( 'clear', filterName );
489 };
490
491 /**
492 * Enable or disable live updates.
493 * @param {boolean} enable True to enable, false to disable
494 */
495 mw.rcfilters.Controller.prototype.toggleLiveUpdate = function ( enable ) {
496 this.changesListModel.toggleLiveUpdate( enable );
497 if ( this.changesListModel.getLiveUpdate() && this.changesListModel.getNewChangesExist() ) {
498 this.updateChangesList( null, this.LIVE_UPDATE );
499 }
500 };
501
502 /**
503 * Set a timeout for the next live update.
504 * @private
505 */
506 mw.rcfilters.Controller.prototype._scheduleLiveUpdate = function () {
507 setTimeout( this._doLiveUpdate.bind( this ), 3000 );
508 };
509
510 /**
511 * Perform a live update.
512 * @private
513 */
514 mw.rcfilters.Controller.prototype._doLiveUpdate = function () {
515 if ( !this._shouldCheckForNewChanges() ) {
516 // skip this turn and check back later
517 this._scheduleLiveUpdate();
518 return;
519 }
520
521 this._checkForNewChanges()
522 .then( function ( data ) {
523 if ( !this._shouldCheckForNewChanges() ) {
524 // by the time the response is received,
525 // it may not be appropriate anymore
526 return;
527 }
528
529 if ( data.changes !== 'NO_RESULTS' ) {
530 if ( this.changesListModel.getLiveUpdate() ) {
531 return this.updateChangesList( null, this.LIVE_UPDATE );
532 } else {
533 this.changesListModel.setNewChangesExist( true );
534 }
535 }
536 }.bind( this ) )
537 .always( this._scheduleLiveUpdate.bind( this ) );
538 };
539
540 /**
541 * @return {boolean} It's appropriate to check for new changes now
542 * @private
543 */
544 mw.rcfilters.Controller.prototype._shouldCheckForNewChanges = function () {
545 var liveUpdateFeatureFlag = mw.config.get( 'wgStructuredChangeFiltersEnableLiveUpdate' ) ||
546 new mw.Uri().query.liveupdate;
547
548 return !document.hidden &&
549 !this.filtersModel.hasConflict() &&
550 !this.changesListModel.getNewChangesExist() &&
551 !this.updatingChangesList &&
552 liveUpdateFeatureFlag;
553 };
554
555 /**
556 * Check if new changes, newer than those currently shown, are available
557 *
558 * @return {jQuery.Promise} Promise object that resolves after trying
559 * to fetch 1 change newer than the last known 'from' parameter value
560 *
561 * @private
562 */
563 mw.rcfilters.Controller.prototype._checkForNewChanges = function () {
564 return this._fetchChangesList(
565 'liveUpdate',
566 {
567 limit: 1,
568 from: this.changesListModel.getNextFrom()
569 }
570 );
571 };
572
573 /**
574 * Show the new changes
575 *
576 * @return {jQuery.Promise} Promise object that resolves after
577 * fetching and showing the new changes
578 */
579 mw.rcfilters.Controller.prototype.showNewChanges = function () {
580 return this.updateChangesList( null, this.SHOW_NEW_CHANGES );
581 };
582
583 /**
584 * Save the current model state as a saved query
585 *
586 * @param {string} [label] Label of the saved query
587 * @param {boolean} [setAsDefault=false] This query should be set as the default
588 */
589 mw.rcfilters.Controller.prototype.saveCurrentQuery = function ( label, setAsDefault ) {
590 var queryID,
591 highlightedItems = {},
592 highlightEnabled = this.filtersModel.isHighlightEnabled(),
593 selectedState = this.filtersModel.getSelectedState();
594
595 // Prepare highlights
596 this.filtersModel.getHighlightedItems().forEach( function ( item ) {
597 highlightedItems[ item.getName() ] = highlightEnabled ?
598 item.getHighlightColor() : null;
599 } );
600 // These are filter states; highlight is stored as boolean
601 highlightedItems.highlight = this.filtersModel.isHighlightEnabled();
602
603 // Delete all excluded filters
604 this._deleteExcludedValuesFromFilterState( selectedState );
605
606 // Add item
607 queryID = this.savedQueriesModel.addNewQuery(
608 label || mw.msg( 'rcfilters-savedqueries-defaultlabel' ),
609 {
610 filters: selectedState,
611 highlights: highlightedItems,
612 invert: this.filtersModel.areNamespacesInverted()
613 }
614 );
615
616 if ( setAsDefault ) {
617 this.savedQueriesModel.setDefault( queryID );
618 }
619
620 // Save item
621 this._saveSavedQueries();
622 };
623
624 /**
625 * Remove a saved query
626 *
627 * @param {string} queryID Query id
628 */
629 mw.rcfilters.Controller.prototype.removeSavedQuery = function ( queryID ) {
630 this.savedQueriesModel.removeQuery( queryID );
631
632 this._saveSavedQueries();
633 };
634
635 /**
636 * Rename a saved query
637 *
638 * @param {string} queryID Query id
639 * @param {string} newLabel New label for the query
640 */
641 mw.rcfilters.Controller.prototype.renameSavedQuery = function ( queryID, newLabel ) {
642 var queryItem = this.savedQueriesModel.getItemByID( queryID );
643
644 if ( queryItem ) {
645 queryItem.updateLabel( newLabel );
646 }
647 this._saveSavedQueries();
648 };
649
650 /**
651 * Set a saved query as default
652 *
653 * @param {string} queryID Query Id. If null is given, default
654 * query is reset.
655 */
656 mw.rcfilters.Controller.prototype.setDefaultSavedQuery = function ( queryID ) {
657 this.savedQueriesModel.setDefault( queryID );
658 this._saveSavedQueries();
659 };
660
661 /**
662 * Load a saved query
663 *
664 * @param {string} queryID Query id
665 */
666 mw.rcfilters.Controller.prototype.applySavedQuery = function ( queryID ) {
667 var data, highlights,
668 queryItem = this.savedQueriesModel.getItemByID( queryID ),
669 currentMatchingQuery = this.findQueryMatchingCurrentState();
670
671 if (
672 queryItem &&
673 (
674 // If there's already a query, don't reload it
675 // if it's the same as the one that already exists
676 !currentMatchingQuery ||
677 currentMatchingQuery.getID() !== queryItem.getID()
678 )
679 ) {
680 data = queryItem.getData();
681 highlights = data.highlights;
682
683 // Backwards compatibility; initial version mispelled 'highlight' with 'highlights'
684 highlights.highlight = highlights.highlights || highlights.highlight;
685
686 // Update model state from filters
687 this.filtersModel.toggleFiltersSelected(
688 // Merge filters with excluded values
689 $.extend( true, {}, data.filters, this.filtersModel.getExcludedFiltersState() )
690 );
691
692 // Update namespace inverted property
693 this.filtersModel.toggleInvertedNamespaces( !!Number( data.invert ) );
694
695 // Update highlight state
696 this.filtersModel.toggleHighlight( !!Number( highlights.highlight ) );
697 this.filtersModel.getItems().forEach( function ( filterItem ) {
698 var color = highlights[ filterItem.getName() ];
699 if ( color ) {
700 filterItem.setHighlightColor( color );
701 } else {
702 filterItem.clearHighlightColor();
703 }
704 } );
705
706 // Check all filter interactions
707 this.filtersModel.reassessFilterInteractions();
708
709 this.updateChangesList();
710
711 // Log filter grouping
712 this.trackFilterGroupings( 'savedfilters' );
713 }
714 };
715
716 /**
717 * Check whether the current filter and highlight state exists
718 * in the saved queries model.
719 *
720 * @return {boolean} Query exists
721 */
722 mw.rcfilters.Controller.prototype.findQueryMatchingCurrentState = function () {
723 var highlightedItems = {},
724 selectedState = this.filtersModel.getSelectedState();
725
726 // Prepare highlights of the current query
727 this.filtersModel.getItemsSupportingHighlights().forEach( function ( item ) {
728 highlightedItems[ item.getName() ] = item.getHighlightColor();
729 } );
730 highlightedItems.highlight = this.filtersModel.isHighlightEnabled();
731
732 // Remove anything that should be excluded from the saved query
733 // this includes sticky filters and filters marked with 'excludedFromSavedQueries'
734 this._deleteExcludedValuesFromFilterState( selectedState );
735
736 return this.savedQueriesModel.findMatchingQuery(
737 {
738 filters: selectedState,
739 highlights: highlightedItems,
740 invert: this.filtersModel.areNamespacesInverted()
741 }
742 );
743 };
744
745 /**
746 * Delete sticky filters from given object
747 *
748 * @param {Object} filterState Filter state
749 */
750 mw.rcfilters.Controller.prototype._deleteExcludedValuesFromFilterState = function ( filterState ) {
751 // Remove excluded filters
752 $.each( this.filtersModel.getExcludedFiltersState(), function ( filterName ) {
753 delete filterState[ filterName ];
754 } );
755 };
756
757 /**
758 * Get an object representing the base state of parameters
759 * and highlights.
760 *
761 * This is meant to make sure that the saved queries that are
762 * in memory are always the same structure as what we would get
763 * by calling the current model's "getSelectedState" and by checking
764 * highlight items.
765 *
766 * In cases where a user saved a query when the system had a certain
767 * set of filters, and then a filter was added to the system, we want
768 * to make sure that the stored queries can still be comparable to
769 * the current state, which means that we need the base state for
770 * two operations:
771 *
772 * - Saved queries are stored in "minimal" view (only changed filters
773 * are stored); When we initialize the system, we merge each minimal
774 * query with the base state (using 'getNormalizedFilters') so all
775 * saved queries have the exact same structure as what we would get
776 * by checking the getSelectedState of the filter.
777 * - When we save the queries, we minimize the object to only represent
778 * whatever has actually changed, rather than store the entire
779 * object. To check what actually is different so we can store it,
780 * we need to obtain a base state to compare against, this is
781 * what #_getMinimalFilterList does
782 */
783 mw.rcfilters.Controller.prototype._buildBaseFilterState = function () {
784 var defaultParams = this.filtersModel.getDefaultParams(),
785 highlightedItems = {};
786
787 // Prepare highlights
788 this.filtersModel.getItemsSupportingHighlights().forEach( function ( item ) {
789 highlightedItems[ item.getName() ] = null;
790 } );
791 highlightedItems.highlight = false;
792
793 this.baseFilterState = {
794 filters: this.filtersModel.getFiltersFromParameters( defaultParams ),
795 highlights: highlightedItems,
796 invert: false
797 };
798 };
799
800 /**
801 * Get an object representing the base filter state of both
802 * filters and highlights. The structure is similar to what we use
803 * to store each query in the saved queries object:
804 * {
805 * filters: {
806 * filterName: (bool)
807 * },
808 * highlights: {
809 * filterName: (string|null)
810 * }
811 * }
812 *
813 * @return {Object} Object representing the base state of
814 * parameters and highlights
815 */
816 mw.rcfilters.Controller.prototype._getBaseFilterState = function () {
817 return this.baseFilterState;
818 };
819
820 /**
821 * Get an object that holds only the parameters and highlights that have
822 * values different than the base default value.
823 *
824 * This is the reverse of the normalization we do initially on loading and
825 * initializing the saved queries model.
826 *
827 * @param {Object} valuesObject Object representing the state of both
828 * filters and highlights in its normalized version, to be minimized.
829 * @return {Object} Minimal filters and highlights list
830 */
831 mw.rcfilters.Controller.prototype._getMinimalFilterList = function ( valuesObject ) {
832 var result = { filters: {}, highlights: {} },
833 baseState = this._getBaseFilterState();
834
835 // XOR results
836 $.each( valuesObject.filters, function ( name, value ) {
837 if ( baseState.filters !== undefined && baseState.filters[ name ] !== value ) {
838 result.filters[ name ] = value;
839 }
840 } );
841
842 $.each( valuesObject.highlights, function ( name, value ) {
843 if ( baseState.highlights !== undefined && baseState.highlights[ name ] !== value ) {
844 result.highlights[ name ] = value;
845 }
846 } );
847
848 return result;
849 };
850
851 /**
852 * Save the current state of the saved queries model with all
853 * query item representation in the user settings.
854 */
855 mw.rcfilters.Controller.prototype._saveSavedQueries = function () {
856 var stringified,
857 state = this.savedQueriesModel.getState(),
858 controller = this;
859
860 // Minimize before save
861 $.each( state.queries, function ( queryID, info ) {
862 state.queries[ queryID ].data = controller._getMinimalFilterList( info.data );
863 } );
864
865 // Stringify state
866 stringified = JSON.stringify( state );
867
868 if ( stringified.length > 65535 ) {
869 // Sanity check, since the preference can only hold that.
870 return;
871 }
872
873 // Save the preference
874 new mw.Api().saveOption( 'rcfilters-saved-queries', stringified );
875 // Update the preference for this session
876 mw.user.options.set( 'rcfilters-saved-queries', stringified );
877 };
878
879 /**
880 * Update sticky preferences with current model state
881 */
882 mw.rcfilters.Controller.prototype.updateStickyPreferences = function () {
883 // Update default sticky values with selected, whether they came from
884 // the initial defaults or from the URL value that is being normalized
885 this.updateDaysDefault( this.filtersModel.getGroup( 'days' ).getSelectedItems()[ 0 ].getParamName() );
886 this.updateLimitDefault( this.filtersModel.getGroup( 'limit' ).getSelectedItems()[ 0 ].getParamName() );
887
888 // TODO: Make these automatic by having the model go over sticky
889 // items and update their default values automatically
890 };
891
892 /**
893 * Update the limit default value
894 *
895 * param {number} newValue New value
896 */
897 mw.rcfilters.Controller.prototype.updateLimitDefault = function ( /* newValue */ ) {
898 // HACK: Temporarily remove this from being sticky
899 // See T172156
900
901 /*
902 if ( !$.isNumeric( newValue ) ) {
903 return;
904 }
905
906 newValue = Number( newValue );
907
908 if ( mw.user.options.get( 'rcfilters-rclimit' ) !== newValue ) {
909 // Save the preference
910 new mw.Api().saveOption( 'rcfilters-rclimit', newValue );
911 // Update the preference for this session
912 mw.user.options.set( 'rcfilters-rclimit', newValue );
913 }
914 */
915 return;
916 };
917
918 /**
919 * Update the days default value
920 *
921 * param {number} newValue New value
922 */
923 mw.rcfilters.Controller.prototype.updateDaysDefault = function ( /* newValue */ ) {
924 // HACK: Temporarily remove this from being sticky
925 // See T172156
926
927 /*
928 if ( !$.isNumeric( newValue ) ) {
929 return;
930 }
931
932 newValue = Number( newValue );
933
934 if ( mw.user.options.get( 'rcdays' ) !== newValue ) {
935 // Save the preference
936 new mw.Api().saveOption( 'rcdays', newValue );
937 // Update the preference for this session
938 mw.user.options.set( 'rcdays', newValue );
939 }
940 */
941 return;
942 };
943
944 /**
945 * Update the group by page default value
946 *
947 * @param {number} newValue New value
948 */
949 mw.rcfilters.Controller.prototype.updateGroupByPageDefault = function ( newValue ) {
950 if ( !$.isNumeric( newValue ) ) {
951 return;
952 }
953
954 newValue = Number( newValue );
955
956 if ( mw.user.options.get( 'usenewrc' ) !== newValue ) {
957 // Save the preference
958 new mw.Api().saveOption( 'usenewrc', newValue );
959 // Update the preference for this session
960 mw.user.options.set( 'usenewrc', newValue );
961 }
962 };
963
964 /**
965 * Synchronize the URL with the current state of the filters
966 * without adding an history entry.
967 */
968 mw.rcfilters.Controller.prototype.replaceUrl = function () {
969 mw.rcfilters.UriProcessor.static.replaceState( this._getUpdatedUri() );
970 };
971
972 /**
973 * Update filter state (selection and highlighting) based
974 * on current URL values.
975 *
976 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
977 * list based on the updated model.
978 */
979 mw.rcfilters.Controller.prototype.updateStateFromUrl = function ( fetchChangesList ) {
980 fetchChangesList = fetchChangesList === undefined ? true : !!fetchChangesList;
981
982 this.uriProcessor.updateModelBasedOnQuery( new mw.Uri().query );
983
984 // Update the sticky preferences, in case we received a value
985 // from the URL
986 this.updateStickyPreferences();
987
988 // Only update and fetch new results if it is requested
989 if ( fetchChangesList ) {
990 this.updateChangesList();
991 }
992 };
993
994 /**
995 * Update the list of changes and notify the model
996 *
997 * @param {Object} [params] Extra parameters to add to the API call
998 * @param {string} [updateMode='filterChange'] One of 'filterChange', 'liveUpdate', 'showNewChanges'
999 * @return {jQuery.Promise} Promise that is resolved when the update is complete
1000 */
1001 mw.rcfilters.Controller.prototype.updateChangesList = function ( params, updateMode ) {
1002 updateMode = updateMode === undefined ? this.FILTER_CHANGE : updateMode;
1003
1004 if ( updateMode === this.FILTER_CHANGE ) {
1005 this._updateURL( params );
1006 }
1007 if ( updateMode === this.FILTER_CHANGE || updateMode === this.SHOW_NEW_CHANGES ) {
1008 this.changesListModel.invalidate();
1009 }
1010 this.changesListModel.setNewChangesExist( false );
1011 this.updatingChangesList = true;
1012 return this._fetchChangesList()
1013 .then(
1014 // Success
1015 function ( pieces ) {
1016 var $changesListContent = pieces.changes,
1017 $fieldset = pieces.fieldset;
1018 this.changesListModel.update(
1019 $changesListContent,
1020 $fieldset,
1021 false,
1022 updateMode === this.SHOW_NEW_CHANGES
1023 );
1024 }.bind( this )
1025 // Do nothing for failure
1026 )
1027 .always( function () {
1028 this.updatingChangesList = false;
1029 }.bind( this ) );
1030 };
1031
1032 /**
1033 * Get an object representing the default parameter state, whether
1034 * it is from the model defaults or from the saved queries.
1035 *
1036 * @return {Object} Default parameters
1037 */
1038 mw.rcfilters.Controller.prototype._getDefaultParams = function () {
1039 var data, queryHighlights,
1040 savedParams = {},
1041 savedHighlights = {},
1042 defaultSavedQueryItem = this.savedQueriesModel.getItemByID( this.savedQueriesModel.getDefault() );
1043
1044 if ( defaultSavedQueryItem ) {
1045 data = defaultSavedQueryItem.getData();
1046
1047 queryHighlights = data.highlights || {};
1048 savedParams = this.filtersModel.getParametersFromFilters(
1049 // Merge filters with sticky values
1050 $.extend( true, {}, data.filters, this.filtersModel.getStickyFiltersState() )
1051 );
1052
1053 // Translate highlights to parameters
1054 savedHighlights.highlight = String( Number( queryHighlights.highlight ) );
1055 $.each( queryHighlights, function ( filterName, color ) {
1056 if ( filterName !== 'highlights' ) {
1057 savedHighlights[ filterName + '_color' ] = color;
1058 }
1059 } );
1060
1061 return $.extend( true, {}, savedParams, savedHighlights );
1062 }
1063
1064 return this.filtersModel.getDefaultParams();
1065 };
1066
1067 /**
1068 * Update the URL of the page to reflect current filters
1069 *
1070 * This should not be called directly from outside the controller.
1071 * If an action requires changing the URL, it should either use the
1072 * highlighting actions below, or call #updateChangesList which does
1073 * the uri corrections already.
1074 *
1075 * @param {Object} [params] Extra parameters to add to the API call
1076 */
1077 mw.rcfilters.Controller.prototype._updateURL = function ( params ) {
1078 var currentUri = new mw.Uri(),
1079 updatedUri = this._getUpdatedUri();
1080
1081 updatedUri.extend( params || {} );
1082
1083 if (
1084 this.uriProcessor.getVersion( currentUri.query ) !== 2 ||
1085 this.uriProcessor.isNewState( currentUri.query, updatedUri.query )
1086 ) {
1087 mw.rcfilters.UriProcessor.static.replaceState( updatedUri );
1088 }
1089 };
1090
1091 /**
1092 * Get an updated mw.Uri object based on the model state
1093 *
1094 * @return {mw.Uri} Updated Uri
1095 */
1096 mw.rcfilters.Controller.prototype._getUpdatedUri = function () {
1097 var uri = new mw.Uri();
1098
1099 // Minimize url
1100 uri.query = this.uriProcessor.minimizeQuery(
1101 $.extend(
1102 true,
1103 {},
1104 // We want to retain unrecognized params
1105 // The uri params from model will override
1106 // any recognized value in the current uri
1107 // query, retain unrecognized params, and
1108 // the result will then be minimized
1109 uri.query,
1110 this.uriProcessor.getUriParametersFromModel(),
1111 { urlversion: '2' }
1112 )
1113 );
1114
1115 return uri;
1116 };
1117
1118 /**
1119 * Fetch the list of changes from the server for the current filters
1120 *
1121 * @param {string} [counterId='updateChangesList'] Id for this request. To allow concurrent requests
1122 * not to invalidate each other.
1123 * @param {Object} [params={}] Parameters to add to the query
1124 *
1125 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1126 * or with a string denoting no results.
1127 */
1128 mw.rcfilters.Controller.prototype._fetchChangesList = function ( counterId, params ) {
1129 var uri = this._getUpdatedUri(),
1130 stickyParams = this.filtersModel.getStickyParams(),
1131 requestId,
1132 latestRequest;
1133
1134 counterId = counterId || 'updateChangesList';
1135 params = params || {};
1136
1137 uri.extend( params );
1138
1139 this.requestCounter[ counterId ] = this.requestCounter[ counterId ] || 0;
1140 requestId = ++this.requestCounter[ counterId ];
1141 latestRequest = function () {
1142 return requestId === this.requestCounter[ counterId ];
1143 }.bind( this );
1144
1145 // Sticky parameters override the URL params
1146 // this is to make sure that whether we represent
1147 // the sticky params in the URL or not (they may
1148 // be normalized out) the sticky parameters are
1149 // always being sent to the server with their
1150 // current/default values
1151 uri.extend( stickyParams );
1152
1153 return $.ajax( uri.toString(), { contentType: 'html' } )
1154 .then(
1155 // Success
1156 function ( html ) {
1157 var $parsed;
1158 if ( !latestRequest() ) {
1159 return $.Deferred().reject();
1160 }
1161
1162 $parsed = $( $.parseHTML( html ) );
1163
1164 return {
1165 // Changes list
1166 changes: $parsed.find( '.mw-changeslist' ).first().contents(),
1167 // Fieldset
1168 fieldset: $parsed.find( 'fieldset.rcoptions' ).first()
1169 };
1170 },
1171 // Failure
1172 function ( responseObj ) {
1173 var $parsed;
1174
1175 if ( !latestRequest() ) {
1176 return $.Deferred().reject();
1177 }
1178
1179 $parsed = $( $.parseHTML( responseObj.responseText ) );
1180
1181 // Force a resolve state to this promise
1182 return $.Deferred().resolve( {
1183 changes: 'NO_RESULTS',
1184 fieldset: $parsed.find( 'fieldset.rcoptions' ).first()
1185 } ).promise();
1186 }
1187 );
1188 };
1189
1190 /**
1191 * Track usage of highlight feature
1192 *
1193 * @param {string} action
1194 * @param {Array|Object|string} filters
1195 */
1196 mw.rcfilters.Controller.prototype._trackHighlight = function ( action, filters ) {
1197 filters = typeof filters === 'string' ? { name: filters } : filters;
1198 filters = !Array.isArray( filters ) ? [ filters ] : filters;
1199 mw.track(
1200 'event.ChangesListHighlights',
1201 {
1202 action: action,
1203 filters: filters,
1204 userId: mw.user.getId()
1205 }
1206 );
1207 };
1208
1209 /**
1210 * Track filter grouping usage
1211 *
1212 * @param {string} action Action taken
1213 */
1214 mw.rcfilters.Controller.prototype.trackFilterGroupings = function ( action ) {
1215 var controller = this,
1216 rightNow = new Date().getTime(),
1217 randomIdentifier = String( mw.user.sessionId() ) + String( rightNow ) + String( Math.random() ),
1218 // Get all current filters
1219 filters = this.filtersModel.getSelectedItems().map( function ( item ) {
1220 return item.getName();
1221 } );
1222
1223 action = action || 'filtermenu';
1224
1225 // Check if these filters were the ones we just logged previously
1226 // (Don't log the same grouping twice, in case the user opens/closes)
1227 // the menu without action, or with the same result
1228 if (
1229 // Only log if the two arrays are different in size
1230 filters.length !== this.prevLoggedItems.length ||
1231 // Or if any filters are not the same as the cached filters
1232 filters.some( function ( filterName ) {
1233 return controller.prevLoggedItems.indexOf( filterName ) === -1;
1234 } ) ||
1235 // Or if any cached filters are not the same as given filters
1236 this.prevLoggedItems.some( function ( filterName ) {
1237 return filters.indexOf( filterName ) === -1;
1238 } )
1239 ) {
1240 filters.forEach( function ( filterName ) {
1241 mw.track(
1242 'event.ChangesListFilterGrouping',
1243 {
1244 action: action,
1245 groupIdentifier: randomIdentifier,
1246 filter: filterName,
1247 userId: mw.user.getId()
1248 }
1249 );
1250 } );
1251
1252 // Cache the filter names
1253 this.prevLoggedItems = filters;
1254 }
1255 };
1256 }( mediaWiki, jQuery ) );