Merge "RCFilters: Add 'advanced filters' label to the view selection"
[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
403 if (
404 this.filtersModel.getFiltersByView( 'namespaces' )
405 .filter( function ( filterItem ) {
406 return filterItem.isSelected();
407 } )
408 .length
409 ) {
410 // Only re-fetch results if there are namespace items that are actually selected
411 this.updateChangesList();
412 }
413 };
414
415 /**
416 * Set the highlight color for a filter item
417 *
418 * @param {string} filterName Name of the filter item
419 * @param {string} color Selected color
420 */
421 mw.rcfilters.Controller.prototype.setHighlightColor = function ( filterName, color ) {
422 this.filtersModel.setHighlightColor( filterName, color );
423 this._updateURL();
424 this._trackHighlight( 'set', { name: filterName, color: color } );
425 };
426
427 /**
428 * Clear highlight for a filter item
429 *
430 * @param {string} filterName Name of the filter item
431 */
432 mw.rcfilters.Controller.prototype.clearHighlightColor = function ( filterName ) {
433 this.filtersModel.clearHighlightColor( filterName );
434 this._updateURL();
435 this._trackHighlight( 'clear', filterName );
436 };
437
438 /**
439 * Enable or disable live updates.
440 * @param {boolean} enable True to enable, false to disable
441 */
442 mw.rcfilters.Controller.prototype.toggleLiveUpdate = function ( enable ) {
443 this.changesListModel.toggleLiveUpdate( enable );
444 if ( this.changesListModel.getLiveUpdate() && this.changesListModel.getNewChangesExist() ) {
445 this.showNewChanges();
446 }
447 };
448
449 /**
450 * Set a timeout for the next live update.
451 * @private
452 */
453 mw.rcfilters.Controller.prototype._scheduleLiveUpdate = function () {
454 setTimeout( this._doLiveUpdate.bind( this ), 3000 );
455 };
456
457 /**
458 * Perform a live update.
459 * @private
460 */
461 mw.rcfilters.Controller.prototype._doLiveUpdate = function () {
462 if ( !this._shouldCheckForNewChanges() ) {
463 // skip this turn and check back later
464 this._scheduleLiveUpdate();
465 return;
466 }
467
468 this._checkForNewChanges()
469 .then( function ( data ) {
470 if ( !this._shouldCheckForNewChanges() ) {
471 // by the time the response is received,
472 // it may not be appropriate anymore
473 return;
474 }
475
476 if ( data.changes !== 'NO_RESULTS' ) {
477 if ( this.changesListModel.getLiveUpdate() ) {
478 return this.updateChangesList( false, null, true, false );
479 } else {
480 this.changesListModel.setNewChangesExist( true );
481 }
482 }
483 }.bind( this ) )
484 .always( this._scheduleLiveUpdate.bind( this ) );
485 };
486
487 /**
488 * @return {boolean} It's appropriate to check for new changes now
489 * @private
490 */
491 mw.rcfilters.Controller.prototype._shouldCheckForNewChanges = function () {
492 var liveUpdateFeatureFlag = mw.config.get( 'wgStructuredChangeFiltersEnableLiveUpdate' ) ||
493 new mw.Uri().query.liveupdate;
494
495 return !document.hidden &&
496 !this.changesListModel.getNewChangesExist() &&
497 !this.updatingChangesList &&
498 liveUpdateFeatureFlag;
499 };
500
501 /**
502 * Check if new changes, newer than those currently shown, are available
503 *
504 * @return {jQuery.Promise} Promise object that resolves after trying
505 * to fetch 1 change newer than the last known 'from' parameter value
506 *
507 * @private
508 */
509 mw.rcfilters.Controller.prototype._checkForNewChanges = function () {
510 return this._fetchChangesList(
511 'liveUpdate',
512 {
513 limit: 1,
514 from: this.changesListModel.getNextFrom()
515 }
516 );
517 };
518
519 /**
520 * Show the new changes
521 *
522 * @return {jQuery.Promise} Promise object that resolves after
523 * fetching and showing the new changes
524 */
525 mw.rcfilters.Controller.prototype.showNewChanges = function () {
526 return this.updateChangesList( false, null, true, true );
527 };
528
529 /**
530 * Save the current model state as a saved query
531 *
532 * @param {string} [label] Label of the saved query
533 * @param {boolean} [setAsDefault=false] This query should be set as the default
534 */
535 mw.rcfilters.Controller.prototype.saveCurrentQuery = function ( label, setAsDefault ) {
536 var queryID,
537 highlightedItems = {},
538 highlightEnabled = this.filtersModel.isHighlightEnabled(),
539 selectedState = this.filtersModel.getSelectedState();
540
541 // Prepare highlights
542 this.filtersModel.getHighlightedItems().forEach( function ( item ) {
543 highlightedItems[ item.getName() ] = highlightEnabled ?
544 item.getHighlightColor() : null;
545 } );
546 // These are filter states; highlight is stored as boolean
547 highlightedItems.highlight = this.filtersModel.isHighlightEnabled();
548
549 // Delete all sticky filters
550 this._deleteStickyValuesFromFilterState( selectedState );
551
552 // Add item
553 queryID = this.savedQueriesModel.addNewQuery(
554 label || mw.msg( 'rcfilters-savedqueries-defaultlabel' ),
555 {
556 filters: selectedState,
557 highlights: highlightedItems,
558 invert: this.filtersModel.areNamespacesInverted()
559 }
560 );
561
562 if ( setAsDefault ) {
563 this.savedQueriesModel.setDefault( queryID );
564 }
565
566 // Save item
567 this._saveSavedQueries();
568 };
569
570 /**
571 * Remove a saved query
572 *
573 * @param {string} queryID Query id
574 */
575 mw.rcfilters.Controller.prototype.removeSavedQuery = function ( queryID ) {
576 this.savedQueriesModel.removeQuery( queryID );
577
578 this._saveSavedQueries();
579 };
580
581 /**
582 * Rename a saved query
583 *
584 * @param {string} queryID Query id
585 * @param {string} newLabel New label for the query
586 */
587 mw.rcfilters.Controller.prototype.renameSavedQuery = function ( queryID, newLabel ) {
588 var queryItem = this.savedQueriesModel.getItemByID( queryID );
589
590 if ( queryItem ) {
591 queryItem.updateLabel( newLabel );
592 }
593 this._saveSavedQueries();
594 };
595
596 /**
597 * Set a saved query as default
598 *
599 * @param {string} queryID Query Id. If null is given, default
600 * query is reset.
601 */
602 mw.rcfilters.Controller.prototype.setDefaultSavedQuery = function ( queryID ) {
603 this.savedQueriesModel.setDefault( queryID );
604 this._saveSavedQueries();
605 };
606
607 /**
608 * Load a saved query
609 *
610 * @param {string} queryID Query id
611 */
612 mw.rcfilters.Controller.prototype.applySavedQuery = function ( queryID ) {
613 var data, highlights,
614 queryItem = this.savedQueriesModel.getItemByID( queryID ),
615 currentMatchingQuery = this.findQueryMatchingCurrentState();
616
617 if (
618 queryItem &&
619 (
620 // If there's already a query, don't reload it
621 // if it's the same as the one that already exists
622 !currentMatchingQuery ||
623 currentMatchingQuery.getID() !== queryItem.getID()
624 )
625 ) {
626 data = queryItem.getData();
627 highlights = data.highlights;
628
629 // Backwards compatibility; initial version mispelled 'highlight' with 'highlights'
630 highlights.highlight = highlights.highlights || highlights.highlight;
631
632 // Update model state from filters
633 this.filtersModel.toggleFiltersSelected(
634 // Merge filters with sticky values
635 $.extend( true, {}, data.filters, this.filtersModel.getStickyFiltersState() )
636 );
637
638 // Update namespace inverted property
639 this.filtersModel.toggleInvertedNamespaces( !!Number( data.invert ) );
640
641 // Update highlight state
642 this.filtersModel.toggleHighlight( !!Number( highlights.highlight ) );
643 this.filtersModel.getItems().forEach( function ( filterItem ) {
644 var color = highlights[ filterItem.getName() ];
645 if ( color ) {
646 filterItem.setHighlightColor( color );
647 } else {
648 filterItem.clearHighlightColor();
649 }
650 } );
651
652 // Check all filter interactions
653 this.filtersModel.reassessFilterInteractions();
654
655 this.updateChangesList();
656
657 // Log filter grouping
658 this.trackFilterGroupings( 'savedfilters' );
659 }
660 };
661
662 /**
663 * Check whether the current filter and highlight state exists
664 * in the saved queries model.
665 *
666 * @return {boolean} Query exists
667 */
668 mw.rcfilters.Controller.prototype.findQueryMatchingCurrentState = function () {
669 var highlightedItems = {},
670 selectedState = this.filtersModel.getSelectedState();
671
672 // Prepare highlights of the current query
673 this.filtersModel.getItemsSupportingHighlights().forEach( function ( item ) {
674 highlightedItems[ item.getName() ] = item.getHighlightColor();
675 } );
676 highlightedItems.highlight = this.filtersModel.isHighlightEnabled();
677
678 // Remove sticky filters
679 this._deleteStickyValuesFromFilterState( selectedState );
680
681 return this.savedQueriesModel.findMatchingQuery(
682 {
683 filters: selectedState,
684 highlights: highlightedItems,
685 invert: this.filtersModel.areNamespacesInverted()
686 }
687 );
688 };
689
690 /**
691 * Delete sticky filters from given object
692 *
693 * @param {Object} filterState Filter state
694 */
695 mw.rcfilters.Controller.prototype._deleteStickyValuesFromFilterState = function ( filterState ) {
696 // Remove sticky filters
697 $.each( this.filtersModel.getStickyFiltersState(), function ( filterName ) {
698 delete filterState[ filterName ];
699 } );
700 };
701
702 /**
703 * Get an object representing the base state of parameters
704 * and highlights.
705 *
706 * This is meant to make sure that the saved queries that are
707 * in memory are always the same structure as what we would get
708 * by calling the current model's "getSelectedState" and by checking
709 * highlight items.
710 *
711 * In cases where a user saved a query when the system had a certain
712 * set of filters, and then a filter was added to the system, we want
713 * to make sure that the stored queries can still be comparable to
714 * the current state, which means that we need the base state for
715 * two operations:
716 *
717 * - Saved queries are stored in "minimal" view (only changed filters
718 * are stored); When we initialize the system, we merge each minimal
719 * query with the base state (using 'getNormalizedFilters') so all
720 * saved queries have the exact same structure as what we would get
721 * by checking the getSelectedState of the filter.
722 * - When we save the queries, we minimize the object to only represent
723 * whatever has actually changed, rather than store the entire
724 * object. To check what actually is different so we can store it,
725 * we need to obtain a base state to compare against, this is
726 * what #_getMinimalFilterList does
727 */
728 mw.rcfilters.Controller.prototype._buildBaseFilterState = function () {
729 var defaultParams = this.filtersModel.getDefaultParams(),
730 highlightedItems = {};
731
732 // Prepare highlights
733 this.filtersModel.getItemsSupportingHighlights().forEach( function ( item ) {
734 highlightedItems[ item.getName() ] = null;
735 } );
736 highlightedItems.highlight = false;
737
738 this.baseFilterState = {
739 filters: this.filtersModel.getFiltersFromParameters( defaultParams ),
740 highlights: highlightedItems,
741 invert: false
742 };
743 };
744
745 /**
746 * Get an object representing the base filter state of both
747 * filters and highlights. The structure is similar to what we use
748 * to store each query in the saved queries object:
749 * {
750 * filters: {
751 * filterName: (bool)
752 * },
753 * highlights: {
754 * filterName: (string|null)
755 * }
756 * }
757 *
758 * @return {Object} Object representing the base state of
759 * parameters and highlights
760 */
761 mw.rcfilters.Controller.prototype._getBaseFilterState = function () {
762 return this.baseFilterState;
763 };
764
765 /**
766 * Get an object that holds only the parameters and highlights that have
767 * values different than the base default value.
768 *
769 * This is the reverse of the normalization we do initially on loading and
770 * initializing the saved queries model.
771 *
772 * @param {Object} valuesObject Object representing the state of both
773 * filters and highlights in its normalized version, to be minimized.
774 * @return {Object} Minimal filters and highlights list
775 */
776 mw.rcfilters.Controller.prototype._getMinimalFilterList = function ( valuesObject ) {
777 var result = { filters: {}, highlights: {} },
778 baseState = this._getBaseFilterState();
779
780 // XOR results
781 $.each( valuesObject.filters, function ( name, value ) {
782 if ( baseState.filters !== undefined && baseState.filters[ name ] !== value ) {
783 result.filters[ name ] = value;
784 }
785 } );
786
787 $.each( valuesObject.highlights, function ( name, value ) {
788 if ( baseState.highlights !== undefined && baseState.highlights[ name ] !== value ) {
789 result.highlights[ name ] = value;
790 }
791 } );
792
793 return result;
794 };
795
796 /**
797 * Save the current state of the saved queries model with all
798 * query item representation in the user settings.
799 */
800 mw.rcfilters.Controller.prototype._saveSavedQueries = function () {
801 var stringified,
802 state = this.savedQueriesModel.getState(),
803 controller = this;
804
805 // Minimize before save
806 $.each( state.queries, function ( queryID, info ) {
807 state.queries[ queryID ].data = controller._getMinimalFilterList( info.data );
808 } );
809
810 // Stringify state
811 stringified = JSON.stringify( state );
812
813 if ( stringified.length > 65535 ) {
814 // Sanity check, since the preference can only hold that.
815 return;
816 }
817
818 // Save the preference
819 new mw.Api().saveOption( 'rcfilters-saved-queries', stringified );
820 // Update the preference for this session
821 mw.user.options.set( 'rcfilters-saved-queries', stringified );
822 };
823
824 /**
825 * Update sticky preferences with current model state
826 */
827 mw.rcfilters.Controller.prototype.updateStickyPreferences = function () {
828 // Update default sticky values with selected, whether they came from
829 // the initial defaults or from the URL value that is being normalized
830 this.updateDaysDefault( this.filtersModel.getGroup( 'days' ).getSelectedItems()[ 0 ].getParamName() );
831 this.updateLimitDefault( this.filtersModel.getGroup( 'limit' ).getSelectedItems()[ 0 ].getParamName() );
832 };
833
834 /**
835 * Update the limit default value
836 *
837 * param {number} newValue New value
838 */
839 mw.rcfilters.Controller.prototype.updateLimitDefault = function ( /* newValue */ ) {
840 // HACK: Temporarily remove this from being sticky
841 // See T172156
842
843 /*
844 if ( !$.isNumeric( newValue ) ) {
845 return;
846 }
847
848 newValue = Number( newValue );
849
850 if ( mw.user.options.get( 'rcfilters-rclimit' ) !== newValue ) {
851 // Save the preference
852 new mw.Api().saveOption( 'rcfilters-rclimit', newValue );
853 // Update the preference for this session
854 mw.user.options.set( 'rcfilters-rclimit', newValue );
855 }
856 */
857 return;
858 };
859
860 /**
861 * Update the days default value
862 *
863 * param {number} newValue New value
864 */
865 mw.rcfilters.Controller.prototype.updateDaysDefault = function ( /* newValue */ ) {
866 // HACK: Temporarily remove this from being sticky
867 // See T172156
868
869 /*
870 if ( !$.isNumeric( newValue ) ) {
871 return;
872 }
873
874 newValue = Number( newValue );
875
876 if ( mw.user.options.get( 'rcdays' ) !== newValue ) {
877 // Save the preference
878 new mw.Api().saveOption( 'rcdays', newValue );
879 // Update the preference for this session
880 mw.user.options.set( 'rcdays', newValue );
881 }
882 */
883 return;
884 };
885
886 /**
887 * Synchronize the URL with the current state of the filters
888 * without adding an history entry.
889 */
890 mw.rcfilters.Controller.prototype.replaceUrl = function () {
891 mw.rcfilters.UriProcessor.static.replaceState( this._getUpdatedUri() );
892 };
893
894 /**
895 * Update filter state (selection and highlighting) based
896 * on current URL values.
897 *
898 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
899 * list based on the updated model.
900 */
901 mw.rcfilters.Controller.prototype.updateStateFromUrl = function ( fetchChangesList ) {
902 fetchChangesList = fetchChangesList === undefined ? true : !!fetchChangesList;
903
904 this.uriProcessor.updateModelBasedOnQuery( new mw.Uri().query );
905
906 // Update the sticky preferences, in case we received a value
907 // from the URL
908 this.updateStickyPreferences();
909
910 // Only update and fetch new results if it is requested
911 if ( fetchChangesList ) {
912 this.updateChangesList();
913 }
914 };
915
916 /**
917 * Update the list of changes and notify the model
918 *
919 * @param {boolean} [updateUrl=true] Whether the URL should be updated with the current state of the filters
920 * @param {Object} [params] Extra parameters to add to the API call
921 * @param {boolean} [isLiveUpdate=false] The purpose of this update is to show new results for the same filters
922 * @param {boolean} [invalidateCurrentChanges=true] Invalidate current changes by default (show spinner)
923 * @return {jQuery.Promise} Promise that is resolved when the update is complete
924 */
925 mw.rcfilters.Controller.prototype.updateChangesList = function ( updateUrl, params, isLiveUpdate, invalidateCurrentChanges ) {
926 updateUrl = updateUrl === undefined ? true : updateUrl;
927 invalidateCurrentChanges = invalidateCurrentChanges === undefined ? true : invalidateCurrentChanges;
928 if ( updateUrl ) {
929 this._updateURL( params );
930 }
931 if ( invalidateCurrentChanges ) {
932 this.changesListModel.invalidate();
933 }
934 this.changesListModel.setNewChangesExist( false );
935 this.updatingChangesList = true;
936 return this._fetchChangesList()
937 .then(
938 // Success
939 function ( pieces ) {
940 var $changesListContent = pieces.changes,
941 $fieldset = pieces.fieldset;
942 this.changesListModel.update( $changesListContent, $fieldset, false, isLiveUpdate );
943 }.bind( this )
944 // Do nothing for failure
945 )
946 .always( function () {
947 this.updatingChangesList = false;
948 }.bind( this ) );
949 };
950
951 /**
952 * Get an object representing the default parameter state, whether
953 * it is from the model defaults or from the saved queries.
954 *
955 * @return {Object} Default parameters
956 */
957 mw.rcfilters.Controller.prototype._getDefaultParams = function () {
958 var data, queryHighlights,
959 savedParams = {},
960 savedHighlights = {},
961 defaultSavedQueryItem = this.savedQueriesModel.getItemByID( this.savedQueriesModel.getDefault() );
962
963 if ( defaultSavedQueryItem ) {
964 data = defaultSavedQueryItem.getData();
965
966 queryHighlights = data.highlights || {};
967 savedParams = this.filtersModel.getParametersFromFilters(
968 // Merge filters with sticky values
969 $.extend( true, {}, data.filters, this.filtersModel.getStickyFiltersState() )
970 );
971
972 // Translate highlights to parameters
973 savedHighlights.highlight = String( Number( queryHighlights.highlight ) );
974 $.each( queryHighlights, function ( filterName, color ) {
975 if ( filterName !== 'highlights' ) {
976 savedHighlights[ filterName + '_color' ] = color;
977 }
978 } );
979
980 return $.extend( true, {}, savedParams, savedHighlights );
981 }
982
983 return this.filtersModel.getDefaultParams();
984 };
985
986 /**
987 * Update the URL of the page to reflect current filters
988 *
989 * This should not be called directly from outside the controller.
990 * If an action requires changing the URL, it should either use the
991 * highlighting actions below, or call #updateChangesList which does
992 * the uri corrections already.
993 *
994 * @param {Object} [params] Extra parameters to add to the API call
995 */
996 mw.rcfilters.Controller.prototype._updateURL = function ( params ) {
997 var currentUri = new mw.Uri(),
998 updatedUri = this._getUpdatedUri();
999
1000 updatedUri.extend( params || {} );
1001
1002 if (
1003 this.uriProcessor.getVersion( currentUri.query ) !== 2 ||
1004 this.uriProcessor.isNewState( currentUri.query, updatedUri.query )
1005 ) {
1006 mw.rcfilters.UriProcessor.static.replaceState( updatedUri );
1007 }
1008 };
1009
1010 /**
1011 * Get an updated mw.Uri object based on the model state
1012 *
1013 * @return {mw.Uri} Updated Uri
1014 */
1015 mw.rcfilters.Controller.prototype._getUpdatedUri = function () {
1016 var uri = new mw.Uri();
1017
1018 // Minimize url
1019 uri.query = this.uriProcessor.minimizeQuery(
1020 $.extend(
1021 true,
1022 {},
1023 // We want to retain unrecognized params
1024 // The uri params from model will override
1025 // any recognized value in the current uri
1026 // query, retain unrecognized params, and
1027 // the result will then be minimized
1028 uri.query,
1029 this.uriProcessor.getUriParametersFromModel(),
1030 { urlversion: '2' }
1031 )
1032 );
1033
1034 return uri;
1035 };
1036
1037 /**
1038 * Fetch the list of changes from the server for the current filters
1039 *
1040 * @param {string} [counterId='updateChangesList'] Id for this request. To allow concurrent requests
1041 * not to invalidate each other.
1042 * @param {Object} [params={}] Parameters to add to the query
1043 *
1044 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1045 * or with a string denoting no results.
1046 */
1047 mw.rcfilters.Controller.prototype._fetchChangesList = function ( counterId, params ) {
1048 var uri = this._getUpdatedUri(),
1049 stickyParams = this.filtersModel.getStickyParams(),
1050 requestId,
1051 latestRequest;
1052
1053 counterId = counterId || 'updateChangesList';
1054 params = params || {};
1055
1056 uri.extend( params );
1057
1058 this.requestCounter[ counterId ] = this.requestCounter[ counterId ] || 0;
1059 requestId = ++this.requestCounter[ counterId ];
1060 latestRequest = function () {
1061 return requestId === this.requestCounter[ counterId ];
1062 }.bind( this );
1063
1064 // Sticky parameters override the URL params
1065 // this is to make sure that whether we represent
1066 // the sticky params in the URL or not (they may
1067 // be normalized out) the sticky parameters are
1068 // always being sent to the server with their
1069 // current/default values
1070 uri.extend( stickyParams );
1071
1072 return $.ajax( uri.toString(), { contentType: 'html' } )
1073 .then(
1074 // Success
1075 function ( html ) {
1076 var $parsed;
1077 if ( !latestRequest() ) {
1078 return $.Deferred().reject();
1079 }
1080
1081 $parsed = $( $.parseHTML( html ) );
1082
1083 return {
1084 // Changes list
1085 changes: $parsed.find( '.mw-changeslist' ).first().contents(),
1086 // Fieldset
1087 fieldset: $parsed.find( 'fieldset.rcoptions' ).first()
1088 };
1089 },
1090 // Failure
1091 function ( responseObj ) {
1092 var $parsed;
1093
1094 if ( !latestRequest() ) {
1095 return $.Deferred().reject();
1096 }
1097
1098 $parsed = $( $.parseHTML( responseObj.responseText ) );
1099
1100 // Force a resolve state to this promise
1101 return $.Deferred().resolve( {
1102 changes: 'NO_RESULTS',
1103 fieldset: $parsed.find( 'fieldset.rcoptions' ).first()
1104 } ).promise();
1105 }
1106 );
1107 };
1108
1109 /**
1110 * Track usage of highlight feature
1111 *
1112 * @param {string} action
1113 * @param {Array|Object|string} filters
1114 */
1115 mw.rcfilters.Controller.prototype._trackHighlight = function ( action, filters ) {
1116 filters = typeof filters === 'string' ? { name: filters } : filters;
1117 filters = !Array.isArray( filters ) ? [ filters ] : filters;
1118 mw.track(
1119 'event.ChangesListHighlights',
1120 {
1121 action: action,
1122 filters: filters,
1123 userId: mw.user.getId()
1124 }
1125 );
1126 };
1127
1128 /**
1129 * Track filter grouping usage
1130 *
1131 * @param {string} action Action taken
1132 */
1133 mw.rcfilters.Controller.prototype.trackFilterGroupings = function ( action ) {
1134 var controller = this,
1135 rightNow = new Date().getTime(),
1136 randomIdentifier = String( mw.user.sessionId() ) + String( rightNow ) + String( Math.random() ),
1137 // Get all current filters
1138 filters = this.filtersModel.getSelectedItems().map( function ( item ) {
1139 return item.getName();
1140 } );
1141
1142 action = action || 'filtermenu';
1143
1144 // Check if these filters were the ones we just logged previously
1145 // (Don't log the same grouping twice, in case the user opens/closes)
1146 // the menu without action, or with the same result
1147 if (
1148 // Only log if the two arrays are different in size
1149 filters.length !== this.prevLoggedItems.length ||
1150 // Or if any filters are not the same as the cached filters
1151 filters.some( function ( filterName ) {
1152 return controller.prevLoggedItems.indexOf( filterName ) === -1;
1153 } ) ||
1154 // Or if any cached filters are not the same as given filters
1155 this.prevLoggedItems.some( function ( filterName ) {
1156 return filters.indexOf( filterName ) === -1;
1157 } )
1158 ) {
1159 filters.forEach( function ( filterName ) {
1160 mw.track(
1161 'event.ChangesListFilterGrouping',
1162 {
1163 action: action,
1164 groupIdentifier: randomIdentifier,
1165 filter: filterName,
1166 userId: mw.user.getId()
1167 }
1168 );
1169 } );
1170
1171 // Cache the filter names
1172 this.prevLoggedItems = filters;
1173 }
1174 };
1175 }( mediaWiki, jQuery ) );