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