Debian Codegraph @

extensions/DiscussionTools/modules/dt-ve/dt.ui.UsernameCompletionAction.js

raw symbols SCIP
1 const controller = require( 'ext.discussionTools.init' ).controller;
2 let sequence = null;
3
4 function sortAuthors( a, b ) {
5 return a.username < b.username ? -1 : ( a.username === b.username ? 0 : 1 );
6 }
7
8 function hasUser( authors, username ) {
9 return authors.some( ( author ) => author.username === username );
10 }
11
12 /**
13 * MWUsernameCompletionAction action.
14 *
15 * Controls autocompletion of usernames
16 *
17 * @class
18 * @extends ve.ui.CompletionAction
19 * @constructor
20 * @param {ve.ui.Surface} surface Surface to act on
21 * @param {string} [source]
22 */
23 function MWUsernameCompletionAction() {
24 // Parent constructor
25 MWUsernameCompletionAction.super.apply( this, arguments );
26
27 // Shared API object so previous requests can be aborted
28 this.api = controller.getApi();
29 this.searchedPrefixes = {};
30 this.localUsers = [];
31 this.ipUsers = [];
32 this.surface.authors.forEach( ( author ) => {
33 if ( mw.util.isIPAddress( author.username ) ) {
34 this.ipUsers.push( author );
35 } else if ( author.username !== mw.user.getName() ) {
36 this.localUsers.push( author );
37 }
38 } );
39 // On user talk pages, always list the "owner" of the talk page
40 const relevantUserName = mw.config.get( 'wgRelevantUserName' );
41 if (
42 relevantUserName &&
43 relevantUserName !== mw.user.getName() &&
44 !hasUser( this.localUsers, relevantUserName )
45 ) {
46 this.localUsers.push( {
47 username: relevantUserName,
48 displayNames: []
49 } );
50 this.localUsers.sort( sortAuthors );
51 }
52 this.remoteUsers = [];
53 this.sequenceAdded = false;
54 }
55
56 /* Inheritance */
57
58 OO.inheritClass( MWUsernameCompletionAction, ve.ui.CompletionAction );
59
60 /* Static Properties */
61
62 MWUsernameCompletionAction.static.name = 'mwUsernameCompletion';
63
64 MWUsernameCompletionAction.static.methods = OO.copy( MWUsernameCompletionAction.static.methods );
65 MWUsernameCompletionAction.static.methods.push( 'insertAndOpen' );
66
67 /* Methods */
68
69 MWUsernameCompletionAction.prototype.insertAndOpen = function () {
70 let inserted = false;
71 const surfaceModel = this.surface.getModel(),
72 fragment = surfaceModel.getFragment();
73
74 // This is opening a window in a slightly weird way, so the normal logging
75 // doesn't catch it. This assumes that the only way to get here is from
76 // the tool. If we add other paths, we'd need to change the logging.
77 ve.track(
78 'activity.' + this.constructor.static.name,
79 { action: 'window-open-from-tool' }
80 );
81
82 // Run the sequence matching logic again to check
83 // if we already have the sequence inserted at the
84 // current offset.
85 if ( fragment.getSelection().isCollapsed() ) {
86 inserted = this.surface.getView().findMatchingSequences()
87 .some( ( item ) => item.sequence === sequence );
88 }
89
90 if ( !inserted ) {
91 fragment.insertContent( '@' );
92 }
93 fragment.collapseToEnd().select();
94
95 this.sequenceAdded = true;
96
97 return this.open();
98 };
99
100 MWUsernameCompletionAction.prototype.getSequenceLength = function () {
101 if ( this.sequenceAdded ) {
102 return this.constructor.static.sequenceLength;
103 }
104 // Parent method
105 return MWUsernameCompletionAction.super.prototype.getSequenceLength.apply( this, arguments );
106 };
107
108 MWUsernameCompletionAction.prototype.getSuggestions = function ( input ) {
109 const title = mw.Title.makeTitle( mw.config.get( 'wgNamespaceIds' ).user, input ),
110 validatedInput = title ? input : '',
111 action = this;
112
113 this.api.abort(); // Abort all unfinished API requests
114 let apiPromise;
115 if ( input.length > 0 && !this.searchedPrefixes[ input ] ) {
116 apiPromise = this.api.get( {
117 action: 'query',
118 list: 'allusers',
119 auprefix: input,
120 auprop: 'blockinfo',
121 auwitheditsonly: 1,
122 // Fetch twice as many results as we need so we can filter
123 // blocked users and still probably have some suggestions left
124 aulimit: this.constructor.static.defaultLimit * 2
125 } ).then( ( response ) => {
126 const suggestions = response.query.allusers.filter(
127 // API doesn't return IPs
128 ( user ) => !hasUser( action.localUsers, user.name ) &&
129 !hasUser( action.remoteUsers, user.name ) &&
130 // Exclude users with indefinite sitewide blocks:
131 // The only place such users could reply is on their
132 // own user talk page, and in that case the user
133 // will be included in localUsers.
134 !( user.blockexpiry === 'infinite' && !user.blockpartial )
135 ).map( ( user ) => ( {
136 username: user.name,
137 displayNames: []
138 } ) );
139
140 action.remoteUsers.push.apply( action.remoteUsers, suggestions );
141 action.remoteUsers.sort( sortAuthors );
142
143 action.searchedPrefixes[ input ] = true;
144 } );
145 } else {
146 apiPromise = ve.createDeferred().resolve().promise();
147 }
148
149 return apiPromise.then(
150 // By concatenating on-thread authors and remote-fetched authors, both
151 // sorted alphabetically, we'll get our suggestion popup sorted so all
152 // on-thread matches come first.
153 () => action.filterSuggestionsForInput(
154 action.localUsers
155 // Show no remote users if no input provided
156 .concat( input.length > 0 ? action.remoteUsers : [] ),
157 // TODO: Consider showing IP users
158 // * Change link to Special:Contributions/<ip> (localised)
159 // * Let users know that mentioning an IP will not create a notification?
160 // .concat( this.ipUsers )
161 validatedInput
162 )
163 );
164 };
165
166 /**
167 * @inheritdoc
168 */
169 MWUsernameCompletionAction.prototype.compareSuggestionToInput = function ( suggestion, normalizedInput ) {
170 const normalizedSuggestion = suggestion.username.toLowerCase(),
171 normalizedSearchIndex = normalizedSuggestion + ' ' +
172 suggestion.displayNames
173 .map( ( displayName ) => displayName.toLowerCase() ).join( ' ' );
174
175 return {
176 isMatch: normalizedSearchIndex.indexOf( normalizedInput ) !== -1,
177 isExact: normalizedSuggestion === normalizedInput
178 };
179 };
180
181 /**
182 * Create a suggestion from an input
183 *
184 * @param {string} input User input
185 * @return {any} Suggestion data, string by default
186 */
187 MWUsernameCompletionAction.prototype.createSuggestion = function ( input ) {
188 return {
189 username: input,
190 displayNames: []
191 };
192 };
193
194 MWUsernameCompletionAction.prototype.getMenuItemForSuggestion = function ( suggestion ) {
195 return new OO.ui.MenuOptionWidget( { data: suggestion.username, label: suggestion.username } );
196 };
197
198 MWUsernameCompletionAction.prototype.getHeaderLabel = function ( input, suggestions ) {
199 if ( suggestions === undefined ) {
200 const $query = $( '<span>' ).text( input );
201 return mw.message( 'discussiontools-replywidget-mention-tool-header', $query ).parseDom();
202 }
203 };
204
205 MWUsernameCompletionAction.prototype.insertCompletion = function ( word, range ) {
206 const prefix = mw.msg( 'discussiontools-replywidget-mention-prefix' ),
207 suffix = mw.msg( 'discussiontools-replywidget-mention-suffix' ),
208 title = mw.Title.newFromText( word, mw.config.get( 'wgNamespaceIds' ).user );
209
210 if ( this.surface.getMode() === 'source' ) {
211 // TODO: this should be configurable per-wiki so that e.g. custom templates can be used
212 word = prefix + '[[' + title.getPrefixedText() + '|' + word + ']]' + suffix;
213 return MWUsernameCompletionAction.super.prototype.insertCompletion.call( this, word, range );
214 }
215
216 const fragment = this.surface.getModel().getLinearFragment( range, true );
217 fragment.removeContent().insertContent( [
218 { type: 'mwPing', attributes: { user: word } },
219 { type: '/mwPing' }
220 ] );
221
222 fragment.collapseToEnd();
223
224 return fragment;
225 };
226
227 MWUsernameCompletionAction.prototype.shouldAbandon = function ( input ) {
228 // TODO: need to consider whether pending loads from server are happening here
229 return MWUsernameCompletionAction.super.prototype.shouldAbandon.apply( this, arguments ) && (
230 // Abandon if the user hit space immediately
231 input.match( /^\s+$/ ) ||
232 // Abandon if there's more than two words entered without a match
233 input.split( /\s+/ ).length > 2
234 );
235 };
236
237 /* Registration */
238
239 ve.ui.actionFactory.register( MWUsernameCompletionAction );
240
241 const openCommand = new ve.ui.Command(
242 'openMWUsernameCompletions', MWUsernameCompletionAction.static.name, 'open',
243 { supportedSelections: [ 'linear' ] }
244 );
245 const insertAndOpenCommand = new ve.ui.Command(
246 'insertAndOpenMWUsernameCompletions', MWUsernameCompletionAction.static.name, 'insertAndOpen',
247 { supportedSelections: [ 'linear' ] }
248 );
249 sequence = new ve.ui.Sequence( 'autocompleteMWUsernames', 'openMWUsernameCompletions', '@', 0 );
250 ve.ui.commandRegistry.register( openCommand );
251 ve.ui.commandRegistry.register( insertAndOpenCommand );
252 ve.ui.wikitextCommandRegistry.register( openCommand );
253 ve.ui.wikitextCommandRegistry.register( insertAndOpenCommand );
254 ve.ui.sequenceRegistry.register( sequence );
255 ve.ui.wikitextSequenceRegistry.register( sequence );
256
257 module.exports = MWUsernameCompletionAction;