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