Merge "RCFilters: Prevent live update fetch if model is in conflict"
[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( '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: 0, // The server normalizes negative numbers to 0 results
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 normalizeWithinRange = function ( range, val ) {
285 if ( val < range.min ) {
286 return range.min; // Min
287 } else if ( val >= range.max ) {
288 return range.max; // Max
289 }
290 return val;
291 };
292
293 arbitraryValues = Array.isArray( arbitraryValues ) ? arbitraryValues : [ arbitraryValues ];
294
295 // Normalize the arbitrary values and the default value for a range
296 if ( groupData.range ) {
297 arbitraryValues = arbitraryValues.map( function ( val ) {
298 return normalizeWithinRange( groupData.range, val );
299 } );
300
301 // Normalize the default, since that's user defined
302 if ( groupData.default !== undefined ) {
303 groupData.default = String( normalizeWithinRange( groupData.range, groupData.default ) );
304 }
305 }
306
307 // This is only true for single_option group
308 // We assume these are the only groups that will allow for
309 // arbitrary, since it doesn't make any sense for the other
310 // groups.
311 arbitraryValues.forEach( function ( val ) {
312 if (
313 // If the group allows for arbitrary data
314 groupData.allowArbitrary &&
315 // and it is single_option (or string_options, but we
316 // don't have cases of those yet, nor do we plan to)
317 groupData.type === 'single_option' &&
318 // and, if there is a validate method and it passes on
319 // the data
320 ( !groupData.validate || groupData.validate( val ) ) &&
321 // but if that value isn't already in the definition
322 groupData.filters
323 .map( function ( filterData ) {
324 return String( filterData.name );
325 } )
326 .indexOf( String( val ) ) === -1
327 ) {
328 // Add the filter information
329 groupData.filters.push( controller._createFilterDataFromNumber(
330 val,
331 groupData.numToLabelFunc ?
332 groupData.numToLabelFunc( val ) :
333 val
334 ) );
335
336 // If there's a sort function set up, re-sort the values
337 if ( groupData.sortFunc ) {
338 groupData.filters.sort( groupData.sortFunc );
339 }
340 }
341 } );
342 };
343
344 /**
345 * Switch the view of the filters model
346 *
347 * @param {string} view Requested view
348 */
349 mw.rcfilters.Controller.prototype.switchView = function ( view ) {
350 this.filtersModel.switchView( view );
351 };
352
353 /**
354 * Reset to default filters
355 */
356 mw.rcfilters.Controller.prototype.resetToDefaults = function () {
357 this.uriProcessor.updateModelBasedOnQuery( this._getDefaultParams() );
358
359 this.updateChangesList();
360 };
361
362 /**
363 * Empty all selected filters
364 */
365 mw.rcfilters.Controller.prototype.emptyFilters = function () {
366 var highlightedFilterNames = this.filtersModel
367 .getHighlightedItems()
368 .map( function ( filterItem ) { return { name: filterItem.getName() }; } );
369
370 this.filtersModel.emptyAllFilters();
371 this.filtersModel.clearAllHighlightColors();
372 // Check all filter interactions
373 this.filtersModel.reassessFilterInteractions();
374
375 this.updateChangesList();
376
377 if ( highlightedFilterNames ) {
378 this._trackHighlight( 'clearAll', highlightedFilterNames );
379 }
380 };
381
382 /**
383 * Update the selected state of a filter
384 *
385 * @param {string} filterName Filter name
386 * @param {boolean} [isSelected] Filter selected state
387 */
388 mw.rcfilters.Controller.prototype.toggleFilterSelect = function ( filterName, isSelected ) {
389 var filterItem = this.filtersModel.getItemByName( filterName );
390
391 if ( !filterItem ) {
392 // If no filter was found, break
393 return;
394 }
395
396 isSelected = isSelected === undefined ? !filterItem.isSelected() : isSelected;
397
398 if ( filterItem.isSelected() !== isSelected ) {
399 this.filtersModel.toggleFilterSelected( filterName, isSelected );
400
401 this.updateChangesList();
402
403 // Check filter interactions
404 this.filtersModel.reassessFilterInteractions( filterItem );
405 }
406 };
407
408 /**
409 * Clear both highlight and selection of a filter
410 *
411 * @param {string} filterName Name of the filter item
412 */
413 mw.rcfilters.Controller.prototype.clearFilter = function ( filterName ) {
414 var filterItem = this.filtersModel.getItemByName( filterName ),
415 isHighlighted = filterItem.isHighlighted();
416
417 if ( filterItem.isSelected() || isHighlighted ) {
418 this.filtersModel.clearHighlightColor( filterName );
419 this.filtersModel.toggleFilterSelected( filterName, false );
420 this.updateChangesList();
421 this.filtersModel.reassessFilterInteractions( filterItem );
422
423 // Log filter grouping
424 this.trackFilterGroupings( 'removefilter' );
425 }
426
427 if ( isHighlighted ) {
428 this._trackHighlight( 'clear', filterName );
429 }
430 };
431
432 /**
433 * Toggle the highlight feature on and off
434 */
435 mw.rcfilters.Controller.prototype.toggleHighlight = function () {
436 this.filtersModel.toggleHighlight();
437 this._updateURL();
438
439 if ( this.filtersModel.isHighlightEnabled() ) {
440 mw.hook( 'RcFilters.highlight.enable' ).fire();
441 }
442 };
443
444 /**
445 * Toggle the namespaces inverted feature on and off
446 */
447 mw.rcfilters.Controller.prototype.toggleInvertedNamespaces = function () {
448 this.filtersModel.toggleInvertedNamespaces();
449
450 if (
451 this.filtersModel.getFiltersByView( 'namespaces' )
452 .filter( function ( filterItem ) {
453 return filterItem.isSelected();
454 } )
455 .length
456 ) {
457 // Only re-fetch results if there are namespace items that are actually selected
458 this.updateChangesList();
459 }
460 };
461
462 /**
463 * Set the highlight color for a filter item
464 *
465 * @param {string} filterName Name of the filter item
466 * @param {string} color Selected color
467 */
468 mw.rcfilters.Controller.prototype.setHighlightColor = function ( filterName, color ) {
469 this.filtersModel.setHighlightColor( filterName, color );
470 this._updateURL();
471 this._trackHighlight( 'set', { name: filterName, color: color } );
472 };
473
474 /**
475 * Clear highlight for a filter item
476 *
477 * @param {string} filterName Name of the filter item
478 */
479 mw.rcfilters.Controller.prototype.clearHighlightColor = function ( filterName ) {
480 this.filtersModel.clearHighlightColor( filterName );
481 this._updateURL();
482 this._trackHighlight( 'clear', filterName );
483 };
484
485 /**
486 * Enable or disable live updates.
487 * @param {boolean} enable True to enable, false to disable
488 */
489 mw.rcfilters.Controller.prototype.toggleLiveUpdate = function ( enable ) {
490 this.changesListModel.toggleLiveUpdate( enable );
491 if ( this.changesListModel.getLiveUpdate() && this.changesListModel.getNewChangesExist() ) {
492 this.showNewChanges();
493 }
494 };
495
496 /**
497 * Set a timeout for the next live update.
498 * @private
499 */
500 mw.rcfilters.Controller.prototype._scheduleLiveUpdate = function () {
501 setTimeout( this._doLiveUpdate.bind( this ), 3000 );
502 };
503
504 /**
505 * Perform a live update.
506 * @private
507 */
508 mw.rcfilters.Controller.prototype._doLiveUpdate = function () {
509 if ( !this._shouldCheckForNewChanges() ) {
510 // skip this turn and check back later
511 this._scheduleLiveUpdate();
512 return;
513 }
514
515 this._checkForNewChanges()
516 .then( function ( data ) {
517 if ( !this._shouldCheckForNewChanges() ) {
518 // by the time the response is received,
519 // it may not be appropriate anymore
520 return;
521 }
522
523 if ( data.changes !== 'NO_RESULTS' ) {
524 if ( this.changesListModel.getLiveUpdate() ) {
525 return this.updateChangesList( false, null, true, false );
526 } else {
527 this.changesListModel.setNewChangesExist( true );
528 }
529 }
530 }.bind( this ) )
531 .always( this._scheduleLiveUpdate.bind( this ) );
532 };
533
534 /**
535 * @return {boolean} It's appropriate to check for new changes now
536 * @private
537 */
538 mw.rcfilters.Controller.prototype._shouldCheckForNewChanges = function () {
539 var liveUpdateFeatureFlag = mw.config.get( 'wgStructuredChangeFiltersEnableLiveUpdate' ) ||
540 new mw.Uri().query.liveupdate;
541
542 return !document.hidden &&
543 !this.filtersModel.hasConflict() &&
544 !this.changesListModel.getNewChangesExist() &&
545 !this.updatingChangesList &&
546 liveUpdateFeatureFlag;
547 };
548
549 /**
550 * Check if new changes, newer than those currently shown, are available
551 *
552 * @return {jQuery.Promise} Promise object that resolves after trying
553 * to fetch 1 change newer than the last known 'from' parameter value
554 *
555 * @private
556 */
557 mw.rcfilters.Controller.prototype._checkForNewChanges = function () {
558 return this._fetchChangesList(
559 'liveUpdate',
560 {
561 limit: 1,
562 from: this.changesListModel.getNextFrom()
563 }
564 );
565 };
566
567 /**
568 * Show the new changes
569 *
570 * @return {jQuery.Promise} Promise object that resolves after
571 * fetching and showing the new changes
572 */
573 mw.rcfilters.Controller.prototype.showNewChanges = function () {
574 return this.updateChangesList( false, null, true, true );
575 };
576
577 /**
578 * Save the current model state as a saved query
579 *
580 * @param {string} [label] Label of the saved query
581 * @param {boolean} [setAsDefault=false] This query should be set as the default
582 */
583 mw.rcfilters.Controller.prototype.saveCurrentQuery = function ( label, setAsDefault ) {
584 var queryID,
585 highlightedItems = {},
586 highlightEnabled = this.filtersModel.isHighlightEnabled(),
587 selectedState = this.filtersModel.getSelectedState();
588
589 // Prepare highlights
590 this.filtersModel.getHighlightedItems().forEach( function ( item ) {
591 highlightedItems[ item.getName() ] = highlightEnabled ?
592 item.getHighlightColor() : null;
593 } );
594 // These are filter states; highlight is stored as boolean
595 highlightedItems.highlight = this.filtersModel.isHighlightEnabled();
596
597 // Delete all sticky filters
598 this._deleteStickyValuesFromFilterState( selectedState );
599
600 // Add item
601 queryID = this.savedQueriesModel.addNewQuery(
602 label || mw.msg( 'rcfilters-savedqueries-defaultlabel' ),
603 {
604 filters: selectedState,
605 highlights: highlightedItems,
606 invert: this.filtersModel.areNamespacesInverted()
607 }
608 );
609
610 if ( setAsDefault ) {
611 this.savedQueriesModel.setDefault( queryID );
612 }
613
614 // Save item
615 this._saveSavedQueries();
616 };
617
618 /**
619 * Remove a saved query
620 *
621 * @param {string} queryID Query id
622 */
623 mw.rcfilters.Controller.prototype.removeSavedQuery = function ( queryID ) {
624 this.savedQueriesModel.removeQuery( queryID );
625
626 this._saveSavedQueries();
627 };
628
629 /**
630 * Rename a saved query
631 *
632 * @param {string} queryID Query id
633 * @param {string} newLabel New label for the query
634 */
635 mw.rcfilters.Controller.prototype.renameSavedQuery = function ( queryID, newLabel ) {
636 var queryItem = this.savedQueriesModel.getItemByID( queryID );
637
638 if ( queryItem ) {
639 queryItem.updateLabel( newLabel );
640 }
641 this._saveSavedQueries();
642 };
643
644 /**
645 * Set a saved query as default
646 *
647 * @param {string} queryID Query Id. If null is given, default
648 * query is reset.
649 */
650 mw.rcfilters.Controller.prototype.setDefaultSavedQuery = function ( queryID ) {
651 this.savedQueriesModel.setDefault( queryID );
652 this._saveSavedQueries();
653 };
654
655 /**
656 * Load a saved query
657 *
658 * @param {string} queryID Query id
659 */
660 mw.rcfilters.Controller.prototype.applySavedQuery = function ( queryID ) {
661 var data, highlights,
662 queryItem = this.savedQueriesModel.getItemByID( queryID ),
663 currentMatchingQuery = this.findQueryMatchingCurrentState();
664
665 if (
666 queryItem &&
667 (
668 // If there's already a query, don't reload it
669 // if it's the same as the one that already exists
670 !currentMatchingQuery ||
671 currentMatchingQuery.getID() !== queryItem.getID()
672 )
673 ) {
674 data = queryItem.getData();
675 highlights = data.highlights;
676
677 // Backwards compatibility; initial version mispelled 'highlight' with 'highlights'
678 highlights.highlight = highlights.highlights || highlights.highlight;
679
680 // Update model state from filters
681 this.filtersModel.toggleFiltersSelected(
682 // Merge filters with sticky values
683 $.extend( true, {}, data.filters, this.filtersModel.getStickyFiltersState() )
684 );
685
686 // Update namespace inverted property
687 this.filtersModel.toggleInvertedNamespaces( !!Number( data.invert ) );
688
689 // Update highlight state
690 this.filtersModel.toggleHighlight( !!Number( highlights.highlight ) );
691 this.filtersModel.getItems().forEach( function ( filterItem ) {
692 var color = highlights[ filterItem.getName() ];
693 if ( color ) {
694 filterItem.setHighlightColor( color );
695 } else {
696 filterItem.clearHighlightColor();
697 }
698 } );
699
700 // Check all filter interactions
701 this.filtersModel.reassessFilterInteractions();
702
703 this.updateChangesList();
704
705 // Log filter grouping
706 this.trackFilterGroupings( 'savedfilters' );
707 }
708 };
709
710 /**
711 * Check whether the current filter and highlight state exists
712 * in the saved queries model.
713 *
714 * @return {boolean} Query exists
715 */
716 mw.rcfilters.Controller.prototype.findQueryMatchingCurrentState = function () {
717 var highlightedItems = {},
718 selectedState = this.filtersModel.getSelectedState();
719
720 // Prepare highlights of the current query
721 this.filtersModel.getItemsSupportingHighlights().forEach( function ( item ) {
722 highlightedItems[ item.getName() ] = item.getHighlightColor();
723 } );
724 highlightedItems.highlight = this.filtersModel.isHighlightEnabled();
725
726 // Remove sticky filters
727 this._deleteStickyValuesFromFilterState( selectedState );
728
729 return this.savedQueriesModel.findMatchingQuery(
730 {
731 filters: selectedState,
732 highlights: highlightedItems,
733 invert: this.filtersModel.areNamespacesInverted()
734 }
735 );
736 };
737
738 /**
739 * Delete sticky filters from given object
740 *
741 * @param {Object} filterState Filter state
742 */
743 mw.rcfilters.Controller.prototype._deleteStickyValuesFromFilterState = function ( filterState ) {
744 // Remove sticky filters
745 $.each( this.filtersModel.getStickyFiltersState(), function ( filterName ) {
746 delete filterState[ filterName ];
747 } );
748 };
749
750 /**
751 * Get an object representing the base state of parameters
752 * and highlights.
753 *
754 * This is meant to make sure that the saved queries that are
755 * in memory are always the same structure as what we would get
756 * by calling the current model's "getSelectedState" and by checking
757 * highlight items.
758 *
759 * In cases where a user saved a query when the system had a certain
760 * set of filters, and then a filter was added to the system, we want
761 * to make sure that the stored queries can still be comparable to
762 * the current state, which means that we need the base state for
763 * two operations:
764 *
765 * - Saved queries are stored in "minimal" view (only changed filters
766 * are stored); When we initialize the system, we merge each minimal
767 * query with the base state (using 'getNormalizedFilters') so all
768 * saved queries have the exact same structure as what we would get
769 * by checking the getSelectedState of the filter.
770 * - When we save the queries, we minimize the object to only represent
771 * whatever has actually changed, rather than store the entire
772 * object. To check what actually is different so we can store it,
773 * we need to obtain a base state to compare against, this is
774 * what #_getMinimalFilterList does
775 */
776 mw.rcfilters.Controller.prototype._buildBaseFilterState = function () {
777 var defaultParams = this.filtersModel.getDefaultParams(),
778 highlightedItems = {};
779
780 // Prepare highlights
781 this.filtersModel.getItemsSupportingHighlights().forEach( function ( item ) {
782 highlightedItems[ item.getName() ] = null;
783 } );
784 highlightedItems.highlight = false;
785
786 this.baseFilterState = {
787 filters: this.filtersModel.getFiltersFromParameters( defaultParams ),
788 highlights: highlightedItems,
789 invert: false
790 };
791 };
792
793 /**
794 * Get an object representing the base filter state of both
795 * filters and highlights. The structure is similar to what we use
796 * to store each query in the saved queries object:
797 * {
798 * filters: {
799 * filterName: (bool)
800 * },
801 * highlights: {
802 * filterName: (string|null)
803 * }
804 * }
805 *
806 * @return {Object} Object representing the base state of
807 * parameters and highlights
808 */
809 mw.rcfilters.Controller.prototype._getBaseFilterState = function () {
810 return this.baseFilterState;
811 };
812
813 /**
814 * Get an object that holds only the parameters and highlights that have
815 * values different than the base default value.
816 *
817 * This is the reverse of the normalization we do initially on loading and
818 * initializing the saved queries model.
819 *
820 * @param {Object} valuesObject Object representing the state of both
821 * filters and highlights in its normalized version, to be minimized.
822 * @return {Object} Minimal filters and highlights list
823 */
824 mw.rcfilters.Controller.prototype._getMinimalFilterList = function ( valuesObject ) {
825 var result = { filters: {}, highlights: {} },
826 baseState = this._getBaseFilterState();
827
828 // XOR results
829 $.each( valuesObject.filters, function ( name, value ) {
830 if ( baseState.filters !== undefined && baseState.filters[ name ] !== value ) {
831 result.filters[ name ] = value;
832 }
833 } );
834
835 $.each( valuesObject.highlights, function ( name, value ) {
836 if ( baseState.highlights !== undefined && baseState.highlights[ name ] !== value ) {
837 result.highlights[ name ] = value;
838 }
839 } );
840
841 return result;
842 };
843
844 /**
845 * Save the current state of the saved queries model with all
846 * query item representation in the user settings.
847 */
848 mw.rcfilters.Controller.prototype._saveSavedQueries = function () {
849 var stringified,
850 state = this.savedQueriesModel.getState(),
851 controller = this;
852
853 // Minimize before save
854 $.each( state.queries, function ( queryID, info ) {
855 state.queries[ queryID ].data = controller._getMinimalFilterList( info.data );
856 } );
857
858 // Stringify state
859 stringified = JSON.stringify( state );
860
861 if ( stringified.length > 65535 ) {
862 // Sanity check, since the preference can only hold that.
863 return;
864 }
865
866 // Save the preference
867 new mw.Api().saveOption( 'rcfilters-saved-queries', stringified );
868 // Update the preference for this session
869 mw.user.options.set( 'rcfilters-saved-queries', stringified );
870 };
871
872 /**
873 * Update sticky preferences with current model state
874 */
875 mw.rcfilters.Controller.prototype.updateStickyPreferences = function () {
876 // Update default sticky values with selected, whether they came from
877 // the initial defaults or from the URL value that is being normalized
878 this.updateDaysDefault( this.filtersModel.getGroup( 'days' ).getSelectedItems()[ 0 ].getParamName() );
879 this.updateLimitDefault( this.filtersModel.getGroup( 'limit' ).getSelectedItems()[ 0 ].getParamName() );
880
881 // TODO: Make these automatic by having the model go over sticky
882 // items and update their default values automatically
883 };
884
885 /**
886 * Update the limit default value
887 *
888 * param {number} newValue New value
889 */
890 mw.rcfilters.Controller.prototype.updateLimitDefault = function ( /* newValue */ ) {
891 // HACK: Temporarily remove this from being sticky
892 // See T172156
893
894 /*
895 if ( !$.isNumeric( newValue ) ) {
896 return;
897 }
898
899 newValue = Number( newValue );
900
901 if ( mw.user.options.get( 'rcfilters-rclimit' ) !== newValue ) {
902 // Save the preference
903 new mw.Api().saveOption( 'rcfilters-rclimit', newValue );
904 // Update the preference for this session
905 mw.user.options.set( 'rcfilters-rclimit', newValue );
906 }
907 */
908 return;
909 };
910
911 /**
912 * Update the days default value
913 *
914 * param {number} newValue New value
915 */
916 mw.rcfilters.Controller.prototype.updateDaysDefault = function ( /* newValue */ ) {
917 // HACK: Temporarily remove this from being sticky
918 // See T172156
919
920 /*
921 if ( !$.isNumeric( newValue ) ) {
922 return;
923 }
924
925 newValue = Number( newValue );
926
927 if ( mw.user.options.get( 'rcdays' ) !== newValue ) {
928 // Save the preference
929 new mw.Api().saveOption( 'rcdays', newValue );
930 // Update the preference for this session
931 mw.user.options.set( 'rcdays', newValue );
932 }
933 */
934 return;
935 };
936
937 /**
938 * Update the group by page default value
939 *
940 * @param {number} newValue New value
941 */
942 mw.rcfilters.Controller.prototype.updateGroupByPageDefault = function ( newValue ) {
943 if ( !$.isNumeric( newValue ) ) {
944 return;
945 }
946
947 newValue = Number( newValue );
948
949 if ( mw.user.options.get( 'usenewrc' ) !== newValue ) {
950 // Save the preference
951 new mw.Api().saveOption( 'usenewrc', newValue );
952 // Update the preference for this session
953 mw.user.options.set( 'usenewrc', newValue );
954 }
955 };
956
957 /**
958 * Synchronize the URL with the current state of the filters
959 * without adding an history entry.
960 */
961 mw.rcfilters.Controller.prototype.replaceUrl = function () {
962 mw.rcfilters.UriProcessor.static.replaceState( this._getUpdatedUri() );
963 };
964
965 /**
966 * Update filter state (selection and highlighting) based
967 * on current URL values.
968 *
969 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
970 * list based on the updated model.
971 */
972 mw.rcfilters.Controller.prototype.updateStateFromUrl = function ( fetchChangesList ) {
973 fetchChangesList = fetchChangesList === undefined ? true : !!fetchChangesList;
974
975 this.uriProcessor.updateModelBasedOnQuery( new mw.Uri().query );
976
977 // Update the sticky preferences, in case we received a value
978 // from the URL
979 this.updateStickyPreferences();
980
981 // Only update and fetch new results if it is requested
982 if ( fetchChangesList ) {
983 this.updateChangesList();
984 }
985 };
986
987 /**
988 * Update the list of changes and notify the model
989 *
990 * @param {boolean} [updateUrl=true] Whether the URL should be updated with the current state of the filters
991 * @param {Object} [params] Extra parameters to add to the API call
992 * @param {boolean} [isLiveUpdate=false] The purpose of this update is to show new results for the same filters
993 * @param {boolean} [invalidateCurrentChanges=true] Invalidate current changes by default (show spinner)
994 * @return {jQuery.Promise} Promise that is resolved when the update is complete
995 */
996 mw.rcfilters.Controller.prototype.updateChangesList = function ( updateUrl, params, isLiveUpdate, invalidateCurrentChanges ) {
997 updateUrl = updateUrl === undefined ? true : updateUrl;
998 invalidateCurrentChanges = invalidateCurrentChanges === undefined ? true : invalidateCurrentChanges;
999 if ( updateUrl ) {
1000 this._updateURL( params );
1001 }
1002 if ( invalidateCurrentChanges ) {
1003 this.changesListModel.invalidate();
1004 }
1005 this.changesListModel.setNewChangesExist( false );
1006 this.updatingChangesList = true;
1007 return this._fetchChangesList()
1008 .then(
1009 // Success
1010 function ( pieces ) {
1011 var $changesListContent = pieces.changes,
1012 $fieldset = pieces.fieldset;
1013 this.changesListModel.update( $changesListContent, $fieldset, false, isLiveUpdate );
1014 }.bind( this )
1015 // Do nothing for failure
1016 )
1017 .always( function () {
1018 this.updatingChangesList = false;
1019 }.bind( this ) );
1020 };
1021
1022 /**
1023 * Get an object representing the default parameter state, whether
1024 * it is from the model defaults or from the saved queries.
1025 *
1026 * @return {Object} Default parameters
1027 */
1028 mw.rcfilters.Controller.prototype._getDefaultParams = function () {
1029 var data, queryHighlights,
1030 savedParams = {},
1031 savedHighlights = {},
1032 defaultSavedQueryItem = this.savedQueriesModel.getItemByID( this.savedQueriesModel.getDefault() );
1033
1034 if ( defaultSavedQueryItem ) {
1035 data = defaultSavedQueryItem.getData();
1036
1037 queryHighlights = data.highlights || {};
1038 savedParams = this.filtersModel.getParametersFromFilters(
1039 // Merge filters with sticky values
1040 $.extend( true, {}, data.filters, this.filtersModel.getStickyFiltersState() )
1041 );
1042
1043 // Translate highlights to parameters
1044 savedHighlights.highlight = String( Number( queryHighlights.highlight ) );
1045 $.each( queryHighlights, function ( filterName, color ) {
1046 if ( filterName !== 'highlights' ) {
1047 savedHighlights[ filterName + '_color' ] = color;
1048 }
1049 } );
1050
1051 return $.extend( true, {}, savedParams, savedHighlights );
1052 }
1053
1054 return this.filtersModel.getDefaultParams();
1055 };
1056
1057 /**
1058 * Update the URL of the page to reflect current filters
1059 *
1060 * This should not be called directly from outside the controller.
1061 * If an action requires changing the URL, it should either use the
1062 * highlighting actions below, or call #updateChangesList which does
1063 * the uri corrections already.
1064 *
1065 * @param {Object} [params] Extra parameters to add to the API call
1066 */
1067 mw.rcfilters.Controller.prototype._updateURL = function ( params ) {
1068 var currentUri = new mw.Uri(),
1069 updatedUri = this._getUpdatedUri();
1070
1071 updatedUri.extend( params || {} );
1072
1073 if (
1074 this.uriProcessor.getVersion( currentUri.query ) !== 2 ||
1075 this.uriProcessor.isNewState( currentUri.query, updatedUri.query )
1076 ) {
1077 mw.rcfilters.UriProcessor.static.replaceState( updatedUri );
1078 }
1079 };
1080
1081 /**
1082 * Get an updated mw.Uri object based on the model state
1083 *
1084 * @return {mw.Uri} Updated Uri
1085 */
1086 mw.rcfilters.Controller.prototype._getUpdatedUri = function () {
1087 var uri = new mw.Uri();
1088
1089 // Minimize url
1090 uri.query = this.uriProcessor.minimizeQuery(
1091 $.extend(
1092 true,
1093 {},
1094 // We want to retain unrecognized params
1095 // The uri params from model will override
1096 // any recognized value in the current uri
1097 // query, retain unrecognized params, and
1098 // the result will then be minimized
1099 uri.query,
1100 this.uriProcessor.getUriParametersFromModel(),
1101 { urlversion: '2' }
1102 )
1103 );
1104
1105 return uri;
1106 };
1107
1108 /**
1109 * Fetch the list of changes from the server for the current filters
1110 *
1111 * @param {string} [counterId='updateChangesList'] Id for this request. To allow concurrent requests
1112 * not to invalidate each other.
1113 * @param {Object} [params={}] Parameters to add to the query
1114 *
1115 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1116 * or with a string denoting no results.
1117 */
1118 mw.rcfilters.Controller.prototype._fetchChangesList = function ( counterId, params ) {
1119 var uri = this._getUpdatedUri(),
1120 stickyParams = this.filtersModel.getStickyParams(),
1121 requestId,
1122 latestRequest;
1123
1124 counterId = counterId || 'updateChangesList';
1125 params = params || {};
1126
1127 uri.extend( params );
1128
1129 this.requestCounter[ counterId ] = this.requestCounter[ counterId ] || 0;
1130 requestId = ++this.requestCounter[ counterId ];
1131 latestRequest = function () {
1132 return requestId === this.requestCounter[ counterId ];
1133 }.bind( this );
1134
1135 // Sticky parameters override the URL params
1136 // this is to make sure that whether we represent
1137 // the sticky params in the URL or not (they may
1138 // be normalized out) the sticky parameters are
1139 // always being sent to the server with their
1140 // current/default values
1141 uri.extend( stickyParams );
1142
1143 return $.ajax( uri.toString(), { contentType: 'html' } )
1144 .then(
1145 // Success
1146 function ( html ) {
1147 var $parsed;
1148 if ( !latestRequest() ) {
1149 return $.Deferred().reject();
1150 }
1151
1152 $parsed = $( $.parseHTML( html ) );
1153
1154 return {
1155 // Changes list
1156 changes: $parsed.find( '.mw-changeslist' ).first().contents(),
1157 // Fieldset
1158 fieldset: $parsed.find( 'fieldset.rcoptions' ).first()
1159 };
1160 },
1161 // Failure
1162 function ( responseObj ) {
1163 var $parsed;
1164
1165 if ( !latestRequest() ) {
1166 return $.Deferred().reject();
1167 }
1168
1169 $parsed = $( $.parseHTML( responseObj.responseText ) );
1170
1171 // Force a resolve state to this promise
1172 return $.Deferred().resolve( {
1173 changes: 'NO_RESULTS',
1174 fieldset: $parsed.find( 'fieldset.rcoptions' ).first()
1175 } ).promise();
1176 }
1177 );
1178 };
1179
1180 /**
1181 * Track usage of highlight feature
1182 *
1183 * @param {string} action
1184 * @param {Array|Object|string} filters
1185 */
1186 mw.rcfilters.Controller.prototype._trackHighlight = function ( action, filters ) {
1187 filters = typeof filters === 'string' ? { name: filters } : filters;
1188 filters = !Array.isArray( filters ) ? [ filters ] : filters;
1189 mw.track(
1190 'event.ChangesListHighlights',
1191 {
1192 action: action,
1193 filters: filters,
1194 userId: mw.user.getId()
1195 }
1196 );
1197 };
1198
1199 /**
1200 * Track filter grouping usage
1201 *
1202 * @param {string} action Action taken
1203 */
1204 mw.rcfilters.Controller.prototype.trackFilterGroupings = function ( action ) {
1205 var controller = this,
1206 rightNow = new Date().getTime(),
1207 randomIdentifier = String( mw.user.sessionId() ) + String( rightNow ) + String( Math.random() ),
1208 // Get all current filters
1209 filters = this.filtersModel.getSelectedItems().map( function ( item ) {
1210 return item.getName();
1211 } );
1212
1213 action = action || 'filtermenu';
1214
1215 // Check if these filters were the ones we just logged previously
1216 // (Don't log the same grouping twice, in case the user opens/closes)
1217 // the menu without action, or with the same result
1218 if (
1219 // Only log if the two arrays are different in size
1220 filters.length !== this.prevLoggedItems.length ||
1221 // Or if any filters are not the same as the cached filters
1222 filters.some( function ( filterName ) {
1223 return controller.prevLoggedItems.indexOf( filterName ) === -1;
1224 } ) ||
1225 // Or if any cached filters are not the same as given filters
1226 this.prevLoggedItems.some( function ( filterName ) {
1227 return filters.indexOf( filterName ) === -1;
1228 } )
1229 ) {
1230 filters.forEach( function ( filterName ) {
1231 mw.track(
1232 'event.ChangesListFilterGrouping',
1233 {
1234 action: action,
1235 groupIdentifier: randomIdentifier,
1236 filter: filterName,
1237 userId: mw.user.getId()
1238 }
1239 );
1240 } );
1241
1242 // Cache the filter names
1243 this.prevLoggedItems = filters;
1244 }
1245 };
1246 }( mediaWiki, jQuery ) );