Debian Codegraph @

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

raw symbols SCIP
1 /*!
2 * VisualEditor user interface MWMediaDialog class.
3 *
4 * @copyright See AUTHORS.txt
5 * @license The MIT License (MIT); see LICENSE.txt
6 */
7
8 /**
9 * Dialog for inserting and editing MediaWiki media.
10 *
11 * @class
12 * @extends ve.ui.NodeDialog
13 *
14 * @constructor
15 * @param {Object} [config] Configuration options
16 */
17 ve.ui.MWMediaDialog = function VeUiMWMediaDialog( config ) {
18 // Parent constructor
19 ve.ui.MWMediaDialog.super.call( this, config );
20
21 // Properties
22 this.imageModel = null;
23 this.isSettingUpModel = false;
24 this.isInsertion = false;
25 this.selectedImageInfo = null;
26 this.searchCache = {};
27
28 this.$element.addClass( 've-ui-mwMediaDialog' );
29 };
30
31 /* Inheritance */
32
33 OO.inheritClass( ve.ui.MWMediaDialog, ve.ui.NodeDialog );
34
35 /* Static Properties */
36
37 ve.ui.MWMediaDialog.static.name = 'media';
38
39 ve.ui.MWMediaDialog.static.title =
40 OO.ui.deferMsg( 'visualeditor-dialog-media-title' );
41
42 ve.ui.MWMediaDialog.static.size = 'medium';
43
44 ve.ui.MWMediaDialog.static.actions = [
45 {
46 action: 'done',
47 label: OO.ui.deferMsg( 'visualeditor-dialog-action-apply' ),
48 flags: [ 'progressive', 'primary' ],
49 modes: 'edit'
50 },
51 {
52 action: 'insert',
53 label: OO.ui.deferMsg( 'visualeditor-dialog-action-insert' ),
54 flags: [ 'primary', 'progressive' ],
55 modes: 'insert'
56 },
57 {
58 action: 'change',
59 label: OO.ui.deferMsg( 'visualeditor-dialog-media-change-image' ),
60 modes: [ 'edit', 'insert' ]
61 },
62 {
63 action: 'choose',
64 label: OO.ui.deferMsg( 'visualeditor-dialog-media-choose-image' ),
65 flags: [ 'primary', 'progressive' ],
66 modes: [ 'info' ]
67 },
68 {
69 action: 'upload',
70 label: OO.ui.deferMsg( 'visualeditor-dialog-media-upload' ),
71 flags: [ 'primary', 'progressive' ],
72 modes: [ 'upload-upload' ]
73 },
74 {
75 action: 'save',
76 label: OO.ui.deferMsg( 'visualeditor-dialog-media-save' ),
77 flags: [ 'primary', 'progressive' ],
78 modes: [ 'upload-info' ]
79 },
80 {
81 action: 'cancelchoose',
82 label: OO.ui.deferMsg( 'visualeditor-dialog-media-goback' ),
83 flags: [ 'safe', 'back' ],
84 modes: [ 'info' ]
85 },
86 {
87 action: 'cancelupload',
88 label: OO.ui.deferMsg( 'visualeditor-dialog-media-goback' ),
89 flags: [ 'safe', 'back' ],
90 modes: [ 'upload-info' ]
91 },
92 {
93 label: OO.ui.deferMsg( 'visualeditor-dialog-action-cancel' ),
94 flags: [ 'safe', 'close' ],
95 modes: [ 'readonly', 'edit', 'insert', 'select', 'search', 'upload-upload' ]
96 },
97 {
98 action: 'back',
99 label: OO.ui.deferMsg( 'visualeditor-dialog-media-goback' ),
100 flags: [ 'safe', 'back' ],
101 modes: [ 'change' ]
102 }
103 ];
104
105 ve.ui.MWMediaDialog.static.modelClasses = [ ve.dm.MWBlockImageNode, ve.dm.MWInlineImageNode ];
106
107 ve.ui.MWMediaDialog.static.includeCommands = null;
108
109 ve.ui.MWMediaDialog.static.excludeCommands = [
110 // No formatting
111 'paragraph',
112 'heading1',
113 'heading2',
114 'heading3',
115 'heading4',
116 'heading5',
117 'heading6',
118 'preformatted',
119 'blockquote',
120 // TODO: Decide if tables tools should be allowed
121 'tableCellHeader',
122 'tableCellData',
123 // No structure
124 'bullet',
125 'bulletWrapOnce',
126 'number',
127 'numberWrapOnce',
128 'indent',
129 'outdent'
130 ];
131
132 /**
133 * Get the import rules for the surface widget in the dialog
134 *
135 * @see ve.dm.ElementLinearData#sanitize
136 * @return {Object} Import rules
137 */
138 ve.ui.MWMediaDialog.static.getImportRules = function () {
139 const rules = ve.copy( ve.init.target.constructor.static.importRules );
140 return ve.extendObject(
141 rules,
142 {
143 all: {
144 blacklist: ve.extendObject(
145 {
146 // Tables (but not lists) are possible in wikitext with a leading
147 // line break but we prevent creating these with the UI
148 list: true,
149 listItem: true,
150 definitionList: true,
151 definitionListItem: true,
152 table: true,
153 tableCaption: true,
154 tableSection: true,
155 tableRow: true,
156 tableCell: true,
157 mwTable: true,
158 mwTransclusionTableCell: true
159 },
160 ve.getProp( rules, 'all', 'blacklist' )
161 ),
162 // Headings are also possible, but discouraged
163 conversions: ve.extendObject(
164 {
165 mwHeading: 'paragraph'
166 },
167 ve.getProp( rules, 'all', 'conversions' )
168 )
169 }
170 }
171 );
172 };
173
174 /* Methods */
175
176 /**
177 * @inheritdoc
178 */
179 ve.ui.MWMediaDialog.prototype.getBodyHeight = function () {
180 // FIXME: This should vary on panel.
181 return 600;
182 };
183
184 /**
185 * @inheritdoc
186 */
187 ve.ui.MWMediaDialog.prototype.initialize = function () {
188 // Parent method
189 ve.ui.MWMediaDialog.super.prototype.initialize.call( this );
190
191 // Main layout
192 this.panels = new OO.ui.StackLayout();
193
194 // Settings panels
195 this.mediaSettingsLayout = new OO.ui.IndexLayout( {
196 classes: [ 've-ui-mwMediaDialog-panel-settings' ]
197 } );
198 this.generalSettingsPanel = new OO.ui.TabPanelLayout( 'general', {
199 label: ve.msg( 'visualeditor-dialog-media-page-general' )
200 } );
201 this.advancedSettingsPanel = new OO.ui.TabPanelLayout( 'advanced', {
202 label: ve.msg( 'visualeditor-dialog-media-page-advanced' )
203 } );
204
205 // General settings panel
206
207 // Filename
208 this.filenameFieldset = new OO.ui.FieldsetLayout( {
209 label: ve.msg( 'visualeditor-dialog-media-content-filename' ),
210 icon: 'image'
211 } );
212
213 // Caption
214 this.captionTarget = ve.init.target.createTargetWidget( {
215 includeCommands: this.constructor.static.includeCommands,
216 excludeCommands: this.constructor.static.excludeCommands,
217 importRules: this.constructor.static.getImportRules(),
218 inDialog: this.constructor.static.name,
219 multiline: false
220 } );
221 const captionField = new OO.ui.FieldLayout( this.captionTarget, {
222 align: 'top'
223 } );
224 this.captionFieldset = new OO.ui.FieldsetLayout( {
225 $overlay: this.$overlay,
226 label: ve.msg( 'visualeditor-dialog-media-content-section' ),
227 help: ve.msg( 'visualeditor-dialog-media-content-section-help' ),
228 classes: [ 've-ui-mwMediaDialog-caption-fieldset' ]
229 } );
230 this.captionFieldset.addItems( [ captionField ] );
231
232 // Alt text
233 this.altTextInput = new OO.ui.MultilineTextInputWidget( {
234 spellcheck: true,
235 classes: [ 've-ui-mwMediaDialog-altText' ],
236 autosize: true,
237 rows: 1,
238 allowLinebreaks: false
239 } );
240 const altTextField = new OO.ui.FieldLayout( this.altTextInput, {
241 align: 'top'
242 } );
243 const altTextFieldset = new OO.ui.FieldsetLayout( {
244 $overlay: this.$overlay,
245 label: ve.msg( 'visualeditor-dialog-media-alttext-section' ),
246 help: ve.msg( 'visualeditor-dialog-media-alttext-section-help' )
247 } );
248 altTextFieldset.addItems( [ altTextField ] );
249
250 // Advanced settings
251
252 // Position
253 this.positionSelect = new ve.ui.AlignWidget( {
254 dir: this.getDir()
255 } );
256 const positionSelectField = new OO.ui.FieldLayout( this.positionSelect );
257 this.positionCheckbox = new OO.ui.CheckboxInputWidget();
258 const positionCheckboxField = new OO.ui.FieldLayout( this.positionCheckbox, {
259 $overlay: this.$overlay,
260 align: 'inline',
261 label: ve.msg( 'visualeditor-dialog-media-position-checkbox' ),
262 help: ve.msg( 'visualeditor-dialog-media-position-checkbox-help' )
263 } );
264 const positionFieldset = new OO.ui.FieldsetLayout( {
265 $overlay: this.$overlay,
266 label: ve.msg( 'visualeditor-dialog-media-position-section' ),
267 help: ve.msg( 'visualeditor-dialog-media-position-section-help' )
268 } );
269 positionFieldset.addItems( [
270 positionCheckboxField,
271 positionSelectField
272 ] );
273
274 // Type
275 this.typeSelectDropdown = new OO.ui.DropdownWidget( { $overlay: this.$overlay } );
276 this.typeSelect = this.typeSelectDropdown.getMenu();
277 this.typeSelect.addItems( [
278 // TODO: Inline images require a bit of further work, will be coming soon
279 new OO.ui.MenuOptionWidget( {
280 data: 'thumb',
281 icon: 'imageLayoutThumbnail',
282 label: ve.msg( 'visualeditor-dialog-media-type-thumb' )
283 } ),
284 new OO.ui.MenuOptionWidget( {
285 data: 'frameless',
286 icon: 'imageLayoutFrameless',
287 label: ve.msg( 'visualeditor-dialog-media-type-frameless' )
288 } ),
289 new OO.ui.MenuOptionWidget( {
290 data: 'frame',
291 icon: 'imageLayoutFrame',
292 label: ve.msg( 'visualeditor-dialog-media-type-frame' )
293 } ),
294 new OO.ui.MenuOptionWidget( {
295 data: 'none',
296 icon: 'imageLayoutBasic',
297 label: ve.msg( 'visualeditor-dialog-media-type-none' )
298 } )
299 ] );
300 const typeSelectField = new OO.ui.FieldLayout( this.typeSelectDropdown, {
301 align: 'top'
302 } );
303 this.borderCheckbox = new OO.ui.CheckboxInputWidget();
304 const borderField = new OO.ui.FieldLayout( this.borderCheckbox, {
305 align: 'inline',
306 label: ve.msg( 'visualeditor-dialog-media-type-border' )
307 } );
308 this.typeFieldset = new OO.ui.FieldsetLayout( {
309 $overlay: this.$overlay,
310 label: ve.msg( 'visualeditor-dialog-media-type-section' ),
311 help: ve.msg( 'visualeditor-dialog-media-type-section-help' )
312 } );
313 this.typeFieldset.addItems( [
314 typeSelectField,
315 borderField
316 ] );
317
318 // Size
319 this.sizeWidget = new ve.ui.MediaSizeWidget( undefined, {
320 dimensionsAlign: 'top'
321 } );
322 const sizeWidgetField = new OO.ui.FieldLayout( this.sizeWidget );
323 this.sizeFieldset = new OO.ui.FieldsetLayout( {
324 $overlay: this.$overlay,
325 label: ve.msg( 'visualeditor-dialog-media-size-section' ),
326 help: ve.msg( 'visualeditor-dialog-media-size-section-help' )
327 } );
328 this.sizeFieldset.addItems( [
329 sizeWidgetField
330 ] );
331
332 // Search, upload and info layouts
333 this.mediaSearchPanel = new OO.ui.TabPanelLayout( {
334 classes: [ 've-ui-mwMediaDialog-panel-search' ],
335 scrollable: true
336 } );
337 if ( mw.ForeignStructuredUpload && mw.ForeignStructuredUpload.BookletLayout ) {
338 this.mediaUploadBooklet = new mw.ForeignStructuredUpload.BookletLayout( {
339 $overlay: this.$overlay
340 } );
341 }
342 this.mediaImageInfoPanel = new OO.ui.TabPanelLayout( {
343 classes: [ 've-ui-mwMediaDialog-panel-imageinfo' ],
344 scrollable: false
345 } );
346 this.$infoPanelWrapper = $( '<div>' ).addClass( 've-ui-mwMediaDialog-panel-imageinfo-wrapper' );
347
348 // Search and upload panels
349 this.searchTabs = new OO.ui.IndexLayout();
350 const searchPanel = new OO.ui.TabPanelLayout( 'search', {
351 label: ve.msg( 'visualeditor-dialog-media-search-tab-search' )
352 } );
353 let uploadPanel;
354 if ( this.mediaUploadBooklet ) {
355 uploadPanel = new OO.ui.TabPanelLayout( 'upload', {
356 label: ve.msg( 'visualeditor-dialog-media-search-tab-upload' ),
357 content: [ this.mediaUploadBooklet ]
358 } );
359 }
360
361 // Search widget
362 this.search = new mw.widgets.MediaSearchWidget( {
363 rowHeight: OO.ui.isMobile() ? 120 : 200
364 } );
365
366 // Events
367 this.positionCheckbox.connect( this, { change: 'onPositionCheckboxChange' } );
368 this.borderCheckbox.connect( this, { change: 'onBorderCheckboxChange' } );
369 this.positionSelect.connect( this, { choose: 'onPositionSelectChoose' } );
370 this.typeSelect.connect( this, { choose: 'onTypeSelectChoose' } );
371 this.search.getQuery().connect( this, { change: 'onSearchQueryChange' } );
372 this.search.getQuery().$indicator.on( 'mousedown', this.onSearchQueryClear.bind( this ) );
373 this.search.getResults().connect( this, { choose: 'onSearchResultsChoose' } );
374 this.captionTarget.connect( this, { change: 'checkChanged' } );
375 this.altTextInput.connect( this, { change: 'onAlternateTextChange' } );
376 this.searchTabs.connect( this, { set: 'onSearchTabsSet' } );
377 if ( this.mediaUploadBooklet ) {
378 this.mediaUploadBooklet.connect( this, {
379 set: 'onMediaUploadBookletSet',
380 uploadValid: 'onUploadValid',
381 infoValid: 'onInfoValid'
382 } );
383 }
384
385 // Append panels
386 searchPanel.$element.append( this.search.$element );
387 this.searchTabs.addTabPanels( [ searchPanel ] );
388 if ( this.mediaUploadBooklet ) {
389 this.searchTabs.addTabPanels( [ uploadPanel ] );
390 }
391 this.mediaSearchPanel.$element.append(
392 this.searchTabs.$element
393 );
394 this.generalSettingsPanel.$element.append(
395 this.filenameFieldset.$element,
396 this.captionFieldset.$element,
397 altTextFieldset.$element
398 );
399 this.advancedSettingsPanel.$element.append(
400 positionFieldset.$element,
401 this.typeFieldset.$element,
402 this.sizeFieldset.$element
403 );
404 this.mediaSettingsLayout.addTabPanels( [
405 this.generalSettingsPanel,
406 this.advancedSettingsPanel
407 ] );
408 this.panels.addItems( [
409 this.mediaSearchPanel,
410 this.mediaImageInfoPanel,
411 this.mediaSettingsLayout
412 ] );
413 this.$body.append( this.panels.$element );
414 };
415
416 /**
417 * Handle set events from the search tabs
418 *
419 * @param {OO.ui.TabPanelLayout} tabPanel Current tabPanel
420 */
421 ve.ui.MWMediaDialog.prototype.onSearchTabsSet = function ( tabPanel ) {
422 const name = tabPanel.getName();
423
424 this.actions.setMode( name );
425
426 switch ( name ) {
427 case 'search':
428 this.setSize( 'larger' );
429 break;
430
431 case 'upload':
432 // Initialize and reset the upload booklet if it hasn't
433 // been initiailized since setup.
434 if ( !this.mediaUploadBookletInit ) {
435 this.mediaUploadBookletInit = true;
436 this.mediaUploadBooklet.initialize();
437 }
438 this.setSize( 'medium' );
439 this.uploadPageNameSet( 'upload' );
440 break;
441 }
442 };
443
444 /**
445 * Handle panelNameSet events from the upload stack
446 *
447 * @param {OO.ui.PageLayout} page Current page
448 */
449 ve.ui.MWMediaDialog.prototype.onMediaUploadBookletSet = function ( page ) {
450 this.uploadPageNameSet( page.getName() );
451 };
452
453 /**
454 * The upload booklet's page name has changed
455 *
456 * @param {string} pageName Page name
457 */
458 ve.ui.MWMediaDialog.prototype.uploadPageNameSet = function ( pageName ) {
459 if ( pageName === 'insert' ) {
460 const imageInfo = this.mediaUploadBooklet.upload.getImageInfo();
461 this.chooseImageInfo( imageInfo );
462 } else {
463 // Hide the tabs after the first page
464 this.searchTabs.toggleMenu( pageName === 'upload' );
465
466 this.actions.setMode( 'upload-' + pageName );
467 }
468 };
469
470 /**
471 * Handle uploadValid events
472 *
473 * @param {boolean} isValid The panel is complete and valid
474 */
475 ve.ui.MWMediaDialog.prototype.onUploadValid = function ( isValid ) {
476 this.actions.setAbilities( { upload: isValid } );
477 };
478
479 /**
480 * Handle infoValid events
481 *
482 * @param {boolean} isValid The panel is complete and valid
483 */
484 ve.ui.MWMediaDialog.prototype.onInfoValid = function ( isValid ) {
485 this.actions.setAbilities( { save: isValid } );
486 };
487
488 /**
489 * Build the image info panel from the information in the API.
490 * Use the metadata info if it exists.
491 * Note: Some information in the metadata object needs to be safely
492 * stripped from its html wrappers.
493 *
494 * @param {Object} imageinfo Image info
495 */
496 ve.ui.MWMediaDialog.prototype.buildMediaInfoPanel = function ( imageinfo ) {
497 const contentDirection = this.getFragment().getDocument().getDir(),
498 imageTitleText = imageinfo.title || imageinfo.canonicaltitle,
499 imageTitle = new OO.ui.LabelWidget( {
500 label: mw.Title.newFromText( imageTitleText ).getNameText()
501 } ),
502 metadata = imageinfo.extmetadata,
503 // Field configuration (in order)
504 apiDataKeysConfig = [
505 {
506 name: 'ImageDescription',
507 value: ve.getProp( metadata, 'ImageDescription', 'value' ),
508 format: 'html',
509 view: {
510 type: 'description',
511 primary: true,
512 descriptionHeight: '5em'
513 }
514 },
515 {
516 name: '$fileDetails',
517 // Real value is set later
518 value: '',
519 format: 'html',
520 view: { icon: 'image' }
521 },
522 {
523 name: 'LicenseShortName',
524 value: ve.getProp( metadata, 'LicenseShortName', 'value' ),
525 format: 'html-remove-formatting',
526 view: {
527 href: ve.getProp( metadata, 'LicenseUrl', 'value' ),
528 icon: this.getLicenseIcon( ve.getProp( metadata, 'LicenseShortName', 'value' ) )
529 }
530 },
531 {
532 name: 'Artist',
533 value: ve.getProp( metadata, 'Artist', 'value' ),
534 format: 'html-remove-formatting',
535 view: {
536 // "Artist" label
537 labelMsg: 'visualeditor-dialog-media-info-meta-artist',
538 icon: 'userAvatar'
539 }
540 },
541 {
542 name: 'Credit',
543 value: ve.getProp( metadata, 'Credit', 'value' ),
544 format: 'html-remove-formatting',
545 view: { icon: 'userAvatar' }
546 },
547 {
548 name: 'user',
549 value: imageinfo.user,
550 format: 'plaintext',
551 view: {
552 icon: 'userAvatar',
553 // This is 'uploaded by'
554 labelMsg: 'visualeditor-dialog-media-info-artist'
555 }
556 },
557 {
558 name: 'timestamp',
559 value: imageinfo.timestamp,
560 format: 'plaintext',
561 view: {
562 icon: 'clock',
563 labelMsg: 'visualeditor-dialog-media-info-uploaded',
564 isDate: true
565 }
566 },
567 {
568 name: 'DateTimeOriginal',
569 value: ve.getProp( metadata, 'DateTimeOriginal', 'value' ),
570 format: 'html-remove-formatting',
571 view: {
572 icon: 'clock',
573 labelMsg: 'visualeditor-dialog-media-info-created'
574 }
575 },
576 {
577 name: 'moreinfo',
578 value: ve.msg( 'visualeditor-dialog-media-info-moreinfo' ),
579 format: 'plaintext',
580 view: {
581 icon: 'info',
582 href: imageinfo.descriptionurl
583 }
584 }
585 ],
586 fields = {},
587 // Store clean API data
588 apiData = {},
589 fileType = this.getFileType( imageinfo.url ),
590 $thumbContainer = $( '<div>' )
591 .addClass( 've-ui-mwMediaDialog-panel-imageinfo-thumb' ),
592 $main = $( '<div>' )
593 .addClass( 've-ui-mwMediaDialog-panel-imageinfo-main' ),
594 $details = $( '<div>' )
595 .addClass( 've-ui-mwMediaDialog-panel-imageinfo-details' ),
596 $image = $( '<img>' );
597
598 // Main section - title
599 $main.append(
600 imageTitle.$element
601 .addClass( 've-ui-mwMediaDialog-panel-imageinfo-title' )
602 );
603
604 // Clean data from the API responses
605 for ( let i = 0; i < apiDataKeysConfig.length; i++ ) {
606 const field = apiDataKeysConfig[ i ].name;
607 if ( apiDataKeysConfig[ i ].format === 'html' ) {
608 apiData[ field ] = new OO.ui.HtmlSnippet( apiDataKeysConfig[ i ].value );
609
610 } else if ( apiDataKeysConfig[ i ].format === 'html-remove-formatting' ) {
611 apiData[ field ] = this.cleanAPIresponse( apiDataKeysConfig[ i ].value );
612
613 } else if ( apiDataKeysConfig[ i ].format === 'plaintext' ) {
614 apiData[ field ] = apiDataKeysConfig[ i ].value;
615
616 } else {
617 throw new Error( 'Unexpected metadata field format' );
618 }
619 }
620
621 // Add sizing info for non-audio images
622 if ( imageinfo.mediatype === 'AUDIO' ) {
623 // Label this file as an audio
624 apiData.$fileDetails = $( '<span>' )
625 .text( ve.msg( 'visualeditor-dialog-media-info-audiofile' ) );
626 } else {
627 // Build the display for image size and type
628 apiData.$fileDetails = $( '<div>' )
629 .append(
630 $( '<span>' ).text(
631 imageinfo.width +
632 '\u00a0' +
633 ve.msg( 'visualeditor-dimensionswidget-times' ) +
634 '\u00a0' +
635 imageinfo.height +
636 ve.msg( 'visualeditor-dimensionswidget-px' )
637 ),
638 $( '<span>' )
639 .addClass( 've-ui-mwMediaDialog-panel-imageinfo-separator' )
640 .text( ve.msg( 'visualeditor-dialog-media-info-separator' ) ),
641 $( '<span>' ).text( fileType )
642 );
643 }
644
645 // Attach all fields in order
646 for ( let i = 0; i < apiDataKeysConfig.length; i++ ) {
647 const field = apiDataKeysConfig[ i ].name;
648 if ( apiData[ field ] ) {
649 const $section = apiDataKeysConfig[ i ].view.primary ? $main : $details;
650
651 fields[ field ] = new ve.ui.MWMediaInfoFieldWidget( apiData[ field ], apiDataKeysConfig[ i ].view );
652 $section.append( fields[ field ].$element );
653 }
654 }
655
656 // Build the info panel
657 const $info = $( '<div>' )
658 .addClass( 've-ui-mwMediaDialog-panel-imageinfo-info' )
659 .append(
660 $main.prop( 'dir', contentDirection ),
661 $details
662 );
663 ve.targetLinksToNewWindow( $info[ 0 ] );
664
665 // Initialize thumb container
666 $thumbContainer
667 .append( $image.prop( 'src', imageinfo.thumburl ) );
668
669 this.$infoPanelWrapper.append(
670 $thumbContainer,
671 $info
672 );
673
674 // Force a scrollbar to the screen before we measure it
675 this.mediaImageInfoPanel.$element.css( 'overflow-y', 'scroll' );
676 const windowWidth = this.mediaImageInfoPanel.$element.width();
677
678 // Define thumbnail size
679 let newDimensions;
680 if ( imageinfo.mediatype === 'AUDIO' ) {
681 // HACK: We are getting the wrong information from the
682 // API about audio files. Set their thumbnail to square
683 newDimensions = {
684 width: imageinfo.thumbwidth,
685 height: imageinfo.thumbwidth
686 };
687 } else {
688 // For regular images, calculate a bigger image dimensions
689 newDimensions = ve.dm.MWImageNode.static.resizeToBoundingBox(
690 // Original image dimensions
691 {
692 width: imageinfo.width,
693 height: imageinfo.height
694 },
695 // Bounding box -- the size of the dialog, minus padding
696 {
697 width: windowWidth,
698 height: this.getBodyHeight() - 120
699 }
700 );
701 }
702 // Resize the image
703 $image.css( {
704 width: newDimensions.width,
705 height: newDimensions.height
706 } );
707
708 // Call for a bigger image
709 this.fetchThumbnail( imageTitleText, newDimensions )
710 .done( ( thumburl ) => {
711 if ( thumburl ) {
712 $image.prop( 'src', thumburl );
713 }
714 } );
715
716 const isPortrait = newDimensions.width < ( windowWidth * 3 / 5 );
717 this.mediaImageInfoPanel.$element.toggleClass( 've-ui-mwMediaDialog-panel-imageinfo-portrait', isPortrait );
718 this.mediaImageInfoPanel.$element.append( this.$infoPanelWrapper );
719 if ( isPortrait ) {
720 $info.outerWidth( Math.floor( windowWidth - $thumbContainer.outerWidth( true ) - 15 ) );
721 }
722
723 // Initialize fields
724 for ( const field in fields ) {
725 fields[ field ].initialize();
726 }
727 // Let the scrollbar appear naturally if it should
728 this.mediaImageInfoPanel.$element.css( 'overflow', '' );
729 };
730
731 /**
732 * Fetch a bigger image thumbnail from the API.
733 *
734 * @param {string} imageName Image source
735 * @param {Object} dimensions Image dimensions
736 * @return {jQuery.Promise} Thumbnail promise that resolves with new thumb url
737 */
738 ve.ui.MWMediaDialog.prototype.fetchThumbnail = function ( imageName, dimensions ) {
739 // Check cache first
740 if ( this.searchCache[ imageName ] ) {
741 return ve.createDeferred().resolve( this.searchCache[ imageName ] );
742 }
743
744 const params = {
745 action: 'query',
746 prop: 'imageinfo',
747 iiprop: 'url',
748 titles: imageName
749 };
750
751 if ( dimensions.width ) {
752 params.iiurlwidth = dimensions.width;
753 }
754 if ( dimensions.height ) {
755 params.iiurlheight = dimensions.height;
756 }
757 return ve.init.target.getContentApi( this.getFragment().getDocument() ).get( params )
758 .then( ( response ) => {
759 const thumburl = ve.getProp( response.query.pages[ 0 ], 'imageinfo', 0, 'thumburl' );
760 // Cache
761 this.searchCache[ imageName ] = thumburl;
762 return thumburl;
763 } );
764 };
765
766 /**
767 * Clean the API responses and return it in plaintext. If needed, truncate.
768 *
769 * @param {string} html Raw response from the API
770 * @return {string} Plaintext clean response
771 */
772 ve.ui.MWMediaDialog.prototype.cleanAPIresponse = function ( html ) {
773 let text = $( $.parseHTML( html ) ).text();
774
775 // Check if the string should be truncated
776 const charLimit = 50;
777 if ( text.length > charLimit ) {
778 const ellipsis = ve.msg( 'visualeditor-dialog-media-info-ellipsis' );
779 text = text.slice( 0, charLimit ) + ellipsis;
780 }
781
782 return text;
783 };
784
785 /**
786 * Get the file type from the suffix of the url
787 *
788 * @param {string} url Full file url
789 * @return {string} File type
790 */
791 ve.ui.MWMediaDialog.prototype.getFileType = function ( url ) {
792 // TODO: Validate these types, and work with icons
793 // SVG, PNG, JPEG, GIF, TIFF, XCF;
794 // OGA, OGG, MIDI, WAV;
795 // WEBM, OGV, OGX;
796 // APNG;
797 // PDF, DJVU
798 return url.split( '.' ).pop().toUpperCase();
799 };
800
801 /**
802 * Get the proper icon for the license if it is recognized
803 * or general info icon if it is not recognized.
804 *
805 * @param {string} license License short name
806 * @return {string} Icon name
807 */
808 ve.ui.MWMediaDialog.prototype.getLicenseIcon = function ( license ) {
809 if ( !license ) {
810 return 'info';
811 }
812
813 const normalized = license.toLowerCase().replace( /[-_]/g, ' ' );
814
815 // FIXME: Structured data from Commons will make this properly
816 // multilingual. For now, this is the limit of what is sensible.
817 if ( /^((cc )?pd|public domain)/.test( normalized ) ) {
818 return 'public-domain';
819 } else if ( /^cc (by|sa)?/.test( normalized ) ) {
820 return 'logoCC';
821 } else {
822 return 'info';
823 }
824 };
825
826 /**
827 * Handle search results choose event.
828 *
829 * @param {mw.widgets.MediaResultWidget} item Chosen item
830 */
831 ve.ui.MWMediaDialog.prototype.onSearchResultsChoose = function ( item ) {
832 this.chooseImageInfo( item.getData() );
833
834 ve.track( 'activity.' + this.constructor.static.name, {
835 action: 'search-choose-image'
836 } );
837 };
838
839 /**
840 * Handle query change events from the search input widget
841 *
842 * @param {string} query
843 */
844 ve.ui.MWMediaDialog.prototype.onSearchQueryChange = function ( query ) {
845 if ( query === '' ) {
846 return;
847 }
848
849 ve.track( 'activity.' + this.constructor.static.name, {
850 action: 'search-change-query'
851 } );
852 };
853
854 /**
855 * Handle clearing of search query by user clicking on indicator
856 */
857 ve.ui.MWMediaDialog.prototype.onSearchQueryClear = function () {
858 ve.track( 'activity.' + this.constructor.static.name, {
859 action: 'search-clear-query'
860 } );
861 };
862
863 /**
864 * Choose image info for editing
865 *
866 * @param {Object} info Image info
867 */
868 ve.ui.MWMediaDialog.prototype.chooseImageInfo = function ( info ) {
869 this.$infoPanelWrapper.empty();
870 // Switch panels
871 this.selectedImageInfo = info;
872 this.switchPanels( 'imageInfo' );
873 // Build info panel
874 this.buildMediaInfoPanel( info );
875 };
876
877 /**
878 * Handle new image being chosen.
879 *
880 * @param {mw.widgets.MediaResultWidget|null} item Selected item
881 */
882 ve.ui.MWMediaDialog.prototype.confirmSelectedImage = function () {
883 const obj = {},
884 info = this.selectedImageInfo;
885
886 if ( info ) {
887 const imageTitleText = info.title || info.canonicaltitle;
888 // Run title through mw.Title so the File: prefix is localised
889 const title = mw.Title.newFromText( imageTitleText ).getPrefixedText();
890 if ( !this.imageModel ) {
891 // Create a new image model based on default attributes
892 this.imageModel = ve.dm.MWImageModel.static.newFromImageAttributes(
893 {
894 // Per https://www.mediawiki.org/w/?diff=931265&oldid=prev
895 href: './' + title,
896 src: info.url,
897 resource: './' + title,
898 width: info.thumbwidth,
899 height: info.thumbheight,
900 mediaType: info.mediatype,
901 type: 'thumb',
902 align: 'default',
903 defaultSize: true,
904 imageClassAttr: 'mw-file-element'
905 },
906 this.getFragment().getDocument()
907 );
908 this.attachImageModel();
909 this.resetCaption();
910 } else {
911 // Update the current image model with the new image source
912 this.imageModel.changeImageSource(
913 {
914 mediaType: info.mediatype,
915 href: './' + title,
916 src: info.url,
917 resource: './' + title
918 },
919 info
920 );
921 this.updateFilenameFieldset();
922 }
923
924 // Cache
925 // We're trimming the stored data down to be consistent with what
926 // ImageInfoCache.getRequestPromise fetches.
927 obj[ imageTitleText ] = {
928 size: info.size,
929 width: info.width,
930 height: info.height,
931 mediatype: info.mediatype
932 };
933 ve.init.platform.imageInfoCache.set( obj );
934
935 this.checkChanged();
936 this.switchPanels( 'edit' );
937
938 ve.track( 'activity.' + this.constructor.static.name, {
939 action: 'search-confirm-image'
940 } );
941 }
942 };
943
944 /**
945 * Update the filename fieldset (link to media page)
946 */
947 ve.ui.MWMediaDialog.prototype.updateFilenameFieldset = function () {
948 const title = mw.Title.newFromText( mw.libs.ve.normalizeParsoidResourceName( this.imageModel.getResourceName() ) );
949 this.filenameFieldset.setLabel(
950 $( '<span>' ).append(
951 $( document.createTextNode( this.imageModel.getFilename() + ' ' ) ),
952 $( '<a>' )
953 .addClass( 've-ui-mwMediaDialog-description-link' )
954 .attr( 'href', title.getUrl() )
955 .attr( 'target', '_blank' )
956 .attr( 'rel', 'noopener' )
957 .text( ve.msg( 'visualeditor-dialog-media-content-description-link' ) )
958 )
959 );
960 };
961
962 /**
963 * Handle image model alignment change
964 *
965 * @param {string} alignment Image alignment
966 */
967 ve.ui.MWMediaDialog.prototype.onImageModelAlignmentChange = function ( alignment ) {
968 alignment = alignment || 'none';
969
970 // Select the item without triggering the 'choose' event
971 this.positionSelect.selectItemByData( alignment !== 'none' ? alignment : undefined );
972
973 this.positionCheckbox.setSelected( alignment !== 'none' );
974 this.checkChanged();
975 };
976
977 /**
978 * Handle image model type change
979 *
980 * @param {string} type Image type
981 */
982 ve.ui.MWMediaDialog.prototype.onImageModelTypeChange = function ( type ) {
983 this.typeSelect.selectItemByData( type );
984
985 this.borderCheckbox.setDisabled(
986 !this.imageModel.isBorderable()
987 );
988
989 this.borderCheckbox.setSelected(
990 this.imageModel.isBorderable() && this.imageModel.hasBorder()
991 );
992 this.checkChanged();
993 };
994
995 /**
996 * Handle change event on the positionCheckbox element.
997 *
998 * @param {boolean} isSelected Checkbox status
999 */
1000 ve.ui.MWMediaDialog.prototype.onPositionCheckboxChange = function ( isSelected ) {
1001 const currentModelAlignment = this.imageModel.getAlignment();
1002
1003 this.positionSelect.setDisabled( !isSelected );
1004 this.checkChanged();
1005 // Only update the model if the current value is different than that
1006 // of the image model
1007 if (
1008 ( currentModelAlignment === 'none' && isSelected ) ||
1009 ( currentModelAlignment !== 'none' && !isSelected )
1010 ) {
1011 if ( isSelected ) {
1012 // Picking a floating alignment value will create a block image
1013 // no matter what the type is, so in here we want to calculate
1014 // the default alignment of a block to set as our initial alignment
1015 // in case the checkbox is clicked but there was no alignment set
1016 // previously.
1017 const newPositionValue = this.imageModel.getDefaultDir( 'mwBlockImage' );
1018 this.imageModel.setAlignment( newPositionValue );
1019 } else {
1020 // If we're unchecking the box, always set alignment to none and unselect the position widget
1021 this.imageModel.setAlignment( 'none' );
1022 }
1023 }
1024 };
1025
1026 /**
1027 * Handle change event on the positionCheckbox element.
1028 *
1029 * @param {boolean} isSelected Checkbox status
1030 */
1031 ve.ui.MWMediaDialog.prototype.onBorderCheckboxChange = function ( isSelected ) {
1032 // Only update if the value is different than the model
1033 if ( this.imageModel.hasBorder() !== isSelected ) {
1034 // Update the image model
1035 this.imageModel.toggleBorder( isSelected );
1036 this.checkChanged();
1037 }
1038 };
1039
1040 /**
1041 * Handle change event on the positionSelect element.
1042 *
1043 * @param {OO.ui.ButtonOptionWidget} item Selected item
1044 */
1045 ve.ui.MWMediaDialog.prototype.onPositionSelectChoose = function ( item ) {
1046 const position = item.getData();
1047
1048 // Only update if the value is different than the model
1049 if ( this.imageModel.getAlignment() !== position ) {
1050 this.imageModel.setAlignment( position );
1051 this.checkChanged();
1052 }
1053 };
1054
1055 /**
1056 * Handle change event on the typeSelect element.
1057 *
1058 * @param {OO.ui.MenuOptionWidget} item Selected item
1059 */
1060 ve.ui.MWMediaDialog.prototype.onTypeSelectChoose = function ( item ) {
1061 const type = item.getData();
1062
1063 // Only update if the value is different than the model
1064 if ( this.imageModel.getType() !== type ) {
1065 this.imageModel.setType( type );
1066 this.checkChanged();
1067 }
1068
1069 // If type is 'frame', custom size is ignored
1070 if ( type === 'frame' ) {
1071 this.sizeWidget.setSizeType( 'default' );
1072 }
1073 };
1074
1075 /**
1076 * Handle changeSizeType events from the MediaSizeWidget
1077 *
1078 * @param {string} sizeType Size type
1079 */
1080 ve.ui.MWMediaDialog.prototype.onChangeSizeType = function ( sizeType ) {
1081 // type=frame is not resizeable, so change it to type=thumb
1082 if ( sizeType === 'custom' && this.imageModel.getType() === 'frame' ) {
1083 this.imageModel.setType( 'thumb' );
1084 }
1085
1086 this.checkChanged();
1087 };
1088
1089 /**
1090 * Respond to change in alternate text
1091 *
1092 * @param {string} text New alternate text
1093 */
1094 ve.ui.MWMediaDialog.prototype.onAlternateTextChange = function ( text ) {
1095 this.imageModel.setAltText( text );
1096 this.checkChanged();
1097 };
1098
1099 /**
1100 * When changes occur, enable the apply button.
1101 */
1102 ve.ui.MWMediaDialog.prototype.checkChanged = function () {
1103 let captionChanged = false;
1104
1105 // Only check 'changed' status after the model has finished
1106 // building itself
1107 if ( !this.isSettingUpModel ) {
1108 captionChanged = !!this.captionTarget && this.captionTarget.hasBeenModified();
1109
1110 if (
1111 this.imageModel &&
1112 // Activate or deactivate the apply/insert buttons
1113 // Make sure sizes are valid first
1114 this.sizeWidget.isValid() &&
1115 (
1116 // Check that the model or caption changed
1117 this.isInsertion ||
1118 captionChanged ||
1119 this.imageModel.hasBeenModified()
1120 )
1121 ) {
1122 this.actions.setAbilities( { insert: true, done: true } );
1123 } else {
1124 this.actions.setAbilities( { insert: false, done: false } );
1125 }
1126 }
1127 };
1128
1129 /**
1130 * @inheritdoc
1131 */
1132 ve.ui.MWMediaDialog.prototype.getSetupProcess = function ( data ) {
1133 return ve.ui.MWMediaDialog.super.prototype.getSetupProcess.call( this, data )
1134 .next( () => {
1135 const isReadOnly = this.isReadOnly();
1136
1137 // Set language for search results
1138 this.search.setLang( this.getFragment().getDocument().getLang() );
1139
1140 if ( this.selectedNode ) {
1141 this.isInsertion = false;
1142 // Create image model
1143 this.imageModel = ve.dm.MWImageModel.static.newFromImageNode( this.selectedNode );
1144 this.attachImageModel();
1145
1146 if ( !this.imageModel.isDefaultSize() ) {
1147 // To avoid dirty diff in case where only the image changes,
1148 // we will store the initial bounding box, in case the image
1149 // is not defaultSize
1150 this.imageModel.setBoundingBox( this.imageModel.getCurrentDimensions() );
1151 }
1152 // Store initial hash to compare against
1153 this.imageModel.storeInitialHash( this.imageModel.getHashObject() );
1154 } else {
1155 this.isInsertion = true;
1156 }
1157
1158 this.search.setup();
1159 // Try to populate with user uploads
1160 this.search.queryMediaQueue();
1161 this.resetCaption();
1162
1163 this.altTextInput.setReadOnly( isReadOnly );
1164 this.positionCheckbox.setDisabled( isReadOnly );
1165 // TODO: This widget is not readable when disabled
1166 this.positionSelect.setDisabled( isReadOnly );
1167 this.typeSelectDropdown.setDisabled( isReadOnly );
1168 this.borderCheckbox.setDisabled( isReadOnly );
1169 this.sizeWidget.setDisabled( isReadOnly );
1170
1171 // Pass `true` to avoid focussing. If we focus the image caption widget during dialog
1172 // opening, and it wants to display a context menu, it will be mispositioned.
1173 this.switchPanels( this.selectedNode ? 'edit' : 'search', true );
1174
1175 this.actions.setAbilities( { upload: false, save: false, insert: false, done: false } );
1176
1177 this.mediaUploadBookletInit = false;
1178 if ( data.file && this.mediaUploadBooklet ) {
1179 this.searchTabs.setTabPanel( 'upload' );
1180 this.mediaUploadBooklet.setFile( data.file );
1181 }
1182 } );
1183 };
1184
1185 /**
1186 * Switch between the edit and insert/search panels
1187 *
1188 * @param {string} panel Panel name
1189 * @param {boolean} [noFocus=false] Do not put focus into the default field of the panel
1190 */
1191 ve.ui.MWMediaDialog.prototype.switchPanels = function ( panel, noFocus ) {
1192 switch ( panel ) {
1193 case 'edit':
1194 this.setSize( this.constructor.static.size );
1195 // Set the edit panel
1196 this.panels.setItem( this.mediaSettingsLayout );
1197 // Focus the general settings page
1198 this.mediaSettingsLayout.setTabPanel( 'general' );
1199 // Parent functionality (edit/insert/readonly)
1200 this.actions.setMode( this.getMode() );
1201 if ( !noFocus ) {
1202 // Focus the caption surface
1203 this.captionTarget.focus();
1204 }
1205 // Auto-sized alt text field is populated while hidden,
1206 // so force a manual resize now.
1207 this.altTextInput.adjustSize( true );
1208 break;
1209 case 'search':
1210 this.setSize( 'larger' );
1211 this.selectedImageInfo = null;
1212 // Set the edit panel
1213 this.panels.setItem( this.mediaSearchPanel );
1214 this.searchTabs.setTabPanel( 'search' );
1215 this.searchTabs.toggleMenu( true );
1216 this.actions.setMode( this.imageModel ? 'change' : 'select' );
1217 if ( !noFocus ) {
1218 this.search.getQuery().focus().select();
1219 }
1220 // Layout pending items
1221 this.search.runLayoutQueue();
1222 break;
1223 default:
1224 case 'imageInfo':
1225 this.setSize( 'larger' );
1226 // Hide/show buttons
1227 this.actions.setMode( 'info' );
1228 // Hide/show the panels
1229 this.panels.setItem( this.mediaImageInfoPanel );
1230 break;
1231 }
1232 this.currentPanel = panel || 'imageinfo';
1233 };
1234
1235 /**
1236 * Attach the image model to the dialog
1237 */
1238 ve.ui.MWMediaDialog.prototype.attachImageModel = function () {
1239 if ( this.imageModel ) {
1240 this.imageModel.disconnect( this );
1241 this.sizeWidget.disconnect( this );
1242 }
1243
1244 // Events
1245 this.imageModel.connect( this, {
1246 alignmentChange: 'onImageModelAlignmentChange',
1247 typeChange: 'onImageModelTypeChange',
1248 sizeDefaultChange: 'checkChanged'
1249 } );
1250
1251 // Set up
1252 // Ignore the following changes in validation while we are
1253 // setting up the initial tools according to the model state
1254 this.isSettingUpModel = true;
1255
1256 // Filename
1257 this.updateFilenameFieldset();
1258
1259 // Size widget
1260 this.sizeWidget.setScalable( this.imageModel.getScalable() );
1261 this.sizeWidget.connect( this, {
1262 changeSizeType: 'onChangeSizeType',
1263 change: 'checkChanged',
1264 valid: 'checkChanged'
1265 } );
1266
1267 // Initialize size
1268 this.sizeWidget.setSizeType( this.imageModel.isDefaultSize() ? 'default' : 'custom' );
1269
1270 // Update default dimensions
1271 this.sizeWidget.updateDefaultDimensions();
1272
1273 // Set initial alt text
1274 this.altTextInput.setValue( this.imageModel.getAltText() );
1275
1276 // Set initial alignment
1277 this.positionSelect.setDisabled( !this.imageModel.isAligned() );
1278 this.positionSelect.selectItemByData( this.imageModel.isAligned() && this.imageModel.getAlignment() );
1279 this.positionCheckbox.setSelected( this.imageModel.isAligned() );
1280
1281 // Border flag
1282 this.borderCheckbox.setDisabled( !this.imageModel.isBorderable() );
1283 this.borderCheckbox.setSelected( this.imageModel.isBorderable() && this.imageModel.hasBorder() );
1284
1285 // Type select
1286 this.typeSelect.selectItemByData( this.imageModel.getType() || 'none' );
1287
1288 this.isSettingUpModel = false;
1289 };
1290
1291 /**
1292 * Reset the caption surface
1293 */
1294 ve.ui.MWMediaDialog.prototype.resetCaption = function () {
1295 const doc = this.getFragment().getDocument();
1296
1297 // Get existing caption. We only do this in setup, because the caption
1298 // should not reset to original if the image is replaced or edited.
1299 //
1300 // If the selected node is a block image and the caption already exists,
1301 // store the initial caption and set it as the caption document
1302 if (
1303 this.imageModel &&
1304 this.selectedNode &&
1305 this.selectedNode.getDocument() &&
1306 this.selectedNode instanceof ve.dm.MWBlockImageNode
1307 ) {
1308 const captionNode = this.selectedNode.getCaptionNode();
1309 if ( captionNode && captionNode.getLength() > 0 ) {
1310 this.imageModel.setCaptionDocument(
1311 this.selectedNode.getDocument().cloneFromRange( captionNode.getRange() )
1312 );
1313 }
1314 }
1315
1316 let captionDocument;
1317 if ( this.imageModel ) {
1318 captionDocument = this.imageModel.getCaptionDocument();
1319 } else {
1320 captionDocument = doc.cloneWithData( [
1321 { type: 'paragraph', internal: { generated: 'wrapper' } },
1322 { type: '/paragraph' },
1323 { type: 'internalList' },
1324 { type: '/internalList' }
1325 ] );
1326 }
1327
1328 // Set document
1329 this.captionTarget.setDocument( captionDocument );
1330 this.captionTarget.setReadOnly( this.isReadOnly() );
1331 };
1332
1333 /**
1334 * @inheritdoc
1335 */
1336 ve.ui.MWMediaDialog.prototype.getReadyProcess = function ( data ) {
1337 return ve.ui.MWMediaDialog.super.prototype.getReadyProcess.call( this, data )
1338 .next( () => {
1339 if ( !data.file ) {
1340 this.switchPanels( this.selectedNode ? 'edit' : 'search' );
1341 }
1342 // Revalidate size
1343 this.sizeWidget.validateDimensions();
1344 } );
1345 };
1346
1347 /**
1348 * @inheritdoc
1349 */
1350 ve.ui.MWMediaDialog.prototype.getTeardownProcess = function ( data ) {
1351 return ve.ui.MWMediaDialog.super.prototype.getTeardownProcess.call( this, data )
1352 .first( () => {
1353 this.mediaSettingsLayout.resetScroll();
1354 // Cleanup
1355 this.search.getQuery().setValue( '' );
1356 this.search.teardown();
1357 if ( this.imageModel ) {
1358 this.imageModel.disconnect( this );
1359 this.sizeWidget.disconnect( this );
1360 }
1361 this.captionTarget.clear();
1362 this.imageModel = null;
1363 } );
1364 };
1365
1366 /**
1367 * @inheritdoc
1368 */
1369 ve.ui.MWMediaDialog.prototype.getActionProcess = function ( action ) {
1370 let handler;
1371
1372 switch ( action ) {
1373 case 'change':
1374 handler = function () {
1375 this.switchPanels( 'search' );
1376 };
1377
1378 ve.track( 'activity.' + this.constructor.static.name, {
1379 action: 'search-change-image'
1380 } );
1381 break;
1382 case 'back':
1383 handler = function () {
1384 this.switchPanels( 'edit' );
1385 };
1386 break;
1387 case 'choose':
1388 handler = function () {
1389 this.confirmSelectedImage();
1390 this.switchPanels( 'edit' );
1391 };
1392 break;
1393 case 'cancelchoose':
1394 handler = function () {
1395 this.switchPanels( 'search' );
1396 };
1397 ve.track( 'activity.' + this.constructor.static.name, {
1398 action: 'search-change-image'
1399 } );
1400 break;
1401 case 'cancelupload':
1402 handler = function () {
1403 this.searchTabs.setTabPanel( 'upload' );
1404 this.searchTabs.toggleMenu( true );
1405 return this.mediaUploadBooklet.initialize();
1406 };
1407 break;
1408 case 'upload':
1409 ve.track( 'activity.' + this.constructor.static.name, {
1410 action: 'search-upload-image'
1411 } );
1412 return new OO.ui.Process( this.mediaUploadBooklet.uploadFile() );
1413 case 'save':
1414 return new OO.ui.Process( this.mediaUploadBooklet.saveFile() );
1415 case 'done':
1416 case 'insert':
1417 handler = function () {
1418 const surfaceModel = this.getFragment().getSurface();
1419
1420 // Update from the form
1421 this.imageModel.setAltText( this.altTextInput.getValue() );
1422 this.imageModel.setCaptionDocument(
1423 this.captionTarget.getSurface().getModel().getDocument()
1424 );
1425
1426 if (
1427 // There was an initial node
1428 this.selectedNode &&
1429 // And we didn't change the image type block/inline or vice versa
1430 this.selectedNode.type === this.imageModel.getImageNodeType() &&
1431 // And we didn't change the image itself
1432 this.selectedNode.getAttribute( 'src' ) ===
1433 this.imageModel.getImageSource()
1434 ) {
1435 // We only need to update the attributes of the current node
1436 this.imageModel.updateImageNode( this.selectedNode, surfaceModel );
1437 } else {
1438 // Replacing an image or inserting a brand new one
1439 this.fragment = this.imageModel.insertImageNode( this.getFragment() );
1440 }
1441
1442 this.close( { action: action } );
1443 };
1444 break;
1445 default:
1446 return ve.ui.MWMediaDialog.super.prototype.getActionProcess.call( this, action );
1447 }
1448
1449 return new OO.ui.Process( handler, this );
1450 };
1451
1452 /* Registration */
1453
1454 ve.ui.windowFactory.register( ve.ui.MWMediaDialog );