Debian Codegraph @

extensions/VisualEditor/modules/ve-mw/ui/dialogs/ve.ui.MWGalleryDialog.js

raw symbols SCIP
1 /*!
2 * VisualEditor user interface MWGalleryDialog class.
3 *
4 * @copyright See AUTHORS.txt
5 * @license The MIT License (MIT); see LICENSE.txt
6 */
7
8 /**
9 * Dialog for editing MediaWiki galleries.
10 *
11 * @class
12 * @extends ve.ui.NodeDialog
13 *
14 * @constructor
15 * @param {Object} [config] Configuration options
16 */
17 ve.ui.MWGalleryDialog = function VeUiMWGalleryDialog() {
18 // Parent constructor
19 ve.ui.MWGalleryDialog.super.apply( this, arguments );
20
21 this.$element.addClass( 've-ui-mwGalleryDialog' );
22 };
23
24 /* Inheritance */
25
26 OO.inheritClass( ve.ui.MWGalleryDialog, ve.ui.NodeDialog );
27
28 /* Static properties */
29
30 ve.ui.MWGalleryDialog.static.name = 'gallery';
31
32 ve.ui.MWGalleryDialog.static.size = 'large';
33
34 ve.ui.MWGalleryDialog.static.title =
35 OO.ui.deferMsg( 'visualeditor-mwgallerydialog-title' );
36
37 ve.ui.MWGalleryDialog.static.modelClasses = [ ve.dm.MWGalleryNode ];
38
39 ve.ui.MWGalleryDialog.static.includeCommands = null;
40
41 ve.ui.MWGalleryDialog.static.excludeCommands = [
42 // No formatting
43 'paragraph',
44 'heading1',
45 'heading2',
46 'heading3',
47 'heading4',
48 'heading5',
49 'heading6',
50 'preformatted',
51 'blockquote',
52 // No block-level markup is allowed inside gallery caption (or gallery image captions)
53 // No tables
54 'insertTable',
55 'deleteTable',
56 'mergeCells',
57 'tableCaption',
58 'tableCellHeader',
59 'tableCellData',
60 // No structure
61 'bullet',
62 'bulletWrapOnce',
63 'number',
64 'numberWrapOnce',
65 'indent',
66 'outdent',
67 // Nested galleries don't work either
68 'gallery'
69 ];
70
71 /**
72 * Get the import rules for the surface widget in the dialog
73 *
74 * @see ve.dm.ElementLinearData#sanitize
75 * @return {Object} Import rules
76 */
77 ve.ui.MWGalleryDialog.static.getImportRules = function () {
78 const rules = ve.copy( ve.init.target.constructor.static.importRules );
79 return ve.extendObject(
80 rules,
81 {
82 all: {
83 blacklist: ve.extendObject(
84 {
85 // No block-level markup is allowed inside gallery caption (or gallery image captions).
86 // No lists, no tables.
87 list: true,
88 listItem: true,
89 definitionList: true,
90 definitionListItem: true,
91 table: true,
92 tableCaption: true,
93 tableSection: true,
94 tableRow: true,
95 tableCell: true,
96 mwTable: true,
97 mwTransclusionTableCell: true,
98 // Nested galleries don't work either
99 mwGallery: true
100 },
101 ve.getProp( rules, 'all', 'blacklist' )
102 ),
103 // Headings are also possible, but discouraged
104 conversions: ve.extendObject(
105 {
106 mwHeading: 'paragraph'
107 },
108 ve.getProp( rules, 'all', 'conversions' )
109 )
110 }
111 }
112 );
113 };
114
115 /* Methods */
116
117 /**
118 * @inheritdoc
119 */
120 ve.ui.MWGalleryDialog.prototype.initialize = function () {
121 // Parent method
122 ve.ui.MWGalleryDialog.super.prototype.initialize.call( this );
123
124 // States
125 this.highlightedItem = null;
126 this.searchPanelVisible = false;
127 this.selectedFilenames = {};
128 this.initialImageData = [];
129 this.originalMwDataNormalized = null;
130 this.originalGalleryGroupItems = [];
131 this.imageData = {};
132 this.isMobile = OO.ui.isMobile();
133
134 // Default settings
135 this.defaults = mw.config.get( 'wgVisualEditorConfig' ).galleryOptions;
136
137 // Images and options tab panels
138 this.indexLayout = new OO.ui.IndexLayout();
139 const imagesTabPanel = new OO.ui.TabPanelLayout( 'images', {
140 label: ve.msg( 'visualeditor-mwgallerydialog-card-images' ),
141 // Contains a menu layout which handles its own scrolling
142 scrollable: false,
143 padded: true
144 } );
145 const optionsTabPanel = new OO.ui.TabPanelLayout( 'options', {
146 label: ve.msg( 'visualeditor-mwgallerydialog-card-options' ),
147 padded: true
148 } );
149
150 // Images tab panel
151
152 // General layout
153 const imageListContentPanel = new OO.ui.PanelLayout( {
154 padded: true,
155 expanded: true,
156 scrollable: true
157 } );
158 const imageListMenuPanel = new OO.ui.PanelLayout( {
159 padded: true,
160 expanded: true
161 } );
162 this.imageListMenuLayout = new OO.ui.MenuLayout( {
163 menuPosition: this.isMobile ? 'after' : 'bottom',
164 classes: [
165 've-ui-mwGalleryDialog-imageListMenuLayout',
166 this.isMobile ?
167 've-ui-mwGalleryDialog-imageListMenuLayout-mobile' :
168 've-ui-mwGalleryDialog-imageListMenuLayout-desktop'
169 ],
170 contentPanel: imageListContentPanel,
171 menuPanel: imageListMenuPanel
172 } );
173 this.editPanel = new OO.ui.PanelLayout( {
174 padded: true,
175 expanded: true,
176 scrollable: true
177 } );
178 this.searchPanel = new OO.ui.PanelLayout( {
179 padded: true,
180 expanded: true,
181 scrollable: true
182 } );
183 this.editSearchStack = new OO.ui.StackLayout( {
184 items: [ this.editPanel, this.searchPanel ]
185 } );
186 this.imageTabMenuLayout = new OO.ui.MenuLayout( {
187 menuPosition: this.isMobile ? 'top' : 'before',
188 classes: [
189 've-ui-mwGalleryDialog-menuLayout',
190 this.isMobile ?
191 've-ui-mwGalleryDialog-menuLayout-mobile' :
192 've-ui-mwGalleryDialog-menuLayout-desktop'
193 ],
194 menuPanel: this.imageListMenuLayout,
195 contentPanel: this.editSearchStack
196 } );
197
198 // Menu
199 this.$emptyGalleryMessage = $( '<div>' )
200 .addClass( 'oo-ui-element-hidden' )
201 .text( ve.msg( 'visualeditor-mwgallerydialog-empty-gallery-message' ) );
202 this.galleryGroup = new ve.ui.MWGalleryGroupWidget( {
203 orientation: this.isMobile ? 'horizontal' : 'vertical'
204 } );
205 this.showSearchPanelButton = new OO.ui.ButtonWidget( {
206 label: ve.msg( 'visualeditor-mwgallerydialog-search-button-label' ),
207 invisibleLabel: !!this.isMobile,
208 icon: 'add',
209 framed: false,
210 flags: [ 'progressive' ],
211 classes: [ 've-ui-mwGalleryDialog-show-search-panel-button' ]
212 } );
213
214 // Edit panel
215 this.filenameFieldset = new OO.ui.FieldsetLayout( {
216 label: ve.msg( 'visualeditor-dialog-media-content-filename' ),
217 icon: 'image'
218 } );
219 this.$highlightedImage = $( '<div>' )
220 .addClass( 've-ui-mwGalleryDialog-highlighted-image mw-no-invert' );
221 this.filenameFieldset.$element.append( this.$highlightedImage );
222 this.highlightedCaptionTarget = ve.init.target.createTargetWidget( {
223 includeCommands: this.constructor.static.includeCommands,
224 excludeCommands: this.constructor.static.excludeCommands,
225 importRules: this.constructor.static.getImportRules(),
226 multiline: false
227 } );
228 this.highlightedAltTextInput = new OO.ui.TextInputWidget( {
229 placeholder: ve.msg( 'visualeditor-dialog-media-alttext-section' )
230 } );
231 this.altTextSameAsCaption = new OO.ui.CheckboxInputWidget();
232 this.removeButton = new OO.ui.ButtonWidget( {
233 label: ve.msg( 'visualeditor-mwgallerydialog-remove-button-label' ),
234 icon: 'trash',
235 flags: [ 'destructive' ],
236 classes: [ 've-ui-mwGalleryDialog-remove-button' ]
237 } );
238
239 const highlightedCaptionField = new OO.ui.FieldLayout( this.highlightedCaptionTarget, {
240 align: 'top'
241 } );
242 const highlightedCaptionFieldset = new OO.ui.FieldsetLayout( {
243 label: ve.msg( 'visualeditor-dialog-media-content-section' )
244 } );
245 highlightedCaptionFieldset.addItems( [ highlightedCaptionField ] );
246
247 const highlightedAltTextField = new OO.ui.FieldLayout( this.highlightedAltTextInput, {
248 align: 'top'
249 } );
250 const altTextSameAsCaptionField = new OO.ui.FieldLayout( this.altTextSameAsCaption, {
251 align: 'inline',
252 label: ve.msg( 'visualeditor-dialog-media-alttext-checkbox' )
253 } );
254 const highlightedAltTextFieldset = new OO.ui.FieldsetLayout( {
255 label: ve.msg( 'visualeditor-dialog-media-alttext-section' )
256 } );
257 highlightedAltTextFieldset.addItems( [
258 highlightedAltTextField,
259 altTextSameAsCaptionField
260 ] );
261
262 // Search panel
263 this.searchWidget = new mw.widgets.MediaSearchWidget( {
264 rowHeight: this.isMobile ? 100 : 150
265 } );
266
267 // Options tab panel
268
269 // Input widgets
270 this.modeDropdown = new OO.ui.DropdownWidget( { menu: { items: [
271 'traditional',
272 'nolines',
273 'packed',
274 'packed-overlay',
275 'packed-hover',
276 'slideshow'
277 ].map( ( data ) => new OO.ui.MenuOptionWidget( {
278 data: data,
279 // Messages used here:
280 // * visualeditor-mwgallerydialog-mode-dropdown-label-traditional
281 // * visualeditor-mwgallerydialog-mode-dropdown-label-nolines
282 // * visualeditor-mwgallerydialog-mode-dropdown-label-packed
283 // * visualeditor-mwgallerydialog-mode-dropdown-label-packed-overlay
284 // * visualeditor-mwgallerydialog-mode-dropdown-label-packed-hover
285 // * visualeditor-mwgallerydialog-mode-dropdown-label-slideshow
286 label: ve.msg( 'visualeditor-mwgallerydialog-mode-dropdown-label-' + data )
287 } ) ) } } );
288 this.captionTarget = ve.init.target.createTargetWidget( {
289 includeCommands: this.constructor.static.includeCommands,
290 excludeCommands: this.constructor.static.excludeCommands,
291 importRules: this.constructor.static.getImportRules(),
292 multiline: false
293 } );
294 this.widthsInput = new OO.ui.NumberInputWidget( {
295 min: 0,
296 showButtons: false,
297 input: {
298 placeholder: ve.msg( 'visualeditor-mwgallerydialog-widths-input-placeholder', this.defaults.imageWidth )
299 }
300 } );
301 this.heightsInput = new OO.ui.NumberInputWidget( {
302 min: 0,
303 showButtons: false,
304 input: {
305 placeholder: ve.msg( 'visualeditor-mwgallerydialog-heights-input-placeholder', this.defaults.imageHeight )
306 }
307 } );
308 this.perRowInput = new OO.ui.NumberInputWidget( {
309 min: 0,
310 showButtons: false
311 } );
312 this.showFilenameCheckbox = new OO.ui.CheckboxInputWidget( {
313 value: 'yes'
314 } );
315 this.classesInput = new OO.ui.TextInputWidget( {
316 placeholder: ve.msg( 'visualeditor-mwgallerydialog-classes-input-placeholder' )
317 } );
318 this.stylesInput = new OO.ui.TextInputWidget( {
319 placeholder: ve.msg( 'visualeditor-mwgallerydialog-styles-input-placeholder' )
320 } );
321
322 // Field layouts
323 const modeField = new OO.ui.FieldLayout( this.modeDropdown, {
324 label: ve.msg( 'visualeditor-mwgallerydialog-mode-field-label' )
325 } );
326 const captionField = new OO.ui.FieldLayout( this.captionTarget, {
327 label: ve.msg( 'visualeditor-mwgallerydialog-caption-field-label' ),
328 align: this.isMobile ? 'top' : 'left'
329 } );
330 const widthsField = new OO.ui.FieldLayout( this.widthsInput, {
331 label: ve.msg( 'visualeditor-mwgallerydialog-widths-field-label' )
332 } );
333 const heightsField = new OO.ui.FieldLayout( this.heightsInput, {
334 label: ve.msg( 'visualeditor-mwgallerydialog-heights-field-label' )
335 } );
336 const perRowField = new OO.ui.FieldLayout( this.perRowInput, {
337 label: ve.msg( 'visualeditor-mwgallerydialog-perrow-field-label' )
338 } );
339 const showFilenameField = new OO.ui.FieldLayout( this.showFilenameCheckbox, {
340 label: ve.msg( 'visualeditor-mwgallerydialog-show-filename-field-label' )
341 } );
342 const classesField = new OO.ui.FieldLayout( this.classesInput, {
343 label: ve.msg( 'visualeditor-mwgallerydialog-classes-field-label' )
344 } );
345 const stylesField = new OO.ui.FieldLayout( this.stylesInput, {
346 label: ve.msg( 'visualeditor-mwgallerydialog-styles-field-label' )
347 } );
348
349 // Append everything
350 imageListMenuPanel.$element.append(
351 this.showSearchPanelButton.$element
352 );
353 imageListContentPanel.$element.append(
354 this.$emptyGalleryMessage,
355 this.galleryGroup.$element
356 );
357 this.editPanel.$element.append(
358 this.filenameFieldset.$element,
359 highlightedCaptionFieldset.$element,
360 highlightedAltTextFieldset.$element,
361 this.removeButton.$element
362 );
363 this.searchPanel.$element.append(
364 this.searchWidget.$element
365 );
366 imagesTabPanel.$element.append(
367 this.imageTabMenuLayout.$element
368 );
369 optionsTabPanel.$element.append(
370 modeField.$element,
371 captionField.$element,
372 widthsField.$element,
373 heightsField.$element,
374 perRowField.$element,
375 showFilenameField.$element,
376 classesField.$element,
377 stylesField.$element
378 );
379 this.indexLayout.addTabPanels( [
380 imagesTabPanel,
381 optionsTabPanel
382 ] );
383 this.$body.append( this.indexLayout.$element );
384 };
385
386 /**
387 * @inheritdoc
388 */
389 ve.ui.MWGalleryDialog.prototype.getSetupProcess = function ( data ) {
390 return ve.ui.MWGalleryDialog.super.prototype.getSetupProcess.call( this, data )
391 .next( () => {
392 const namespaceIds = mw.config.get( 'wgNamespaceIds' ),
393 mwData = this.selectedNode && this.selectedNode.getAttribute( 'mw' ),
394 attributes = mwData && mwData.attrs,
395 captionNode = this.selectedNode && this.selectedNode.getCaptionNode(),
396 imageNodes = this.selectedNode && this.selectedNode.getImageNodes(),
397 isReadOnly = this.isReadOnly();
398
399 this.anyItemModified = false;
400
401 // Images tab panel
402 // If editing an existing gallery, populate with the images...
403 if ( this.selectedNode ) {
404 const imageTitles = [];
405
406 for ( let i = 0, ilen = imageNodes.length; i < ilen; i++ ) {
407 const image = imageNodes[ i ];
408 const resourceTitle = mw.Title.newFromText( mw.libs.ve.normalizeParsoidResourceName( image.getAttribute( 'resource' ) ), namespaceIds.file );
409 if ( !resourceTitle ) {
410 continue;
411 }
412 const resource = resourceTitle.getPrefixedText();
413 const imageCaptionNode = image.getCaptionNode();
414 imageTitles.push( resource );
415 this.initialImageData.push( {
416 resource: resource,
417 altText: image.getAttribute( 'altText' ),
418 altTextSame: image.getAttribute( 'altTextSame' ),
419 href: image.getAttribute( 'href' ),
420 src: image.getAttribute( 'src' ),
421 height: image.getAttribute( 'height' ),
422 width: image.getAttribute( 'width' ),
423 captionDocument: this.createCaptionDocument( imageCaptionNode ),
424 tagName: image.getAttribute( 'tagName' ),
425 isError: image.getAttribute( 'isError' ),
426 errorText: image.getAttribute( 'errorText' ),
427 imageClassAttr: image.getAttribute( 'imageClassAttr' ),
428 imgWrapperClassAttr: image.getAttribute( 'imgWrapperClassAttr' ),
429 mw: image.getAttribute( 'mw' ),
430 mediaClass: image.getAttribute( 'mediaClass' ),
431 mediaTag: image.getAttribute( 'mediaTag' )
432 } );
433 }
434
435 // Populate menu and edit panels
436 this.imagesPromise = this.requestImages( {
437 titles: imageTitles
438 } ).done( () => {
439 this.onHighlightItem();
440 } );
441
442 // ...Otherwise show the search panel
443 } else {
444 this.toggleEmptyGalleryMessage( true );
445 this.toggleSearchPanel( true );
446 }
447
448 // Options tab panel
449
450 // Set options
451 const mode = attributes && attributes.mode || this.defaults.mode;
452 const widths = attributes && parseInt( attributes.widths ) || '';
453 const heights = attributes && parseInt( attributes.heights ) || '';
454 const perRow = attributes && attributes.perrow || '';
455 const showFilename = attributes && attributes.showfilename === 'yes';
456 const classes = attributes && attributes.class || '';
457 const styles = attributes && attributes.style || '';
458 // Caption
459 this.captionDocument = this.createCaptionDocument( captionNode );
460
461 // Populate options panel
462 this.modeDropdown.getMenu().selectItemByData( mode );
463 this.widthsInput.setValue( widths );
464 this.heightsInput.setValue( heights );
465 this.perRowInput.setValue( perRow );
466 this.showFilenameCheckbox.setSelected( showFilename );
467 this.classesInput.setValue( classes );
468 this.stylesInput.setValue( styles );
469 // Caption
470 this.captionTarget.setDocument( this.captionDocument );
471 this.captionTarget.setReadOnly( isReadOnly );
472
473 if ( mwData ) {
474 this.originalMwDataNormalized = ve.copy( mwData );
475 this.updateMwData( this.originalMwDataNormalized );
476 }
477
478 this.highlightedAltTextInput.setReadOnly( isReadOnly || this.altTextSameAsCaption.isSelected() );
479 this.altTextSameAsCaption.setDisabled( isReadOnly );
480 this.modeDropdown.setDisabled( isReadOnly );
481 this.widthsInput.setReadOnly( isReadOnly );
482 this.heightsInput.setReadOnly( isReadOnly );
483 this.perRowInput.setReadOnly( isReadOnly );
484 this.showFilenameCheckbox.setDisabled( isReadOnly );
485 this.classesInput.setReadOnly( isReadOnly );
486 this.stylesInput.setReadOnly( isReadOnly );
487
488 this.showSearchPanelButton.setDisabled( isReadOnly );
489 this.removeButton.setDisabled( isReadOnly );
490
491 this.galleryGroup.toggleDraggable( !isReadOnly );
492
493 // Disable fields depending on mode
494 this.onModeDropdownChange();
495
496 // Add event handlers
497 this.indexLayout.connect( this, { set: 'updateDialogSize' } );
498 this.searchWidget.getResults().connect( this, { choose: 'onSearchResultsChoose' } );
499 this.showSearchPanelButton.connect( this, { click: 'onShowSearchPanelButtonClick' } );
500 this.galleryGroup.connect( this, { editItem: 'onHighlightItem' } );
501 this.galleryGroup.connect( this, { change: 'updateActions' } );
502 this.removeButton.connect( this, { click: 'onRemoveItem' } );
503 this.modeDropdown.getMenu().connect( this, { choose: 'onModeDropdownChange' } );
504 this.widthsInput.connect( this, { change: 'updateActions' } );
505 this.heightsInput.connect( this, { change: 'updateActions' } );
506 this.perRowInput.connect( this, { change: 'updateActions' } );
507 this.showFilenameCheckbox.connect( this, { change: 'updateActions' } );
508 this.classesInput.connect( this, { change: 'updateActions' } );
509 this.stylesInput.connect( this, { change: 'updateActions' } );
510 this.captionTarget.connect( this, { change: 'updateActions' } );
511 this.highlightedAltTextInput.connect( this, { change: 'updateActions' } );
512 this.altTextSameAsCaption.connect( this, { change: 'onAltTextSameAsCaptionChange' } );
513 this.highlightedCaptionTarget.connect( this, { change: 'onHighlightedCaptionTargetChange' } );
514
515 return this.imagesPromise;
516 } );
517 };
518
519 /**
520 * Get a new caption document for the gallery caption or an image caption.
521 *
522 * @private
523 * @param {ve.dm.MWGalleryCaptionNode|ve.dm.MWGalleryImageCaptionNode|null} captionNode
524 * @return {ve.dm.Document}
525 */
526 ve.ui.MWGalleryDialog.prototype.createCaptionDocument = function ( captionNode ) {
527 if ( captionNode && captionNode.getLength() > 0 ) {
528 return this.selectedNode.getDocument().cloneFromRange( captionNode.getRange() );
529 } else {
530 return this.getFragment().getDocument().cloneWithData( [
531 { type: 'paragraph', internal: { generated: 'wrapper' } },
532 { type: '/paragraph' },
533 { type: 'internalList' },
534 { type: '/internalList' }
535 ] );
536 }
537 };
538
539 /**
540 * @inheritdoc
541 */
542 ve.ui.MWGalleryDialog.prototype.getReadyProcess = function ( data ) {
543 return ve.ui.MWGalleryDialog.super.prototype.getReadyProcess.call( this, data )
544 .next( () => {
545 this.searchWidget.getQuery().focus().select();
546 } );
547 };
548
549 /**
550 * @inheritdoc
551 */
552 ve.ui.MWGalleryDialog.prototype.getTeardownProcess = function ( data ) {
553 return ve.ui.MWGalleryDialog.super.prototype.getTeardownProcess.call( this, data )
554 .first( () => {
555 // Layouts
556 this.indexLayout.setTabPanel( 'images' );
557 this.indexLayout.resetScroll();
558 this.imageTabMenuLayout.resetScroll();
559
560 // Widgets
561 this.galleryGroup.clearItems();
562 this.searchWidget.getQuery().setValue( '' );
563 this.searchWidget.teardown();
564
565 // States
566 this.highlightedItem = null;
567 this.searchPanelVisible = false;
568 this.selectedFilenames = {};
569 this.initialImageData = [];
570 this.originalMwDataNormalized = null;
571 this.originalGalleryGroupItems = [];
572
573 // Disconnect events
574 this.indexLayout.disconnect( this );
575 this.searchWidget.getResults().disconnect( this );
576 this.showSearchPanelButton.disconnect( this );
577 this.galleryGroup.disconnect( this );
578 this.removeButton.disconnect( this );
579 this.modeDropdown.disconnect( this );
580 this.widthsInput.disconnect( this );
581 this.heightsInput.disconnect( this );
582 this.perRowInput.disconnect( this );
583 this.showFilenameCheckbox.disconnect( this );
584 this.classesInput.disconnect( this );
585 this.stylesInput.disconnect( this );
586 this.highlightedAltTextInput.disconnect( this );
587 this.altTextSameAsCaption.disconnect( this );
588 this.captionTarget.disconnect( this );
589 this.highlightedCaptionTarget.disconnect( this );
590
591 } );
592 };
593
594 ve.ui.MWGalleryDialog.prototype.getActionProcess = function ( action ) {
595 return ve.ui.MWGalleryDialog.super.prototype.getActionProcess.call( this, action )
596 .next( () => {
597 if ( action === 'done' ) {
598 // Save the input values for the highlighted item
599 this.updateHighlightedItem();
600
601 this.insertOrUpdateNode();
602 this.close( { action: 'done' } );
603 }
604 } );
605 };
606
607 /**
608 * @inheritdoc
609 */
610 ve.ui.MWGalleryDialog.prototype.getBodyHeight = function () {
611 return 600;
612 };
613
614 /**
615 * Request the images for the images tab panel menu
616 *
617 * @param {Object} options Options for the request
618 * @return {jQuery.Promise} Promise which resolves when image data has been fetched
619 */
620 ve.ui.MWGalleryDialog.prototype.requestImages = function ( options ) {
621 const promises = options.titles.map( ( title ) => ve.init.platform.galleryImageInfoCache.get( title ) );
622
623 return ve.promiseAll( promises )
624 .done( ( ...args ) => {
625 const resp = {};
626 options.titles.forEach( ( title, i ) => {
627 resp[ title ] = args[ i ];
628 } );
629 this.onRequestImagesSuccess( resp );
630 } );
631 };
632
633 /**
634 * Create items for the returned images and add them to the gallery group
635 *
636 * @param {Object} response jQuery response object
637 */
638 ve.ui.MWGalleryDialog.prototype.onRequestImagesSuccess = function ( response ) {
639 const thumbUrls = {},
640 items = [],
641 config = { isMobile: this.isMobile, draggable: !this.isReadOnly() };
642
643 let title;
644 for ( title in response ) {
645 thumbUrls[ title ] = {
646 thumbUrl: response[ title ].thumburl,
647 width: response[ title ].thumbwidth,
648 height: response[ title ].thumbheight
649 };
650 }
651
652 if ( this.initialImageData.length > 0 ) {
653 this.initialImageData.forEach( ( image ) => {
654 image.thumbUrl = thumbUrls[ image.resource ].thumbUrl;
655 items.push( new ve.ui.MWGalleryItemWidget( image, config ) );
656 } );
657 this.initialImageData = [];
658 this.originalGalleryGroupItems = ve.copy( items );
659 } else {
660 for ( title in this.selectedFilenames ) {
661 if ( Object.prototype.hasOwnProperty.call( thumbUrls, title ) ) {
662 items.push( new ve.ui.MWGalleryItemWidget( {
663 resource: title,
664 altText: null,
665 altTextSame: true,
666 // TODO: support changing the link in the UI somewhere;
667 // for now, always link to the resource. Do it here when
668 // generating new results, so existing links from source
669 // will be preserved.
670 href: title,
671 src: '',
672 height: thumbUrls[ title ].height,
673 width: thumbUrls[ title ].width,
674 thumbUrl: thumbUrls[ title ].thumbUrl,
675 captionDocument: this.createCaptionDocument( null ),
676 isError: false,
677 errorText: null,
678 imageClassAttr: 'mw-file-element',
679 mw: {},
680 mediaClass: 'File',
681 mediaTag: 'img'
682 }, config ) );
683 delete this.selectedFilenames[ title ];
684 }
685 }
686 }
687
688 this.galleryGroup.addItems( items );
689
690 // Gallery is no longer empty
691 this.updateActions();
692 this.toggleEmptyGalleryMessage( false );
693 };
694
695 /**
696 * Request a new image and highlight it
697 *
698 * @param {string} title Normalized title of the new image
699 */
700 ve.ui.MWGalleryDialog.prototype.addNewImage = function ( title ) {
701 // Make list of unique pending images, for onRequestImagesSuccess
702 this.selectedFilenames[ title ] = true;
703
704 // Request image
705 this.requestImages( {
706 titles: [ title ]
707 } ).done( () => {
708 // populate edit panel with the new image
709 const items = this.galleryGroup.items;
710 this.onHighlightItem( items[ items.length - 1 ] );
711 this.highlightedCaptionTarget.focus();
712 } );
713 };
714
715 /**
716 * Update the image currently being edited (ve.ui.MWGalleryItemWidget) with the values from inputs
717 * in this dialog (currently only the image caption).
718 */
719 ve.ui.MWGalleryDialog.prototype.updateHighlightedItem = function () {
720 this.anyItemModified = this.anyItemModified || this.isHighlightedItemModified();
721
722 // TODO: Support link, page and lang
723 if ( this.highlightedItem ) {
724 // No need to call setCaptionDocument(), the document object is updated on every change
725 this.highlightedItem.setAltText( this.highlightedAltTextInput.getValue() );
726 this.highlightedItem.setAltTextSame( this.altTextSameAsCaption.isSelected() );
727 }
728 };
729
730 /**
731 * Handle search results choose event.
732 *
733 * @param {mw.widgets.MediaResultWidget} item Chosen item
734 */
735 ve.ui.MWGalleryDialog.prototype.onSearchResultsChoose = function ( item ) {
736 const title = mw.Title.newFromText( item.getData().title ).getPrefixedText();
737
738 // Check title against pending insertions
739 // TODO: Prevent two 'choose' events firing from the UI
740 if ( !Object.prototype.hasOwnProperty.call( this.selectedFilenames, title ) ) {
741 this.addNewImage( title );
742 }
743
744 this.updateActions();
745 };
746
747 /**
748 * Handle click event for the remove button
749 */
750 ve.ui.MWGalleryDialog.prototype.onRemoveItem = function () {
751 // Remove the highlighted item
752 this.galleryGroup.removeItems( [ this.highlightedItem ] );
753
754 // Highlight another item, or show the search panel if the gallery is now empty
755 this.onHighlightItem();
756 };
757
758 /**
759 * Handle clicking on an image in the menu
760 *
761 * @param {ve.ui.MWGalleryItemWidget} [item] The item that was clicked on
762 */
763 ve.ui.MWGalleryDialog.prototype.onHighlightItem = function ( item ) {
764 // Unhighlight previous item
765 if ( this.highlightedItem ) {
766 this.highlightedItem.toggleHighlighted( false );
767 }
768
769 // Show edit panel
770 // (This also calls updateHighlightedItem() to save the input values.)
771 this.toggleSearchPanel( false );
772
773 // Highlight new item.
774 // If no item was given, highlight the first item in the gallery.
775 item = item || this.galleryGroup.items[ 0 ];
776
777 if ( !item ) {
778 // Show the search panel if the gallery is empty
779 this.toggleEmptyGalleryMessage( true );
780 this.toggleSearchPanel( true );
781 return;
782 }
783
784 item.toggleHighlighted( true );
785 this.highlightedItem = item;
786
787 // Scroll item into view in menu
788 OO.ui.Element.static.scrollIntoView( item.$element[ 0 ] );
789
790 // Populate edit panel
791 const title = mw.Title.newFromText( mw.libs.ve.normalizeParsoidResourceName( item.resource ) );
792 const $link = $( '<a>' )
793 .addClass( 've-ui-mwMediaDialog-description-link' )
794 .attr( 'target', '_blank' )
795 .attr( 'rel', 'noopener' )
796 .text( ve.msg( 'visualeditor-dialog-media-content-description-link' ) );
797
798 // T322704
799 ve.setAttributeSafe( $link[ 0 ], 'href', title.getUrl(), '#' );
800
801 this.filenameFieldset.setLabel(
802 $( '<span>' ).append(
803 $( document.createTextNode( title.getMainText() + ' ' ) ),
804 $link
805 )
806 );
807 this.$highlightedImage
808 .css( 'background-image', 'url(' + item.thumbUrl + ')' );
809 this.highlightedCaptionTarget.setDocument( item.captionDocument );
810 this.highlightedCaptionTarget.setReadOnly( this.isReadOnly() );
811 this.highlightedAltTextInput.setValue( item.altText );
812 this.highlightedAltTextInput.setReadOnly( this.isReadOnly() || item.altTextSame );
813 this.altTextSameAsCaption.setSelected( item.altTextSame );
814 };
815
816 /**
817 * Handle change event for this.modeDropdown
818 */
819 ve.ui.MWGalleryDialog.prototype.onModeDropdownChange = function () {
820 const mode = this.modeDropdown.getMenu().findSelectedItem().getData(),
821 disabled = (
822 mode === 'packed' ||
823 mode === 'packed-overlay' ||
824 mode === 'packed-hover' ||
825 mode === 'slideshow'
826 );
827
828 this.widthsInput.setDisabled( disabled );
829 this.perRowInput.setDisabled( disabled );
830
831 // heights is only ignored in slideshow mode
832 this.heightsInput.setDisabled( mode === 'slideshow' );
833
834 this.updateActions();
835 };
836
837 /**
838 * Handle change event for this.highlightedCaptionTarget
839 */
840 ve.ui.MWGalleryDialog.prototype.onHighlightedCaptionTargetChange = function () {
841 if ( this.altTextSameAsCaption.isSelected() ) {
842 const surfaceModel = this.highlightedCaptionTarget.getSurface().getModel();
843 const caption = surfaceModel.getLinearFragment(
844 surfaceModel.getDocument().getDocumentRange()
845 ).getText();
846 this.highlightedAltTextInput.setValue( caption );
847 }
848 this.updateActions();
849 };
850
851 /**
852 * Handle change event for this.altTextSameAsCaption
853 */
854 ve.ui.MWGalleryDialog.prototype.onAltTextSameAsCaptionChange = function () {
855 this.highlightedAltTextInput.setReadOnly( this.isReadOnly() || this.altTextSameAsCaption.isSelected() );
856 this.onHighlightedCaptionTargetChange();
857 };
858
859 /**
860 * Handle click event for showSearchPanelButton
861 */
862 ve.ui.MWGalleryDialog.prototype.onShowSearchPanelButtonClick = function () {
863 this.toggleSearchPanel( true );
864 };
865
866 /**
867 * Toggle the search panel (and the edit panel, the opposite way)
868 *
869 * @param {boolean} [visible] The search panel is visible
870 */
871 ve.ui.MWGalleryDialog.prototype.toggleSearchPanel = function ( visible ) {
872 visible = visible !== undefined ? visible : !this.searchPanelVisible;
873
874 // If currently visible panel is an edit panel, save the input values for the highlighted item
875 if ( !this.searchPanelVisible ) {
876 this.updateHighlightedItem();
877 }
878
879 // Record the state of the search panel
880 this.searchPanelVisible = visible;
881
882 // Toggle the search panel, and do the opposite for the edit panel
883 this.editSearchStack.setItem( visible ? this.searchPanel : this.editPanel );
884
885 this.imageListMenuLayout.toggleMenu( !visible );
886 if ( this.highlightedItem && visible ) {
887 this.highlightedItem.toggleHighlighted( false );
888 this.highlightedItem = null;
889 }
890
891 // If the edit panel is visible, focus the caption target
892 if ( !visible ) {
893 this.highlightedCaptionTarget.focus();
894 } else {
895 // Try to populate with user uploads
896 this.searchWidget.queryMediaQueue();
897 this.searchWidget.getQuery().focus().select();
898 }
899 this.updateDialogSize();
900 };
901
902 /**
903 * Resize the dialog according to which panel is focused
904 */
905 ve.ui.MWGalleryDialog.prototype.updateDialogSize = function () {
906 if ( this.searchPanelVisible && this.indexLayout.currentTabPanelName === 'images' ) {
907 this.setSize( 'larger' );
908 } else {
909 this.setSize( 'large' );
910 }
911 };
912
913 /**
914 * Toggle the empty gallery message
915 *
916 * @param {boolean} empty The gallery is empty
917 */
918 ve.ui.MWGalleryDialog.prototype.toggleEmptyGalleryMessage = function ( empty ) {
919 this.$emptyGalleryMessage.toggleClass( 'oo-ui-element-hidden', !empty );
920 };
921
922 /**
923 * Disable the "Done" button if the gallery is empty, otherwise enable it
924 *
925 * TODO Disable the button until the user makes any changes
926 */
927 ve.ui.MWGalleryDialog.prototype.updateActions = function () {
928 this.actions.setAbilities( { done: this.isSaveable() } );
929 };
930
931 /**
932 * Check if gallery attributes or contents would be modified if changes were applied.
933 *
934 * @return {boolean}
935 */
936 ve.ui.MWGalleryDialog.prototype.isSaveable = function () {
937 // Check attributes
938 if ( this.originalMwDataNormalized ) {
939 const mwDataCopy = ve.copy( this.selectedNode.getAttribute( 'mw' ) );
940 this.updateMwData( mwDataCopy );
941 if ( !ve.compare( mwDataCopy, this.originalMwDataNormalized ) ) {
942 return true;
943 }
944 }
945 if ( this.captionTarget.hasBeenModified() ) {
946 return true;
947 }
948
949 // Check contents: each image's attributes and contents (caption)
950 if ( this.anyItemModified || this.isHighlightedItemModified() ) {
951 return true;
952 }
953
954 // Check contents: added/removed/reordered images
955 if ( this.originalGalleryGroupItems ) {
956 if ( this.galleryGroup.items.length !== this.originalGalleryGroupItems.length ) {
957 return true;
958 }
959 for ( let i = 0; i < this.galleryGroup.items.length; i++ ) {
960 if ( this.galleryGroup.items[ i ] !== this.originalGalleryGroupItems[ i ] ) {
961 return true;
962 }
963 }
964 }
965
966 return false;
967 };
968
969 /**
970 * Check if currently highlighted item's attributes or contents would be modified if changes were
971 * applied.
972 *
973 * @return {boolean}
974 */
975 ve.ui.MWGalleryDialog.prototype.isHighlightedItemModified = function () {
976 if ( this.highlightedItem ) {
977 if ( this.highlightedAltTextInput.getValue() !== this.highlightedItem.altText ) {
978 return true;
979 }
980 if ( this.altTextSameAsCaption.isSelected() !== this.highlightedItem.altTextSame ) {
981 return true;
982 }
983 if ( this.highlightedCaptionTarget.hasBeenModified() ) {
984 return true;
985 }
986 }
987 return false;
988 };
989
990 /**
991 * Insert or update the node in the document model from the new values
992 */
993 ve.ui.MWGalleryDialog.prototype.insertOrUpdateNode = function () {
994 const surfaceModel = this.getFragment().getSurface(),
995 surfaceModelDocument = surfaceModel.getDocument(),
996 items = this.galleryGroup.items,
997 data = [];
998
999 let mwData;
1000
1001 function scaleImage( height, width, maxHeight, maxWidth ) {
1002 const heightScaleFactor = maxHeight / height;
1003 const widthScaleFactor = maxWidth / width;
1004
1005 const scaleFactor = width * heightScaleFactor > maxWidth ? widthScaleFactor : heightScaleFactor;
1006
1007 return {
1008 height: Math.round( height * scaleFactor ),
1009 width: Math.round( width * scaleFactor )
1010 };
1011 }
1012
1013 /**
1014 * Get linear data from a gallery item
1015 *
1016 * @param {ve.ui.MWGalleryItemWidget} galleryItem Gallery item
1017 * @return {Array} Linear data
1018 */
1019 function getImageLinearData( galleryItem ) {
1020 const size = scaleImage(
1021 parseInt( galleryItem.height ),
1022 parseInt( galleryItem.width ),
1023 parseInt( mwData.attrs.heights || this.defaults.imageHeight ),
1024 parseInt( mwData.attrs.widths || this.defaults.imageWidth )
1025 );
1026 const imageAttributes = {
1027 resource: './' + galleryItem.resource,
1028 altText: ( !galleryItem.altText && !galleryItem.originalAltText ) ?
1029 // Use original null/empty value
1030 galleryItem.originalAltText :
1031 galleryItem.altText,
1032 altTextSame: galleryItem.altTextSame,
1033 href: galleryItem.href,
1034 // For existing images use `src` to avoid triggering a diff if the
1035 // thumbnail size changes. For new images we have to use `thumbUrl` (T310623).
1036 src: galleryItem.src || galleryItem.thumbUrl,
1037 height: size.height,
1038 width: size.width,
1039 tagName: galleryItem.tagName,
1040 isError: galleryItem.isError,
1041 errorText: galleryItem.errorText,
1042 imageClassAttr: galleryItem.imageClassAttr,
1043 imgWrapperClassAttr: galleryItem.imgWrapperClassAttr,
1044 mw: galleryItem.mw,
1045 mediaClass: galleryItem.mediaClass,
1046 mediaTag: galleryItem.mediaTag
1047 };
1048
1049 return [
1050 { type: 'mwGalleryImage', attributes: imageAttributes },
1051 { type: 'mwGalleryImageCaption' },
1052 // Actual caption contents are inserted later
1053 { type: '/mwGalleryImageCaption' },
1054 { type: '/mwGalleryImage' }
1055 ];
1056 }
1057
1058 let innerRange;
1059 if ( this.selectedNode ) {
1060 // Update mwData
1061 mwData = ve.copy( this.selectedNode.getAttribute( 'mw' ) );
1062 this.updateMwData( mwData );
1063 surfaceModel.change(
1064 ve.dm.TransactionBuilder.static.newFromAttributeChanges(
1065 surfaceModelDocument,
1066 this.selectedNode.getOuterRange().start,
1067 { mw: mwData }
1068 )
1069 );
1070
1071 innerRange = this.selectedNode.getRange();
1072 } else {
1073 // Make gallery node and mwData
1074 const element = {
1075 type: 'mwGallery',
1076 attributes: {
1077 mw: {
1078 name: 'gallery',
1079 attrs: {},
1080 body: {}
1081 }
1082 }
1083 };
1084 mwData = element.attributes.mw;
1085 this.updateMwData( mwData );
1086 // Collapse returns a new fragment, so update this.fragment
1087 this.fragment = this.getFragment().collapseToEnd();
1088 this.getFragment().insertContent( [
1089 element,
1090 { type: '/mwGallery' }
1091 ] );
1092
1093 innerRange = new ve.Range( this.fragment.getSelection().getRange().from + 1 );
1094 }
1095
1096 // Update all child elements' data, but without the contents of the captions
1097 if ( this.captionDocument.data.hasContent() ) {
1098 data.push(
1099 { type: 'mwGalleryCaption' },
1100 { type: '/mwGalleryCaption' }
1101 );
1102 }
1103 // Build node for each image
1104 for ( let i = 0, ilen = items.length; i < ilen; i++ ) {
1105 ve.batchPush( data, getImageLinearData.call( this, items[ i ] ) );
1106 }
1107 // Replace whole contents of this node with the new ones
1108 surfaceModel.change(
1109 ve.dm.TransactionBuilder.static.newFromReplacement(
1110 surfaceModelDocument,
1111 innerRange,
1112 data
1113 )
1114 );
1115
1116 // Minus 2 to skip past </mwGalleryImageCaption></mwGalleryImage>
1117 let captionInsertionOffset = innerRange.from + data.length - 2;
1118 // Update image captions. In reverse order to avoid having to adjust offsets for each insertion.
1119 for ( let i = items.length - 1; i >= 0; i-- ) {
1120 surfaceModel.change(
1121 ve.dm.TransactionBuilder.static.newFromDocumentInsertion(
1122 surfaceModel.getDocument(),
1123 captionInsertionOffset,
1124 items[ i ].captionDocument
1125 )
1126 );
1127 // Skip past </mwGalleryImageCaption></mwGalleryImage><mwGalleryImage><mwGalleryImageCaption>
1128 captionInsertionOffset -= 4;
1129 }
1130
1131 // Update gallery caption
1132 if ( this.captionDocument.data.hasContent() ) {
1133 surfaceModel.change(
1134 ve.dm.TransactionBuilder.static.newFromDocumentInsertion(
1135 surfaceModel.getDocument(),
1136 // Plus 1 to skip past <mwGalleryCaption>
1137 innerRange.from + 1,
1138 this.captionDocument
1139 )
1140 );
1141 }
1142 };
1143
1144 /**
1145 * Update the 'mw' attribute with data from inputs in the dialog.
1146 *
1147 * @param {Object} mwData Value of the 'mw' attribute, updated in-place
1148 * @private
1149 */
1150 ve.ui.MWGalleryDialog.prototype.updateMwData = function ( mwData ) {
1151 // Need to do this, otherwise mwData.body.extsrc will override all attribute changes
1152 mwData.body = {};
1153 // Need to do this, otherwise it will override the caption from the gallery caption node
1154 delete mwData.attrs.caption;
1155 // Update attributes
1156 let mode;
1157 if ( this.modeDropdown.getMenu().findSelectedItem() ) {
1158 mode = this.modeDropdown.getMenu().findSelectedItem().getData();
1159 }
1160 // Unset mode attribute if it is the same as the default
1161 mwData.attrs.mode = mode === this.defaults.mode ? undefined : mode;
1162 mwData.attrs.widths = this.widthsInput.getValue() || undefined;
1163 mwData.attrs.heights = this.heightsInput.getValue() || undefined;
1164 mwData.attrs.perrow = this.perRowInput.getValue() || undefined;
1165 mwData.attrs.showfilename = this.showFilenameCheckbox.isSelected() ? 'yes' : undefined;
1166 mwData.attrs.class = this.classesInput.getValue() || undefined;
1167 mwData.attrs.style = this.stylesInput.getValue() || undefined;
1168 };
1169
1170 /* Registration */
1171
1172 ve.ui.windowFactory.register( ve.ui.MWGalleryDialog );