Debian Codegraph @

resources/src/mediawiki.rcfilters/Controller.js

raw symbols SCIP
1 const byteLength = require( 'mediawiki.String' ).byteLength,
2 UriProcessor = require( './UriProcessor.js' );
3
4 /* eslint no-underscore-dangle: "off" */
5 /**
6 * Controller for the filters in Recent Changes.
7 *
8 * @class Controller
9 * @memberof mw.rcfilters
10 * @ignore
11 * @param {mw.rcfilters.dm.FiltersViewModel} filtersModel Filters view model
12 * @param {mw.rcfilters.dm.ChangesListViewModel} changesListModel Changes list view model
13 * @param {mw.rcfilters.dm.SavedQueriesModel} savedQueriesModel Saved queries model
14 * @param {Object} config Additional configuration
15 * @param {string} config.savedQueriesPreferenceName Where to save the saved queries
16 * @param {string} config.daysPreferenceName Preference name for the days filter
17 * @param {string} config.limitPreferenceName Preference name for the limit filter
18 * @param {string} config.collapsedPreferenceName Preference name for collapsing and showing
19 * the active filters area
20 * @param {boolean} [config.normalizeTarget] Dictates whether or not to go through the
21 * title normalization to separate title subpage/parts into the target= url
22 * parameter
23 */
24 const Controller = function MwRcfiltersController( filtersModel, changesListModel, savedQueriesModel, config ) {
25 this.filtersModel = filtersModel;
26 this.changesListModel = changesListModel;
27 this.savedQueriesModel = savedQueriesModel;
28 this.savedQueriesPreferenceName = config.savedQueriesPreferenceName;
29 this.daysPreferenceName = config.daysPreferenceName;
30 this.limitPreferenceName = config.limitPreferenceName;
31 this.collapsedPreferenceName = config.collapsedPreferenceName;
32 this.normalizeTarget = !!config.normalizeTarget;
33
34 // TODO merge dmConfig.json and config.json virtual files, see T256836
35 this.pollingRate = require( './dmConfig.json' ).StructuredChangeFiltersLiveUpdatePollingRate;
36
37 this.requestCounter = {};
38 this.uriProcessor = null;
39 this.initialized = false;
40 this.wereSavedQueriesSaved = false;
41
42 this.prevLoggedItems = [];
43
44 this.FILTER_CHANGE = 'filterChange';
45 this.SHOW_NEW_CHANGES = 'showNewChanges';
46 this.LIVE_UPDATE = 'liveUpdate';
47 };
48
49 /* Initialization */
50 OO.initClass( Controller );
51
52 /**
53 * Initialize the filter and parameter states
54 *
55 * @param {Array} filterStructure Filter definition and structure for the model
56 * @param {Object} namespaceStructure Namespace definition
57 * @param {Object} tagList Tag definition
58 * @param {Object} [conditionalViews] Conditional view definition
59 */
60 Controller.prototype.initialize = function ( filterStructure, namespaceStructure, tagList, conditionalViews ) {
61 const displayConfig = mw.config.get( 'StructuredChangeFiltersDisplayConfig' ),
62 defaultSavedQueryExists = mw.config.get( 'wgStructuredChangeFiltersDefaultSavedQueryExists' ),
63 controller = this,
64 views = $.extend( true, {}, conditionalViews ),
65 url = new URL( location.href );
66
67 // Prepare views
68 const nsAllContents = {
69 name: 'all-contents',
70 label: mw.msg( 'rcfilters-allcontents-label' ),
71 description: '',
72 identifiers: [ 'subject' ],
73 cssClass: 'mw-changeslist-ns-subject',
74 subset: []
75 };
76 const nsAllDiscussions = {
77 name: 'all-discussions',
78 label: mw.msg( 'rcfilters-alldiscussions-label' ),
79 description: '',
80 identifiers: [ 'talk' ],
81 cssClass: 'mw-changeslist-ns-talk',
82 subset: []
83 };
84 const items = [ nsAllContents, nsAllDiscussions ];
85 for ( const namespaceID in namespaceStructure ) {
86 const label = namespaceStructure[ namespaceID ];
87 // Build and clean up the individual namespace items definition
88 const isTalk = mw.Title.isTalkNamespace( namespaceID ),
89 nsFilter = {
90 name: namespaceID,
91 label: label || mw.msg( 'blanknamespace' ),
92 description: '',
93 identifiers: [
94 isTalk ? 'talk' : 'subject'
95 ],
96 cssClass: 'mw-changeslist-ns-' + namespaceID
97 };
98 items.push( nsFilter );
99 ( isTalk ? nsAllDiscussions : nsAllContents ).subset.push( { filter: namespaceID } );
100 }
101
102 views.namespaces = {
103 title: mw.msg( 'namespaces' ),
104 trigger: ':',
105 groups: [ {
106 // Group definition (single group)
107 name: 'namespace', // parameter name is singular
108 type: 'string_options',
109 title: mw.msg( 'namespaces' ),
110 labelPrefixKey: {
111 default: 'rcfilters-tag-prefix-namespace',
112 inverted: 'rcfilters-tag-prefix-namespace-inverted'
113 },
114 separator: ';',
115 supportsAll: false,
116 fullCoverage: true,
117 filters: items
118 } ]
119 };
120 views.invertNamespaces = {
121 groups: [
122 {
123 // Should really be called invertNamespacesGroup; legacy name is used so that
124 // saved queries don't break
125 name: 'invertGroup',
126 type: 'boolean',
127 hidden: true,
128 filters: [ {
129 name: 'invert',
130 default: '0'
131 } ]
132 } ]
133 };
134
135 views.tags = {
136 title: mw.msg( 'rcfilters-view-tags' ),
137 trigger: '#',
138 groups: [ {
139 // Group definition (single group)
140 name: 'tagfilter', // Parameter name
141 type: 'string_options',
142 title: 'rcfilters-view-tags', // Message key
143 labelPrefixKey: {
144 default: 'rcfilters-tag-prefix-tags',
145 inverted: 'rcfilters-tag-prefix-tags-inverted'
146 },
147 separator: '|',
148 supportsAll: false,
149 fullCoverage: false,
150 filters: tagList
151 } ]
152 };
153 views.invertTags = {
154 groups: [
155 {
156 name: 'invertTagsGroup',
157 type: 'boolean',
158 hidden: true,
159 filters: [ {
160 name: 'inverttags',
161 default: '0'
162 } ]
163 } ]
164 };
165
166 // Add parameter range operations
167 views.range = {
168 groups: [
169 {
170 name: 'limit',
171 type: 'single_option',
172 title: '', // Because it's a hidden group, this title actually appears nowhere
173 hidden: true,
174 allowArbitrary: true,
175 // FIXME: $.isNumeric is deprecated
176 validate: $.isNumeric,
177 range: {
178 min: 0, // The server normalizes negative numbers to 0 results
179 max: 1000
180 },
181 sortFunc: function ( a, b ) {
182 return Number( a.name ) - Number( b.name );
183 },
184 default: mw.user.options.get( this.limitPreferenceName, displayConfig.limitDefault ),
185 sticky: true,
186 filters: displayConfig.limitArray.map( ( num ) => controller._createFilterDataFromNumber( num, num ) )
187 },
188 {
189 name: 'days',
190 type: 'single_option',
191 title: '', // Because it's a hidden group, this title actually appears nowhere
192 hidden: true,
193 allowArbitrary: true,
194 // FIXME: $.isNumeric is deprecated
195 validate: $.isNumeric,
196 range: {
197 min: 0,
198 max: displayConfig.maxDays
199 },
200 sortFunc: function ( a, b ) {
201 return Number( a.name ) - Number( b.name );
202 },
203 numToLabelFunc: function ( i ) {
204 return Number( i ) < 1 ?
205 ( Number( i ) * 24 ).toFixed( 2 ) :
206 Number( i );
207 },
208 default: mw.user.options.get( this.daysPreferenceName, displayConfig.daysDefault ),
209 sticky: true,
210 filters: [
211 // Hours (1, 2, 6, 12)
212 0.04166, 0.0833, 0.25, 0.5
213 // Days
214 ].concat( displayConfig.daysArray )
215 .map( ( num ) => controller._createFilterDataFromNumber(
216 num,
217 // Convert fractions of days to number of hours for the labels
218 num < 1 ? Math.round( num * 24 ) : num
219 ) )
220 }
221 ]
222 };
223
224 views.display = {
225 groups: [
226 {
227 name: 'display',
228 type: 'boolean',
229 title: '', // Because it's a hidden group, this title actually appears nowhere
230 hidden: true,
231 sticky: true,
232 filters: [
233 {
234 name: 'enhanced',
235 default: String( mw.user.options.get( 'usenewrc', 0 ) )
236 }
237 ]
238 }
239 ]
240 };
241
242 // Before we do anything, we need to see if we require additional items in the
243 // groups that have 'AllowArbitrary'. For the moment, those are only single_option
244 // groups; if we ever expand it, this might need further generalization:
245 for ( const viewName in views ) {
246 const viewData = views[ viewName ];
247 viewData.groups.forEach( ( groupData ) => {
248 const extraValues = [];
249 if ( groupData.allowArbitrary ) {
250 // If the value in the URL isn't in the group, add it
251 if ( url.searchParams.get( groupData.name ) !== null ) {
252 extraValues.push( url.searchParams.get( groupData.name ) );
253 }
254 // If the default value isn't in the group, add it
255 if ( groupData.default !== undefined ) {
256 extraValues.push( String( groupData.default ) );
257 }
258 controller.addNumberValuesToGroup( groupData, extraValues );
259 }
260 } );
261 }
262
263 // Initialize the model
264 this.filtersModel.initializeFilters( filterStructure, views );
265
266 this.uriProcessor = new UriProcessor(
267 this.filtersModel,
268 { normalizeTarget: this.normalizeTarget }
269 );
270
271 let parsedSavedQueries;
272 if ( !mw.user.isAnon() ) {
273 try {
274 parsedSavedQueries = JSON.parse( mw.user.options.get( this.savedQueriesPreferenceName ) || '{}' );
275 } catch ( err ) {
276 parsedSavedQueries = {};
277 }
278
279 // Initialize saved queries
280 this.savedQueriesModel.initialize( parsedSavedQueries );
281 if ( this.savedQueriesModel.isConverted() ) {
282 // Since we know we converted, we're going to re-save
283 // the queries so they are now migrated to the new format
284 this._saveSavedQueries();
285 }
286 }
287
288 if ( defaultSavedQueryExists ) {
289 // This came from the server, meaning that we have a default
290 // saved query, but the server could not load it, probably because
291 // it was pre-conversion to the new format.
292 // We need to load this query again
293 this.applySavedQuery( this.savedQueriesModel.getDefault() );
294 } else {
295 // There are either recognized parameters in the URL
296 // or there are none, but there is also no default
297 // saved query (so defaults are from the backend)
298 // We want to update the state but not fetch results
299 // again
300 this.updateStateFromUrl( false );
301
302 const pieces = this._extractChangesListInfo( $( '#mw-content-text' ) );
303
304 // Update the changes list with the existing data
305 // so it gets processed
306 this.changesListModel.update(
307 pieces.changes,
308 pieces.fieldset,
309 pieces.noResultsDetails,
310 true // We're using existing DOM elements
311 );
312 }
313
314 this.initialized = true;
315 this.switchView( 'default' );
316
317 if ( this.pollingRate ) {
318 this._scheduleLiveUpdate();
319 }
320 };
321
322 /**
323 * Check if the controller has finished initializing.
324 *
325 * @return {boolean} Controller is initialized
326 */
327 Controller.prototype.isInitialized = function () {
328 return this.initialized;
329 };
330
331 /**
332 * Extracts information from the changes list DOM
333 *
334 * @param {jQuery} $root Root DOM to find children from
335 * @param {number} [statusCode] Server response status code
336 * @return {Object} Information about changes list
337 * @return {Object|string} return.changes Changes list, or 'NO_RESULTS' if there are no results
338 * (either normally or as an error)
339 * @return {string} [return.noResultsDetails] 'NO_RESULTS_NORMAL' for a normal 0-result set,
340 * 'NO_RESULTS_TIMEOUT' for no results due to a timeout, or omitted for more than 0 results
341 * @return {jQuery} return.fieldset Fieldset
342 */
343 Controller.prototype._extractChangesListInfo = function ( $root, statusCode ) {
344 const $changesListContents = $root.find( '.mw-changeslist' ).first().contents(),
345 areResults = !!$changesListContents.length,
346 checkForLogout = !areResults && statusCode === 200;
347
348 // We check if user logged out on different tab/browser or the session has expired.
349 // 205 status code returned from the server, which indicates that we need to reload the page
350 // is not usable on WL page, because we get redirected to login page, which gives 200 OK
351 // status code (if everything else goes well).
352 // Bug: T177717
353 if ( checkForLogout && !!$root.find( '#wpName1' ).length ) {
354 location.reload( false );
355 return;
356 }
357
358 const info = {
359 changes: $changesListContents.length ? $changesListContents : 'NO_RESULTS',
360 fieldset: $root.find( 'fieldset.cloptions' ).first()
361 };
362
363 if ( !areResults ) {
364 if ( $root.find( '.mw-changeslist-timeout' ).length ) {
365 info.noResultsDetails = 'NO_RESULTS_TIMEOUT';
366 } else if ( $root.find( '.mw-changeslist-notargetpage' ).length ) {
367 info.noResultsDetails = 'NO_RESULTS_NO_TARGET_PAGE';
368 } else if ( $root.find( '.mw-changeslist-invalidtargetpage' ).length ) {
369 info.noResultsDetails = 'NO_RESULTS_INVALID_TARGET_PAGE';
370 } else {
371 info.noResultsDetails = 'NO_RESULTS_NORMAL';
372 }
373 }
374
375 return info;
376 };
377
378 /**
379 * Create filter data from a number, for the filters that are numerical value
380 *
381 * @param {number} num Number
382 * @param {number} numForDisplay Number for the label
383 * @return {Object} Filter data
384 */
385 Controller.prototype._createFilterDataFromNumber = function ( num, numForDisplay ) {
386 return {
387 name: String( num ),
388 label: mw.language.convertNumber( numForDisplay )
389 };
390 };
391
392 /**
393 * Add an arbitrary values to groups that allow arbitrary values
394 *
395 * @param {Object} groupData Group data
396 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
397 */
398 Controller.prototype.addNumberValuesToGroup = function ( groupData, arbitraryValues ) {
399 const controller = this,
400 normalizeWithinRange = function ( range, val ) {
401 if ( val < range.min ) {
402 return range.min; // Min
403 } else if ( val >= range.max ) {
404 return range.max; // Max
405 }
406 return val;
407 };
408
409 arbitraryValues = Array.isArray( arbitraryValues ) ? arbitraryValues : [ arbitraryValues ];
410
411 // Normalize the arbitrary values and the default value for a range
412 if ( groupData.range ) {
413 arbitraryValues = arbitraryValues.map( ( val ) => normalizeWithinRange( groupData.range, val ) );
414
415 // Normalize the default, since that's user defined
416 if ( groupData.default !== undefined ) {
417 groupData.default = String( normalizeWithinRange( groupData.range, groupData.default ) );
418 }
419 }
420
421 // This is only true for single_option group
422 // We assume these are the only groups that will allow for
423 // arbitrary, since it doesn't make any sense for the other
424 // groups.
425 arbitraryValues.forEach( ( val ) => {
426 if (
427 // If the group allows for arbitrary data
428 groupData.allowArbitrary &&
429 // and it is single_option (or string_options, but we
430 // don't have cases of those yet, nor do we plan to)
431 groupData.type === 'single_option' &&
432 // and, if there is a validate method and it passes on
433 // the data
434 ( !groupData.validate || groupData.validate( val ) ) &&
435 // but if that value isn't already in the definition
436 groupData.filters
437 .map( ( filterData ) => String( filterData.name ) )
438 .indexOf( String( val ) ) === -1
439 ) {
440 // Add the filter information
441 groupData.filters.push( controller._createFilterDataFromNumber(
442 val,
443 groupData.numToLabelFunc ?
444 groupData.numToLabelFunc( val ) :
445 val
446 ) );
447
448 // If there's a sort function set up, re-sort the values
449 if ( groupData.sortFunc ) {
450 groupData.filters.sort( groupData.sortFunc );
451 }
452 }
453 } );
454 };
455
456 /**
457 * Reset to default filters
458 */
459 Controller.prototype.resetToDefaults = function () {
460 const params = this._getDefaultParams();
461 if ( this.applyParamChange( params ) ) {
462 // Only update the changes list if there was a change to actual filters
463 this.updateChangesList();
464 } else {
465 this.uriProcessor.updateURL( params );
466 }
467 };
468
469 /**
470 * Check whether the default values of the filters are all false.
471 *
472 * @return {boolean} Defaults are all false
473 */
474 Controller.prototype.areDefaultsEmpty = function () {
475 return $.isEmptyObject( this._getDefaultParams() );
476 };
477
478 /**
479 * Empty all selected filters
480 */
481 Controller.prototype.emptyFilters = function () {
482 if ( this.applyParamChange( {} ) ) {
483 // Only update the changes list if there was a change to actual filters
484 this.updateChangesList();
485 } else {
486 this.uriProcessor.updateURL();
487 }
488 };
489
490 /**
491 * Update the selected state of a filter
492 *
493 * @param {string} filterName Filter name
494 * @param {boolean} [isSelected] Filter selected state
495 */
496 Controller.prototype.toggleFilterSelect = function ( filterName, isSelected ) {
497 const filterItem = this.filtersModel.getItemByName( filterName );
498
499 if ( !filterItem ) {
500 // If no filter was found, break
501 return;
502 }
503
504 isSelected = isSelected === undefined ? !filterItem.isSelected() : isSelected;
505
506 if ( filterItem.isSelected() !== isSelected ) {
507 this.filtersModel.toggleFilterSelected( filterName, isSelected );
508
509 this.updateChangesList();
510
511 // Check filter interactions
512 this.filtersModel.reassessFilterInteractions( filterItem );
513 }
514 };
515
516 /**
517 * Clear both highlight and selection of a filter
518 *
519 * @param {string} filterName Name of the filter item
520 */
521 Controller.prototype.clearFilter = function ( filterName ) {
522 const filterItem = this.filtersModel.getItemByName( filterName ),
523 isHighlighted = filterItem.isHighlighted(),
524 isSelected = filterItem.isSelected();
525
526 if ( isSelected || isHighlighted ) {
527 this.filtersModel.clearHighlightColor( filterName );
528 this.filtersModel.toggleFilterSelected( filterName, false );
529
530 if ( isSelected ) {
531 // Only update the changes list if the filter changed
532 // its selection state. If it only changed its highlight
533 // then don't reload
534 this.updateChangesList();
535 }
536
537 this.filtersModel.reassessFilterInteractions( filterItem );
538 }
539 };
540
541 /**
542 * Toggle the highlight feature on and off
543 */
544 Controller.prototype.toggleHighlight = function () {
545 this.filtersModel.toggleHighlight();
546 this.uriProcessor.updateURL();
547
548 if ( this.filtersModel.isHighlightEnabled() ) {
549 /**
550 * Fires when highlight feature is enabled.
551 *
552 * @event ~'RcFilters.highlight.enable'
553 * @memberof Hooks
554 */
555 mw.hook( 'RcFilters.highlight.enable' ).fire();
556 }
557 };
558
559 /**
560 * Toggle the inverted tags feature on and off
561 */
562 Controller.prototype.toggleInvertedTags = function () {
563 this.filtersModel.toggleInvertedTags();
564
565 if (
566 this.filtersModel.getFiltersByView( 'tags' ).filter(
567 ( filterItem ) => filterItem.isSelected()
568 ).length
569 ) {
570 // Only re-fetch results if there are tags items that are actually selected
571 this.updateChangesList();
572 } else {
573 this.uriProcessor.updateURL();
574 }
575 };
576
577 /**
578 * Toggle the inverted namespaces feature on and off
579 */
580 Controller.prototype.toggleInvertedNamespaces = function () {
581 this.filtersModel.toggleInvertedNamespaces();
582
583 if (
584 this.filtersModel.getFiltersByView( 'namespaces' ).filter(
585 ( filterItem ) => filterItem.isSelected()
586 ).length
587 ) {
588 // Only re-fetch results if there are namespace items that are actually selected
589 this.updateChangesList();
590 } else {
591 this.uriProcessor.updateURL();
592 }
593 };
594
595 /**
596 * Set the value of the 'showlinkedto' parameter
597 *
598 * @param {boolean} value
599 */
600 Controller.prototype.setShowLinkedTo = function ( value ) {
601 const targetItem = this.filtersModel.getGroup( 'page' ).getItemByParamName( 'target' ),
602 showLinkedToItem = this.filtersModel.getGroup( 'toOrFrom' ).getItemByParamName( 'showlinkedto' );
603
604 this.filtersModel.toggleFilterSelected( showLinkedToItem.getName(), value );
605 this.uriProcessor.updateURL();
606 // reload the results only when target is set
607 if ( targetItem.getValue() ) {
608 this.updateChangesList();
609 }
610 };
611
612 /**
613 * Set the target page
614 *
615 * @param {string} page
616 */
617 Controller.prototype.setTargetPage = function ( page ) {
618 const targetItem = this.filtersModel.getGroup( 'page' ).getItemByParamName( 'target' );
619 targetItem.setValue( page );
620 this.uriProcessor.updateURL();
621 this.updateChangesList();
622 };
623
624 /**
625 * Set the highlight color for a filter item
626 *
627 * @param {string} filterName Name of the filter item
628 * @param {string} color Selected color
629 */
630 Controller.prototype.setHighlightColor = function ( filterName, color ) {
631 this.filtersModel.setHighlightColor( filterName, color );
632 this.uriProcessor.updateURL();
633 };
634
635 /**
636 * Clear highlight for a filter item
637 *
638 * @param {string} filterName Name of the filter item
639 */
640 Controller.prototype.clearHighlightColor = function ( filterName ) {
641 this.filtersModel.clearHighlightColor( filterName );
642 this.uriProcessor.updateURL();
643 };
644
645 /**
646 * Enable or disable live updates.
647 *
648 * @param {boolean} enable True to enable, false to disable
649 */
650 Controller.prototype.toggleLiveUpdate = function ( enable ) {
651 this.changesListModel.toggleLiveUpdate( enable );
652 if ( this.changesListModel.getLiveUpdate() && this.changesListModel.getNewChangesExist() ) {
653 this.updateChangesList( null, this.LIVE_UPDATE );
654 }
655 };
656
657 /**
658 * Set a timeout for the next live update.
659 *
660 * @private
661 */
662 Controller.prototype._scheduleLiveUpdate = function () {
663 setTimeout( this._doLiveUpdate.bind( this ), this.pollingRate * 1000 );
664 };
665
666 /**
667 * Perform a live update.
668 *
669 * @private
670 */
671 Controller.prototype._doLiveUpdate = function () {
672 if ( !this._shouldCheckForNewChanges() ) {
673 // skip this turn and check back later
674 this._scheduleLiveUpdate();
675 return;
676 }
677
678 this._checkForNewChanges()
679 .then( ( statusCode ) => {
680 // no result is 204 with the 'peek' param
681 // logged out is 205
682 const newChanges = statusCode === 200;
683
684 if ( !this._shouldCheckForNewChanges() ) {
685 // by the time the response is received,
686 // it may not be appropriate anymore
687 return;
688 }
689
690 // 205 is the status code returned from server when user's logged in/out
691 // status is not matching while fetching live update changes.
692 // This works only on Recent Changes page. For WL, look _extractChangesListInfo.
693 // Bug: T177717
694 if ( statusCode === 205 ) {
695 location.reload( false );
696 return;
697 }
698
699 if ( newChanges ) {
700 if ( this.changesListModel.getLiveUpdate() ) {
701 return this.updateChangesList( null, this.LIVE_UPDATE );
702 } else {
703 this.changesListModel.setNewChangesExist( true );
704 }
705 }
706 } )
707 .always( this._scheduleLiveUpdate.bind( this ) );
708 };
709
710 /**
711 * @return {boolean} It's appropriate to check for new changes now
712 * @private
713 */
714 Controller.prototype._shouldCheckForNewChanges = function () {
715 return !document.hidden &&
716 !this.filtersModel.hasConflict() &&
717 !this.changesListModel.getNewChangesExist() &&
718 !this.updatingChangesList &&
719 this.changesListModel.getNextFrom();
720 };
721
722 /**
723 * Check if new changes, newer than those currently shown, are available
724 *
725 * @return {jQuery.Promise} Promise object that resolves with a bool
726 * specifying if there are new changes or not
727 *
728 * @private
729 */
730 Controller.prototype._checkForNewChanges = function () {
731 const params = {
732 limit: 1,
733 peek: 1, // bypasses ChangesList specific UI
734 from: this.changesListModel.getNextFrom(),
735 isAnon: mw.user.isAnon()
736 };
737 return this._queryChangesList( 'liveUpdate', params ).then(
738 ( data ) => data.status
739 );
740 };
741
742 /**
743 * Show the new changes
744 *
745 * @return {jQuery.Promise} Promise object that resolves after
746 * fetching and showing the new changes
747 */
748 Controller.prototype.showNewChanges = function () {
749 return this.updateChangesList( null, this.SHOW_NEW_CHANGES );
750 };
751
752 /**
753 * Save the current model state as a saved query
754 *
755 * @param {string} [label] Label of the saved query
756 * @param {boolean} [setAsDefault=false] This query should be set as the default
757 */
758 Controller.prototype.saveCurrentQuery = function ( label, setAsDefault ) {
759 // Add item
760 this.savedQueriesModel.addNewQuery(
761 label || mw.msg( 'rcfilters-savedqueries-defaultlabel' ),
762 this.filtersModel.getCurrentParameterState( true ),
763 setAsDefault
764 );
765
766 // Save item
767 this._saveSavedQueries();
768 };
769
770 /**
771 * Remove a saved query
772 *
773 * @param {string} queryID Query id
774 */
775 Controller.prototype.removeSavedQuery = function ( queryID ) {
776 this.savedQueriesModel.removeQuery( queryID );
777
778 this._saveSavedQueries();
779 };
780
781 /**
782 * Rename a saved query
783 *
784 * @param {string} queryID Query id
785 * @param {string} newLabel New label for the query
786 */
787 Controller.prototype.renameSavedQuery = function ( queryID, newLabel ) {
788 const queryItem = this.savedQueriesModel.getItemByID( queryID );
789
790 if ( queryItem ) {
791 queryItem.updateLabel( newLabel );
792 }
793 this._saveSavedQueries();
794 };
795
796 /**
797 * Set a saved query as default
798 *
799 * @param {string} queryID Query Id. If null is given, default
800 * query is reset.
801 */
802 Controller.prototype.setDefaultSavedQuery = function ( queryID ) {
803 this.savedQueriesModel.setDefault( queryID );
804 this._saveSavedQueries();
805 };
806
807 /**
808 * Load a saved query
809 *
810 * @param {string} queryID Query id
811 */
812 Controller.prototype.applySavedQuery = function ( queryID ) {
813 const params = this.savedQueriesModel.getItemParams( queryID );
814
815 const currentMatchingQuery = this.findQueryMatchingCurrentState();
816
817 if (
818 currentMatchingQuery &&
819 currentMatchingQuery.getID() === queryID
820 ) {
821 // If the query we want to load is the one that is already
822 // loaded, don't reload it
823 return;
824 }
825
826 if ( this.applyParamChange( params ) ) {
827 // Update changes list only if there was a difference in filter selection
828 this.updateChangesList();
829 } else {
830 this.uriProcessor.updateURL( params );
831 }
832 };
833
834 /**
835 * Check whether the current filter and highlight state exists
836 * in the saved queries model.
837 *
838 * @ignore
839 * @return {mw.rcfilters.dm.SavedQueryItemModel} Matching item model
840 */
841 Controller.prototype.findQueryMatchingCurrentState = function () {
842 return this.savedQueriesModel.findMatchingQuery(
843 this.filtersModel.getCurrentParameterState( true )
844 );
845 };
846
847 /**
848 * Save the current state of the saved queries model with all
849 * query item representation in the user settings.
850 */
851 Controller.prototype._saveSavedQueries = function () {
852 const backupPrefName = this.savedQueriesPreferenceName + '-versionbackup',
853 state = this.savedQueriesModel.getState();
854
855 // Stringify state
856 const stringified = JSON.stringify( state );
857
858 if ( byteLength( stringified ) > 65535 ) {
859 // Double check, since the preference can only hold that.
860 return;
861 }
862
863 if ( !this.wereSavedQueriesSaved && this.savedQueriesModel.isConverted() ) {
864 // The queries were converted from the previous version
865 // Keep the old string in the [prefname]-versionbackup
866 const oldPrefValue = mw.user.options.get( this.savedQueriesPreferenceName );
867
868 // Save the old preference in the backup preference
869 new mw.Api().saveOption( backupPrefName, oldPrefValue );
870 // Update the preference for this session
871 mw.user.options.set( backupPrefName, oldPrefValue );
872 }
873
874 // Save the preference
875 new mw.Api().saveOption( this.savedQueriesPreferenceName, stringified );
876 // Update the preference for this session
877 mw.user.options.set( this.savedQueriesPreferenceName, stringified );
878
879 // Tag as already saved so we don't do this again
880 this.wereSavedQueriesSaved = true;
881 };
882
883 /**
884 * Update sticky preferences with current model state
885 */
886 Controller.prototype.updateStickyPreferences = function () {
887 // Update default sticky values with selected, whether they came from
888 // the initial defaults or from the URL value that is being normalized
889 this.updateDaysDefault( this.filtersModel.getGroup( 'days' ).findSelectedItems()[ 0 ].getParamName() );
890 this.updateLimitDefault( this.filtersModel.getGroup( 'limit' ).findSelectedItems()[ 0 ].getParamName() );
891
892 // TODO: Make these automatic by having the model go over sticky
893 // items and update their default values automatically
894 };
895
896 /**
897 * Update the limit default value
898 *
899 * @param {number} newValue New value
900 */
901 Controller.prototype.updateLimitDefault = function ( newValue ) {
902 this.updateNumericPreference( this.limitPreferenceName, newValue );
903 };
904
905 /**
906 * Update the days default value
907 *
908 * @param {number} newValue New value
909 */
910 Controller.prototype.updateDaysDefault = function ( newValue ) {
911 this.updateNumericPreference( this.daysPreferenceName, newValue );
912 };
913
914 /**
915 * Update the group by page default value
916 *
917 * @param {boolean} newValue New value
918 */
919 Controller.prototype.updateGroupByPageDefault = function ( newValue ) {
920 this.updateNumericPreference( 'usenewrc', Number( newValue ) );
921 };
922
923 /**
924 * Update the collapsed state value
925 *
926 * @param {boolean} isCollapsed Filter area is collapsed
927 */
928 Controller.prototype.updateCollapsedState = function ( isCollapsed ) {
929 this.updateNumericPreference( this.collapsedPreferenceName, Number( isCollapsed ) );
930 };
931
932 /**
933 * Update a numeric preference with a new value
934 *
935 * @param {string} prefName Preference name
936 * @param {number|string} newValue New value
937 */
938 Controller.prototype.updateNumericPreference = function ( prefName, newValue ) {
939 // FIXME: $.isNumeric is deprecated
940 // eslint-disable-next-line no-jquery/no-is-numeric
941 if ( !$.isNumeric( newValue ) ) {
942 return;
943 }
944
945 if ( String( mw.user.options.get( prefName ) ) !== String( newValue ) ) {
946 // Save the preference
947 new mw.Api().saveOption( prefName, newValue );
948 // Update the preference for this session
949 mw.user.options.set( prefName, newValue );
950 }
951 };
952
953 /**
954 * Synchronize the URL with the current state of the filters
955 * without adding a history entry.
956 */
957 Controller.prototype.replaceUrl = function () {
958 this.uriProcessor.updateURL();
959 };
960
961 /**
962 * Update filter state (selection and highlighting) based
963 * on current URL values.
964 *
965 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
966 * list based on the updated model.
967 */
968 Controller.prototype.updateStateFromUrl = function ( fetchChangesList ) {
969 fetchChangesList = fetchChangesList === undefined ? true : !!fetchChangesList;
970
971 this.uriProcessor.updateModelBasedOnQuery();
972
973 // Update the sticky preferences, in case we received a value
974 // from the URL
975 this.updateStickyPreferences();
976
977 // Only update and fetch new results if it is requested
978 if ( fetchChangesList ) {
979 this.updateChangesList();
980 }
981 };
982
983 /**
984 * Update the list of changes and notify the model
985 *
986 * @param {Object} [params] Extra parameters to add to the API call
987 * @param {string} [updateMode='filterChange'] One of 'filterChange', 'liveUpdate', 'showNewChanges', 'markSeen'
988 * @return {jQuery.Promise} Promise that is resolved when the update is complete
989 */
990 Controller.prototype.updateChangesList = function ( params, updateMode ) {
991 updateMode = updateMode === undefined ? this.FILTER_CHANGE : updateMode;
992
993 if ( updateMode === this.FILTER_CHANGE ) {
994 this.uriProcessor.updateURL( params );
995 }
996 if ( updateMode === this.FILTER_CHANGE || updateMode === this.SHOW_NEW_CHANGES ) {
997 this.changesListModel.invalidate();
998 }
999 this.changesListModel.setNewChangesExist( false );
1000 this.updatingChangesList = true;
1001 return this._fetchChangesList()
1002 .then(
1003 // Success
1004 ( pieces ) => {
1005 const $changesListContent = pieces.changes,
1006 $fieldset = pieces.fieldset;
1007 this.changesListModel.update(
1008 $changesListContent,
1009 $fieldset,
1010 pieces.noResultsDetails,
1011 false,
1012 // separator between old and new changes
1013 updateMode === this.SHOW_NEW_CHANGES || updateMode === this.LIVE_UPDATE
1014 );
1015 }
1016 // Do nothing for failure
1017 )
1018 .always( () => {
1019 this.updatingChangesList = false;
1020 } );
1021 };
1022
1023 /**
1024 * Get an object representing the default parameter state, whether
1025 * it is from the model defaults or from the saved queries.
1026 *
1027 * @return {Object} Default parameters
1028 */
1029 Controller.prototype._getDefaultParams = function () {
1030 if ( this.savedQueriesModel.getDefault() ) {
1031 return this.savedQueriesModel.getDefaultParams();
1032 } else {
1033 return this.filtersModel.getDefaultParams();
1034 }
1035 };
1036
1037 /**
1038 * Query the list of changes from the server for the current filters
1039 *
1040 * @param {string} counterId 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 resolved with { content, status }
1045 */
1046 Controller.prototype._queryChangesList = function ( counterId, params ) {
1047 const uri = this.uriProcessor.getUpdatedUri(),
1048 stickyParams = this.filtersModel.getStickyParamsValues();
1049
1050 params = params || {};
1051 params.action = 'render'; // bypasses MW chrome
1052
1053 uri.extend( params );
1054
1055 this.requestCounter[ counterId ] = this.requestCounter[ counterId ] || 0;
1056 const requestId = ++this.requestCounter[ counterId ];
1057 const latestRequest = function () {
1058 return requestId === this.requestCounter[ counterId ];
1059 }.bind( this );
1060
1061 // Sticky parameters override the URL params
1062 // this is to make sure that whether we represent
1063 // the sticky params in the URL or not (they may
1064 // be normalized out) the sticky parameters are
1065 // always being sent to the server with their
1066 // current/default values
1067 uri.extend( stickyParams );
1068
1069 return $.ajax( uri.toString() )
1070 .then(
1071 ( content, message, jqXHR ) => {
1072 if ( !latestRequest() ) {
1073 return $.Deferred().reject();
1074 }
1075 return {
1076 content: content,
1077 status: jqXHR.status
1078 };
1079 },
1080 // RC returns 404 when there is no results
1081 ( jqXHR ) => {
1082 if ( latestRequest() ) {
1083 return $.Deferred().resolve(
1084 {
1085 content: jqXHR.responseText,
1086 status: jqXHR.status
1087 }
1088 ).promise();
1089 }
1090 }
1091 );
1092 };
1093
1094 /**
1095 * Fetch the list of changes from the server for the current filters
1096 *
1097 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1098 * and the fieldset.
1099 */
1100 Controller.prototype._fetchChangesList = function () {
1101 return this._queryChangesList( 'updateChangesList' )
1102 .then(
1103 ( data ) => {
1104 // Status code 0 is not HTTP status code,
1105 // but is valid value of XMLHttpRequest status.
1106 // It is used for variety of network errors, for example
1107 // when an AJAX call was cancelled before getting the response
1108 if ( data && data.status === 0 ) {
1109 return {
1110 changes: 'NO_RESULTS',
1111 // We need empty result set, to avoid exceptions because of undefined value
1112 fieldset: $( [] ),
1113 noResultsDetails: 'NO_RESULTS_NETWORK_ERROR'
1114 };
1115 }
1116
1117 const $parsed = $( '<div>' ).append( $( $.parseHTML(
1118 data ? data.content : ''
1119 ) ) );
1120
1121 return this._extractChangesListInfo( $parsed, data.status );
1122 }
1123 );
1124 };
1125
1126 /**
1127 * Apply a change of parameters to the model state, and check whether
1128 * the new state is different than the old state.
1129 *
1130 * @param {Object} newParamState New parameter state to apply
1131 * @return {boolean} New applied model state is different than the previous state
1132 */
1133 Controller.prototype.applyParamChange = function ( newParamState ) {
1134 const before = this.filtersModel.getSelectedState();
1135
1136 this.filtersModel.updateStateFromParams( newParamState );
1137
1138 const after = this.filtersModel.getSelectedState();
1139
1140 return !OO.compare( before, after );
1141 };
1142
1143 /**
1144 * Mark all changes as seen on Watchlist
1145 */
1146 Controller.prototype.markAllChangesAsSeen = function () {
1147 const api = new mw.Api();
1148 api.postWithToken( 'csrf', {
1149 formatversion: 2,
1150 action: 'setnotificationtimestamp',
1151 entirewatchlist: true
1152 } ).then( () => {
1153 this.updateChangesList( null, 'markSeen' );
1154 } );
1155 };
1156
1157 /**
1158 * Set the current search for the system.
1159 *
1160 * @param {string} searchQuery Search query, including triggers
1161 */
1162 Controller.prototype.setSearch = function ( searchQuery ) {
1163 this.filtersModel.setSearch( searchQuery );
1164 };
1165
1166 /**
1167 * Switch the view by changing the search query trigger
1168 * without changing the search term
1169 *
1170 * @param {string} view View to change to
1171 */
1172 Controller.prototype.switchView = function ( view ) {
1173 this.setSearch(
1174 this.filtersModel.getViewTrigger( view ) +
1175 this.filtersModel.removeViewTriggers( this.filtersModel.getSearch() )
1176 );
1177 };
1178
1179 /**
1180 * Reset the search for a specific view. This means we null the search query
1181 * and replace it with the relevant trigger for the requested view
1182 *
1183 * @param {string} [view='default'] View to change to
1184 */
1185 Controller.prototype.resetSearchForView = function ( view ) {
1186 view = view || 'default';
1187
1188 this.setSearch(
1189 this.filtersModel.getViewTrigger( view )
1190 );
1191 };
1192
1193 module.exports = Controller;