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