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