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