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