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