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