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