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