b07df579e39327237ca8af491af6e64217272f22
[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._scheduleLiveUpdate();
267 };
268
269 /**
270 * Create filter data from a number, for the filters that are numerical value
271 *
272 * @param {Number} num Number
273 * @param {Number} numForDisplay Number for the label
274 * @return {Object} Filter data
275 */
276 mw.rcfilters.Controller.prototype._createFilterDataFromNumber = function ( num, numForDisplay ) {
277 return {
278 name: String( num ),
279 label: mw.language.convertNumber( numForDisplay )
280 };
281 };
282
283 /**
284 * Add an arbitrary values to groups that allow arbitrary values
285 *
286 * @param {Object} groupData Group data
287 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
288 */
289 mw.rcfilters.Controller.prototype.addNumberValuesToGroup = function ( groupData, arbitraryValues ) {
290 var controller = this,
291 normalizeWithinRange = function ( range, val ) {
292 if ( val < range.min ) {
293 return range.min; // Min
294 } else if ( val >= range.max ) {
295 return range.max; // Max
296 }
297 return val;
298 };
299
300 arbitraryValues = Array.isArray( arbitraryValues ) ? arbitraryValues : [ arbitraryValues ];
301
302 // Normalize the arbitrary values and the default value for a range
303 if ( groupData.range ) {
304 arbitraryValues = arbitraryValues.map( function ( val ) {
305 return normalizeWithinRange( groupData.range, val );
306 } );
307
308 // Normalize the default, since that's user defined
309 if ( groupData.default !== undefined ) {
310 groupData.default = String( normalizeWithinRange( groupData.range, groupData.default ) );
311 }
312 }
313
314 // This is only true for single_option group
315 // We assume these are the only groups that will allow for
316 // arbitrary, since it doesn't make any sense for the other
317 // groups.
318 arbitraryValues.forEach( function ( val ) {
319 if (
320 // If the group allows for arbitrary data
321 groupData.allowArbitrary &&
322 // and it is single_option (or string_options, but we
323 // don't have cases of those yet, nor do we plan to)
324 groupData.type === 'single_option' &&
325 // and, if there is a validate method and it passes on
326 // the data
327 ( !groupData.validate || groupData.validate( val ) ) &&
328 // but if that value isn't already in the definition
329 groupData.filters
330 .map( function ( filterData ) {
331 return String( filterData.name );
332 } )
333 .indexOf( String( val ) ) === -1
334 ) {
335 // Add the filter information
336 groupData.filters.push( controller._createFilterDataFromNumber(
337 val,
338 groupData.numToLabelFunc ?
339 groupData.numToLabelFunc( val ) :
340 val
341 ) );
342
343 // If there's a sort function set up, re-sort the values
344 if ( groupData.sortFunc ) {
345 groupData.filters.sort( groupData.sortFunc );
346 }
347 }
348 } );
349 };
350
351 /**
352 * Switch the view of the filters model
353 *
354 * @param {string} view Requested view
355 */
356 mw.rcfilters.Controller.prototype.switchView = function ( view ) {
357 this.filtersModel.switchView( view );
358 };
359
360 /**
361 * Reset to default filters
362 */
363 mw.rcfilters.Controller.prototype.resetToDefaults = function () {
364 this.uriProcessor.updateModelBasedOnQuery( this._getDefaultParams() );
365
366 this.updateChangesList();
367 };
368
369 /**
370 * Empty all selected filters
371 */
372 mw.rcfilters.Controller.prototype.emptyFilters = function () {
373 var highlightedFilterNames = this.filtersModel
374 .getHighlightedItems()
375 .map( function ( filterItem ) { return { name: filterItem.getName() }; } );
376
377 this.filtersModel.emptyAllFilters();
378 this.filtersModel.clearAllHighlightColors();
379 // Check all filter interactions
380 this.filtersModel.reassessFilterInteractions();
381
382 this.updateChangesList();
383
384 if ( highlightedFilterNames ) {
385 this._trackHighlight( 'clearAll', highlightedFilterNames );
386 }
387 };
388
389 /**
390 * Update the selected state of a filter
391 *
392 * @param {string} filterName Filter name
393 * @param {boolean} [isSelected] Filter selected state
394 */
395 mw.rcfilters.Controller.prototype.toggleFilterSelect = function ( filterName, isSelected ) {
396 var filterItem = this.filtersModel.getItemByName( filterName );
397
398 if ( !filterItem ) {
399 // If no filter was found, break
400 return;
401 }
402
403 isSelected = isSelected === undefined ? !filterItem.isSelected() : isSelected;
404
405 if ( filterItem.isSelected() !== isSelected ) {
406 this.filtersModel.toggleFilterSelected( filterName, isSelected );
407
408 this.updateChangesList();
409
410 // Check filter interactions
411 this.filtersModel.reassessFilterInteractions( filterItem );
412 }
413 };
414
415 /**
416 * Clear both highlight and selection of a filter
417 *
418 * @param {string} filterName Name of the filter item
419 */
420 mw.rcfilters.Controller.prototype.clearFilter = function ( filterName ) {
421 var filterItem = this.filtersModel.getItemByName( filterName ),
422 isHighlighted = filterItem.isHighlighted();
423
424 if ( filterItem.isSelected() || isHighlighted ) {
425 this.filtersModel.clearHighlightColor( filterName );
426 this.filtersModel.toggleFilterSelected( filterName, false );
427 this.updateChangesList();
428 this.filtersModel.reassessFilterInteractions( filterItem );
429
430 // Log filter grouping
431 this.trackFilterGroupings( 'removefilter' );
432 }
433
434 if ( isHighlighted ) {
435 this._trackHighlight( 'clear', filterName );
436 }
437 };
438
439 /**
440 * Toggle the highlight feature on and off
441 */
442 mw.rcfilters.Controller.prototype.toggleHighlight = function () {
443 this.filtersModel.toggleHighlight();
444 this._updateURL();
445
446 if ( this.filtersModel.isHighlightEnabled() ) {
447 mw.hook( 'RcFilters.highlight.enable' ).fire();
448 }
449 };
450
451 /**
452 * Toggle the namespaces inverted feature on and off
453 */
454 mw.rcfilters.Controller.prototype.toggleInvertedNamespaces = function () {
455 this.filtersModel.toggleInvertedNamespaces();
456
457 if (
458 this.filtersModel.getFiltersByView( 'namespaces' ).filter(
459 function ( filterItem ) { return filterItem.isSelected(); }
460 ).length
461 ) {
462 // Only re-fetch results if there are namespace items that are actually selected
463 this.updateChangesList();
464 }
465 };
466
467 /**
468 * Set the highlight color for a filter item
469 *
470 * @param {string} filterName Name of the filter item
471 * @param {string} color Selected color
472 */
473 mw.rcfilters.Controller.prototype.setHighlightColor = function ( filterName, color ) {
474 this.filtersModel.setHighlightColor( filterName, color );
475 this._updateURL();
476 this._trackHighlight( 'set', { name: filterName, color: color } );
477 };
478
479 /**
480 * Clear highlight for a filter item
481 *
482 * @param {string} filterName Name of the filter item
483 */
484 mw.rcfilters.Controller.prototype.clearHighlightColor = function ( filterName ) {
485 this.filtersModel.clearHighlightColor( filterName );
486 this._updateURL();
487 this._trackHighlight( 'clear', filterName );
488 };
489
490 /**
491 * Enable or disable live updates.
492 * @param {boolean} enable True to enable, false to disable
493 */
494 mw.rcfilters.Controller.prototype.toggleLiveUpdate = function ( enable ) {
495 this.changesListModel.toggleLiveUpdate( enable );
496 if ( this.changesListModel.getLiveUpdate() && this.changesListModel.getNewChangesExist() ) {
497 this.updateChangesList( null, this.LIVE_UPDATE );
498 }
499 };
500
501 /**
502 * Set a timeout for the next live update.
503 * @private
504 */
505 mw.rcfilters.Controller.prototype._scheduleLiveUpdate = function () {
506 setTimeout( this._doLiveUpdate.bind( this ), 3000 );
507 };
508
509 /**
510 * Perform a live update.
511 * @private
512 */
513 mw.rcfilters.Controller.prototype._doLiveUpdate = function () {
514 if ( !this._shouldCheckForNewChanges() ) {
515 // skip this turn and check back later
516 this._scheduleLiveUpdate();
517 return;
518 }
519
520 this._checkForNewChanges()
521 .then( function ( newChanges ) {
522 if ( !this._shouldCheckForNewChanges() ) {
523 // by the time the response is received,
524 // it may not be appropriate anymore
525 return;
526 }
527
528 if ( newChanges ) {
529 if ( this.changesListModel.getLiveUpdate() ) {
530 return this.updateChangesList( null, this.LIVE_UPDATE );
531 } else {
532 this.changesListModel.setNewChangesExist( true );
533 }
534 }
535 }.bind( this ) )
536 .always( this._scheduleLiveUpdate.bind( this ) );
537 };
538
539 /**
540 * @return {boolean} It's appropriate to check for new changes now
541 * @private
542 */
543 mw.rcfilters.Controller.prototype._shouldCheckForNewChanges = function () {
544 return !document.hidden &&
545 !this.filtersModel.hasConflict() &&
546 !this.changesListModel.getNewChangesExist() &&
547 !this.updatingChangesList &&
548 this.changesListModel.getNextFrom();
549 };
550
551 /**
552 * Check if new changes, newer than those currently shown, are available
553 *
554 * @return {jQuery.Promise} Promise object that resolves with a bool
555 * specifying if there are new changes or not
556 *
557 * @private
558 */
559 mw.rcfilters.Controller.prototype._checkForNewChanges = function () {
560 var params = {
561 limit: 1,
562 peek: 1, // bypasses ChangesList specific UI
563 from: this.changesListModel.getNextFrom()
564 };
565 return this._queryChangesList( 'liveUpdate', params ).then(
566 function ( data ) {
567 // no result is 204 with the 'peek' param
568 return data.status === 200;
569 }
570 );
571 };
572
573 /**
574 * Show the new changes
575 *
576 * @return {jQuery.Promise} Promise object that resolves after
577 * fetching and showing the new changes
578 */
579 mw.rcfilters.Controller.prototype.showNewChanges = function () {
580 return this.updateChangesList( null, this.SHOW_NEW_CHANGES );
581 };
582
583 /**
584 * Save the current model state as a saved query
585 *
586 * @param {string} [label] Label of the saved query
587 * @param {boolean} [setAsDefault=false] This query should be set as the default
588 */
589 mw.rcfilters.Controller.prototype.saveCurrentQuery = function ( label, setAsDefault ) {
590 var queryID,
591 highlightedItems = {},
592 highlightEnabled = this.filtersModel.isHighlightEnabled(),
593 selectedState = this.filtersModel.getSelectedState();
594
595 // Prepare highlights
596 this.filtersModel.getHighlightedItems().forEach( function ( item ) {
597 highlightedItems[ item.getName() ] = highlightEnabled ?
598 item.getHighlightColor() : null;
599 } );
600 // These are filter states; highlight is stored as boolean
601 highlightedItems.highlight = this.filtersModel.isHighlightEnabled();
602
603 // Delete all excluded filters
604 this._deleteExcludedValuesFromFilterState( selectedState );
605
606 // Add item
607 queryID = this.savedQueriesModel.addNewQuery(
608 label || mw.msg( 'rcfilters-savedqueries-defaultlabel' ),
609 {
610 filters: selectedState,
611 highlights: highlightedItems,
612 invert: this.filtersModel.areNamespacesInverted()
613 }
614 );
615
616 if ( setAsDefault ) {
617 this.savedQueriesModel.setDefault( queryID );
618 }
619
620 // Save item
621 this._saveSavedQueries();
622 };
623
624 /**
625 * Remove a saved query
626 *
627 * @param {string} queryID Query id
628 */
629 mw.rcfilters.Controller.prototype.removeSavedQuery = function ( queryID ) {
630 this.savedQueriesModel.removeQuery( queryID );
631
632 this._saveSavedQueries();
633 };
634
635 /**
636 * Rename a saved query
637 *
638 * @param {string} queryID Query id
639 * @param {string} newLabel New label for the query
640 */
641 mw.rcfilters.Controller.prototype.renameSavedQuery = function ( queryID, newLabel ) {
642 var queryItem = this.savedQueriesModel.getItemByID( queryID );
643
644 if ( queryItem ) {
645 queryItem.updateLabel( newLabel );
646 }
647 this._saveSavedQueries();
648 };
649
650 /**
651 * Set a saved query as default
652 *
653 * @param {string} queryID Query Id. If null is given, default
654 * query is reset.
655 */
656 mw.rcfilters.Controller.prototype.setDefaultSavedQuery = function ( queryID ) {
657 this.savedQueriesModel.setDefault( queryID );
658 this._saveSavedQueries();
659 };
660
661 /**
662 * Load a saved query
663 *
664 * @param {string} queryID Query id
665 */
666 mw.rcfilters.Controller.prototype.applySavedQuery = function ( queryID ) {
667 var data, highlights,
668 queryItem = this.savedQueriesModel.getItemByID( queryID ),
669 currentMatchingQuery = this.findQueryMatchingCurrentState();
670
671 if (
672 queryItem &&
673 (
674 // If there's already a query, don't reload it
675 // if it's the same as the one that already exists
676 !currentMatchingQuery ||
677 currentMatchingQuery.getID() !== queryItem.getID()
678 )
679 ) {
680 data = queryItem.getData();
681 highlights = data.highlights;
682
683 // Backwards compatibility; initial version mispelled 'highlight' with 'highlights'
684 highlights.highlight = highlights.highlights || highlights.highlight;
685
686 // Update model state from filters
687 this.filtersModel.toggleFiltersSelected(
688 // Merge filters with excluded values
689 $.extend( true, {}, data.filters, this.filtersModel.getExcludedFiltersState() )
690 );
691
692 // Update namespace inverted property
693 this.filtersModel.toggleInvertedNamespaces( !!Number( data.invert ) );
694
695 // Update highlight state
696 this.filtersModel.toggleHighlight( !!Number( highlights.highlight ) );
697 this.filtersModel.getItems().forEach( function ( filterItem ) {
698 var color = highlights[ filterItem.getName() ];
699 if ( color ) {
700 filterItem.setHighlightColor( color );
701 } else {
702 filterItem.clearHighlightColor();
703 }
704 } );
705
706 // Check all filter interactions
707 this.filtersModel.reassessFilterInteractions();
708
709 this.updateChangesList();
710
711 // Log filter grouping
712 this.trackFilterGroupings( 'savedfilters' );
713 }
714 };
715
716 /**
717 * Check whether the current filter and highlight state exists
718 * in the saved queries model.
719 *
720 * @return {boolean} Query exists
721 */
722 mw.rcfilters.Controller.prototype.findQueryMatchingCurrentState = function () {
723 var highlightedItems = {},
724 selectedState = this.filtersModel.getSelectedState();
725
726 // Prepare highlights of the current query
727 this.filtersModel.getItemsSupportingHighlights().forEach( function ( item ) {
728 highlightedItems[ item.getName() ] = item.getHighlightColor();
729 } );
730 highlightedItems.highlight = this.filtersModel.isHighlightEnabled();
731
732 // Remove anything that should be excluded from the saved query
733 // this includes sticky filters and filters marked with 'excludedFromSavedQueries'
734 this._deleteExcludedValuesFromFilterState( selectedState );
735
736 return this.savedQueriesModel.findMatchingQuery(
737 {
738 filters: selectedState,
739 highlights: highlightedItems,
740 invert: this.filtersModel.areNamespacesInverted()
741 }
742 );
743 };
744
745 /**
746 * Delete sticky filters from given object
747 *
748 * @param {Object} filterState Filter state
749 */
750 mw.rcfilters.Controller.prototype._deleteExcludedValuesFromFilterState = function ( filterState ) {
751 // Remove excluded filters
752 $.each( this.filtersModel.getExcludedFiltersState(), function ( filterName ) {
753 delete filterState[ filterName ];
754 } );
755 };
756
757 /**
758 * Get an object representing the base state of parameters
759 * and highlights.
760 *
761 * This is meant to make sure that the saved queries that are
762 * in memory are always the same structure as what we would get
763 * by calling the current model's "getSelectedState" and by checking
764 * highlight items.
765 *
766 * In cases where a user saved a query when the system had a certain
767 * set of filters, and then a filter was added to the system, we want
768 * to make sure that the stored queries can still be comparable to
769 * the current state, which means that we need the base state for
770 * two operations:
771 *
772 * - Saved queries are stored in "minimal" view (only changed filters
773 * are stored); When we initialize the system, we merge each minimal
774 * query with the base state (using 'getNormalizedFilters') so all
775 * saved queries have the exact same structure as what we would get
776 * by checking the getSelectedState of the filter.
777 * - When we save the queries, we minimize the object to only represent
778 * whatever has actually changed, rather than store the entire
779 * object. To check what actually is different so we can store it,
780 * we need to obtain a base state to compare against, this is
781 * what #_getMinimalFilterList does
782 */
783 mw.rcfilters.Controller.prototype._buildBaseFilterState = function () {
784 var defaultParams = this.filtersModel.getDefaultParams(),
785 highlightedItems = {};
786
787 // Prepare highlights
788 this.filtersModel.getItemsSupportingHighlights().forEach( function ( item ) {
789 highlightedItems[ item.getName() ] = null;
790 } );
791 highlightedItems.highlight = false;
792
793 this.baseFilterState = {
794 filters: this.filtersModel.getFiltersFromParameters( defaultParams ),
795 highlights: highlightedItems,
796 invert: false
797 };
798 };
799
800 /**
801 * Get an object representing the base filter state of both
802 * filters and highlights. The structure is similar to what we use
803 * to store each query in the saved queries object:
804 * {
805 * filters: {
806 * filterName: (bool)
807 * },
808 * highlights: {
809 * filterName: (string|null)
810 * }
811 * }
812 *
813 * @return {Object} Object representing the base state of
814 * parameters and highlights
815 */
816 mw.rcfilters.Controller.prototype._getBaseFilterState = function () {
817 return this.baseFilterState;
818 };
819
820 /**
821 * Get an object that holds only the parameters and highlights that have
822 * values different than the base default value.
823 *
824 * This is the reverse of the normalization we do initially on loading and
825 * initializing the saved queries model.
826 *
827 * @param {Object} valuesObject Object representing the state of both
828 * filters and highlights in its normalized version, to be minimized.
829 * @return {Object} Minimal filters and highlights list
830 */
831 mw.rcfilters.Controller.prototype._getMinimalFilterList = function ( valuesObject ) {
832 var result = { filters: {}, highlights: {}, invert: valuesObject.invert },
833 baseState = this._getBaseFilterState();
834
835 // XOR results
836 $.each( valuesObject.filters, function ( name, value ) {
837 if ( baseState.filters !== undefined && baseState.filters[ name ] !== value ) {
838 result.filters[ name ] = value;
839 }
840 } );
841
842 $.each( valuesObject.highlights, function ( name, value ) {
843 if ( baseState.highlights !== undefined && baseState.highlights[ name ] !== value ) {
844 result.highlights[ name ] = value;
845 }
846 } );
847
848 return result;
849 };
850
851 /**
852 * Save the current state of the saved queries model with all
853 * query item representation in the user settings.
854 */
855 mw.rcfilters.Controller.prototype._saveSavedQueries = function () {
856 var stringified,
857 state = this.savedQueriesModel.getState(),
858 controller = this;
859
860 // Minimize before save
861 $.each( state.queries, function ( queryID, info ) {
862 state.queries[ queryID ].data = controller._getMinimalFilterList( info.data );
863 } );
864
865 // Stringify state
866 stringified = JSON.stringify( state );
867
868 if ( $.byteLength( stringified ) > 65535 ) {
869 // Sanity check, since the preference can only hold that.
870 return;
871 }
872
873 // Save the preference
874 new mw.Api().saveOption( this.savedQueriesPreferenceName, stringified );
875 // Update the preference for this session
876 mw.user.options.set( this.savedQueriesPreferenceName, stringified );
877 };
878
879 /**
880 * Update sticky preferences with current model state
881 */
882 mw.rcfilters.Controller.prototype.updateStickyPreferences = function () {
883 // Update default sticky values with selected, whether they came from
884 // the initial defaults or from the URL value that is being normalized
885 this.updateDaysDefault( this.filtersModel.getGroup( 'days' ).getSelectedItems()[ 0 ].getParamName() );
886 this.updateLimitDefault( this.filtersModel.getGroup( 'limit' ).getSelectedItems()[ 0 ].getParamName() );
887
888 // TODO: Make these automatic by having the model go over sticky
889 // items and update their default values automatically
890 };
891
892 /**
893 * Update the limit default value
894 *
895 * param {number} newValue New value
896 */
897 mw.rcfilters.Controller.prototype.updateLimitDefault = function ( /* newValue */ ) {
898 // HACK: Temporarily remove this from being sticky
899 // See T172156
900
901 /*
902 if ( !$.isNumeric( newValue ) ) {
903 return;
904 }
905
906 newValue = Number( newValue );
907
908 if ( mw.user.options.get( 'rcfilters-rclimit' ) !== newValue ) {
909 // Save the preference
910 new mw.Api().saveOption( 'rcfilters-rclimit', newValue );
911 // Update the preference for this session
912 mw.user.options.set( 'rcfilters-rclimit', newValue );
913 }
914 */
915 return;
916 };
917
918 /**
919 * Update the days default value
920 *
921 * param {number} newValue New value
922 */
923 mw.rcfilters.Controller.prototype.updateDaysDefault = function ( /* newValue */ ) {
924 // HACK: Temporarily remove this from being sticky
925 // See T172156
926
927 /*
928 if ( !$.isNumeric( newValue ) ) {
929 return;
930 }
931
932 newValue = Number( newValue );
933
934 if ( mw.user.options.get( 'rcdays' ) !== newValue ) {
935 // Save the preference
936 new mw.Api().saveOption( 'rcdays', newValue );
937 // Update the preference for this session
938 mw.user.options.set( 'rcdays', newValue );
939 }
940 */
941 return;
942 };
943
944 /**
945 * Update the group by page default value
946 *
947 * @param {number} newValue New value
948 */
949 mw.rcfilters.Controller.prototype.updateGroupByPageDefault = function ( newValue ) {
950 if ( !$.isNumeric( newValue ) ) {
951 return;
952 }
953
954 newValue = Number( newValue );
955
956 if ( mw.user.options.get( 'usenewrc' ) !== newValue ) {
957 // Save the preference
958 new mw.Api().saveOption( 'usenewrc', newValue );
959 // Update the preference for this session
960 mw.user.options.set( 'usenewrc', newValue );
961 }
962 };
963
964 /**
965 * Synchronize the URL with the current state of the filters
966 * without adding an history entry.
967 */
968 mw.rcfilters.Controller.prototype.replaceUrl = function () {
969 mw.rcfilters.UriProcessor.static.replaceState( this._getUpdatedUri() );
970 };
971
972 /**
973 * Update filter state (selection and highlighting) based
974 * on current URL values.
975 *
976 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
977 * list based on the updated model.
978 */
979 mw.rcfilters.Controller.prototype.updateStateFromUrl = function ( fetchChangesList ) {
980 fetchChangesList = fetchChangesList === undefined ? true : !!fetchChangesList;
981
982 this.uriProcessor.updateModelBasedOnQuery( new mw.Uri().query );
983
984 // Update the sticky preferences, in case we received a value
985 // from the URL
986 this.updateStickyPreferences();
987
988 // Only update and fetch new results if it is requested
989 if ( fetchChangesList ) {
990 this.updateChangesList();
991 }
992 };
993
994 /**
995 * Update the list of changes and notify the model
996 *
997 * @param {Object} [params] Extra parameters to add to the API call
998 * @param {string} [updateMode='filterChange'] One of 'filterChange', 'liveUpdate', 'showNewChanges', 'markSeen'
999 * @return {jQuery.Promise} Promise that is resolved when the update is complete
1000 */
1001 mw.rcfilters.Controller.prototype.updateChangesList = function ( params, updateMode ) {
1002 updateMode = updateMode === undefined ? this.FILTER_CHANGE : updateMode;
1003
1004 if ( updateMode === this.FILTER_CHANGE ) {
1005 this._updateURL( params );
1006 }
1007 if ( updateMode === this.FILTER_CHANGE || updateMode === this.SHOW_NEW_CHANGES ) {
1008 this.changesListModel.invalidate();
1009 }
1010 this.changesListModel.setNewChangesExist( false );
1011 this.updatingChangesList = true;
1012 return this._fetchChangesList()
1013 .then(
1014 // Success
1015 function ( pieces ) {
1016 var $changesListContent = pieces.changes,
1017 $fieldset = pieces.fieldset;
1018 this.changesListModel.update(
1019 $changesListContent,
1020 $fieldset,
1021 false,
1022 // separator between old and new changes
1023 updateMode === this.SHOW_NEW_CHANGES || updateMode === this.LIVE_UPDATE
1024 );
1025 }.bind( this )
1026 // Do nothing for failure
1027 )
1028 .always( function () {
1029 this.updatingChangesList = false;
1030 }.bind( this ) );
1031 };
1032
1033 /**
1034 * Get an object representing the default parameter state, whether
1035 * it is from the model defaults or from the saved queries.
1036 *
1037 * @return {Object} Default parameters
1038 */
1039 mw.rcfilters.Controller.prototype._getDefaultParams = function () {
1040 var data, queryHighlights,
1041 savedParams = {},
1042 savedHighlights = {},
1043 defaultSavedQueryItem = !mw.user.isAnon() && this.savedQueriesModel.getItemByID( this.savedQueriesModel.getDefault() );
1044
1045 if ( defaultSavedQueryItem ) {
1046 data = defaultSavedQueryItem.getData();
1047
1048 queryHighlights = data.highlights || {};
1049 savedParams = this.filtersModel.getParametersFromFilters(
1050 // Merge filters with sticky values
1051 $.extend( true, {}, data.filters, this.filtersModel.getStickyFiltersState() )
1052 );
1053
1054 // Translate highlights to parameters
1055 savedHighlights.highlight = String( Number( queryHighlights.highlight ) );
1056 $.each( queryHighlights, function ( filterName, color ) {
1057 if ( filterName !== 'highlights' ) {
1058 savedHighlights[ filterName + '_color' ] = color;
1059 }
1060 } );
1061
1062 return $.extend( true, {}, savedParams, savedHighlights, { invert: String( Number( data.invert || 0 ) ) } );
1063 }
1064
1065 return this.filtersModel.getDefaultParams();
1066 };
1067
1068 /**
1069 * Update the URL of the page to reflect current filters
1070 *
1071 * This should not be called directly from outside the controller.
1072 * If an action requires changing the URL, it should either use the
1073 * highlighting actions below, or call #updateChangesList which does
1074 * the uri corrections already.
1075 *
1076 * @param {Object} [params] Extra parameters to add to the API call
1077 */
1078 mw.rcfilters.Controller.prototype._updateURL = function ( params ) {
1079 var currentUri = new mw.Uri(),
1080 updatedUri = this._getUpdatedUri();
1081
1082 updatedUri.extend( params || {} );
1083
1084 if (
1085 this.uriProcessor.getVersion( currentUri.query ) !== 2 ||
1086 this.uriProcessor.isNewState( currentUri.query, updatedUri.query )
1087 ) {
1088 mw.rcfilters.UriProcessor.static.replaceState( updatedUri );
1089 }
1090 };
1091
1092 /**
1093 * Get an updated mw.Uri object based on the model state
1094 *
1095 * @return {mw.Uri} Updated Uri
1096 */
1097 mw.rcfilters.Controller.prototype._getUpdatedUri = function () {
1098 var uri = new mw.Uri();
1099
1100 // Minimize url
1101 uri.query = this.uriProcessor.minimizeQuery(
1102 $.extend(
1103 true,
1104 {},
1105 // We want to retain unrecognized params
1106 // The uri params from model will override
1107 // any recognized value in the current uri
1108 // query, retain unrecognized params, and
1109 // the result will then be minimized
1110 uri.query,
1111 this.uriProcessor.getUriParametersFromModel(),
1112 { urlversion: '2' }
1113 )
1114 );
1115
1116 return uri;
1117 };
1118
1119 /**
1120 * Query the list of changes from the server for the current filters
1121 *
1122 * @param {string} counterId Id for this request. To allow concurrent requests
1123 * not to invalidate each other.
1124 * @param {Object} [params={}] Parameters to add to the query
1125 *
1126 * @return {jQuery.Promise} Promise object resolved with { content, status }
1127 */
1128 mw.rcfilters.Controller.prototype._queryChangesList = function ( counterId, params ) {
1129 var uri = this._getUpdatedUri(),
1130 stickyParams = this.filtersModel.getStickyParams(),
1131 requestId,
1132 latestRequest;
1133
1134 params = params || {};
1135 params.action = 'render'; // bypasses MW chrome
1136
1137 uri.extend( params );
1138
1139 this.requestCounter[ counterId ] = this.requestCounter[ counterId ] || 0;
1140 requestId = ++this.requestCounter[ counterId ];
1141 latestRequest = function () {
1142 return requestId === this.requestCounter[ counterId ];
1143 }.bind( this );
1144
1145 // Sticky parameters override the URL params
1146 // this is to make sure that whether we represent
1147 // the sticky params in the URL or not (they may
1148 // be normalized out) the sticky parameters are
1149 // always being sent to the server with their
1150 // current/default values
1151 uri.extend( stickyParams );
1152
1153 return $.ajax( uri.toString(), { contentType: 'html' } )
1154 .then(
1155 function ( content, message, jqXHR ) {
1156 if ( !latestRequest() ) {
1157 return $.Deferred().reject();
1158 }
1159 return {
1160 content: content,
1161 status: jqXHR.status
1162 };
1163 },
1164 // RC returns 404 when there is no results
1165 function ( jqXHR ) {
1166 if ( latestRequest() ) {
1167 return $.Deferred().resolve(
1168 {
1169 content: jqXHR.responseText,
1170 status: jqXHR.status
1171 }
1172 ).promise();
1173 }
1174 }
1175 );
1176 };
1177
1178 /**
1179 * Fetch the list of changes from the server for the current filters
1180 *
1181 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1182 * and the fieldset.
1183 */
1184 mw.rcfilters.Controller.prototype._fetchChangesList = function () {
1185 return this._queryChangesList( 'updateChangesList' )
1186 .then(
1187 function ( data ) {
1188 var $parsed = $( '<div>' ).append( $( $.parseHTML( data.content ) ) ),
1189 pieces = {
1190 // Changes list
1191 changes: $parsed.find( '.mw-changeslist' ).first().contents(),
1192 // Fieldset
1193 fieldset: $parsed.find( 'fieldset.cloptions' ).first()
1194 };
1195
1196 if ( pieces.changes.length === 0 ) {
1197 pieces.changes = 'NO_RESULTS';
1198 }
1199
1200 return pieces;
1201 }
1202 );
1203 };
1204
1205 /**
1206 * Track usage of highlight feature
1207 *
1208 * @param {string} action
1209 * @param {Array|Object|string} filters
1210 */
1211 mw.rcfilters.Controller.prototype._trackHighlight = function ( action, filters ) {
1212 filters = typeof filters === 'string' ? { name: filters } : filters;
1213 filters = !Array.isArray( filters ) ? [ filters ] : filters;
1214 mw.track(
1215 'event.ChangesListHighlights',
1216 {
1217 action: action,
1218 filters: filters,
1219 userId: mw.user.getId()
1220 }
1221 );
1222 };
1223
1224 /**
1225 * Track filter grouping usage
1226 *
1227 * @param {string} action Action taken
1228 */
1229 mw.rcfilters.Controller.prototype.trackFilterGroupings = function ( action ) {
1230 var controller = this,
1231 rightNow = new Date().getTime(),
1232 randomIdentifier = String( mw.user.sessionId() ) + String( rightNow ) + String( Math.random() ),
1233 // Get all current filters
1234 filters = this.filtersModel.getSelectedItems().map( function ( item ) {
1235 return item.getName();
1236 } );
1237
1238 action = action || 'filtermenu';
1239
1240 // Check if these filters were the ones we just logged previously
1241 // (Don't log the same grouping twice, in case the user opens/closes)
1242 // the menu without action, or with the same result
1243 if (
1244 // Only log if the two arrays are different in size
1245 filters.length !== this.prevLoggedItems.length ||
1246 // Or if any filters are not the same as the cached filters
1247 filters.some( function ( filterName ) {
1248 return controller.prevLoggedItems.indexOf( filterName ) === -1;
1249 } ) ||
1250 // Or if any cached filters are not the same as given filters
1251 this.prevLoggedItems.some( function ( filterName ) {
1252 return filters.indexOf( filterName ) === -1;
1253 } )
1254 ) {
1255 filters.forEach( function ( filterName ) {
1256 mw.track(
1257 'event.ChangesListFilterGrouping',
1258 {
1259 action: action,
1260 groupIdentifier: randomIdentifier,
1261 filter: filterName,
1262 userId: mw.user.getId()
1263 }
1264 );
1265 } );
1266
1267 // Cache the filter names
1268 this.prevLoggedItems = filters;
1269 }
1270 };
1271
1272 /**
1273 * Mark all changes as seen on Watchlist
1274 */
1275 mw.rcfilters.Controller.prototype.markAllChangesAsSeen = function () {
1276 var api = new mw.Api();
1277 api.postWithToken( 'csrf', {
1278 formatversion: 2,
1279 action: 'setnotificationtimestamp',
1280 entirewatchlist: true
1281 } ).then( function () {
1282 this.updateChangesList( null, 'markSeen' );
1283 }.bind( this ) );
1284 };
1285 }( mediaWiki, jQuery ) );