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