Debian Codegraph @

extensions/VisualEditor/modules/ve-mw/ui/widgets/ve.ui.MWCategoryWidget.js

raw symbols SCIP
1 /*!
2 * VisualEditor UserInterface MWCategoryWidget class.
3 *
4 * @copyright See AUTHORS.txt
5 * @license The MIT License (MIT); see LICENSE.txt
6 */
7
8 /**
9 * Creates an ve.ui.MWCategoryWidget object.
10 *
11 * @class
12 * @abstract
13 * @extends OO.ui.Widget
14 * @mixes OO.ui.mixin.GroupElement
15 * @mixes OO.ui.mixin.DraggableGroupElement
16 *
17 * @constructor
18 * @param {Object} [config] Configuration options
19 * @param {jQuery} [config.$overlay] Overlay to render dropdowns in
20 */
21 ve.ui.MWCategoryWidget = function VeUiMWCategoryWidget( config ) {
22 // Config initialization
23 config = config || {};
24
25 // Parent constructor
26 ve.ui.MWCategoryWidget.super.call( this, config );
27
28 // Mixin constructors
29 OO.ui.mixin.GroupElement.call( this, config );
30 OO.ui.mixin.DraggableGroupElement.call( this, ve.extendObject( {}, config, { orientation: 'horizontal' } ) );
31
32 const categoryNamespace = mw.config.get( 'wgNamespaceIds' ).category;
33 // Properties
34 this.fragment = null;
35 this.categories = {};
36 // Source -> target
37 this.categoryRedirects = {};
38 // Title cache - will contain entries even if title is already normalized
39 this.normalizedTitles = {};
40 this.popup = new ve.ui.MWCategoryPopupWidget();
41 this.input = new ve.ui.MWCategoryInputWidget( this, { $overlay: config.$overlay } );
42 this.forceCapitalization = mw.config.get( 'wgCaseSensitiveNamespaces' ).indexOf( categoryNamespace ) === -1;
43 this.categoryPrefix = mw.config.get( 'wgFormattedNamespaces' )[ categoryNamespace ] + ':';
44 this.expandedItem = null;
45
46 // Events
47 this.input.connect( this, { choose: 'onInputChoose' } );
48 this.popup.connect( this, {
49 removeCategory: 'onRemoveCategory',
50 updateSortkey: 'onUpdateSortkey',
51 ready: 'onPopupOpened',
52 closing: 'onPopupClosing'
53 } );
54 this.connect( this, {
55 drag: 'onDrag'
56 } );
57
58 // Initialization
59 this.$element.addClass( 've-ui-mwCategoryWidget' )
60 .append(
61 this.$group.addClass( 've-ui-mwCategoryWidget-items' ).append(
62 this.input.$element
63 ),
64 this.popup.$element,
65 $( '<div>' ).css( 'clear', 'both' )
66 );
67 };
68
69 /* Inheritance */
70
71 OO.inheritClass( ve.ui.MWCategoryWidget, OO.ui.Widget );
72
73 OO.mixinClass( ve.ui.MWCategoryWidget, OO.ui.mixin.GroupElement );
74 OO.mixinClass( ve.ui.MWCategoryWidget, OO.ui.mixin.DraggableGroupElement );
75
76 /* Events */
77
78 /**
79 * @event ve.ui.MWCategoryWidget#newCategory
80 * @param {Object} item Category item
81 * @param {string} item.name Fully prefixed category name
82 * @param {string} item.value Category value (name without prefix)
83 * @param {ve.dm.MWCategoryMetaItem} item.metaItem
84 * @param {ve.dm.MetaItem} [beforeCategory] Insert after this category; if unset, insert at the end
85 */
86
87 /**
88 * @event ve.ui.MWCategoryWidget#updateSortkey
89 * @param {Object} item Category item
90 * @param {string} item.name Fully prefixed category name
91 * @param {string} item.value Category value (name without prefix)
92 * @param {ve.dm.MWCategoryMetaItem} item.metaItem
93 */
94
95 /* Methods */
96
97 /**
98 * Surface fragment for modifying meta list
99 *
100 * @param {ve.dm.SurfaceFragment|null} fragment Surface fragment
101 */
102 ve.ui.MWCategoryWidget.prototype.setFragment = function ( fragment ) {
103 this.fragment = fragment;
104 };
105
106 /**
107 * Handle input 'choose' event.
108 *
109 * @param {OO.ui.MenuOptionWidget} item Selected item
110 */
111 ve.ui.MWCategoryWidget.prototype.onInputChoose = function ( item ) {
112 const value = item.getData();
113
114 if ( value && value !== '' ) {
115 // Add new item
116 const categoryItem = this.getCategoryItemFromValue( value );
117 this.queryCategoryStatus( [ categoryItem.name ] ).done( () => {
118 // Remove existing items by name
119 const toRemove = mw.Title.newFromText( categoryItem.name ).getMainText();
120 if ( Object.prototype.hasOwnProperty.call( this.categories, toRemove ) ) {
121 this.fragment.removeMeta( this.categories[ toRemove ].metaItem );
122 }
123 categoryItem.name = this.normalizedTitles[ categoryItem.name ];
124 this.emit( 'newCategory', categoryItem );
125 } );
126 }
127 };
128
129 /**
130 * Hanle popup open event
131 *
132 */
133 ve.ui.MWCategoryWidget.prototype.onPopupOpened = function () {
134 this.popup.removeButton.focus();
135 };
136
137 /**
138 * Handle popup closing dialog
139 */
140 ve.ui.MWCategoryWidget.prototype.onPopupClosing = function () {
141 this.expandedItem.focus();
142 };
143
144 /**
145 * Get a category item.
146 *
147 * @param {string} value Category name
148 * @return {Object} Category item with name, value and metaItem properties
149 */
150 ve.ui.MWCategoryWidget.prototype.getCategoryItemFromValue = function ( value ) {
151 // Normalize
152 const title = mw.Title.newFromText( this.categoryPrefix + value );
153 if ( title ) {
154 return {
155 name: title.getPrefixedText(),
156 value: title.getMainText(),
157 metaItem: {}
158 };
159 }
160
161 if ( this.forceCapitalization ) {
162 value = value.slice( 0, 1 ).toUpperCase() + value.slice( 1 );
163 }
164
165 return {
166 name: this.categoryPrefix + value,
167 value: value,
168 metaItem: {}
169 };
170 };
171
172 /**
173 * Focus the widget
174 */
175 ve.ui.MWCategoryWidget.prototype.focus = function () {
176 this.input.$input[ 0 ].focus();
177 };
178
179 /**
180 * @param {ve.ui.MWCategoryItemWidget} item Item that was moved
181 * @param {number} newIndex The new index of the item
182 */
183 ve.ui.MWCategoryWidget.prototype.onDrag = function () {
184 this.fitInput();
185 };
186
187 /**
188 * @inheritdoc OO.ui.mixin.DraggableGroupElement
189 * @fires ve.ui.MWCategoryWidget#newCategory
190 */
191 ve.ui.MWCategoryWidget.prototype.reorder = function ( item, newIndex ) {
192 // Compute beforeCategory before removing, otherwise newIndex
193 // could be off by one
194 const beforeCategory = this.items[ newIndex ] && this.items[ newIndex ].metaItem;
195 if ( Object.prototype.hasOwnProperty.call( this.categories, item.value ) ) {
196 this.fragment.removeMeta( this.categories[ item.value ].metaItem );
197 }
198
199 this.emit( 'newCategory', item, beforeCategory );
200 };
201
202 /**
203 * Removes category from model.
204 *
205 * @param {string} name Removed category name
206 */
207 ve.ui.MWCategoryWidget.prototype.onRemoveCategory = function ( name ) {
208 this.fragment.removeMeta( this.categories[ name ].metaItem );
209 delete this.categories[ name ];
210 };
211
212 /**
213 * Update sortkey value, emit updateSortkey event
214 *
215 * @param {string} name
216 * @param {string} value
217 * @fires ve.ui.MWCategoryWidget#updateSortkey
218 */
219 ve.ui.MWCategoryWidget.prototype.onUpdateSortkey = function ( name, value ) {
220 this.categories[ name ].sortKey = value;
221 this.emit( 'updateSortkey', this.categories[ name ] );
222 };
223
224 /**
225 * @inheritdoc
226 */
227 ve.ui.MWCategoryWidget.prototype.clearItems = function () {
228 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
229 this.categories = {};
230 };
231
232 /**
233 * Toggles popup menu per category item
234 *
235 * @param {Object} item
236 */
237 ve.ui.MWCategoryWidget.prototype.onTogglePopupMenu = function ( item ) {
238 // Close open popup.
239 if ( item.value !== this.popup.category ) {
240 this.popup.openPopup( item );
241 this.expandedItem = item;
242 this.popup
243 .$element
244 .attr( 'aria-label',
245 ve.msg( 'visualeditor-dialog-meta-categories-category' )
246 );
247 } else {
248 // Handle toggle
249 this.popup.closePopup();
250 }
251 };
252
253 /**
254 * Set the default sort key.
255 *
256 * @param {string} value Default sort key value
257 */
258 ve.ui.MWCategoryWidget.prototype.setDefaultSortKey = function ( value ) {
259 this.popup.setDefaultSortKey( value );
260 };
261
262 /**
263 * @inheritdoc
264 */
265 ve.ui.MWCategoryWidget.prototype.setDisabled = function () {
266 // Parent method
267 ve.ui.MWCategoryWidget.super.prototype.setDisabled.apply( this, arguments );
268
269 const isDisabled = this.isDisabled();
270
271 if ( this.input ) {
272 this.input.setDisabled( isDisabled );
273 }
274 if ( this.items ) {
275 this.items.forEach( ( item ) => {
276 item.setDisabled( isDisabled );
277 } );
278 }
279 if ( this.popup ) {
280 this.popup.closePopup();
281 }
282 };
283
284 /**
285 * Get list of category names.
286 *
287 * @return {string[]} List of category names
288 */
289 ve.ui.MWCategoryWidget.prototype.getCategories = function () {
290 return Object.keys( this.categories );
291 };
292
293 /**
294 * Starts a request to update the link cache's hidden and missing status for
295 * the given titles, following normalisation responses as necessary.
296 *
297 * @param {string[]} categoryNames
298 * @return {jQuery.Promise}
299 */
300 ve.ui.MWCategoryWidget.prototype.queryCategoryStatus = function ( categoryNames ) {
301 // Get rid of any we already know the hidden status of, or have an entry
302 // if normalizedTitles (i.e. have been fetched before)
303 const categoryNamesToQuery = categoryNames.filter( ( name ) => {
304 if ( this.normalizedTitles[ name ] ) {
305 return false;
306 }
307 const cacheEntry = ve.init.platform.linkCache.getCached( name );
308 if ( cacheEntry && cacheEntry.hidden ) {
309 // As we aren't doing an API request for this category, mark it in the cache.
310 this.normalizedTitles[ name ] = name;
311 return false;
312 }
313 return true;
314 } );
315
316 if ( !categoryNamesToQuery.length ) {
317 return ve.createDeferred().resolve( {} ).promise();
318 }
319
320 let index = 0;
321 const batchSize = 50, promises = [];
322 // Batch this up into groups of 50
323 while ( index < categoryNamesToQuery.length ) {
324 promises.push( ve.init.target.getContentApi().get( {
325 action: 'query',
326 prop: 'pageprops',
327 titles: categoryNamesToQuery.slice( index, index + batchSize ),
328 ppprop: 'hiddencat',
329 redirects: ''
330 } ).then( ( result ) => {
331 const linkCacheUpdate = {},
332 normalizedTitles = {};
333 if ( result && result.query && result.query.pages ) {
334 result.query.pages.forEach( ( pageInfo ) => {
335 linkCacheUpdate[ pageInfo.title ] = {
336 missing: Object.prototype.hasOwnProperty.call( pageInfo, 'missing' ),
337 hidden: pageInfo.pageprops &&
338 Object.prototype.hasOwnProperty.call( pageInfo.pageprops, 'hiddencat' )
339 };
340 } );
341 }
342 if ( result && result.query && result.query.redirects ) {
343 result.query.redirects.forEach( ( redirectInfo ) => {
344 this.categoryRedirects[ redirectInfo.from ] = redirectInfo.to;
345 } );
346 }
347 ve.init.platform.linkCache.set( linkCacheUpdate );
348
349 if ( result.query && result.query.normalized ) {
350 result.query.normalized.forEach( ( normalisation ) => {
351 normalizedTitles[ normalisation.from ] = normalisation.to;
352 } );
353 }
354
355 categoryNames.forEach( ( name ) => {
356 this.normalizedTitles[ name ] = normalizedTitles[ name ] || name;
357 } );
358 } ) );
359 index += batchSize;
360 }
361
362 return ve.promiseAll( promises );
363 };
364
365 /**
366 * Adds category items.
367 *
368 * @param {Object[]} items Items to add
369 * @param {number} [index] Index to insert items after
370 * @return {jQuery.Promise}
371 */
372 ve.ui.MWCategoryWidget.prototype.addItems = function ( items, index ) {
373 const categoryItems = [],
374 // eslint-disable-next-line no-jquery/no-map-util
375 categoryNames = $.map( items, ( item ) => item.name );
376
377 return this.queryCategoryStatus( categoryNames ).then( () => {
378 let config;
379 const checkValueMatches = function ( existingCategoryItem ) {
380 return config.item.value === existingCategoryItem.value;
381 };
382
383 items.forEach( ( item ) => {
384 item.name = this.normalizedTitles[ item.name ];
385
386 const itemTitle = new mw.Title( item.name, mw.config.get( 'wgNamespaceIds' ).category );
387 // Create a widget using the item data
388 config = {
389 item: item
390 };
391 let cachedData;
392 if ( Object.prototype.hasOwnProperty.call( this.categoryRedirects, itemTitle.getPrefixedText() ) ) {
393 config.redirectTo = new mw.Title(
394 this.categoryRedirects[ itemTitle.getPrefixedText() ],
395 mw.config.get( 'wgNamespaceIds' ).category
396 ).getMainText();
397 cachedData = ve.init.platform.linkCache.getCached( this.categoryRedirects[ itemTitle.getPrefixedText() ] );
398 } else {
399 cachedData = ve.init.platform.linkCache.getCached( item.name );
400 }
401 config.hidden = cachedData.hidden;
402 config.missing = cachedData.missing;
403 config.disabled = this.disabled;
404
405 const categoryItem = new ve.ui.MWCategoryItemWidget( config );
406 categoryItem.connect( this, {
407 togglePopupMenu: 'onTogglePopupMenu'
408 } );
409
410 // Index item
411 this.categories[ itemTitle.getMainText() ] = categoryItem;
412 // Copy sortKey from old item when "moving"
413 const existingCategoryItems = this.items.filter( checkValueMatches );
414 if ( existingCategoryItems.length ) {
415 // There should only be one element in existingCategoryItems
416 categoryItem.sortKey = existingCategoryItems[ 0 ].sortKey;
417 this.removeItems( [ existingCategoryItems[ 0 ] ] );
418 }
419
420 categoryItems.push( categoryItem );
421 } );
422
423 OO.ui.mixin.DraggableGroupElement.prototype.addItems.call( this, categoryItems, index );
424
425 // Ensure the input remains the last item in the list, and preserve focus
426 const hadFocus = this.getElementDocument().activeElement === this.input.$input[ 0 ];
427 this.$group.append( this.input.$element );
428 if ( hadFocus ) {
429 this.input.$input[ 0 ].focus();
430 }
431 this.fitInput();
432 } );
433 };
434
435 /**
436 * @inheritdoc
437 */
438 ve.ui.MWCategoryWidget.prototype.removeItems = function ( items ) {
439 for ( let i = 0, len = items.length; i < len; i++ ) {
440 const categoryItem = items[ i ];
441 if ( categoryItem ) {
442 categoryItem.disconnect( this );
443 items.push( categoryItem );
444 delete this.categories[ categoryItem.value ];
445 }
446 }
447
448 OO.ui.mixin.DraggableGroupElement.prototype.removeItems.call( this, items );
449
450 this.fitInput();
451 };
452
453 /**
454 * Auto-fit the input.
455 */
456 ve.ui.MWCategoryWidget.prototype.fitInput = function () {
457 const $input = this.input.$element;
458
459 // eslint-disable-next-line no-jquery/no-sizzle
460 if ( !this.items.length || !$input.is( ':visible' ) ) {
461 return;
462 }
463
464 // Measure the input's natural size
465 $input.css( 'width', '' );
466 const inputWidth = $input.outerWidth( true );
467
468 // this.items hasn't been updated if this was triggered by a drag event,
469 // so look at document order
470 const $lastItem = this.$group.find( '.ve-ui-mwCategoryItemWidget' ).last();
471 // Try to fit to the right of the last item
472 const availableSpace = Math.floor( this.$group.width() - ( $lastItem.position().left + $lastItem.outerWidth( true ) ) );
473 if ( availableSpace > inputWidth ) {
474 $input.css( 'width', availableSpace );
475 }
476 };