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