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