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