Merge "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( '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.changesListModel.getNewChangesExist() &&
544 !this.updatingChangesList &&
545 liveUpdateFeatureFlag;
546 };
547
548 /**
549 * Check if new changes, newer than those currently shown, are available
550 *
551 * @return {jQuery.Promise} Promise object that resolves after trying
552 * to fetch 1 change newer than the last known 'from' parameter value
553 *
554 * @private
555 */
556 mw.rcfilters.Controller.prototype._checkForNewChanges = function () {
557 return this._fetchChangesList(
558 'liveUpdate',
559 {
560 limit: 1,
561 from: this.changesListModel.getNextFrom()
562 }
563 );
564 };
565
566 /**
567 * Show the new changes
568 *
569 * @return {jQuery.Promise} Promise object that resolves after
570 * fetching and showing the new changes
571 */
572 mw.rcfilters.Controller.prototype.showNewChanges = function () {
573 return this.updateChangesList( false, null, true, true );
574 };
575
576 /**
577 * Save the current model state as a saved query
578 *
579 * @param {string} [label] Label of the saved query
580 * @param {boolean} [setAsDefault=false] This query should be set as the default
581 */
582 mw.rcfilters.Controller.prototype.saveCurrentQuery = function ( label, setAsDefault ) {
583 var queryID,
584 highlightedItems = {},
585 highlightEnabled = this.filtersModel.isHighlightEnabled(),
586 selectedState = this.filtersModel.getSelectedState();
587
588 // Prepare highlights
589 this.filtersModel.getHighlightedItems().forEach( function ( item ) {
590 highlightedItems[ item.getName() ] = highlightEnabled ?
591 item.getHighlightColor() : null;
592 } );
593 // These are filter states; highlight is stored as boolean
594 highlightedItems.highlight = this.filtersModel.isHighlightEnabled();
595
596 // Delete all sticky filters
597 this._deleteStickyValuesFromFilterState( selectedState );
598
599 // Add item
600 queryID = this.savedQueriesModel.addNewQuery(
601 label || mw.msg( 'rcfilters-savedqueries-defaultlabel' ),
602 {
603 filters: selectedState,
604 highlights: highlightedItems,
605 invert: this.filtersModel.areNamespacesInverted()
606 }
607 );
608
609 if ( setAsDefault ) {
610 this.savedQueriesModel.setDefault( queryID );
611 }
612
613 // Save item
614 this._saveSavedQueries();
615 };
616
617 /**
618 * Remove a saved query
619 *
620 * @param {string} queryID Query id
621 */
622 mw.rcfilters.Controller.prototype.removeSavedQuery = function ( queryID ) {
623 this.savedQueriesModel.removeQuery( queryID );
624
625 this._saveSavedQueries();
626 };
627
628 /**
629 * Rename a saved query
630 *
631 * @param {string} queryID Query id
632 * @param {string} newLabel New label for the query
633 */
634 mw.rcfilters.Controller.prototype.renameSavedQuery = function ( queryID, newLabel ) {
635 var queryItem = this.savedQueriesModel.getItemByID( queryID );
636
637 if ( queryItem ) {
638 queryItem.updateLabel( newLabel );
639 }
640 this._saveSavedQueries();
641 };
642
643 /**
644 * Set a saved query as default
645 *
646 * @param {string} queryID Query Id. If null is given, default
647 * query is reset.
648 */
649 mw.rcfilters.Controller.prototype.setDefaultSavedQuery = function ( queryID ) {
650 this.savedQueriesModel.setDefault( queryID );
651 this._saveSavedQueries();
652 };
653
654 /**
655 * Load a saved query
656 *
657 * @param {string} queryID Query id
658 */
659 mw.rcfilters.Controller.prototype.applySavedQuery = function ( queryID ) {
660 var data, highlights,
661 queryItem = this.savedQueriesModel.getItemByID( queryID ),
662 currentMatchingQuery = this.findQueryMatchingCurrentState();
663
664 if (
665 queryItem &&
666 (
667 // If there's already a query, don't reload it
668 // if it's the same as the one that already exists
669 !currentMatchingQuery ||
670 currentMatchingQuery.getID() !== queryItem.getID()
671 )
672 ) {
673 data = queryItem.getData();
674 highlights = data.highlights;
675
676 // Backwards compatibility; initial version mispelled 'highlight' with 'highlights'
677 highlights.highlight = highlights.highlights || highlights.highlight;
678
679 // Update model state from filters
680 this.filtersModel.toggleFiltersSelected(
681 // Merge filters with sticky values
682 $.extend( true, {}, data.filters, this.filtersModel.getStickyFiltersState() )
683 );
684
685 // Update namespace inverted property
686 this.filtersModel.toggleInvertedNamespaces( !!Number( data.invert ) );
687
688 // Update highlight state
689 this.filtersModel.toggleHighlight( !!Number( highlights.highlight ) );
690 this.filtersModel.getItems().forEach( function ( filterItem ) {
691 var color = highlights[ filterItem.getName() ];
692 if ( color ) {
693 filterItem.setHighlightColor( color );
694 } else {
695 filterItem.clearHighlightColor();
696 }
697 } );
698
699 // Check all filter interactions
700 this.filtersModel.reassessFilterInteractions();
701
702 this.updateChangesList();
703
704 // Log filter grouping
705 this.trackFilterGroupings( 'savedfilters' );
706 }
707 };
708
709 /**
710 * Check whether the current filter and highlight state exists
711 * in the saved queries model.
712 *
713 * @return {boolean} Query exists
714 */
715 mw.rcfilters.Controller.prototype.findQueryMatchingCurrentState = function () {
716 var highlightedItems = {},
717 selectedState = this.filtersModel.getSelectedState();
718
719 // Prepare highlights of the current query
720 this.filtersModel.getItemsSupportingHighlights().forEach( function ( item ) {
721 highlightedItems[ item.getName() ] = item.getHighlightColor();
722 } );
723 highlightedItems.highlight = this.filtersModel.isHighlightEnabled();
724
725 // Remove sticky filters
726 this._deleteStickyValuesFromFilterState( selectedState );
727
728 return this.savedQueriesModel.findMatchingQuery(
729 {
730 filters: selectedState,
731 highlights: highlightedItems,
732 invert: this.filtersModel.areNamespacesInverted()
733 }
734 );
735 };
736
737 /**
738 * Delete sticky filters from given object
739 *
740 * @param {Object} filterState Filter state
741 */
742 mw.rcfilters.Controller.prototype._deleteStickyValuesFromFilterState = function ( filterState ) {
743 // Remove sticky filters
744 $.each( this.filtersModel.getStickyFiltersState(), function ( filterName ) {
745 delete filterState[ filterName ];
746 } );
747 };
748
749 /**
750 * Get an object representing the base state of parameters
751 * and highlights.
752 *
753 * This is meant to make sure that the saved queries that are
754 * in memory are always the same structure as what we would get
755 * by calling the current model's "getSelectedState" and by checking
756 * highlight items.
757 *
758 * In cases where a user saved a query when the system had a certain
759 * set of filters, and then a filter was added to the system, we want
760 * to make sure that the stored queries can still be comparable to
761 * the current state, which means that we need the base state for
762 * two operations:
763 *
764 * - Saved queries are stored in "minimal" view (only changed filters
765 * are stored); When we initialize the system, we merge each minimal
766 * query with the base state (using 'getNormalizedFilters') so all
767 * saved queries have the exact same structure as what we would get
768 * by checking the getSelectedState of the filter.
769 * - When we save the queries, we minimize the object to only represent
770 * whatever has actually changed, rather than store the entire
771 * object. To check what actually is different so we can store it,
772 * we need to obtain a base state to compare against, this is
773 * what #_getMinimalFilterList does
774 */
775 mw.rcfilters.Controller.prototype._buildBaseFilterState = function () {
776 var defaultParams = this.filtersModel.getDefaultParams(),
777 highlightedItems = {};
778
779 // Prepare highlights
780 this.filtersModel.getItemsSupportingHighlights().forEach( function ( item ) {
781 highlightedItems[ item.getName() ] = null;
782 } );
783 highlightedItems.highlight = false;
784
785 this.baseFilterState = {
786 filters: this.filtersModel.getFiltersFromParameters( defaultParams ),
787 highlights: highlightedItems,
788 invert: false
789 };
790 };
791
792 /**
793 * Get an object representing the base filter state of both
794 * filters and highlights. The structure is similar to what we use
795 * to store each query in the saved queries object:
796 * {
797 * filters: {
798 * filterName: (bool)
799 * },
800 * highlights: {
801 * filterName: (string|null)
802 * }
803 * }
804 *
805 * @return {Object} Object representing the base state of
806 * parameters and highlights
807 */
808 mw.rcfilters.Controller.prototype._getBaseFilterState = function () {
809 return this.baseFilterState;
810 };
811
812 /**
813 * Get an object that holds only the parameters and highlights that have
814 * values different than the base default value.
815 *
816 * This is the reverse of the normalization we do initially on loading and
817 * initializing the saved queries model.
818 *
819 * @param {Object} valuesObject Object representing the state of both
820 * filters and highlights in its normalized version, to be minimized.
821 * @return {Object} Minimal filters and highlights list
822 */
823 mw.rcfilters.Controller.prototype._getMinimalFilterList = function ( valuesObject ) {
824 var result = { filters: {}, highlights: {} },
825 baseState = this._getBaseFilterState();
826
827 // XOR results
828 $.each( valuesObject.filters, function ( name, value ) {
829 if ( baseState.filters !== undefined && baseState.filters[ name ] !== value ) {
830 result.filters[ name ] = value;
831 }
832 } );
833
834 $.each( valuesObject.highlights, function ( name, value ) {
835 if ( baseState.highlights !== undefined && baseState.highlights[ name ] !== value ) {
836 result.highlights[ name ] = value;
837 }
838 } );
839
840 return result;
841 };
842
843 /**
844 * Save the current state of the saved queries model with all
845 * query item representation in the user settings.
846 */
847 mw.rcfilters.Controller.prototype._saveSavedQueries = function () {
848 var stringified,
849 state = this.savedQueriesModel.getState(),
850 controller = this;
851
852 // Minimize before save
853 $.each( state.queries, function ( queryID, info ) {
854 state.queries[ queryID ].data = controller._getMinimalFilterList( info.data );
855 } );
856
857 // Stringify state
858 stringified = JSON.stringify( state );
859
860 if ( stringified.length > 65535 ) {
861 // Sanity check, since the preference can only hold that.
862 return;
863 }
864
865 // Save the preference
866 new mw.Api().saveOption( 'rcfilters-saved-queries', stringified );
867 // Update the preference for this session
868 mw.user.options.set( 'rcfilters-saved-queries', stringified );
869 };
870
871 /**
872 * Update sticky preferences with current model state
873 */
874 mw.rcfilters.Controller.prototype.updateStickyPreferences = function () {
875 // Update default sticky values with selected, whether they came from
876 // the initial defaults or from the URL value that is being normalized
877 this.updateDaysDefault( this.filtersModel.getGroup( 'days' ).getSelectedItems()[ 0 ].getParamName() );
878 this.updateLimitDefault( this.filtersModel.getGroup( 'limit' ).getSelectedItems()[ 0 ].getParamName() );
879
880 // TODO: Make these automatic by having the model go over sticky
881 // items and update their default values automatically
882 };
883
884 /**
885 * Update the limit default value
886 *
887 * param {number} newValue New value
888 */
889 mw.rcfilters.Controller.prototype.updateLimitDefault = function ( /* newValue */ ) {
890 // HACK: Temporarily remove this from being sticky
891 // See T172156
892
893 /*
894 if ( !$.isNumeric( newValue ) ) {
895 return;
896 }
897
898 newValue = Number( newValue );
899
900 if ( mw.user.options.get( 'rcfilters-rclimit' ) !== newValue ) {
901 // Save the preference
902 new mw.Api().saveOption( 'rcfilters-rclimit', newValue );
903 // Update the preference for this session
904 mw.user.options.set( 'rcfilters-rclimit', newValue );
905 }
906 */
907 return;
908 };
909
910 /**
911 * Update the days default value
912 *
913 * param {number} newValue New value
914 */
915 mw.rcfilters.Controller.prototype.updateDaysDefault = function ( /* newValue */ ) {
916 // HACK: Temporarily remove this from being sticky
917 // See T172156
918
919 /*
920 if ( !$.isNumeric( newValue ) ) {
921 return;
922 }
923
924 newValue = Number( newValue );
925
926 if ( mw.user.options.get( 'rcdays' ) !== newValue ) {
927 // Save the preference
928 new mw.Api().saveOption( 'rcdays', newValue );
929 // Update the preference for this session
930 mw.user.options.set( 'rcdays', newValue );
931 }
932 */
933 return;
934 };
935
936 /**
937 * Update the group by page default value
938 *
939 * @param {number} newValue New value
940 */
941 mw.rcfilters.Controller.prototype.updateGroupByPageDefault = function ( newValue ) {
942 if ( !$.isNumeric( newValue ) ) {
943 return;
944 }
945
946 newValue = Number( newValue );
947
948 if ( mw.user.options.get( 'usenewrc' ) !== newValue ) {
949 // Save the preference
950 new mw.Api().saveOption( 'usenewrc', newValue );
951 // Update the preference for this session
952 mw.user.options.set( 'usenewrc', newValue );
953 }
954 };
955
956 /**
957 * Synchronize the URL with the current state of the filters
958 * without adding an history entry.
959 */
960 mw.rcfilters.Controller.prototype.replaceUrl = function () {
961 mw.rcfilters.UriProcessor.static.replaceState( this._getUpdatedUri() );
962 };
963
964 /**
965 * Update filter state (selection and highlighting) based
966 * on current URL values.
967 *
968 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
969 * list based on the updated model.
970 */
971 mw.rcfilters.Controller.prototype.updateStateFromUrl = function ( fetchChangesList ) {
972 fetchChangesList = fetchChangesList === undefined ? true : !!fetchChangesList;
973
974 this.uriProcessor.updateModelBasedOnQuery( new mw.Uri().query );
975
976 // Update the sticky preferences, in case we received a value
977 // from the URL
978 this.updateStickyPreferences();
979
980 // Only update and fetch new results if it is requested
981 if ( fetchChangesList ) {
982 this.updateChangesList();
983 }
984 };
985
986 /**
987 * Update the list of changes and notify the model
988 *
989 * @param {boolean} [updateUrl=true] Whether the URL should be updated with the current state of the filters
990 * @param {Object} [params] Extra parameters to add to the API call
991 * @param {boolean} [isLiveUpdate=false] The purpose of this update is to show new results for the same filters
992 * @param {boolean} [invalidateCurrentChanges=true] Invalidate current changes by default (show spinner)
993 * @return {jQuery.Promise} Promise that is resolved when the update is complete
994 */
995 mw.rcfilters.Controller.prototype.updateChangesList = function ( updateUrl, params, isLiveUpdate, invalidateCurrentChanges ) {
996 updateUrl = updateUrl === undefined ? true : updateUrl;
997 invalidateCurrentChanges = invalidateCurrentChanges === undefined ? true : invalidateCurrentChanges;
998 if ( updateUrl ) {
999 this._updateURL( params );
1000 }
1001 if ( invalidateCurrentChanges ) {
1002 this.changesListModel.invalidate();
1003 }
1004 this.changesListModel.setNewChangesExist( false );
1005 this.updatingChangesList = true;
1006 return this._fetchChangesList()
1007 .then(
1008 // Success
1009 function ( pieces ) {
1010 var $changesListContent = pieces.changes,
1011 $fieldset = pieces.fieldset;
1012 this.changesListModel.update( $changesListContent, $fieldset, false, isLiveUpdate );
1013 }.bind( this )
1014 // Do nothing for failure
1015 )
1016 .always( function () {
1017 this.updatingChangesList = false;
1018 }.bind( this ) );
1019 };
1020
1021 /**
1022 * Get an object representing the default parameter state, whether
1023 * it is from the model defaults or from the saved queries.
1024 *
1025 * @return {Object} Default parameters
1026 */
1027 mw.rcfilters.Controller.prototype._getDefaultParams = function () {
1028 var data, queryHighlights,
1029 savedParams = {},
1030 savedHighlights = {},
1031 defaultSavedQueryItem = this.savedQueriesModel.getItemByID( this.savedQueriesModel.getDefault() );
1032
1033 if ( defaultSavedQueryItem ) {
1034 data = defaultSavedQueryItem.getData();
1035
1036 queryHighlights = data.highlights || {};
1037 savedParams = this.filtersModel.getParametersFromFilters(
1038 // Merge filters with sticky values
1039 $.extend( true, {}, data.filters, this.filtersModel.getStickyFiltersState() )
1040 );
1041
1042 // Translate highlights to parameters
1043 savedHighlights.highlight = String( Number( queryHighlights.highlight ) );
1044 $.each( queryHighlights, function ( filterName, color ) {
1045 if ( filterName !== 'highlights' ) {
1046 savedHighlights[ filterName + '_color' ] = color;
1047 }
1048 } );
1049
1050 return $.extend( true, {}, savedParams, savedHighlights );
1051 }
1052
1053 return this.filtersModel.getDefaultParams();
1054 };
1055
1056 /**
1057 * Update the URL of the page to reflect current filters
1058 *
1059 * This should not be called directly from outside the controller.
1060 * If an action requires changing the URL, it should either use the
1061 * highlighting actions below, or call #updateChangesList which does
1062 * the uri corrections already.
1063 *
1064 * @param {Object} [params] Extra parameters to add to the API call
1065 */
1066 mw.rcfilters.Controller.prototype._updateURL = function ( params ) {
1067 var currentUri = new mw.Uri(),
1068 updatedUri = this._getUpdatedUri();
1069
1070 updatedUri.extend( params || {} );
1071
1072 if (
1073 this.uriProcessor.getVersion( currentUri.query ) !== 2 ||
1074 this.uriProcessor.isNewState( currentUri.query, updatedUri.query )
1075 ) {
1076 mw.rcfilters.UriProcessor.static.replaceState( updatedUri );
1077 }
1078 };
1079
1080 /**
1081 * Get an updated mw.Uri object based on the model state
1082 *
1083 * @return {mw.Uri} Updated Uri
1084 */
1085 mw.rcfilters.Controller.prototype._getUpdatedUri = function () {
1086 var uri = new mw.Uri();
1087
1088 // Minimize url
1089 uri.query = this.uriProcessor.minimizeQuery(
1090 $.extend(
1091 true,
1092 {},
1093 // We want to retain unrecognized params
1094 // The uri params from model will override
1095 // any recognized value in the current uri
1096 // query, retain unrecognized params, and
1097 // the result will then be minimized
1098 uri.query,
1099 this.uriProcessor.getUriParametersFromModel(),
1100 { urlversion: '2' }
1101 )
1102 );
1103
1104 return uri;
1105 };
1106
1107 /**
1108 * Fetch the list of changes from the server for the current filters
1109 *
1110 * @param {string} [counterId='updateChangesList'] Id for this request. To allow concurrent requests
1111 * not to invalidate each other.
1112 * @param {Object} [params={}] Parameters to add to the query
1113 *
1114 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1115 * or with a string denoting no results.
1116 */
1117 mw.rcfilters.Controller.prototype._fetchChangesList = function ( counterId, params ) {
1118 var uri = this._getUpdatedUri(),
1119 stickyParams = this.filtersModel.getStickyParams(),
1120 requestId,
1121 latestRequest;
1122
1123 counterId = counterId || 'updateChangesList';
1124 params = params || {};
1125
1126 uri.extend( params );
1127
1128 this.requestCounter[ counterId ] = this.requestCounter[ counterId ] || 0;
1129 requestId = ++this.requestCounter[ counterId ];
1130 latestRequest = function () {
1131 return requestId === this.requestCounter[ counterId ];
1132 }.bind( this );
1133
1134 // Sticky parameters override the URL params
1135 // this is to make sure that whether we represent
1136 // the sticky params in the URL or not (they may
1137 // be normalized out) the sticky parameters are
1138 // always being sent to the server with their
1139 // current/default values
1140 uri.extend( stickyParams );
1141
1142 return $.ajax( uri.toString(), { contentType: 'html' } )
1143 .then(
1144 // Success
1145 function ( html ) {
1146 var $parsed;
1147 if ( !latestRequest() ) {
1148 return $.Deferred().reject();
1149 }
1150
1151 $parsed = $( $.parseHTML( html ) );
1152
1153 return {
1154 // Changes list
1155 changes: $parsed.find( '.mw-changeslist' ).first().contents(),
1156 // Fieldset
1157 fieldset: $parsed.find( 'fieldset.rcoptions' ).first()
1158 };
1159 },
1160 // Failure
1161 function ( responseObj ) {
1162 var $parsed;
1163
1164 if ( !latestRequest() ) {
1165 return $.Deferred().reject();
1166 }
1167
1168 $parsed = $( $.parseHTML( responseObj.responseText ) );
1169
1170 // Force a resolve state to this promise
1171 return $.Deferred().resolve( {
1172 changes: 'NO_RESULTS',
1173 fieldset: $parsed.find( 'fieldset.rcoptions' ).first()
1174 } ).promise();
1175 }
1176 );
1177 };
1178
1179 /**
1180 * Track usage of highlight feature
1181 *
1182 * @param {string} action
1183 * @param {Array|Object|string} filters
1184 */
1185 mw.rcfilters.Controller.prototype._trackHighlight = function ( action, filters ) {
1186 filters = typeof filters === 'string' ? { name: filters } : filters;
1187 filters = !Array.isArray( filters ) ? [ filters ] : filters;
1188 mw.track(
1189 'event.ChangesListHighlights',
1190 {
1191 action: action,
1192 filters: filters,
1193 userId: mw.user.getId()
1194 }
1195 );
1196 };
1197
1198 /**
1199 * Track filter grouping usage
1200 *
1201 * @param {string} action Action taken
1202 */
1203 mw.rcfilters.Controller.prototype.trackFilterGroupings = function ( action ) {
1204 var controller = this,
1205 rightNow = new Date().getTime(),
1206 randomIdentifier = String( mw.user.sessionId() ) + String( rightNow ) + String( Math.random() ),
1207 // Get all current filters
1208 filters = this.filtersModel.getSelectedItems().map( function ( item ) {
1209 return item.getName();
1210 } );
1211
1212 action = action || 'filtermenu';
1213
1214 // Check if these filters were the ones we just logged previously
1215 // (Don't log the same grouping twice, in case the user opens/closes)
1216 // the menu without action, or with the same result
1217 if (
1218 // Only log if the two arrays are different in size
1219 filters.length !== this.prevLoggedItems.length ||
1220 // Or if any filters are not the same as the cached filters
1221 filters.some( function ( filterName ) {
1222 return controller.prevLoggedItems.indexOf( filterName ) === -1;
1223 } ) ||
1224 // Or if any cached filters are not the same as given filters
1225 this.prevLoggedItems.some( function ( filterName ) {
1226 return filters.indexOf( filterName ) === -1;
1227 } )
1228 ) {
1229 filters.forEach( function ( filterName ) {
1230 mw.track(
1231 'event.ChangesListFilterGrouping',
1232 {
1233 action: action,
1234 groupIdentifier: randomIdentifier,
1235 filter: filterName,
1236 userId: mw.user.getId()
1237 }
1238 );
1239 } );
1240
1241 // Cache the filter names
1242 this.prevLoggedItems = filters;
1243 }
1244 };
1245 }( mediaWiki, jQuery ) );